How to backtest a strategy in TradingView before you automate it
A TradingView backtest runs a Pine Script strategy over the chart's history and records every trade it would have taken. It's the cheapest place to find out whether your rules do what you think they do. It can't tell you what the market will do next, and its results depend heavily on settings most people never open.
This guide covers how to run one, which settings keep it honest, how to read the report, and where a backtest and a live account part ways. The last section connects the same strategy to Autoview. Autoview takes a webhook from whatever sent it and places the order, so a tested TradingView strategy is one of many ways to drive it.
TradingView facts on this page come from its Pine v6 Strategies manual and Help Center, all checked October 4, 2026.
What a TradingView backtest is
Any script that starts with strategy() instead of indicator() can simulate trades. TradingView's manual describes strategies as scripts that "simulate trades across historical and realtime bars, allowing users to backtest and forward test their trading systems." The historical part is the backtest. Letting the strategy keep running as new bars arrive is the forward test.
The trades come from TradingView's broker emulator, not from an exchange. By default it fills orders using only the chart's own bars, which means it has to make assumptions about what happened inside each bar. Most of this guide is about those assumptions. If you're new to the strategy() declaration itself, Pine Script basics covers the syntax first.
Run your first backtest
- Open a chart on a standard bar or candle type. The manual warns that non-standard charts such as Heikin Ashi or Renko use synthetic prices, which typically produce unrealistic results.
- Add a strategy. Pick a built-in, published, or personal one from the chart's menu of indicators and strategies, or write your own in the Pine Editor and click Add to chart.
- The strategy marks its trades on the chart and opens a strategy report in a tab in the bottom panel.
- Open the strategy's Settings, then the Properties tab, and set the values in the next section before reading a single number.
If you need a script to start with, Pine Script strategy alerts has a small moving-average strategy you can paste in. The settings below apply to it like any other.
Settings that keep the test honest
Every value in the Properties tab maps to an argument of strategy(). TradingView's Strategy properties article lists them. If you set them in the code, they become the defaults anyone running the script sees, and anyone can still change them in the Properties tab.
| Setting | Default | What to do with it |
|---|---|---|
Initial capital (initial_capital) | 1,000,000 | Set it to roughly the amount you'll actually trade. Percentage sizing and margin calls both depend on it. |
Order size (default_qty_type, default_qty_value) | Set per script | Choose a fixed quantity, a cash amount, or a percentage of equity. An explicit qty on an order call overrides it. |
Commission (commission_type, commission_value) | None | Enter your venue's fee as a percent, per contract, or per order. TradingView applies it on both entry and exit. |
Slippage (slippage) | 0 ticks | Add a few ticks to market and stop fills. The Help Center says it can also stand in for the spread. |
Pyramiding (pyramiding) | 1 | Leave it at 1 unless the strategy is meant to add to a position. It only limits strategy.entry() orders. |
Margin (margin_long, margin_short) | 100, or 1:1 | Match the leverage you'd really use. The manual calls a 0% margin "extremely misleading." |
Limit order check (backtest_fill_limits_assumption) | 0 ticks | Raise it to require price to trade through a limit before it counts as filled. |
Here's what those look like set in code. The numbers are placeholders, so swap in your own capital and your venue's fee schedule:
//@version=6
strategy(
"My strategy", overlay = true, initial_capital = 1000,
default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
commission_type = strategy.commission.percent, commission_value = 0.1,
slippage = 2, pyramiding = 1, margin_long = 100, margin_short = 100
)The manual shows why this matters. In its own commission example, adding a 1% commission to the same strategy on the same data visibly cut net profit and deepened the maximum drawdown. A report with zero fees is describing a market you can't trade in.
Slippage needs a lighter hand. The manual says real slippage is "dynamic and unpredictable, making it impossible to simulate precisely," and that too much simulated slippage can push fills outside the candle and make results look unrealistically bad. A small fixed amount is the goal.
How orders fill inside a bar
Two more settings decide when and where the emulator fills an order:
- Fill timing. By default a strategy runs once when each bar closes and fills its orders at the next bar's open. The Order execution delay input, or
process_orders_on_close = true, lets an order fill at the close of the bar that created it instead. The tutorial's repainting and fills section covers this trade-off. - The path inside the bar. On history, the emulator only knows four prices for each bar: the open, the close, the high and the low. If the open is closer to the high, it assumes price went to the high first, then the low. If the open is closer to the low, it assumes the low came first. A stop and a target on the same bar can resolve the wrong way under that guess.
Bar Magnifier replaces the guess with lower-timeframe data. Turn it on with the High option in the strategy's bar detail settings, or with use_bar_magnifier = true. Per the Help Center, a 60-minute chart reads 10-minute bars and a daily chart reads 60-minute bars. It can't request more than 200,000 lower-timeframe bars, so the oldest trades on a long history may still use the guess. The Pine manual lists this higher bar detail for users on Premium and Ultimate plans.
Testing further back
A normal backtest only covers the bars loaded on your chart. TradingView's Deep Backtesting runs the strategy on all available history for the symbol instead. The Help Center lists it for Premium and higher plans, with a limit of two million bars and one million trades.
To use it, pick a testing period at the top of the strategy report. Deep Backtesting starts on its own and shows a pink icon. Its results appear only in the report, not on the chart. After you edit the script, click Update report, and click Reset to chart session to go back.
One related limit from the manual: on the default range, the Trades list keeps only the latest 9,000 trades. Deep Backtesting keeps all of them. The totals on the Metrics tab are unaffected either way.
Reading the strategy report
The report has two main views. Metrics holds the summary and Trades lists the simulated trades one by one. You can switch between them with the icons in its top-left corner.
Key stats sits at the top of Metrics. It shows total profit or loss, maximum drawdown, profitable trades out of closed trades, and profit factor. Read them together. A high share of winners means little next to a drawdown you couldn't sit through, and a large total can come from a handful of trades.
Further down, a few sections answer specific questions:
- Return details puts the strategy next to a buy-and-hold line over the same range. If simply holding did about as well, the rules may not be adding much.
- Trades analysis shows the spread of trade results, the largest single win and loss, and the average bars per trade.
- Equity run-ups and drawdowns shows how long the losing stretches lasted, not just how deep they went.
- Capital efficiency counts margin calls. Any margin call in a backtest is worth understanding before real leverage is involved.
Then open the Trades tab and check a few trades by hand. Find each one on the chart and confirm the entry and exit happened where your rules say they should. The Signal column shows each order's name or comment, which helps when a strategy has several entry rules.
None of these numbers predicts future results. A backtest tells you how a fixed set of rules would have behaved on one past dataset under the emulator's assumptions. Its best use is catching rules that don't do what you meant.
Where a backtest and live trading differ
TradingView's repainting page defines the core problem: a script that calculates differently on historical bars than on realtime ones. These are the forms that matter most for a strategy:
- Recalculating on every tick. With
calc_on_every_tick = true, a strategy runs on every live price update but only once per bar on history. The manual says such strategies "will most probably not generate the same order executions, and so repaint." The Help Center adds that tick data is lost when the chart refreshes. - Lookahead on historical bars. Running a strategy again after each fill with
calc_on_order_fillscan let it see the rest of a historical bar it shouldn't know yet. Arequest.security()call with lookahead on and no one-bar offset pulls future higher-timeframe values into history. Combining conditions on two symbols shows the safe pattern. - Fills. On history, a market order fills at a known open price. Live, it fills wherever the book is when your order arrives, after the alert, the webhook, and the exchange have each taken their turn.
- Fees and slippage. The backtest uses one fixed fee and one fixed slippage figure. Your venue charges what it charges, and slippage changes with liquidity.
- Fills at the close. If you use
process_orders_on_close, the manual notes that in markets with sessions the alert still fires after the session ends, so a real order may not fill until the market reopens.
This is why forward testing matters. A strategy that keeps behaving the same on new bars as it did in history is one you understand better, even before any money is involved.
From backtest to automation
A backtest places no real orders. To trade the same rules, you have TradingView fire an alert each time the strategy fills an order and send that alert to your Autoview webhook. The manual notes that these order fill alerts fire right away, whatever the script's execution settings, and calls them "often more suitable for sending alerts to third parties for automation."
The alert's message has to be an Autoview command. You have two ways to build it from the strategy:
- Placeholders. Write one command with
{{strategy.order.action}}and{{strategy.order.contracts}}filling in the side and size. Pine Script strategy alerts walks through it, including the exact Create Alert steps. - alert_message. Give each order call its own full command with the
alert_messageargument, and put{{strategy.order.alert_message}}in the alert's message. Pine Script alert_message covers which calls accept it.
Then test the live chain before it touches money:
- Add
d=1to the command so Autoview logs what it would do without placing the order. - Point the webhook at a demo or testnet connection, such as Binance testnet or an OANDA practice account, and let a few real demo orders land.
- Compare each order in your Autoview log with the trade the strategy report shows for the same bar.
How to test and debug your Autoview setup has the full routine. Common strategies with Autoview shows how other kinds of strategy map to commands.
A note on what Autoview is. Autoview is an execution tool, not a trading or investment advisor. It places the orders your alerts and strategies tell it to; it doesn't generate signals, run backtests, or make any claim about results. Trading carries risk of loss, and you're responsible for the strategy you automate. See our disclosures.