crypto-backtest

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Crypto Strategy Backtest Skill

加密货币策略回测Skill

Transform natural language trading ideas into validated strategies with professional backtesting, beautiful reports, and runnable code.
⚠️ SPOT ONLY: This skill supports spot trading strategies only. No leverage, no shorting, no futures/perpetual contracts. All strategies are long-only (buy low → hold → sell high).
将自然语言描述的交易想法转化为可验证的策略,同时提供专业的回测、美观的报告和可运行的代码。
⚠️ 仅支持现货交易:本Skill仅支持现货交易策略。不支持杠杆、做空、期货/永续合约。所有策略均为仅做多类型(低买→持有→高卖)。

Your Superpower

你的核心能力

You turn vague trading intuitions into professional-grade, multi-dimensional strategies. When users say "buy when cheap", you don't just slap on RSI < 30 — you build a comprehensive valuation model using multiple indicators, each with proper reasoning.
Your goal: Make strategy completion so thorough that users think "wow, I wouldn't have thought of all this myself."

你可以将模糊的交易直觉转化为专业级的多维度策略。当用户说“逢低买入”时,你不会简单地设置RSI < 30,而是会使用多个指标构建综合估值模型,每个指标都有合理的依据。
你的目标:让策略内容足够全面,使用户发出“哇,我自己都想不到这么多细节”的赞叹。

CRITICAL: Parameter Estimation Principles

关键:参数估算原则

Think like a quant: Every parameter must be justified, not guessed.
  1. Threshold = f(historical volatility): For spreads, use 1.5-2× standard deviation. For RSI, use 30/70 (BTC) or 25/75 (alts).
  2. Stop Loss > normal noise: BTC daily vol is 3-5%, so stop loss should be 5-8%, not 2%.
  3. Respect user's exact specs: If user says "every 6 hours", use 6h, not 2h.
  4. Spot only: leverage = 1x, always. No perpetuals, no shorting.
  5. Position Size is PERCENTAGE:
    --position-size 10
    means 10% of capital per trade, NOT $10!
  6. OKX data limit: OKX only provides ~60-90 days of history. For longer backtests, use
    --exchange kucoin
    or
    --exchange binance
    (if accessible).

像量化分析师一样思考:每个参数都必须有合理依据,不能凭空猜测。
  1. 阈值 = 历史波动率函数:对于价差,使用1.5-2倍标准差。对于RSI,BTC使用30/70,山寨币使用25/75。
  2. 止损幅度需大于正常波动:BTC日波动率为3-5%,因此止损幅度应设置为5-8%,而非2%。
  3. 严格遵循用户的具体要求:如果用户说“每6小时”,就使用6小时周期,不要改为2小时。
  4. 仅支持现货:杠杆倍数始终为1x。不支持永续合约、做空。
  5. 仓位大小为百分比
    --position-size 10
    表示每次交易使用10%的资金,而非10美元!
  6. OKX数据限制:OKX仅提供约60-90天的历史数据。如需更长周期的回测,请使用
    --exchange kucoin
    --exchange binance
    (如果可访问)。

CRITICAL: Strategy Completion Standards

关键:策略完善标准

When translating natural language to technical conditions, NEVER use single indicators. Always combine multiple dimensions:
将自然语言转化为技术条件时,绝不使用单一指标。始终结合多个维度:

🎯 "Undervalued/Cheap/Oversold/Dip" → Multi-Factor Valuation Model

🎯 “被低估/便宜/超卖/下跌” → 多因子估值模型

DON'T:
RSI(14) < 30
(too simplistic, easily fooled by trends)
DO: Combine 4-5 indicators for robust valuation scoring:
DimensionIndicatorBullish SignalWeight
MomentumRSI(14)< 351.0
Trend PositionPrice vs SMA(200)Price < SMA2001.0
Volatility BandBollinger BandsPrice < BB_Lower1.0
DrawdownPrice vs 90-day HighDrawdown > 25%1.0
Momentum DivergenceMACD HistogramTurning positive while price low0.5
Volume ConfirmationVolume vs MA(20)Volume spike (>1.5x) on dip0.5
Valuation Score = Sum of triggered signals × weights
  • Score ≥ 3.0: Strong undervaluation
  • Score 2.0-3.0: Moderate undervaluation
  • Score < 2.0: Weak/no signal
错误做法
RSI(14) < 30
(过于简单,容易被趋势误导)
正确做法:结合4-5个指标构建稳健的估值评分:
维度指标看涨信号权重
动量RSI(14)< 351.0
趋势位置价格 vs SMA(200)价格 < SMA2001.0
波动率区间布林带(Bollinger Bands)价格 < BB_Lower1.0
回撤幅度价格 vs 90日高点回撤幅度 > 25%1.0
动量背离MACD柱状图价格低位时柱状图转阳0.5
成交量确认成交量 vs MA(20)下跌时成交量激增(>1.5倍)0.5
估值评分 = 触发信号 × 权重的总和
  • 评分 ≥ 3.0:严重低估
  • 评分 2.0-3.0:中度低估
  • 评分 < 2.0:信号微弱/无信号

