Commit Graph

23 Commits

Author SHA1 Message Date
ZhouYongyou
498cec0b92 修復關鍵 BUG:validActions 缺少新動作導致驗證失敗
問題根因:
- 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 分支,等待測試確認
2025-11-02 06:06:55 +08:00
ZhouYongyou
82660b12c5 feat: 添加部分平仓和动态止盈止损功能
新增功能:
- update_stop_loss: 调整止损价格(追踪止损)
- update_take_profit: 调整止盈价格(技术位优化)
- partial_close: 部分平仓(分批止盈)

实现细节:
- Decision struct 新增字段:NewStopLoss, NewTakeProfit, ClosePercentage
- 新增执行函数:executeUpdateStopLossWithRecord, executeUpdateTakeProfitWithRecord, executePartialCloseWithRecord
- 修复持仓字段获取 bug(使用 "side" 并转大写)
- 更新 adaptive.txt 文档,包含详细使用示例和策略建议
- 优先级排序:平仓 > 调整止盈止损 > 开仓

命名统一:
- 与社区 PR #197 保持一致,使用 update_* 而非 adjust_*
- 独有功能:partial_close(部分平仓)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-02 05:32:23 +08:00
ZhouYongyou
8faa2b3494 refactor: 恢復模板加載失敗時的簡化版本 fallback
## 問題
之前修改將模板加載失敗時改為返回空字符串,但:
- 上層函數沒有檢測空字符串的邏輯
- 空字符串會直接傳給 AI API,導致錯誤
- 極端情況下系統無法運行

## 解決方案
恢復原始邏輯,保留內置簡化版本作為最後防線:
```
用戶模板失敗 → default 失敗 → 使用內置簡化版本
"你是专业的加密货币交易AI。请根据市场数据做出交易决策。"
```

## 差異對比
### 之前(不安全)
```go
if default 加載失敗 {
    return ""  //  上層未檢測,會傳空字符串給 AI
}
```

### 現在(安全)
```go
if default 加載失敗 {
    sb.WriteString("你是专业的加密货币交易AI。请根据市场数据做出交易决策。\n\n")
    //  有最後防線,極端情況下仍能運行
}
```

## 測試驗證
-  Go 編譯成功
-  Docker build 成功
-  邏輯恢復到原始穩定版本

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-02 01:27:44 +08:00
ZhouYongyou
bac5744039 refactor: 移除 engine.go 冗餘硬編碼策略,優化模板系統
## 問題
用戶反饋:「怎麼 engine.go 還寫入了這些?... 有必要嗎?」

**根本原因**:
- prompts/ 目錄下已有 default.txt (114行) 和 adaptive.txt (259行)
- engine.go 卻硬編碼了 183 行 adaptive 策略作為 fallback
- 這導致:
  1. 重複維護兩份相同的策略內容
  2. templateLoaded 標記多餘(模板系統本身已有 fallback)
  3. 如果 default.txt 都加載失敗,說明文件系統有嚴重問題,不應繼續交易

## 解決方案

### 1. 移除冗餘硬編碼
- 刪除 183 行硬編碼 adaptive 策略(271-453 行)
- 移除 templateLoaded 標記及其邏輯

### 2. 簡化模板加載邏輯
```go
// 之前(複雜)
templateLoaded := false
if 模板加載成功 {
    templateLoaded = true
}
if !templateLoaded {
    追加 183 行硬編碼策略  //  冗餘
}

// 現在(簡潔)
if 用戶模板加載失敗 {
    嘗試 default.txt  //  已經是 fallback
}
if default.txt 也失敗 {
    返回空字符串,上層應停止交易  //  安全
}
```

### 3. 新增動態止盈止損設計文檔
創建 `DYNAMIC_TP_SL_PROPOSAL.md`,記錄:
- 用戶反饋:「建议加个 adjust tp sl 或者给 close 加个 quantity」
- 問題分析:策略提到追蹤止損,但 AI 無法執行
- 解決方案:添加 `adjust_stop_loss`, `adjust_take_profit`, `partial_close` actions
- 實施步驟:修改 Decision 結構、執行邏輯、模板說明

## 測試驗證
-  Go 編譯成功
-  Docker build 成功
-  模板系統邏輯清晰(用戶模板 → default → 報錯)
-  代碼減少 183 行(更易維護)

## 檔案變更
- `decision/engine.go`: -183 行硬編碼策略
- `DYNAMIC_TP_SL_PROPOSAL.md`: +300 行設計文檔

## 後續工作
- [ ] 實現 adjust_stop_loss action
- [ ] 實現 partial_close action
- [ ] 更新模板文件說明新 actions

---

