In order to include time-based conditions in the back-testing code – we can use TimeNum() function to check the time-stamp of given bar and use it as input for any time-based conditions.
http://www.amibroker.com/f?timenum
In order to code a strategy that triggers trades only in certain hours of the day, 9:30-11:00 in this example, we can use the following approach (code uses simple MACD crossovers to generate signals):
tn = TimeNum(); startTime = 93000; // start in HHMMSS format endTime = 110000; // end in HHMMSS format timeOK = tn >= startTime AND tn <= endTime; Buy = Cross( MACD(), Signal() ) AND timeOK; Sell = Cross( Signal(), MACD() ) AND timeOK;
It is also possible to force an exit signal after 11:00 to avoid overnight positions:
tn = TimeNum(); startTime = 93000; // start in HHMMSS format endTime = 110000; // end in HHMMSS format timeOK = tn >= startTime AND tn <= endTime; Buy = Cross( MACD(), Signal() ) AND timeOK; Sell = (Cross( Signal(), MACD() ) AND timeOK) OR Cross( tn, endTime );