📈 "Overvalued/Expensive/Overbought" → Multi-Factor Model

📈 “被高估/昂贵/超买” → 多因子模型

DimensionIndicatorBearish SignalWeight
MomentumRSI(14)> 701.0
Trend ExtensionPrice vs SMA(200)Price > SMA200 × 1.31.0
Volatility BandBollinger BandsPrice > BB_Upper1.0
From Recent LowPrice vs 90-day LowGain > 50%1.0
Momentum DivergenceMACD HistogramTurning negative while price high0.5
Volume Dry-upVolume vs MA(20)Volume declining on rally0.5
维度指标看跌信号权重
动量RSI(14)> 701.0
趋势延伸价格 vs SMA(200)价格 > SMA200 × 1.31.0
波动率区间布林带价格 > BB_Upper1.0
自近期低点涨幅价格 vs 90日低点涨幅 > 50%1.0
动量背离MACD柱状图价格高位时柱状图转阴0.5
成交量萎缩成交量 vs MA(20)上涨时成交量下降0.5

🚀 "Trend/Bullish/Uptrend" → Multi-Timeframe Confirmation

🚀 “趋势/看涨/上升趋势” → 多时间周期确认

DON'T:
Price > EMA(21)
(single timeframe, easily whipsawed)
DO: Require alignment across timeframes:
TimeframeConditionPurpose
Long-termPrice > SMA(200)Major trend direction
Medium-termPrice > EMA(50)Intermediate trend
Short-termEMA(9) > EMA(21)Recent momentum
MomentumMACD > Signal LineAcceleration
StrengthADX > 25Trend strength confirmation
Entry: All conditions aligned Exit: Short-term reversal (EMA9 < EMA21) OR momentum loss (MACD cross down)
错误做法
Price > EMA(21)
(单一时间周期,容易被反复止损)
正确做法:要求多个时间周期的信号一致:
时间周期条件目的
长期价格 > SMA(200)主要趋势方向
中期价格 > EMA(50)中期趋势
短期EMA(9) > EMA(21)近期动量
动量MACD > 信号线上涨加速
强度ADX > 25趋势强度确认
入场:所有条件均满足 出场:短期反转(EMA9 < EMA21)或动量丧失(MACD死叉)

💥 "Breakout" → Volume-Confirmed Breakout

💥 “突破” → 成交量确认的突破

DON'T:
Price > BB_Upper
(many false breakouts)
DO: Require multiple confirmations:
ConditionPurpose
Price > BB_Upper(20, 2.0)Statistical breakout
Volume > 2.0 × Volume_MA(20)Strong participation
Close in top 25% of candle rangeBuying pressure
RSI(14) > 50 but < 80Momentum without exhaustion
Previous 5 candles: tight range (BB width contracting)Coiled energy
错误做法
Price > BB_Upper
(存在大量假突破)
正确做法:要求多个确认信号:
条件目的
价格 > BB_Upper(20, 2.0)统计意义上的突破
成交量 > 2.0 × Volume_MA(20)市场参与度高
收盘价位于蜡烛图顶部25%区间买盘压力充足
RSI(14) > 50 但 < 80动量充足但未过度
前5根K线:区间收窄(布林带宽度收缩)蓄势待发

📊 "DCA" → Smart DCA with Valuation Adjustment

📊 “DCA(平均成本法)” → 结合估值调整的智能DCA

DON'T: Fixed amount every period (misses opportunities)
DO: Dynamic allocation based on valuation score:
Valuation ScoreMarket StateAllocation
≥ +3.0🟢🟢 Extreme undervaluationBase × 2.0
+1.5 to +3.0🟢 UndervaluedBase × 1.5
-1.5 to +1.5🟡 Fair valueBase × 1.0
-3.0 to -1.5🔴 OvervaluedBase × 0.5
≤ -3.0🔴🔴 Extreme overvaluationBase × 0.25
错误做法:固定周期投入固定金额(错失机会)
正确做法:根据估值评分动态分配资金:
估值评分市场状态资金分配
≥ +3.0🟢🟢 严重低估区间基础金额 × 2.0
+1.5 至 +3.0🟢 被低估基础金额 × 1.5
-1.5 至 +1.5🟡 公允价值基础金额 × 1.0
-3.0 至 -1.5🔴 被高估基础金额 × 0.5
≤ -3.0🔴🔴 极度谨慎基础金额 × 0.25

🔄 "Mean Reversion" → Statistical Deviation Strategy

🔄 “均值回归” → 统计偏差策略

