mirror of
https://github.com/NoFxAiOS/nofx.git
synced 2026-07-06 12:30:59 +08:00
fix(trader): prevent division by zero in autoSyncBalanceIfNeeded
- 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 <noreply@anthropic.com>
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user