Commit Graph

18 Commits

Author SHA1 Message Date
SkywalkerJi 1c4c933b7f refactor(decision): use XML tags to separate reasoning from JSON decisions (#719)
* Separate the AI's thought process from the instruction JSON using XML tags.
* Avoid committing encryption key related materials to Git.
* Removing adaptive series prompts, awaiting subsequent modifications for compatibility.
2025-11-07 22:35:53 +08:00
0xYYBB | ZYY | Bobo c7856aa900 refactor(prompts): upgrade to v6.0.0 with enhanced safety rules (#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 #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)
---
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-07 20:30:17 +08:00
0xYYBB | ZYY | Bobo 36365a3b30 fix(prompts): reduce margin usage from 95% to 88% for Hyperliquid liquidation buffer (#666)
## Problem
Users with small accounts (<$200) encounter Hyperliquid error:
"Insufficient margin to place order. asset=1"
Real case: $98.89 account failed to open position
## Root Cause
5% reserve insufficient for:
- Trading fees (~0.04%)
- Slippage (0.01-0.1%)
- Liquidation margin buffer (Hyperliquid requirement)
Additionally, undefined "Allocation %" parameter caused confusion.
## Solution
1. Reduce margin usage rate from 95% to 88% (reserve 12%)
2. Remove undefined "Allocation %" parameter
3. Add small account example ($98.89) for clarity
## Example ($98.89 account)
Before: $93.95 margin → $4.75 remaining 
After:  $87.02 margin → $11.87 remaining 
## Modified Files
- prompts/adaptive.txt
- prompts/default.txt
- prompts/nof1.txt
## Testing
Verified with $98.89 account on z-dev branch - successful order placement
Fixes #549
2025-11-07 09:19:20 +08:00
ZhouYongyou 40c0995bfe fix(prompts): correct risk_usd formula - remove duplicate leverage multiplication
## Problem (Issue #592)
risk_usd formula incorrectly multiplies leverage twice:
- Incorrect: risk_usd = |Entry - Stop| × Position Size × Leverage 
This causes AI to calculate risk as 10x (or leverage倍) higher than actual.
## Root Cause
Position Size already includes leverage effect:
- Position Size (coins) = position_size_usd / price
- position_size_usd = margin × leverage
- Therefore: Position Size = (margin × leverage) / price
Multiplying leverage again amplifies risk calculation by "leverage" times.
## Example
Scenario: $100 margin, 10x leverage, 0.02 BTC position, $500 stop distance
**Correct calculation:**
risk_usd = $500 × 0.02 = $10 
Risk % = 10% of margin (reasonable)
**Incorrect calculation (current):**
risk_usd = $500 × 0.02 × 10 = $100 
Risk % = 100% of margin (completely wrong!)
## Impact
- AI miscalculates risk as "leverage" times higher
- May refuse valid trades thinking risk is too high
- Risk control logic becomes ineffective
- Potential for position sizing errors
## Solution
Correct formula: risk_usd = |Entry - Stop| × Position Size (coins)
Added warnings:
- CN: ⚠️ 不要再乘杠杆:仓位数量已包含杠杆效应
- EN: ⚠️ Do NOT multiply by leverage: Position Size already includes leverage effect
## Modified Files
- prompts/adaptive.txt (line 404)
- prompts/nof1.txt (line 104)
Closes #592
2025-11-07 08:46:37 +08:00
0xYYBB | ZYY | Bobo 366a7fd5f5 fix(prompts): correct confidence scale from 0-1 to 0-100 to match backend schema (#564)
## Problem
The prompts specified confidence range as 0-1 (float), but the backend code
expects 0-100 (integer). This causes JSON parsing errors when AI outputs
values like 0.85:
```
Error: json: cannot unmarshal number 0.85 into Go struct field Decision.confidence of type int
Result: confidence defaults to 0
```
## Root Cause
**Backend Definition** (decision/engine.go:103):
```go
Confidence int `json:"confidence,omitempty"` // 信心度 (0-100)
```
**Prompts (before fix)**:
- adaptive.txt: "confidence (信心度 0-1)"
- nof1.txt: "confidence (float, 0-1)"
**buildHardSystemPrompt** (decision/engine.go:336):
```go
sb.WriteString("- `confidence`: 0-100(开仓建议≥75)\n")
```
The dynamic system prompt was correct, but the base prompts contradicted it.
## Solution
Update prompt files to use consistent 0-100 integer scale:
### adaptive.txt
- `confidence (信心度 0-1)` → `confidence (信心度 0-100)`
- `<0.85` → `<85`
- `0.85-0.90` → `85-90`
- etc.
### nof1.txt
- `confidence (float, 0-1)` → `confidence (int, 0-100)`
- `0.0-0.3` → `0-30`
- `0.3-0.6` → `30-60`
- etc.
## Impact
-  Fixes JSON parsing errors when AI outputs float values
-  Aligns prompts with backend schema
-  Consistent with buildHardSystemPrompt() output format
-  No breaking changes (backend already expects 0-100)
## Testing
```bash
# Verify backend expects 0-100
grep "Confidence int" decision/engine.go
# Output: Confidence int `json:"confidence,omitempty"` // 信心度 (0-100)
# Verify buildHardSystemPrompt uses 0-100
grep "confidence.*0-100" decision/engine.go
# Output: sb.WriteString("- `confidence`: 0-100(开仓建议≥75)\n")
# Build test
go build ./decision/...  #  PASS
```
## Related
- Addresses schema mismatch mentioned in Issue #557
- Note: confidence field is currently not validated by backend (validateDecision
  does not check confidence value), but correct schema prevents parsing errors
---
Co-authored-by: tinkle-community <tinklefund@gmail.com>
2025-11-06 00:35:53 +08:00
Icyoung 89f95d2bef Merge pull request #437 from zhouyongyou/fix/margin-calculation
fix(margin): correct position sizing formula to prevent insufficient margin errors
2025-11-05 16:13:37 +08:00
Icyoung e33f9babfe 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
Icyoung 678392fab1 Merge pull request #325 from zhouyongyou/refactor/enhance-partial-close-guidance
refactor(prompts): 增強部分平倉使用指導 [依賴 #415]
2025-11-05 15:43:08 +08:00
Hansen1018 deca0e5427 增加 稳健和风险控制均衡基础策略提示词
主要优化点:

强化风险控制框架 明确单笔风险≤2%,总风险≤6%
添加连续亏损后的仓位调整规则

设置单日和每周最大亏损限制

提高开仓标准 要求至少3个技术指标支持
必须有多时间框架趋势确认

入场时机要求更具体

完善决策流程 增加市场环境评估环节
明确风险回报比计算要求

添加资金保护检查点

细化行为准则 明确等待最佳机会的重要性
强调分批止盈和严格止损

添加情绪控制具体方法

增强绩效反馈机制 不同夏普比率区间的具体行动指南
亏损状态下的仓位控制要求

盈利状态下的纪律保持提醒

这个优化版本更加注重风险控制和稳健性,同时保持了交易的专业性和灵活性。
2025-11-05 13:19:07 +08:00
ZhouYongyou f99052e780 fix(prompts): rename actions to match backend implementation
## Problem
Backend code expects these action names:
- `open_long`, `open_short`, `close_long`, `close_short`
But prompts use outdated names:
- `buy_to_enter`, `sell_to_enter`, `close`
This causes all trading decisions to fail with unknown action errors.
## Solution
Minimal changes to fix action name compatibility:
### prompts/nof1.txt
-  `buy_to_enter` → `open_long`
-  `sell_to_enter` → `open_short`
-  `close` → `close_long` / `close_short`
-  Explicitly list `wait` action
- +18 lines, -6 lines (only action definitions section)
### prompts/adaptive.txt
-  `buy_to_enter` → `open_long`
-  `sell_to_enter` → `open_short`
-  `close` → `close_long` / `close_short`
- +15 lines, -6 lines (only action definitions section)
## Impact
-  Trading decisions now execute successfully
-  Maintains all existing functionality
-  No new features added (minimal diff)
## Verification
```bash
# Backend expects these actions:
grep 'Action string' decision/engine.go
# "open_long", "open_short", "close_long", "close_short", ...
# Old names removed:
grep -r "buy_to_enter\|sell_to_enter" prompts/
# (no results)
```
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 19:41:23 +08:00
ZhouYongyou 4e6b868531 fix(margin): correct position sizing formula to prevent insufficient margin errors
## Problem
AI was calculating position_size_usd incorrectly, treating it as margin requirement instead of notional value, causing code=-2019 errors (insufficient margin).
## Solution
### 1. Updated AI prompts with correct formula
- **prompts/adaptive.txt**: Added clear position sizing calculation steps
- **prompts/nof1.txt**: Added English version with example
- **prompts/default.txt**: Added Chinese version with example
**Correct formula:**
1. Available Margin = Available Cash × 0.95 × Allocation % (reserve 5% for fees)
2. Notional Value = Available Margin × Leverage
3. position_size_usd = Notional Value (this is the value for JSON)
**Example:** $500 cash, 5x leverage → position_size_usd = $2,375 (not $500)
### 2. Added code-level validation
- **trader/auto_trader.go**: Added margin checks in executeOpenLong/ShortWithRecord
- Validates required margin + fees ≤ available balance before opening position
- Returns clear error message if insufficient
## Impact
- Prevents code=-2019 errors
- AI now understands the difference between notional value and margin requirement
- Double validation: AI prompt + code check
## Testing
-  Compiles successfully
- ⚠️ Requires live trading environment testing
2025-11-04 18:44:07 +08:00
ZhouYongyou b8eea8eaad 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 5d2d849226 refactor(prompts): add comprehensive partial_close guidance to adaptive.txt
Add detailed guidance chapter for dynamic TP/SL management and partial close operations.
## Changes
- New chapter: "动态止盈止损与部分平仓指引" (Dynamic TP/SL & Partial Close Guidance)
- Inserted between "可用动作" (Actions) and "决策流程" (Decision Flow) sections
- 4 key guidance points covering:
  1. Partial close best practices (use clear percentages like 25%/50%/75%)
  2. Reassessing remaining position after partial exit
  3. Proper use cases for update_stop_loss / update_take_profit
  4. Multi-stage exit strategy requirements
## Benefits
-  Provides concrete operational guidelines for AI decision-making
-  Clarifies when and how to use partial_close effectively
-  Emphasizes remaining position management (prevents "orphan" positions)
-  Aligns with existing backend support for partial_close action
## Background
While adaptive.txt already lists partial_close as an available action,
it lacked detailed operational guidance. This enhancement fills that gap
by providing specific percentages, use cases, and multi-stage exit examples.
Backend (decision/engine.go) already validates partial_close with
close_percentage field, so this is purely a prompt enhancement with
no code changes required.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-04 17:20:57 +08:00
tinkle-community a1a0782d52 Merge pull request #268 from yutou123/dev 2025-11-03 06:59:28 +08:00
ZhouYongyou 6810ed3234 docs(prompts): Update AI prompt to support dynamic TP/SL features (v5.5.1)
- Add 3 new action types: update_stop_loss, update_take_profit, partial_close
- Introduce "Zero Principle" (疑惑优先) for risk control
- Expand decision flow to 8 steps with critical safeguards:
  * Step 2: Consecutive loss pause (2x→45min, 3x→24h, 4x→72h)
  * Step 5: BTC status check (multi-timeframe MACD confirmation)
  * Step 6: Long/short confirmation checklist (≥5/8 indicators)
  * Step 7: Fake breakout detection (RSI multi-timeframe + candle patterns)
  * Step 8: Objective confidence scoring (base 60 + conditions)
- Add signal priority ranking (trend resonance > volume > BTC > RSI...)
- Add dynamic TP/SL strategies with examples
- Increase confidence threshold: 0.6 → 0.85 for opening positions
- Add cooldown rules and slippage buffer (0.05%)
- Optimize prompt length: 4445 words → 1500 words (-66%)
Key improvements in v5.5.1:
 BTC status check - Most critical protection for altcoin trading
 Long/short checklist - 5/8 indicators required, prevent false signals
 Objective confidence scoring - Base 60 + condition adjustments
 Fake breakout logic - RSI multi-timeframe + candle filters
 Consecutive loss pause - 2x/3x/4x trigger different cooldowns
 OI confirmation - >+5% for real breakout validation
 Signal priority ranking - Trend resonance > volume > BTC...
 Slippage handling - 0.05% buffer + profit check
Design philosophy: Let AI autonomously judge trend vs chop, trust strong reasoning models.
Co-Authored-By: tinkle-community <tinklefund@gmail.com>
2025-11-03 01:59:54 +08:00
芋头 b2f0ef3300 文件命名空格问题 2025-11-03 00:16:28 +08:00
芋头 cecaf6ae18 补充提示词 2025-11-02 23:56:32 +08:00
SkywalkerJi 5ad135310f Supports custom system prompts and custom models. 2025-11-01 19:45:54 +08:00