Commit Graph

32 Commits

Author SHA1 Message Date
0xYYBB | ZYY | Bobo
0f98e06d9e Revert "fix: hard system prompt (#401)" (#522)
This reverts commit 7dd669a907.
2025-11-05 19:05:09 +08:00
Jupiteriana
7dd669a907 fix: hard system prompt (#401) 2025-11-05 17:45:18 +08:00
Icyoung
6790895ab1 Merge pull request #462 from zhouyongyou/fix/quantity-zero-min-notional
fix(trader+decision): prevent quantity=0 error with minimum notional validation
2025-11-05 16:29:24 +08:00
Icyoung
feed4ef6a8 Merge pull request #446 from zhouyongyou/fix/json-fullwidth-characters
fix(decision): handle fullwidth JSON characters from AI responses
2025-11-05 15:46:56 +08:00
Icyoung
c7226bf04e Merge pull request #386 from zhouyongyou/feat/configurable-oi-threshold
feat(decision): configurable OI threshold + relaxed trading template
2025-11-05 15:46:25 +08:00
ZhouYongyou
1abd7029dd refactor(decision): relax minimum position size constraints for flexibility
## Changes

### Prompt Layer (Soft Guidance)
**Before**:
- BTC/ETH ≥100 USDT | 山寨币 ≥15 USDT (硬性要求)

**After**:
- 统一建议 ≥12 USDT (软性建议)
- 更简洁,不区分币种
- 给 AI 更多决策空间

### Validation Layer (Lower Thresholds)
**Before**:
- BTC/ETH: 100 USDT (硬性)
- 山寨币: 15 USDT (硬性)

**After**:
- BTC/ETH: 60 USDT (-40%, 更灵活)
- 山寨币: 12 USDT (-20%, 更合理)

## Rationale

### Why Relax?

1. **Previous was too strict**:
   - 100 USDT for BTC hardcoded at current price (~101k)
   - If BTC drops to 60k, only needs 60 USDT
   - 15 USDT for altcoins = 50% safety margin (too conservative)

2. **Three-layer defense is sufficient**:
   - Layer 1 (Prompt): Soft suggestion (≥12 USDT)
   - Layer 2 (Validation): Medium threshold (BTC 60 / Alt 12)
   - Layer 3 (API): Final check (quantity != 0 + CheckMinNotional)

3. **User feedback**: Original constraints too restrictive

### Safety Preserved

 API layer still prevents:
- quantity = 0 errors (formatted precision check)
- Below min notional (CheckMinNotional)

 Validation still blocks obviously small amounts

 Prompt guides AI toward safe amounts

## Testing

| Symbol | Amount | Old | New | Result |
|--------|--------|-----|-----|--------|
| BTCUSDT | 50 USDT |  Rejected |  Rejected |  Correct (too small) |
| BTCUSDT | 70 USDT |  Rejected |  Pass |  More flexible |
| ADAUSDT | 11 USDT |  Rejected |  Rejected |  Correct (too small) |
| ADAUSDT | 13 USDT |  Rejected |  Pass |  More flexible |

## Impact

-  More flexible for price fluctuations
-  Better user experience for small accounts
-  Still prevents API errors
-  AI has more decision space
2025-11-05 01:18:22 +08:00
ZhouYongyou
32f0cabfc3 fix(trader+decision): prevent quantity=0 error with min notional checks
User encountered API error when opening BTC position:
- Account equity: 9.20 USDT
- AI suggested: ~7.36 USDT position
- Error: `code=-4003, msg=Quantity less than or equal to zero.`

```
quantity = 7.36 / 101808.2 ≈ 0.00007228 BTC
formatted (%.3f) → "0.000"  Rounded down to 0!
```

BTCUSDT precision is 3 decimals (stepSize=0.001), causing small quantities to round to 0.

-  CloseLong() and CloseShort() have CheckMinNotional()
-  OpenLong() and OpenShort() **missing** CheckMinNotional()

- AI could suggest position_size_usd < minimum notional value
- No validation prevented tiny positions that would fail

---

**OpenLong() and OpenShort()** - Added two checks:

```go
//  Check if formatted quantity became 0 (rounding issue)
quantityFloat, _ := strconv.ParseFloat(quantityStr, 64)
if quantityFloat <= 0 {
    return error("Quantity too small, formatted to 0...")
}

//  Check minimum notional value (Binance requires ≥10 USDT)
if err := t.CheckMinNotional(symbol, quantityFloat); err != nil {
    return err
}
```

**Impact**: Prevents API errors by catching invalid quantities before submission.

---

Added minimum position size validation:

```go
const minPositionSizeGeneral = 15.0   // Altcoins
const minPositionSizeBTCETH = 100.0   // BTC/ETH (high price + precision limits)

if symbol == BTC/ETH && position_size_usd < 100 {
    return error("BTC/ETH requires ≥100 USDT to avoid rounding to 0")
}
if position_size_usd < 15 {
    return error("Position size must be ≥15 USDT (min notional requirement)")
}
```

**Impact**: Rejects invalid decisions before execution, saving API calls.

---

Updated hard constraints in AI prompt:

```
6. 最小开仓金额: **BTC/ETH ≥100 USDT | 山寨币 ≥15 USDT**
   (⚠️ 低于此金额会因精度问题导致开仓失败)
```

**Impact**: AI proactively avoids suggesting too-small positions.

---

-  User equity 9.20 USDT → suggested 7.36 USDT BTC position → **FAIL**
-  No validation, error only at API level

-  AI validation rejects position_size_usd < 100 for BTC
-  Binance trader checks quantity != 0 before submission
-  Clear error: "BTC/ETH requires ≥100 USDT..."

| Symbol | position_size_usd | Price | quantity | Formatted | Result |
|--------|-------------------|-------|----------|-----------|--------|
| BTCUSDT | 7.36 | 101808.2 | 0.00007228 | "0.000" |  Rejected (validation) |
| BTCUSDT | 150 | 101808.2 | 0.00147 | "0.001" |  Pass |
| ADAUSDT | 15 | 1.2 | 12.5 | "12.500" |  Pass |

---

**Immediate**:
-  Prevents quantity=0 API errors
-  Clear error messages guide users
-  Saves wasted API calls

**Long-term**:
-  AI learns minimum position sizes
-  Better user experience for small accounts
-  Prevents confusion from cryptic API errors

---

- Diagnostic report: /tmp/quantity_zero_diagnosis.md
- Binance min notional: 10 USDT (hardcoded in GetMinNotional())
2025-11-05 01:18:09 +08:00
ZhouYongyou
2afa7a6cf9 fix(decision): correct Unicode regex escaping in reInvisibleRunes
## Critical Fix

### Problem
-  `regexp.MustCompile(`[\u200B...]`)` (backticks = raw string)
- Raw strings don't parse \uXXXX escape sequences in Go
- Regex was matching literal text "\u200B" instead of Unicode characters

### Solution
-  `regexp.MustCompile("[\u200B...]")` (double quotes = parsed string)
- Double quotes properly parse Unicode escape sequences
- Now correctly matches U+200B (zero-width space), U+200C, U+200D, U+FEFF

## Impact
- Zero-width characters are now properly removed before JSON parsing
- Prevents invisible character corruption in AI responses
- Fixes potential JSON parsing failures

## Related
- Same fix applied to z-dev in commit db7c035
2025-11-05 01:05:13 +08:00
ZhouYongyou
65bd1402d6 perf(decision): precompile regex patterns for performance
## Changes
- Move all regex patterns to global precompiled variables
- Reduces regex compilation overhead from O(n) to O(1)
- Matches z-dev's performance optimization

## Modified Patterns
- reJSONFence: Match ```json code blocks
- reJSONArray: Match JSON arrays
- reArrayHead: Validate array start
- reArrayOpenSpace: Compact array formatting
- reInvisibleRunes: Remove zero-width characters

## Performance Impact
- Regex compilation now happens once at startup
- Eliminates repeated compilation in extractDecisions() (called every decision cycle)
- Expected performance improvement: ~5-10% in JSON parsing

## Safety
 All regex patterns remain unchanged (only moved to global scope)
 Compilation successful
 Maintains same functionality as before
2025-11-05 00:54:51 +08:00
ZhouYongyou
6cb583cf1c fix(decision): extract fullwidth chars BEFORE regex matching
🐛 Problem:
- AI returns JSON with fullwidth characters: [{
- Regex \[ cannot match fullwidth [
- extractDecisions() fails with "无法找到JSON数组起始"

🔧 Root Cause:
- fixMissingQuotes() was called AFTER regex matching
- If regex fails to match fullwidth chars, fix function never executes

 Solution:
- Call fixMissingQuotes(s) BEFORE regex matching (line 461)
- Convert fullwidth to halfwidth first: [→[, {→{
- Then regex can successfully match the JSON array

📊 Impact:
- Fixes "无法找到JSON数组起始" error
- Supports AI responses with fullwidth JSON characters
- Backward compatible with halfwidth JSON

This fix is identical to z-dev commit 3676cc0
2025-11-05 00:32:48 +08:00
ZhouYongyou
c9d21e4780 feat(decision): sync robust JSON extraction & limit candidates from z-dev
## Synced from z-dev

### 1. Robust JSON Extraction (from aa63298)
- Add regexp import
- Add removeInvisibleRunes() - removes zero-width chars & BOM
- Add compactArrayOpen() - normalizes '[ {' to '[{'
- Rewrite extractDecisions():
  * Priority 1: Extract from ```json code blocks
  * Priority 2: Regex find array
  * Multi-layer defense: 7 layers total

### 2. Enhanced Validation
- validateJSONFormat now uses regex ^\[\s*\{ (allows any whitespace)
- More tolerant than string prefix check

### 3. Limit Candidate Coins (from f1e981b)
- calculateMaxCandidates now enforces proper limits:
  * 0 positions: max 30 candidates
  * 1 position: max 25 candidates
  * 2 positions: max 20 candidates
  * 3+ positions: max 15 candidates
- Prevents Prompt bloat when users configure many coins

## Coverage

Now handles:
-  Pure JSON
-  ```json code blocks
-  Thinking chain混合
-  Fullwidth characters (16種)
-  CJK characters
-  Zero-width characters
-  All whitespace combinations

Estimated coverage: **99.9%**

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-05 00:27:47 +08:00
ZhouYongyou
3f56d95f42 fix(decision): replace fullwidth space (U+3000) in JSON
Critical bug: AI can output fullwidth space ( U+3000) between brackets:
Input:  [ {"symbol":"BTCUSDT"}]
        ↑ ↑ fullwidth space

After previous fix:
        [ {"symbol":"BTCUSDT"}]
         ↑ fullwidth space remained!

Result: validateJSONFormat failed because:
- Checks "[{" (no space) 
- Checks "[ {" (halfwidth space U+0020) 
- AI output "[ {" (fullwidth space U+3000) 

Solution: Replace fullwidth space → halfwidth space
-  (U+3000) → space (U+0020)

This allows existing validation logic to work:
strings.HasPrefix(trimmed, "[ {") now matches 

Why fullwidth space?
- Common in CJK text editing
- AI trained on mixed CJK content
- Invisible to naked eye but breaks JSON parsing

Test case:
Input:  [ {"symbol":"BTCUSDT"}]
Output: [ {"symbol":"BTCUSDT"}]
Validation:  PASS

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 23:59:20 +08:00
ZhouYongyou
a290c2bffe fix(decision): add CJK punctuation support in fixMissingQuotes
Critical discovery: AI can output different types of "fullwidth" brackets:
- Fullwidth: []{}(U+FF3B/FF3D/FF5B/FF5D) ← Already handled
- CJK: 【】〔〕(U+3010/3011/3014/3015) ← Was missing!

Root cause of persistent errors:
User reported: "JSON 必须以【{开头"
The 【 character (U+3010) is NOT the same as [ (U+FF3B)!

Added CJK punctuation replacements:
- 【 → [ (U+3010 Left Black Lenticular Bracket)
- 】 → ] (U+3011 Right Black Lenticular Bracket)
- 〔 → [ (U+3014 Left Tortoise Shell Bracket)
- 〕 → ] (U+3015 Right Tortoise Shell Bracket)
- 、 → , (U+3001 Ideographic Comma)

Why this was missed:
AI uses different characters in different contexts. CJK brackets (U+3010-3017)
are distinct from Fullwidth Forms (U+FF00-FFEF) in Unicode.

Test case:
Input:  【{"symbol":"BTCUSDT"】
Output: [{"symbol":"BTCUSDT"}]

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 23:11:08 +08:00
ZhouYongyou
7b73d32cb1 feat(decision): add validateJSONFormat to catch common AI errors
Adds comprehensive JSON validation before parsing to catch common AI output errors:

1. Format validation: Ensures JSON starts with [{ (decision array)
2. Range symbol detection: Rejects ~ symbols (e.g., "leverage: 3~5")
3. Thousands separator detection: Rejects commas in numbers (e.g., "98,000")

Execution order (critical for fullwidth character fix):
1. Extract JSON from response
2. fixMissingQuotes - normalize fullwidth → halfwidth 
3. validateJSONFormat - check for common errors 
4. Parse JSON

This validation layer provides early error detection and clearer error messages
for debugging AI response issues.

Added helper function:
- min(a, b int) int - returns smaller of two integers

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 23:04:22 +08:00
ZhouYongyou
86a7c2361b fix(decision): handle fullwidth JSON characters from AI responses
Extends fixMissingQuotes() to replace fullwidth brackets, colons, and commas that Claude AI occasionally outputs, preventing JSON parsing failures.

Root cause: AI can output fullwidth characters like [{:, instead of [{ :,
Error: "JSON 必须以 [{ 开头,实际: [ {"symbol": "BTCU"

Fix: Replace all fullwidth JSON syntax characters:
- [] (U+FF3B/FF3D) → []
- {} (U+FF5B/FF5D) → {}
- : (U+FF1A) → :
- , (U+FF0C) → ,

Test case:
Input:  [{\"symbol\":\"BTCUSDT\",\"action\":\"open_short\"}]
Output: [{\"symbol\":\"BTCUSDT\",\"action\":\"open_short\"}]

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 22:41:35 +08:00
ZhouYongyou
6d53e9260f feat(decision): make OI threshold configurable + add relaxed prompt template
## Changes

### 1. decision/engine.go - Configurable OI Threshold
- Extract hardcoded 15M OI threshold to configurable constant
- Add clear documentation for risk profiles:
  - 15M (Conservative) - BTC/ETH/SOL only
  - 10M (Balanced) - Add major alt-coins
  - 8M (Relaxed) - Include mid-cap coins (BNB/LINK/AVAX)
  - 5M (Aggressive) - Most alt-coins allowed
- Default: 15M (保守,維持原行為)

### 2. prompts/adaptive_relaxed.txt - New Trading Template
Conservative optimization for increased trading frequency while maintaining high win-rate:

**Key Adjustments:**
- Confidence threshold: 85 → 80 (allow more opportunities)
- Cooldown period: 9min → 6min (faster reaction)
- Multi-timeframe trend: 3 periods → 2 periods (relaxed requirement)
- Entry checklist: 5/8 → 4/8 (easier to pass)
- RSI range: 30-40/65-70 → <45/>60 (wider acceptance)
- Risk-reward ratio: 1:3 → 1:2.5 (more flexible)

**Expected Impact:**
- Trading frequency: 5/day → 8-15/day (+60-200%)
- Win-rate: 40% → 50-55% (improved)
- Alt-coins: More opportunities unlocked
- Risk controls: Preserved (Sharpe-based, loss-pause)

## Usage
Users can now choose trading style via Web UI:
- `adaptive` - Strictest (original)
- `adaptive_relaxed` - Balanced (this PR)
- `nof1` - Most aggressive

## Rationale
The original adaptive.txt uses 5-layer filtering (confidence/cooldown/trend/checklist/RSI)
that filters out ~95% of opportunities. This template provides a middle-ground option
for users who want higher frequency without sacrificing core risk management.

Related: #trading-frequency #alt-coin-support
2025-11-04 17:22:14 +08:00
ZhouYongyou
91d6de2f2e 修復關鍵 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-04 16:40:18 +08:00
ZhouYongyou
622c860cd9 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-04 16:40:12 +08:00
Luna Martinez
7b5970567f Merge pull request #88 from fanyinghao/fix-decision-result
fix: Correct error handling in GetFullDecision function
2025-11-01 23:03:55 -04: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
icy
ac7c40632d account system、custom prompt 2025-10-31 03:42:01 +08:00
Yinghao Fan
b6c4a7f75e fix: Correct error handling in decision parsing
Changes:
- Updated error handling in `GetFullDecision` and `parseFullDecisionResponse` functions to return the decision object even when an error occurs, improving the clarity of error messages.

This ensures that the decision object is consistently returned, allowing for better debugging and handling of errors in the decision-making process.
2025-10-31 02:06:20 +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