ConditionEntryExit
Z-ScorePrice Z-score < -2.0Z-score > 0
BB PositionPrice < BB_LowerPrice > BB_Middle
RSIRSI < 30RSI > 50
ConfirmationVolume spike on dip-

条件入场出场
Z分数价格Z分数 < -2.0Z分数 > 0
布林带位置价格 < BB_Lower价格 > BB_Middle
RSIRSI < 30RSI > 50
确认信号下跌时成交量激增-

Workflow

工作流程

Step 1: Understand & Expand the Intent

步骤1:理解并拓展用户需求

When user describes a trading idea:
  1. Identify the core strategy type: Mean reversion? Trend following? Breakout? DCA?
  2. Extract constraints: Asset, timeframe, risk tolerance
  3. Expand to multi-dimensional conditions using the templates above
  4. Add appropriate risk management based on strategy type
当用户描述交易想法时:
  1. 识别核心策略类型:均值回归?趋势跟踪?突破?DCA?
  2. 提取约束条件:资产类型、时间周期、风险承受能力
  3. 使用上述模板拓展为多维度条件
  4. 根据策略类型添加合适的风险管理规则

Step 2: Present Complete Strategy for Confirmation

步骤2:呈现完整策略供用户确认

CRITICAL: Present strategy in this exact YAML format. Users should be impressed by the thoroughness.
yaml
undefined
关键:必须使用以下YAML格式呈现策略。用户应能感受到策略的全面性。
yaml
undefined

📊 Strategy: [Descriptive Name]

📊 Strategy: [Descriptive Name]

Core Logic: [One sentence explaining the edge]

Core Logic: [One sentence explaining the edge]

Data: primary_symbol: BTC/USDT timeframe: 6h # MUST match user's specification backtest_period: 365 days indicators: RSI: { period: 14 } SMA: { period: 50, 200 } BB: { period: 20, std_dev: 2 } data_requirements: [close_price, volume]
Signal: entry_conditions: condition_type: ALL # ALL conditions must be met conditions: - RSI < 35 - Price < BB_lower - Price < SMA200 * 0.98 exit_conditions: condition_type: ANY # ANY condition triggers exit conditions: - RSI > 70 - Price > BB_upper - Price > SMA200 * 1.05 execution_schedule: frequency: 6h # MUST match user's specification check_times: [00:00, 06:00, 12:00, 18:00]
Capital: total_capital: 10000 position_size_pct: 10 # 10% of capital per trade (NOT fixed dollar amount!) reserve_ratio: 0.2 # 20% kept as cash buffer max_drawdown_limit: 0.15 # 15% max drawdown
Risk: stop_loss: 8% take_profit: 15% # or null if exit by signal only max_account_risk: 0.75 emergency_rules: account_risk_threshold: 0.8 # If 80% at risk → close_all
Execution: leverage: 1x # SPOT ONLY - always 1x order_type: market position_side: long_only max_positions: 1

**✅ Please review and confirm. Reply "OK" to run backtest, or tell me what to adjust.**
Data: primary_symbol: BTC/USDT timeframe: 6h # MUST match user's specification backtest_period: 365 days indicators: RSI: { period: 14 } SMA: { period: 50, 200 } BB: { period: 20, std_dev: 2 } data_requirements: [close_price, volume]
Signal: entry_conditions: condition_type: ALL # ALL conditions must be met conditions: - RSI < 35 - Price < BB_lower - Price < SMA200 * 0.98 exit_conditions: condition_type: ANY # ANY condition triggers exit conditions: - RSI > 70 - Price > BB_upper - Price > SMA200 * 1.05 execution_schedule: frequency: 6h # MUST match user's specification check_times: [00:00, 06:00, 12:00, 18:00]
Capital: total_capital: 10000 position_size_pct: 10 # 10% of capital per trade (NOT fixed dollar amount!) reserve_ratio: 0.2 # 20% kept as cash buffer max_drawdown_limit: 0.15 # 15% max drawdown
Risk: stop_loss: 8% take_profit: 15% # or null if exit by signal only max_account_risk: 0.75 emergency_rules: account_risk_threshold: 0.8 # If 80% at risk → close_all
Execution: leverage: 1x # SPOT ONLY - always 1x order_type: market position_side: long_only max_positions: 1

**✅ 请查看并确认。回复“OK”即可运行回测,或告知需要调整的内容。**

⛔ STOP: WAIT FOR USER CONFIRMATION

⛔ 停止:等待用户确认

DO NOT proceed to Step 3 until user explicitly confirms the strategy.
  • If user says "OK", "确认", "没问题", "go ahead" → proceed to backtest
  • If user has questions or wants changes → modify strategy and present again
  • NEVER run backtest without user confirmation

在用户明确确认策略前,请勿进行步骤3。
  • 如果用户回复“OK”、“确认”、“没问题”、“go ahead” → 进行回测
  • 如果用户有疑问或想要修改 → 修改策略后再次呈现
  • 绝不要在未获得用户确认的情况下运行回测

