Skip to content
AlgoVault

Guides/How to Backtest Pine Script Strategies on TradingView

Guide · 11 min read · Updated 2026-12-03

How to backtest Pine Script strategies without fooling yourself

A practical TradingView backtesting guide: avoid repainting, set realistic commission and slippage, read the Strategy Tester honestly, and validate on data you did not tune on.

Start from a backtest-honest template

The strategy() declaration is where most realism is set. This template uses percent-of-equity sizing, a commission, slippage in ticks, no pyramiding, and bar-close evaluation. Replace the cost numbers with your own instrument and broker.

backtest_template.pine
//@version=6
strategy("Backtest-honest template", 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,      // percent per side: use your broker's real fee
     slippage = 2,                 // in ticks: use your instrument's real spread/impact
     pyramiding = 0,
     calc_on_every_tick = false,   // evaluate on bar close, not every tick
     process_orders_on_close = false) // fill on the next bar open

fast = ta.ema(close, 20)
slow = ta.ema(close, 50)

// Only act on a confirmed bar so history and live trading agree
longSignal = barstate.isconfirmed and ta.crossover(fast, slow)
exitSignal = barstate.isconfirmed and ta.crossunder(fast, slow)

if longSignal
    strategy.entry("Long", strategy.long)
if exitSignal
    strategy.close("Long")

plot(fast, "Fast", color.teal)
plot(slow, "Slow", color.orange)

1. Avoid repainting and lookahead

A repainting script draws or trades differently in real time than it did in history. In a backtest this nearly always makes results look better than they were achievable. The common causes are below.

CauseWhat goes wrongFix
request.securityHigher-timeframe values for the current HTF bar are not final until that bar closes, but historical data shows the final value on every lower-timeframe bar.Use the previous HTF value (for example close[1]) with lookahead = barmerge.lookahead_on, or lookahead_off and act only after the HTF bar is confirmed.
ta.pivothigh / ta.pivotlowA pivot is only confirmed after the right-hand bars have printed, so it is reported late. Plotting it back at the pivot bar with a negative offset makes it look instant.Treat the pivot as known only at the confirmation bar. Never trade at the earlier bar.
Intrabar signalsA condition true mid-bar can be false by the close. On history only the final OHLC exists, so the test never sees the flicker.Gate signals with barstate.isconfirmed and keep calc_on_every_tick = false.
Future-leaking helpersUsing values like high or low of the current bar in the entry condition and filling at the open of the same bar.Decide on bar close, fill on the next bar open (the default for strategy orders).

The safe higher-timeframe pattern

htf_safe.pine
// Yesterday's confirmed daily close, available on every intraday bar of today
htfClose = request.security(syminfo.tickerid, "D", close[1], lookahead = barmerge.lookahead_on)

// Compare today's price with a value that was already final
aboveYesterday = close > htfClose

The offset [1] is what makes lookahead_on safe here: you are asking for the value that was already final, not the one still forming.

A quick repainting test: add the strategy to a chart, note the trades on the last 50 closed bars, let a few new bars form in real time (or use Bar Replay), then compare. If any past signal appeared, moved or vanished, the script repaints.

2. Use realistic commission and slippage

Costs matter more than most people expect, especially for frequent, small-edge systems. A strategy that earns slightly more than its costs per trade on paper can be negative after real fees, spread and slippage. TradingView models them with three settings:

  • commission_type and commission_value: percent of trade value, cash per order, or cash per contract. Match how your broker actually charges.
  • slippage: how many ticks worse than the signal price a market order fills. Use a higher number for illiquid symbols, fast markets and lower timeframes.
  • Spread: for forex and CFDs the quoted spread is a cost on both entry and exit. Fold it into slippage if the chart data is mid or bid only.

