From 7ab2dbcc8d933b1cd6d47adecf36f6ab60e8e785 Mon Sep 17 00:00:00 2001 From: zcan <127599333+zcanic@users.noreply.github.com> Date: Wed, 5 Nov 2025 17:09:47 +0800 Subject: [PATCH] Fix/binance server time (#453) * Fix Binance futures server time sync * Fix Binance server time sync; clean up logging and restore decision sorting --------- Co-authored-by: tinkle-community --- trader/auto_trader.go | 6 ++++-- trader/binance_futures.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/trader/auto_trader.go b/trader/auto_trader.go index 172bcd4f..3934e85e 100644 --- a/trader/auto_trader.go +++ b/trader/auto_trader.go @@ -436,7 +436,7 @@ func (at *AutoTrader) runCycle() error { }) } - // 保存候选币种列表 + log.Print(strings.Repeat("=", 70)) for _, coin := range ctx.CandidateCoins { record.CandidateCoins = append(record.CandidateCoins, coin.Symbol) } @@ -465,7 +465,6 @@ func (at *AutoTrader) runCycle() error { // 打印系统提示词和AI思维链(即使有错误,也要输出以便调试) if decision != nil { - if decision.SystemPrompt != "" { log.Print("\n" + strings.Repeat("=", 70) + "\n") log.Printf("📋 系统提示词 [模板: %s] (错误情况)", at.systemPromptTemplate) log.Println(strings.Repeat("=", 70)) @@ -510,6 +509,9 @@ func (at *AutoTrader) runCycle() error { // } // } log.Println() + log.Print(strings.Repeat("-", 70)) + // 8. 对决策排序:确保先平仓后开仓(防止仓位叠加超限) + log.Print(strings.Repeat("-", 70)) // 8. 对决策排序:确保先平仓后开仓(防止仓位叠加超限) sortedDecisions := sortDecisionsByPriority(decision.Decisions) diff --git a/trader/binance_futures.go b/trader/binance_futures.go index 8df2ff60..df6c5b29 100644 --- a/trader/binance_futures.go +++ b/trader/binance_futures.go @@ -33,6 +33,8 @@ type FuturesTrader struct { // NewFuturesTrader 创建合约交易器 func NewFuturesTrader(apiKey, secretKey string) *FuturesTrader { client := futures.NewClient(apiKey, secretKey) + // 同步时间,避免 Timestamp ahead 错误 + syncBinanceServerTime(client) trader := &FuturesTrader{ client: client, cacheDuration: 15 * time.Second, // 15秒缓存 @@ -69,6 +71,20 @@ func (t *FuturesTrader) setDualSidePosition() error { return nil } +// syncBinanceServerTime 同步币安服务器时间,确保请求时间戳合法 +func syncBinanceServerTime(client *futures.Client) { + serverTime, err := client.NewServerTimeService().Do(context.Background()) + if err != nil { + log.Printf("⚠️ 同步币安服务器时间失败: %v", err) + return + } + + now := time.Now().UnixMilli() + offset := now - serverTime + client.TimeOffset = offset + log.Printf("⏱ 已同步币安服务器时间,偏移 %dms", offset) +} + // GetBalance 获取账户余额(带缓存) func (t *FuturesTrader) GetBalance() (map[string]interface{}, error) { // 先检查缓存是否有效