16 Commits

Author SHA1 Message Date
thuanle 617b067203 chore: address review for market filename refactor
Rename pair tests to match post-refactor boundaries and remove unused alpha cache refresh helper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 09:51:24 +07:00
thuanle f5e2e178e1 refactor: standardize market filenames by data dimension
Split market pair logic into spot and futures files and rename price files to plural data-dimension names without changing behavior.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 07:04:37 +07:00
thuanle 635b0c5b39 Merge pull request 'fix: recognize spot-only tokens in IsToken' (#25) from fix/issue-24-is-token-spot-only into main
Build Docker Image / build (amd64) (push) Successful in 1m1s
Reviewed-on: #25
2026-04-27 05:00:41 +07:00
thuanle d6338fa092 fix: preserve futures token identity in canonical cache
Keep futureToken2Symbol keyed by raw futures token and use explicit spot-to-future alias mapping during resolver fallback lookups.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 04:53:54 +07:00
thuanle 711721c1ee 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>
2026-04-27 04:44:30 +07:00
thuanle 06c40ef30f refactor: separate direct and related spot resolvers
Keep IsToken checks explicit across futures and direct spot symbols, move futures-derived spot mapping to a clearly named helper, and update token data collection to use related spot resolution.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 04:10:06 +07:00
thuanle 0705e909dc fix: recognize spot-only tokens in IsToken
Gate token detection via spot symbol resolution so chat flow accepts spot-only tokens, and add regression coverage for the fallback path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 03:59:32 +07:00
thuanle 72bbe66c3e Merge pull request 'Refactor Binance symbol resolver' (#23) from binance-symbol-resolver-refactor into main
Build Docker Image / build (amd64) (push) Successful in 1m39s
Reviewed-on: #23
Reviewed-by: claudecode <38+claudecode@noreply.localhost>
2026-04-27 03:54:01 +07:00
thuanle 252e77c000 test binance symbol resolver 2026-04-27 03:46:46 +07:00
thuanle 2c5a9e23bf refactor binance symbol resolver 2026-04-27 03:32:59 +07:00
thuanle 47d07f2092 style: fix gofmt alignment in resolver_test.go stub
Build Docker Image / build (amd64) (push) Successful in 1m3s
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 21:15:53 +07:00
thuanle 72fdb598af fix: resolve shared symbol mapping for token command (#22)
Build Docker Image / build (amd64) (push) Successful in 1m36s
Co-authored-by: thuanle <tl@thuanle.me>
Co-committed-by: thuanle <tl@thuanle.me>
2026-04-26 21:13:06 +07:00
thuanle 1486681ef9 Merge pull request 'fix: independent token source lookups' (#19) from feat/token-message-rich into main
Build Docker Image / build (amd64) (push) Successful in 2m10s
2026-04-26 18:51:17 +07:00
thuanle a4644f5982 Merge branch 'main' into feat/token-message-rich 2026-04-26 18:39:53 +07:00
thuanle 82b0f2f1a8 feat: fetch alpha price by symbol ticker
Keep alpha token existence from list cache and fetch live alpha price via symbol ticker endpoint for richer token response accuracy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 18:22:48 +07:00
thuanle 6e8a2e8f68 fix: decouple token spot/future/alpha lookups
Collect token market data independently for spot, futures, and alpha so any available source can be rendered even if others fail.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 18:13:13 +07:00
15 changed files with 608 additions and 245 deletions
+14 -4
View File
@@ -1,11 +1,21 @@
package binance package binance
var SymbolPrefixList = []string{"1000000", "1000", "1M"} var SymbolPrefixList = []string{"1000000", "1000", "1M"}
var SymbolSuffixList = []string{"USDT", "USDC", "FDUSD"}
var SymbolSuffixMap = map[string]string{ var SymbolSuffixMap = map[string]string{
"USDT": "", "USDT": "",
"USDC": "c", "USDC": "c",
"FDUSD": "fd",
} }
var Future2SpotSymbolMap = map[string]string{ var QuotePriority = []string{"USDT", "USDC", "FDUSD"}
"LUNA2USDT": "LUNAUSDT",
var FutureToken2SpotTokenMap = map[string]string{
"LUNA2": "LUNA",
}
var SpotToken2FutureTokenMap = map[string]string{
"LUNA": "LUNA2",
} }
+3
View File
@@ -13,9 +13,12 @@ type IMarket interface {
// Alpha token methods // Alpha token methods
IsAlphaToken(symbol string) bool IsAlphaToken(symbol string) bool
GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool)
GetAlphaPrice(symbol string) (float64, bool)
// Trading pair methods // Trading pair methods
IsSpotPair(symbol string) bool IsSpotPair(symbol string) bool
IsFuturesPair(symbol string) bool IsFuturesPair(symbol string) bool
GetSpotSymbolByToken(token string) (string, bool)
GetFutureSymbolByToken(token string) (string, bool)
RefreshTradingPairCache() error RefreshTradingPairCache() error
} }
+49 -3
View File
@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"time" "time"
@@ -54,10 +55,21 @@ type AlphaTokenInfo struct {
// AlphaTokenResponse represents the API response structure // AlphaTokenResponse represents the API response structure
type AlphaTokenResponse struct { type AlphaTokenResponse struct {
Code string `json:"code"` Code string `json:"code"`
Message *string `json:"message"` Message *string `json:"message"`
MessageDetail *string `json:"messageDetail"`
Data []AlphaTokenInfo `json:"data"`
}
type AlphaTickerData struct {
Price string `json:"price"`
}
type AlphaTickerResponse struct {
Code string `json:"code"`
Message *string `json:"message"`
MessageDetail *string `json:"messageDetail"` MessageDetail *string `json:"messageDetail"`
Data []AlphaTokenInfo `json:"data"` Data AlphaTickerData `json:"data"`
} }
// GetPrice returns the price as float64 // GetPrice returns the price as float64
@@ -150,3 +162,37 @@ func (ms *MarketData) IsAlphaToken(symbol string) bool {
_, exists := ms.GetAlphaToken(symbol) _, exists := ms.GetAlphaToken(symbol)
return exists return exists
} }
func (ms *MarketData) GetAlphaPrice(symbol string) (float64, bool) {
const alphaTickerURL = "https://www.binance.com/bapi/defi/v1/public/alpha-trade/ticker"
client := &http.Client{Timeout: 5 * time.Second}
endpoint := alphaTickerURL + "?" + url.Values{"symbol": []string{symbol}}.Encode()
resp, err := client.Get(endpoint)
if err != nil {
log.Error().Err(err).Str("symbol", symbol).Msg("Failed to fetch Alpha ticker")
return 0, false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, false
}
var tickerResp AlphaTickerResponse
if err := json.NewDecoder(resp.Body).Decode(&tickerResp); err != nil {
return 0, false
}
if tickerResp.Code != "000000" {
return 0, false
}
price, err := strconv.ParseFloat(tickerResp.Data.Price, 64)
if err != nil || price <= 0 {
return 0, false
}
return price, true
}
+65
View File
@@ -0,0 +1,65 @@
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
}
+49 -13
View File
@@ -13,6 +13,8 @@ type MarketData struct {
// Trading pair caches // Trading pair caches
spotPairs map[string]bool spotPairs map[string]bool
futuresPairs map[string]bool futuresPairs map[string]bool
spotToken2Symbol map[string]string
futureToken2Symbol map[string]string
pairCacheMutex sync.RWMutex pairCacheMutex sync.RWMutex
lastPairCacheUpdate time.Time lastPairCacheUpdate time.Time
@@ -29,27 +31,61 @@ type MarketData struct {
func NewMarketData() *MarketData { func NewMarketData() *MarketData {
log.Info().Msg("Start market service") log.Info().Msg("Start market service")
ms := &MarketData{ ms := &MarketData{
spotPairs: make(map[string]bool), spotPairs: make(map[string]bool),
futuresPairs: make(map[string]bool), futuresPairs: make(map[string]bool),
alphaTokens: make(map[string]AlphaTokenInfo), spotToken2Symbol: make(map[string]string),
spotClient: binance.NewClient("", ""), futureToken2Symbol: make(map[string]string),
futuresClient: futures.NewClient("", ""), alphaTokens: make(map[string]AlphaTokenInfo),
spotClient: binance.NewClient("", ""),
futuresClient: futures.NewClient("", ""),
} }
if err := ms.refreshTradingPairCache(); err != nil { ms.refreshAllCaches()
log.Error().Err(err).Msg("Failed initial trading pair cache load") go ms.cacheRefreshLoop()
}
go ms.pairCacheRefreshLoop()
go ms.alphaCacheRefreshLoop()
return ms return ms
} }
func (ms *MarketData) alphaCacheRefreshLoop() { func (ms *MarketData) refreshTradingPairCache() error {
ms.refreshAlphaTokenCache() 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) ticker := time.NewTicker(time.Hour)
defer ticker.Stop() defer ticker.Stop()
for range ticker.C { for range ticker.C {
ms.refreshAlphaTokenCache() 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 (ms *MarketData) RefreshTradingPairCache() error {
return ms.refreshTradingPairCache()
}
+41
View File
@@ -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 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
@@ -0,0 +1,103 @@
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
@@ -1,74 +0,0 @@
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()
}
+45 -12
View File
@@ -3,20 +3,60 @@ package binancex
import ( import (
"strings" "strings"
"me.thuanle/bbot/internal/configs/binance"
"me.thuanle/bbot/internal/data" "me.thuanle/bbot/internal/data"
"me.thuanle/bbot/internal/utils/stringx"
) )
func Token2FutureSymbols(token string) []string { func Token2FutureSymbols(token string) []string {
return Token2Symbols(token) if !stringx.IsAlphaNumeric(token) {
return nil
}
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}
}
}
return nil
} }
func Token2SpotSymbols(token string) []string { func Token2SpotSymbols(token string) []string {
futureSymbols := Token2FutureSymbols(token) if !stringx.IsAlphaNumeric(token) {
spots := make([]string, 0, len(futureSymbols)+1) return nil
seen := make(map[string]struct{}, len(futureSymbols)+1) }
for _, futureSymbol := range futureSymbols { 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) {
spotSymbol := Future2SpotSymbol(futureSymbol) 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 { if _, ok := seen[spotSymbol]; ok {
continue continue
} }
@@ -24,12 +64,5 @@ func Token2SpotSymbols(token string) []string {
spots = append(spots, spotSymbol) 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 return spots
} }
+149 -38
View File
@@ -1,13 +1,16 @@
package binancex package binancex
import ( import (
"strings"
"testing" "testing"
"me.thuanle/bbot/internal/configs/binance"
"me.thuanle/bbot/internal/data" "me.thuanle/bbot/internal/data"
"me.thuanle/bbot/internal/data/market" "me.thuanle/bbot/internal/data/market"
) )
type resolverMarketStub struct { type resolverMarketStub struct {
alphaTokens map[string]bool
spotPairs map[string]bool spotPairs map[string]bool
futuresPairs map[string]bool futuresPairs map[string]bool
} }
@@ -19,70 +22,178 @@ func (m *resolverMarketStub) GetAllPremiumIndex() (map[string]market.PremiumInde
return nil, nil return nil, nil
} }
func (m *resolverMarketStub) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil } 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) GetSpotPrice(symbol string) (float64, bool) { return 0, false }
func (m *resolverMarketStub) GetMarginInterestRates() map[string]float64 { return nil } func (m *resolverMarketStub) GetMarginInterestRates() map[string]float64 { return nil }
func (m *resolverMarketStub) IsAlphaToken(symbol string) bool { return false } func (m *resolverMarketStub) IsAlphaToken(symbol string) bool { return m.alphaTokens[symbol] }
func (m *resolverMarketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) { func (m *resolverMarketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) {
return market.AlphaTokenInfo{}, false return market.AlphaTokenInfo{}, false
} }
func (m *resolverMarketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] } func (m *resolverMarketStub) GetAlphaPrice(symbol string) (float64, bool) { return 0, false }
func (m *resolverMarketStub) IsFuturesPair(symbol string) bool { return m.futuresPairs[symbol] } func (m *resolverMarketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] }
func (m *resolverMarketStub) RefreshTradingPairCache() error { return nil } 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 TestToken2FutureSymbols_ResolvesPrefixAndSuffix(t *testing.T) { func withResolverMarketStub(t *testing.T, marketStub *resolverMarketStub) {
t.Helper()
orig := data.Market orig := data.Market
defer func() { data.Market = orig }() data.Market = marketStub
t.Cleanup(func() { data.Market = orig })
}
data.Market = &resolverMarketStub{ func TestToken2FutureSymbols_ReturnsCanonicalFutureSymbol(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
futuresPairs: map[string]bool{ futuresPairs: map[string]bool{
"1000PEPEUSDT": true, "1000PEPEUSDT": true,
"1000PEPEUSDC": true, "1000PEPEUSDC": true,
}, },
} })
syms := Token2FutureSymbols("pepe") syms := Token2FutureSymbols("pepe")
if len(syms) == 0 { if len(syms) != 1 || syms[0] != "1000PEPEUSDT" {
t.Fatalf("expected future symbols for PEPE") t.Fatalf("expected canonical [1000PEPEUSDT], got %+v", syms)
}
foundUSDT := false
foundUSDC := false
for _, sym := range syms {
if sym == "1000PEPEUSDT" {
foundUSDT = true
}
if sym == "1000PEPEUSDC" {
foundUSDC = true
}
}
if !foundUSDT || !foundUSDC {
t.Fatalf("expected both 1000PEPEUSDT and 1000PEPEUSDC, got %+v", syms)
} }
} }
func TestToken2SpotSymbols_AppliesExplicitRemap(t *testing.T) { func TestToken2FutureSymbols_UsesCanonicalQuotePriority(t *testing.T) {
orig := data.Market withResolverMarketStub(t, &resolverMarketStub{
defer func() { data.Market = orig }() futuresPairs: map[string]bool{
"1000PEPEUSDT": true,
"1000PEPEUSDC": true,
"PEPEUSDT": true,
"PEPEUSDC": true,
},
})
data.Market = &resolverMarketStub{ syms := Token2FutureSymbols("pepe")
futuresPairs: map[string]bool{"LUNA2USDT": true}, if len(syms) != 1 || syms[0] != "1000PEPEUSDT" {
spotPairs: map[string]bool{"LUNAUSDT": true}, 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)
}
seen[suffix] = struct{}{}
} }
for suffix := range binance.SymbolSuffixMap {
if _, ok := seen[suffix]; !ok {
t.Fatalf("SymbolSuffixMap contains %q missing from SymbolSuffixList", suffix)
}
}
}
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)
}
})
}
}
func TestToken2SpotSymbols_DoesNotDependOnFutureMappings(t *testing.T) {
withResolverMarketStub(t, &resolverMarketStub{
futuresPairs: map[string]bool{"LUNA2USDT": true},
spotPairs: map[string]bool{"LUNAUSDT": true},
})
spots := Token2SpotSymbols("luna2") 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" { if len(spots) != 1 || spots[0] != "LUNAUSDT" {
t.Fatalf("expected [LUNAUSDT], got %+v", spots) t.Fatalf("expected [LUNAUSDT], got %+v", spots)
} }
} }
func TestToken2SpotSymbols_SpotOnlyFallback(t *testing.T) { func TestToken2SpotSymbols_SpotOnlyFallback(t *testing.T) {
orig := data.Market withResolverMarketStub(t, &resolverMarketStub{
defer func() { data.Market = orig }()
data.Market = &resolverMarketStub{
spotPairs: map[string]bool{"ABCUSDT": true}, spotPairs: map[string]bool{"ABCUSDT": true},
} })
spots := Token2SpotSymbols("abc") spots := Token2SpotSymbols("abc")
if len(spots) != 1 || spots[0] != "ABCUSDT" { if len(spots) != 1 || spots[0] != "ABCUSDT" {
+10 -53
View File
@@ -14,7 +14,8 @@ func Symbol2Token(sym string) string {
for _, prefix := range binance.SymbolPrefixList { for _, prefix := range binance.SymbolPrefixList {
token, _ = strings.CutPrefix(token, prefix) token, _ = strings.CutPrefix(token, prefix)
} }
for suffix, abbr := range binance.SymbolSuffixMap { for _, suffix := range binance.SymbolSuffixList {
abbr := binance.SymbolSuffixMap[suffix]
var f bool var f bool
token, f = stringx.ReplaceSuffix(token, suffix, abbr) token, f = stringx.ReplaceSuffix(token, suffix, abbr)
if f { if f {
@@ -28,58 +29,14 @@ var (
checkingPrefixList = append(binance.SymbolPrefixList, "") checkingPrefixList = append(binance.SymbolPrefixList, "")
) )
func testSym(sym string) bool {
return data.Market.IsFuturesPair(sym)
}
func Token2Symbols(token string) []string {
var syms []string
if !stringx.IsAlphaNumeric(token) {
return syms
}
token = strings.ToUpper(token)
for _, prefix := range checkingPrefixList {
prefix = strings.ToUpper(prefix)
s := prefix + token
//no suffix
if testSym(s) {
syms = append(syms, s)
continue
}
for suffix, abbr := range binance.SymbolSuffixMap {
suffix = strings.ToUpper(suffix)
abbr = strings.ToUpper(abbr)
//suffix
sym := s + suffix
if testSym(sym) {
syms = append(syms, sym)
continue
}
//suffix abbr
symAbr, found := stringx.ReplaceSuffix(s, abbr, suffix)
if found && testSym(symAbr) {
syms = append(syms, symAbr)
continue
}
}
}
return syms
}
func IsToken(s string) bool { func IsToken(s string) bool {
// First check regular symbols if len(Token2FutureSymbols(s)) > 0 {
if len(Token2Symbols(s)) > 0 { return true
}
if len(Token2SpotSymbols(s)) > 0 {
return true return true
} }
// Then check Alpha tokens
s = strings.ToUpper(s) s = strings.ToUpper(s)
return data.Market.IsAlphaToken(s) return data.Market.IsAlphaToken(s)
} }
@@ -94,9 +51,9 @@ func Future2SpotSymbol(sym string) string {
} }
} }
spotSym, ok := binance.Future2SpotSymbolMap[sym] token := Symbol2Token(sym)
if !ok { if mapped, ok := binance.FutureToken2SpotTokenMap[token]; ok {
return sym token = strings.ToUpper(mapped)
} }
return spotSym return token + "USDT"
} }
+6 -3
View File
@@ -67,9 +67,13 @@ func collectRichTokenData(token string) buildRichTokenMessageArgs {
if alphaToken, ok := data.Market.GetAlphaToken(token); ok { if alphaToken, ok := data.Market.GetAlphaToken(token); ok {
a.HasAlpha = true a.HasAlpha = true
a.AlphaPrice = alphaToken.GetPrice()
a.HasAlpha24h = true a.HasAlpha24h = true
a.Alpha24h = alphaToken.GetPercentChange24h() a.Alpha24h = alphaToken.GetPercentChange24h()
if alphaPrice, ok := data.Market.GetAlphaPrice(token + "USDT"); ok {
a.AlphaPrice = alphaPrice
} else {
a.AlphaPrice = alphaToken.GetPrice()
}
} }
futureSymbols := binancex.Token2FutureSymbols(token) futureSymbols := binancex.Token2FutureSymbols(token)
@@ -83,7 +87,7 @@ func collectRichTokenData(token string) buildRichTokenMessageArgs {
} }
} }
spotSymbols := binancex.Token2SpotSymbols(token) spotSymbols := binancex.Token2RelatedSpotSymbols(token)
for _, spotSymbol := range spotSymbols { for _, spotSymbol := range spotSymbols {
if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok { if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok {
a.HasSpot = true a.HasSpot = true
@@ -109,7 +113,6 @@ func OnTokenInfoByToken(context telebot.Context, token string) error {
} }
msg := view.RenderRichTokenMessage(buildRichTokenMessageInput(args)) msg := view.RenderRichTokenMessage(buildRichTokenMessageInput(args))
_ = chat.ReplyMessage(context, msg) _ = chat.ReplyMessage(context, msg)
return nil return nil
} }
+73 -44
View File
@@ -1,51 +1,14 @@
package commands package commands
import ( import (
"strings"
"testing" "testing"
"me.thuanle/bbot/internal/data" "me.thuanle/bbot/internal/data"
"me.thuanle/bbot/internal/data/market" "me.thuanle/bbot/internal/data/market"
"me.thuanle/bbot/internal/helper/binancex"
) )
type marketStub struct {
spotPairs map[string]bool
futuresPairs map[string]bool
spotPrices map[string]float64
futurePrices map[string]struct {
price float64
rate float64
time int64
}
alphaTokens map[string]market.AlphaTokenInfo
marginRates map[string]float64
}
func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
v, ok := m.futurePrices[symbol]
if !ok {
return 0, 0, 0, false
}
return v.price, v.rate, v.time, true
}
func (m *marketStub) GetAllPremiumIndex() (map[string]market.PremiumIndex, error) { return nil, nil }
func (m *marketStub) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil }
func (m *marketStub) GetSpotPrice(symbol string) (float64, bool) {
v, ok := m.spotPrices[symbol]
return v, ok
}
func (m *marketStub) GetMarginInterestRates() map[string]float64 { return m.marginRates }
func (m *marketStub) IsAlphaToken(symbol string) bool {
_, ok := m.alphaTokens[symbol]
return ok
}
func (m *marketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) {
v, ok := m.alphaTokens[symbol]
return v, ok
}
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) RefreshTradingPairCache() error { return nil }
func TestBuildRichTokenMessageInput_AllSources(t *testing.T) { func TestBuildRichTokenMessageInput_AllSources(t *testing.T) {
in := buildRichTokenMessageInput(buildRichTokenMessageArgs{ in := buildRichTokenMessageInput(buildRichTokenMessageArgs{
Token: "ETH", Token: "ETH",
@@ -85,6 +48,68 @@ func TestBuildRichTokenMessageInput_OnlyAlpha(t *testing.T) {
} }
} }
type marketStub struct {
spotPairs map[string]bool
futuresPairs map[string]bool
spotPrices map[string]float64
futurePrices map[string]struct {
price float64
rate float64
time int64
}
alphaTokens map[string]market.AlphaTokenInfo
alphaPrices map[string]float64
marginRates map[string]float64
}
func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
v, ok := m.futurePrices[symbol]
if !ok {
return 0, 0, 0, false
}
return v.price, v.rate, v.time, true
}
func (m *marketStub) GetAllPremiumIndex() (map[string]market.PremiumIndex, error) { return nil, nil }
func (m *marketStub) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil }
func (m *marketStub) GetSpotPrice(symbol string) (float64, bool) {
v, ok := m.spotPrices[symbol]
return v, ok
}
func (m *marketStub) GetMarginInterestRates() map[string]float64 { return m.marginRates }
func (m *marketStub) IsAlphaToken(symbol string) bool {
_, ok := m.alphaTokens[symbol]
return ok
}
func (m *marketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) {
v, ok := m.alphaTokens[symbol]
return v, ok
}
func (m *marketStub) GetAlphaPrice(symbol string) (float64, bool) {
v, ok := m.alphaPrices[symbol]
return v, ok
}
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 TestCollectRichTokenData_SpotOnlyReachable(t *testing.T) { func TestCollectRichTokenData_SpotOnlyReachable(t *testing.T) {
orig := data.Market orig := data.Market
defer func() { data.Market = orig }() defer func() { data.Market = orig }()
@@ -194,21 +219,25 @@ func TestCollectRichTokenData_PrefixFutureMapsToSpot(t *testing.T) {
} }
} }
func TestCollectRichTokenData_AlphaIndependent(t *testing.T) { func TestCollectRichTokenData_AlphaUsesSymbolPrice(t *testing.T) {
orig := data.Market orig := data.Market
defer func() { data.Market = orig }() defer func() { data.Market = orig }()
data.Market = &marketStub{ data.Market = &marketStub{
alphaTokens: map[string]market.AlphaTokenInfo{ alphaTokens: map[string]market.AlphaTokenInfo{
"ABC": {Symbol: "ABC", PercentChange24h: "12.4", Price: "0.1234"}, "ABC": {Symbol: "ABC", PercentChange24h: "12.4", Price: "0.1"},
}, },
alphaPrices: map[string]float64{"ABCUSDT": 0.1234},
} }
args := collectRichTokenData("ABC") args := collectRichTokenData("ABC")
if !args.HasAlpha { if !args.HasAlpha {
t.Fatalf("expected alpha source available, got %+v", args) t.Fatalf("expected alpha to be available: %+v", args)
} }
if args.HasSpot || args.HasFuture { if !args.HasAlpha24h {
t.Fatalf("expected alpha independent from spot/future, got %+v", args) t.Fatalf("expected alpha 24h to be available: %+v", args)
}
if args.AlphaPrice != 0.1234 {
t.Fatalf("expected alpha price from symbol lookup, got %.4f", args.AlphaPrice)
} }
} }