TradingView Backtesting

Set a TradingView Backtest Date Range

Use a strategy's date inputs to restrict when it submits entries, or select a calculation range in TradingView's Strategy Report to use Deep Backtesting on an eligible plan. A Pine date filter cannot load missing history and does not automatically close positions. Keep the calculation start, entry window, and actual fill timestamps separate when checking the result.

Explore Strategy Optimizer

Choose the range control that matches your task

Chart history, script inputs, and the report's calculation range affect different parts of a backtest. Zooming into a month does not by itself filter the strategy to that month. Check which history is available for the symbol and timeframe before selecting the test dates.

ControlWhat it changesBoundary to check
Regular chart datasetBars available to calculate the strategyThe earliest loaded bar depends on data availability and applicable plan limits.
Pine Script date inputsRules such as whether an entry may be submittedThe script must use those inputs. They do not fetch history or filter every order automatically.
Deep Backtesting date rangeThe history used for the report's calculationAvailable on Premium and higher plans; subject to stored history and calculation limits.

A complete Pine Script date filter

This educational example uses an inclusive start and exclusive end: startTime <= time < endTime. For a calendar year in UTC, set the end to January 1 of the next year. The filter checks bar opening times. Moving averages and crossover calculations run on every available bar, including those before the entry window. The chosen lengths and costs are illustrative, not recommended trading settings.

  • Paste the complete script into Pine Editor, add it to a standard candlestick chart, then change Start and End in Settings / Inputs.
  • The timestamp string sets an unambiguous default instant. The date fields still display in your chart timezone; changing the chart timezone changes their display, not that instant.
  • With Force close after end disabled, new entries stop at the boundary and the normal crossunder exit remains active afterward.
Pine Script v6: entry window with an optional end exitpinescript
//@version=6
strategy("Date window example", overlay = true, initial_capital = 10000,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 10,
     commission_type = strategy.commission.percent, commission_value = 0.1,
     slippage = 1)

startTime = input.time(timestamp("01 Jan 2024 00:00 +0000"), "Start (inclusive)")
endTime = input.time(timestamp("01 Jan 2025 00:00 +0000"), "End (exclusive)")
forceClose = input.bool(false, "Force close after end")
fastLength = input.int(20, "Fast SMA", minval = 1)
slowLength = input.int(50, "Slow SMA", minval = 2)

if startTime >= endTime
    runtime.error("Start must be earlier than end.")

// Calculate on every available bar, including warm-up history.
fast = ta.sma(close, fastLength)
slow = ta.sma(close, slowLength)
enterLong = ta.crossover(fast, slow)
exitLong = ta.crossunder(fast, slow)
inWindow = time >= startTime and time < endTime
pastEnd = time >= endTime

if inWindow and enterLong and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

if pastEnd and forceClose
    // Cancel pending orders before creating a new market exit.
    strategy.cancel_all()
    if strategy.position_size != 0
        strategy.close_all(comment = "Window exit")
else if exitLong and strategy.position_size > 0
    // Normal exits remain enabled outside the entry window.
    strategy.close("Long", comment = "SMA exit")

plot(fast, "Fast SMA", color.blue)
plot(slow, "Slow SMA", color.orange)
bgcolor(inWindow ? color.new(color.teal, 90) : na, title = "Entry window")

Check actual bars and fills at both endpoints

An input timestamp need not coincide with a bar. If the start falls on a closed market day, the first eligible bar is the next available bar whose opening time meets the condition. A bar that opens before the end can close after it. The shaded window therefore identifies eligible signal bars, not a guarantee that all fills occur inside the requested dates.

  • Under the example's default execution settings, orders are created at bar close and market orders normally fill at the next bar's open. An entry from the last eligible bar can fill after the end timestamp.
  • The optional end exit is submitted at the close of the first calculated bar opening at or after the end. It normally fills on the following bar, not at the selected timestamp. If there is no later bar, that exit cannot complete.
  • For strategies with pending limit or stop entries, blocking new submissions does not cancel existing orders. Review their IDs and cancellation policy separately; do not cancel protective exits unintentionally.
  • Check the first and last shaded bars and the report's actual entry and exit times. For finer boundaries, test a smaller chart timeframe and recheck data coverage and fill assumptions.

Preserve warm-up history and choose an exit policy

The calculation start and the first allowed entry do not have to match. A moving average needs earlier observations; recursive indicators such as EMA can also depend on where calculation began. Keep indicator calculations outside the entry condition. A date filter cannot supply missing warm-up bars.

  • Use the same warm-up and end policy for every candidate you compare.
  • Do not interpret a syntax-valid example as an empirically validated strategy. Check its order timing and open positions in your own report.
End policyWhat the report includesTradeoff
Stop entries; keep normal exitsPositions entered during the window may close later.Retains the exit rules, but trade outcomes can use prices after the window.
Force a boundary exitAn additional market exit under the chosen timing model.Changes holding periods, realized profit, costs, and drawdown. It is a different test specification.

How Deep Backtesting changes the date range

TradingView's current help describes selecting a time range in the Strategy Report to start Deep Backtesting, identified by a pink icon. After changing the strategy, use Update report. Reset to chart session returns to the regular calculation. Deep Backtesting uses stored history beyond the chart dataset where available; it does not create data for missing periods.

  • A calculation can use at most two million bars. If the selected period is larger, TradingView uses its most recent two million bars. Coverage varies by symbol and timeframe.
  • Deep calculations begin at the selected range's start, whereas regular calculations begin at the chart dataset's first bar. This can change EMA values and signals even within overlapping dates.
  • To allow warm-up before an entry window, choose an earlier Deep calculation start and keep the Pine entry start later. Confirm the requested earlier data is actually available.
  • Deep Backtesting trades appear only in its report. Chart trade markers continue to represent the regular calculation, including where the two ranges overlap.

A repeatable checklist for sample splits

Choose a development period and a later validation period before tuning parameters. A held-out period can reveal sensitivity to the chosen history; it cannot prove future profitability. The procedure below is a test plan, not a report of measured results.

  • Record the exchange-qualified symbol, timeframe, session, chart type, script version, execution settings, commission, and slippage.
  • Record calculation start, entry start, exclusive entry end, timezone, and end-exit policy. Verify actual available bars and the first and last fill timestamps.
  • Tune on the development window and save the chosen parameters before viewing validation results. Keep the dates fixed while comparing parameter candidates.
  • Run the held-out window with those parameters and the same assumptions. Record closed trades, open exposure, drawdown, costs, and any boundary exits.
  • If you revise the rules after viewing validation results, treat that period as development data and reserve another untouched period.
  • For each new date window, configure and verify the dates before using Pineify Strategy Optimizer to compare supported parameter combinations. Retain the run settings with exported results.
Where Pineify fits

TradingView Strategy Optimizer

Compare supported strategy parameter combinations after fixing your date window and execution settings. Keep a separate record for each development and validation run.

Also useful: Pine Script AI Coding Agent. Ask for date inputs and an explicit entry, cancellation, and exit policy in your strategy. Review the generated code and verify its boundary behavior in TradingView.

Explore Strategy Optimizer

Frequently asked questions

Educational reference, not investment advice. Backtest results depend on data and simulation assumptions and do not guarantee future returns.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.