How to Backtest a Pine Script Strategy in TradingView
Your Pine Script backtest looks great until it isn't. A step-by-step guide to the TradingView Strategy Tester, real metrics, and avoiding overfitting.
How to Backtest a Pine Script Strategy in TradingView
A strategy that "feels right" isn't the same as a strategy that's actually held up over time. Running a Pine Script backtest is the step that closes that gap — and the TradingView Strategy Tester will run the numbers on almost any rule set you can code, whether it's a strategy you wrote yourself or one you're evaluating from someone else.
This guide covers how to actually backtest a trading strategy in TradingView properly, what to look at once you have results, and the mistakes that quietly make a backtest lie to you.
Step 1: Get Your Script Into a Testable Format
The Strategy Tester only works with scripts declared as strategy(), not indicator(). If you're starting from an indicator someone shared, or one you built to plot signals, it needs to be converted first.
The difference is mostly in the declaration line and how entries are logged:
// Indicator version — just plots, no backtest data
//@version=5
indicator("My Signal", overlay=true)
buySignal = ta.crossover(ta.sma(close, 9), ta.sma(close, 21))
plotshape(buySignal, style=shape.triangleup, color=color.green)
// Strategy version — same logic, now backtestable
//@version=5
strategy("My Signal - Backtest", overlay=true, initial_capital=10000)
buySignal = ta.crossover(ta.sma(close, 9), ta.sma(close, 21))
sellSignal = ta.crossunder(ta.sma(close, 9), ta.sma(close, 21))
if buySignal
strategy.entry("Long", strategy.long)
if sellSignal
strategy.close("Long")
The logic (buySignal, sellSignal) doesn't need to change at all — only the wrapper around it does. This is worth knowing if you're testing someone else's public indicator: you can usually drop their exact condition logic straight into a strategy() shell without touching the underlying rules.
Step 2: Set Realistic Backtest Conditions
This is the step most people skip, and it's the one that decides whether your results mean anything. Pine Script defaults to a frictionless world — no commission, no slippage, unlimited fill size — which will always make a strategy look better than it will trade in reality.
Set these explicitly in your strategy() declaration:
strategy("My Signal - Backtest",
overlay=true,
initial_capital=10000,
default_qty_type=strategy.percent_of_equity,
default_qty_value=10,
commission_type=strategy.commission.percent,
commission_value=0.05,
slippage=2)
commission_value— match this to what you'd actually pay per trade on your broker or exchange. Even a small commission compounds heavily across hundreds of trades.slippage— measured in ticks; accounts for the gap between your intended fill price and your actual one, which matters more on fast-moving or lower-liquidity symbols.default_qty_type/default_qty_value— decide whether you're sizing as a fixed contract count, a fixed cash amount, or a percentage of equity, and be consistent with how you'd actually size live.
Skipping this step is the single most common reason a backtest looks profitable and a live version doesn't.
Step 3: Run It in the TradingView Strategy Tester
Open the Strategy Tester panel at the bottom of the chart — this is TradingView's built-in backtesting engine, and where every result from here on comes from. Four tabs matter:
- Overview — the quick visual: equity curve, net profit, and drawdown over time. Useful for a gut check, not for a real verdict.
- Performance Summary — the actual numbers: net profit, profit factor, max drawdown, win rate, average trade, Sharpe ratio.
- List of Trades — every individual entry and exit. Worth scanning manually for anything that looks like an edge case or an obviously bad fill.
- Properties — confirms the settings you actually tested with (capital, commission, slippage), which is worth double-checking before you trust any of the other tabs.
Step 4: Know Which Metrics Actually Matter
Net profit is the number everyone looks at first, and it's the least useful one on its own. A strategy can show a large net profit from one lucky outlier trade and still be a bad strategy. Look at these instead:
- Profit factor — gross profit divided by gross loss. Above 1 is technically profitable; most traders want to see comfortably above 1.5 before taking a strategy seriously.
- Max drawdown — the largest peak-to-trough equity decline during the test. This is the number that tells you what it would actually feel like to trade this live, and it's the one people underestimate.
- Win rate — useful, but only in context. A 35% win rate with a strong average win/loss ratio can outperform a 65% win rate with poor risk/reward.
- Number of trades — a backtest with 15 trades over three years isn't a statistically meaningful sample, no matter how good the other numbers look. A few hundred trades is a much safer floor before drawing conclusions.
- Average trade — net profit divided by number of trades. If this number is smaller than your commission and slippage assumptions, the edge may not survive real-world friction.
Step 5: Watch for the Traps
A backtest can pass every metric above and still be misleading. The usual culprits:
- Repainting logic. If any part of your condition references the current, unclosed bar's
closeor a function that recalculates on historical bars differently than it does live, your backtest is testing a version of the strategy that couldn't have existed at the time. Anchor signals to confirmed, closed-bar values. - Look-ahead bias. Related but distinct — this happens when a script accidentally uses information that wouldn't have been available yet at that point in time (common with certain higher-timeframe
request.security()calls that aren't configured correctly). - Overfitting. If you've tuned five different input parameters until the backtest looks great on one specific symbol and timeframe, you've likely fit the strategy to noise in that exact dataset rather than found a real edge. Test across multiple symbols and time periods before trusting it.
- Ignoring the sample period. A backtest run only over a strong trending market will make a trend-following strategy look far better than it is. Test across at least one full range-bound period and one volatile period, not just the friendliest stretch of data you can find.
- Survivorship and data quality issues. Less common on major pairs and large-cap symbols, but worth a sanity check on thinly traded instruments where historical data can have gaps or errors.
Step 6: Out-of-Sample and Walk-Forward Testing
Once a strategy looks solid on your main dataset, split your data and test it on a period you haven't looked at yet — commonly by holding back the most recent 20–30% of your history and not tuning anything against it. This is often called out-of-sample testing, and a more rigorous version of the same idea — repeating it across several rolling windows of data — is known as walk-forward testing. If performance holds up on data the strategy (and you) never saw during development, that's a meaningfully stronger signal than a single backtest run. If it falls apart, that's usually a sign of overfitting rather than bad luck.
What Backtesting Doesn't Tell You
A clean backtest confirms the logic is sound on historical data — it doesn't confirm the alert will fire correctly, that the payload will reach an execution system, or how the strategy behaves with real order fills instead of simulated ones. Once you're satisfied with what you're seeing here, turning that same logic into a live, alert-driven strategy is a separate step with its own set of things to get right — worth treating as its own checklist rather than assuming a good backtest guarantees a clean live run.
Route your alerts to every MT5 account.
Per-account risk, trading windows and session rules, from a single TradingView alert.
Keep reading

TradingView Alert Not Working? Find the Point Where the Signal Died
Your alert fired and no trade appeared. Work down the five points where a TradingView signal dies before it reaches MT5, symptom first.

Do You Need a VPS for Automated MT5 Trading? What Always-On Actually Requires
Automated MT5 trading needs a terminal that never closes. Why that means Windows, when MetaTrader's own VPS is enough, and what to check before buying.

From Pine Script Indicator to Live Automated Strategy: A Practical Guide
Turn a Pine Script indicator into a strategy that emits an executable alert, then route it to MetaTrader 5. Syntax, the alert call, and what breaks.