0
votes

How can you backtest your strategy only within a specific time window on an intraday basis?

I'm testing a combination of MACD and BB on a timeframe of 1 minute. But I only want to enter a long or short position at UTC+2 between 10am and 1430 and 1600 and 2000 for CME listed futures. I want to exit any open position within X minutes outside of the entry window.

In a simplified way, my code currently looks like below:

++

longentry = crossover(macd, signal) and src <= lowerBB shortentry = crossunder(macd, signal) and src >= upperBB

longclose = crossunder(src, lowerBB) shortclose = crossover(src, upperBB)

if longentry strategy.entry("id=LONG", strategy.long)

if shortentry strategy.entry("id=SHORT", strategy.short)

++

Your assistance would be much appreciated.

Thanks and best regards,

Bas

1
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Community

1 Answers

0
votes

Here is an example script of how to set up a time window for your trades. Below you will see a couple inputs. One is a bool to turn our filter on and off and the other is the time we would like to trade between. We then create a condition that checks if we are outside of our time, and that we have filter trades checked off. Then we add that to our entry with "and not timeFilter". I added some background color so you can see where exemption lies.

//@version=4
strategy("My Strategy", overlay=true, margin_long=100, margin_short=100)
    
useTimeFilter = input(false, "Use Time Session Filter", input.bool,    group="Filters")  
timeSession   = input("0000-0300", "Time Session To Trade In", input.session, group="Filters")    

timeFilter = na(time(timeframe.period, timeSession + ":1234567", "GMT-2")) == true and useTimeFilter 

longentry = crossover(sma(close, 14), sma(close, 28))

shortentry = crossunder(sma(close, 14), sma(close, 28))

longclose = crossunder(sma(close, 14), sma(close, 28)) 

shortclose = crossover(sma(close, 14), sma(close, 28))

if longentry and not timeFilter
    strategy.entry("LONG", strategy.long)

if longclose and not timeFilter
    strategy.entry("SHORT", strategy.short)

strategy.close("LONG", when=longclose, comment="Long Close")

strategy.close("SHORT", when=shortclose, comment="Short Close")

bgcolor(timeFilter ? color.red : na)

All the best,

Bjorgum