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.
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")