Commit Graph

6 Commits

Author SHA1 Message Date
ZhouYongyou
1b48c06362 fix(trader): restore TP/SL after partial_close to prevent unprotected positions
## Problem
- User reported: After partial_close, remaining position has NO TP/SL protection
- Root cause: Binance automatically cancels TP/SL orders when position size changes
- Impact: Remaining position exposed to unlimited risk (爆仓风险)

## Why TP/SL disappears
```
Opening:
  Position: 0.130 BTC
  TP order: 0.130 BTC ✓
  SL order: 0.130 BTC ✓

After 50% partial_close:
  Position: 0.065 BTC (remaining)
  TP order: 0.130 BTC  Quantity mismatch → Binance cancels
  SL order: 0.130 BTC  Quantity mismatch → Binance cancels
  → Remaining position has NO protection
```

## Solution

### Code changes (trader/auto_trader.go:1278-1305)

After partial_close execution, restore TP/SL with new quantity:

```go
// If AI provides new TP/SL prices
if decision.NewStopLoss > 0 || decision.NewTakeProfit > 0 {
    // Re-set SL with remaining quantity
    at.trader.SetStopLoss(symbol, side, remainingQuantity, newStopLoss)
    // Re-set TP with remaining quantity
    at.trader.SetTakeProfit(symbol, side, remainingQuantity, newTakeProfit)
} else {
    // WARNING: Remaining position has NO protection
    log.Printf("⚠️⚠️⚠️ 警告: 剩余仓位无止盈止损保护")
}
```

### Prompt updates

**Updated files**:
- prompts/adaptive.txt (line 171)
- prompts/default.txt (line 190)
- prompts/nof1.txt (line 334)

**Key change**: Emphasize AI MUST provide `new_stop_loss` and `new_take_profit` in `partial_close` decisions:

```markdown
- **partial_close**: Fill `close_percentage` (1-100),
  **STRONGLY RECOMMEND** providing `new_stop_loss` AND `new_take_profit`
  to protect remaining position (otherwise NO stop protection)
```

## Benefits

-  Risk control: Remaining position protected after partial_close
-  Clear warning: Logs explicit warning if AI doesn't provide new TP/SL
-  AI guidance: Updated prompts emphasize importance of new TP/SL
-  Backwards compatible: Works even if AI doesn't provide (just warns)

## Testing checklist

- [ ] Partial_close with new_stop_loss & new_take_profit → TP/SL restored
- [ ] Check Binance UI shows TP/SL orders after partial_close
- [ ] Partial_close without new TP/SL → Warning logged
- [ ] Remaining quantity matches TP/SL order quantity

Related: partial-close-tpsl-bug.md
2025-11-05 01:27:09 +08:00
ZhouYongyou
dcfc997b59 feat(prompts): add strict ASCII-only format guidelines to prevent fullwidth chars
🎯 Problem Prevention:
After analyzing the fullwidth character bug (2025-11-04 22:30), we discovered
that prompt changes can trigger AI to output fullwidth JSON characters.

 Solution: Explicit format constraints

Added "⚠️ 格式硬规范" sections to both prompts:

**adaptive.txt** (+23 lines):
- 仅输出 ASCII 字符(半角括号、英文标点)
- 禁止 Markdown 围栏(```json)
- 思维链格式规范(cooldown/trend/confidence/Key insight)
- 单一数组输出(避免嵌套)

**default.txt** (+20 lines):
- 仅输出 ASCII 字符(禁止全角标点)
- 禁止 Markdown 包裹
- 唯一思维链格式(THINK: ...)
- 严格数组格式

📊 Expected Impact:
- Reduce fullwidth character occurrence: 5-10% → <1%
- Clearer AI output format expectations
- Prevent future JSON parsing failures

🔗 Related:
- Bug timeline: /Users/sotadic/Documents/GitHub/fullwidth-bug-timeline-analysis.md
- Root cause: Prompt changes → increased Chinese context → fullwidth punctuation
2025-11-05 00:45:41 +08:00
ZhouYongyou
8bf6c2e1e2 fix: add JSON validation to prevent range values and thousand separators
修復 LLM 返回範圍值導致 JSON 解析失敗的問題

## 問題
LLM 有時返回價格範圍 [98,000 ~ 102,000] 而不是單一數值,
導致 JSON 解析失敗:invalid character '0' after array element

## 修復內容

### 1. Prompts 更新(3 個文件)
- prompts/default.txt: 添加數字格式要求(中文)
- prompts/adaptive.txt: 添加數字格式要求(中文)
- prompts/nof1.txt: 添加數字格式要求(英文)

明確禁止:
-  範圍符號 ~
-  千位分隔符 98,000
-  文字描述

### 2. JSON 驗證邏輯(decision/engine.go)
新增函數:
- validateJSONFormat(): 檢測範圍、千位分隔符等錯誤
- min(): 輔助函數

檢測內容:
1. 必須是對象數組 [{...}]
2. 不可包含範圍符號 ~
3. 不可包含千位分隔符 98,000

## 測試
✓ go build ./...  編譯成功
✓ go fmt ./...    格式正確

修改統計:+132 行(46 行代碼 + 86 行 prompts)
2025-11-04 21:18:27 +08:00
ZhouYongyou
df2d6533de fix: 修復5個關鍵交易bug(保證金計算、部分平倉統計、止損止盈分離、雙向持倉)
## 修復內容

### 1. 保證金計算錯誤(Critical)
- 修正提示詞中的保證金公式(adaptive.txt, nof1.txt, default.txt)
- 新增代碼級保證金驗證(auto_trader.go)
- 防止開倉時保證金不足錯誤(code=-2019)

### 2. 部分平倉統計錯誤(Medium)
- 修改統計邏輯:多次 partial_close 聚合為一筆交易
- 新增追蹤字段:remainingQuantity, accumulatedPnL
- 只在完全平倉時計入 TotalTrades++

### 3. 前端配置覆蓋問題(Medium)
- 修正 TraderConfigModal.tsx 條件判斷
- 防止空字符串覆蓋用戶選擇的提示詞

### 4/5. 動態止損/止盈刪除配對訂單(Critical)
- 新增接口:CancelStopLossOrders, CancelTakeProfitOrders
- 分離訂單取消邏輯(Binance, Hyperliquid, Aster)
- 調整止損時不刪除止盈,反之亦然

### 7. 雙向持倉模式初始化(Critical)
- 新增 setDualSidePosition() 函數
- 在 NewFuturesTrader() 中初始化 Hedge Mode
- 防止 code=-4061 錯誤(PositionSide 參數錯誤)

## 影響範圍
- 修改文件:10個
- 新增代碼:+480行
- 刪除代碼:-71行

## 測試狀態
-  編譯通過(go build ./...)
-  語法檢查通過
- ⚠️ 需要在測試環境運行驗證實際交易效果
2025-11-04 18:36:39 +08:00
ZhouYongyou
b3b68b2b62 refactor(prompts): unify action schema & optimize trading discipline
## Core Changes

### 1. adaptive.txt - Adopt v5.5.6.1 strict strategy
- Migrate from dual-strategy system to unified adaptive approach
- Maintain strict confidence threshold ≥85 (anti-overtrading)
- Remove complex market state detection, focus on signal quality
- Explicitly disable partial_close (full exit only)
- -160 lines (removed redundant strategy logic)

### 2. nof1.txt - Fix contradictions & align standards
-  Fix: Remove "NO partial exits" contradiction (now explicitly supported)
-  Unify: Change confidence threshold from 60 → 75
-  Unify: Change risk-reward ratio from 2:1 → 3:1
- Add confidence level guidance (75-85: good, 85-100: high)
- +85 lines (enhanced risk management framework)

### 3. default.txt - Add standardized output format
- Add structured thinking summary format
- Add comprehensive JSON schema documentation
- Add required fields rules for all action types
- +36 lines (improved contract clarity)

## Action Schema Migration

All prompts now use unified action naming:
-  open_long / open_short (was: buy_to_enter / sell_to_enter)
-  close_long / close_short (was: close)
-  update_stop_loss / update_take_profit (new)
-  partial_close (new, nof1 only)
-  hold / wait (unchanged)

## Confidence Scale Migration

-  Changed from 0-1 float to 0-100 integer across all prompts
-  Opening threshold: adaptive=85, nof1=75, default=75
-  Prevents overtrading through strict quality control

## Risk-Reward Standardization

-  Minimum RR ratio: 1:3 across all prompts
-  Replaces previous 1:2 requirement in nof1.txt

## Breaking Changes

- Backend must support new action names
- Confidence field now expects integer 0-100 (not float 0-1)
- partial_close action available in nof1.txt only

## Prompt Positioning

- **adaptive.txt**: Strict strategy (conf≥85, RR≥1:3, no partial exits)
- **nof1.txt**: English framework (conf≥75, RR≥1:3, supports partial_close)
- **default.txt**: Balanced CN strategy (conf≥75, RR≥1:3)

Related: feature/partial-close-dynamic-tpsl
2025-11-03 14:52:31 +08:00
SkywalkerJi
4250c11ddf Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00