Send the exit one bar before the last bar of the session, so it fills inside the session, and stop new entries from the same time. An exit sent on the final bar's close can only fill at the next open, which leaves the position overnight. Do the time check in the exchange's own time zone, then confirm from the trade list that every trade opened and closed on the same day.
Why the last bar is too late
In an honest backtest, a decision made on a bar's close fills on a later bar. With 5-minute US stock bars, the 15:55 bar is the last of the session. A strategy that sees the 15:55 bar close and sends a market exit has no bar left that day: the order fills at the next morning's open, at whatever price the overnight gap brings. A backtest that fills it at 16:00 instead is filling at a price that was no longer available.
The fix is to decide one bar earlier: on the close of the 15:50 bar, send the exit, and it fills at the start of the 15:55 bar.
Three things to get right
- Time zone. Bars are usually stamped in UTC. New York's close is 21:00 UTC in winter and 20:00 UTC in summer. Convert each bar time to the exchange's zone before comparing it with the session clock.
- Short sessions. The day after Thanksgiving and Christmas Eve close at 13:00 in New York. A fixed 15:50 cutoff misses them. Use a session calendar, or cut off on a bar that is followed by no bar the same day.
- Resting orders. A pending limit or stop entry can still fill after the cutoff. Cancel resting orders at the same time as the exit.
How Reamer Research handles it
In Reamer Research, an order returned on bar N fills from bar N+1, so the exit is sent on the bar before the last. This class cancels resting orders and closes the position from the cutoff, and enters only before it:
from datetime import datetime
from zoneinfo import ZoneInfo
import reamer_research as rr
class FlatByClose:
lookback = 13
def __init__(self, tz='America/New_York', cutoff=(15, 50), qty=10):
self.tz, self.cutoff, self.qty = ZoneInfo(tz), cutoff, qty
def on_bar(self, d):
local = datetime.fromtimestamp(d.ts, self.tz)
if (local.hour, local.minute) >= self.cutoff: # last decision of the day
return rr.orders(rr.cancel_all(), rr.close_all())
if d.close[0] == 0 or d.position() != 0:
return None
if d.close[-1] > d.high[:-1].max(): # an hour's breakout
return rr.buy_market(self.qty, stop_loss=d.low[-6:].min())
def session_day(utc_text, tz=ZoneInfo('America/New_York')):
return datetime.fromisoformat(utc_text + '+00:00').astimezone(tz).date()
result = rr.backtest(FlatByClose(), 'data/SPY_5min.bin',
spread=0.01, commission_per_unit=0.005)
overnight = [t for t in result.closed_trades
if session_day(t['open_timestamp']) != session_day(t['close_timestamp'])]
print(result.closed_trades_count, 'trades,', len(overnight), 'held overnight')
d.ts is the step's epoch seconds, and zoneinfo handles the summer and winter switch. Bars here are stamped at their open, so the 15:50 bar closes at 15:55 and the exit fills at the start of the last bar. If your vendor stamps bars at their close, use a 15:55 cutoff instead. The last lines check the result: trade times are UTC, and any trade whose open and close fall on different New York dates was held overnight. The same rule can be a plain on_bar(data) function or a class with class attributes; this form keeps the time zone and cutoff configurable per market.
The visual trade diagnostics tool (open_viewer=True) shows each trade on its candles, so an exit that lands on the next morning's open stands out across the gap.
Limits to know
- The session calendar is yours. The engine runs on the bars it is given; half days and holidays come from your data or a calendar library such as
exchange_calendars. - Evaluation Mode runs 30 days or 50,000 bars of one ticker. A month of 5-minute bars fits, which covers about 20 sessions of closes.
A $20 month includes the full kit, so you can run your intraday rules over full histories and cancel if it does not fit.