Skip to main content

Backtest Strategy

Type: backtest_strategy β€’ Category: flow β€’ Tags: backtest, trading, strategy, finance, risk, walk-forward, optimization

Description​

High-performance strategy backtesting with comprehensive statistics

Parameters​

NameTypeDescriptionRequiredDefault
datastringOHLC data from upstream worker (e.g., {{workers[1].[result]}})yes
signalsstringTrading signals with time and action (long/short/close)yes
initial_capitalnumberStarting capitalno10000
commissionnumberCommission per trade (0.001 = 0.1%)no0.001
slippagenumberSlippage (0.0005 = 0.05%)no0.0005
time_fieldstringTimestamp field name. Supports Unix timestamps (seconds/ms), ISO strings, or datetime objects.no"time"
open_fieldstringOpen price field name. Used for entry price when signal triggers at bar open.no"open"
high_fieldstringHigh price field name. Used for take profit hit detection - the highest price in each bar determines if TP was triggered.no"high"
low_fieldstringLow price field name. Used for stop loss hit detection - the lowest price in each bar determines if SL was triggered.no"low"
close_fieldstringClose price field name. Used for position valuation, trailing stop updates, and exits at bar close.no"close"
ai_optimizebooleanπŸ€– AI Find Best Strategy - Automatically analyze data volatility and test all parameter combinations to find optimal settings. No configuration needed!nofalse
ai_optimize_targetstringMetric to optimize forno"sharpe_ratio"
ai_sl_tp_typestringSL/TP calculation type: percent (% of price), fixed (price units/pips), atr (ATR multiples)no"percent"
ai_show_trades_fornumberShow detailed trades for which result (1-N). Change this to see trades for different top results.no1
ai_top_results_countnumberHow many top results to include in output (1-50). More results = more data to compare.no10
position_size_typestringHow to calculate position sizeno"percent"
position_sizenumberPosition size value (0.1 = 10% for percent type)no0.1
stop_loss_typestringStop loss calculation methodno"percent"
stop_loss_valuenumberStop loss value (2.0 = 2% for percent type)no2
take_profit_typestringTake profit calculation methodno"percent"
take_profit_valuenumberTake profit value (4.0 = 4% for percent type, or 3.0 = 1:3 RR)no4
trailing_stopbooleanEnable trailing stopnofalse
trailing_stop_valuenumberTrailing stop distance in %no1
analysis_blocksnumberSplit data into N blocks for consistency analysis (0=disabled, recommended: 4, 6, or 12)no0
max_hold_durationstringMax position hold time (e.g., '30m', '2h', '1d'). Leave empty to disable.no""
close_at_timestringClose all positions at specific time daily (e.g., '16:00', '8pm'). Leave empty to disable.no""
close_at_time_offsetnumberUTC offset in hours for time settings (e.g., -5 for EST, 1 for CET)no0
trading_window_startstringOnly open positions after this time (e.g., '9:30', '9am'). Leave empty for no restriction.no""
trading_window_endstringOnly open positions before this time (e.g., '15:30', '3pm'). Leave empty for no restriction.no""
optimize_slstringStop loss range to optimize (e.g., '1-5:0.5' or '1,2,3,4'). Leave empty for no optimization.no""
optimize_tpstringTake profit range to optimize (e.g., '2-10:1' or '2,4,6,8'). Leave empty for no optimization.no""
optimize_sizestringPosition size range to optimize (e.g., '0.05-0.2:0.05'). Leave empty for no optimization.no""
optimize_targetstringMetric to optimize for when running parameter optimizationno"total_return"

Help​

Backtest Strategy

A high-performance, license-free backtesting engine for evaluating trading strategies. Built with pure numpy for maximum speed - no GPL dependencies (unlike vectorbt/backtrader).


⚑ Key Advantages​

Performance​

  • Vectorized numpy operations - processes 100k+ bars in milliseconds
  • O(1) signal lookup using hashmap for instant bar matching
  • Memory optimized with __slots__ and contiguous arrays
  • No external dependencies - only numpy (BSD) and pandas (BSD)

