fix(trader): fix auto balance sync using totalEquity instead of availableBalance #905
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Pull Request - Backend | 后端 PR
📝 Description | 描述
English:
This PR fixes a critical bug in the auto balance sync mechanism that caused incorrect
initialBalanceupdates when traders had open positions.Problem:
availableBalanceto detect balance changesavailableBalancedecreases due to margin usageinitialBalanceto a lower valueExample Scenario:
initialBalance= 1000 USDT (total equity)totalEquity= 1100 USDT (correct account value)availableBalance= ~900 USDT (margin locked)changePercent= (900 - 1000) / 1000 = -10% ❌ (incorrectly detected as loss)initialBalancechanges from 1000 to 900 ❌Solution:
✅ Use
totalEquity = totalWalletBalance + totalUnrealizedProfit✅ Accurately reflects true account value, unaffected by open positions
✅ Keep
availableBalanceas fallback✅ Maintain 5% change threshold (reasonable)
✅ Enhanced logging: show wallet balance and unrealized P&L breakdown
中文:
本 PR 修复自动余额同步机制的严重 bug,该 bug 会在交易员有持仓时错误更新
initialBalance。问题:
availableBalance检测余额变化availableBalance会因保证金占用而减少initialBalance更新为更小的值示例场景:
initialBalance= 1000 USDT(总资产)totalEquity= 1100 USDT(正确的账户价值)availableBalance= ~900 USDT(保证金占用)changePercent= (900 - 1000) / 1000 = -10% ❌(误判为亏损)initialBalance从 1000 改成 900 ❌修复:
✅ 使用
totalEquity = totalWalletBalance + totalUnrealizedProfit✅ 准确反映账户真实价值,不受持仓影响
✅ 保留
availableBalance作为 fallback✅ 保持 5% 变化阈值(合理)
✅ 增强日志:显示钱包余额和未实现盈亏明细
🎯 Type of Change | 变更类型
🔗 Related Issues | 相关 Issue
Reported Bug:
if math.Abs(changePercent) > 5改成> 50000作为临时 workaroundRoot Cause:
availableBalance而不是totalEquityThis PR:
📋 Changes Made | 具体变更
1. Fix Balance Extraction Logic (trader/auto_trader.go:306-335)
Before (Incorrect):
After (Correct):
2. Enhanced Logging (trader/auto_trader.go:367-368, 395)
Before:
After:
3. Comprehensive Unit Tests (trader/auto_balance_sync_test.go)
Added 3 test suites with 33 test cases:
TestAutoBalanceSyncTotalEquityCalculation (11 cases):
TestAutoBalanceSyncChangeDetection (11 cases):
TestAutoBalanceSyncAvoidsFalsePositives (3 cases):
🧪 Testing | 测试
Test Environment | 测试环境
Manual Testing | 手动测试
Automated Testing | 自动化测试
go build ./trader)go test ./trader -v -run TestAutoBalanceSync)go fmt ./trader)Test Output:
📊 Impact Analysis | 影响分析
Affected Components | 影响范围
trader/auto_trader.go:autoSyncBalanceIfNeeded()Severity | 严重性
initialBalancecauses completely broken P&L calculationsRisk Assessment | 风险评估
availableBalanceiftotalEquityunavailable🎓 Technical Deep Dive | 技术深度分析
Why
availableBalanceis WrongWhen a trader has open positions:
availableBalance: Free margin available to open new positionstotalWalletBalance: Total deposited balance (excluding unrealized P&L)totalUnrealizedProfit: Unrealized P&L from open positionsTotal equity (true account value):
Example:
availableBalance: ~900 USDT (locked in margin)totalWalletBalance: 1000 USDT (deposit)totalUnrealizedProfit: +100 USDT (profit)totalEquity: 1100 USDT ← Correct account valueIf we use
availableBalance(900):If we use
totalEquity(1100):Why 5% Threshold is Reasonable
✅ Checklist | 检查清单
Code Quality | 代码质量
go build ./trader)Testing | 测试
go fmt)Documentation | 文档
Git
upstream/devbranch | 已基于最新upstream/dev分支💡 Why Not Change Threshold to 50000? | 为什么不改成 50000?
Someone suggested changing
if math.Abs(changePercent) > 5to> 50000as a workaround.Why this is wrong:
availableBalance)Our fix:
totalEquity)📚 Additional Notes | 补充说明
Relationship to Other PRs
This PR is independent and can be merged without conflicts:
This fix addresses the auto sync mechanism, while those PRs address initial balance creation.
Verification in Production
After merging, monitor logs for:
If you see large negative changes with positions open, it indicates the old bug. With this fix, changes should reflect true account value changes.
By submitting this PR, I confirm | 提交此 PR,我确认:
🌟 Thank you for reviewing! | 感谢审阅!
This PR fixes a critical bug that caused incorrect P&L calculations for all traders with open positions.