感謝 @user 指出這個設計缺陷!🙏

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-02 01:18:57 +08:00
ZhouYongyou
a2411d2843 refactor: 優化 engine.go 模板加載邏輯,避免策略重複
## 問題
- 之前邏輯:加載模板 → 無條件追加硬編碼策略
- 結果:選擇 adaptive 模板時,會收到重複的策略內容
  * adaptive.txt: 259 行
  * 硬編碼: 184 行
  * 總計:443 行重複指導 

## 解決方案
使用 templateLoaded 標記追蹤模板加載狀態:
-  模板成功 → 使用模板,跳過硬編碼
-  模板失敗 → 使用硬編碼作為 fallback

## 變更內容
1. 添加 templateLoaded bool 變量
2. 硬編碼策略包裹在 `if !templateLoaded {}` 中(277-463 行)
3. 硬約束和輸出格式始終追加(不受影響)
4. 添加日誌追蹤模板使用情況

## 測試驗證
-  Go 編譯成功
-  Docker build 成功
-  向後兼容(模板失敗時回退到硬編碼)

## 架構改進
```
加載流程:
1. 嘗試加載指定模板(如 adaptive)
2. 失敗 → 嘗試 default
3. 仍失敗 → 使用硬編碼
4. 追加硬約束(動態生成)
5. 追加輸出格式(動態生成)
```

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-02 01:09:37 +08:00
ZhouYongyou
b1e4a7598a fix: 修复中文引号导致的 Go 编译错误
问题:
- Go 语言不识别中文双引号 ""
- 导致编译失败:syntax error: unexpected name

修复:
- 将所有中文双引号 "" 替换为英文单引号 ''
- 影响行:287, 365-369

错误示例:
- 错误:"趋势市场"
- 正确:'趋势市场'

🤖 Generated with Claude Code
2025-11-02 00:25:25 +08:00
ZhouYongyou
88a7055561 feat: 添加技术位优先止盈 + 追踪止损(阶段1)
解决问题:
- 固定百分比止盈经常在技术位前回撤
- 浮盈没有保护机制,从 +1.5% 回撤到止损

核心改进:
1. 技术位优先止盈:
   - 震荡策略:技术位 < 2% → 止盈设在技术位前 0.1%
   - 趋势策略:技术位 < 5% → 止盈设在技术位前 0.2%
   - 技术位识别:EMA20、最近高低点、整数关口

2. 追踪止损机制:
   - 震荡:浮盈 0.8% → 止损移到成本价,浮盈 1.2% → 止损移到 +0.5%
   - 趋势:浮盈 2% → 止损移到成本价,浮盈 5% → 止损移到 +2.5%
   - 价格接近技术位 → 主动平仓避免回撤

3. 分批止盈预留:
   - 趋势策略:技术位在 5-10% → 分两批止盈
   - 为阶段2分批止盈做准备

预期效果:
- 减少"快到止盈就回撤"的情况
- 锁定浮盈,避免全部回撤
- 提高实际盈亏比

实施方式:纯提示词改进,基于已有数据(EMA20、K线高低点)

🤖 Generated with Claude Code
2025-11-02 00:03:20 +08:00
ZhouYongyou
e708c99db2 feat: 添加自适应双策略系统(震荡 + 趋势)
根据 ADAPTIVE_STRATEGY_DESIGN.md 方案 A(简单版)实现:

新增功能:
1. 市场状态判断(3个指标交叉验证):
   - 多时间框架一致性(15m/1h/4h MACD 方向)
   - 价格波动率(最近 10 根 K线波动幅度)
   - 买卖压力极端值(BuySellRatio 连续性)

2. 双策略系统:
   - 策略 A(震荡交易):止盈 1-2%,止损 0.8-1%,盈亏比 1:1.5-1:2
   - 策略 B(趋势跟随):止盈 5-10%,止损 1.5-2%,盈亏比 1:3-1:5

3. 策略选择指导:AI 必须在思维链中明确说明市场状态判断和策略选择

改进效果:
- 让 AI 根据市场状态动态调整止盈止损
- 震荡市场快进快出,趋势市场让利润奔跑
- 预期提升胜率和盈亏比,降低最大回撤

实施方式:纯提示词改进(无代码变更),耗时 30 分钟

🤖 Generated with Claude Code
2025-11-01 20:40:31 +08:00
Z
4fbb4ecea5 Merge branch 'dev' into dev 2025-11-01 20:17:20 +08:00
SkywalkerJi
4250c11ddf Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00
SkywalkerJi
7bc936880c Reordering system prompts. 2025-11-01 16:25:36 +08:00
SkywalkerJi
db782eb314 Eliminating Model Shorting Bias. 2025-11-01 14:44:07 +08:00
ZhouYongyou
0b9d696853 添加震荡交易策略 + 买卖压力分析
**核心功能**:
- 新增买卖压力数据解析(TakerBuyVolume, BuySellRatio)
- 重写系统提示词为震荡交易策略
- 添加连续放量检测功能(2-3根K线)

**技术细节**:
- market/data.go: 解析币安 K线 item[9] 为主动买入量
- decision/engine.go: 震荡区间识别 + 区间边界入场逻辑
- IntradayData: 新增 Volumes 和 BuySellRatios 数组
2025-11-01 11:30:50 +08:00
ZhouYongyou
8e5a35e664 Add multi-timeframe data analysis support
Introduces 15m and 1h timeframes to Data struct and related calculations for more robust multi-timeframe analysis. Updates system prompt to reflect new data sources and analysis methods, and extends Format output to include mid-term series. Enhances signal quality and trend confirmation by leveraging multiple timeframes.
2025-10-31 22:41:13 +08:00
icy
ac7c40632d account system、custom prompt 2025-10-31 03:42:01 +08:00
tpkeeper
1083c06d1f Fix mcp defaultConfig override issue in multi-trader, multi-AI model scenario 2025-10-30 15:46:17 +08:00
sue
66b8eb416b fix: 修复配置硬编码问题
## 修复内容

### 1. AI决策杠杆配置动态化 (decision/engine.go)
- **问题**: System Prompt 中硬编码 50x/20x 杠杆,导致 AI 生成的决策不符合用户配置(5x)
- **修复**:
  - buildSystemPrompt() 新增 btcEthLeverage, altcoinLeverage 参数
  - System Prompt 文本使用动态杠杆值(第225-226行)
  - 示例 JSON 使用配置杠杆值(第299行)
  - 调用时传入实际配置值(第100行)
- **影响**: AI 现在会根据用户配置的杠杆限制生成决策

### 2. 前端初始余额显示优化 (web/src/components/EquityChart.tsx)
- **问题**: 初始余额硬编码为 1000 USDT,与用户配置的 100 USDT 不符
- **修复**: 实现三级回退机制
  1. 优先使用历史数据第一个点的 total_equity
  2. 备用使用当前账户 account.total_equity
  3. 最后使用默认值 100(匹配常见配置)
- **影响**: 前端显示的初始余额现在与实际配置一致

## 技术细节

**函数签名变更**:
```go
// 修改前
func buildSystemPrompt(accountEquity float64) string

// 修改后
func buildSystemPrompt(accountEquity float64, btcEthLeverage, altcoinLeverage int) string
```

**React 状态优化**:
```typescript
// 修改前
const initialBalance = history[0]?.total_equity || 1000;

// 修改后
const initialBalance = history[0]?.total_equity || account?.total_equity || 100;
```

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-30 02:43:14 +08:00
tinkle
d2edc5e0a4 Refactor: Improve AI prompt with more technical analysis methods
Changes to decision/engine.go:
- Clean up Context struct field alignment for better readability
- Enhance system prompt to include more technical analysis methods:
  * Added: technical resistance levels, Fibonacci, volatility bands
  * Changed wording from "you can do X" to "you can do but not limited to X"
  to encourage AI to use broader range of analysis techniques

This gives the AI decision engine more explicit guidance on available
technical analysis tools while maintaining flexibility.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 22:05:58 +08:00
PorunC
36840d52dd Feat: Integrate leverage configuration across trading system
- Pass leverage config through TraderManager to AutoTrader
- Add BTCETHLeverage and AltcoinLeverage fields to Context and AutoTraderConfig
- Update decision validation to use configured leverage limits
- Display configured leverage in startup message
- Update error messages to show current leverage limits

Changes:
- main.go: Pass leverage config to AddTrader, update startup message
- manager/trader_manager.go: Accept and forward leverage config
- trader/auto_trader.go: Store leverage config, pass to Context
- decision/engine.go: Use dynamic leverage limits in validation

This completes the leverage configuration feature implementation.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 20:30:04 +08:00
tinkle
1d697c978f Refactor: Give AI full freedom to analyze raw sequence data
Remove prescriptive indicator combinations and let AI freely use all available data.

**Changes**:
- Emphasized AI has access to **raw sequence data** (MidPrices array, 4h candles)
- Listed all available sequences: price, technical (EMA/MACD/RSI), and capital flow (volume/OI)
- Removed hard-coded indicator combinations (e.g., "MACD + RSI + Volume")
- Changed from prescriptive examples to open-ended analysis freedom
- AI can now freely perform trend analysis, pattern recognition, support/resistance calculation
- Reduced minimum close-open interval from 30min to 15min for more flexibility

**Before**:
```
强信号示例:
- 趋势突破 + 多个指标确认(MACD + RSI + 成交量)
- 持仓量暴增 + 价格突破关键位
```

