FAQ · Getting systematic research right

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.

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.

A worked example

A stock closes at $100. You hold 100 shares with a sell stop at $95. Bad news overnight, and it opens at $88.

Fill ruleFill priceLoss on the trade
At the stop price$95.00$500
At the open$88.00$1,200

The first row is a price nobody could trade at: the stock never traded between $95 and $88 that morning. A strategy with tight stops on gappy stocks can look safe under the first rule and lose more than twice as much live.

The same gap helps limits

A buy limit at $95 on the same morning fills at about $88, $7 better than the limit. A backtest that fills it at $95 understates what the limit earned. Both errors come from one shortcut: filling at the order's price instead of at the first price that crossed it.

Where gaps happen

  • Stocks: every morning, and largest after earnings, dividends and news.
  • Futures: on Sunday opens and after limit moves, and at each roll unless the series is back-adjusted. See futures rolls and FX swap.
  • FX: mostly at the Sunday evening open.
  • Intraday bars: at the first bar of the session, and after halts.
  • Crypto: rarely on liquid pairs, which trade around the clock.

How Reamer Research handles it

Reamer Research generates a seeded tick path inside each bar, starting at its open. A resting stop or limit that the open has already crossed triggers on the bar's first tick and fills there, near the open, as its execution specification (ยง8) states. This configured object holds a stop under each entry, and the code afterwards measures how far beyond their stops the stop exits filled:

import reamer_research as rr

class GapCheck:
    def __init__(self, stop_pct=0.003, qty=10):
        self.stop_pct, self.qty, self.lookback = stop_pct, qty, 13
    def on_bar(self, d):
        if d.close[0] == 0 or d.position() != 0:
            return None
        if d.close[-1] > d.close[:-1].max():
            stop = d.close[-1] * (1 - self.stop_pct)
            return rr.buy_market(self.qty, stop_loss=stop,
                                 take_profit=d.close[-1] * (1 + 2 * self.stop_pct))

result = rr.backtest(GapCheck(), 'data/SPY_5min.bin', spread=0.01)
for t in result.json()['closed_trades']:
    if t['stop_loss'] and t['exit_price'] < t['stop_loss'] - 0.02:
        print(t['close_timestamp'], 'stop', round(t['stop_loss'], 2),
              'filled', round(t['exit_price'], 2))

Each line is an exit that filled more than two cents beyond its stop. Those at a session's first bar are gap fills; the rest are the spread and slippage every stop pays. In the visual trade diagnostics tool (open_viewer=True) those trades show their stop level drawn above an exit that landed on the opening gap. The rule could equally be written as a function or a class with class attributes.

Limits to know

  • Gap fills carry your configured slippage and spread, with nothing extra for gap size. A stock that gaps on thin pre-market liquidity can fill further away live; raise slippage for those names with ticker_config.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. About 20 overnight gaps on 5-minute data; earnings-season studies need a licence.

A $20 month includes the full kit, so you can measure your own strategy's gap exits and cancel if it does not fit.

Next questions

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.Should my backtest use market or limit orders?Whichever you will use live, because they test different things. A market order always fills and pays the spread and slippage. A limit order saves that cost but fills only when price comes to it, and misses the trades that run away. A backtest of limit entries is honest only if a limit fills when price trades through it, and the trades it missed stay missed.How realistic do slippage and spread need to be in a backtest?Realistic enough that the result survives them. Set spread, slippage and commission per instrument from what your broker actually charges, let spread and slippage widen when the market moves fast, and then rerun at one and a half and two times those costs. A strategy whose edge disappears under slightly higher costs was never a reliable edge.How do I backtest an ATR stop or trailing stop in Python?Set the initial stop a multiple of the average true range below the entry, then on each closed bar raise it to the close minus the same multiple, never lowering it. The stop must rest as a real order that fills inside the next bar, at the stop price or worse on a gap, rather than being checked against the next close.

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.