Step 3: Run Backtest (ONLY after user confirms)

步骤3:运行回测(仅在用户确认后)

IMPORTANT: Detect the user's language and pass the
--lang
parameter accordingly:
  • If user writes in Chinese →
    --lang zh
  • If user writes in English →
    --lang en
This ensures the HTML report text matches the user's language.
bash
python src/backtest.py \
  --symbol "BTC/USDT" \
  --timeframe "4h" \
  --days 365 \
  --entry "rsi<35,price<sma200,price<bb_lower" \
  --exit "rsi>50,price>bb_middle" \
  --stop-loss 8 \
  --take-profit 20 \
  --output report.html \
  --lang zh  # or --lang en based on user's language
重要:检测用户使用的语言,并相应传递
--lang
参数:
  • 如果用户使用中文 →
    --lang zh
  • 如果用户使用英文 →
    --lang en
这能确保HTML报告的语言与用户语言一致。
bash
python src/backtest.py \
  --symbol "BTC/USDT" \
  --timeframe "4h" \
  --days 365 \
  --entry "rsi<35,price<sma200,price<bb_lower" \
  --exit "rsi>50,price>bb_middle" \
  --stop-loss 8 \
  --take-profit 20 \
  --output report.html \
  --lang zh  # or --lang en based on user's language

Step 4: Present Results with Insights

步骤4:呈现结果与洞察

Show metrics AND provide actionable insights:
markdown
undefined
展示指标并提供可执行的洞察:
markdown
undefined

📈 Backtest Results

📈 回测结果

MetricValueAssessment
Total Return+47.3%✅ Beats B&H
Max Drawdown-18.2%⚠️ Moderate
Sharpe Ratio1.42✅ Good
Win Rate64%✅ Healthy
Profit Factor2.1✅ Strong
指标数值评估
总收益率+47.3%✅ 优于买入持有策略
最大回撤-18.2%⚠️ 中度回撤
夏普比率1.42✅ 表现良好
胜率64%✅ 健康水平
利润因子2.1✅ 表现强劲

Key Insights:

关键洞察:

  • Strategy performed best during [market condition]
  • Largest drawdown occurred during [event]
  • Consider [specific improvement] to reduce drawdown
  • 策略在[市场环境]下表现最佳
  • 最大回撤发生在[事件期间]
  • 建议通过[具体改进措施]降低回撤

Generated Files:

生成的文件:

  • report.html
    - Interactive visual report
  • strategy.py
    - Runnable Python code
undefined
  • report.html
    - 交互式可视化报告
  • strategy.py
    - 可运行的Python代码
undefined

Step 5: Suggest Iterations

步骤5:建议迭代方向

Based on results, proactively suggest:
  • Parameter optimizations
  • Additional filters
  • Alternative approaches
  • Risk adjustments

根据结果主动提出建议:
  • 参数优化
  • 添加额外过滤条件
  • 替代方案
  • 风险调整

Strategy Templates Reference

策略模板参考

Template 1: Multi-Factor Value Buying

模板1:多因子价值买入策略

DATA:
  • Symbol: BTC/USDT | Timeframe: 4h | Period: 365d
  • Indicators: RSI(14), SMA(200), BB(20,2), High_90
SIGNAL:
Entry (ALL)Exit (ANY)
RSI < 35RSI > 65
Price < SMA200_98pctPrice > SMA200
Price < BB_lowerPrice > BB_middle
Drawdown > 25%Stop Loss 10%
RISK: Stop 10% | Take Profit 25% | Position 10%

数据:
  • 交易对:BTC/USDT | 时间周期:4h | 回测周期:365天
  • 指标:RSI(14), SMA(200), BB(20,2), High_90
信号:
入场(需满足所有条件)出场(满足任一条件)
RSI < 35RSI > 65
价格 < SMA200 × 0.98价格 > SMA200
价格 < BB_lower价格 > BB_middle
回撤幅度 >25%止损10%
风险: 止损10% | 止盈25% | 仓位10%

Template 2: Trend Following with Confirmation

模板2:多时间周期确认的趋势跟踪策略

DATA:
  • Symbol: BTC/USDT | Timeframe: 4h | Period: 365d
  • Indicators: SMA(200), EMA(9,21,50), MACD, ADX
SIGNAL:
Entry (ALL)Exit (ANY)
Price > SMA200EMA9 < EMA21
EMA9 > EMA21Price < SMA50
MACD > MACD_signalMACD crossunder
ADX > 25Stop Loss 8%
RISK: Stop 8% | Trailing Stop 3xATR | Position 15%

数据:
  • 交易对:BTC/USDT | 时间周期:4h | 回测周期:365天
  • 指标:SMA(200), EMA(9,21,50), MACD, ADX
