2 Commits

Author SHA1 Message Date
thuanle 7001ba00b4 refactor binance symbol resolver 2026-04-27 03:31:48 +07:00
thuanle a9d5d070c4 remove redundant file 2026-04-27 03:22:42 +07:00
20 changed files with 181 additions and 569 deletions
-2
View File
@@ -1,4 +1,2 @@
/.env
/.worktrees/
.DS_Store
.idea/
@@ -1,85 +0,0 @@
# Go filenames consistency design
## Context
The repository has inconsistent `.go` filename semantics in multiple areas (domain-oriented names, endpoint/history-oriented names, mixed singular/plural forms).
This slows code navigation because filenames do not consistently communicate data dimension or responsibility.
Goal: refactor `.go` filenames across the whole repository to a consistent naming model, and align declaration placement with filename responsibility, without changing runtime behavior.
## Scope
Applies to all `.go` files in the repository.
In scope:
- Rename `.go` files to consistent, responsibility-first names.
- Mechanical updates required by rename/move.
- Move declarations between files when needed so file responsibility is clear.
Out of scope:
- Any behavior or logic changes.
- Non-`.go` files.
- New feature work.
## Requirements
1. `.go` filename naming is consistent across the repository.
2. Filenames follow responsibility-first conventions:
- data-dimension names where applicable (`spot_*`, `futures_*`, etc.)
- pluralized collection-oriented files (`*_pairs.go`, `*_prices.go`)
- avoid endpoint/history-oriented naming that obscures responsibility.
3. Declarations in each file match filename responsibility.
4. No public/package behavior change.
5. Resulting PR remains reviewable by grouping changes mechanically and keeping logic untouched.
## Design
### Naming model
Use a responsibility-first naming model for all `.go` files:
- A reader should infer the primary responsibility from filename alone.
- Prefer domain/data-dimension names over transport/implementation-history names.
- Use consistent singular/plural convention based on file content (entity vs collection).
### Refactor mechanics
1. Inventory `.go` files by package and classify naming inconsistencies.
2. Define target filename map package-by-package.
3. Rename files with git-aware rename operations.
4. Move declarations when file content does not match filename responsibility.
5. Keep signatures and bodies unchanged.
6. Apply only mechanical reference/import updates required by moves.
### Execution strategy for reviewability
- Use focused commits by package or subsystem.
- Keep each commit behavior-neutral.
- Separate any necessary declaration moves from broad rename waves when this improves diff readability.
## Error handling and behavior
No new error handling paths are introduced.
Existing control flow and error behavior remain unchanged.
## Testing and verification
1. Run project tests after each major package/subsystem batch.
2. Run full project test command before PR.
3. Confirm no functional diff beyond rename/move/mechanical updates.
4. Final check: each renamed file contains declarations aligned with its responsibility.
## Risks and mitigations
- Risk: accidental behavior change while moving declarations.
- Mitigation: keep signatures/bodies unchanged and validate with tests per batch.
- Risk: review noise from repo-wide scope.
- Mitigation: package-grouped commits, strict mechanical-only edits, and explicit PR summary.
- Risk: large PR becomes hard to review.
- Mitigation: preserve commit structure and provide a clear rename map in PR description.
## Success criteria
- `.go` filenames are consistent and responsibility-first across the repo.
- Declarations in each file align with filename responsibility.
- Tests pass with no behavior regression.
- PR is understandable through structured, behavior-neutral commits.
+2 -2
View File
@@ -7,7 +7,7 @@ require (
github.com/go-resty/resty/v2 v2.17.2
github.com/jedib0t/go-pretty/v6 v6.7.10
github.com/joho/godotenv v1.5.1
github.com/rs/zerolog v1.35.1
github.com/rs/zerolog v1.32.0
github.com/samber/lo v1.53.0
golang.org/x/text v0.36.0
gopkg.in/telebot.v3 v3.3.8
@@ -18,7 +18,7 @@ require (
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
+10 -4
View File
@@ -99,6 +99,7 @@ github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -293,14 +294,16 @@ github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
@@ -359,8 +362,9 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rs/zerolog v1.35.1 h1:m7xQeoiLIiV0BCEY4Hs+j2NG4Gp2o2KPKmhnnLiazKI=
github.com/rs/zerolog v1.35.1/go.mod h1:EjML9kdfa/RMA7h/6z6pYmq1ykOuA8/mjWaEvGI+jcw=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sagikazarmark/crypt v0.6.0/go.mod h1:U8+INwJo3nBv1m6A/8OBXAq7Jnpspk5AxSgDyEQcea8=
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
@@ -619,7 +623,9 @@ golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220502124256-b6088ccd6cba/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+5 -12
View File
@@ -2,20 +2,13 @@ package binance
var SymbolPrefixList = []string{"1000000", "1000", "1M"}
var SymbolSuffixList = []string{"USDT", "USDC", "FDUSD"}
var SymbolSuffixList = []string{"USDT", "USDC"}
var SymbolSuffixMap = map[string]string{
"USDT": "",
"USDC": "c",
"FDUSD": "fd",
"USDT": "",
"USDC": "c",
}
var QuotePriority = []string{"USDT", "USDC", "FDUSD"}
var FutureToken2SpotTokenMap = map[string]string{
"LUNA2": "LUNA",
}
var SpotToken2FutureTokenMap = map[string]string{
"LUNA": "LUNA2",
var Future2SpotSymbolMap = map[string]string{
"LUNA2USDT": "LUNAUSDT",
}
+1 -1
View File
@@ -8,7 +8,7 @@ const (
var Token2StickerIdxMap = map[string]int{
"BNB": 3,
"TON": 5,
"TON": 7,
}
var Sticker2TokenMap = map[string]string{
-2
View File
@@ -18,7 +18,5 @@ 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
}
-65
View File
@@ -1,65 +0,0 @@
package market
import (
"context"
"strings"
"time"
"github.com/rs/zerolog/log"
)
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
}
futurePairs := make(map[string]bool, len(futuresInfo.Symbols))
futureTokenCandidates := make(map[string][]string)
for _, s := range futuresInfo.Symbols {
if s.Status != "TRADING" {
continue
}
futurePairs[s.Symbol] = true
token := parseTokenFromSymbolByQuotePriority(s.Symbol)
if token == "" {
continue
}
token = futureCacheTokenKey(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()
ms.pairCacheMutex.Unlock()
return nil
}
func futureCacheTokenKey(token string) string {
return strings.ToUpper(token)
}
func (ms *MarketData) IsFuturesPair(symbol string) bool {
ms.pairCacheMutex.RLock()
defer ms.pairCacheMutex.RUnlock()
return ms.futuresPairs[symbol]
}
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
}
+13 -49
View File
@@ -13,8 +13,6 @@ 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
@@ -31,61 +29,27 @@ type MarketData struct {
func NewMarketData() *MarketData {
log.Info().Msg("Start market service")
ms := &MarketData{
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("", ""),
spotPairs: make(map[string]bool),
futuresPairs: make(map[string]bool),
alphaTokens: make(map[string]AlphaTokenInfo),
spotClient: binance.NewClient("", ""),
futuresClient: futures.NewClient("", ""),
}
ms.refreshAllCaches()
go ms.cacheRefreshLoop()
if err := ms.refreshTradingPairCache(); err != nil {
log.Error().Err(err).Msg("Failed initial trading pair cache load")
}
go ms.pairCacheRefreshLoop()
go ms.alphaCacheRefreshLoop()
return ms
}
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()
func (ms *MarketData) alphaCacheRefreshLoop() {
ms.refreshAlphaTokenCache()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for range ticker.C {
ms.refreshAllCaches()
ms.refreshAlphaTokenCache()
}
}
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 (ms *MarketData) RefreshTradingPairCache() error {
return ms.refreshTradingPairCache()
}
-41
View File
@@ -1,41 +0,0 @@
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 TestFutureCacheTokenKey_PreservesRawFutureToken(t *testing.T) {
got := futureCacheTokenKey("LUNA2")
if got != "LUNA2" {
t.Fatalf("expected LUNA2, got %q", got)
}
}
func TestFutureCacheTokenKey_NoOverride(t *testing.T) {
got := futureCacheTokenKey("PEPE")
if got != "PEPE" {
t.Fatalf("expected PEPE, got %q", got)
}
}
-103
View File
@@ -1,103 +0,0 @@
package market
import (
"context"
"sort"
"strings"
"time"
"github.com/rs/zerolog/log"
"me.thuanle/bbot/internal/configs/binance"
)
func (ms *MarketData) refreshSpotPairCache() error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
spotInfo, err := ms.spotClient.NewExchangeInfoService().Do(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to fetch spot exchange info")
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 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 (ms *MarketData) IsSpotPair(symbol string) bool {
ms.pairCacheMutex.RLock()
defer ms.pairCacheMutex.RUnlock()
return ms.spotPairs[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
}
+74
View File
@@ -0,0 +1,74 @@
package market
import (
"context"
"time"
"github.com/rs/zerolog/log"
)
func (ms *MarketData) refreshTradingPairCache() error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
spotInfo, err := ms.spotClient.NewExchangeInfoService().Do(ctx)
if err != nil {
log.Error().Err(err).Msg("Failed to fetch spot exchange info")
return err
}
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))
for _, s := range futuresInfo.Symbols {
if s.Status == "TRADING" {
ms.futuresPairs[s.Symbol] = true
}
}
ms.lastPairCacheUpdate = time.Now()
log.Info().
Int("spot", len(ms.spotPairs)).
Int("futures", len(ms.futuresPairs)).
Msg("Trading pair cache refreshed")
return nil
}
func (ms *MarketData) pairCacheRefreshLoop() {
ms.refreshTradingPairCache()
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for range ticker.C {
ms.refreshTradingPairCache()
}
}
func (ms *MarketData) IsSpotPair(symbol string) bool {
ms.pairCacheMutex.RLock()
defer ms.pairCacheMutex.RUnlock()
return ms.spotPairs[symbol]
}
func (ms *MarketData) IsFuturesPair(symbol string) bool {
ms.pairCacheMutex.RLock()
defer ms.pairCacheMutex.RUnlock()
return ms.futuresPairs[symbol]
}
func (ms *MarketData) RefreshTradingPairCache() error {
return ms.refreshTradingPairCache()
}
+39 -36
View File
@@ -9,54 +9,50 @@ import (
)
func Token2FutureSymbols(token string) []string {
var syms []string
if !stringx.IsAlphaNumeric(token) {
return nil
return syms
}
token = strings.ToUpper(token)
if mapped, ok := data.Market.GetFutureSymbolByToken(token); ok {
return []string{mapped}
}
if futureToken, ok := binance.SpotToken2FutureTokenMap[token]; ok {
if mapped, ok := data.Market.GetFutureSymbolByToken(strings.ToUpper(futureToken)); ok {
return []string{mapped}
for _, prefix := range checkingPrefixList {
prefix = strings.ToUpper(prefix)
s := prefix + token
if data.Market.IsFuturesPair(s) {
syms = append(syms, s)
continue
}
for _, suffix := range binance.SymbolSuffixList {
suffix = strings.ToUpper(suffix)
abbr := strings.ToUpper(binance.SymbolSuffixMap[suffix])
sym := s + suffix
if data.Market.IsFuturesPair(sym) {
syms = append(syms, sym)
continue
}
symAbr, found := stringx.ReplaceSuffix(s, abbr, suffix)
if found && data.Market.IsFuturesPair(symAbr) {
syms = append(syms, symAbr)
continue
}
}
}
return nil
return syms
}
func Token2SpotSymbols(token string) []string {
if !stringx.IsAlphaNumeric(token) {
return nil
}
futureSymbols := Token2FutureSymbols(token)
spots := make([]string, 0, len(futureSymbols)+1)
seen := make(map[string]struct{}, len(futureSymbols)+1)
token = strings.ToUpper(token)
if mapped, ok := data.Market.GetSpotSymbolByToken(token); ok {
return []string{mapped}
}
return nil
}
func Token2RelatedSpotSymbols(token string) []string {
token = strings.ToUpper(token)
seen := make(map[string]struct{}, 2)
spots := make([]string, 0, 2)
for _, futureSymbol := range Token2FutureSymbols(token) {
for _, futureSymbol := range futureSymbols {
spotSymbol := Future2SpotSymbol(futureSymbol)
if _, ok := seen[spotSymbol]; ok {
continue
}
if data.Market.IsSpotPair(spotSymbol) {
seen[spotSymbol] = struct{}{}
spots = append(spots, spotSymbol)
}
}
for _, spotSymbol := range Token2SpotSymbols(token) {
if _, ok := seen[spotSymbol]; ok {
continue
}
@@ -64,5 +60,12 @@ func Token2RelatedSpotSymbols(token string) []string {
spots = append(spots, spotSymbol)
}
spotOnly := strings.ToUpper(token) + "USDT"
if data.Market.IsSpotPair(spotOnly) {
if _, ok := seen[spotOnly]; !ok {
spots = append(spots, spotOnly)
}
}
return spots
}
+28 -138
View File
@@ -1,16 +1,13 @@
package binancex
import (
"strings"
"testing"
"me.thuanle/bbot/internal/configs/binance"
"me.thuanle/bbot/internal/data"
"me.thuanle/bbot/internal/data/market"
)
type resolverMarketStub struct {
alphaTokens map[string]bool
spotPairs map[string]bool
futuresPairs map[string]bool
}
@@ -24,176 +21,69 @@ func (m *resolverMarketStub) GetAllPremiumIndex() (map[string]market.PremiumInde
func (m *resolverMarketStub) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil }
func (m *resolverMarketStub) GetSpotPrice(symbol string) (float64, bool) { return 0, false }
func (m *resolverMarketStub) GetMarginInterestRates() map[string]float64 { return nil }
func (m *resolverMarketStub) IsAlphaToken(symbol string) bool { return m.alphaTokens[symbol] }
func (m *resolverMarketStub) IsAlphaToken(symbol string) bool { return false }
func (m *resolverMarketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) {
return market.AlphaTokenInfo{}, false
}
func (m *resolverMarketStub) GetAlphaPrice(symbol string) (float64, bool) { return 0, false }
func (m *resolverMarketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] }
func (m *resolverMarketStub) IsFuturesPair(symbol string) bool { return m.futuresPairs[symbol] }
func (m *resolverMarketStub) GetSpotSymbolByToken(token string) (string, bool) {
token = strings.ToUpper(token)
for sym := range m.spotPairs {
if strings.ToUpper(Symbol2Token(sym)) == token {
return sym, true
}
}
return "", false
}
func (m *resolverMarketStub) GetFutureSymbolByToken(token string) (string, bool) {
token = strings.ToUpper(token)
for sym := range m.futuresPairs {
if strings.ToUpper(Symbol2Token(sym)) == token {
return sym, true
}
}
return "", false
}
func (m *resolverMarketStub) RefreshTradingPairCache() error { return nil }
func (m *resolverMarketStub) RefreshTradingPairCache() error { return nil }
func withResolverMarketStub(t *testing.T, marketStub *resolverMarketStub) {
t.Helper()
func TestToken2FutureSymbols_ResolvesPrefixAndSuffix(t *testing.T) {
orig := data.Market
data.Market = marketStub
t.Cleanup(func() { data.Market = orig })
}
defer func() { data.Market = orig }()
func TestToken2FutureSymbols_ReturnsCanonicalFutureSymbol(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
data.Market = &resolverMarketStub{
futuresPairs: map[string]bool{
"1000PEPEUSDT": true,
"1000PEPEUSDC": true,
},
})
}
syms := Token2FutureSymbols("pepe")
if len(syms) != 1 || syms[0] != "1000PEPEUSDT" {
t.Fatalf("expected canonical [1000PEPEUSDT], got %+v", syms)
if len(syms) == 0 {
t.Fatalf("expected future symbols for PEPE")
}
}
func TestToken2FutureSymbols_UsesCanonicalQuotePriority(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
futuresPairs: map[string]bool{
"1000PEPEUSDT": true,
"1000PEPEUSDC": true,
"PEPEUSDT": true,
"PEPEUSDC": true,
},
})
syms := Token2FutureSymbols("pepe")
if len(syms) != 1 || syms[0] != "1000PEPEUSDT" {
t.Fatalf("expected canonical [1000PEPEUSDT], got %+v", syms)
}
}
func TestToken2FutureSymbols_ResolvesUSDCAbbreviation(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
futuresPairs: map[string]bool{"PEPEUSDC": true},
})
syms := Token2FutureSymbols("pepec")
if len(syms) != 1 || syms[0] != "PEPEUSDC" {
t.Fatalf("expected [PEPEUSDC], got %+v", syms)
}
}
func TestSymbolSuffixListMatchesSymbolSuffixMap(t *testing.T) {
seen := make(map[string]struct{}, len(binance.SymbolSuffixList))
for _, suffix := range binance.SymbolSuffixList {
if _, ok := binance.SymbolSuffixMap[suffix]; !ok {
t.Fatalf("SymbolSuffixList contains %q missing from SymbolSuffixMap", suffix)
foundUSDT := false
foundUSDC := false
for _, sym := range syms {
if sym == "1000PEPEUSDT" {
foundUSDT = true
}
seen[suffix] = struct{}{}
}
for suffix := range binance.SymbolSuffixMap {
if _, ok := seen[suffix]; !ok {
t.Fatalf("SymbolSuffixMap contains %q missing from SymbolSuffixList", suffix)
if sym == "1000PEPEUSDC" {
foundUSDC = true
}
}
}
func TestIsToken(t *testing.T) {
tests := []struct {
name string
input string
marketStub *resolverMarketStub
want bool
}{
{
name: "futures token resolution success",
input: "pepe",
marketStub: &resolverMarketStub{
futuresPairs: map[string]bool{"1000PEPEUSDT": true},
},
want: true,
},
{
name: "alpha token fallback",
input: "alpha",
marketStub: &resolverMarketStub{
alphaTokens: map[string]bool{"ALPHA": true},
},
want: true,
},
{
name: "spot only token fallback",
input: "abc",
marketStub: &resolverMarketStub{
spotPairs: map[string]bool{"ABCUSDT": true},
},
want: true,
},
{
name: "non alphanumeric input",
input: "bad!",
marketStub: &resolverMarketStub{},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
withResolverMarketStub(t, tt.marketStub)
got := IsToken(tt.input)
if got != tt.want {
t.Fatalf("expected %v, got %v", tt.want, got)
}
})
if !foundUSDT || !foundUSDC {
t.Fatalf("expected both 1000PEPEUSDT and 1000PEPEUSDC, got %+v", syms)
}
}
func TestToken2SpotSymbols_DoesNotDependOnFutureMappings(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
func TestToken2SpotSymbols_AppliesExplicitRemap(t *testing.T) {
orig := data.Market
defer func() { data.Market = orig }()
data.Market = &resolverMarketStub{
futuresPairs: map[string]bool{"LUNA2USDT": true},
spotPairs: map[string]bool{"LUNAUSDT": true},
})
}
spots := Token2SpotSymbols("luna2")
if len(spots) != 0 {
t.Fatalf("expected no direct spot symbols for LUNA2, got %+v", spots)
}
}
func TestToken2RelatedSpotSymbols_AppliesExplicitRemap(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
futuresPairs: map[string]bool{"LUNA2USDT": true},
spotPairs: map[string]bool{"LUNAUSDT": true},
})
spots := Token2RelatedSpotSymbols("luna2")
if len(spots) != 1 || spots[0] != "LUNAUSDT" {
t.Fatalf("expected [LUNAUSDT], got %+v", spots)
}
}
func TestToken2SpotSymbols_SpotOnlyFallback(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
orig := data.Market
defer func() { data.Market = orig }()
data.Market = &resolverMarketStub{
spotPairs: map[string]bool{"ABCUSDT": true},
})
}
spots := Token2SpotSymbols("abc")
if len(spots) != 1 || spots[0] != "ABCUSDT" {
+6 -7
View File
@@ -30,13 +30,12 @@ var (
)
func IsToken(s string) bool {
// First check regular symbols
if len(Token2FutureSymbols(s)) > 0 {
return true
}
if len(Token2SpotSymbols(s)) > 0 {
return true
}
// Then check Alpha tokens
s = strings.ToUpper(s)
return data.Market.IsAlphaToken(s)
}
@@ -51,9 +50,9 @@ func Future2SpotSymbol(sym string) string {
}
}
token := Symbol2Token(sym)
if mapped, ok := binance.FutureToken2SpotTokenMap[token]; ok {
token = strings.ToUpper(mapped)
spotSym, ok := binance.Future2SpotSymbolMap[sym]
if !ok {
return sym
}
return token + "USDT"
return spotSym
}
+1 -1
View File
@@ -87,7 +87,7 @@ func collectRichTokenData(token string) buildRichTokenMessageArgs {
}
}
spotSymbols := binancex.Token2RelatedSpotSymbols(token)
spotSymbols := binancex.Token2SpotSymbols(token)
for _, spotSymbol := range spotSymbols {
if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok {
a.HasSpot = true
+1 -21
View File
@@ -1,12 +1,10 @@
package commands
import (
"strings"
"testing"
"me.thuanle/bbot/internal/data"
"me.thuanle/bbot/internal/data/market"
"me.thuanle/bbot/internal/helper/binancex"
)
func TestBuildRichTokenMessageInput_AllSources(t *testing.T) {
@@ -90,25 +88,7 @@ func (m *marketStub) GetAlphaPrice(symbol string) (float64, bool) {
}
func (m *marketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] }
func (m *marketStub) IsFuturesPair(symbol string) bool { return m.futuresPairs[symbol] }
func (m *marketStub) GetSpotSymbolByToken(token string) (string, bool) {
token = strings.ToUpper(token)
for symbol := range m.spotPairs {
if binancex.Symbol2Token(symbol) == token {
return symbol, true
}
}
return "", false
}
func (m *marketStub) GetFutureSymbolByToken(token string) (string, bool) {
token = strings.ToUpper(token)
for symbol := range m.futuresPairs {
if binancex.Symbol2Token(symbol) == token {
return symbol, true
}
}
return "", false
}
func (m *marketStub) RefreshTradingPairCache() error { return nil }
func (m *marketStub) RefreshTradingPairCache() error { return nil }
func TestCollectRichTokenData_SpotOnlyReachable(t *testing.T) {
orig := data.Market
Executable
+1
View File
@@ -0,0 +1 @@
go run cmd/tele/main.go ─╯