How Orders Fill in a Backtest

A backtest only knows each bar’s open, high, low and close. It does not know the order in which prices traded inside the bar. These are the rules LumiBot uses so results are not better than live trading would have been.

How backtest orders fill: always the next price after the order

An order fills at the next available price after the order time. Never at a price from before the order. This is how a real broker works: you cannot buy at a price that already went by.

  • A market order fills at the open of the first bar that opens at or after the order time.

  • An order placed while the market is closed fills at the next session’s open.

  • The data your strategy reads follows the same clock: a bar is readable only after it has ended, so its high, low and close are never seen early.

Stock on daily bars. A daily bar has only the day’s open (09:30) and close (16:00). An order placed before the open fills at that day’s open. An order placed on a Saturday fills at Monday’s open. By the contract, an order placed at noon should fill at the close (the next price after noon), not at the open, which was two and a half hours earlier.

24/7 market (crypto, perpetuals) on daily bars. A daily bar covers one UTC day and starts at 00:00 UTC (19:00 or 20:00 the evening before in New York). A strategy that wakes at 00:00 New York time on November 1 is four hours into the November 1 UTC day. Its market order fills at the open of the November 2 UTC day, the next bar after the order. The newest bar it can read is October 31, the last UTC day that has ended.

Known gaps (found November 28, 2026, not yet changed). In these cases a backtest still fills at a price from before the order:

  • Daily stock bars, order placed during the session (for example at noon): it fills at that day’s open instead of its close.

  • Minute bars, order placed after the last bar of the session (for example at 17:00 on stock or futures data with a gap): it fills at once at the open of the last bar before the order instead of the next session’s open.

tests/test_backtest_fill_timing_invariants.py checks this contract for every offline data source, asset class and bar size, and lists these gaps so a fix shows up there.

Market orders

A market order fills at the open of the next bar after it is submitted.

Partial executions

When a data source supplies a partial execution quantity, the unfilled remainder stays eligible on later bars until the order fills or is canceled. Each execution is capped at the quantity still open, and the order becomes filled when the total executed quantity reaches its requested size. Its average fill price includes all executions, weighted by their quantities. Quantity-based fees use each actual execution quantity, including the final remainder. This also applies to an OCO child; its sibling cancellation behavior is unchanged.

Limit orders

  • If the bar opens at or better than your limit (a gap), the order fills at the open.

  • Otherwise, if the limit price is inside the bar’s range, it fills at the limit price.

  • Otherwise it keeps waiting.

When the data has a bid and ask on each bar (common for futures, crypto and options), a limit that can trade against the quote (a buy at or above the ask, a sell at or below the bid) fills at the quote. A limit the quote does not reach is still checked against the bar’s traded range with the rules above, because the order rests through the whole bar. A strategy that cancels and re-places its limit every bar therefore fills on the bar that trades through its price, just like it would live. IOC and FOK orders are the exception: they are canceled if the quote does not fill them.

Before 4.6.93 a limit on quoted bars was compared only with the quote, so a limit below the quote never filled even when the bar traded through it. Backtests that use limit orders on quoted data may now show fills they did not show before.

Stop orders

  • The stop triggers when the bar’s range touches the stop price, and fills at the stop price.

  • If the bar opens past the stop (a gap), it fills at the open, not at the stop price. A gap can make the loss bigger than you planned, just like in live trading.

  • A stop-limit order triggers the same way, then fills only if its limit can be met.

  • A trailing stop moves its stop price as the bar’s high (for a sell) or low (for a buy) moves in your favor, then fills like a stop.

When one bar touches both the stop and the target

Bracket and OCO orders have a target (a limit) and a stop, and only one may fill. When a single bar reaches both prices, LumiBot assumes the stop filled first. The bar’s high and low cannot tell us which came first, and assuming the target would make results look better than they were.

The one exception: if the bar opens beyond the target, the target fills at the open, because the open is the first price of the bar.

Examples for a long position with a target at 105 and a stop at 95:

Bar (open, high, low)

What fills

Price

100, 106, 94

Stop (both touched)

95

107, 108, 94

Target (opened past it)

107 (the open)

93, 106, 92

Stop (opened past it)

93 (the open)

100, 106, 99

Target

105

The entry bar cannot stop out

The stop and target of a bracket or OTO order start working on the bar after the entry fills. A wide entry bar does not stop you out on the same bar you entered.

Intraday data gives more accurate fills

All of this is guesswork forced by bar data. Running the backtest on minute bars (instead of daily bars) makes these “both touched” bars much rarer and the results closer to live trading.

Resting orders are checked on every bar

A stop or limit rests at the broker. It can fill at any moment, not only when your strategy runs. In a backtest, waiting stop, limit, stop-limit and trailing stop orders (including the target and stop of a bracket, OTO or OCO order) are checked on every bar the backtest has loaded for that asset, also the bars between two runs of your strategy.

Example: a strategy runs once a day (sleeptime = "1D") on minute bars and holds a stop at 90. At 11:01 the price dips to 85, and by 11:05 it is back at 100.

Bar

What happens

11:00, low 92

Nothing. The stop is not reached.

11:01, opens 93, low 85

The stop fills at 90, at 11:01.

11:01, opens 88 (a gap under 90)

The stop fills at 88, the open.

The fill rules are the ones above, bar by bar:

  • A stop fills at the stop price when the bar’s range crosses it, or at the bar’s open when the bar opens past it.

  • A limit fills at the limit price, or at the open when the open is better.

  • A trailing stop follows every bar’s high (for a sell) or low (for a buy), then fills like a stop.

  • For a bracket or OCO, the exit that is touched first wins. If one bar touches both, the stop fills.

Your strategy’s on_filled_order runs at the time of the fill. An order it places there is processed on the next bar.

Aware timestamps may use datetime.timezone, zoneinfo or pytz. The broker preserves their absolute instant when advancing its clock, including a configured end bound in another timezone after a resting order fills. The clock still stops at that configured end; timezone conversion does not extend the backtest window.

What bars are used:

  • The bars the backtest already fills that order from. Nothing extra is downloaded.

  • With daily bars only, each bar is the whole day, so nothing changes: a stop touched during the day fills at the stop price, as before.

  • Bars outside the market session (pre-market, overnight) do not fill resting orders.

What is not covered yet: Alpaca, CCXT and Yahoo backtests, SMART_LIMIT orders, multi-leg packages with a net limit, and time skipped with self.sleep() still check resting orders only when the strategy runs.

What changed in 4.6.64

Before 4.6.64, resting orders were only checked when the strategy ran (once per sleeptime). A stop crossed between two runs was missed unless the price was still past the stop at the next run, so a dip that recovered never filled the stop. A limit touched between two runs was missed the same way.

If your strategy runs less often than its bars (for example "1D" or "15M" on minute bars) and uses stops, limits, trailing stops or brackets, its backtest results will change. Stops now fill when the price first crosses them, so results are more realistic and often worse than before. Strategies that run on every bar, strategies on daily bars, and strategies that only use market orders are unchanged.

4.6.64 also fixes percent trailing stops (trail_percent): a sell trailing stop no longer moves down when the price falls, and a buy trailing stop now moves down with the price. Trailing stops set with trail_price already worked this way.

Options: every fill price belongs to the fill bar

Option contracts trade thinly. A contract often has no trade in the minute your order should fill. LumiBot never fills an option at a price from an earlier bar. For each bar it uses, in this order:

  1. Quote: the real bid or ask on that bar, when the data source has quotes (buys pay the ask, sells receive the bid).

  2. Trade: a real trade on that bar (the bar’s open).

  3. Estimated: a model value for that bar, priced with the underlying price on the bar.

    • When minute trade bars for other contracts of the same expiration are already loaded in the backtest (at least five that traded earlier in the session), the volatility comes from a smooth curve fitted across all of those recent trades, calls and puts separately, with newer trades counting more. For index options, in-the-money contracts are priced from the more actively traded out-of-the-money side, using the forward price implied by calls and puts that traded at the same strike.

    • Otherwise it uses the implied volatility backed out from the contract’s own most recent real trade. If the contract never traded, it uses the nearest strike with the same expiry and type. A deep in-the-money contract often last traded at, or a little below, what it was worth in the money at that bar’s underlying price, so no volatility explains the trade. That trade carried no time value, and the estimate carries none either: the contract is valued at what it is worth in the money at the current underlying price. (Before 4.6.79 such a contract got no estimate, so its order, and any package containing it, never filled; a spread could not be closed on its expiry day.) A last trade above anything a volatility can reach still gets no estimate.

    Only trades that happened before the fill bar are used, and nothing extra is downloaded for this. The estimate is used as computed: no penalty is added. If you want estimated fills to be more conservative, set LUMIBOT_BACKTEST_OPTION_ESTIMATE_PENALTY_PCT (percent of the price; buys pay more, sells receive less). The default is 0.

Every option fill is marked in the trades file (price_source is quote, trade or estimated), and data_provenance.json counts them under optionFillPrices. If no price can be found (for example nothing has traded yet in that expiry), the order keeps waiting. When the contract expires first, the order is canceled at expiry with the reason on the order ([OPTION_EXPIRY][CANCEL] in the log), as a broker would; a multi-leg order is canceled whole.

Spreads and condors: submit all legs as one order

A multi-leg order fills every leg on the same bar, or none of them. A credit or debit limit is checked against the net of the leg prices. If one leg’s time in force ends first, the whole order is canceled. Closing a spread works the same way.

legs = [
    self.create_order(long_put, 1, "buy"),
    self.create_order(short_put, 1, "sell"),
    self.create_order(short_call, 1, "sell"),
    self.create_order(long_call, 1, "buy"),
]
self.submit_order(legs, is_multileg=True)

Legs submitted one at a time are separate orders. Each fills on its own, so a spread submitted that way can be half open for a while.

How close are the estimates?

The estimate was validated against historical quote data (November 2026): 691,306 contract-minutes that had a real bid and ask, on 64 trading days in 2025 (47 calm, 17 volatile), expirations from 0 to 45 days. For each one, the estimate was built only from trades that happened earlier and compared with the real quote midpoint.

For strikes from 5 delta to at the money (147,293 contract-minutes), error in cents per share:

Price used

Median error

90th percentile

Inside real bid/ask

Last trade price, unchanged

25.0

390.0

36.8%

Contract’s own last trade (model)

17.7

113.1

33.8%

Curve across the expiration (model)

12.1

67.0

44.8%

The real half-spread in the same sample was 10 cents (median), so the typical estimate is off by about half a spread. The curve helps most where an estimate matters most: contracts that have not traded for minutes or days, 1 to 45 days to expiry, and volatile days. For contracts expiring the same day the two models are about equal (median 4.9 cents both).

Limits of that check, so you know how far to trust it:

  • Almost all of the sample (97.6%) is one family of cash-settled index options. The remaining rows are calls on one large ETF. Single stocks, and puts on American-style options, were not measured.

  • The comparison is with the quote midpoint. A real fill is not the midpoint: quote fills in LumiBot buy at the ask and sell at the bid, while an estimate is a midpoint-like price. Set the penalty above if you want estimated fills to give up some spread.

  • Interest and dividends are taken as zero. Fitting calls and puts separately removes most of that error for at- and out-of-the-money contracts.

  • The curve is only used when the other contracts’ trade bars are already loaded. A backtest that only ever asked for its own legs uses the contract’s own last trade.

An earlier check on SPY 1-minute option trades (November 2026), hiding a real trade and estimating it from the contract’s previous trade, found a median error of about 1% of the price at the money, 2 to 3% for 5 to 15 delta wings, and about 1 cent for contracts worth a few cents. Errors grew when the previous trade was 15 minutes or more old (at-the-money median 13 to 31 cents). Treat estimated fills as approximations.

Spreads held to expiry

When options on the same underlying expire in the money and deliver shares in both directions (for example both legs of a call debit spread, where the long call would buy shares and the short call would sell them), every one of those options settles in cash at its intrinsic value. No stock position is left behind.

Example: long the 100 call and short the 105 call, underlying at 110 at expiry. The long call settles for +10.00 and the short call for -5.00, so the spread pays 5.00 per share (500 per contract) in cash.

Options that deliver in one direction only (a single long call, a covered call, a cash-secured put) keep the normal exercise and assignment behavior.

Cash-settled index options (for example SPX and SPXW) always settle in cash at intrinsic value against the index’s closing level on the expiry day. Settlement uses the same-day close, never the next day’s. Contracts settled from the morning opening value (AM-settled monthlies) also use that day’s close, because the official opening settlement value is not in the price data; treat AM-settled results as approximate.

Index and stock prices during the day

In an intraday backtest that routes stocks or indexes to another provider (for example {"default": "alpaca", "index": "ibkr"}), get_last_price() on the underlying uses intraday bars, so the price moves during the session. If the provider has no intraday bars for that symbol, the last completed daily close is used and the log says so once ([ROUTED][INTRADAY_UNAVAILABLE]). Daily backtests use daily bars.

How open positions are valued between fills

The account value in a backtest uses, for each open position, in this order:

  1. the current price from the data source,

  2. the last real price seen for that asset earlier in the run (thinly traded options can go days without a trade),

  3. the position’s own fill price, when no market price has been seen since it was opened.

Rule 3 matters right after a multi-leg option order fills: every leg is valued from the moment of the fill until its own first market price arrives, so the account value never counts only some legs of a new spread. A position with no known price at all is left out and a warning is logged. None of these valuation prices creates a bar, a trade or a fill.

Option legs are valued for the same moment

Two option contracts rarely trade in the same bar. If each held contract were simply valued at its last trade, one leg of a spread could be priced from this bar and the other from hours or a day earlier, while the stock moved in between. The account value would then jump for one row and come back, and a spread could appear to be worth more than the distance between its strikes.

So, for every held option contract, on every valuation:

  1. A real quote or a real trade on the valuation bar is used as it is.

  2. Otherwise the contract is valued at a model estimate for that moment: the underlying’s price now, and the volatility implied by the contract’s own last real trade (together with the underlying’s price in the bar of that trade). A last trade that no volatility explains is treated as having had no time value.

A price from an earlier bar is never used as if it were current.

Daily bars need one more rule. A daily bar has no time of day: its open is the day’s first trade, whenever that happened. So on daily bars a contract’s bar for today counts as a real price only after the session has closed (its close). During the session the contract is estimated from earlier sessions and the underlying’s price now, and today’s bar is never read before the open. Before the open, a contract that traded in the last completed session keeps that real close.

data_provenance.json counts how held contracts were valued under optionValuationMarks (real and estimated, one count per contract per valuation). Estimates only affect the account value between trades (and so the drawdown shown). Fills, the trade log and cash are not changed, so the profit of a closed position is the same.

Limit to know: on daily bars the closing price of each leg is still that leg’s last trade of the day, and two legs’ last trades can be minutes or hours apart. Minute bars do not have this limit.

Market-On-Open (opg) and Market-On-Close (cls) orders

Orders submitted with time_in_force="opg" (Market-On-Open) or time_in_force="cls" (Market-On-Close) follow live auction semantics and the strict next-price rule:

  • ``opg`` (Market-On-Open): fills at the opening price of the first eligible session bar at or after order submission, matching live opening-auction behavior. Mid-session bid/ask quote fill shortcuts are skipped so an opg order never fills at an arbitrary intraday quote.

  • ``cls`` (Market-On-Close): fills at the closing price of the current (unfinished) session bar when submitted before the close, or the next session’s close when submitted after the close. It never fills at a closing price from a bar the strategy has already observed (no look-ahead), and mid-session quote fill shortcuts are skipped.

Synthetic option quotes and estimated_smart_limit provenance

When a data provider supplies real option bid/ask quotes (bid > 0 and ask >= bid), BacktestingBroker.get_quote() returns the real quote unchanged. When a trade-bar-only option feed (such as Alpaca historical option bars) has no bid/ask, LumiBot derives a calibrated synthetic {bid, ask} around the observed trade price (or Black-Scholes forward mark) so SMART_LIMIT orders can simulate realistic spread crossing. Every such quote carries raw_data["synthetic_quote"] = True, and every fill relying on a synthetic quote is explicitly labeled estimated_smart_limit in the trade log and counted under estimated in data_provenance.json.