Live vs Backtest

Software · Quant research

Live vs Backtest 回测实盘对比

Live results trailed the desk’s backtest. Shuo rebuilt the simulator trade for trade and found where the two part ways: inside a quarter of a second. After his report, the desk gave its live-hog engine a server of its own.

  • Conceived, designed and built by Shuo Huang, self-initiated
  • Bit-exact replica: every fill of a benchmark day
  • Live orders replayed one by one through the backtest
  • ML validated walk-forward on 6.87 M ticks
  • After his report: a server of its own for the engine
  • Daily production report from 25 Aug 20261
  • Python (standard library only) · SQL · R

01How the research is built

Rebuild the simulator bit for bit, then push the desk’s live orders through it.

The backtester and the live engine place the same orders. The only way to find where they part is to own a bit-for-bit copy of the first and a complete record of the second, both built in standard-library Python.

Model team

R backtester

The desk’s simulator: a main loop and its matching functions. The reference to reproduce.

Model team

ML signal files

The signal’s prediction for every 250 ms snapshot.

Read-only SQL

Tick database

Five-level order-book snapshots, one every 250 ms.

Trading engine

Engine logs

Every insert, acknowledgment, cancel and fill, stamped to the nanosecond.

Pure Python

Bit-exact replica

A line-by-line Python port. Every day and configuration equal; every fill of a benchmark day identical.

Finding 1

Delay counterfactual

Re-run the replica with the signal 0.25, 0.5, 1 and 2 s late.

Finding 2

Order-fate audit

Each live order, with its own lifetime, matched by the backtest’s rules. One order, two worlds.

Pure Python

Order-lifecycle extractor

Rebuilds each order’s life from the log; agrees with the database to the lot.

Decision

The desk

Gave the live-hog engine a server of its own.

To the model team

R patch

A drop-in queue correction with its own self-test, in the backtester’s code style. Adopted by the model team.

The fix

Matching variants V0–V5

The same live orders through six candidate matching rules, scored on timing error; V5 is the recommended V3 plus one guard.

Production

Live-Hog FAK Daily Report

The audit as a daily report on two engines: the original and V5.

Simplified: the speed audit, the local trigger model, the arbitration and the A/B analysis reuse the same replica and extractor and are described below.

Why exact, and not close?

The first port matched the reference results to within 3.7%. That is close enough to be wrong about anything that matters. Only an exact copy lets a difference between two runs be blamed on the one thing that was changed, so the port was reconciled until every fill agreed.2

Why replay live orders, not compare totals?

Two daily totals can differ for a hundred reasons. One order with two fates has only one: what the backtest assumes happens to it inside a 250 ms slice that nobody outside the exchange can see.

Standard library only

The desk’s PCs are standard-user machines with nothing extra installed, so every analysis script is standard-library Python 3.10: the regressions, the gradient-boosted trees, the bootstrap and the charts were written from scratch.

Whose parts are whose

The backtester, the machine-learning signal and the trading engine belong to the desk’s model team and IT. The comparison, the replica port, the log reconstruction, the audits, the fixes and the findings are Shuo’s; where a colleague raised the question or the idea he then tested, the page says so.3

02The story

The backtest credited a gain that live trading did not deliver. He found where the two part ways: inside a quarter of a second.

A trading desk’s simulator credited its machine-learning signal with a large gain that live trading, running the same signal, did not deliver. Shuo asked why, rebuilt the simulator until it reproduced the original trade for trade, and showed that the advantage exists only for an engine that acts instantly: one quarter-second late, the signal does worse than no signal at all.4 After his report, the desk gave its live-hog engine a server of its own.5 He then replayed the desk’s live orders one by one through the simulator’s own rules, found why it was too generous, and fixed it; the model team adopted the fix.6

  1. 01

    The problem

    A market maker posts buy and sell quotes all day and earns the gap between them when others trade against both. The desk tests its high-frequency machine-learning signal every day in a simulator, a backtest, run on recorded market data. The backtest credited the signal with a large gain per lot (one lot is one contract). Live trading, running the very same signal, did not deliver it.

    Nobody could say where the difference went. No independent copy of the simulator existed, so not one simulated trade could be inspected, and there was no record that lined up what a live order actually did against what the simulator assumed it would do.

    • Same signal, same quoting rule, different results
    • No independent copy of the simulator
    • No way to split the gap between the signal, the engine’s timing and the simulator’s own assumptions
  2. 02

    What he built

    Shuo posed the question himself: why does live trading trail the backtest, even with the same signal? On his own initiative, he answered it in layers.

    An exact copy. He ported the desk’s R backtester to Python and refused to accept “close.” When the first port disagreed slightly, he knew from a colleague who had rerun the original that its results were reproducible, so the error had to be in the port; he chased it to an undocumented session rule and reconciled the copy until it was bit-exact: every day and configuration tested equal on every total, and every fill of a full benchmark day identical in time, price, size and side.2

    One question on the exact copy. What if the signal arrives a quarter of a second late? The answer was not “a little less profit.” A short-horizon signal’s predictive power fades within a fraction of a second, and on the replica one market snapshot of delay turns the signal’s backtested gain into a loss against using no signal at all.4 A tip about where a price is heading in the next half-second is valuable if you act at once and costly a beat later, when the move has already happened and you are chasing it.

    One order, two worlds. He then rebuilt the desk’s live orders, one by one, from the trading engine’s nanosecond-stamped logs and handed each one, with the lifetime it actually had, to the backtest’s matching rules. The backtest filled fewer lots yet credited far more value.7 It credits cross orders that in reality arrived too late, and it fills the desk’s resting quotes sooner than the queue ahead of them allows.

    The mechanism and the fix. He traced the early fills to rivals who join the same price in the same quarter-second, invisible to any snapshot simulator, and to a volume-splitting rule that burns through the queue faster than the market does.8 He designed two corrections that together cut the worst timing errors sharply and packaged them as a drop-in patch for the backtester’s own code, which the model team adopted.6

    A model that does not wait. A cross order, the aggressive order that trades at once against the best quote on the other side, is only worth sending while that quote is still there. So Shuo built a local machine-learning model, ridge regression and gradient-boosted trees written from scratch in pure Python, that makes the signal’s trade-now call the moment a tick arrives, from the current order book and the signal values already received. Tested walk-forward on 6.87 million market ticks it had never seen, it recovered a majority of the signal’s trade-now calls on the busiest contract.9

  3. 03

    What changed

    The desk changed its infrastructure. After his delay report, the desk gave its live-hog engine a server of its own.5

    The simulator got an honest ruler. The order-by-order audit became a daily production report that runs on two matching engines, the original and Shuo’s improved one (Live-Hog FAK Daily Report).1 The replica became the desk’s reference engine: later studies, including the Smart Queue Review and an A/B test of the signal, are built on it. A colleague’s independent rewrite of the volume rule turned out to be identical to Shuo’s, slice for slice.6

    Then he audited his own impact. He measured the move from the engine’s own logs and ran a difference-in-differences against a frozen control. The order round trip was slower afterward, not faster, and the comparison could not separate the move from other changes over the same days, so he credited no gain to the move. Reporting that plainly, against his own finding’s interest, is the standard the whole project was held to.