**After**:
```
你拥有的完整数据:
- 📊 原始序列:3分钟价格序列(MidPrices数组) + 4小时K线序列
- 📈 技术序列:EMA20序列、MACD序列、RSI7序列、RSI14序列
- 💰 资金序列:成交量序列、持仓量(OI)序列、资金费率

分析方法(完全由你自主决定):
- 自由运用序列数据,你可以做趋势分析、形态识别、支撑阻力计算
- 多维度交叉验证(价格+量+OI+指标+序列形态)
- 用你认为最有效的方法发现高确定性机会
```

**Philosophy**: Trust AI to discover effective patterns in raw data rather than constraining it to pre-defined indicator combinations.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 14:33:54 +08:00
tinkle
68c0c62d04 Feature: Add position holding duration to AI decision context
Track and display how long each position has been held to help AI make better timing decisions.

**Implementation**:
- Added UpdateTime field to PositionInfo struct (decision/engine.go:26)
- Added positionFirstSeenTime map to AutoTrader for tracking (trader/auto_trader.go:60)
- Record opening time when position is created successfully:
  - executeOpenLongWithRecord: Records timestamp for long positions (trader/auto_trader.go:540-541)
  - executeOpenShortWithRecord: Records timestamp for short positions (trader/auto_trader.go:593-594)
- Fallback tracking in buildTradingContext for program restart scenarios (trader/auto_trader.go:386-392)
- Auto-cleanup closed positions from tracking map (trader/auto_trader.go:409-414)
- Display duration in user prompt with smart formatting:
  - Under 60 min: "持仓时长25分钟"
  - Over 60 min: "持仓时长2小时15分钟"

**Example Output**:
```
1. TAOUSDT LONG | 入场价435.5300 当前价433.1900 | 盈亏-0.54% | 杠杆20x | 保证金25 | 强平价418.1528 | 持仓时长2小时15分钟
```

**Benefits**:
- AI can see how long positions have been held
- Helps enforce minimum holding period (30-60 min) from system prompt
- Simple implementation with minimal overhead
- Auto-cleanup prevents memory leaks

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 14:20:40 +08:00
tinkle
f3b7131ba8 Refactor: Enhance AI decision engine with Sharpe ratio optimization
Major improvements to the AI trading decision engine:

**Core Changes in decision/engine.go** (175 lines modified):

1. **Sharpe Ratio Optimization Focus**
   - Restructured system prompt to emphasize Sharpe ratio maximization
   - Added clear guidance: high-quality trades over frequent trading
   - Explained that 3-minute scan interval ≠ trade every cycle

2. **Trading Frequency Controls**
   - Defined optimal frequency: 2-4 trades/day (0.1-0.2 trades/hour)
   - Over-trading threshold: >2 trades/hour indicates issues
   - Minimum holding period: 30-60 minutes per position

3. **Long/Short Balance Incentives**
   - Emphasized equal profit potential for long and short positions
   - Removed long-bias with explicit short trading encouragement
   - Clear guidance: uptrend→long, downtrend→short, sideways→wait

4. **Stricter Entry Signal Standards**
   - Strong signals only: confidence ≥75, multi-indicator confirmation
   - Weak signals explicitly discouraged (single indicator, unclear trend)
   - Self-check mechanism to prevent premature re-entry (<30min)

5. **Enhanced Sharpe Ratio Feedback Loop**
   - Sharpe < -0.5: Stop trading for 6+ cycles (18min), deep reflection
   - Sharpe -0.5~0: Strict control, confidence >80 only
   - Sharpe 0~0.7: Maintain current strategy
   - Sharpe >0.7: Consider position size increase

6. **Risk-Reward Ratio Validation**
   - Added hard constraint: R:R must be ≥ 3.0:1
   - Automatic calculation and validation in `validateDecision()`
   - Rejects trades with insufficient risk-reward ratio

7. **Improved Prompt Structure**
   - More organized sections with clear headers
   - Actionable guidance instead of abstract principles
   - Better examples for JSON output format

**Impact**: These changes should significantly improve trading quality,
reduce over-trading, and increase Sharpe ratio through better risk management
and trade selection discipline.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 12:49:34 +08:00
tinkle
f3a87b5a7a Refactor: Modularize codebase with separate decision and MCP packages
Architecture improvements:
- Extract AI decision engine to dedicated `decision` package
- Create `mcp` package for Model Context Protocol client
- Separate market data structures into `market/data.go`
- Update trader to use new modular structure

New packages:
- `decision/engine.go` - AI decision logic and prompt building
- `mcp/client.go` - Unified AI API client (DeepSeek/Qwen)
- `market/data.go` - Market data type definitions

Benefits:
- Better separation of concerns
- Improved code organization and maintainability
- Easier to test individual components
- More flexible AI provider integration
- Cleaner dependency management

Updated imports:
- trader/auto_trader.go now uses decision and mcp packages
- Consistent API across different AI providers

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-29 06:14:57 +08:00