FAQ · Getting systematic research right

How do I backtest an intraday strategy that must be flat by the close?

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.

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.

Next questions

How do I backtest an opening range breakout strategy in Python?Use intraday bars, take the high and low of the first minutes of each session, then rest a buy stop above the range and a sell stop below it, with the opposite side of the range as the stop loss. Allow one trade a day and close everything before the session ends. Daily bars cannot test this strategy, because they do not show which came first.How should a backtest fill stops and limits across an overnight gap?At the opening price, or close to it, and not at the order's own price. When a stock opens below a sell stop, the stop triggers at the open and fills there, worse than the stop. When it opens below a buy limit, the limit fills at the open, better than the limit. A backtest that fills at the stop or limit price across a gap overstates stops and understates limits.How do I backtest a strategy across several timeframes?Run the strategy on the fastest timeframe it trades on and build the slower ones from it, using only completed higher-timeframe bars. The most common mistake is reading an hourly or daily bar before it has closed, which gives the strategy prices it could not have known.How do I size positions in a backtest?Choose a sizing rule and compute the quantity at each entry. Fixed fractional risks a set share of equity per trade, volatility targeting scales size so each position carries similar risk, and ATR sizing sets quantity so a stop placed a multiple of ATR away loses a fixed amount. Then check the size against your buying power.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.