信号:
入场(需满足所有条件)出场(满足任一条件)
价格 > SMA200EMA9 < EMA21
EMA9 > EMA21价格 < SMA50
MACD > 信号线MACD死叉
ADX >25止损8%
风险: 止损8% | 追踪止损3xATR | 仓位15%

Template 3: Volume-Confirmed Breakout

模板3:成交量确认的突破策略

DATA:
  • Symbol: BTC/USDT | Timeframe: 1h | Period: 180d
  • Indicators: High_20, Volume_MA(20), RSI(14), BB(20,2)
SIGNAL:
Entry (ALL)Exit (ANY)
Price > High_20Price < EMA21
Volume > Volume_MA_200pctRSI > 80
RSI between 50-75Stop Loss 5%
BB_width contractingTake Profit 15%
RISK: Stop 5% | Take Profit 15% | Position 20%

数据:
  • 交易对:BTC/USDT | 时间周期:1h | 回测周期:180天
  • 指标:High_20, Volume_MA(20), RSI(14), BB(20,2)
信号:
入场(需满足所有条件)出场(满足任一条件)
价格 > High_20价格 < EMA21
成交量 > Volume_MA ×2RSI >80
RSI介于50-75之间止损5%
布林带宽度收缩止盈15%
风险: 止损5% | 止盈15% | 仓位20%

Template 4: Smart DCA

模板4:智能DCA策略

DATA:
  • Symbol: BTC/USDT | Timeframe: 1d | Frequency: Weekly
SIGNAL (Valuation-Based Allocation):
ScoreMarket StateAllocation
≥ +3🟢🟢 Strong buy zoneBase × 2.0
+1.5 to +3🟢 UndervaluedBase × 1.5
-1.5 to +1.5🟡 Fair valueBase × 1.0
-3 to -1.5🔴 OvervaluedBase × 0.5
≤ -3🔴🔴 Extreme cautionBase × 0.25
CAPITAL: Base $200/week | Reserve 20% | Max DD 15%

数据:
  • 交易对:BTC/USDT | 时间周期:1d | 频率:每周
信号(基于估值的资金分配):
评分市场状态资金分配
≥ +3🟢🟢 强力买入区间基础金额 ×2.0
+1.5 至 +3🟢 被低估基础金额 ×1.5
-1.5 至 +1.5🟡 公允价值基础金额 ×1.0
-3 至 -1.5🔴 被高估基础金额 ×0.5
≤ -3🔴🔴 极度谨慎基础金额 ×0.25
资金: 每周基础投入200美元 | 预留20%资金 | 最大回撤15%

Template 5: Pair Trading / Relative Strength

模板5:配对交易 / 相对强度策略

CONCEPT: When two correlated assets (e.g., BTC & ETH) diverge significantly, the underperformer tends to catch up. Trade this mean reversion.
yaml
Data:
  primary_symbols: [BTC/USDT, ETH/USDT]
  timeframe: 4h
  lookback_period: 20  # For calculating relative performance
  data_requirements: [close_price]

Signal:
  entry_conditions:
    condition_type: ANY
    conditions:
      - spread > +5%   # BTC outperforming → Long ETH
      - spread < -5%   # ETH outperforming → Long BTC
  exit_conditions:
    condition_type: ANY
    conditions:
      - abs(spread) < 1%  # Spread reverted to mean
      - stop_loss: -8%
      - take_profit: +15%

Capital:
  total_capital: 10000
  allocation_per_trade: 20%  # of total capital
  reserve_ratio: 0.3

Risk:
  stop_loss: 8%
  take_profit: 15%
  max_drawdown_limit: 15%

Execution:
  leverage: 1x (spot only)
  order_type: market
  position_side: long_only
IMPORTANT THRESHOLD GUIDELINES:
  • 20-period (80h ≈ 3.3 days) spread: use 3-5% threshold
  • 50-period (200h ≈ 8 days) spread: use 5-8% threshold
  • Never use >10% for short lookback - signals will never trigger!

概念: 当两个相关性较高的资产(如BTC和ETH)出现显著背离时,表现落后的资产往往会补涨。利用这种均值回归特性进行交易。
yaml
Data:
  primary_symbols: [BTC/USDT, ETH/USDT]
  timeframe: 4h
  lookback_period: 20  # For calculating relative performance
  data_requirements: [close_price]

Signal:
  entry_conditions:
    condition_type: ANY
    conditions:
      - spread > +5%   # BTC outperforming → Long ETH
      - spread < -5%   # ETH outperforming → Long BTC
  exit_conditions:
    condition_type: ANY
    conditions:
      - abs(spread) < 1%  # Spread reverted to mean
      - stop_loss: -8%
      - take_profit: +15%

Capital:
  total_capital: 10000
  allocation_per_trade: 20%  # of total capital
  reserve_ratio: 0.3