100%

of a benchmark day’s fills reproduced by his replica, identical in time, price, size and side2

250ms

of signal delay, one market snapshot, turns the signal’s backtested gain negative4

6.87M

unseen market ticks in the walk-forward test of his from-scratch machine-learning model9

6engines

candidate matching rules scored on the same live orders; the model team adopted his fix6

12days

from the first question to a daily production report1

0libraries

beyond standard Python: the regressions, boosted trees, bootstrap and charts are written from scratch

03Functions

Nine studies, one chain of evidence

In the order the questions were asked. Each answer raised the next question.

A

Measure the gap

A one-click comparison of live per-lot results against every backtest configuration, reconciled against official figures, opened the investigation.

  • One read-only SQL pull supplies the live side per contract and day; contracts are compared only while they are the dominant month (the most traded delivery month), a colleague’s rule
  • Self-checking: the live side is reconciled against official figures, and the tool backfills missing days and re-pulls days whose settlement prices arrive late
  • Its output posed the question behind everything that follows: same signal, same quoting rule, so where do live and backtest part ways?

B

Replicate the backtester, exactly

A line-by-line Python port of the desk’s R backtester, reconciled until nothing differed.

  • Every day and configuration tested: profit, lots and cancels all equal; cumulative difference 0.00%2
  • Every fill of a full benchmark day identical in timestamp, price, size and side, which also proves the replica runs on the same signal inputs as the original
  • The last discrepancy was an undocumented session-boundary rule, found by reading the first and last timestamps of a reference fill file

C

Find the delay cliff

On the exact engine, shift the signal later and watch the uplift: it does not fade, it falls off a cliff.

  • Predictive power (the information coefficient: the correlation between the signal and the price move that follows) fades within a fraction of a second4
  • On the replica, one 250 ms snapshot of delay turns the backtested uplift negative: below the same backtest with no signal at all
  • A late signal trades more and chooses worse, and the mark-out (how far the price has moved in a fill’s favor some seconds later, the standard check of whether a fill was a good one) shows that signature: live fills hold on to less of their initial edge than the backtest’s fills do

Edge kept after the fill

Thirty seconds after the fill, live fills hold on to far less of their edge than the backtest’s fills.

Data: Edge kept after the fill
Time after the fillBacktest fillsLive fills
At the fill100%100%
+1 s75%74%
+5 s67%55%
+30 s57%29%
Synthetic data. Illustrative values, generated to show the effect: the two lines start together and part ways within seconds. Each line is a lot-weighted mark-out (how far the mid price has moved in the fill’s favor), indexed to its own edge at the moment of the fill (= 100%). The method is as built; the desk’s own figures are confidential.10

D

One order, two worlds

Each live order, with the lifetime it actually had, pushed through the backtest’s matching rules: the same order, two fates.

  • Placement is the same: live orders sit on the backtest’s own formula prices. Same signal, same orders
  • The fates are not: the backtest fills fewer lots yet credits far more value, at every mark-out horizon from 2 to 30 seconds7
  • Largest source: cross orders (aggressive orders that take the other side’s best quote, sent live as fill-and-kill: trade at once or cancel) that missed in reality but “filled” in the backtest. Next: orders already canceled live that still fill there

The same orders in two worlds

Through the backtest’s matching rules, the same orders fill fewer lots yet book more value, and the gap grows with the horizon.

