Backtesting Trading Strategies ๐
Introduction to Backtesting
Backtesting is the process of testing a trading strategy against historical price data to evaluate how it would have performed in the past. It is one of the most important steps in strategy development because it lets you measure profitability, risk, and robustness before risking real capital.
Pine Script's strategy engine replays historical data bar by bar, simulating trade entries, exits, position sizing, commissions, and slippage exactly as if you were trading live. On every historical bar, the engine:
- Receives the bar's OHLCV data.
- Evaluates your script's conditions.
- Submits any orders generated by
strategy.entry(),strategy.exit(), orstrategy.close(). - Fills pending orders against the bar's price action.
- Updates equity, drawdown, and all performance metrics.
Understanding this bar-by-bar execution model is critical. Your script never "sees" future bars -- it only has access to the current bar and all bars that came before it, just like real trading.
Basic Strategy Structure
Every Pine Script strategy starts with a strategy() declaration instead of indicator(). Here is a complete moving average crossover strategy:
//@version=5
strategy("MA Crossover Strategy", overlay=true, initial_capital=10000,
default_qty_type=strategy.percent_of_equity, default_qty_value=100)
// Input parameters
fastLen = input.int(10, "Fast MA Period", minval=1)
slowLen = input.int(20, "Slow MA Period", minval=1)
// Calculate moving averages
fastMA = ta.sma(close, fastLen)
slowMA = ta.sma(close, slowLen)
// Define entry conditions
longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)
// Execute trades
if longCondition
strategy.entry("Long", strategy.long)
if shortCondition
strategy.entry("Short", strategy.short)
// Plot moving averages on the chart
plot(fastMA, "Fast MA", color=color.blue, linewidth=2)
plot(slowMA, "Slow MA", color=color.red, linewidth=2)The strategy() declaration accepts many parameters that control how the backtester behaves. The most important ones are:
overlay-- whether the strategy is drawn on the price chart or in a separate pane.initial_capital-- the starting account balance for the simulation.default_qty_type-- how the default order size is interpreted (strategy.fixed,strategy.cash, orstrategy.percent_of_equity).default_qty_value-- the numeric value for the default order size.
Continue reading
Sign in or create a free account to unlock Backtesting Strategies and access the full academy.
Free account ยท No credit card required