Fill assumptions

  • process_orders_on_close = false fills on the next bar open, which is what a bar-close signal can really achieve. Setting it to true fills at the signal bar close and is optimistic for most live setups.
  • Limit and stop orders are filled by TradingView using bar OHLC. Within one bar the order of the high and the low is unknown, so tight stop-and-target setups on large bars can show a different outcome than live. The bar magnifier option (availability depends on your TradingView plan) uses lower-timeframe data to improve this.
  • Cap leverage and position size. A backtest that sizes into an unrealistic share of the volume cannot be reproduced.

3. Read the Strategy Tester honestly

Do not stop at net profit. Look at how the profit was earned.

MetricWhat to look for
Total closed tradesEnough trades to be more than luck. Be sceptical of a few dozen or fewer.
Max drawdownCould you actually sit through that loss, in money and in time?
Profit factorGross profit divided by gross loss. A value barely above 1 leaves no margin for costs you did not model.
Average trade vs costAverage profit per trade should be clearly larger than commission plus slippage.
Largest winnerIf one trade is most of the profit, the strategy is one lucky event, not a system.
Long vs short splitA system that only works in one direction in a one-directional market is an exposure, not an edge.

4. Validate on data you did not tune on

  1. Split the data. Develop on the older portion. Reserve the most recent portion and do not look at it until the settings are final.
  2. Test other symbols. A rule that works on one chart only is more likely a coincidence than a market behaviour.
  3. Test across regimes. Include trending, ranging, high-volatility and low-volatility periods.
  4. Check parameter neighbourhoods. If changing a length from 20 to 22 destroys the result, you found noise.
  5. Forward test. Run the strategy on a paper account in real time for a while and compare live trades to what the backtest would have taken.

Pre-trade backtest checklist

  • Signals gated by a confirmed bar; no lookahead; pivots treated as late.
  • Commission and slippage set from real costs, and the result survives double costs.
  • Orders fill on the next bar open, not on the signal close.
  • Sizing is realistic and leverage is capped.
  • Enough trades across several regimes.
  • Out-of-sample and forward-test results broadly agree with the in-sample test.
  • You can explain in one sentence why the edge should exist.

Strategies you can use to practise

Every AlgoVault Pine strategy is built to this checklist: decisions on confirmed bar close, fills at the next open, no request.security lookahead, a commission and slippage placeholder in strategy() that you should replace with your own, and a plain-English guide listing each input and its default. They make convenient test subjects while you learn to read the Strategy Tester.

Not sure which style to start with? The strategy-style overview compares trend, momentum and mean-reversion families.

WaveTrend Oscillator Strategy Pack

Classic hlc3 EMA channel oscillator with WT1 / WT2 crosses inside the overbought and oversold bands.

Get the free starter

FAQ

Why does my Pine Script backtest look better than live trading?

The usual causes are repainting or lookahead (the test used information that was not available at the time), zero or unrealistic commission and slippage, optimistic fill assumptions, and parameters tuned to the same data used to judge them. Fix those four before trusting any equity curve.

What commission and slippage should I use in TradingView?

Use your broker's actual fee schedule and an honest estimate of the spread and market impact on the instrument and timeframe you trade. There is no universal number: liquid index futures, forex majors and small-cap crypto have very different costs. When unsure, test with higher costs than you expect and see if the strategy still holds up.

How many trades do I need for a meaningful backtest?

More is better, and there is no magic number. Results from only a handful of trades are dominated by luck. Aim for a sample that covers different market regimes (trend, range, high and low volatility) and treat any result from a few dozen trades or fewer as tentative.

Does calc_on_every_tick cause repainting?

It can. With calc_on_every_tick = true a strategy re-evaluates on every real-time tick, but historical bars only have OHLC, so live behaviour can differ from the historical test. Keeping it false and acting on confirmed bar closes makes live and historical results consistent.

More guides

Educational software, not financial advice. Nothing here is a recommendation to buy or sell any instrument. Backtests and simulations are hypothetical, leave out slippage, spreads and fees, and past or simulated performance does not guarantee future results. Trading leveraged products can lose more than your deposit.