Data: The same orders in two worlds
CategoryLiveBacktest
Lots filled10075
Value at 2 s100111
Value at 5 s100116
Value at 30 s100146
Synthetic data. Illustrative values, generated to show the effect: fewer lots, more credited value, and a gap that widens with the horizon. Each order is replayed with its own lifetime through the backtest’s matching rules; value is the mark-out of every fill at 2, 5 and 30 seconds, and both worlds are indexed to live = 100. The method is as built; the desk’s own figures are confidential.

E

Why the backtest fills too early

The orders that both worlds filled, but the backtest filled first. Shuo proposed the cause, tested it, and found a second one.

  • Simultaneous queue-jumping: orders at one price fill first come, first served, and in most early fills other orders joined the desk’s price inside the same 250 ms window; the backtest counts none of them ahead of the desk’s order8
  • A dose-response: the more that joined unseen, the earlier the backtest filled
  • The rest: the backtest’s two-price volume split consumes a queue faster than the market clears it, shown slice by slice on a worked example

How early the backtest filled, by unseen arrivals

The more rivals joined the desk’s price unseen, the earlier the backtest filled its order.

Show the dataHide the data
Data: How early the backtest filled, by unseen arrivals
Lots others added at the desk’s price in the same 250 ms windowBacktest fill ahead of the live fill, median
None0.59 s
1–80.78 s
9–241.26 s
25–502.07 s
Over 504.64 s
Synthetic data. Illustrative values, generated to show the effect: 860 generated early-filled orders, grouped by how much other traders’ size at the desk’s price grew in the first snapshot that surely contains the order (311, 175, 253, 89 and 32 orders). The method is as built; the desk’s own figures are confidential.
Histogram, on synthetic data, of how many lots other traders added at the desk’s price in the same 250 millisecond window, for orders the backtest filled early. A violet group (36 percent) sits at or below zero; a larger amber group (64 percent) extends to the right, with a dashed line at its median of plus 13 lots and a long tail. Enlarge
Synthetic data. A redraw of the study’s central chart on generated orders. Each bar counts early-filled orders by how many lots, net, other traders added at the desk’s price in the same 250 ms window. Look at how much of the mass sits right of zero: rivals may have joined ahead of the desk’s order, and a snapshot backtest counts none of them. The method is as built; the desk’s own figures are confidential.
  1. Marker 1: Zero line. Right of it, the price level grew by more than the desk’s own order: someone else arrived in the same window.
  2. Marker 2: Violet: no net arrivals. These early fills need a second explanation, the volume-allocation rule.
  3. Marker 3: Amber: net arrivals. Queue-jumping ahead of the desk’s order was possible and material.
  4. Marker 4: Dashed line: the median of the amber group, the typical unseen queue.
  5. Marker 5: Long tail. The more lots arrived unseen, the earlier the backtest filled, as the dose-response chart shows.

F

Fix the matching rule

Six candidate matching engines (the simulator’s rule for deciding when a resting order fills), scored on the same replayed live orders by how far their fill times stray from the live ones.

  • A queue-join correction (assume half of the same-window arrivals got in first) alone removes most of the over-credit6
  • Paired with a tick-grid volume allocation it cuts the timing-error tail sharply
  • Delivered to the model team as a drop-in R function with a self-test; setting its one parameter to zero reproduces the original engine bit for bit

Timing-error tail by matching engine

The recommended engine, V3, cuts the timing-error tail sharply; the α = 1 engines cut it further but under-credit fills.

Show the dataHide the data
Data: Timing-error tail by matching engine
Matching engine90th-percentile timing error (s)
V0 original8.36
V15.04
V1b6.25
V27.68
V35.72
V44.65
Synthetic data. Illustrative values, generated to show the effect; shorter is better: one fill in ten is timed wrong by more than the bar. V0 is the original rule; V1 and V1b add the queue-join correction alone (α = 1 and 0.5); V2 is the tick-grid allocation alone; V3 is both (α = 0.5), the recommended engine; V4 is both at α = 1, the worst-case bound. The α = 1 engines under-credit fills. The method is as built; the desk’s own figures are confidential.

G

A local model for the trade-now call

LocalTrigger: a compact local model that makes the signal’s trade-now call from the current order book and the signal values already received.

  • First the question behind it: a counterfactual study of what triggers a cross order, the signal, inventory or both
  • A machine-learning surrogate of the signal: ridge regression and histogram gradient-boosted trees written from scratch in pure Python, 44 order-book and lagged-signal features, validated on an eight-fold expanding walk-forward over 6.87 million ticks and three contract rolls9
  • It recovered a majority of the signal’s trade-now calls on the busiest contract. A research prototype with a deployable specification

H

Audit the server move

The desk acted on the delay report. Shuo then tested the move against the mechanism his own analysis predicted.

  • Latency measured on one clock from the engine’s own logs, so no clock offset can enter: order sent to exchange acknowledgment, split into an engine leg and an exchange leg
  • A difference-in-differences against a frozen control backtest, then a regression that controls for the main confound
  • The verdict, reported as found: the order round trip was slower afterward, and no gain is credited to the move5

I

Arbitrate, then experiment

Two sequels on the same replica: settling a disagreement between two runs of one backtest, and an A/B test of the signal itself.

  • Arbitration: two runs of the same backtest specification disagreed. The replica reproduced one exactly once Shuo chased the last small residual to the individual fill; the cause was a session-split convention
  • A/B: a treated contract and a matched control, priced on a same-tape replica of both, with a minute-block bootstrap, a replica-bias check and a power analysis11
  • The result was inconclusive and reported as such; he designed the follow-up crossover test and sized it in advance