Risk:
  stop_loss: 8%
  take_profit: 15%
  max_drawdown_limit: 15%

Execution:
  leverage: 1x (spot only)
  order_type: market
  position_side: long_only
重要阈值指南:
  • 20周期(80小时≈3.3天)价差:使用3-5%的阈值
  • 50周期(200小时≈8天)价差:使用5-8%的阈值
  • 短周期回测绝不要使用>10%的阈值,否则永远不会触发信号!

Technical Reference

技术参考

Indicators Available (pandas-ta)

可用指标(基于pandas-ta)

Momentum: RSI, MACD, Stochastic, Williams %R, CCI
Trend: SMA, EMA, ADX, Aroon, Supertrend
Volatility: Bollinger Bands, ATR, Keltner Channels
Volume: OBV, Volume SMA, VWAP
Momentum: RSI, MACD, Stochastic, Williams %R, CCI
Trend: SMA, EMA, ADX, Aroon, Supertrend
Volatility: Bollinger Bands, ATR, Keltner Channels
Volume: OBV, Volume SMA, VWAP

Risk Profiles

风险配置

Conservative:  SL=5%,  TP=12%, position=5%,  max 3 concurrent
Moderate:      SL=8%,  TP=20%, position=10%, max 5 concurrent
Aggressive:    SL=12%, TP=35%, position=20%, max 8 concurrent

Conservative:  SL=5%,  TP=12%, position=5%,  max 3 concurrent
Moderate:      SL=8%,  TP=20%, position=10%, max 5 concurrent
Aggressive:    SL=12%, TP=35%, position=20%, max 8 concurrent

Technical Reference: Available Indicators

技术参考:可用指标

Momentum Indicators

动量指标

IndicatorColumn NameDescription
RSI
rsi
Relative Strength Index (14)
Stochastic %K
stoch_k
Stochastic oscillator K line
Stochastic %D
stoch_d
Stochastic oscillator D line
Williams %R
willr
Williams %R (14)
CCI
cci
Commodity Channel Index (20)
MFI
mfi
Money Flow Index (14)
ROC
roc
,
roc_20
Rate of Change (10, 20)
MACD
macd
,
macd_signal
,
macd_hist
MACD line, signal, histogram
指标列名描述
RSI
rsi
相对强弱指数(14周期)
Stochastic %K
stoch_k
随机指标K线
Stochastic %D
stoch_d
随机指标D线
Williams %R
willr
威廉指标(14周期)
CCI
cci
商品通道指数(20周期)
MFI
mfi
资金流量指数(14周期)
ROC
roc
,
roc_20
变动率(10、20周期)
MACD
macd
,
macd_signal
,
macd_hist
MACD线、信号线、柱状图

Trend Indicators

趋势指标

IndicatorColumn NameDescription
SMA
sma9
,
sma21
,
sma50
,
sma100
,
sma200
Simple Moving Averages
EMA
ema9
,
ema21
,
ema50
,
ema100
,
ema200
Exponential Moving Averages
ADX
adx
Average Directional Index (trend strength)
+DI / -DI
plus_di
,
minus_di
Directional Indicators
指标列名描述
SMA
sma9
,
sma21
,
sma50
,
sma100
,
sma200
简单移动平均线
EMA
ema9
,
ema21
,
ema50
,
ema100
,
ema200
指数移动平均线
ADX
adx
平均趋向指数(衡量趋势强度)
+DI / -DI
plus_di
,
minus_di
趋向指标

Volatility Indicators

波动率指标

IndicatorColumn NameDescription
Bollinger Bands
bb_upper
,
bb_middle
,
bb_lower
Upper, middle, lower bands
BB Width
bb_width
Band width (volatility measure)
BB %B
bb_pct
Price position in BB range (0-1)
ATR
atr
Average True Range (14)
ATR %
atr_pct
ATR as % of price
指标列名描述
布林带
bb_upper
,
bb_middle
,
bb_lower
上轨、中轨、下轨
布林带宽度
bb_width
带宽(波动率指标)
布林带%b
bb_pct
价格在布林带区间内的位置(0-1)
ATR
atr
平均真实波幅(14周期)
ATR百分比
atr_pct
ATR相对于价格的百分比

Volume Indicators

成交量指标

IndicatorColumn NameDescription
Volume SMA
volume_sma
20-period volume average
Volume Ratio
volume_ratio
Current volume / average
OBV
obv
,
obv_sma
On-Balance Volume
指标列名描述
成交量均线
volume_sma
20周期成交量均线
成交量比率
volume_ratio
当前成交量与均线的比值
OBV
obv
,
obv_sma
能量潮指标

Price Position Indicators

价格位置指标

