refactor: use canonical token-to-symbol maps for market lookup
Build canonical spot/future token maps with quote priority, unify cache refresh scheduling, and switch resolver/token tests to map-based token lookups. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -18,5 +18,7 @@ type IMarket interface {
|
||||
// Trading pair methods
|
||||
IsSpotPair(symbol string) bool
|
||||
IsFuturesPair(symbol string) bool
|
||||
GetSpotSymbolByToken(token string) (string, bool)
|
||||
GetFutureSymbolByToken(token string) (string, bool)
|
||||
RefreshTradingPairCache() error
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ type MarketData struct {
|
||||
// Trading pair caches
|
||||
spotPairs map[string]bool
|
||||
futuresPairs map[string]bool
|
||||
spotToken2Symbol map[string]string
|
||||
futureToken2Symbol map[string]string
|
||||
pairCacheMutex sync.RWMutex
|
||||
lastPairCacheUpdate time.Time
|
||||
|
||||
@@ -29,18 +31,17 @@ type MarketData struct {
|
||||
func NewMarketData() *MarketData {
|
||||
log.Info().Msg("Start market service")
|
||||
ms := &MarketData{
|
||||
spotPairs: make(map[string]bool),
|
||||
futuresPairs: make(map[string]bool),
|
||||
alphaTokens: make(map[string]AlphaTokenInfo),
|
||||
spotClient: binance.NewClient("", ""),
|
||||
futuresClient: futures.NewClient("", ""),
|
||||
spotPairs: make(map[string]bool),
|
||||
futuresPairs: make(map[string]bool),
|
||||
spotToken2Symbol: make(map[string]string),
|
||||
futureToken2Symbol: make(map[string]string),
|
||||
alphaTokens: make(map[string]AlphaTokenInfo),
|
||||
spotClient: binance.NewClient("", ""),
|
||||
futuresClient: futures.NewClient("", ""),
|
||||
}
|
||||
|
||||
if err := ms.refreshTradingPairCache(); err != nil {
|
||||
log.Error().Err(err).Msg("Failed initial trading pair cache load")
|
||||
}
|
||||
go ms.pairCacheRefreshLoop()
|
||||
go ms.alphaCacheRefreshLoop()
|
||||
ms.refreshAllCaches()
|
||||
go ms.cacheRefreshLoop()
|
||||
|
||||
return ms
|
||||
}
|
||||
|
||||
@@ -2,12 +2,15 @@ package market
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
"me.thuanle/bbot/internal/configs/binance"
|
||||
)
|
||||
|
||||
func (ms *MarketData) refreshTradingPairCache() error {
|
||||
func (ms *MarketData) refreshSpotPairCache() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -17,46 +20,162 @@ func (ms *MarketData) refreshTradingPairCache() error {
|
||||
return err
|
||||
}
|
||||
|
||||
spotPairs := make(map[string]bool, len(spotInfo.Symbols))
|
||||
spotTokenCandidates := make(map[string][]string)
|
||||
for _, s := range spotInfo.Symbols {
|
||||
if s.Status != "TRADING" {
|
||||
continue
|
||||
}
|
||||
spotPairs[s.Symbol] = true
|
||||
token := parseTokenFromSymbolByQuotePriority(s.Symbol)
|
||||
if token == "" {
|
||||
continue
|
||||
}
|
||||
spotTokenCandidates[token] = append(spotTokenCandidates[token], s.Symbol)
|
||||
}
|
||||
|
||||
spotToken2Symbol := make(map[string]string, len(spotTokenCandidates))
|
||||
for token, candidates := range spotTokenCandidates {
|
||||
spotToken2Symbol[token] = selectCanonicalSymbolByQuotePriority(token, candidates)
|
||||
}
|
||||
|
||||
ms.pairCacheMutex.Lock()
|
||||
ms.spotPairs = spotPairs
|
||||
ms.spotToken2Symbol = spotToken2Symbol
|
||||
ms.lastPairCacheUpdate = time.Now()
|
||||
ms.pairCacheMutex.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *MarketData) refreshFuturePairCache() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
|
||||
futuresInfo, err := ms.futuresClient.NewExchangeInfoService().Do(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to fetch futures exchange info")
|
||||
return err
|
||||
}
|
||||
|
||||
ms.pairCacheMutex.Lock()
|
||||
defer ms.pairCacheMutex.Unlock()
|
||||
|
||||
ms.spotPairs = make(map[string]bool, len(spotInfo.Symbols))
|
||||
for _, s := range spotInfo.Symbols {
|
||||
if s.Status == "TRADING" {
|
||||
ms.spotPairs[s.Symbol] = true
|
||||
}
|
||||
}
|
||||
|
||||
ms.futuresPairs = make(map[string]bool, len(futuresInfo.Symbols))
|
||||
futurePairs := make(map[string]bool, len(futuresInfo.Symbols))
|
||||
futureTokenCandidates := make(map[string][]string)
|
||||
for _, s := range futuresInfo.Symbols {
|
||||
if s.Status == "TRADING" {
|
||||
ms.futuresPairs[s.Symbol] = true
|
||||
if s.Status != "TRADING" {
|
||||
continue
|
||||
}
|
||||
futurePairs[s.Symbol] = true
|
||||
token := parseTokenFromSymbolByQuotePriority(s.Symbol)
|
||||
if token == "" {
|
||||
continue
|
||||
}
|
||||
token = normalizeFutureToken(token)
|
||||
futureTokenCandidates[token] = append(futureTokenCandidates[token], s.Symbol)
|
||||
}
|
||||
|
||||
futureToken2Symbol := make(map[string]string, len(futureTokenCandidates))
|
||||
for token, candidates := range futureTokenCandidates {
|
||||
futureToken2Symbol[token] = selectCanonicalSymbolByQuotePriority(token, candidates)
|
||||
}
|
||||
|
||||
ms.pairCacheMutex.Lock()
|
||||
ms.futuresPairs = futurePairs
|
||||
ms.futureToken2Symbol = futureToken2Symbol
|
||||
ms.lastPairCacheUpdate = time.Now()
|
||||
log.Info().
|
||||
Int("spot", len(ms.spotPairs)).
|
||||
Int("futures", len(ms.futuresPairs)).
|
||||
Msg("Trading pair cache refreshed")
|
||||
ms.pairCacheMutex.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *MarketData) pairCacheRefreshLoop() {
|
||||
ms.refreshTradingPairCache()
|
||||
func (ms *MarketData) refreshTradingPairCache() error {
|
||||
if err := ms.refreshSpotPairCache(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ms.refreshFuturePairCache(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ms.pairCacheMutex.RLock()
|
||||
spotCount := len(ms.spotPairs)
|
||||
futureCount := len(ms.futuresPairs)
|
||||
ms.pairCacheMutex.RUnlock()
|
||||
|
||||
log.Info().
|
||||
Int("spot", spotCount).
|
||||
Int("futures", futureCount).
|
||||
Msg("Trading pair cache refreshed")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ms *MarketData) cacheRefreshLoop() {
|
||||
ms.refreshAllCaches()
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
ms.refreshTradingPairCache()
|
||||
ms.refreshAllCaches()
|
||||
}
|
||||
}
|
||||
|
||||
func (ms *MarketData) refreshAllCaches() {
|
||||
if err := ms.refreshSpotPairCache(); err != nil {
|
||||
log.Error().Err(err).Msg("Failed spot pair refresh")
|
||||
}
|
||||
if err := ms.refreshFuturePairCache(); err != nil {
|
||||
log.Error().Err(err).Msg("Failed futures pair refresh")
|
||||
}
|
||||
ms.refreshAlphaTokenCache()
|
||||
}
|
||||
|
||||
func parseTokenFromSymbolByQuotePriority(symbol string) string {
|
||||
symbol = strings.ToUpper(symbol)
|
||||
for _, quote := range binance.QuotePriority {
|
||||
quote = strings.ToUpper(quote)
|
||||
if strings.HasSuffix(symbol, quote) {
|
||||
token := strings.TrimSuffix(symbol, quote)
|
||||
if token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func selectCanonicalSymbolByQuotePriority(token string, candidates []string) string {
|
||||
if len(candidates) == 0 {
|
||||
return ""
|
||||
}
|
||||
if len(candidates) == 1 {
|
||||
return strings.ToUpper(candidates[0])
|
||||
}
|
||||
|
||||
token = strings.ToUpper(token)
|
||||
normalized := make([]string, 0, len(candidates))
|
||||
for _, c := range candidates {
|
||||
normalized = append(normalized, strings.ToUpper(c))
|
||||
}
|
||||
|
||||
for _, quote := range binance.QuotePriority {
|
||||
target := token + strings.ToUpper(quote)
|
||||
for _, c := range normalized {
|
||||
if c == target {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(normalized)
|
||||
return normalized[0]
|
||||
}
|
||||
|
||||
func normalizeFutureToken(token string) string {
|
||||
token = strings.ToUpper(token)
|
||||
if mapped, ok := binance.FutureToken2SpotTokenMap[token]; ok {
|
||||
return strings.ToUpper(mapped)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func (ms *MarketData) IsSpotPair(symbol string) bool {
|
||||
ms.pairCacheMutex.RLock()
|
||||
defer ms.pairCacheMutex.RUnlock()
|
||||
@@ -69,6 +188,20 @@ func (ms *MarketData) IsFuturesPair(symbol string) bool {
|
||||
return ms.futuresPairs[symbol]
|
||||
}
|
||||
|
||||
func (ms *MarketData) GetSpotSymbolByToken(token string) (string, bool) {
|
||||
ms.pairCacheMutex.RLock()
|
||||
defer ms.pairCacheMutex.RUnlock()
|
||||
sym, ok := ms.spotToken2Symbol[strings.ToUpper(token)]
|
||||
return sym, ok
|
||||
}
|
||||
|
||||
func (ms *MarketData) GetFutureSymbolByToken(token string) (string, bool) {
|
||||
ms.pairCacheMutex.RLock()
|
||||
defer ms.pairCacheMutex.RUnlock()
|
||||
sym, ok := ms.futureToken2Symbol[strings.ToUpper(token)]
|
||||
return sym, ok
|
||||
}
|
||||
|
||||
func (ms *MarketData) RefreshTradingPairCache() error {
|
||||
return ms.refreshTradingPairCache()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package market
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSelectCanonicalSymbolByQuotePriority(t *testing.T) {
|
||||
pairs := []string{"DOGEFDUSD", "DOGEUSDC", "DOGEUSDT"}
|
||||
got := selectCanonicalSymbolByQuotePriority("DOGE", pairs)
|
||||
if got != "DOGEUSDT" {
|
||||
t.Fatalf("expected DOGEUSDT, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectCanonicalSymbolByQuotePriority_FallbackOrder(t *testing.T) {
|
||||
pairs := []string{"DOGEFDUSD", "DOGEUSDC"}
|
||||
got := selectCanonicalSymbolByQuotePriority("DOGE", pairs)
|
||||
if got != "DOGEUSDC" {
|
||||
t.Fatalf("expected DOGEUSDC, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectCanonicalSymbolByQuotePriority_NoPreferredQuote(t *testing.T) {
|
||||
pairs := []string{"DOGEBUSD"}
|
||||
got := selectCanonicalSymbolByQuotePriority("DOGE", pairs)
|
||||
if got != "DOGEBUSD" {
|
||||
t.Fatalf("expected DOGEBUSD, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeFutureToken_AppliesOverride(t *testing.T) {
|
||||
got := normalizeFutureToken("LUNA2")
|
||||
if got != "LUNA" {
|
||||
t.Fatalf("expected LUNA, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeFutureToken_NoOverride(t *testing.T) {
|
||||
got := normalizeFutureToken("PEPE")
|
||||
if got != "PEPE" {
|
||||
t.Fatalf("expected PEPE, got %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user