04How it works

One snapshot late, and the edge is gone

The delay cliff

Synthetic data. Illustrative values, generated to show the effect: the uplift is full only at zero delay and negative from the first 250 ms snapshot. The method is as built; the desk’s own figures are confidential. The straight lines between the five delays are schematic.10

Text description of this figure

The figure has three stages, all on synthetic values. Stage one, the replica: a Python port of the desk’s backtester is reconciled until it matches, shown as a grid of 24 runs (12 days times 2 configurations) that turn green one by one and a counter that reaches 1,684 of 1,684 identical fills on a benchmark day. Stage two, the delay test: the machine-learning signal is shifted later on that engine. Used instantly the signal has an information coefficient of 0.360 and the backtest shows its full uplift, 100 percent. One 250 millisecond snapshot late the coefficient is 0.123 and the uplift is minus 40 percent, below using no signal. At 0.5, 1 and 2 seconds the uplift is minus 76, minus 98 and minus 109 percent, and the coefficient falls to 0.057, 0.024 and 0.004. Stage three, the result: after the report, the desk gave its live-hog engine a server of its own, and Shuo’s follow-up audit credited no gain to the move. The last step shows the order audit: live orders replayed through the backtest’s matching rules fill 25 percent fewer lots yet book 1.46 times the value 30 seconds later, because cross orders that missed live and orders already canceled live still fill in the backtest.

05Under the hood

Methods, equations, pseudo-code and illustrative results

Under the hoodReplication standard, ML model spec, equations, pseudo-code, illustrative tables and the errors caught on the way

Everything below is on DCE live hog unless stated. The exchange feed is a five-level order-book snapshot every 250 ms with cumulative volume and turnover; the order of events inside a slice is invisible, and there is no order-by-order feed. Every snapshot backtest must therefore guess queue position and per-price traded volume. The project measures how those guesses differ from what the desk’s own orders experienced.

All analysis code is standard-library Python 3.10, with no numerical libraries; charts are plain SVG built from scratch. The desk’s own figures are confidential: outcomes are stated in words, and every results chart and table on this page carries synthetic, illustrative values, marked as such.10

1 · The replication standard

Object. The desk’s market-making backtester: an R main loop plus its matching functions. The strategy it simulates quotes around a fair value adjusted for inventory and a short-horizon signal.

What a snapshot backtest has to assume, all of it reproduced. A snapshot feed gives each 250 ms slice only its total volume and turnover. The simulator must therefore decide (a) how to split that volume across prices, here between two prices solved from volume and turnover (below); (b) where a new order stands in the queue, here behind the size displayed at its price; (c) how later snapshots move it, here by never letting the queue exceed the displayed size; and (d) when a resting order fills and whether a cancel wins its race.

Parity test. Per day and configuration: total profit, total lots and total cancels against the reference values, then a fill-by-fill diff against a reference fill file. Result: every day and configuration equal on all three totals, cumulative difference 0.00%, and every fill of the benchmark day identical in timestamp, price, size and side. Because the signal-on configuration matches fill for fill, the replica provably runs on the same signal inputs as the original.

What exactness required. R’s round is half-to-even (banker’s rounding) and so is Python’s, which the port relies on; one comparison that must stay a strict inequality; a sentinel for an empty book side; and a session-boundary convention that was written down nowhere. The first port landed 3.7% off, close enough to be wrong; the missing convention was read off the first and last timestamps of the reference fills.

Va=T−V·pbpa−pb,Vb=V−Va
The two-price split. V, T: the slice’s traded volume and turnover (per unit of the contract multiplier); p_b, p_a: the two prices the volume is split between, anchored on the end-of-slice best bid and ask; V_b, V_a: the lots assumed traded at each. The tick-grid fix of section 6 changes only how p_b and p_a are chosen.

2 · Signal decay and the delay counterfactual

Decay. The information coefficient is the correlation between the signal at t and the mid move over the next h = 0.5 s, when the signal is applied d seconds late, computed offline on the 250 ms grid of the signal files.

Counterfactual. Parity first; then every signal timestamp is shifted by τ and the exact engine is re-run on the same days. U(τ) is the per-lot uplift over the no-signal baseline as a share of its zero-delay value. It is negative from the first snapshot of delay, while traded volume rises: a late signal makes the strategy chase moves that already happened.

Why one snapshot is enough. A cross order pays the spread up front. A signal strong enough to justify crossing predicts a move that is largely over one snapshot later, so the same order sent a beat late pays the spread for a move it no longer gets.

What was ruled out first. Three simpler explanations: that live applies the signal differently from the backtest (tested by regressing live quote offsets on the signal), that the engine is simply slow, and that live crosses more or less often than the backtest. None explained the gap. What live loses is the race inside the slice, which a snapshot backtest awards to the strategy every time.

The table as a price list. Each row prices a step of latency, and it gives an honest expectation to report next to any backtest: the same backtest at one and two snapshots of signal delay.

IC(d,h)=corr(st,mt+d+h−mt+d)U(τ)=π¯(ML,τ)−π¯(no ML)π¯(ML,0)−π¯(no ML)
s: the ML prediction; m: the mid price; d: application delay; h: horizon (0.5 s). π̄(·): backtested average profit per lot on the replica; τ: the shift applied to every signal timestamp.
Synthetic data. Illustrative values, generated to show the effect: full uplift only at zero delay, negative from the first snapshot. The method is as built; the desk’s own figures are confidential.
Signal delayIC (h = 0.5 s)Uplift U(τ)Reading
0 s (the backtest as run)0.360100%Full uplift
+0.25 s (one snapshot)0.123−40%Below the no-signal baseline
+0.50 s0.057−76%Chasing
+1.00 s0.024−98%Most of the IC gone
+2.00 s0.004−109%Trades more, chooses worse

3 · One order, two worlds: the open-loop replay

Design (Shuo’s). Take a live order placed at time t; record how its life actually ended; hand the same order, with the same lifetime, to the backtest’s matching engine; record its fate there. As a sanity check, recompute the backtest’s formula price from each order’s own information set.

Order reconstruction. A parser turns the engine’s log lines (insert, acknowledgment, cancel, fill) into complete order lifecycles at nanosecond resolution, validated against the end-of-day counts and against the database to the lot. Orders are keyed by engine run and reference, so a restart can never merge two orders.

Valuation. Mark-outs, not hold-to-close: the comparison is open-loop (a fate difference creates a virtual position that the fixed order stream never rebalances), so each fill is valued by the favorable mid move h seconds later, every partial fill included. Timing compares first fill with first fill, one observation per order.

Result. The backtest fills fewer lots and books far more value, in the same direction at every horizon. The bias is state-dependent: flattering in quiet tape, harsh in a fast market, where snapshot conventions turn cancels that in fact escaped into fills.

Timing. Among the orders filled in both worlds, a large share fill earlier in the backtest, some by many seconds. And for orders the market filled but the backtest never reached, the backtest still believed a queue stood ahead at the moment of the fill: a ghost queue.

Vh=∑f∈fillsδf(m(tf+h)−pf)qfM,Δt=t1replay−t1live
δ: +1 for a buy, −1 for a sell; m(t): the mid; p, q: fill price and lots; M: the contract multiplier; h ∈ {2, 5, 30} s. Δt compares each order’s first fill in the replay with its first fill live.
Synthetic data. Illustrative values, generated to show the effect: 4,000 generated orders sorted by their fate in each world, with each fate’s share of the backtest-minus-live value difference; a negative share is value the backtest fails to credit. The method is as built; the desk’s own figures are confidential.
Fate (live / backtest)OrdersShare of the net over-credit at 30 s
Neither filled1,4150%
Cross missed live, filled in the backtest412+54%
Canceled live, still filled in the backtest197+30%
Filled in both1,254+20%
Filled live, never reached by the backtest722−4%
All 4,000 orders4,000100% (the backtest books 1.46× the live value at 30 s; 1.16× at 5 s, 1.11× at 2 s)

4 · Why the simulator fills early: two mechanisms, both measured

The audit list. Every order that both worlds filled but the backtest filled more than half a snapshot earlier, each row carrying the live lifecycle, both first-fill times, the queue at join and before the fill slice, and the slice’s allocation, so every case could be checked by hand.

A first explanation, refuted. The obvious suspect was the rule that clamps a queue to the displayed size. Shuo rejected it on logic: displayed size is everything ahead of the desk plus everything behind, so clamping to it can only be conservative. An instrumented replay agreed: the early fills are at-price queue fills, not through-price fills and not fills before the order reached the exchange. The fault is over-counted consumption, not position.

Mechanism 1: simultaneous queue-jumping (Shuo’s hypothesis). If a level shows 100 lots and the desk adds 20, the backtest puts the desk at 101–120. If the next snapshot shows 150, others arrived in the same window and some may be ahead of the desk. Screen: did everyone else’s size at the desk’s price grow beyond the backtest’s assumed queue in the first snapshot that surely contains the desk’s order (insert time plus a conservative bound on the channel delay), netting out all of the desk’s own resting lots? Yes for most early fills, stable from day to day, with a dose-response: the more size arrived unseen, the earlier the backtest filled. The ghost queue of section 3, measured independently on orders only the market filled, is of the same size.

Mechanism 2: the two-price allocation. For the remaining early fills, every lot of the ahead-queue was tagged by the rule that removed it, with a checksum equal to the starting queue on every order. Nearly all of it left through allocated slice volume, which burns a queue markedly faster than the market clears it.

A worked example (made-up prices and sizes on the 5-yuan tick). An 8-lot sell rests at 14,775. The replica correctly burns the queue ahead from 47 to 34 on genuine prints at 14,775 and correctly ignores trading one tick below. Then a slice prints 92 lots at a turnover-implied average of exactly 14,770, while the 14,770 level has vanished from the book by the end of the slice. A two-price split anchored on the end-of-slice book has no bucket for it and puts 46 / 46 onto 14,765 and 14,775, wiping the 34-lot queue and filling the order 4.17 s before the market would. A grid rule books all 92 at 14,770 and the early fill disappears.

What cannot be fixed. The backtest-late tail and the ghost queue are an observability limit of snapshot data. Only order-by-order data would remove them, and the reports say so.

5 · Fix one: the queue-join correction

On joining, part of the next snapshot’s growth at the desk’s price is assumed to have arrived ahead of the desk. α = 0.5 is the arrival-symmetry expectation; α = 1 is the worst case (the desk is last in the queue as it now stands). It is not look-ahead: it aligns the virtual order with the moment it would in fact have reached the exchange inside the window, and fills still start only after the next snapshot.

The deliverable is an R function written in the backtester’s own style, so it drops into the main loop directly after the quote-update step: it fires exactly once per order, needs no new order-book columns, and α = 0 reproduces the original engine bit for bit. Its self-test’s expected values were verified through an independent Python port. The model team adopted it.

Qj+1=Dj(p)+α·max(0,Dj+1(p)−Dj(p)),α∈{0,0.5,1}
Q: lots assumed ahead of the desk’s order; D_j(p): size displayed at the desk’s price p in snapshot j (the desk’s own excluded); j: the last snapshot before the order joins. The delivered patch applies the same top-up to the queue as it stands after that snapshot’s other updates.

6 · Fix two: the tick-grid allocation, and the scoreboard

Instead of anchoring on the end-of-slice best bid and ask, allocate a slice’s volume to the tick grid that brackets its own volume-weighted average price; an average that sits on a tick goes to that one price. This removes the vanished-middle-price case of section 4.

A second implementation. A colleague on the model team later wrote an independent version of the allocation rule. Ported and compared, it is pointwise identical to the grid rule on every market slice checked.

Scoreboard. The same replayed live orders through each engine. Each fix helps on its own; together, in V3, they beat either one alone on both timing and over-credit, while α = 1 overshoots into under-crediting. Colleagues then raised a further point, that a cross order cannot fill against the desk’s own resting quote; it was verified in the logs before it was adopted and became the guard in V5, the second engine of the daily report. The daily audit has since found a consistent optimistic bias in the original rule, and the improved one cuts it substantially.

Pseudo-code
function ALLOCATE_ON_GRID(volume, turnover, tick):
    # anchor on the slice's own average price, not on the end-of-slice book
    vwap <- turnover / volume
    if vwap sits on a tick price:
        return all volume at vwap
    lower <- highest tick price below vwap
    upper <- lower + tick
    at_upper <- round((turnover - volume * lower) / tick), kept within [0, volume]
    return (volume - at_upper) at lower, at_upper at upper
Pseudo-code. The tick-grid allocation, simplified: a slice’s volume goes to the two tick prices that bracket its own average price, or all to one price when the average sits on a tick.
Synthetic data. Illustrative values, generated to show the effect: each fix helps alone, both together beat either, and α = 1 overshoots. Δt: first fill in the replay minus first fill live. A negative over-credit means the engine now under-credits fills. The method is as built; the desk’s own figures are confidential.
EngineAllocationαp90 |Δt|5 s over-credit vs V0
V0 (original)two-pricenone8.36 s100%
V1btwo-price0.56.25 s32%
V1two-price15.04 s−23%
V2tick gridnone7.68 s76%
V3 (recommended)tick grid0.55.72 s22%
V4tick grid14.65 s−17%

7 · The cross-order study and LocalTrigger

The question first. What triggers a cross order: the signal, inventory, or both? Two counterfactuals split every cross moment into what the signal alone, inventory alone, or only the two together could have triggered. The study fixed what a local model has to reproduce: the trade-now tail of the signal.

LocalTrigger: the idea. A cross is only worth sending while the thin quote it aims at is still there. So build a compact local surrogate for the signal’s trade-now tail from what is already at hand when a tick arrives, and let the full signal confirm afterwards.

Target. The signal’s value on the current tick.

Features. 44 in the full set: spread, top-of-book and five-level imbalance and their changes (the touch collapsing), log size changes, returns over the last 1, 2 and 4 snapshots, microprice minus mid, signed flow, 1–5 s rolling flow, volume, momentum and volatility, 11 features of the sibling contract and of the price spread between the two contracts, and two signal-lag features carrying the values already received 250 and 500 ms earlier (the last value and its change). Sides are made symmetric by mirroring. The sibling-contract features added almost nothing, so the trees leave them out.

Models. Closed-form ridge regression (squared loss with an L2 penalty, solved by Gaussian elimination written from scratch) and histogram gradient-boosted regression trees written from scratch. The booster fits each tree to the current residuals (squared-error boosting): 30 trees, depth 2, learning rate 0.18, every feature pre-binned into 16 quantile bins, at least 30 rows on each side of a split. It uses 15 of the features: the last signal already received and its change, slice volume, volume bursts and rolling volume, returns over the last 1 and 2 snapshots, top-of-book imbalance and its change, microprice minus mid, signed and rolling flow, the largest recent drop in size at each touch, and rolling volatility. Each fit is stride-subsampled to about 100,000 rows, every row is added again mirrored (bid and ask swapped, target negated), and the output is quantile-calibrated on the training side. The fitted model is exported as a complete specification: every ridge coefficient, every bin edge and every tree as IF/THEN rules.

Validation. Eight-fold expanding walk-forward; each fold trains on all earlier contract-days and tests on the next window: 6,866,001 test ticks across three contract rolls.

Metrics, and one that was rejected. Out-of-sample correlation; a colleague’s n/N recall (of the ticks where the signal says trade now, on how many does the local model also fire); and an end-to-end simulation of the trigger rule on recorded cross moments. An earlier ±0.3 s matching window was thrown out after Shuo questioned it: it had counted fires that were one tick late, and it flattered a rule built on past signals alone. The surviving metric is “same tick or earlier.”