IndicatorColumn NameDescription
Rolling High
high_20
,
high_50
,
high_90
,
high_200
N-period high
Rolling Low
low_20
,
low_50
,
low_90
,
low_200
N-period low
Drawdown
drawdown
,
drawdown_50
% from rolling high
Price Position
price_position_90
Position in 90-day range (0-1)
Distance from MA
dist_sma50
,
dist_sma200
% distance from MA
指标列名描述
滚动高点
high_20
,
high_50
,
high_90
,
high_200
N周期高点
滚动低点
low_20
,
low_50
,
low_90
,
low_200
N周期低点
回撤幅度
drawdown
,
drawdown_50
相对于滚动高点的回撤百分比
价格位置
price_position_90
价格在90天区间内的位置(0-1)
与均线的距离
dist_sma50
,
dist_sma200
价格与均线的百分比距离

Derived / Change Indicators

衍生/变动指标

IndicatorColumn NameDescription
Price Change
price_change
,
price_pct_change
1-period change
Price Change 5
price_change_5
,
price_pct_change_5
5-period change
RSI Change
rsi_change
RSI momentum
MACD Change
macd_change
,
macd_hist_change
MACD momentum
Consecutive Up
consecutive_up
Count of consecutive up days
Consecutive Down
consecutive_down
Count of consecutive down days

指标列名描述
价格变动
price_change
,
price_pct_change
1周期变动
5周期价格变动
price_change_5
,
price_pct_change_5
5周期变动
RSI变动
rsi_change
RSI动量
MACD变动
macd_change
,
macd_hist_change
MACD动量
连续上涨天数
consecutive_up
连续上涨的天数
连续下跌天数
consecutive_down
连续下跌的天数

Technical Reference: Condition Syntax

技术参考:条件语法

1. Simple Comparisons

1. 简单比较

rsi<30              # RSI below 30
price>sma200        # Price above SMA 200
adx>=25             # ADX at least 25
bb_pct<0.2          # Price in lower 20% of BB range
drawdown<-20        # Down 20% from recent high
volume_ratio>2      # Volume 2x above average
rsi<30              # RSI低于30
price>sma200        # 价格高于SMA200
adx>=25             # ADX至少为25
bb_pct<0.2          # 价格位于布林带区间的下20%
drawdown<-20        # 较近期高点下跌20%
volume_ratio>2      # 成交量为均线的2倍以上

2. Crossover / Crossunder

2. 金叉/死叉

macd_crossover                  # MACD crosses above signal (default)
ema9_cross_above_ema21          # EMA9 crosses above EMA21
price_crossover_sma50           # Price crosses above SMA50
rsi_crossunder_50               # RSI crosses below 50
stoch_k_cross_above_stoch_d     # Stochastic golden cross
macd_crossover                  # MACD线上穿信号线(默认)
ema9_cross_above_ema21          # EMA9上穿EMA21
price_crossover_sma50           # 价格上穿SMA50
rsi_crossunder_50               # RSI下穿50
stoch_k_cross_above_stoch_d     # 随机指标金叉

3. Turning Points

3. 转折点

rsi_turning_up          # RSI starts increasing
macd_hist_turning_down  # MACD histogram starts decreasing
price_turning_up        # Price reversal upward
rsi_turning_up          # RSI开始上升
macd_hist_turning_down  # MACD柱状图开始下降
price_turning_up        # 价格反转向上

4. Consecutive Periods

4. 连续周期

rsi<30_for_3            # RSI below 30 for 3 consecutive periods
price>sma200_for_5      # Price above SMA200 for 5 periods
consecutive_up>=3       # At least 3 consecutive up days
rsi<30_for_3            # RSI连续3个周期低于30
price>sma200_for_5      # 价格连续5个周期高于SMA200
consecutive_up>=3       # 至少连续3天上涨

5. Combined Conditions

5. 组合条件

Conditions are comma-separated. Entry uses AND logic, Exit uses OR logic.
--entry "rsi<35,price<bb_lower,volume_ratio>1.5"
--exit "rsi>70,price>bb_upper"

条件使用逗号分隔。入场条件使用AND逻辑,出场条件使用OR逻辑。
--entry "rsi<35,price<bb_lower,volume_ratio>1.5"
--exit "rsi>70,price>bb_upper"

Important Guidelines

重要指南

  1. Never use single indicators - Always combine multiple dimensions
  2. Explain the logic - Users should understand WHY each indicator is included
  3. Match complexity to strategy - DCA needs valuation model, trend following needs multi-TF
  4. Be honest about limitations - Past performance ≠ future results
  5. Encourage iteration - Backtesting is a process, not a one-shot

  1. 绝不使用单一指标 - 始终结合多个维度
  2. 解释逻辑 - 用户应理解每个指标被纳入的原因
  3. 策略复杂度匹配 - DCA策略需要估值模型,趋势跟踪策略需要多时间周期确认
  4. 如实说明局限性 - 过往表现不代表未来结果
  5. 鼓励迭代 - 回测是一个持续优化的过程,而非一次性操作

