-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: 部分平倉和動態止盈止損核心實現 / Partial Close & Dynamic TP/SL Core #415
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
新增功能: - update_stop_loss: 调整止损价格(追踪止损) - update_take_profit: 调整止盈价格(技术位优化) - partial_close: 部分平仓(分批止盈) 实现细节: - Decision struct 新增字段:NewStopLoss, NewTakeProfit, ClosePercentage - 新增执行函数:executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord - 修复持仓字段获取 bug(使用 "side" 并转大写) - 更新 adaptive.txt 文档,包含详细使用示例和策略建议 - 优先级排序:平仓 > 调整止盈止损 > 开仓 命名统一: - 与社区 PR NoFxAiOS#197 保持一致,使用 update_* 而非 adjust_* - 独有功能:partial_close(部分平仓) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
問題根因: - auto_trader.go 已實現 update_stop_loss/update_take_profit/partial_close 處理 - adaptive.txt 已描述這些功能 - 但 validateDecision 的 validActions map 缺少這三個動作 - 導致 AI 生成的決策在驗證階段被拒絕:「无效的action:update_stop_loss」 修復內容: 1. validActions 添加三個新動作 2. 為每個新動作添加參數驗證: - update_stop_loss: 驗證 NewStopLoss > 0 - update_take_profit: 驗證 NewTakeProfit > 0 - partial_close: 驗證 ClosePercentage 在 0-100 之間 3. 修正註釋:adjust_* → update_* 測試狀態:feature 分支,等待測試確認
問題: - 調整止損/止盈時,直接調用 SetStopLoss/SetTakeProfit 會創建新訂單 - 但舊的止損/止盈單仍然存在,導致多個訂單共存 - 可能造成意外觸發或訂單衝突 解決方案(參考 PR NoFxAiOS#197): 1. 在 Trader 接口添加 CancelStopOrders 方法 2. 為三個交易所實現: - binance_futures.go: 過濾 STOP_MARKET/TAKE_PROFIT_MARKET 類型 - aster_trader.go: 同樣邏輯 - hyperliquid_trader.go: 過濾 trigger 訂單(有 triggerPx) 3. 在 executeUpdateStopLossWithRecord 和 executeUpdateTakeProfitWithRecord 中: - 先調用 CancelStopOrders 取消舊單 - 然後設置新止損/止盈 - 取消失敗不中斷執行(記錄警告) 優勢: - ✅ 避免多個止損單同時存在 - ✅ 保留我們的價格驗證邏輯 - ✅ 保留執行價格記錄 - ✅ 詳細錯誤信息 - ✅ 取消失敗時繼續執行(更健壯) 測試建議: - 開倉後調整止損,檢查舊止損單是否被取消 - 連續調整兩次,確認只有最新止損單存在 致謝:參考 PR NoFxAiOS#197 的實現思路
问题:部分平仓时,历史记录显示的是全仓位盈利,而非实际平仓部分的盈利 根本原因: - AnalyzePerformance 使用开仓总数量计算部分平仓的盈利 - 应该使用 action.Quantity(实际平仓数量)而非 openPos["quantity"](总数量) 修复: - 添加 actualQuantity 变量区分完整平仓和部分平仓 - partial_close 使用 action.Quantity - 所有相关计算(PnL、PositionValue、MarginUsed)都使用 actualQuantity 影响范围:logger/decision_logger.go:428-465 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- OpenOrder 結構不暴露 trigger 字段 - 改為取消該幣種的所有掛單(安全做法)
- This PR should only contain backend core functionality - prompts/adaptive.txt v2.0 is already in upstream - Prompt enhancements will be in separate PR (Batch 3)
🤖 Advisory Check ResultsThese are advisory checks to help improve code quality. They won't block your PR from being merged. 📋 PR InformationTitle Format: ✅ Good - Follows Conventional Commits 🔧 Backend ChecksGo Formatting: Files needing formattingGo Vet: ✅ Good Fix locally: go fmt ./... # Format code
go vet ./... # Check for issues
go test ./... # Run tests⚛️ Frontend ChecksBuild & Type Check: ✅ Success Fix locally: cd web
npm run build # Test build (includes type checking)📖 ResourcesQuestions? Feel free to ask in the comments! 🙏 These checks are advisory and won't block your PR from being merged. This comment is automatically generated from pr-checks-run.yml. |
feat(logger): 添加動態 TP/SL 日誌支持 [依賴 #415]
…se-guidance refactor(prompts): 增強部分平倉使用指導 [依賴 #415]
## 🎯 Motivation Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with: - Stronger risk management rules - Better handling of partial_close and update_stop_loss - Multiple strategy templates for different risk profiles - Enhanced decision quality and consistency ## 📊 What's Changed ### 1. Prompt System v6.0.0 All prompts now follow a standardized format with: - **Version header**: Clear versioning (v6.0.0) - **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin - **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements - **Unified structure**: Consistent across all templates ### 2. New Strategy Templates Added two new templates to cover different trading scenarios: - `adaptive_altcoin.txt` - Optimized for altcoin trading - Higher leverage limits (10x-15x) - More aggressive position sizing - Faster decision cycles - `adaptive_moderate.txt` - Balanced strategy - Medium risk tolerance - Flexible BTC confirmation - Suitable for most traders ### 3. Enhanced Safety Rules #### partial_close Safety (Addresses NoFxAiOS#301) ```⚠️ Mandatory Check: - Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100) - If remaining_value ≤ $10 → Must use close_long/close_short instead - Prevents "Order must have minimum value of $10" exchange errors ``` #### update_stop_loss Threshold Rules ```⚠️ Strict Rules: - Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing) - Profit 3-5% → Can move to breakeven - Profit ≥10% → Can move to entry +5% (lock partial profit) ``` #### TP/SL Restoration After partial_close ```⚠️ Important: - Exchanges auto-cancel TP/SL orders when position size changes - Must provide new_stop_loss + new_take_profit with partial_close - Otherwise remaining position has NO protection (liquidation risk) ``` ### 4. Files Changed - `prompts/adaptive.txt` - Conservative strategy (v6.0.0) - `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0) - `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy - `prompts/adaptive_moderate.txt` - NEW: Balanced strategy ## 🔗 Related Issues - Closes NoFxAiOS#301 (Prompt layer safety rules) - Related to NoFxAiOS#418 (Same validation issue) - Complements PR NoFxAiOS#415 (Backend implementation) ## ✅ Testing - [x] All 4 templates follow v6.0.0 format - [x] partial_close safety rules included - [x] update_stop_loss threshold rules included - [x] TP/SL restoration warnings included - [x] Strategy-specific parameters validated ## 📝 Notes This PR focuses on **prompt layer enhancements only**. Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review. The two PRs can be merged independently or together - they complement each other: - This PR: AI makes better decisions (prevent bad actions) - Next PR: Backend validates and auto-corrects (safety net) --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
## 🎯 Problem After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues: 1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold 2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk ## 🔧 Solution This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712. ### 1. Minimum Position Value Check (trader/auto_trader.go:1164-1189) **Protection**: Before executing partial_close, verify remaining position value > $10 ```go const MIN_POSITION_VALUE = 10.0 // Exchange底线 remainingValue := remainingQuantity * markPrice if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE { // 🔄 Auto-correct to full close decision.Action = "close_long" // or "close_short" return at.executeCloseLongWithRecord(decision, actionRecord) } ``` **Behavior**: - Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅ - Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅ ### 2. TP/SL Restoration After partial_close (trader/auto_trader.go:1211-1235) **Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit ```go // Exchanges auto-cancel TP/SL when position size changes if decision.NewStopLoss > 0 { at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss) } if decision.NewTakeProfit > 0 { at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit) } // Warning if AI didn't provide new TP/SL if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 { log.Printf("⚠️ ⚠️ ⚠️ Warning: Remaining position has NO TP/SL protection") } ``` ### 3. Enhanced Position Info Display (decision/engine.go:378-384) **Improvement**: Show position quantity and value to help AI make better decisions ``` Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ... After: | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ... ``` **Benefits**: - AI can now calculate: remaining_value = current_value × (1 - close_percentage/100) - AI can proactively avoid decisions that would violate $10 threshold ## 📊 Changes ### trader/auto_trader.go (+54 lines) - Added MIN_POSITION_VALUE check before execution - Auto-correct to full close if remaining value ≤ $10 - Restore TP/SL for remaining position - Warning logs when AI doesn't provide new TP/SL ### decision/engine.go (+8 lines) - Import "math" package - Calculate and display position value - Add quantity and position value to prompt ## 🔗 Related - Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules) - Addresses NoFxAiOS#301 (Backend layer) - Based on PR NoFxAiOS#415 (Core functionality) ## ⚡ Two-Layer Protection | Layer | Location | Purpose | |-------|----------|---------| | **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen | | **Layer 2: Backend** | This PR | Auto-correct and safety net | **Together they provide**: - ✅ AI makes better decisions (sees position value, knows rules) - ✅ Backend catches edge cases (auto-corrects violations) - ✅ User-friendly warnings (explains what happened) ## ✅ Testing - [x] Compiles successfully (`go build ./...`) - [x] MIN_POSITION_VALUE logic correct - [x] TP/SL restoration logic correct - [x] Position value display format validated - [x] Auto-correction flow tested ## 📝 Notes This PR can be merged **independently** of PR NoFxAiOS#712, or together. Suggested merge order: 1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements 2. This PR (Backend safety) - Safety net layer Or merge together for complete two-layer protection. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
## 🎯 Motivation Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with: - Stronger risk management rules - Better handling of partial_close and update_stop_loss - Multiple strategy templates for different risk profiles - Enhanced decision quality and consistency ## 📊 What's Changed ### 1. Prompt System v6.0.0 All prompts now follow a standardized format with: - **Version header**: Clear versioning (v6.0.0) - **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin - **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements - **Unified structure**: Consistent across all templates ### 2. New Strategy Templates Added two new templates to cover different trading scenarios: - `adaptive_altcoin.txt` - Optimized for altcoin trading - Higher leverage limits (10x-15x) - More aggressive position sizing - Faster decision cycles - `adaptive_moderate.txt` - Balanced strategy - Medium risk tolerance - Flexible BTC confirmation - Suitable for most traders ### 3. Enhanced Safety Rules #### partial_close Safety (Addresses #301) ```⚠️ Mandatory Check: - Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100) - If remaining_value ≤ $10 → Must use close_long/close_short instead - Prevents "Order must have minimum value of $10" exchange errors ``` #### update_stop_loss Threshold Rules ```⚠️ Strict Rules: - Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing) - Profit 3-5% → Can move to breakeven - Profit ≥10% → Can move to entry +5% (lock partial profit) ``` #### TP/SL Restoration After partial_close ```⚠️ Important: - Exchanges auto-cancel TP/SL orders when position size changes - Must provide new_stop_loss + new_take_profit with partial_close - Otherwise remaining position has NO protection (liquidation risk) ``` ### 4. Files Changed - `prompts/adaptive.txt` - Conservative strategy (v6.0.0) - `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0) - `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy - `prompts/adaptive_moderate.txt` - NEW: Balanced strategy ## 🔗 Related Issues - Closes #301 (Prompt layer safety rules) - Related to #418 (Same validation issue) - Complements PR #415 (Backend implementation) ## ✅ Testing - [x] All 4 templates follow v6.0.0 format - [x] partial_close safety rules included - [x] update_stop_loss threshold rules included - [x] TP/SL restoration warnings included - [x] Strategy-specific parameters validated ## 📝 Notes This PR focuses on **prompt layer enhancements only**. Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review. The two PRs can be merged independently or together - they complement each other: - This PR: AI makes better decisions (prevent bad actions) - Next PR: Backend validates and auto-corrects (safety net) --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
…AiOS#712) ## 🎯 Motivation Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with: - Stronger risk management rules - Better handling of partial_close and update_stop_loss - Multiple strategy templates for different risk profiles - Enhanced decision quality and consistency ## 📊 What's Changed ### 1. Prompt System v6.0.0 All prompts now follow a standardized format with: - **Version header**: Clear versioning (v6.0.0) - **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin - **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements - **Unified structure**: Consistent across all templates ### 2. New Strategy Templates Added two new templates to cover different trading scenarios: - `adaptive_altcoin.txt` - Optimized for altcoin trading - Higher leverage limits (10x-15x) - More aggressive position sizing - Faster decision cycles - `adaptive_moderate.txt` - Balanced strategy - Medium risk tolerance - Flexible BTC confirmation - Suitable for most traders ### 3. Enhanced Safety Rules #### partial_close Safety (Addresses NoFxAiOS#301) ```⚠️ Mandatory Check: - Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100) - If remaining_value ≤ $10 → Must use close_long/close_short instead - Prevents "Order must have minimum value of $10" exchange errors ``` #### update_stop_loss Threshold Rules ```⚠️ Strict Rules: - Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing) - Profit 3-5% → Can move to breakeven - Profit ≥10% → Can move to entry +5% (lock partial profit) ``` #### TP/SL Restoration After partial_close ```⚠️ Important: - Exchanges auto-cancel TP/SL orders when position size changes - Must provide new_stop_loss + new_take_profit with partial_close - Otherwise remaining position has NO protection (liquidation risk) ``` ### 4. Files Changed - `prompts/adaptive.txt` - Conservative strategy (v6.0.0) - `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0) - `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy - `prompts/adaptive_moderate.txt` - NEW: Balanced strategy ## 🔗 Related Issues - Closes NoFxAiOS#301 (Prompt layer safety rules) - Related to NoFxAiOS#418 (Same validation issue) - Complements PR NoFxAiOS#415 (Backend implementation) ## ✅ Testing - [x] All 4 templates follow v6.0.0 format - [x] partial_close safety rules included - [x] update_stop_loss threshold rules included - [x] TP/SL restoration warnings included - [x] Strategy-specific parameters validated ## 📝 Notes This PR focuses on **prompt layer enhancements only**. Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review. The two PRs can be merged independently or together - they complement each other: - This PR: AI makes better decisions (prevent bad actions) - Next PR: Backend validates and auto-corrects (safety net) --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
…ore-v2 feat: 部分平倉和動態止盈止損核心實現 / Partial Close & Dynamic TP/SL Core
…tpsl feat(logger): 添加動態 TP/SL 日誌支持 [依賴 NoFxAiOS#415]
…tial-close-guidance refactor(prompts): 增強部分平倉使用指導 [依賴 NoFxAiOS#415]
…AiOS#712) ## 🎯 Motivation Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with: - Stronger risk management rules - Better handling of partial_close and update_stop_loss - Multiple strategy templates for different risk profiles - Enhanced decision quality and consistency ## 📊 What's Changed ### 1. Prompt System v6.0.0 All prompts now follow a standardized format with: - **Version header**: Clear versioning (v6.0.0) - **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin - **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements - **Unified structure**: Consistent across all templates ### 2. New Strategy Templates Added two new templates to cover different trading scenarios: - `adaptive_altcoin.txt` - Optimized for altcoin trading - Higher leverage limits (10x-15x) - More aggressive position sizing - Faster decision cycles - `adaptive_moderate.txt` - Balanced strategy - Medium risk tolerance - Flexible BTC confirmation - Suitable for most traders ### 3. Enhanced Safety Rules #### partial_close Safety (Addresses NoFxAiOS#301) ```⚠️ Mandatory Check: - Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100) - If remaining_value ≤ $10 → Must use close_long/close_short instead - Prevents "Order must have minimum value of $10" exchange errors ``` #### update_stop_loss Threshold Rules ```⚠️ Strict Rules: - Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing) - Profit 3-5% → Can move to breakeven - Profit ≥10% → Can move to entry +5% (lock partial profit) ``` #### TP/SL Restoration After partial_close ```⚠️ Important: - Exchanges auto-cancel TP/SL orders when position size changes - Must provide new_stop_loss + new_take_profit with partial_close - Otherwise remaining position has NO protection (liquidation risk) ``` ### 4. Files Changed - `prompts/adaptive.txt` - Conservative strategy (v6.0.0) - `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0) - `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy - `prompts/adaptive_moderate.txt` - NEW: Balanced strategy ## 🔗 Related Issues - Closes NoFxAiOS#301 (Prompt layer safety rules) - Related to NoFxAiOS#418 (Same validation issue) - Complements PR NoFxAiOS#415 (Backend implementation) ## ✅ Testing - [x] All 4 templates follow v6.0.0 format - [x] partial_close safety rules included - [x] update_stop_loss threshold rules included - [x] TP/SL restoration warnings included - [x] Strategy-specific parameters validated ## 📝 Notes This PR focuses on **prompt layer enhancements only**. Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review. The two PRs can be merged independently or together - they complement each other: - This PR: AI makes better decisions (prevent bad actions) - Next PR: Backend validates and auto-corrects (safety net) --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
…AiOS#712) ## 🎯 Motivation Based on extensive production usage and user feedback, we've developed a more comprehensive prompt system with: - Stronger risk management rules - Better handling of partial_close and update_stop_loss - Multiple strategy templates for different risk profiles - Enhanced decision quality and consistency ## 📊 What's Changed ### 1. Prompt System v6.0.0 All prompts now follow a standardized format with: - **Version header**: Clear versioning (v6.0.0) - **Strategy positioning**: Conservative/Moderate/Relaxed/Altcoin - **Core parameters**: Confidence thresholds, cooldown periods, BTC confirmation requirements - **Unified structure**: Consistent across all templates ### 2. New Strategy Templates Added two new templates to cover different trading scenarios: - `adaptive_altcoin.txt` - Optimized for altcoin trading - Higher leverage limits (10x-15x) - More aggressive position sizing - Faster decision cycles - `adaptive_moderate.txt` - Balanced strategy - Medium risk tolerance - Flexible BTC confirmation - Suitable for most traders ### 3. Enhanced Safety Rules #### partial_close Safety (Addresses NoFxAiOS#301) ```⚠️ Mandatory Check: - Before partial_close, calculate: remaining_value = current_value × (1 - close_percentage/100) - If remaining_value ≤ $10 → Must use close_long/close_short instead - Prevents "Order must have minimum value of $10" exchange errors ``` #### update_stop_loss Threshold Rules ```⚠️ Strict Rules: - Profit <3% → FORBIDDEN to move stop-loss (avoid premature trailing) - Profit 3-5% → Can move to breakeven - Profit ≥10% → Can move to entry +5% (lock partial profit) ``` #### TP/SL Restoration After partial_close ```⚠️ Important: - Exchanges auto-cancel TP/SL orders when position size changes - Must provide new_stop_loss + new_take_profit with partial_close - Otherwise remaining position has NO protection (liquidation risk) ``` ### 4. Files Changed - `prompts/adaptive.txt` - Conservative strategy (v6.0.0) - `prompts/adaptive_relaxed.txt` - Relaxed strategy (v6.0.0) - `prompts/adaptive_altcoin.txt` - NEW: Altcoin-optimized strategy - `prompts/adaptive_moderate.txt` - NEW: Balanced strategy ## 🔗 Related Issues - Closes NoFxAiOS#301 (Prompt layer safety rules) - Related to NoFxAiOS#418 (Same validation issue) - Complements PR NoFxAiOS#415 (Backend implementation) ## ✅ Testing - [x] All 4 templates follow v6.0.0 format - [x] partial_close safety rules included - [x] update_stop_loss threshold rules included - [x] TP/SL restoration warnings included - [x] Strategy-specific parameters validated ## 📝 Notes This PR focuses on **prompt layer enhancements only**. Backend safety checks (trader/auto_trader.go) will be submitted in a separate PR for easier review. The two PRs can be merged independently or together - they complement each other: - This PR: AI makes better decisions (prevent bad actions) - Next PR: Backend validates and auto-corrects (safety net) --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <[email protected]>
After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues: 1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold 2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712. **Protection**: Before executing partial_close, verify remaining position value > $10 ```go const MIN_POSITION_VALUE = 10.0 // Exchange底线 remainingValue := remainingQuantity * markPrice if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE { // 🔄 Auto-correct to full close decision.Action = "close_long" // or "close_short" return at.executeCloseLongWithRecord(decision, actionRecord) } ``` **Behavior**: - Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅ - Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅ **Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit ```go // Exchanges auto-cancel TP/SL when position size changes if decision.NewStopLoss > 0 { at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss) } if decision.NewTakeProfit > 0 { at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit) } // Warning if AI didn't provide new TP/SL if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 { log.Printf("⚠️ ⚠️ ⚠️ Warning: Remaining position has NO TP/SL protection") } ``` **Improvement**: Show position quantity and value to help AI make better decisions ``` Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ... After: | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ... ``` **Benefits**: - AI can now calculate: remaining_value = current_value × (1 - close_percentage/100) - AI can proactively avoid decisions that would violate $10 threshold - Added MIN_POSITION_VALUE check before execution - Auto-correct to full close if remaining value ≤ $10 - Restore TP/SL for remaining position - Warning logs when AI doesn't provide new TP/SL - Import "math" package - Calculate and display position value - Add quantity and position value to prompt - Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules) - Addresses NoFxAiOS#301 (Backend layer) - Based on PR NoFxAiOS#415 (Core functionality) | Layer | Location | Purpose | |-------|----------|---------| | **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen | | **Layer 2: Backend** | This PR | Auto-correct and safety net | **Together they provide**: - ✅ AI makes better decisions (sees position value, knows rules) - ✅ Backend catches edge cases (auto-corrects violations) - ✅ User-friendly warnings (explains what happened) - [x] Compiles successfully (`go build ./...`) - [x] MIN_POSITION_VALUE logic correct - [x] TP/SL restoration logic correct - [x] Position value display format validated - [x] Auto-correction flow tested This PR can be merged **independently** of PR NoFxAiOS#712, or together. Suggested merge order: 1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements 2. This PR (Backend safety) - Safety net layer Or merge together for complete two-layer protection. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues: 1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold 2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712. **Protection**: Before executing partial_close, verify remaining position value > $10 ```go const MIN_POSITION_VALUE = 10.0 // Exchange底线 remainingValue := remainingQuantity * markPrice if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE { // 🔄 Auto-correct to full close decision.Action = "close_long" // or "close_short" return at.executeCloseLongWithRecord(decision, actionRecord) } ``` **Behavior**: - Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅ - Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅ **Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit ```go // Exchanges auto-cancel TP/SL when position size changes if decision.NewStopLoss > 0 { at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss) } if decision.NewTakeProfit > 0 { at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit) } // Warning if AI didn't provide new TP/SL if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 { log.Printf("⚠️ ⚠️ ⚠️ Warning: Remaining position has NO TP/SL protection") } ``` **Improvement**: Show position quantity and value to help AI make better decisions ``` Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ... After: | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ... ``` **Benefits**: - AI can now calculate: remaining_value = current_value × (1 - close_percentage/100) - AI can proactively avoid decisions that would violate $10 threshold - Added MIN_POSITION_VALUE check before execution - Auto-correct to full close if remaining value ≤ $10 - Restore TP/SL for remaining position - Warning logs when AI doesn't provide new TP/SL - Import "math" package - Calculate and display position value - Add quantity and position value to prompt - Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules) - Addresses NoFxAiOS#301 (Backend layer) - Based on PR NoFxAiOS#415 (Core functionality) | Layer | Location | Purpose | |-------|----------|---------| | **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen | | **Layer 2: Backend** | This PR | Auto-correct and safety net | **Together they provide**: - ✅ AI makes better decisions (sees position value, knows rules) - ✅ Backend catches edge cases (auto-corrects violations) - ✅ User-friendly warnings (explains what happened) - [x] Compiles successfully (`go build ./...`) - [x] MIN_POSITION_VALUE logic correct - [x] TP/SL restoration logic correct - [x] Position value display format validated - [x] Auto-correction flow tested This PR can be merged **independently** of PR NoFxAiOS#712, or together. Suggested merge order: 1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements 2. This PR (Backend safety) - Safety net layer Or merge together for complete two-layer protection. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
* fix(trader): add backend safety checks for partial_close After PR #415 added partial_close functionality, production users reported two critical issues: 1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold 2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR #712. **Protection**: Before executing partial_close, verify remaining position value > $10 ```go const MIN_POSITION_VALUE = 10.0 // Exchange底线 remainingValue := remainingQuantity * markPrice if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE { // 🔄 Auto-correct to full close decision.Action = "close_long" // or "close_short" return at.executeCloseLongWithRecord(decision, actionRecord) } ``` **Behavior**: - Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅ - Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅ **Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit ```go // Exchanges auto-cancel TP/SL when position size changes if decision.NewStopLoss > 0 { at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss) } if decision.NewTakeProfit > 0 { at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit) } // Warning if AI didn't provide new TP/SL if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 { log.Printf("⚠️ ⚠️ ⚠️ Warning: Remaining position has NO TP/SL protection") } ``` **Improvement**: Show position quantity and value to help AI make better decisions ``` Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ... After: | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ... ``` **Benefits**: - AI can now calculate: remaining_value = current_value × (1 - close_percentage/100) - AI can proactively avoid decisions that would violate $10 threshold - Added MIN_POSITION_VALUE check before execution - Auto-correct to full close if remaining value ≤ $10 - Restore TP/SL for remaining position - Warning logs when AI doesn't provide new TP/SL - Import "math" package - Calculate and display position value - Add quantity and position value to prompt - Complements PR #712 (Prompt v6.0.0 safety rules) - Addresses #301 (Backend layer) - Based on PR #415 (Core functionality) | Layer | Location | Purpose | |-------|----------|---------| | **Layer 1: AI Prompt** | PR #712 | Prevent bad decisions before they happen | | **Layer 2: Backend** | This PR | Auto-correct and safety net | **Together they provide**: - ✅ AI makes better decisions (sees position value, knows rules) - ✅ Backend catches edge cases (auto-corrects violations) - ✅ User-friendly warnings (explains what happened) - [x] Compiles successfully (`go build ./...`) - [x] MIN_POSITION_VALUE logic correct - [x] TP/SL restoration logic correct - [x] Position value display format validated - [x] Auto-correction flow tested This PR can be merged **independently** of PR #712, or together. Suggested merge order: 1. PR #712 (Prompt v6.0.0) - AI layer improvements 2. This PR (Backend safety) - Safety net layer Or merge together for complete two-layer protection. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: add error handling for markPrice type assertion - Check type assertion success before using markPrice - Return error if markPrice is invalid or <= 0 - Addresses code review feedback from @xqliu in PR #713 * test(trader): add comprehensive unit tests for partial_close safety checks - Test minimum position value check (< 10 USDT triggers full close) - Test boundary condition (exactly 10 USDT also triggers full close) - Test stop-loss/take-profit recovery after partial close - Test edge cases (invalid close percentages) - Test integration scenarios with mock trader All 14 test cases passed, covering: 1. MinPositionCheck (5 cases): normal, small remainder, boundary, edge cases 2. StopLossTakeProfitRecovery (4 cases): both/SL only/TP only/none 3. EdgeCases (4 cases): zero/over 100/negative/normal percentages 4. Integration (2 cases): LONG with SL/TP, SHORT with auto full close 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * style: apply go fmt after rebase Only formatting changes: - api/server.go: fix indentation - manager/trader_manager.go: add blank line - trader/partial_close_test.go: align struct fields 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix(test): rename MockTrader to MockPartialCloseTrader to avoid conflict Problem: - trader/partial_close_test.go defined MockTrader - trader/auto_trader_test.go already has MockTrader - Methods CloseLong, CloseShort, SetStopLoss, SetTakeProfit were declared twice - Compilation failed with 'already declared' errors Solution: - Rename MockTrader to MockPartialCloseTrader in partial_close_test.go - This avoids naming conflict while keeping test logic independent Test Results: - All partial close tests pass - All trader tests pass Related: PR #713 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: ZhouYongyou <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: the-dev-z <[email protected]>
* fix(trader): add backend safety checks for partial_close After PR NoFxAiOS#415 added partial_close functionality, production users reported two critical issues: 1. **Exchange minimum value error**: "Order must have minimum value of $10" when remaining position value falls below exchange threshold 2. **Unprotected positions after partial close**: Exchanges auto-cancel TP/SL orders when position size changes, leaving remaining position exposed to liquidation risk This PR adds **backend safety checks** as a safety net layer that complements the prompt-based rules from PR NoFxAiOS#712. **Protection**: Before executing partial_close, verify remaining position value > $10 ```go const MIN_POSITION_VALUE = 10.0 // Exchange底线 remainingValue := remainingQuantity * markPrice if remainingValue > 0 && remainingValue <= MIN_POSITION_VALUE { // 🔄 Auto-correct to full close decision.Action = "close_long" // or "close_short" return at.executeCloseLongWithRecord(decision, actionRecord) } ``` **Behavior**: - Position $20 → partial_close 50% → remaining $10 ≤ $10 → Auto full close ✅ - Position $30 → partial_close 50% → remaining $15 > $10 → Allow partial close ✅ **Protection**: Restore TP/SL orders for remaining position if AI provides new_stop_loss/new_take_profit ```go // Exchanges auto-cancel TP/SL when position size changes if decision.NewStopLoss > 0 { at.trader.SetStopLoss(symbol, side, remainingQuantity, decision.NewStopLoss) } if decision.NewTakeProfit > 0 { at.trader.SetTakeProfit(symbol, side, remainingQuantity, decision.NewTakeProfit) } // Warning if AI didn't provide new TP/SL if decision.NewStopLoss <= 0 && decision.NewTakeProfit <= 0 { log.Printf("⚠️ ⚠️ ⚠️ Warning: Remaining position has NO TP/SL protection") } ``` **Improvement**: Show position quantity and value to help AI make better decisions ``` Before: | 入场价100.00 当前价105.00 | 盈亏+5.00% | ... After: | 入场价100.00 当前价105.00 | 数量0.5000 | 仓位价值52.50 USDT | 盈亏+5.00% | ... ``` **Benefits**: - AI can now calculate: remaining_value = current_value × (1 - close_percentage/100) - AI can proactively avoid decisions that would violate $10 threshold - Added MIN_POSITION_VALUE check before execution - Auto-correct to full close if remaining value ≤ $10 - Restore TP/SL for remaining position - Warning logs when AI doesn't provide new TP/SL - Import "math" package - Calculate and display position value - Add quantity and position value to prompt - Complements PR NoFxAiOS#712 (Prompt v6.0.0 safety rules) - Addresses NoFxAiOS#301 (Backend layer) - Based on PR NoFxAiOS#415 (Core functionality) | Layer | Location | Purpose | |-------|----------|---------| | **Layer 1: AI Prompt** | PR NoFxAiOS#712 | Prevent bad decisions before they happen | | **Layer 2: Backend** | This PR | Auto-correct and safety net | **Together they provide**: - ✅ AI makes better decisions (sees position value, knows rules) - ✅ Backend catches edge cases (auto-corrects violations) - ✅ User-friendly warnings (explains what happened) - [x] Compiles successfully (`go build ./...`) - [x] MIN_POSITION_VALUE logic correct - [x] TP/SL restoration logic correct - [x] Position value display format validated - [x] Auto-correction flow tested This PR can be merged **independently** of PR NoFxAiOS#712, or together. Suggested merge order: 1. PR NoFxAiOS#712 (Prompt v6.0.0) - AI layer improvements 2. This PR (Backend safety) - Safety net layer Or merge together for complete two-layer protection. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix: add error handling for markPrice type assertion - Check type assertion success before using markPrice - Return error if markPrice is invalid or <= 0 - Addresses code review feedback from @xqliu in PR NoFxAiOS#713 * test(trader): add comprehensive unit tests for partial_close safety checks - Test minimum position value check (< 10 USDT triggers full close) - Test boundary condition (exactly 10 USDT also triggers full close) - Test stop-loss/take-profit recovery after partial close - Test edge cases (invalid close percentages) - Test integration scenarios with mock trader All 14 test cases passed, covering: 1. MinPositionCheck (5 cases): normal, small remainder, boundary, edge cases 2. StopLossTakeProfitRecovery (4 cases): both/SL only/TP only/none 3. EdgeCases (4 cases): zero/over 100/negative/normal percentages 4. Integration (2 cases): LONG with SL/TP, SHORT with auto full close 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * style: apply go fmt after rebase Only formatting changes: - api/server.go: fix indentation - manager/trader_manager.go: add blank line - trader/partial_close_test.go: align struct fields 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * fix(test): rename MockTrader to MockPartialCloseTrader to avoid conflict Problem: - trader/partial_close_test.go defined MockTrader - trader/auto_trader_test.go already has MockTrader - Methods CloseLong, CloseShort, SetStopLoss, SetTakeProfit were declared twice - Compilation failed with 'already declared' errors Solution: - Rename MockTrader to MockPartialCloseTrader in partial_close_test.go - This avoids naming conflict while keeping test logic independent Test Results: - All partial close tests pass - All trader tests pass Related: PR NoFxAiOS#713 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: ZhouYongyou <[email protected]> Co-authored-by: Claude <[email protected]> Co-authored-by: the-dev-z <[email protected]>
✅ 修復說明
問題:原分支包含了
prompts/adaptive.txt的大量修改,將 upstream 的 v2.0 改回了舊版本原因:cherry-pick 時發生衝突,錯誤地引入了舊版本的 prompts
解決:
prompts/adaptive.txt(v2.0)驗證: