Backtest Limit Order Fill Assumption: Fix Fake Profits
A backtest limit order fill assumption that fills at the bar low is lookahead, because the low is only known after the bar closes. Decide on bar t, set the limit from known data, and fill on bar t+1 only if price trades through it, at min(open, limit).
- Using the same bar's low (or high) as a limit price is lookahead: the strategy buys the exact bottom every time.
- Require low < limit (high > limit for sells), ideally by one tick, because a touch alone rarely fills a resting order.
- Fill price for buys is min(limit, open) and for sells max(limit, open), so gaps never fill at a better price than the market offered.
- Run the same strategy under touch, 1-tick trade-through, close-confirmed and probabilistic fills; if profit collapses, the edge was the fill model.
- Log fill rate, slippage vs limit and filled vs unfilled counterfactual PnL, then compare them to paper trading.
How do I check in 60 seconds whether my backtest fills are fake?
A backtest limit order fill assumption that is too generous usually fails one of a few quick tests. Run these before changing anything else.
The smoothness comes from the same source each time: the simulator is told about the future, and the orders that would have gone wrong are quietly counted as winners.
- Search the code for any limit price computed from low, high, or a rolling min/max that includes the current bar. If a buy limit equals low[t] and the fill is tested on bar t, you have lookahead.
- Compute the fill rate: filled orders divided by placed orders. Close to 100% on a limit order that sits below the market is a red flag.
- Shift the signal and limit by one bar and rerun. If the equity curve flattens or turns negative, the original edge came from seeing the bar.
- Change the fill test from low <= limit to low < limit - 1 tick. A large drop in profit means the result depended on touches.
- Check the average entry price versus the next bar's open. If you consistently buy far below the open and the bar's low equals your fill, you are buying the extreme.
Why does filling at the bar low create fake profits?
Three separate biases stack up, and each one alone can manufacture an edge.
Lookahead: the low of a bar is only known once the bar closes. A rule such as limit = low and fill = True is not a rule a live system can follow, because the live system cannot know where the low will be. The strategy is effectively buying the bottom of every bar.
Touch is not trade-through: when low == limit, price reached the level and turned. A resting order at that price sits in a queue, and the orders ahead of it are served first. Often the level trades only enough to clear the front of the queue, so most such orders stay unfilled. Requiring low < limit (high > limit for sells) shows the market actually traded beyond your price, so your order was likely reached. Add a tick of margin for conservatism.
Adverse selection: a resting buy fills most reliably when selling pressure continues, which is when price keeps falling through your level. It fills least when price bounces away from you in your favour. A naive backtest counts the filled, then-profitable bounces and, when it fills at touch, also fills orders that would never have executed live. The result is a fill rate that is highest exactly where the outcome is best.
How do I choose a backtest limit order fill assumption?
Think of fill models as a ladder from naive to conservative. Move down it until results stop changing much, and treat the most conservative rung as the number you can trust.
Whatever rung you choose, the timing rule stays the same: decide on bar t using data up to close[t], set the limit as a function of that data (for example close[t] - k*ATR[t]), and test it only on bar t+1. Never use bar t+1's own low to compute the limit for bar t+1.
Gaps: if bar t+1 opens beyond your limit (open < buy limit), the order would have been marketable at the open. Fill at the open, not at your limit. So buy fill = min(limit, open), sell fill = max(limit, open).
| Model | Buy fill rule | Bias | Use it for |
|---|---|---|---|
| Touch | low <= limit | Strongly optimistic | Upper bound only |
| 1-tick trade-through | low <= limit - tick | Mildly optimistic | Default baseline |
| Close confirmed | trade-through and close > limit | Conservative, filters falling knives | Stress test |
| Probabilistic | trade-through and random < p (0.3 to 0.5) | Approximates queue misses | Sensitivity runs |
| Volume participation | trade-through, qty <= 5 to 10% of bar volume | Models size and liquidity | Illiquid names |
| Queue position | fill after volume at level exceeds size ahead | Closest to live, needs tick data | Final validation |
What does a tested next-bar fill function look like?
The function below is vectorised, framework-agnostic and applies the next-bar, gap and trade-through rules. It expects columns open, high, low, close, volume and a boolean signal computed from information available at the close of each bar.
Limits are rounded down to the tick for buys. Partial fills cap quantity at a fraction of bar volume; the remainder is simply dropped here, which is the conservative choice (carry-over logic needs order state).
import numpy as np
import pandas as pd
def atr(df, n=14):
pc = df['close'].shift(1)
tr = pd.concat([df['high'] - df['low'],
(df['high'] - pc).abs(),
(df['low'] - pc).abs()], axis=1).max(axis=1)
return tr.rolling(n).mean()
def limit_buy_fills(df, signal, k=1.0, tick=0.01, mode='trade_through',
p_fill=0.4, order_qty=100, participation=0.10, seed=0):
a = atr(df)
# limit known at close of t, rounded down to tick
raw = df['close'] - k * a
limit_t = np.floor(raw / tick) * tick
# shift so the order is tested on t+1 only
limit = limit_t.shift(1)
sig = signal.shift(1).fillna(False).astype(bool)
if mode == 'touch':
hit = df['low'] <= limit
elif mode == 'trade_through':
hit = df['low'] <= limit - tick
elif mode == 'close_confirmed':
hit = (df['low'] <= limit - tick) & (df['close'] > limit)
elif mode == 'probabilistic':
rng = np.random.default_rng(seed)
hit = (df['low'] <= limit - tick) & (rng.random(len(df)) < p_fill)
else:
raise ValueError(mode)
filled = sig & hit & limit.notna()
price = np.minimum(df['open'], limit) # gap rule for buys
qty = np.minimum(order_qty, np.floor(participation * df['volume']))
out = pd.DataFrame({'placed': sig, 'filled': filled,
'fill_price': price.where(filled),
'qty': qty.where(filled, 0),
'limit': limit})
return out
# Adverse selection check: fill rate split by what price did afterwards
f = limit_buy_fills(df, signal)
next_ret = df['close'].shift(-2) / df['open'].shift(-1) - 1 # after the fill bar
placed = f[f.placed]
print(placed.groupby(next_ret[placed.index] > 0)['filled'].mean())How do Backtrader, backtesting.py and vectorbt handle limit fills?
Backtrader submits an order on bar t and evaluates it against bar t+1. A buy Order.Limit executes when the bar's low reaches the limit (touch counts), and if the bar opens at or below the limit it executes at the open. That is the touch model, so it is optimistic by default. To be conservative, set the limit price one tick lower, or write a custom broker or filler through cerebro.broker (for example the volume filler classes) to cap size by bar volume.
backtesting.py fills a limit order when low <= limit, also a touch rule. Compute your limit from the previous bar's data, subtract a tick, and avoid placing orders with limits derived from the current bar.
vectorbt does not model the order book: from_signals takes a price array and assumes the fill happens. Compute the fill mask and price with a function like the one above, then pass entries=filled and price=fill_price. Without that step, vectorbt fills every signal at whatever price you give it.
Costs matter as much as fills. Model a maker fee or rebate explicitly, because a limit order that earns a rebate in the backtest but pays a fee live changes per-trade expectancy. Round prices to the tick size, and remember that a limit buy resting at the bid only fills when sellers trade through it, so the quoted spread decides how often that happens.
What about brackets, OCO orders and bar-internal ordering?
OHLC data cannot say whether the low came before the high. If a limit entry and its stop or target can both be hit within the same bar, the true sequence is unknown.
Take the conservative branch: when both the stop and the target fall inside the bar's range, assume the stop was hit first. Also apply this when the entry and the stop are in the same bar: if low pierces both your limit and your stop, assume you were filled and stopped out.
The better fix is to resolve ambiguous bars with lower-timeframe data. Replay 1-minute or tick bars only for bars where more than one level was crossed, which keeps the cost small.
How do I measure sensitivity and validate the fill model?
Run the identical strategy and costs under each rung of the ladder, changing only the fill rule. Tabulate net PnL, trade count, fill rate and max drawdown per model.
If net profit falls sharply between touch and 1-tick trade-through, or becomes negative under close-confirmed or a 30 to 50% probabilistic fill, the edge was fill-driven rather than signal-driven. A robust signal degrades gradually as the fill model gets stricter.
Then log diagnostics for every run: fill rate, average slippage versus the limit (fill_price - limit), and the PnL of filled trades versus the counterfactual PnL of unfilled ones. Compute the unfilled counterfactual by assuming a fill and marking the trade to your exit rule. If the unfilled trades would have been the better ones, the model is adversely selected.
Finally compare against live paper trading. Collect the paper fill rate and slippage over a meaningful sample and check that the backtest model's fill rate is not higher. Adjust the model until it is equal or lower, and only then trust its numbers.
| Common mistake | Why it inflates results | Fix |
|---|---|---|
| Same-bar low or high for signals | Lookahead, buys the exact extreme | Shift limit and signal by one bar |
| 100% fill at touch | Ignores queue position | Require trade-through by 1 tick |
| Ignoring opening gap | Fills at a better price than the market offered | Use min(limit, open) for buys |
| Ignoring thin liquidity | Full size filled in a tiny bar | Cap at 5 to 10% of bar volume |
| Touch as a tick-resolution fill | Bar data cannot show queue | Use tick data or probabilistic fill |
| Adjusted prices for limit levels | Levels that never traded | Use raw prices for execution |
Common questions
Why do my backtest limit orders look too good to be true?
Usually because the fill rule uses information from the same bar, or treats a touch of the level as a guaranteed fill. Both remove the cases where price never reached you or only just kissed your level, so the backtest keeps the winners and drops the misses.
Does a limit order at the low always fill in a backtest?
In a naive simulator it does, because the low is by definition a price that traded. In reality you cannot know the low in advance, and a resting order at that price often sits behind other orders in the queue and does not fill.
What is the difference between trade-through and touch fills?
A touch fill assumes execution when price merely reaches your limit, which is low <= limit for a buy. A trade-through fill requires price to go beyond your limit, low < limit, which implies the orders queued at your level were consumed before yours.
How much volume can I assume I fill in one bar?
A common conservative cap is 5 to 10% of the bar's volume. The right value depends on the instrument and bar size, so test several caps and see where results stop being sensitive.
Can I model queue position with OHLCV bars?
Only roughly. A workable approximation is to fill after volume traded at or beyond your level exceeds the estimated size ahead of you, but bar data does not reveal how much traded at each price, so tick or order book data is needed for a reliable queue model.