License-Safe​

  • 100% BSD/MIT licensed - safe for commercial use
  • No GPL contamination - unlike vectorbt, backtrader, zipline
  • No attribution required - use freely in paid products

Unique Features​

  • Block Analysis - Walk-forward validation with consistency scoring
  • Trading Window - Restrict entry times (market hours only)
  • Time-Based Exits - Auto-close at specific times or after duration
  • Flexible Field Mapping - Works with any OHLC data format

Complete Risk Management​

  • Multiple position sizing methods (percent, fixed, risk-based)
  • Stop loss & take profit (percent, ATR, fixed, R:R ratio)
  • Trailing stops with customizable distance
  • Commission and slippage modeling

Professional Statistics​

  • Risk-adjusted returns (Sharpe, Sortino, Calmar)
  • Drawdown analysis (max DD, duration, recovery)
  • Trade breakdown by direction and exit reason
  • Equity & drawdown curves for visualization

πŸ“₯ Inputs​

OHLC Data​

Connect data with time, open, high, low, close fields. Sources: postgres_sql, fetch_ohlc, fetch_csv, or any worker returning OHLC data.

Use the field dropdowns to select the correct columns from your data:

  • time_field: Timestamp column (Unix seconds/ms, ISO string, or datetime)
  • open_field: Entry price when signal triggers at bar open
  • high_field: Used for take profit hit detection (highest price in bar)
  • low_field: Used for stop loss hit detection (lowest price in bar)
  • close_field: Position valuation, trailing stops, and bar close exits

Signals​

List of trading signals with:

  • time: Timestamp (Unix, ISO string, or datetime)
  • action: "long", "short", or "close"
  • size (optional): Override position size for this signal

πŸ’° Position Sizing​

TypeDescriptionExample
percentUse X% of capital per trade0.1 = 10% of capital
fixedFixed dollar amount1000 = $1000 per trade
risk_basedSize based on stop loss distance0.02 = risk 2% per trade

Risk-based sizing automatically calculates position size so that if stopped out, you lose exactly X% of capital. Professional money management!


πŸ›‘οΈ Risk Management​

Stop Loss Types​

TypeDescriptionExample
percentDistance as % of entry price2.0 = 2% below entry
atrMultiple of ATR(14)1.5 = 1.5x ATR
fixedFixed price distance5.0 = $5 from entry

Take Profit Types​

TypeDescriptionExample
percentDistance as % of entry price4.0 = 4% above entry
atrMultiple of ATR(14)3.0 = 3x ATR
rr_ratioRisk:Reward ratio3.0 = 1:3 (3x stop distance)
fixedFixed price distance10.0 = $10 from entry

Trailing Stop​

When enabled, stop loss follows price movement:

  • Long: Stop moves up as price rises (never down)
  • Short: Stop moves down as price falls (never up)
  • Distance: trailing_stop_value in percent

⏰ Time-Based Rules​

Max Hold Duration​

Close positions after a specific time period:

max_hold_duration: "30m"  β†’ 30 minutes
max_hold_duration: "2h" β†’ 2 hours
max_hold_duration: "1d" β†’ 1 day

Use cases: Scalping, momentum strategies, avoiding overnight gaps

Close At Time​

Close all positions at a specific time daily:

close_at_time: "16:00"           β†’ 4:00 PM
close_at_time: "8pm" β†’ 8:00 PM
close_at_time_offset: -5 β†’ EST timezone

Use cases: Day trading, avoiding after-hours, market close exits

Trading Window​

Only allow new positions during specific hours:

trading_window_start: "9:30"     β†’ Market open
trading_window_end: "15:30" β†’ 30 min before close
close_at_time_offset: -5 β†’ EST timezone

Examples:

MarketStartEndOffset
US Stocks9:3016:00-5
US Futures18:0017:00-5
London Forex8:0016:000
Asian Session0:009:009

Note: Overnight windows are supported (end < start).


πŸ€– AI Find Best Strategy​

One-click optimization! Let AI automatically find the best parameters for your strategy.

How to Use​

  1. Configure only: data, signals, OHLC field mappings, initial_capital, commission, slippage
  2. Check the "πŸ€– AI Find Best Strategy" checkbox
  3. Select your optimization target (sharpe_ratio recommended)
  4. Run the backtest