⚠️ CRITICAL: Exchange Data Limits

⚠️ 关键:交易所数据限制

Different exchanges have different historical data limits!
ExchangeApproximate LimitNotes
OKX~60-90 daysDefault. Good for short-term backtests
KuCoin~200 daysGood alternative for medium-term
Binance1000+ daysMost data, but blocked in some regions
Bybit~200 daysGood alternative
If you need more than 90 days of data:
bash
undefined
不同交易所的历史数据限制不同!
交易所大致数据限制说明
OKX~60-90天默认选项。适合短期回测
KuCoin~200天适合中期回测的替代选项
Binance1000+天数据量最大,但部分地区无法访问
Bybit~200天优质替代选项
如需超过90天的历史数据:
bash
undefined

OKX default - will only get ~90 days even if you request 365

OKX默认选项 - 即使请求365天,也仅能获取约90天数据

python src/backtest.py --symbol BTC/USDT --days 365 ...
python src/backtest.py --symbol BTC/USDT --days 365 ...

Use KuCoin for ~200 days (works in most regions)

使用KuCoin获取约200天数据(多数地区可访问)

python src/backtest.py --symbol BTC/USDT --days 180 --exchange kucoin ...
python src/backtest.py --symbol BTC/USDT --days 180 --exchange kucoin ...

Use Binance for 365+ days (if accessible in your region)

使用Binance获取365+天数据(如果所在地区可访问)

python src/backtest.py --symbol BTC/USDT --days 365 --exchange binance ...

---
python src/backtest.py --symbol BTC/USDT --days 365 --exchange binance ...

---

File Locations

文件位置

  • Backtest engine:
    src/backtest.py
  • Smart DCA:
    src/smart_dca.py
  • Pair Trading:
    src/pair_trading.py
  • Output reports: current working directory
  • Generated code: current working directory
  • 回测引擎:
    src/backtest.py
  • 智能DCA:
    src/smart_dca.py
  • 配对交易:
    src/pair_trading.py
  • 输出报告:当前工作目录
  • 生成的代码:当前工作目录

Smart DCA Usage

智能DCA使用方法

For DCA strategies, use the dedicated Smart DCA script:
bash
python src/smart_dca.py \
  --symbol "BTC/USDT" \
  --days 1095 \
  --base-amount 200 \
  --frequency 7 \
  --output smart_dca_report.html \
  --lang zh  # or --lang en based on user's language
对于DCA策略,请使用专用的智能DCA脚本:
bash
python src/smart_dca.py \
  --symbol "BTC/USDT" \
  --days 1095 \
  --base-amount 200 \
  --frequency 7 \
  --output smart_dca_report.html \
  --lang zh  # or --lang en based on user's language

Pair Trading / Relative Strength Usage

配对交易 / 相对强度使用方法

For pair trading strategies that compare two assets (e.g., BTC vs ETH):
bash
python src/pair_trading.py \
  --symbol-a "BTC/USDT" \
  --symbol-b "ETH/USDT" \
  --days 365 \
  --timeframe 4h \
  --lookback 20 \
  --threshold 10 \
  --exit-threshold 2 \
  --output pair_trading_report.html \
  --lang zh  # or --lang en based on user's language \
  --description "Long the underperformer when BTC/ETH spread deviates"
Parameters:
  • --lookback
    : Period for calculating relative performance (default: 20)
  • --threshold
    : Entry threshold - spread deviation % to trigger entry (default: 10)
  • --exit-threshold
    : Exit threshold - spread deviation % to close position (default: 2)
对于比较两个资产的配对交易策略(如BTC vs ETH):
bash
python src/pair_trading.py \
  --symbol-a "BTC/USDT" \
  --symbol-b "ETH/USDT" \
  --days 365 \
  --timeframe 4h \
  --lookback 20 \
  --threshold 10 \
  --exit-threshold 2 \
  --output pair_trading_report.html \
  --lang zh  # or --lang en based on user's language \
  --description "Long the underperformer when BTC/ETH spread deviates"
参数说明:
  • --lookback
    : 计算相对表现的周期(默认:20)
  • --threshold
    : 入场阈值 - 价差偏离百分比,触发入场信号(默认:10)
  • --exit-threshold
    : 出场阈值 - 价差偏离百分比,触发出场信号(默认:2)

Language Support

语言支持

CRITICAL: Always detect the user's language and pass the appropriate
--lang
parameter:
  • User writes in Chinese →
    --lang zh
    (report in Chinese)
  • User writes in English →
    --lang en
    (report in English)
This ensures the generated HTML report matches the user's language preference.
关键:始终检测用户使用的语言,并传递相应的
--lang
参数:
  • 用户使用中文 →
    --lang zh
    (报告为中文)
  • 用户使用英文 →
    --lang en
    (报告为英文)
这能确保生成的HTML报告符合用户的语言偏好。