Introduction
A limit order book changes through a stream of messages: new limit orders (LO), cancellations (CA)
and executions triggered by market orders (MO). A generative model of that stream is meant to serve as
a market simulator. Given the same-day history up to a cut, it samples continuations, and those
continuations should respond to events the way the real market does. A market order should move
the price by about the right amount over the right horizon, and a run of buying should look like
real buying. That is what react measures, and it is a harder target than matching marginal
distributions of sizes, prices and inter-arrival times.
The field covers a wide range of models. At one end are stochastic models of the book that are cheap and interpretable: the Cont-Stoikov-Talreja zero-intelligence model, which is this task's starter [1], queue-reactive models whose intensities depend on a projected book state such as spread and imbalance [2], and compound Hawkes processes with self- and cross-excitation [3]. At the other end are learned sequence models of the message stream: a world agent trained as a conditional GAN [4], token-level autoregressive models built on state-space networks [5], order-level transformer foundation models [6, 7] and diffusion models [8]. LOB-Bench [9] is a common benchmark for generative models of limit-order-book data.
Our starting observation came from our own development harness, which ran on cuts drawn from the training days. The starter and the queue-reactive baseline both produced order flow with almost no sign memory. In our development measurement the lag-1 sign autocorrelation was 0.32 for the real flow, 0.014 for the queue-reactive model and 0.11 for the starter. Neither produced the price drift that follows a real market order, which in the same measurement was about +2.5 ticks for the real data and close to zero for the queue-reactive model. A model that conditions only on the instantaneous book cannot carry the persistence of a large parent order being worked over many child orders. Our method adds that persistence as a latent state, keeps everything else as simple conditional tables, and is therefore fast and almost never emits an invalid message.
Method
We call the method MQR: a queue-reactive marked point process with a latent metaorder regime. Each event is sampled from a factorised conditional model
where is the kind, the side, the price level (inside the spread, at the touch, or one, two or three-plus ticks behind it), the size and the inter-arrival time. The state is : , is one of seven bins of the best-level imbalance with edges at , and , is the metaorder regime, and when the previous event was a market order. That gives states. Every conditional is a count table, and sampling is a sequence of inverse-CDF draws against a shadow copy of the current book.
The regime: labelled from flow, evolved as a semi-Markov chain
In training, the regime has to be read off real data. We give every event a signed flow for limit and market orders (the aggressor's side for a market order) and for cancellations, smooth it with an exponential moving average and threshold it:
The label for event uses flow only up to , so the tables learn what follows from a regime, not what defines it.
# persistent flow regime R from EWMA of net signed flow (LO adds, MO consumes, CA removes),
# thresholded into neutral/buy/sell. State BEFORE event i uses flow up to i-1.
mo = kind == K_MO
f = np.where(kind == K_CA, -side, side).astype(float)
from scipy.signal import lfilter
p = lfilter([ALPHA], [1.0, -(1.0 - ALPHA)], f)
p_before = np.concatenate([[0.0], p[:-1]])
R = np.where(p_before > REG_THR, 1, np.where(p_before < -REG_THR, 2, 0)).astype(np.int64)
# burst state B = previous event was a MO (MO time-clustering)
B = np.zeros(len(r), np.int64)
B[1:] = mo[:-1].astype(np.int64)In generation there is no data to label, so the regime is exogenous. From neutral, a metaorder starts with probability 0.016 per event, buy or sell with equal probability. Its dwell, counted in events, is drawn from a two-component geometric mixture:
so most metaorders are short and some are long. A mixture of two time scales gives a slower decay of flow autocorrelation than a single geometric dwell would. When the dwell runs out, the regime returns to neutral.
Kind and side: three Markov chains and a regime tilt
The kind is drawn from with add-one smoothing. Its market-order column is scaled by 0.9 when and by 0.8 when before normalisation, a calibration that lowers the market order rate and the burst persistence of the fitted tables toward the rates we measured in development; the exact factors were chosen by sweeps.
def build_tables(acc, mes, smooth=1.0):
kind = acc["kind"] + smooth
kind[1::2, K_MO] *= BURST_SCALE
kind[::2, K_MO] *= MO_RATE
kc = kind / kind.sum(-1, keepdims=True)
side = acc["side"] + smooth
sc = side / side.sum(-1, keepdims=True)
lvl = acc["lvl"] + smooth
lvl[: N_IMB * N_R * N_B, :, :, 0] = 0.0
lc = lvl / np.maximum(lvl.sum(-1, keepdims=True), 1e-9)The side is where most of the persistence lives, and each kind gets its own model. Let for the buy, sell and neutral regime, let , and let be a fitted Markov table of the side given the imbalance bin and the side of the previous event of the same kind. Then
The Markov term carries short-lag persistence and the regime tilt carries the long tail. The factor weakens the tilt when the spread is wide. The cancellation table is smoothed with 5 pseudo-counts per cell and the other two with one. A market order takes its side from its own last-sign chain alone; the regime reaches market orders only through the kind, timing and size tables, which are conditioned on the state. In the buy regime the tilt raises the probability that a cancellation is on the bid side, while the training labels count a bid-side cancellation as sell flow; we kept that sign because it helped in development, not because we derived it.
The term is a short-lived contrarian bias on limit-order sides. When the mid price has moved since the previous step, is reset to after an up-move and after a down-move. It is then multiplied by 0.7 at every step, including the step that set it:
It gives limit-order flow a little of the mean reversion that the real book shows after a price change. It applies only while the spread is at most 5 ticks.
def step(self, sh):
bb, ba = sh.best_bid(), sh.best_ask()
if bb is None or ba is None:
return None, 0, False
tick = self.tick
mid_now = 0.5 * (bb + ba)
if self.prev_mid is not None:
dmid = mid_now - self.prev_mid
if dmid != 0:
self.mr_bias = -MR_STRENGTH if dmid > 0 else MR_STRENGTH
self.prev_mid = mid_now
self.mr_bias *= MR_DECAY
qb = sh.level_vol(1, bb); qa = sh.level_vol(-1, ba)
imb = (qb - qa) / max(qb + qa, 1)
spr = (ba - bb) // tick
sp = 0 if spr <= 1 else 1 rng = self.rng
if self.R == 0:
if rng.random() < P_START:
self.R = 1 if rng.random() < 0.5 else 2
mean_d = DWELL_SHORT if rng.random() < DWELL_PSHORT else DWELL_LONG
self.dwell = max(1, int(rng.geometric(1.0 / mean_d)))
else:
self.dwell -= 1
if self.dwell <= 0:
self.R = 0
st = _state_idx(sp, imb_bin(imb), self.R, self.B)
sh_f = 1.0 / math.sqrt(max(1, (ba - bb) // tick))
k = min(_draw(self.tab["kind_cdf"][st], rng.random()), N_KIND - 1)
if k == K_LO:
lms = 0.8 if spr <= 1 else LO_MARKOV_SCALE
pb_lo = 0.5 + lms * (float(self.tab["lo_markov"][imb_bin(imb), self.last_lo]) - 0.5)
pb_lo += sh_f * (LO_REG_SHIFT if self.R == 1 else (-LO_REG_SHIFT if self.R == 2 else 0.0))
pb_lo = min(0.98, max(0.02, pb_lo + (self.mr_bias if spr <= 5 else 0.0)))
sd = 0 if rng.random() < pb_lo else 1
elif k == K_CA:
pb_ca = float(self.tab["ca_markov"][imb_bin(imb), self.last_ca])
pb_ca += sh_f * (CA_REG_SHIFT if self.R == 1 else (-CA_REG_SHIFT if self.R == 2 else 0.0))
pb_ca = min(0.98, max(0.02, pb_ca))
sd = 0 if rng.random() < pb_ca else 1
else:
sd = min(_draw(self.tab["side_cdf"][st, k], rng.random()), 1)
if k == K_MO:
pb = float(self.tab["mo_markov"][imb_bin(imb), self.last_mo])
sd = 0 if rng.random() < pb else 1
side = 1 if sd == 0 else -1
if k == K_LO: self.last_lo = sd
if k == K_MO: self.last_mo = sd
if k == K_CA: self.last_ca = sdMarket orders are sized against the queue they hit
A market order is drawn as a ratio to the best queue it hits, not as an absolute size. The ratio table is fitted on each execution row's size divided by the best queue at that moment, and a drawn bin is used at its midpoint:
The order is sent as a marketable limit two ticks through the touch, so it can sweep up to three levels. The shadow book refuses it if it would empty the whole opposite side. Limit orders and cancellations instead use a size in multiples of a per-(kind, level) median event size, and an inside-spread limit order is placed uniformly among the free price levels inside the spread.
if k == K_MO:
# size relative to the queue it hits (empirical ratio ~ 1 -> depletes the touch)
rb = min(_draw(self.tab["mo_ratio_cdf"][self.R, self.B], rng.random()), N_RATIO - 1)
ratio = 0.5 * (RATIO_EDGES[rb] + RATIO_EDGES[rb + 1])
hit_q = qa if side > 0 else qb
size = max(1, int(round(hit_q * ratio * MO_SIZE_MULT)))
else:
szm = min(_draw(self.tab["size_cdf"][k, lv, sd], rng.random()), MAXSZ - 1) + 1
size = max(1, int(szm * self.mes[k, lv]))
dc = self.tab["dt_cdf"][st, k]
b = min(_draw(dc, rng.random()), DT_MAX_BIN)
ldt = b * 0.2 + rng.random() * 0.2
dt = max(1, int(10.0 ** ldt))
self.t += dt
t = self.t
self.B = 1 if k == K_MO else 0
if k == K_MO:
px = ba + 2 * tick if side > 0 else bb - 2 * tick # sweep up to 3 levels
n = sh.limit(side, px, size)
return (Action.limit(t, side, px, size), n, True) if n >= 0 else (None, 0, True)Fitting and per-cut calibration
fit builds count tables for every training instrument from its training days (in parallel worker
processes) and a pooled table, and stores, for each instrument, three features: the log event rate,
the log median spread and the log median price in ticks. At each cut, begin_cut counts the same
day's history up to the cut and shrinks it toward a prior table:
so the prior always carries 3000 pseudo-events, whatever its own size. The prior is the instrument's own table when there is one, otherwise the nearest instrument in the standardised three-feature space, and otherwise the pooled table. The median sizes come from the history when it holds more than 500 events and from the prior otherwise.
def _calibrate(self, ctx):
since = max(600.0, ctx.tod_s - HIST_START_S)
hr, hb = ctx.history(since)
tick = int(ctx.tick)
t_lo = -int(since * NS)
feat = _feat(hr, hb, tick, t_lo, 0)
prior = self._prior_for(ctx, feat)
ex = extract(hr, hb, tick, t_lo, 0, max_rows=HIST_MAX_ROWS)
if ex is not None:
mes_h = _mes_from(ex)
acc_h = accumulate(_empty(), ex, mes_h)
else:
mes_h = prior["mes"]; acc_h = _empty()
n_prior = float(prior["n"])
lam = PRIOR_PSEUDO / max(n_prior, 1.0)
post = {k: acc_h[k] + lam * prior[k] for k in ("kind", "side", "lvl", "size", "mo_ratio", "lo_markov", "mo_markov", "ca_markov", "dt")}
post["n"] = acc_h["n"] + PRIOR_PSEUDO
mes = mes_h if ex is not None and acc_h["n"] > 500 else prior["mes"]
return build_tables(post, mes)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 ↓ | |
| Qwen4-Max | 2.558 | 0.053 | 0.316 | 3.004 | 3.069 | 0.116 | 0.452 | 4.225 | 3.006 | 0.071 | 0.390 | 3.784 |
| 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
react. MQR improves on the starter on every setting: 2.558 against 3.682 on Large-tick, 3.069 against 3.149 on Small-tick and 3.006 against 3.257 on New-ticker. Against the other stochastic models the picture depends on the setting. On Small-tick and New-ticker MQR is ahead of the queue-reactive model (3.357 and 3.199) and of the Hawkes model (3.384 and 3.506). On Large-tick both are ahead of us (2.479 and 2.510). The transformer models are well ahead everywhere: the best baseline is MarketGPT [7] on each setting, at 1.808, 2.290 and 2.150, and both MarS variants are also ahead of us on every setting. Counting all published baselines, five are ahead of MQR on Large-tick, four on Small-tick (the three transformer models and LOBS5, at 2.988) and three on New-ticker.
Realism measures. On the energy score of the continuation summary MQR is third on every setting, behind MarketGPT [7] and the MarS order model and ahead of everything else: 3.004, 4.225 and 3.784, against the starter's 3.168, 5.570 and 4.759. Rejected rows stay small, 0.053, 0.116 and 0.071, against 2.223, 7.905 and 6.233 for the starter. That is the shadow book doing its job. The conditional GAN has no rejected rows at all, the Hawkes model has fewer than we do on every setting, the queue-reactive model on Small-tick and New-ticker, TRADES on Large-tick and both MarS variants on Small-tick. L1 is our weakest measure. MQR improves on the starter only on Large-tick (0.316 against 0.335) and is worse than it on Small-tick (0.452 against 0.424) and New-ticker (0.390 against 0.362). On Small-tick only the queue-reactive model has a higher L1 than ours.
Taken together, our cheap table model is better than the zero-intelligence starter on every setting, and on two of the settings better than the snapshot queue-reactive and Hawkes models, on the measure the task cares about most. It did not close the gap to the learned sequence models.
How we got here
The design came out of one diagnosis, flow without memory, followed by a long sequence of failed and successful attempts to put the memory back. The agent's trace records more than eighty variants. The development numbers below are the agent's own measurements on cuts from the training days. They use its own proxies for the response score, mainly an energy distance over pooled response-curve, sign-autocorrelation and order-flow-imbalance features, where lower is better.
- An endogenous pressure state could not break symmetry. Our first version conditioned on an exponential moving average of signed market-order and inside-spread limit-order flow. The pressure decayed to zero between sparse market orders, and generated sign autocorrelation stayed near zero. Driving it with all signed flow did not help either: in our development runs the pressure stayed near zero (standard deviation 0.128) and was beyond only about 2% of the time. We concluded that persistence had to come from outside, as an exogenous regime, although these measurements predate the sign-encoding fix described next. A three-state hidden Markov model fitted to the flow reproduced the persistence in development (market-order sign autocorrelation 0.647 against 0.609 real), but labelling with it was slow, so the final labels use the thresholded moving average, which tracked it well.
- One sign-encoding bug undermined every early version. Training stored buy as 1 while generation read 0 as buy, so the learned positive feedback became negative feedback, which killed the memory and flipped the sign of the price response. After the fix, development market-order sign autocorrelation went to 0.687 against 0.609 real, and the development response first beat the queue-reactive model's.
- Market orders come in bursts and are sized to the queue. In our development probe, the probability that a market order follows a market order was 0.41 against a base rate of 0.047, and the median ratio of market-order size to the best queue was 0.96. That led to the burst flag and the queue-relative size. An attempt to group fills into whole aggressor orders reduced the market-order rate too much and was dropped.
- Persistence needed both a Markov term and a regime tilt. A last-sign Markov chain for limit orders matched real lag-1 autocorrelation (0.42 against 0.37 real) but decayed far too fast (0.015 at lag 5 against 0.20 real). Adding the regime tilt on top supplied the tail, and our development proxy fell from 1.70 to 0.98, averaged over three development splits. On a single split, a market-order Markov chain then lowered it from 0.921 to 0.811, and a cancellation chain with its own regime tilt lowered it to 0.575, whereas the cancellation chain without a tilt had made things worse.
- Spread-awareness came from the least liquid instruments. On the widest-spread instruments in our development data, flow at the touch was nearly uncorrelated and the fixed tilt persisted too much, so the tilt was scaled by . Inside-spread limit orders had always been placed one tick inside; placing them uniformly across the spread improved or matched every development split we checked.
- Mean reversion only helped when it was narrow. Real prices revert after some events where ours continued. A uniform contrarian bias on all sides disturbed cancellation dynamics that were already right, so we restricted it to limit orders. Even so, it hurt the widest-spread instruments (1.47 against 1.24 in development), and scaling it by made that worse (1.62). Gating it to spreads of at most 5 ticks fixed the regression (1.139). A later ablation that removed it was worse on the development splits it was tried on. The damping of the limit-order chain came from the same kind of search: generated limit-order sign runs were longer than real ones (a mean of 4.4 against 3.3). Ungated, and still with a gate at five ticks, the damping hurt the widest-spread instruments; with tighter gates it helped, and the tightest gate, to one-tick spreads, worked best.
- Abandoned directions. A small numpy MLP in place of the kind and side tables was worse in development (0.665 against 0.472) and slower. Sampling realistic far-from-touch depths for deep limit orders, queue-relative sizes for limit orders and cancellations, a regime that ends once its impact reaches a target, regime-sign reversal, a Pareto dwell and a queue-size state all made the development response proxy worse on balance. We also found that limit-order and cancellation sizes are reconstructed at the upper edge of their bin, which biases them upward. Two unbiased reconstructions both did worse on balance: the first one looked like a large gain only until we repeated the baseline on a matched set of development cuts. We kept the biased version, on the reading that the rest of the calibration had grown around it.
Our development comparisons were only against the starter and the queue-reactive model. The Hawkes baseline could not run in our development environment because of a missing dependency, and we did not run the transformer baselines.
Limitations
- The learned sequence models are far ahead. On react, MarketGPT and both MarS variants beat MQR on every setting, by wide margins: on Large-tick, 1.808 against our 2.558. A per-state table model cannot represent the long-range dependence those models learn. Our contribution is a better cheap simulator, not a better simulator overall.
- Our development proxy overstated the gain. On our own proxies MQR looked several times better than the queue-reactive model. On the measured react it is ahead of that model on Small-tick and New-ticker only by modest margins, and behind it on Large-tick (2.558 against 2.479). Our development cuts came from the training days, on which the per-instrument tables were also fitted, and the proxy features are our own reconstruction of response features, not the task's.
- The calibration is tuned, not derived. The regime-start probability, the dwell mixture, the tilt strengths, the market-order scalings, the inter-arrival cap at bin 50 of the histogram, the mean-reversion strength, decay and gate, and the limit-order damping and its gate were all chosen by sweeps on development cuts. Several of them trade one measure against another. The biased size reconstruction and the larger-than-measured market orders are known compensating errors that we kept.
- L1 got worse on two settings. Our L1 is worse than the starter's on Small-tick and New-ticker. Deep limit orders are placed at most three ticks behind the touch, much shallower than the real far-from-touch depths we observed in development, and fixing that hurt the response.
- One sign in the method is unexplained. The cancellation tilt raises bid-side cancellations in the buy regime, which is the opposite of how the training labels count a bid-side cancellation. It was kept on its development effect.
- The file's self-description is stale. The module docstring still describes an earlier version
whose regime was the last market-order sign. The constants
MO_BIASandHMM_A(withHMM_CUM, computed from it) are defined but play no part in fitting or generation.
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.
- 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, 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.
- Junjie Li, Yang Liu, Weiqing Liu et al. (2025). MarS: a Financial Market Simulation Engine Powered by Generative Foundation Model. ICLR.
- Aaron Wheeler, Jeffrey D. Varner (2024). MarketGPT: Developing a Pre-trained transformer (GPT) for Modeling Financial Time Series.
- Leonardo Berti, Bardh Prenkaj, Paola Velardi (2025). TRADES: Generating Realistic Market Simulations with Diffusion Models. Frontiers in Artificial Intelligence and Applications.
- Peer Nagy, Sascha Frey, Kang Li et al. (2025). LOB-Bench: Benchmarking Generative AI for Finance -- an Application to Limit Order Book Data. ICML.