Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c3b3ef616 | |||
| 0a1a61d8d3 | |||
| 5912157ed1 | |||
| c5ff494e13 | |||
| 617b067203 | |||
| f5e2e178e1 | |||
| bc99d40713 | |||
| 8010a00e4d | |||
| 259a630b78 | |||
| f64a3521c4 | |||
| 635b0c5b39 | |||
| d6338fa092 | |||
| 711721c1ee | |||
| 06c40ef30f | |||
| 0705e909dc | |||
| 72bbe66c3e | |||
| 252e77c000 | |||
| 2c5a9e23bf | |||
| 47d07f2092 | |||
| 72fdb598af | |||
| 1486681ef9 |
@@ -1,2 +1,4 @@
|
|||||||
/.env
|
/.env
|
||||||
/.worktrees/
|
/.worktrees/
|
||||||
|
.DS_Store
|
||||||
|
.idea/
|
||||||
Generated
-8
@@ -1,8 +0,0 @@
|
|||||||
# Default ignored files
|
|
||||||
/shelf/
|
|
||||||
/workspace.xml
|
|
||||||
# Editor-based HTTP Client requests
|
|
||||||
/httpRequests/
|
|
||||||
# Datasource local storage ignored files
|
|
||||||
/dataSources/
|
|
||||||
/dataSources.local.xml
|
|
||||||
Generated
-9
@@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<module type="WEB_MODULE" version="4">
|
|
||||||
<component name="Go" enabled="true" />
|
|
||||||
<component name="NewModuleRootManager">
|
|
||||||
<content url="file://$MODULE_DIR$" />
|
|
||||||
<orderEntry type="inheritedJdk" />
|
|
||||||
<orderEntry type="sourceFolder" forTests="false" />
|
|
||||||
</component>
|
|
||||||
</module>
|
|
||||||
Generated
-8
@@ -1,8 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ProjectModuleManager">
|
|
||||||
<modules>
|
|
||||||
<module fileurl="file://$PROJECT_DIR$/.idea/crypto-price-bot.iml" filepath="$PROJECT_DIR$/.idea/crypto-price-bot.iml" />
|
|
||||||
</modules>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
Generated
-6
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="" vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# 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.
|
||||||
@@ -5,7 +5,7 @@ go 1.25.0
|
|||||||
require (
|
require (
|
||||||
github.com/adshao/go-binance/v2 v2.8.11
|
github.com/adshao/go-binance/v2 v2.8.11
|
||||||
github.com/go-resty/resty/v2 v2.17.2
|
github.com/go-resty/resty/v2 v2.17.2
|
||||||
github.com/jedib0t/go-pretty/v6 v6.7.10
|
github.com/jedib0t/go-pretty/v6 v6.8.0
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/rs/zerolog v1.32.0
|
github.com/rs/zerolog v1.32.0
|
||||||
github.com/samber/lo v1.53.0
|
github.com/samber/lo v1.53.0
|
||||||
|
|||||||
@@ -257,8 +257,8 @@ github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpT
|
|||||||
github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=
|
github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=
|
||||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.7.10 h1:B/2qW2Bkv2L6n14PP8o1kx75kWzHOQ3YTluWzg9icac=
|
github.com/jedib0t/go-pretty/v6 v6.8.0 h1:fQOTjATVQl5RhssBro6ZuHANFybCkmJ7FjYPo4b7sEY=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.7.10/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
github.com/jedib0t/go-pretty/v6 v6.8.0/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
|
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
|
||||||
|
|||||||
@@ -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",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ const (
|
|||||||
|
|
||||||
var Token2StickerIdxMap = map[string]int{
|
var Token2StickerIdxMap = map[string]int{
|
||||||
"BNB": 3,
|
"BNB": 3,
|
||||||
"TON": 7,
|
"TON": 5,
|
||||||
}
|
}
|
||||||
|
|
||||||
var Sticker2TokenMap = map[string]string{
|
var Sticker2TokenMap = map[string]string{
|
||||||
|
|||||||
@@ -18,5 +18,7 @@ type IMarket interface {
|
|||||||
// 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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -31,25 +33,59 @@ func NewMarketData() *MarketData {
|
|||||||
ms := &MarketData{
|
ms := &MarketData{
|
||||||
spotPairs: make(map[string]bool),
|
spotPairs: make(map[string]bool),
|
||||||
futuresPairs: make(map[string]bool),
|
futuresPairs: make(map[string]bool),
|
||||||
|
spotToken2Symbol: make(map[string]string),
|
||||||
|
futureToken2Symbol: make(map[string]string),
|
||||||
alphaTokens: make(map[string]AlphaTokenInfo),
|
alphaTokens: make(map[string]AlphaTokenInfo),
|
||||||
spotClient: binance.NewClient("", ""),
|
spotClient: binance.NewClient("", ""),
|
||||||
futuresClient: futures.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.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()
|
ms.refreshAlphaTokenCache()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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()
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package binancex
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"me.thuanle/bbot/internal/configs/binance"
|
||||||
|
"me.thuanle/bbot/internal/data"
|
||||||
|
"me.thuanle/bbot/internal/utils/stringx"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Token2FutureSymbols(token string) []string {
|
||||||
|
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 {
|
||||||
|
if !stringx.IsAlphaNumeric(token) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
seen[spotSymbol] = struct{}{}
|
||||||
|
spots = append(spots, spotSymbol)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spots
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *resolverMarketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
|
||||||
|
return 0, 0, 0, false
|
||||||
|
}
|
||||||
|
func (m *resolverMarketStub) GetAllPremiumIndex() (map[string]market.PremiumIndex, error) {
|
||||||
|
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) GetMarginInterestRates() map[string]float64 { return nil }
|
||||||
|
func (m *resolverMarketStub) IsAlphaToken(symbol string) bool { return m.alphaTokens[symbol] }
|
||||||
|
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 withResolverMarketStub(t *testing.T, marketStub *resolverMarketStub) {
|
||||||
|
t.Helper()
|
||||||
|
orig := data.Market
|
||||||
|
data.Market = marketStub
|
||||||
|
t.Cleanup(func() { data.Market = orig })
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToken2FutureSymbols_ReturnsCanonicalFutureSymbol(t *testing.T) {
|
||||||
|
withResolverMarketStub(t, &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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
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")
|
||||||
|
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{
|
||||||
|
spotPairs: map[string]bool{"ABCUSDT": true},
|
||||||
|
})
|
||||||
|
|
||||||
|
spots := Token2SpotSymbols("abc")
|
||||||
|
if len(spots) != 1 || spots[0] != "ABCUSDT" {
|
||||||
|
t.Fatalf("expected [ABCUSDT], got %+v", spots)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,11 +2,11 @@ package commands
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"gopkg.in/telebot.v3"
|
"gopkg.in/telebot.v3"
|
||||||
"me.thuanle/bbot/internal/configs/tele"
|
"me.thuanle/bbot/internal/configs/tele"
|
||||||
"me.thuanle/bbot/internal/data"
|
"me.thuanle/bbot/internal/data"
|
||||||
|
"me.thuanle/bbot/internal/helper/binancex"
|
||||||
"me.thuanle/bbot/internal/services/tele/chat"
|
"me.thuanle/bbot/internal/services/tele/chat"
|
||||||
"me.thuanle/bbot/internal/services/tele/view"
|
"me.thuanle/bbot/internal/services/tele/view"
|
||||||
)
|
)
|
||||||
@@ -65,63 +65,41 @@ func showStickerMode(context telebot.Context, token string) {
|
|||||||
func collectRichTokenData(token string) buildRichTokenMessageArgs {
|
func collectRichTokenData(token string) buildRichTokenMessageArgs {
|
||||||
a := buildRichTokenMessageArgs{Token: token}
|
a := buildRichTokenMessageArgs{Token: token}
|
||||||
|
|
||||||
marginRates := data.Market.GetMarginInterestRates()
|
|
||||||
a.MarginAPRPercent = marginRates[token] * 365 * 100
|
|
||||||
a.HasMarginAPR = marginRates[token] != 0
|
|
||||||
|
|
||||||
futureSymbol := token + "USDT"
|
|
||||||
spotSymbol := token + "USDT"
|
|
||||||
|
|
||||||
var (
|
|
||||||
wg sync.WaitGroup
|
|
||||||
mu sync.Mutex
|
|
||||||
)
|
|
||||||
wg.Add(3)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
if alphaToken, ok := data.Market.GetAlphaToken(token); ok {
|
if alphaToken, ok := data.Market.GetAlphaToken(token); ok {
|
||||||
alpha24h := alphaToken.GetPercentChange24h()
|
|
||||||
alphaPrice := alphaToken.GetPrice()
|
|
||||||
if p, ok := data.Market.GetAlphaPrice(token + "USDT"); ok {
|
|
||||||
alphaPrice = p
|
|
||||||
}
|
|
||||||
mu.Lock()
|
|
||||||
a.HasAlpha = true
|
a.HasAlpha = true
|
||||||
a.HasAlpha24h = true
|
a.HasAlpha24h = true
|
||||||
a.Alpha24h = alpha24h
|
a.Alpha24h = alphaToken.GetPercentChange24h()
|
||||||
|
if alphaPrice, ok := data.Market.GetAlphaPrice(token + "USDT"); ok {
|
||||||
a.AlphaPrice = alphaPrice
|
a.AlphaPrice = alphaPrice
|
||||||
mu.Unlock()
|
} else {
|
||||||
|
a.AlphaPrice = alphaToken.GetPrice()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
futureSymbols := binancex.Token2FutureSymbols(token)
|
||||||
defer wg.Done()
|
for _, futureSymbol := range futureSymbols {
|
||||||
if data.Market.IsFuturesPair(futureSymbol) {
|
|
||||||
if fp, fr, ft, ok := data.Market.GetFuturePrice(futureSymbol); ok {
|
if fp, fr, ft, ok := data.Market.GetFuturePrice(futureSymbol); ok {
|
||||||
mu.Lock()
|
|
||||||
a.HasFuture = true
|
a.HasFuture = true
|
||||||
a.FuturePrice = fp
|
a.FuturePrice = fp
|
||||||
a.FundingRate = fr
|
a.FundingRate = fr
|
||||||
a.FundingTimeMs = ft
|
a.FundingTimeMs = ft
|
||||||
mu.Unlock()
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
spotSymbols := binancex.Token2RelatedSpotSymbols(token)
|
||||||
defer wg.Done()
|
for _, spotSymbol := range spotSymbols {
|
||||||
if data.Market.IsSpotPair(spotSymbol) {
|
|
||||||
if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok {
|
if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok {
|
||||||
mu.Lock()
|
|
||||||
a.HasSpot = true
|
a.HasSpot = true
|
||||||
a.SpotPrice = sp
|
a.SpotPrice = sp
|
||||||
mu.Unlock()
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
|
||||||
wg.Wait()
|
marginRates := data.Market.GetMarginInterestRates()
|
||||||
|
a.MarginAPRPercent = marginRates[token] * 365 * 100
|
||||||
|
a.HasMarginAPR = marginRates[token] != 0
|
||||||
|
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
package commands
|
package commands
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBuildRichTokenMessageInput_AllSources(t *testing.T) {
|
func TestBuildRichTokenMessageInput_AllSources(t *testing.T) {
|
||||||
@@ -60,27 +60,9 @@ type marketStub struct {
|
|||||||
alphaTokens map[string]market.AlphaTokenInfo
|
alphaTokens map[string]market.AlphaTokenInfo
|
||||||
alphaPrices map[string]float64
|
alphaPrices map[string]float64
|
||||||
marginRates map[string]float64
|
marginRates map[string]float64
|
||||||
|
|
||||||
gate *sync.WaitGroup
|
|
||||||
ready chan struct{}
|
|
||||||
done chan struct{}
|
|
||||||
mu sync.Mutex
|
|
||||||
starts int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *marketStub) waitConcurrentGate() {
|
|
||||||
if m.gate == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
m.mu.Lock()
|
|
||||||
m.starts++
|
|
||||||
m.mu.Unlock()
|
|
||||||
m.gate.Done()
|
|
||||||
<-m.ready
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
|
func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
|
||||||
m.waitConcurrentGate()
|
|
||||||
v, ok := m.futurePrices[symbol]
|
v, ok := m.futurePrices[symbol]
|
||||||
if !ok {
|
if !ok {
|
||||||
return 0, 0, 0, false
|
return 0, 0, 0, false
|
||||||
@@ -90,7 +72,6 @@ func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, boo
|
|||||||
func (m *marketStub) GetAllPremiumIndex() (map[string]market.PremiumIndex, error) { return nil, nil }
|
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) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil }
|
||||||
func (m *marketStub) GetSpotPrice(symbol string) (float64, bool) {
|
func (m *marketStub) GetSpotPrice(symbol string) (float64, bool) {
|
||||||
m.waitConcurrentGate()
|
|
||||||
v, ok := m.spotPrices[symbol]
|
v, ok := m.spotPrices[symbol]
|
||||||
return v, ok
|
return v, ok
|
||||||
}
|
}
|
||||||
@@ -104,12 +85,29 @@ func (m *marketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool)
|
|||||||
return v, ok
|
return v, ok
|
||||||
}
|
}
|
||||||
func (m *marketStub) GetAlphaPrice(symbol string) (float64, bool) {
|
func (m *marketStub) GetAlphaPrice(symbol string) (float64, bool) {
|
||||||
m.waitConcurrentGate()
|
|
||||||
v, ok := m.alphaPrices[symbol]
|
v, ok := m.alphaPrices[symbol]
|
||||||
return v, ok
|
return v, ok
|
||||||
}
|
}
|
||||||
func (m *marketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] }
|
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) 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) {
|
func TestCollectRichTokenData_SpotOnlyReachable(t *testing.T) {
|
||||||
@@ -135,9 +133,15 @@ func TestCollectRichTokenData_FutureFailureStillKeepsSpot(t *testing.T) {
|
|||||||
defer func() { data.Market = orig }()
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
data.Market = &marketStub{
|
data.Market = &marketStub{
|
||||||
spotPairs: map[string]bool{"ETHUSDT": true},
|
spotPairs: map[string]bool{
|
||||||
futuresPairs: map[string]bool{"ETHUSDT": true},
|
"ETHUSDT": true,
|
||||||
spotPrices: map[string]float64{"ETHUSDT": 3245},
|
},
|
||||||
|
futuresPairs: map[string]bool{
|
||||||
|
"ETHUSDT": true,
|
||||||
|
},
|
||||||
|
spotPrices: map[string]float64{
|
||||||
|
"ETHUSDT": 3245,
|
||||||
|
},
|
||||||
futurePrices: map[string]struct {
|
futurePrices: map[string]struct {
|
||||||
price float64
|
price float64
|
||||||
rate float64
|
rate float64
|
||||||
@@ -154,6 +158,67 @@ func TestCollectRichTokenData_FutureFailureStillKeepsSpot(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_UsesSharedResolverMapping(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
data.Market = &marketStub{
|
||||||
|
spotPairs: map[string]bool{
|
||||||
|
"LUNAUSDT": true,
|
||||||
|
},
|
||||||
|
futuresPairs: map[string]bool{
|
||||||
|
"LUNA2USDT": true,
|
||||||
|
},
|
||||||
|
spotPrices: map[string]float64{
|
||||||
|
"LUNAUSDT": 0.49,
|
||||||
|
},
|
||||||
|
futurePrices: map[string]struct {
|
||||||
|
price float64
|
||||||
|
rate float64
|
||||||
|
time int64
|
||||||
|
}{
|
||||||
|
"LUNA2USDT": {price: 0.50, rate: 0.0001, time: 1740000000000},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
args := collectRichTokenData("LUNA2")
|
||||||
|
if !args.HasFuture || !args.HasSpot {
|
||||||
|
t.Fatalf("expected both future and mapped spot, got %+v", args)
|
||||||
|
}
|
||||||
|
if args.SpotPrice != 0.49 {
|
||||||
|
t.Fatalf("expected mapped spot price 0.49, got %f", args.SpotPrice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_PrefixFutureMapsToSpot(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
data.Market = &marketStub{
|
||||||
|
spotPairs: map[string]bool{
|
||||||
|
"PEPEUSDT": true,
|
||||||
|
},
|
||||||
|
futuresPairs: map[string]bool{
|
||||||
|
"1000PEPEUSDT": true,
|
||||||
|
},
|
||||||
|
spotPrices: map[string]float64{
|
||||||
|
"PEPEUSDT": 0.000012,
|
||||||
|
},
|
||||||
|
futurePrices: map[string]struct {
|
||||||
|
price float64
|
||||||
|
rate float64
|
||||||
|
time int64
|
||||||
|
}{
|
||||||
|
"1000PEPEUSDT": {price: 0.000013, rate: 0.0002, time: 1740000000000},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
args := collectRichTokenData("PEPE")
|
||||||
|
if !args.HasFuture || !args.HasSpot {
|
||||||
|
t.Fatalf("expected both future and mapped spot for prefixed contract, got %+v", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCollectRichTokenData_AlphaUsesSymbolPrice(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 }()
|
||||||
@@ -176,55 +241,3 @@ func TestCollectRichTokenData_AlphaUsesSymbolPrice(t *testing.T) {
|
|||||||
t.Fatalf("expected alpha price from symbol lookup, got %.4f", args.AlphaPrice)
|
t.Fatalf("expected alpha price from symbol lookup, got %.4f", args.AlphaPrice)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestCollectRichTokenData_RunsLookupsConcurrently(t *testing.T) {
|
|
||||||
orig := data.Market
|
|
||||||
defer func() { data.Market = orig }()
|
|
||||||
|
|
||||||
gate := &sync.WaitGroup{}
|
|
||||||
gate.Add(3)
|
|
||||||
st := &marketStub{
|
|
||||||
spotPairs: map[string]bool{"ABCUSDT": true},
|
|
||||||
futuresPairs: map[string]bool{"ABCUSDT": true},
|
|
||||||
spotPrices: map[string]float64{"ABCUSDT": 1.23},
|
|
||||||
futurePrices: map[string]struct {
|
|
||||||
price float64
|
|
||||||
rate float64
|
|
||||||
time int64
|
|
||||||
}{"ABCUSDT": {price: 1.24, rate: 0.0001, time: 1740000000000}},
|
|
||||||
alphaTokens: map[string]market.AlphaTokenInfo{
|
|
||||||
"ABC": {Symbol: "ABC", PercentChange24h: "2.5", Price: "1.22"},
|
|
||||||
},
|
|
||||||
alphaPrices: map[string]float64{"ABCUSDT": 1.22},
|
|
||||||
gate: gate,
|
|
||||||
ready: make(chan struct{}),
|
|
||||||
}
|
|
||||||
data.Market = st
|
|
||||||
|
|
||||||
finished := make(chan buildRichTokenMessageArgs, 1)
|
|
||||||
go func() {
|
|
||||||
finished <- collectRichTokenData("ABC")
|
|
||||||
}()
|
|
||||||
|
|
||||||
waitDone := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
gate.Wait()
|
|
||||||
close(waitDone)
|
|
||||||
}()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-waitDone:
|
|
||||||
close(st.ready)
|
|
||||||
case <-time.After(200 * time.Millisecond):
|
|
||||||
t.Fatalf("expected price lookups to run concurrently")
|
|
||||||
}
|
|
||||||
|
|
||||||
select {
|
|
||||||
case args := <-finished:
|
|
||||||
if !args.HasSpot || !args.HasFuture || !args.HasAlpha {
|
|
||||||
t.Fatalf("expected all lookups present: %+v", args)
|
|
||||||
}
|
|
||||||
case <-time.After(200 * time.Millisecond):
|
|
||||||
t.Fatalf("collectRichTokenData did not finish")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
go run cmd/tele/main.go ─╯
|
|
||||||
Reference in New Issue
Block a user