Error cost. A miss costs nothing, because the order still goes out as it does today; false fires are the money error, so they were valued separately by mark-out and tracked month by month, which located a decay in training-sample dilution and not in the market. Deployment rule: busiest contract only, shadow test before any live use.

G=SL2nL+SR2nR−S2n,S=∑i(yi−F(xi)),recall=nN
G: the squared-error gain of a candidate split (the gain line in the sketch). S, n: the sum of residuals and the row count in a node; L, R: its two children; y: the target; F: the ensemble so far, raised in each leaf by the learning rate × that leaf’s mean residual. N: thin-book ticks on which the signal says trade now; n: those on which the local model fires on the same tick.
Pseudo-code
def best_split(node_rows):
    # residual = target - current ensemble prediction
    total = sum(residual[r] for r in node_rows)
    n = len(node_rows)
    if n < MIN_NODE_ROWS:
        return None
    best = None
    for feature in FEATURES:
        # one pass builds the histogram: row count and residual sum per bin
        count, resid_sum = histogram(node_rows, feature)
        left_n, left_sum = 0, 0.0
        for b in ALL_BINS_BUT_LAST:              # every boundary between two bins
            left_n += count[b]
            left_sum += resid_sum[b]
            right_n = n - left_n
            if min(left_n, right_n) < MIN_CHILD_ROWS:
                continue
            gain = left_sum**2 / left_n + (total - left_sum)**2 / right_n - total**2 / n
            if best is None or gain > best.gain:
                best = Split(feature, b, gain)
    return best
Pseudo-code. The split search of the from-scratch histogram booster, simplified: one histogram pass per feature, then the squared-error gain at every bin boundary.
The specification and validation design of Shuo’s own model. Its result is given in words because it measures how much of the desk’s signal can be rebuilt. A research prototype; the recommended next step was a shadow test before any live use.
LocalTriggerSpecification
TargetThe signal’s value on the current tick
Features44: order book, flow, volatility, sibling contract and calendar spread, two signal lags
Linear modelRidge regression, closed form, Gaussian elimination from scratch
Tree modelHistogram gradient boosting from scratch: 30 trees, depth 2, learning rate 0.18, 16 quantile bins, 15 features
TrainingAbout 100,000 stride-subsampled rows per fit, each mirrored; quantile-calibrated output
ValidationEight-fold expanding walk-forward; 6,866,001 test ticks; three contract rolls
MetricRecall of trade-now calls on the same tick or earlier
OutcomeA majority of the signal’s trade-now calls recovered on the busiest contract
ExportEvery coefficient, bin edge and tree as IF/THEN rules

8 · Auditing the server move

Design. The move was the intervention the delay table prices, so the audit tested the mechanism first and the outcome second. If speed had improved, acknowledgments would be faster and cross orders would miss clearly less often.

Latency on one clock. Order-acknowledgment round trip = the engine’s insert line to the first return carrying an exchange order id, both stamped by the same clock, so immune to clock offset. It splits into an engine-local leg and an exchange leg. Feed lag crosses two clocks and is read for trend only.

Outcome. The daily outcome is the live per-lot result minus a same-day control backtest under a frozen configuration; a difference-in-differences before and after the move; then a regression that adds the main confound as a control, with matched day pairs as a cross-check.

Verdict, as written in the report. The order round trip was slower afterward, not faster; attributing any change in results to server speed is not supported by the evidence; nobody should claim the move earned a given amount per lot. The report closed with the tests that would separate the effects, and the daily report went on tracking the same latency measure.

yd=πdlive−πdcontrol,yd=β0+β1postd+β2zd+εd
π: per-lot result on day d; control: the same-day backtest under a frozen configuration; post: 1 after the move; z: a confounder that changed over the same days.

9 · Arbitration and the A/B design

Arbitration. Two runs of the same backtest specification disagreed. The replica matched one of them on lots immediately and on profit to within a few hundredths of a percent. Shuo chased that residual to the individual fill, since identical code on identical data must match perfectly. The clue: every daily difference was an integer multiple of the contract multiplier times half a tick, which only a close-out at the mid of an odd spread can produce, so the number of flattening segments differed. One session-split convention made the match exact on every day; the alternatives tried matched on none.

A/B: the design. A treated contract with the signal off and a matched control contract with it on. Analysis: a same-tape replica of both contracts with and without the signal, using the engine’s own logged predictions and cross fills calibrated on live outcomes; a replica-bias check (live minus replica under the day’s live state); a minute-level block bootstrap; and a power calculation.

Result. Inconclusive, and reported as such: the replica-bias check showed that the comparison could not yet price the signal’s live value precisely enough to call it either way. Shuo designed the follow-up, a daily crossover judged on live minus same-tape replica, and sized it in advance with the power analysis.

