Strategy · Pine Script v5 · On the chart

How To Set Time Ranges

by regalouisei· code credited to allanster

How To Set Time Ranges is a strategy template designed to demonstrate date and time filtering for backtesting.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code56
Settings13inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago25 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

56 lines of Pine Script v5 from pinescript/editors_picks/how-to-set-backtest-time-ranges.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

how-to-set-backtest-time-ranges.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © allanster

//@version=5
strategy(title = "How To Set Time Ranges", shorttitle = "Timed", overlay = true, precision = 8, max_bars_back = 200, pyramiding = 0, initial_capital = 100000, 
     currency = currency.NONE, default_qty_type = strategy.cash, default_qty_value = 100000, commission_type = "percent", commission_value = 0.27)

// Revision: 2
// Author:   @allanster
// Credit:   Special thanks to @LucF and @a.tesla2018 for help with including ':1234567' for time ranges on weekends        

// === INPUT MA LENGTHS ===
fastMA     = input.int(defval = 14,      title = "FastMA Length",   minval = 1, step = 1)
slowMA     = input.int(defval = 28,      title = "SlowMA Length",   minval = 1, step = 1)

// === INPUT DATE RANGE ===
fromMonth  = input.int(defval = 1,       title = "From Month",      minval = 1, maxval = 12)
fromDay    = input.int(defval = 1,       title = "From Day",        minval = 1, maxval = 31)
fromYear   = input.int(defval = 2021,    title = "From Year",       minval = 1970)
thruMonth  = input.int(defval = 1,       title = "Thru Month",      minval = 1, maxval = 12)
thruDay    = input.int(defval = 1,       title = "Thru Day",        minval = 1, maxval = 31)
thruYear   = input.int(defval = 2112,    title = "Thru Year",       minval = 1970)

// === INPUT TIME RANGE ===
entryTime  = input.session('0000-0000',  title = "Entry Time")   // '0000-0000' is anytime to enter
exitTime   = input.session('0000-0000',  title = "Exit Time")    // '0000-0000' is anytime to exit

// === INPUT SHOW PLOTS ===
showDate   = input(true,                 title = "Show Date Range")
showTimeE  = input(true,                 title = "Show Time Entry")
showTimeX  = input(true,                 title = "Show Time Exit")

// === DATE & TIME RANGE FUNCTIONS ===
isDate() =>                                                               // create function "within window of dates"
    start  = timestamp(fromYear, fromMonth, fromDay, 00, 00)              // date start
    finish = timestamp(thruYear, thruMonth, thruDay, 23, 59)              // date finish
    isDate = time >= start and time <= finish                             // current date is "within window of dates"

isTime(_position) =>                                                      // create function "within window of time"
    isTime = time(timeframe.period, _position + ':1234567')               // current time is "within window of time"

// === LOGIC ===
enterLong  = ta.crossover (ta.sma(close, fastMA), ta.sma(close, slowMA))  // enter when fastMA crosses over  slowMA
exitLong   = ta.crossunder(ta.sma(close, fastMA), ta.sma(close, slowMA))  // exits when fastMA crosses under slowMA

// === EXECUTION ===
strategy.entry("L", strategy.long, when = isDate() and isTime(entryTime) and enterLong)  // enter "within window of dates and time" AND crossover
strategy.close("L", when = isDate() and isTime(exitTime) and exitLong)                   // exits "within window of dates and time" AND crossunder         

// === PLOTTING ===
bgcolor(color = showDate  and isDate()                       ? color.new(color.gray, 90)   : color(na))  // plot "within window of dates"
bgcolor(color = showTimeE and isDate() and isTime(entryTime) ? color.new(color.lime, 90)   : color(na))  // plot "within window of entry time"
bgcolor(color = showTimeX and isDate() and isTime(exitTime)  ? color.new(color.purple, 90) : color(na))  // plot "within window of exit time"

plot(ta.sma(close, fastMA), title = 'FastMA', color = color.new(color.yellow, 0), linewidth = 2, style = plot.style_line)  // plot FastMA
plot(ta.sma(close, slowMA), title = 'SlowMA', color = color.new(color.aqua, 0),   linewidth = 2, style = plot.style_line)  // plot SlowMA

Overview

How To Set Time Ranges calculates fast and slow simple moving averages to trigger long entries on bullish crossovers and close positions on bearish crossunders. Trades are strictly executed within customizable start and end date ranges, as well as specific intraday entry and exit session windows. The script overlays background shading on the price chart to visualize active date and time windows. Note that the strategy includes no hard stop loss or take profit rules.

Details

Published by

regalouisei on GitHub

Code credit

allanster, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Moving averages, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
FastMA Lengthint14fastMA
SlowMA Lengthint28slowMA
From Monthint1fromMonth
From Dayint1fromDay
From Yearint2021fromYear
Thru Monthint1thruMonth
Thru Dayint1thruDay
Thru Yearint2112thruYear
Entry Timesession0000-0000entryTime
Exit Timesession0000-0000exitTime
Show Date RangebooltrueshowDate
Show Time EntrybooltrueshowTimeE
Show all 13 settings
SettingTypeDefaultVariable
Show Time ExitbooltrueshowTimeX
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers