Introduction
A limit order book changes through a stream of messages: limit orders are added, partly or fully cancelled, executed, and hidden liquidity trades. A generative model of that stream is a market simulator. Given the same-day history of a book up to some moment, it samples continuations, and the question this task asks is whether the simulated market reacts to what happens in it as the real one does: after a trade or a price change, does the flow of orders, the book and the price respond with the right timing, mix and size?
The field has tried two families of answers. Stochastic models of the book, such as the zero-intelligence model of Cont, Stoikov and Talreja [1], queue-reactive dynamics [2] and compound Hawkes processes [3], are calibrated from the data and have few parameters. Deep generative models learn the message flow itself: token-level autoregressive models with state-space [4] or transformer backbones [5, 6], diffusion models [7] and conditional GANs [8]. LOB-Bench [9] scores such models by distributional distances over features of the generated data.
Three properties make the problem hard, and our method is organised around them.
A message is only meaningful relative to the book. A price is a choice of queue: join the best level, improve inside the spread, open a new level behind the best, or rest far away. A cancellation or execution has to name an order that actually rests in the book. A model that emits absolute prices and order identifiers produces messages the matching engine rejects, and every rejected or replaced row counts against it.
The model is trained on real histories and run on its own. Next-message training conditions on real past messages; at generation time the past is the model's own draws. Small biases in timing or in which events follow which compound over a continuation, much as text from a language model degenerates when it feeds on its own output. In our development runs, a model with good held-out likelihood still produced post-event activity that relaxed too slowly and chains of deep-book deletions that re-triggered themselves.
Likelihood is not the target. What is measured is the distribution of responses in closed loop. We found repeatedly that a lower held-out negative log-likelihood did not mean better closed-loop behaviour, so the design has to correct the closed loop directly.
Method
We call the method BRAT, a book-relative autoregressive transformer. One token is one message row; the model is a causal transformer over a sliding window of rows, and sampling is constrained by a mirror of the matching engine. A short calibration step at the end of the fit then corrects the closed-loop biases that training cannot see.
One message as a book-relative, time-first token
Each row is described by five discrete fields: a delay bin , an event class , a sub-offset that fixes the price inside the region the class names, a size bin , and the age bin of the resting order it targets. The class combines type and side with a price region defined against the book before the row: improve inside the spread, join level for , open a new level in the gap behind level , go deeper than the tenth level, partially cancel or delete at level or deeper, execute at the best, or a hidden execution. That gives 45 locations per side, 90 classes in all.
def _classify(r, pre, tick):
n = len(r)
typ, px, d = r[:, 1], r[:, 4], r[:, 5]
cls = np.full(n, UNK, dtype=np.int64)
sub = np.full(n, NOSUB, dtype=np.int64)
ap, bp = pre[:, 0::4], pre[:, 2::4]
ok = (ap[:, 0] != AD) & (bp[:, 0] != BD)
isb = d > 0
side = np.where(isb, 0, 1)
L = np.where(isb[:, None], bp, ap)
Lok = np.where(isb[:, None], bp != BD, ap != AD)
best = L[:, 0]
sgn = np.where(isb, 1, -1)
dep = sgn * (best - px)
Ldep = sgn[:, None] * (best[:, None] - L)
S = (ap[:, 0] - bp[:, 0]) // tick
nlev = Lok.sum(1)
loc = np.full(n, -1, dtype=np.int64)
a = (typ == 1) & ok
imp = a & (dep < 0)
loc[imp] = C_IMP
eq = (Ldep == dep[:, None]) & Lok
j_any = eq.any(1)
j_idx = np.argmax(eq, 1)
jm = a & ~imp & j_any
loc[jm] = C_J0 + j_idx[jm]
deeper = (Ldep > dep[:, None]) & Lok
g_any = deeper.any(1)
g_idx = np.argmax(deeper, 1)
gm = a & ~imp & ~j_any & g_any & (g_idx >= 1)
loc[gm] = C_G1 + g_idx[gm] - 1
dm = a & ~imp & ~j_any & ~gm
loc[dm] = C_DEEP
lastdep = Ldep[np.arange(n), np.maximum(nlev - 1, 0)]Offsets are coded exactly for one to eight ticks and in geometric bins of ratio 1.1 beyond, sizes exactly up to 128 shares, multiples of ten exactly up to 1000 with other sizes in that range in four range bins, and log-binned above, and delays in bins of 0.2 in nanoseconds, with a separate bin for "same nanosecond as the previous row". A special size class marks an execution that consumes the rest of its order.
The next row is factorised time first:
where is the transformer's state after row . Each later stage adds an embedding of the earlier draws to before its head. Putting the delay first is deliberate: every stage that depends on which resting order is hit comes after the event time is known, so the age of each candidate order can be measured at that time.
def losses(s, h, tgt):
"""h [N,d] hidden states, tgt [N,5] next-row labels. Stages (a marked point process, time first):
dt bin (bin 0 = same nanosecond) -> class -> sub-offset -> size -> target age. Every stage that
depends on which resting order is hit comes after dt, so at sampling a cancel's target is drawn
from the exact joint posterior over the resting orders, with ages measured at the event time."""
cls, sub, szb, ageb, dtb = tgt.unbind(-1)
IG = -100
def ce(lg, y): # mean over labelled positions; 0 (not NaN) when a stage has none
return F.cross_entropy(lg.float(), y, ignore_index=IG, reduction="sum") / (y != IG).sum().clamp(min=1)
out = {}
vc = cls < NC
out["dt"] = ce(s.h_dt(h), torch.where(vc, dtb, IG))
z = h + s.c_dt(dtb)
out["cls"] = ce(s.h_cls(z), torch.where(vc, cls, IG))
z = z + s.c_cls(cls)
out["sub"] = ce(s.h_sub(z), torch.where(vc & (sub < NOSUB), sub, IG))
z = z + s.c_sub(sub)
out["sz"] = ce(s.h_sz(z), torch.where(vc, szb, IG))
z = z + s.c_sz(szb)
out["age"] = ce(s.h_age(z), torch.where(vc & (ageb > 0), ageb, IG))
return outThe input to the transformer is the sum of embeddings of the five fields, a projection of continuous book features (log distances and log sizes of ten levels per side, spread, imbalance, the mid-price change, the signed offset of the row, among others) and a projection of per-cut statistics (from the last 30 minutes of the same-day history: message rate, typical order and execution sizes, shares of executions, partial cancellations, deletions and hidden trades, odd-lot share; and price level, lot size, time of day and time to the close). These statistics condition every token, so the model adapts to a book from data rather than from a per-instrument table. The delay is fed back only through its bin centre, the same in training and sampling, so generated rows carry no within-bin detail that real rows never have. The network has , 8 layers and 8 heads with rotary positions, a conditioning window of 384 rows, and is trained with AdamW (learning rate , weight decay 0.1), dropout 0.1 and an exponential moving average of the weights (0.9995). The best checkpoint is chosen by negative log-likelihood on held-out data, whole days when the training set has enough of them.
Every training window is replaced by its bid–ask mirror image with probability one half. Swapping the sides and reflecting prices is an exact symmetry of the representation, and the mirror doubles the effective data in a regime of many passes over the training days.
Sampling against a mirror of the matching engine
For each stream we keep a mirror of the matching engine, rebuilt from the live book or reused when the engine accepted exactly the rows we proposed. Before a class is drawn, every class that the current book cannot realise is masked: no improvement without a spread of at least two ticks, no gap class without a gap, no cancel at a level whose orders cannot be identified, no execution on an empty best queue.
for side in (0, 1):
L = lv[side]
n = len(L)
base = side * NLOC
if S >= 2:
mask[base + C_IMP] = True
for j in range(min(n, NLEV)):
mask[base + C_J0 + j] = True
if j >= 1 and abs(L[j] - L[j - 1]) // tick >= 2:
mask[base + C_G1 + j - 1] = True
mask[base + C_DEEP] = True
single = nord[side] <= 1
for j in range(min(n, NLEV)):
if not single and del_cands(side, L[j]):
mask[base + C_DEL0 + j] = True
if any(r >= 2 and (o < PLACEHOLDER or len(queue(side, L[j])) == 1) for o, r in queue(side, L[j])):
mask[base + C_CAN0 + j] = True
if n > NLEV:
deep = L[NLEV:NLEV + 64]
if not single and any(del_cands(side, p) for p in deep):
mask[base + C_DEL0 + 10] = True
if any(r >= 2 and (o < PLACEHOLDER or len(queue(side, p)) == 1) for p in deep for o, r in queue(side, p)):
mask[base + C_CAN0 + 10] = True
q0 = queue(side, L[0])
if q0 and not (single and q0[0][1] <= 1):
mask[base + C_EXE] = True
mask[base + C_HID] = TrueA cancellation, deletion or execution is then pointed at an actual resting order. For a deletion we score every candidate order by the model's own joint posterior over the fields it would have produced,
where is the order's remaining size, its age at the event time, and the number of candidates that share the same (offset, size, age) bin, so that each bin's mass is split among the orders in it. Partial cancels draw the cancelled size first and then a target among the larger orders by age; executions hit the front of the best queue. Orders younger than a minimum cancel latency are not eligible for cancellation; the fit estimates that floor as the largest of a few candidate latencies below which at most 0.1% of real cancellations fall.
if is_del: # joint (offset, size, age) posterior over the candidate orders
cb = _size_bin(rems)
pair = xb * NSZT + cb
up, pinv = np.unique(pair, return_inverse=True)
la = hd.mlp("h_age", z[None, :] + hd.c_sub[up // NSZT] + hd.c_sz[up % NSZT]).astype(np.float64)
pa = np.exp(la - la.max(1, keepdims=True))
pa /= pa.sum(1, keepdims=True)
pag = pa[pinv, ages]
score = psz[xinv, cb] * pag * (pag >= AGE_EPS)
if psub is not None:
score = score * psub[xb]
if not (score > 0).any():
return None
_, kinv, kcnt = np.unique(pair * NAGE + ages, return_inverse=True, return_counts=True)
score = score / kcnt[kinv]
if not np.isfinite(score).all() or score.sum() <= 0:
score = np.ones(len(ids))
i = int(rng.choice(len(ids), p=score / score.sum()))
oid = int(ids[i])
return oid, int(prices[i]), int(rems[i]), ("DELETE" if oid < PLACEHOLDER else "CANCEL_LEVEL"), FalseEvery proposed row is applied to the mirror first and only accepted if the mirror accepts it, so the rows we propose contain no rejected action; a stream the sampler cannot continue is handed to the fallback.
Closed-loop calibration inside the fit
The model is trained on real histories, but at generation time its own draws feed back. We therefore end the fit by rolling the trained model out on held-out days, on cuts placed right after a trade or a mid-price change, and matching a few statistics of the generated continuations to the realised ones. The corrections are logit offsets applied at sampling time and ramped in with the number of rows generated since the cut, , because the drift grows with the length of the closed loop. For the delay head,
where is the bin's centre shifted by 4, a tilt of the delay law, one of ten delay groups (same nanosecond, then roughly one group per decade of delay), and a separate correction for the first rows after the cut that fades out as the ramp grows. For the class head,
with one of eleven event groups and a diagonal matrix that only acts when the next event repeats the group of the previous one: a learned correction of repeats, of either sign, aimed at self-sustaining chains.
def _dt(self, h, min_dt, rng):
"""stage 0: bin 0 = same nanosecond as the previous row (only if no minimum delay applies), else a
log-binned delay >= min_dt."""
lgd = self.hd.mlp("h_dt", h)
w = min(1.0, self.nstep / TILT_RAMP)
lgd = lgd + w * (self.tilt * _DT_LOGC + self.dt_off) + (1.0 - w) * self.dt_off0
dmask = _HI_EDGE > min_dt
dmask[0] = min_dt <= 0
dmask[-1] = True
db, _ = _softmax_sample(lgd, dmask, rng)
if db <= 0:
return 0, 0
lo = 0.2 * (db - 1)
hi = 0.2 * db if db < NDT - 1 else 12.2
lo = max(lo, math.log10(max(min_dt, 1)))
return max(int(10.0 ** rng.uniform(lo, max(hi, lo))), min_dt, 1), dbThe fit estimates these in two stages. First it rolls out the model at three tilts, , with common random numbers, and interpolates the tilt at which the mean log delay over the later rows of a continuation matches the real one, clipped to . Then, at that tilt, it runs three rounds of damped iterative proportional fitting: each offset moves by of its group's share, clipped to ; the repeat penalty moves by the same step on the conditional share of a repeat minus the marginal step, clipped to ; groups with fewer than 50 counts (100 for repeats) are left alone. If calibration fails, or no time is left to start it, all corrections stay at zero and the fit still completes; if time runs out between rounds, the corrections fitted so far are kept.
for rnd in range(3):
if time.time() > deadline - 60:
break
rr = _cal_run(specs, ckpt, [(tilt, off_g[:NGROUP][CLS_GROUP], off_g[NGROUP:][DT_GROUP], big, off_e[DT_GROUP])],
n_gpus, seed + 17, deadline)
gg = rr[0][1]
stepm = np.zeros(NGROUP)
for lo, hi in ((0, NGROUP), (NGROUP, K)):
a, b = rg[lo:hi], gg[lo:hi]
ok = (a >= 50) & (b >= 50)
if not ok.any():
continue
pr, pg = a / max(a.sum(), 1), b / max(b.sum(), 1)
step = np.where(ok, 0.7 * np.log(np.maximum(pr, 1e-9) / np.maximum(pg, 1e-9)), 0.0)
off_g[lo:hi] = np.clip(off_g[lo:hi] + step, -1.0, 1.0)
if lo == 0:
stepm = step
info[f"mix{rnd}_{lo}"] = dict(real=np.round(pr, 4).tolist(), gen=np.round(pg, 4).tolist())
a, b = rg[NCAL - NDTG:], gg[NCAL - NDTG:]
ok = (a >= 50) & (b >= 50)
if ok.any():
pr, pg = a / max(a.sum(), 1), b / max(b.sum(), 1)
off_e = np.clip(off_e + np.where(ok, 0.7 * np.log(np.maximum(pr, 1e-9) / np.maximum(pg, 1e-9)), 0.0), -1.0, 1.0)
info[f"early{rnd}"] = dict(real=np.round(pr, 4).tolist(), gen=np.round(pg, 4).tolist())
tr, tg = rg[K:K + NGROUP * NGROUP].reshape(NGROUP, NGROUP), gg[K:K + NGROUP * NGROUP].reshape(NGROUP, NGROUP)
ok = (tr >= 100) & (tg >= 100) & np.eye(NGROUP, dtype=bool) # self-transitions: closed-loop self-excitation
cr = tr / np.maximum(tr.sum(1, keepdims=True), 1)
cg = tg / np.maximum(tg.sum(1, keepdims=True), 1)
stepb = np.where(ok, 0.7 * np.log(np.maximum(cr, 1e-9) / np.maximum(cg, 1e-9)) - stepm[None, :], 0.0)
big = np.clip(big + stepb, -2.0, 2.0)All corrections are pooled across instruments and days and estimated from the training data inside
fit. The same code and constants run everywhere; there is no per-setting branch.
Results
| Method | ① | ② | ③ | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Market response score ↓ | Rejected rows, % ↓ | L1 at continuation start ↓ | Continuation energy score ↓ | Market response score ↓ | Rejected rows, % ↓ | L1 at continuation start ↓ | Continuation energy score ↓ | Market response score ↓ | Rejected rows, % ↓ | L1 at continuation start ↓ | Continuation energy score ↓ | |
| Claude Opus 5.5 | 1.693 | 0 | 0.076 | 2.119 | 2.068 | 0 | 0.107 | 2.588 | 2.044 | 0 | 0.115 | 2.629 |
| Cont-Stoikov-Talreja model | 3.682 | 2.223 | 0.335 | 3.168 | 3.149 | 7.905 | 0.424 | 5.570 | 3.257 | 6.233 | 0.362 | 4.759 |
| Queue-Reactive | 2.479 | 0.067 | 0.329 | 3.023 | 3.357 | 0.028 | 0.517 | 13.21 | 3.199 | 0.048 | 0.425 | 5.591 |
| Hawkes process | 2.510 | 0.034 | 0.324 | 3.251 | 3.384 | 0.050 | 0.422 | 7.254 | 3.506 | 0.042 | 0.355 | 5.636 |
| MarS | 1.894 | 0.144 | 0.263 | 2.614 | 2.593 | 0.044 | 0.337 | 3.238 | 2.454 | 0.097 | 0.305 | 3.392 |
| MarS, multi-order cancels | 1.825 | 0.061 | 0.243 | 4.182 | 2.575 | 0.029 | 0.326 | 4.304 | 2.374 | 0.096 | 0.294 | 4.456 |
| MarketGPT | 1.808 | 0.058 | 0.223 | 2.578 | 2.290 | 1.966 | 0.261 | 2.675 | 2.150 | 0.751 | 0.236 | 2.911 |
| LOBS5 | 3.180 | 3.719 | 0.271 | 3.025 | 2.988 | 14.40 | 0.333 | 4.999 | 3.272 | 11.53 | 0.295 | 4.178 |
| TRADES | 2.565 | 0.008 | 0.409 | 3.403 | 3.502 | 0.126 | 0.378 | 9.683 | 3.371 | 0.206 | 0.391 | 11.01 |
| Conditional WGAN world agent | 4.806 | 0 | 0.554 | 11.36 | 8.221 | 0 | 0.446 | 19.49 | 5.317 | 0 | 0.420 | 14.91 |
- ① Large-tick stocks, months later
- ② Small-tick stocks, months later
- ③ Tickers unseen in training
BRAT has the lowest react of all published baselines on every setting. On Large-tick it reaches 1.693 against 1.808 for the strongest baseline, MarketGPT [5]; on Small-tick 2.068 against 2.290 (MarketGPT [5]); on New-ticker 2.044 against 2.150 (MarketGPT [5]).
The realism measures move the same way. No generated row was rejected or replaced on any setting, which is what the mirror engine is built to ensure; the conditional GAN also reaches 0.000 there, but at a far higher react. The L1 distance on the start of the continuation is the clearest gap: 0.076 on Large-tick against 0.223 for MarketGPT [5], and similar margins on Small-tick and New-ticker. The energy score of the continuation summary is lowest on every setting too, though by a smaller margin on Small-tick, 2.588 against 2.675 for MarketGPT [5].
Large-tick is the easiest for most methods in the table, and our react rises from 1.693 there to 2.068 and 2.044 on the other two, while our margin over the strongest baseline stays of the same order. The development measurements in the next section explain where the remaining error lies.
How we got here
The method came from a long sequence of closed-loop experiments, each run on cuts from held-out training days with our own approximations of the task's measures. All numbers in this section are those development measurements, not the task's.
- The representation came first. We read the reference generators, then built the book-relative class space and the mirror engine before training anything. The first model, after a short training run, already showed a large gap to the starter on our proxies: an L1 of 0.16 against 0.36 and an energy score of 3.1 against 5.3 on the same 64 cuts.
- Class first lost the joint information of a cancel; delay first restored it. An early version drew a deep deletion's offset from its marginal before the delay. Only 58% of deep deletes were then followed by a re-add, against 82% in an earlier joint version and 84% in real data. Moving the delay to the front and drawing the target from the exact joint posterior brought that back to 85% and executions to 3.11 per 100 rows against 3.07 real. This is the factorisation we kept.
- Rejection sampling of infeasible events made things worse. We tried accepting an event with probability equal to the model's mass on targets present in the book and redrawing otherwise. Our react proxy doubled (0.207 against 0.095), and we reverted it. Excluding age-implausible targets gave mixed results, and ignoring the age head made things worse.
- Changes to training and to the model did not remove the drift. Longer training, scheduled sampling of the input delays, a longer conditioning window, an ensemble of two models and a deep-book state feature (counts of orders beyond the tenth level by age) left the closed-loop time compression largely unchanged or were within seed noise. Feeding the delay back only as its bin centre helped (react proxy 0.081 against 0.096 for the control) and was kept, as were the minimum cancel latency and dropout 0.1. A wider model () had much lower held-out loss and a clearly worse energy score in closed loop; dropout 0.2 lowered validation loss and worsened L1. Likelihood was not a reliable guide.
- Correcting the closed loop directly worked. A hand-set tilt of the delay law improved all four of our proxies at once, which told us the bias was in timing. A constant was not acceptable as a method, so we turned it into the fit-time calibration. Tilt alone lowered our energy-score proxy by about 3 standard errors; adding the event-mix offsets lowered our react proxy from 0.079 to 0.057. A full transition matrix of offsets gave mixed results, which we put down to noisy sparse cells; we kept only its diagonal, the repeat penalty. The bid–ask mirror augmentation improved L1 and energy score at a small cost on react. A fourth proportional-fitting round, truncating low-probability draws, per-class offsets and per-trigger tilts were not better.
- Ablations of the final calibration. Removing the tilt, the repeat penalty or the first-row delay correction each made our proxies worse; the repeat penalty matters most, and without it deep-delete repeats rose from 5.5% to 12.4% (3.5% in real data). Over three calibration seeds the final calibration lowered our L1 proxy by about 12%, our react proxy by about 24% and our energy-score proxy by about 10% against the uncalibrated model, with little spread between seeds.
The repetition penalty plays the role that unlikelihood training and repetition penalties play in text generation, and the calibration as a whole resembles statistical post-processing of weather forecasts, where a model's biases are re-estimated against observations. We noticed both analogies only after the design was in place.
Limitations
- The calibration is pooled and fitted on few days. The corrections are the same for every instrument and every day, estimated on whole held-out training days. In our development runs a day outside the calibration days needed a stronger timing correction than the pooled one, and continuations there were still too fast by a median of about 0.37 decades in time to the hundredth event. Calibrating on that day itself, as an upper bound, recovered most but not all of the gap. Making the correction depend on statistics of each context would need more held-out days than were available.
- Timing and event mix are coupled. Because the event class is drawn given the delay, a stronger delay correction also changes which events happen; in our tests it worsened depth and spread after many events. A time warp that rescales only the emitted timestamps would separate the two, and we did not build it.
- Price impact fades too fast. In our development measurements the generated price response over longer lags is weaker than the real one, and the side of the book a trade consumed refills too early and recovers too little later. Nothing in the calibration targets the signed price move or the depth recovery after the trigger.
- Our scores are not uniform across settings. React on Small-tick and New-ticker is higher than on Large-tick by more than our lead over the strongest baseline on either. Most methods are worse there, but our pooled calibration does not close that gap.
- The method is large and costly. The submission is close to 2,000 lines; training uses every GPU through data-parallel training, and the calibration takes part of the fit budget away from training. In development we saw seed-to-seed differences in our energy-score proxy comparable to the effects of several design choices.
References
- Rama Cont, Sasha Stoikov, Rishi Talreja (2010). A Stochastic Model for Order Book Dynamics. Operations Research.
- Patrick Noble, Mathieu Rosenbaum, Saad Souilmi (2026). Bridging the Reality Gap in Limit Order Book Simulation.
- Konark Jain, Nick Firoozye, Jonathan Kochems et al. (2023). Limit Order Book Dynamics and Order Size Modelling Using Compound Hawkes Process.
- Peer Nagy, Sascha Frey, Silvia Sapora et al. (2023). Generative AI for End-to-End Limit Order Book Modelling: A Token-Level Autoregressive Generative Model of Message Flow Using a Deep State Space Network.
- Aaron Wheeler, Jeffrey D. Varner (2024). MarketGPT: Developing a Pre-trained transformer (GPT) for Modeling Financial Time Series.
- Junjie Li, Yang Liu, Weiqing Liu et al. (2025). MarS: a Financial Market Simulation Engine Powered by Generative Foundation Model. ICLR.
- Leonardo Berti, Bardh Prenkaj, Paola Velardi (2025). TRADES: Generating Realistic Market Simulations with Diffusion Models. Frontiers in Artificial Intelligence and Applications.
- Andrea Coletta, Aymeric Moulin, Svitlana Vyetrenko et al. (2022). Learning to simulate realistic limit order book markets from data as a World Agent. Proceedings of the Third ACM International Conference on AI in Finance.
- Peer Nagy, Sascha Frey, Kang Li et al. (2025). LOB-Bench: Benchmarking Generative AI for Finance -- an Application to Limit Order Book Data. ICML.