10 · Alternatives rejected, and failure modes engineered out

  • “Close enough” replication. Rejected: a 3.7% residual hid an undocumented session-boundary rule. Exactness is the only standard under which a counterfactual isolates one cause.
  • Hold-to-close valuation in the order replay. Rejected: an open-loop replay creates positions the order stream never rebalances; mark-outs at 2, 5 and 30 s carry no holding-period assumption.
  • A fixed ±0.3 s window for “the model fired in time.” Rejected: it credited one-tick-late fires.
  • An off-the-shelf boosting library. The analysis runs on standard-library Python, so ridge and the booster were written from scratch; 30 depth-2 trees are small enough that the exported specification lists every one as IF/THEN rules.
  • Waiting for order-by-order exchange data. It would remove the ghost queue outright, but it is not available; every fix here works from 250 ms snapshots, and the reports say which errors remain.
  • Crediting the server move with a gain. Rejected by the audit’s own confound control.
  • Counting the queue-insertion screen as proof. It is a necessary-condition screen, reported as “insertion ahead was possible and material,” with the dose-response as the supporting evidence.
  • First-pass results that did not add up. Several findings came from checking a first result against domain knowledge before it was reported, the queue mechanism among them.
  • Ambiguous order keys. Orders are keyed by engine run and reference; when the keying was tightened, the affected day was rebuilt and reconciled to the database and the local-model replays were re-run, with no conclusion changed.
  • Unsafe data pulls. Every query is read-only; the database password is typed once, hidden, and held only in the child process’s environment; column names are checked against the schema reference, never written from memory.
  • Unverifiable claims. Every early fill is listed in an audit file with the raw quantities needed to check it by hand.

Built with

  • Python 3.10 (standard library only)
  • SQL · MariaDB
  • R
  • Machine learning
  • Backtesting
  • Exact replication
  • Market microstructure
  • Order-book queue modeling
  • Mark-out analysis
  • Counterfactual simulation
  • Difference-in-differences
  • OLS regression
  • Ridge regression
  • Gradient-boosted trees
  • Histogram gradient boosting from scratch
  • Walk-forward validation
  • A/B testing
  • Block bootstrap
  • Power analysis
  • Nanosecond log parsing
  • Latency measurement
  • Signal decay (IC) analysis
  • Data pipelines
  • Daily production reporting

06Releases

Twelve days from question to production, then the sequels

  1. The comparisonLive per-lot results against every backtest configuration, from one read-only SQL pull.
  2. Bit-exact replica and the delay cliffOne-click daily comparison tool in the afternoon; by late evening the replica matches on every day and configuration tested and the delay report is finished.
  3. One order, two worldsThe order-by-order fate audit and the placement check.
  4. Mechanism and matching variantsSimultaneous queue-jumping report with a worked example; the cross-order study; matching engines V0–V4.
  5. R patch and LocalTriggerThe queue correction delivered as an R patch, which the model team adopted; full-period walk-forward of the local trigger model.
  6. V5 goes to productionColleagues’ own-quote point is verified in the logs and added as a guard; V5 becomes the second engine of the daily report.
  7. Backtest arbitrationA disagreement between two runs of the same backtest settled by reproducing one exactly.
  8. Order-key correctionOrders re-keyed by engine run; the affected day rebuilt and reconciled to the database; the local-model replays re-run, no conclusion changed.
  9. A/B analysis of the signalAn on/off design analyzed on a same-tape replica, with the follow-up crossover test sized in advance.
  1. 1The first comparison ran on August 13, 2026; the order-by-order audit has run as a daily production report since August 25, 2026.
  2. 2Total profit, total lots and total cancels equal on every day and configuration tested (cumulative difference 0.00%), and every fill of a full benchmark day identical in timestamp, price, size and side against a reference fill file. The replica is a Python port of the desk’s R backtester; the backtester itself is the model team’s.
  3. 3The model team supplied the backtester’s R source and the signal files. Colleagues raised several of the questions and ideas tested here: the profit formula and the dominant-month rule used in the comparison, the shorter mark-out horizons, the question behind the cross-order study, an outcome taxonomy for the daily report, the own-quote guard, the recall metric for the local model and an independent rewrite of the allocation rule. They are credited here without names.
  4. 4A backtest counterfactual on the bit-exact replica, not a live latency measurement: every signal timestamp is shifted later and the backtest is re-run. 250 ms is the exchange feed’s snapshot interval. The figure and the table on this page carry synthetic values; the desk’s own figures are confidential.
  5. 5The decision was the desk’s. No speed or profit gain is claimed for the move: Shuo’s own follow-up audit, a difference-in-differences against a frozen control, found the order round trip slower afterward and credited no gain to the move.
  6. 6Every engine is scored on the same replayed live orders. The queue correction was delivered to the model team as an R patch with a self-test, and the model team adopted it. A colleague’s own rewrite of the allocation matched the grid rule on every market slice compared.
  7. 7The desk’s live orders on the audit days, each replayed with its own lifetime through the backtest’s matching rules. Value is the mark-out of every fill at 2, 5 and 30 seconds. The chart and the table on this page carry synthetic values; the desk’s own counts and ratios are confidential.
  8. 8A necessary-condition screen: for each early-filled order, did the size other participants displayed at the desk’s price grow within the same 250 ms window by more than the desk’s own order? It shows queue-jumping was possible and material, and the dose-response supports it. The remaining early fills trace to the two-price allocation.
  9. 9Eight-fold expanding walk-forward, each fold trained on all earlier contract-days: 6,866,001 test ticks across three contract rolls. The signal is the model team’s; LocalTrigger is Shuo’s research prototype, delivered with a deployable specification and a recommended shadow test before any live use.
  10. 10Charts, figure data and screenshots on this page are synthetic, illustrative or public market data. Methods and outcomes are described as they happened; the desk’s own figures are confidential and do not appear here.
  11. 11A treated contract with the signal off and a matched control with it on, analyzed on a same-tape replica of both. The result was inconclusive, so no value is claimed for the signal either way.
Previous
Previous

Smart Queue Review

Next
Next

SPD Parameter Optimizer