FAQ

How to insert backtesting range to PineScript strategies?

How to insert backtesting range to PineScript strategies?

Quite often you want to test your Strategy on a specific date range. Unfortunately, there is no way to change this range with standard TradingView features. But you can easily adjust your strategy to include custom parameters for the backtesting range.

To do that you need to complete 3 pretty simple steps.

1. Add the following code to your strategy:

////////////////////////////////////////////////////////////////////////////////
// BACKTESTING RANGE
 
// From Date Inputs
fromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)
fromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)
fromYear = input(defval = 2018, title = "From Year", minval = 1970)
 
// To Date Inputs
toDay = input(defval = 1, title = "To Day", minval = 1, maxval = 31)
toMonth = input(defval = 1, title = "To Month", minval = 1, maxval = 12)
toYear = input(defval = 2019, title = "To Year", minval = 1970)
 
// Calculate start/end date and time condition
startDate = timestamp(fromYear, fromMonth, fromDay, 00, 00)
finishDate = timestamp(toYear, toMonth, toDay, 00, 00)
time_cond = time >= startDate and time <= finishDate
 
////////////////////////////////////////////////////////////////////////////////

Add it after the last input you have in your script and before any strategy.* functions.

Using these codes you will add input parameters for start and end date. Also time_code variable will be calculated and it will be true if we’re inside needed date interval and false if it will be outside this interval.

2. time_cond variable to all your entry condition:

Depend on your strategy your entry condition may look differently, but here are some examples of how this should look like.

// Using if to create an order
if (psar >= high and time_cond)
    strategy.entry("ParLE", strategy.long, stop=psar, comment="ParLE")
// Using market orders
strategy.entry("ParLE", strategy.long, comment="ParLE", when = psar >= high and time_cond)

3. Add the following code at the very end of your strategy:

if (not time_cond)
    strategy.close_all()
    strategy.cancel_all()

This code will close all positions and orders when your backtesting range will be over.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

In the following video you can find an example of adding backtesting range to PineScript strategies:

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news