That's it! All other parameters will be hidden - AI determines everything automatically!

What AI Does​

  1. Analyzes your data's volatility:

    • Average bar price change %
    • 95th percentile price change
    • Detects timeframe (tick/intraday/hourly/daily)
    • Adjusts parameters based on volatility
  2. Auto-determines parameter types:

    • Stop Loss Type: percent (universal)
    • Take Profit Type: percent (universal)
    • Position Size Type: percent (universal)
  3. Calculates smart ranges based on volatility:

    ParameterHow Range is Calculated
    Stop Loss0.5x to 3x average bar change
    Take Profit1x to 5x average bar change
    Position Size5% - 25% of capital
    Trailing StopDisabled, tight, normal, wide (based on volatility)
    Max Hold DurationBased on detected timeframe (5min-2weeks)
  4. Tests all combinations (up to 600) and finds optimal settings

  5. πŸ”„ Recursive Search - If best result is unprofitable, AI automatically:

    • Expands parameter ranges (tighter AND wider)
    • Increases granularity (more test values)
    • Tries up to 3 additional searches
    • Compares results and returns the best
  6. Runs full backtest with optimal parameters to get detailed trade data for charting

πŸ”„ Recursive Search (Auto-Retry)​

If the best strategy found is losing money or has negative Sharpe ratio, AI doesn't give up! It automatically expands the search with wider parameter ranges:

AttemptSL/TP Range ExpansionTest Values
Initial1.0x (baseline)5-7 values
Retry 11.5x wider + tighter7-9 values
Retry 22.0x wider + tighter9-11 values
Retry 32.5x wider + tighter11-13 values

Trigger conditions:

  • total_return &lt; 0% (losing money)
  • sharpe_ratio &lt; 0 (negative risk-adjusted return)
  • sharpe_ratio &lt; 0.3 AND return &lt; 2% (poor results)

Output includes:

"recursive_search": {
"performed": true,
"depth": 2,
"max_depth": 3,
"reason": "Searched 2 additional time(s) for better parameters",
"improved": true
}

Recommendations will show:

  • πŸ”„ AI performed 2 additional search(es) with expanded parameter ranges
  • ⚠️ Strategy remains unprofitable even after exhaustive search. Consider revising signal logic.

πŸ” Verify Top 10 Results​

Want to verify that calculations are correct for any of the top 10 results? Use the ai_show_trades_for parameter!

How to use:

  1. Run AI optimization normally
  2. Look at top_10 array - you'll see 10 best results with different parameters
  3. Change ai_show_trades_for to any number 1-10
  4. Re-run the worker
  5. Now trades, trades_summary, equity_curve, drawdown_curve will show data for that specific result

Example workflow:

Step 1: ai_show_trades_for = 1 (default)
β†’ See trades for best result (#1)

Step 2: ai_show_trades_for = 5
β†’ See trades for 5th best result
β†’ Compare equity curve, verify calculations

Step 3: ai_show_trades_for = 10
β†’ See trades for 10th result
β†’ Understand why it ranked lower

Output includes info about which result is shown:

"showing_trades_for": {
"rank": 5,
"parameters": {
"stop_loss": 1.2,
"take_profit": 3.6,
"position_size": 0.15,
"trailing_stop": true
},
"results": {
"total_return_pct": 8.5,
"sharpe_ratio": 0.85,
"win_rate": 52.3,
"total_trades": 127
},
"note": "Change 'ai_show_trades_for' parameter (1-10) to see trades for different top results"
}

This allows you to:

  • βœ… Verify calculations are correct for each strategy
  • βœ… Compare equity curves between different parameter sets
  • βœ… Visualize trades on chart for any top 10 result
  • βœ… Understand why certain parameters rank higher/lower

AI Output​

  • data_analysis: Full volatility analysis with detected timeframe
  • auto_determined_types: Explains why AI chose percent types
  • best_parameters: Optimal settings ready to use (copy-paste!)
  • best_results: Summary statistics for optimal configuration
    • initial_capital: Starting capital
    • final_capital: Ending capital after all trades
    • total_return_pct: Percentage return
    • total_return_value: Absolute return in currency
    • max_drawdown_pct: Maximum drawdown as percentage
    • max_drawdown_value: Maximum drawdown in currency
  • recommendations: Actionable insights about your strategy
  • top_10: Top 10 performing parameter combinations (with all metrics)
  • trades: Full list of all trades with entry/exit details for charting
  • trades_summary: Breakdown of trades by type and exit reason
  • equity_curve: Equity over time for charting
  • drawdown_curve: Drawdown over time for charting
  • ranges_tested: Shows what ranges AI tested based on volatility
  • statistics: Distribution of results across all tests
  • recursive_search: Info about recursive search attempts

Trade Details (for charting)​

Each trade in the trades array includes:

FieldDescription
entry_timeWhen position was opened (ISO timestamp)
exit_timeWhen position was closed (ISO timestamp)
directionlong or short
entry_pricePrice at entry
exit_pricePrice at exit
stop_lossStop loss price level
take_profitTake profit price level
sizePosition size / lots
profitProfit/loss in currency
profit_pctProfit/loss as percentage
exit_reasonstop_loss, take_profit, signal, trailing_stop, max_duration
bars_heldNumber of bars position was held
commissionCommission paid for this trade

Example Output​

{
"ai_optimization": true,
"message": "πŸ€– AI analyzed 280 combinations based on your data's volatility...",
"best_parameters": {
"stop_loss_value": 0.9,
"take_profit_value": 2.7,
"position_size": 0.15,
"trailing_stop": true,
"rr_ratio": 3.0
},
"trades": [
{
"entry_time": "2024-01-15T09:30:00+00:00",
"exit_time": "2024-01-15T14:22:00+00:00",
"direction": "long",
"entry_price": 150.25,
"exit_price": 154.31,
"stop_loss": 148.90,
"take_profit": 154.31,
"size": 66,
"profit": 267.96,
"profit_pct": 2.7,
"exit_reason": "take_profit",
"bars_held": 58
}
],
"trades_summary": {
"total_trades": 127,
"winning_trades": 74,
"losing_trades": 53,
"exits_by_tp": 48,
"exits_by_sl": 45,
"exits_by_trailing": 26
},
"equity_curve": [...],
"drawdown_curve": [...]
}

πŸ” Manual Parameter Optimization​

For advanced users who want full control over parameter ranges.

How to Use​

Fill in the optimization range fields:

  • optimize_sl: Stop loss values to test
  • optimize_tp: Take profit values to test
  • optimize_size: Position size values to test (optional)

Range Format​

FormatExampleResult
Single value2[2.0]
List1,2,3,4[1.0, 2.0, 3.0, 4.0]
Range1-5[1.0, 2.0, 3.0, 4.0, 5.0]
Range with step1-5:0.5[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

Examples​

Test SL from 1% to 3%, TP from 2% to 6%:

optimize_sl: "1-3:0.5"     β†’ [1.0, 1.5, 2.0, 2.5, 3.0]
optimize_tp: "2-6:1" β†’ [2.0, 3.0, 4.0, 5.0, 6.0]
optimize_target: "sharpe_ratio"

This tests 5 Γ— 5 = 25 combinations.

Test specific values:

optimize_sl: "1,1.5,2,2.5,3"
optimize_tp: "3,4,5,6"
optimize_size: "0.05,0.1,0.15,0.2"

This tests 5 Γ— 4 Γ— 4 = 80 combinations.

Optimization Targets​

TargetDescription
total_return(Default) Maximum profit
sharpe_ratioBest risk-adjusted return
profit_factorHighest gross profit / gross loss
win_rateHighest winning percentage
expectancyBest expected value per trade
sortino_ratioBest downside risk-adjusted return

Output​

The optimization returns:

  • best_parameters: Optimal SL, TP, position size, and R:R ratio
  • best_results: Performance metrics for best combination
  • top_10: Top 10 performing combinations
  • heatmap: Data for SL vs TP heatmap visualization
  • statistics: Distribution of results across all tests

Limits​

Maximum 1000 combinations per optimization to prevent excessive computation.


πŸ“Š Block Analysis (Walk-Forward Validation)​

Divide your backtest into N blocks to validate strategy consistency. This helps detect overfitting - a robust strategy should perform similarly across all periods.

analysis_blocks: 6  β†’ Split data into 6 equal periods

Why Use Block Analysis?​

  • Detect overfitting: Strategy that works only in one period is likely curve-fitted
  • Validate robustness: Consistent profits across all blocks = reliable strategy
  • Walk-forward simulation: Each block is like a forward test

Consistency Score (0-100)​

ScoreRatingMeaning
80-100⭐ ExcellentStrategy works consistently across all periods
60-80βœ… GoodMinor variations, generally reliable
40-60⚠️ ModerateNotable differences, needs review
20-40❌ PoorLikely overfitted to specific periods
0-20🚫 Very PoorStrategy fails in multiple periods

Block Output​

Each block includes:

  • Start/end dates
  • Total return & trades
  • Win rate & profit factor
  • Sharpe ratio

πŸ“ˆ Output Metrics​

Summary Statistics​

MetricDescription
total_returnTotal profit/loss in currency
total_return_pctTotal return as percentage
annual_returnAnnualized return
sharpe_ratioRisk-adjusted return (volatility)
sortino_ratioRisk-adjusted return (downside only)
calmar_ratioReturn / Max Drawdown

Risk Metrics​

MetricDescription
max_drawdownLargest peak-to-trough decline
max_drawdown_durationLongest recovery period
volatilityAnnualized standard deviation
win_ratePercentage of winning trades
profit_factorGross profit / Gross loss
expectancyAverage expected profit per trade

Trade Analysis​

FieldDescription
total_tradesNumber of completed trades
avg_win / avg_lossAverage winning/losing trade
best_trade / worst_tradeExtremes
avg_bars_heldAverage holding period
statistics_by_directionSeparate stats for long/short
exit_analysisBreakdown by exit reason

Visualizations​

OutputDescription
equity_curveCapital over time (for charting)
drawdown_curveDrawdown over time
tradesFull trade list with details

πŸ”§ Complete Parameter Reference​

Required​

ParameterTypeDescription
datastringOHLC data from upstream worker
signalsstringTrading signals array

Capital & Sizing​

ParameterDefaultDescription
initial_capital10000Starting capital
position_size_typepercentpercent, fixed, or risk_based
position_size0.1Size value (0.1 = 10% for percent)

Costs​

ParameterDefaultDescription
commission0.001Per-trade commission (0.1%)
slippage0.0005Slippage (0.05%)

Risk Management​

ParameterDefaultDescription
stop_loss_typepercentpercent, atr, or fixed
stop_loss_value2.0Stop loss distance
take_profit_typepercentpercent, atr, rr_ratio, or fixed
take_profit_value4.0Take profit distance
trailing_stopfalseEnable trailing stop
trailing_stop_value1.0Trailing distance (%)

Time Rules​

ParameterDefaultDescription
max_hold_duration""Max hold time (30m, 2h, 1d)
close_at_time""Daily close time (16:00, 8pm)
close_at_time_offset0UTC offset in hours
trading_window_start""Entry window start (9:30)
trading_window_end""Entry window end (15:30)

Advanced​

ParameterDefaultDescription
time_fieldtimeTimestamp field name
open_fieldopenOpen price field
high_fieldhighHigh price field
low_fieldlowLow price field
close_fieldcloseClose price field
analysis_blocks0Block analysis (4, 6, or 12)

AI Optimization​

ParameterDefaultDescription
ai_optimizefalseπŸ€– Enable AI auto-optimization
ai_optimize_targetsharpe_ratioMetric for AI to optimize
ai_sl_tp_typepercentSL/TP type: percent (%), fixed (pips/price), atr (ATRΓ—)
ai_top_results_count10How many top results to include (1-50)
ai_show_trades_for1Show trades for which result (1-N). Change to verify different results!

Manual Optimization​

ParameterDefaultDescription
optimize_sl""SL range (e.g., "1-3:0.5" or "1,2,3")
optimize_tp""TP range (e.g., "2-6:1" or "2,4,6")
optimize_size""Position size range (e.g., "0.05-0.2:0.05")
optimize_targettotal_returnMetric to maximize