Trade within selected period strategy

This example gives an understanding of building a strategy that can be tested with any period within the available history of the chart. It is helpful to analyse particular places in the backtest history to do adjustments. Let's say you want to run a strategy within a single month. Select the period in the settings and see the backtest result only for this period.

// @version=5
strategy('Trade within selected period strategy', overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=25, commission_type=strategy.commission.percent, commission_value=0.04)

// define the time period borders
tradeFrom = input.time(title="Trade from      ", inline="Trade from", defval=timestamp("01 Jan 2019 00:00 UTC"), tooltip="There will be no trades triggered before this timestamp.")
tradeTo = input.time(title="Trade to        ", inline="Trade to", defval=timestamp("31 Dec 2024 23:59 UTC"), tooltip="There will be no trades triggered after this timestamp.")

// determine whether the starategy should be traded within the selected period
// this is the core condition to select when to open trades
isTradeEnabled = time >= tradeFrom and time < tradeTo


// *******************************************************************************************
// Strategy logic simulation
// *******************************************************************************************
// this logic is only to simulate long and short positions
rsiEmulationData = ta.rsi(close, 7)
rsiEmulationCrossover = ta.crossover(rsiEmulationData, 70) // go long condition
rsiEmulationCrossunder = ta.crossunder(rsiEmulationData, 30) // go short condition


// entry loogic based on the rsi calculations
if isTradeEnabled and rsiEmulationCrossover
    // go long only if the trades are enabled at this bar
    // and if the rsi crossed over the filter value
    strategy.entry('Long', strategy.long)
if isTradeEnabled and rsiEmulationCrossunder
    // go short only if the trades are enabled at this bar
    // and if the rsi crossed under the filter value
    strategy.entry('Short', strategy.short)
Made on
Tilda