Introduction
A limit order book changes only through messages: a new limit order is added at a price, an existing order is partly cancelled or deleted, a resting order is executed against, or a trade happens against hidden liquidity. A generative model of the book is a model of this message stream. Given the same day's history up to a cut, it samples continuations, and those continuations are judged, above all, on whether the simulated market reacts to events in it the way the real market does: what the order flow, the book and the price do after a trade, a cancellation or a change of the best quotes.
Three properties make this hard.
Messages are not free-standing tokens. A cancellation or an execution names a specific order that must be resting in the book; a new order must be at a price the book allows; a partial cancellation must leave something behind. A model that emits messages as sequences of tokens over absolute prices and identifiers can produce a message that refers to nothing, and the matching engine rejects it.
The relevant state is long and multi-scale. How the flow responds depends on the queue at each price, on the age and position of individual orders, on how much has traded in the last millisecond and in the last minute, and on the regime of the day: how wide the spread usually is, how fast messages arrive, how large orders are.
Regimes differ across assets and days. A model trained on a pool of days must transfer to an asset or a day whose spread, depth, message rate and order sizes it has not seen in that combination.
The field has answered with three families of model. Point-process and zero-intelligence models describe order arrival, cancellation and execution through stochastic rates, from the stochastic model of Cont, Stoikov and Talreja [1], which this task's starter implements and calibrates per cut on same-day history as LOB-Bench does [2], to compound Hawkes processes [3] and queue-reactive models [4]. Deep generative models learn the flow from data: an autoregressive deep state-space model at the level of tokens [5], pretrained transformers over order streams [6, 7], diffusion [8] and a conditional adversarial world agent [9]. Rate models are simple to keep consistent with the book but too simple to react realistically; learned models can react, but must learn validity along with everything else.
Method
Our method, CLOB-Reactor, keeps the learned model and removes validity from what it has to learn. A causal transformer reads a feature vector per message; each new message is sampled as a short chain of decisions, and every decision that refers to the book is a choice among candidates that the book itself supplies.
An exact book, and a feature per message
We maintain an exact order-level book: for every resting order its side, price, remaining size and time of birth, the price-time queue at each level, and a ring of the most recently added order identifiers. After every message we form a 112-dimensional feature vector from the book before and after it and from the message itself. It contains the spread, relative to the day's median spread; the mid price's deviation from three exponential moving averages and from two reference mids; queue imbalances over the best 1, 3, 5 and 10 levels and the change in the best-level one; log depths and gaps over the best five levels; the message's class, side, size, waiting time and its position relative to the touch; for cancels and executions, the age and queue position of the order touched; which best quotes moved; and exponentially decayed accumulators
of four quantities: message counts, signed and square-root-size-weighted visible trades, the same for hidden trades, and order-flow imbalance at the best quotes. The last 23 coordinates are a per-cut context vector from the same day's history and the asset; among them are the median spread, median best and top-ten depth, the median and interquartile range of inter-arrival times, the share of simultaneous messages, the rates at which a delete is followed at the same instant by an add on the same side and an execution by another execution on the same side, the event mix, the price volatility over 100 trades, the time of day and the time to close. Prices are measured in units of the median spread or of that volatility, sizes in lots, waiting times as with the day's median and interquartile range. The model therefore sees the regime and is asked to react to the book in the units of that regime.
The network is a causal transformer: an MLP input projection, eight pre-normalised blocks of width 512 with eight heads, rotary positions, a sliding attention window of 256 messages and SwiGLU feed-forward layers of width 1536. During generation it runs incrementally with a key-value cache.
A message as a chain of decisions
Writing for the transformer state after message , we factorise the next message as
and each later factor reads the earlier choices through additive embeddings: , , and so on.
Waiting time. A message at the same instant as the previous one is a separate event with probability , where is the day's share of zero waiting times. Otherwise the standardised log waiting time is an eight-component Gaussian mixture,
with centres evenly spaced on .
Event class. Nine classes: add, partial cancel, delete and execute on either side, and a hidden execution. Their logits are the network's output plus the log of the event mix measured on the same day, .
Target. A new order's price is one of 34 candidate slots built from the current book: eight inside the spread, the ten occupied levels of its own side, six behind the touch and in the gaps between the first levels, two one tick either side of the price of an immediately preceding cancel on the same side, and eight geometrically spaced bands beyond the tenth occupied level (or the deepest one), inside which the exact distance is drawn from the day's empirical pool. A cancel or delete first picks one of 16 zones (the ten best levels and six deeper bands) and then one of up to 16 candidate orders in it; an execution picks one of up to eight orders at the best price, then whether it is filled in full; a hidden execution picks whether it prints at the mid or roughly a quarter of the spread inside either quote. Zones and orders are chosen by pointer attention: with the features of candidate (for an order: age, recency, queue position, whether it is at the head or tail of its queue, remaining size and distance from the touch),
with key width for zones and cancel candidates and for executions; a zone's features also carry a one-hot code of the zone.
def score_ca_zones(self, h2, z_feats, z_valid, bca_prior=None):
N = h2.shape[0]
eye16 = torch.eye(16, device=h2.device, dtype=h2.dtype)[None, :, :].expand(N, -1, -1)
zf_in = torch.cat([z_feats.to(h2.dtype), eye16], dim=-1)
q = self.ca_z_q(h2)[:, None, :]
k = self.ca_z_k(zf_in)
logits = ((q * k).sum(-1) * (1.0 / 8.0) + self.ca_z_v(zf_in).squeeze(-1)).float()
if bca_prior is not None:
logits = logits + bca_prior.float()
return logits.masked_fill(~z_valid, -1e9)
def score_ca_orders(self, h3, o_feats, o_valid):
of_in = o_feats.to(h3.dtype)
q = self.ca_o_q(h3)[:, None, :]
k = self.ca_o_k(of_in)
logits = (q * k).sum(-1) * (1.0 / 8.0) + self.ca_o_v(of_in).squeeze(-1)
return logits.float().masked_fill(~o_valid, -1e9)
def score_ex_orders(self, h2, e_feats, e_valid):
ef_in = e_feats.to(h2.dtype)
q = self.ex_o_q(h2)[:, None, :]
k = self.ex_o_k(ef_in)
logits = (q * k).sum(-1) * (1.0 / math.sqrt(48.0)) + self.ex_o_v(ef_in).squeeze(-1)
return logits.float().masked_fill(~e_valid, -1e9)Size. One of 16 buckets defined in lots: exact sizes of one share, half a lot, one, two, three, five and ten lots and 100 shares, ranges in between and above, and a bucket that copies the size of an immediately preceding cancel or delete on the same side, which is how a replace appears in the message stream. Within a bucket the size is drawn from the day's empirical sizes for that message type when there are any. A partial cancel or partial execution is restricted to buckets below the order's remaining size.
The training loss is a weighted sum of the negative log-likelihoods of all the factors, with the positions that predict the continuation of each training window weighted 1.4 against 1 for the others. The quoted passage shows how the chain is built.
ldt0_prior = b["ldt0"][:, None].expand(B, T).reshape(N)
logit_dt0 = raw_net.head_dt0(h0).squeeze(-1).float() + ldt0_prior
ydt0 = b["ydt0"].reshape(N)
mdt0 = b["mdt0"].reshape(N)
bce_dt0 = F.binary_cross_entropy_with_logits(logit_dt0, ydt0, reduction="none") * mdt0
loss_dt0 = (bce_dt0 * w_flat).sum() / (w_flat * mdt0).sum().clamp_min(1.0)
gmm_raw = raw_net.head_gmm(h0).float()
pi_log = F.log_softmax(gmm_raw[:, :8], dim=-1)
mu = gmm_raw[:, 8:16] + raw_net.gmm_centers[None, :]
log_sig = torch.clamp(gmm_raw[:, 16:24], -2.5, 1.2)
sig = torch.exp(log_sig)
yzdt = b["yzdt"].reshape(N)
pos_mask = (1.0 - ydt0) * w_flat
z_diff = (yzdt[:, None] - mu) / sig
log_prob_k = pi_log - log_sig - 0.5 * math.log(2.0 * math.pi) - 0.5 * (z_diff ** 2)
nll_gmm = -torch.logsumexp(log_prob_k, dim=-1)
loss_gmm = (nll_gmm * pos_mask).sum() / pos_mask.sum().clamp_min(1.0)
dt_in = torch.stack([ydt0, yzdt * (1.0 - ydt0), 1.0 - ydt0], dim=-1).to(h0.dtype)
h1 = h0 + raw_net.dt_emb(dt_in)
bev = b["bev"][:, None, :].expand(B, T, 9).reshape(N, 9)
logits_ev = raw_net.head_ev(h1).float() + bev
yev = b["yev"].reshape(N)
ce_ev = F.cross_entropy(logits_ev, yev, reduction="none")
loss_ev = (ce_ev * w_flat).sum() / w_flat.sum()
h2 = h1 + raw_net.ev_emb(yev)Same-day priors
The priors do more than set a base rate. For new-order prices we count, over the context, how often an add lands inside the spread, at an occupied level of its own side, in a gap or behind the touch, and beyond the tenth level; the deep share is averaged half and half with the same share measured on the last 30 minutes of history, and the deep mass is spread over the eight bands by the history's own distances. Cancels get the same treatment over their 16 zones. The log priors are centred and added to the network's logits, so the network learns a correction to the day's own behaviour rather than the behaviour itself. This is how we expect it to transfer to days and assets whose mix differs from the training pool.
tot_lo_m = c_ins + c_top10 + c_gap + c_deep
blo_p = np.zeros(34, dtype=np.float64)
blo_p[0:8] = (c_ins / tot_lo_m) / 8.0
blo_p[8:18] = (c_top10 / tot_lo_m) / 10.0
blo_p[18:26] = (c_gap / tot_lo_m) / 8.0
blo_p[26:34] = (c_deep / tot_lo_m) * (lo_deep_cnts / lo_deep_cnts.sum())
blo_logp = np.log(np.maximum(blo_p, 1e-6)).astype(np.float32)
blo_logp -= float(np.mean(blo_logp))
tot_ca_m = ca_top10_c + ca_deep_c
bca_p = np.zeros(16, dtype=np.float64)
bca_p[0:10] = (ca_top10_c / tot_ca_m) / 10.0
bca_p[10:16] = (ca_deep_c / tot_ca_m) * (ca_deep_cnts / ca_deep_cnts.sum())
bca_logp = np.log(np.maximum(bca_p, 1e-6)).astype(np.float32)
bca_logp -= float(np.mean(bca_logp))Bid-ask reflection
The book is symmetric under exchanging bids and asks and reversing the direction of price. We make this exact in feature space: a permutation that swaps every bid feature with its ask counterpart and a sign vector that flips every signed quantity (mid deviations, imbalances, signed trade accumulators, signed price moves), together with the swap of the two sides of each event class and of the two off-mid hidden-print positions. Half of every training batch is reflected, .
def make_reflect_tables():
"""Return (perm[112], sign[112]) for exact Bid-Ask reflection symmetry on GPU."""
perm = list(range(FEAT_DIM))
sign = [1.0] * FEAT_DIM
for i in range(5, 15):
sign[i] = -1.0
perm[15], perm[16] = 16, 15
for l in range(5):
perm[18 + l], perm[23 + l] = 23 + l, 18 + l
for l in range(4):
perm[28 + l], perm[32 + l] = 32 + l, 28 + l
for k in range(5):
perm[37 + 2 * k], perm[38 + 2 * k] = 38 + 2 * k, 37 + 2 * k
perm[60], perm[61] = 61, 60
perm[62], perm[63] = 63, 62
sign[64] = -1.0
for i in range(71, 89):
sign[i] = -1.0
return perm, signPredicting the book ahead
The title of our method refers to a multi-horizon predictive state. A linear head on , used only in training, regresses ten targets with a smooth- loss of width 0.5: the change over the next 16 and 64 messages in the mid's deviation from its reference and in the log spread, the best-level imbalance 16 and 64 messages ahead, the change in mean log best-level depth over the same horizons, and the number and signed balance of trades over the next 64 messages. These are the quantities through which a market reacts, and asking the state to anticipate them is meant to make it carry what the next messages should respond to. The full objective is
Training
Training windows are cut from every training day and asset, 192 messages of context followed by 128 of continuation, each with its own same-day calibration computed causally. Cuts are drawn in part immediately after executions, hidden trades, adds and deletes, so that the model sees the moments a reaction starts, and no cut is taken within ten minutes after a trading halt. We train with AdamW (learning rate , , weight decay on parameters with two or more dimensions), 120 warm-up steps and a cosine decay to 0.06 of the peak, gradient clipping at 1, bfloat16, Gaussian noise of scale 0.025 on the depth and gap features, data parallelism over the available GPUs, and we keep an exponential moving average of the weights, which is what is deployed. The schedule length is set from the measured step time and the time remaining.
Generation that cannot be rejected
At generation time the event class is sampled from the calibrated logits masked by what the book allows: a partial cancel only on a side with an order of at least two shares, a delete only on a side with at least two orders, an execution only if it cannot remove the last share of a side, and a hidden execution only up to a per-call cap. When the book is not two-sided only adds are allowed. A zero waiting time is not allowed for the first message of a continuation or straight after a partial execution.
for bi, si in enumerate(active_ix):
r = runners[si]
bk = r.book
bb, ba = bk.best_bid(), bk.best_ask()
v_ev = np.zeros(9, dtype=bool)
if bb is not None and ba is not None and ba > bb:
v_ev[0] = True
v_ev[1] = True
v_ev[2] = bk.has_partial_cancelable(1)
v_ev[3] = bk.has_partial_cancelable(-1)
v_ev[4] = bk.bn >= 2
v_ev[5] = bk.an >= 2
v_ev[6] = bk.can_execute_side(1)
v_ev[7] = bk.can_execute_side(-1)
v_ev[8] = (hid_counts[si] < max(2, max_rows // 3)) and (len(out_acts[si]) < 3 * max_rows)
else:
v_ev[0] = True
v_ev[1] = True
lg_ev = np.where(v_ev, ev_logits_np[bi], -1e9)
ev_chosen[bi] = _sample_categorical_np(lg_ev, rng)
ev_t = torch.as_tensor(ev_chosen, dtype=torch.long, device=device)
h2 = h1 + net.ev_emb(ev_t)New prices are snapped to the price grid and to the allowed range, and a new order's identifier is predicted as the next one the engine will assign; if that is not yet known, the call stops after the first add so the identifier can be read back. Before each call we save the stream's state, and if the engine accepted fewer messages than we proposed or rejected one, we restore the saved state, replay the accepted messages through the network and rebuild our book from the engine's.
need_rebuild = (n_acc != self.expected_len) or bool(st.rejects) or (self.verified_next_id is not None and not rebound_first and -1 in self.book.orders)
if (n_acc < self.expected_len or bool(st.rejects)) and self.ckpt is not None:
(self.ema, self.h_state, self.prev_bk, self.prev_row, self.was_ff,
self.last_trade_px, self.last_p_sign,
self.h_cur, self.k_list, self.v_list, self.pos, self.vlen, self.verified_next_id) = self.ckpt
dt_dtype = self.h_cur.dtype
for idx in range(self.synced_len, n_acc):
rk = tuple(int(v) for v in st.rows[idx])
cur_bk = st.books[idx]
dt_k = max(0, rk[0] - max(0, self.prev_row[0]))
ff_k = (rk[1] == 4) and (st.book.order(rk[2]) is None)
mod_age = None
mod_qf = 0.0
if rk[1] in (2, 3, 4):
tb_r = self.birth_map.get(rk[2])
if tb_r is not None:
mod_age = max(1, rk[0] - tb_r)
mod_qf = 0.0 if rk[1] == 4 else min(1.0, max(0.0, 1.0 - mod_age / 2e9))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 ↓ | |
| Gemini 4 Carbon | 1.702 | 0 | 0.082 | 2.083 | 2.205 | 0 | 0.098 | 2.484 | 2.015 | 0 | 0.109 | 2.674 |
| 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
On every setting CLOB-Reactor is ahead of every published baseline on the response metric, the L1 score and the energy score, and level with the best on rejected rows. On the response metric it reaches 1.702 on Large-tick, 2.205 on Small-tick and 2.015 on New-ticker, against 1.808, 2.290 and 2.150 for the strongest baseline, which is MarketGPT [6] on all three. The margin is modest, and smallest on Small-tick.
The gains are much larger on the realism metrics. The L1 score on the start of the continuation is 0.082, 0.098 and 0.109, less than half of the strongest baseline's 0.223, 0.261 and 0.236 (MarketGPT [6]). The energy score is 2.083, 2.484 and 2.674, against 2.578, 2.675 and 2.911. The share of rejected and fallback rows is 0.000 on every setting; the only baseline that also has none is the conditional WGAN world agent (0.000), which is the weakest baseline on the response metric. That our generator has no rejections is what the design is for: every reference it emits is to an order in its mirror of the book, and the event mask keeps the book two-sided.
Against the starter, the calibrated Cont-Stoikov-Talreja model, the response metric falls from 3.682 to 1.702 on Large-tick, from 3.149 to 2.205 on Small-tick and from 3.257 to 2.015 on New-ticker.
How we got here
The code records a version: the module calls the method "CLOB-Reactor v2b", the generator class "CLOB-Reactor v2", and the training cache is named for a second version. So the submitted design followed at least one earlier one, but nothing in the file says what changed between them or why.
The starter's model was not discarded. If no trained checkpoint exists, the generator falls back to the calibrated Cont-Stoikov-Talreja stream [1], so a failed training run degrades to the starter rather than to nothing.
Several design choices are explained in the code's own comments and structure rather than in prose. The copy-previous-size bucket is labelled as the replace message of the exchange feed, a delete followed by an add of the same size. The 100-share bucket is labelled as distinct only when the asset's lot is not 100 shares. The hidden-execution branch is described as mirroring the engine's trade-sign rule, which signs a print by its side of the mid, then by the direction from the last trade price, then by the previous sign. And the calibration combines two estimates of the deep share of new orders, from the context and from the last half hour, half and half, rather than choosing one. The code gives no measurement behind any of these choices.
Limitations
- The response gain is modest. On the response metric, the task's measure of performance, we are ahead of MarketGPT [6] by a small margin on every setting and by the least on Small-tick (2.205 against 2.290). Most of our advantage is in start-of-continuation realism and validity, not in how the simulated market reacts.
- There is no ablation. The method combines an exact book mirror, a factorised pointer head, same-day priors, reflection augmentation, an auxiliary predictive loss and a resynchronisation protocol, and the run left no measurement of what each contributes. Which of them produces the gain cannot be read from the results.
- Training and generation do not compute every feature the same way. In training the queue position of a cancelled or executed order is exact. When the context is encoded at a cut, and when accepted messages are replayed, it is replaced by a proxy computed from the order's age (by zero for an execution), and whether an execution was a full fill is inferred from the book after the cut. The tick size of a training window is also inferred from the price level, whereas generation uses the tick the task supplies. At generation time the model therefore sees inputs whose statistics differ from training on these coordinates.
- Memory is short. Attention sees the last 256 messages; anything older reaches the model only through the decayed accumulators and the per-cut context vector.
- Hand-set structure. The 34 price slots, the 16 zones, the 16 size buckets, the three hidden print positions, the per-call caps and the loss weights are set by hand, and a hidden execution can only print at three positions in the spread.
- It is a system, not a component. The method replaces the whole generator file and is built to train and to sample on GPUs. It is not a single modular change that could be carried into another generator unchanged.
References
- Rama Cont, Sasha Stoikov, Rishi Talreja (2010). A Stochastic Model for Order Book Dynamics. Operations Research.
- Peer Nagy, Sascha Frey, Kang Li et al. (2025). LOB-Bench: Benchmarking Generative AI for Finance -- an Application to Limit Order Book Data. ICML.
- Konark Jain, Nick Firoozye, Jonathan Kochems et al. (2023). Limit Order Book Dynamics and Order Size Modelling Using Compound Hawkes Process.
- Patrick Noble, Mathieu Rosenbaum, Saad Souilmi (2026). Bridging the Reality Gap in Limit Order Book Simulation.
- 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.