From c46f0be31590cdc422b713df05d07d6c70e58d74 Mon Sep 17 00:00:00 2001 From: ZhouYongyou <128128010+zhouyongyou@users.noreply.github.com> Date: Tue, 4 Nov 2025 21:07:55 +0800 Subject: [PATCH] fix(trader): prevent division by zero in autoSyncBalanceIfNeeded MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add check for oldBalance <= 0 before calculating changePercent - Directly update to actualBalance if initialBalance is invalid - Add warning logs for database nil scenarios - Prevent panic when initial_balance is 0 in database Applies same critical fix from feat/auto-balance-sync (3a5dea7) to z-dev branch with adapted database type handling. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- trader/auto_trader.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/trader/auto_trader.go b/trader/auto_trader.go index 4dcaf475..aa53aef4 100644 --- a/trader/auto_trader.go +++ b/trader/auto_trader.go @@ -336,6 +336,26 @@ func (at *AutoTrader) autoSyncBalanceIfNeeded() { } oldBalance := at.initialBalance + + // 防止除以零:如果初始余额无效,直接更新为实际余额 + if oldBalance <= 0 { + log.Printf("⚠️ [%s] 初始余额无效 (%.2f),直接更新为实际余额 %.2f USDT", at.name, oldBalance, actualBalance) + at.initialBalance = actualBalance + + if at.database != nil { + if err := at.database.UpdateTraderInitialBalance(at.userID, at.id, actualBalance); err != nil { + log.Printf("❌ [%s] 更新数据库失败: %v", at.name, err) + } else { + log.Printf("✅ [%s] 已自动同步余额到数据库", at.name) + } + } else { + log.Printf("⚠️ [%s] 数据库引用为空,余额仅在内存中更新", at.name) + } + + at.lastBalanceSyncTime = time.Now() + return + } + changePercent := ((actualBalance - oldBalance) / oldBalance) * 100 // 变化超过5%才更新 @@ -354,6 +374,8 @@ func (at *AutoTrader) autoSyncBalanceIfNeeded() { } else { log.Printf("✅ [%s] 已自动同步余额到数据库", at.name) } + } else { + log.Printf("⚠️ [%s] 数据库引用为空,余额仅在内存中更新", at.name) } } else { log.Printf("✓ [%s] 余额变化不大 (%.2f%%),无需更新", at.name, changePercent)