Commit Graph

17 Commits

Author SHA1 Message Date
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
db7b24e2e0 style: apply go fmt to fix indentation and alignment
Fix formatting issues across multiple files:
- logger/decision_logger.go: correct if statement indentation
- main.go: fix DataKLineTime field tab alignment
- trader/auto_trader.go: align struct field comments and code blocks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 10:44:15 +08:00
ZhouYongyou
527dcd6fc2 feat: Add position snapshot to track auto-closed positions (PR #231)
- Add position_snapshots table to track all closed positions
- Record both manual and auto-closed positions
- Fix data integrity issue where auto-closed positions were not recorded
- Improve trade history tracking and analysis
- Merge with existing partial_close functionality
2025-11-03 22:15:12 +08:00
ZhouYongyou
366ae87077 style: format Go code with go fmt
- Fix formatting issues flagged by PR advisory checks
- Run go fmt ./... on all Go files
- No functional changes, code style improvements only

Files formatted:
- api/server.go
- auth/auth.go
- decision/engine.go
- logger/decision_logger.go
- manager/trader_manager.go
- market/monitor.go
- market/types.go
- mcp/client.go
- trader/*.go (aster, auto, binance, hyperliquid)
2025-11-03 19:35:41 +08:00
ZhouYongyou
fed3ce95f3 fix: 修复部分平仓盈利计算错误
问题:部分平仓时,历史记录显示的是全仓位盈利,而非实际平仓部分的盈利

根本原因:
- 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 <noreply@anthropic.com>
2025-11-02 21:26:58 +08:00
Xeron
5c9b396e5a fix: detect and record stop-loss/take-profit auto-close trades
Fixes #200

Previously, positions closed via stop-loss or take-profit were not
recorded in decision logs, causing inaccurate performance metrics
(win rate, profit factor, etc.) displayed in the frontend.

This commit implements a position snapshot mechanism to detect
auto-closed positions by comparing positions between trading cycles.

Changes:
- Add PositionSnapshot struct to track position state
- Add detectAutoClosedPositions() to detect disappeared positions
- Update position snapshots at cycle end (after AI execution)
- Support auto_close_long/auto_close_short action types in logger
- Ensure accurate performance analysis including auto-closed trades

Key fix:
- Snapshots are updated AFTER AI execution to avoid false positives
- AI manual closes won't be mistakenly detected as auto-closes
2025-11-02 12:35:37 +08:00
ZhouYongyou
ed8bb94dea 更新 logger:支持新增的三個動作類型
更新內容:
1. DecisionAction 註釋:添加 update_stop_loss, update_take_profit, partial_close
2. GetStatistics:partial_close 計入 TotalClosePositions
3. AnalyzePerformance 預填充邏輯:處理 partial_close(不刪除持倉記錄)
4. AnalyzePerformance 分析邏輯:
   - partial_close 正確判斷持倉方向
   - 記錄部分平倉的盈虧統計
   - 保留持倉記錄(因為還有剩餘倉位)

說明:partial_close 會記錄盈虧,但不刪除 openPositions,
      因為還有剩餘倉位可能繼續交易
2025-11-02 06:11:12 +08:00
SkywalkerJi
4250c11ddf Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
tinkle
0c0056f4e8 Feature: Add position details to Trade History
Add missing fields to TradeOutcome:
- Quantity: Position size
- Leverage: Leverage multiplier
- PositionValue: Total position value (quantity × openPrice)
- MarginUsed: Margin required (positionValue / leverage)

This provides complete trade information for analysis and display.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 18:09:16 +08:00
tinkle
9139407739 Fix: Resolve Trade History data loss and P&L calculation errors
Major fixes:
1. Trade History data loss issue
   - Root cause: Open records outside analysis window caused close matching failures
   - Solution: Pre-populate position state by reading 3x window of historical records
   - Ensures long-term positions (>5 hours) generate correct trade records

2. P&L calculation errors
   - Remove incorrect leverage multiplication from absolute P&L
   - Correct calculation: Futures P&L = quantity × price difference
   - Leverage only affects P&L percentage (relative to margin)

3. Other fixes
   - Break-even trades (pnl=0) no longer misclassified as losses
   - Perfect strategy shows Profit Factor as 999.0 instead of 0.0
   - Expand analysis window from 20 to 100 cycles (5 hours)

Files changed:
- logger/decision_logger.go: Core matching and calculation logic
- api/server.go: API analysis window
- trader/auto_trader.go: AI decision analysis window

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 17:58:25 +08:00
tinkle
1d356be402 Fix: Correct Sharpe Ratio calculation by using proper equity values
Critical bug fix in Sharpe Ratio calculation logic:

Problem:
- Previously calculated equity as TotalBalance + TotalUnrealizedProfit
- This was incorrect because TotalBalance already stores TotalEquity
- TotalUnrealizedProfit actually stores TotalPnL (not unrealized profit)
- This caused: equity = 2 * TotalEquity - InitialBalance (wrong!)

Root cause:
- Field naming mismatch between AccountSnapshot and actual stored values
- TotalBalance field actually contains TotalEquity (wallet + unrealized)
- TotalUnrealizedProfit field actually contains TotalPnL (equity - initial)

Solution:
- Use TotalBalance directly as it already represents complete account equity
- Added clear comments explaining the field name vs content mismatch
- Sharpe Ratio now correctly calculates risk-adjusted returns

Impact:
- Sharpe Ratio values are now mathematically accurate
- AI performance assessment is now reliable
- No changes needed to data storage or API layer

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 18:08:36 +08:00
tinkle
a0ce1e20a9 Fix: Correct Profit Factor calculation and display units in AI Learning
Backend changes (logger/decision_logger.go):
- Fixed Profit Factor to use standard formula (total profit / total loss)
- Previously used average values which was incorrect when win/loss counts differ
- Now saves total amounts before calculating averages for accurate ratio

Frontend changes (web/src/components/AILearning.tsx):
- Fixed display units: changed USDT amounts from "%" to "USDT"
- Updated avg_win and avg_loss to show "USDT Average" instead of "%"
- Updated best/worst performer displays to show "USDT" instead of "%"
- Added "(USDT)" labels to table headers for clarity
- Removed "%" from all table data cells showing monetary amounts

This ensures accurate performance metrics and eliminates user confusion
between percentage values and absolute USDT amounts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 17:59:19 +08:00
tinkle
a3f896d3b3 Fix: Correct PnL calculation in trade history analysis
Fixed critical issues in historical trade record and performance analysis:

1. PnL Calculation: Changed from percentage-only to actual USDT amount
   - Now correctly calculates: positionValue × priceChange% × leverage
   - Previously: 100U@5% and 1000U@5% both showed 5.0
   - Now: Properly reflects different position sizes and leverage

2. Position Tracking: Added quantity and leverage to open position records
   - Store complete trade data for accurate PnL calculation
   - Previously only stored: side, openPrice, openTime
   - Now includes: quantity, leverage for proper accounting

3. Position Key: Fixed to distinguish long/short positions
   - Changed from symbol to symbol_side (e.g., BTCUSDT_long)
   - Prevents conflicts when holding both long and short positions

4. Sharpe Ratio: Replaced custom Newton's method with math.Sqrt
   - Simplified standard deviation calculation
   - More reliable and maintainable

Impact: Win rate, profit factor, and Sharpe ratio now based on accurate USDT amounts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 15:30:32 +08:00
tinkle
102d9f438d Refactor: Improve AI decision system and Sharpe ratio calculation
Major improvements:
- Use period-level Sharpe ratio (range -2 to +2) instead of annualized
- Save full user prompt in decision logs for debugging
- Format complete market data (3m + 4h candles) for AI analysis
- Prevent position stacking with duplicate position checks
- Update Sharpe ratio interpretation thresholds

Market data enhancements:
- Display full technical indicators in user prompt
- Include 3-minute and 4-hour timeframe data
- Add OI (Open Interest) change and funding rate signals

Risk control:
- Block opening duplicate positions (same symbol + direction)
- Suggest close action first before opening new position
- Prevent margin usage from exceeding limits

UI improvements:
- Update multi-language translations
- Refine AI learning dashboard display

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 04:44:17 +08:00
tinkle
35c7a1d037 Feature: Add Sharpe ratio for AI self-evolution
- Implement Sharpe ratio calculation in decision logger
- Add adaptive behavior recommendations based on Sharpe ratio
- Display Sharpe ratio in AI learning dashboard with visual indicators
- Enable AI to adjust trading strategy based on risk-adjusted returns
- Color-coded performance levels (red/yellow/green) for easy monitoring

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 02:31:15 +08:00
tinkle
14ffb0593a Update: Merge nofx improvements
- Frontend trading records and UI enhancements
- Optimized AI prompts and decision engine
- Performance analysis and comparison features
- Binance-style UI improvements
2025-10-28 21:45:28 +08:00
tinkle
7e8a494ed3 Initial commit: NOFX AI Trading System
- Multi-AI competition mode (Qwen vs DeepSeek)
- Binance Futures integration
- AI self-learning mechanism
- Professional web dashboard
- Complete risk management system
2025-10-28 15:47:34 +08:00