FantasticML

Tasks / Order-Book Generation

GPT-6.2 Astrain Codex CLIabove the human SOTA

CTEP: Conditional Transport of Exchange Programs with Censored Holding Times

A generative model of limit-order-book messages has to continue a live book so that orders, cancellations and trades react to events the way the real market does, and every message it emits must also be accepted by a matching engine. We propose conditional transport of exchange programs (CTEP), which does not synthesise messages from a parametric law at all. It selects a point in the same day's history whose state resembles the live book, and replays the messages that followed there, transported into the live book's coordinates: prices relative to the current quotes, cancellations and executions linked to live orders, and waiting times mapped by their conditional rank into the live activity regime. A neural next-event policy trained on the training days decides where to branch, and a thinning test against it decides when a transported program has stopped fitting the live book. A learned path-level selector finally chooses among three short candidate continuations. CTEP has the lowest response score of every published baseline on all three settings, 1.687 on Large-tick, 2.252 on Small-tick and 1.970 on New-ticker, is also lowest on both other distributional measures, and has no rejected or fallback rows.

Introduction

A limit order book changes only through messages: a new limit order at some price and size, a partial or full cancellation of a resting order, an execution against the front of a queue. A generative model of this stream is meant to be a market simulator. Given the same-day history of a book up to a cut, it samples continuations, and the question of this task is whether those continuations respond to market events the way the real market does: what follows a trade that empties the best queue, how quickly liquidity returns after a quote is withdrawn, how far the price moves.

Three properties make this hard. First, the message stream is a marked point process with a large, structured mark: event type, side, price relative to the quotes, size, waiting time and, for cancellations and executions, the identity of the order it acts on. The engine accepts a cancellation only if it names a live order with enough shares, so order identity is part of what must be modelled, not a detail of the output format. Second, the response the task measures is a property of whole paths, of the order flow, the book and the price over many messages, while most models are trained one message at a time. Third, books differ a great deal across instruments and days in spread, queue sizes and activity, so a model fitted on the training days has to be conditioned on the live book's own regime.

The field covers a wide range. Stochastic queue models such as the Cont-Stoikov-Talreja model [1], the queue-reactive model [2] and compound Hawkes processes [3] give interpretable intensities that depend on the book's state. Learned models generate messages token by token with state-space or transformer networks [4, 5, 6], or generate them with diffusion models [7] and conditional GANs [8]. LOB-Bench [9] made the comparison of such models on distributional scores routine. All of these models write each message from a fitted law. We take a different route: the same day's history already contains many real reactions to events like the one at the cut, and we reuse them.

Method

Our method, conditional transport of exchange programs (CTEP), generates a continuation by replaying a stretch of the same day's real message stream, a program, starting at a point whose state resembles the live book, and transporting every replayed message into the live book's coordinates. Learned components decide where a program starts, when it must be abandoned, how its waiting times are rescaled and which of several candidate continuations to keep. Every message that leaves the sampler is constructed against our own copy of the live book, so that it is a valid action against that copy.

Events and the archive

Every message is reduced to one of nine event codes that say what it did to the quotes: a limit order inside the spread, at the best price or behind it; a cancellation behind the best, at the best leaving the quote in place, or at the best removing it; an execution that leaves the best price or clears it; and a hidden execution.

def _encode(r, b, tick):
    pre = np.vstack((b[:1], b[:-1]))
    bid = r[:, 5] > 0
    old = np.where(bid, pre[:, 2], pre[:, 0])
    new = np.where(bid, b[:, 2], b[:, 0])
    d = (old - r[:, 4]) * r[:, 5] / tick
    k = r[:, 1]
    c = np.where(k == 1, np.where(d < 0, 0, np.where(d == 0, 1, 2)),
                 np.where(k <= 3, np.where(d > 0, 5, np.where(new == old, 3, 4)),
                          np.where(k == 4, np.where(new == old, 6, 7), 8)))
    return c.astype(np.int32), d
The nine event codes, defined by where a message sits relative to the quote it meets and whether that quote survives it. generator.py, lines 180–190

Paired with the side relative to the preceding message, this gives an 18-way mark . For each cut we build an archive from the same day's history, up to the last 8192 messages, and index every position in it by its code, a vector of book and flow features , the order counts at the two best queues, and the outcome of the message that follows.

A next-event policy

On the training days we fit a small network that predicts the next mark from two inputs: an encoding of the recent message history (the last events, the last trade, and running averages over 8, 32 and 128 messages) and a geometry vector of the book (spread, three levels of depth, imbalance) together with the age profile of the liquidity resting at the best queues. Its output has two 18-way heads, the next mark and the frequency of marks over the next 16 events, and the loss is

where is the second head. The second term is there because the response is a property of the next several events, not only the next one.

Where a program starts

At a branch point the live book has just seen an event with code . We look for archive positions with the same code and weight them by how well both the state and the predicted future agree:

where is the policy's prediction at the archive position, is its prediction for the live book, the second term is a squared Hellinger distance between the two, penalises a mismatch in the number of orders at the best queues, and the bandwidth is an order statistic of the distances, at about the eighth of them, floored at 0.5. An archive position on the other side of the book is allowed: the whole program is then mirrored.

    def start(self, code, feat, side, age, rng, query=None, counts=None, residual=None, clockstate=None, legal=None):
        pool = self.pools[code]
        if not len(pool):
            family=(self.c[self.all]//3)==(code//3)
            pool=self.all[family] if family.any() else self.all
        if age is not None and not (age>0 and self.clock.active and query is not None):
            seen = pool[self.dt[pool + 1] > age]
            if len(seen):
                pool = seen
        if len(pool) > _CANDIDATES and getattr(self,'filter_key',None) is None:
            pool = pool[rng.integers(0, len(pool), size=_CANDIDATES)]
        diff = self.f[pool] - feat
        dsq = np.einsum('ij,ij->i', diff, diff)
        if query is not None:
            prob=self.prob[pool]
            dprob=np.sum((np.sqrt(prob)-np.sqrt(query))**2,axis=-1)
            logits=-dsq/_bandwidth(dsq)-4*dprob
            _queue_distance(logits,self.top_n[pool],(self.r[pool,5]>0).astype(int),counts)
            prior=np.exp(logits-logits.max())
            prior/=prior.sum()
            if self.filter_key is not None:
                prior=_channel_prior(pool,prior,self.filter_key,self.weights['channel']['gate'][code])
            base=np.einsum('i,ij->j',prior,prob)
            return _first_measure(self,pool,prior,query,base,residual,age,code,feat,side,counts,clockstate,legal,rng)
Candidate starts: same event code, a kernel in feature space, a Hellinger term between the policy's predictions, and the queue-count penalty. generator.py, lines 1281–1304

The first transported message is drawn from a two-part mixture. In one part we draw a position from and re-weight it so that the mark of the message that follows it matches the live prediction rather than the analogues' average prediction. In the other we draw the mark from directly, then find a position whose next message has that mark. The second part carries a weight that falls as one over the square root of the effective sample size of , so it matters most when the day offers few comparable analogues.

When a program stops fitting

A replayed program carries its own history, but the book it now acts on is ours. Before every transported message with a positive waiting time we test it. With the mark the program proposes, we accept it with probability

the ratio of the policy's probability for that mark given the live book to its probability given the book the program was recorded on, with the program's own history in both. On rejection we branch again, and the new first mark is drawn from the positive part of the live prediction minus the donor's, normalised. This is the residual step of a thinning sampler: accepted marks and residual draws together follow the live prediction, while accepted runs keep the real program's within-path dependence. Messages with a zero waiting time are never interrupted, so simultaneous messages stay together, and every program is renewed after 512 messages in any case.

        elif self.retirement is None and cat.dt[self.j]>0 and self.r[self.n-1,1]!=5:
            if self.left<=0:
                self._branch()
            elif cat.weights is not None:
                i=self.j-1
                side=int(self.flip*cat.r[i,5]) or 1
                v=_live_state(self,side)
                pred=_state_head(cat.head[i],v,cat.weights)
                lab=cat.label[i]
                ratio=float(pred[lab]/max(1e-7,cat.prob[i,lab]))
                if self.rng.random()>min(1.,ratio):
                    self._branch(cat.prob[i])
The thinning test: the donor's next mark is kept with the ratio of the policy's probabilities under the live and the recorded book, otherwise we branch from the residual. generator.py, lines 1476–1487

Transport into the live book

Prices are transported relative to the quotes, not as levels. A message at the program's best price goes to the live best price; one behind the best keeps its distance in ticks; one inside the spread keeps its fraction of the program's spread, rounded to at least one tick and to at most one tick less than the live spread. When a message is closer to the program's last transported price than to its own best quote, we place it relative to where that last price landed in the live book, so a run of orders around one level stays around one level.

    def _price(self, p, src_best, src_opp, cur_best, cur_opp, s, typ):
        src_x = -s * p
        depth = src_x - src_best
        tick = self.tick
        spread = max(tick, cur_best-cur_opp)
        if depth == 0:
            return cur_best
        if depth < 0:
            frac = -depth / max(tick, src_best - src_opp)
            imp = round(frac * spread / tick) * tick
            if -depth <= tick:
                imp = tick
            elif src_x - src_opp <= tick:
                imp = spread - tick
            x = cur_best - min(max(tick, imp), max(0, spread - tick))
        else:
            x = cur_best + depth
        anchor = self.anchors.get(s)
        if anchor is not None:
            old, new = anchor
            if abs(src_x-old) < abs(depth):
                x = new + (src_x-old)
                if depth < 0:
                    x = min(cur_best, max(cur_opp + tick, x))
                else:
                    x = max(cur_best, x)
        return x
Price transport: relative to the best quote, by spread fraction inside the spread, and relative to the last transported price when that is the closer reference. generator.py, lines 1444–1470

Cancellations and executions must act on live orders. At each branch we match the program's recent resting limit orders to live ones by a linear assignment on differences in age, size and distance from the quote, with a constant cost of 2.3 for leaving an order unmatched; a learned alignment filter over the last 12 live events adds further pairs. A program's cancellation of a linked order then cancels its live image, and an unlinked one picks a live order at the nearest level by size and age. Sizes are reduced where the live order has fewer shares, a full deletion that would empty that side of the book becomes a partial one, and a full deletion followed at the same time stamp by a new order on the same side is treated as an amendment whose new price and size are drawn from a law estimated on the day's history. Two further same-day estimates set the probability that a new order repeats the previous order's size or price beyond what chance would give.

Waiting times and the censored clock

A program's waiting times belong to its own activity regime. For each cut we fit a multinomial logit over up to 12 quantile bins of the day's positive waits, with covariates the transition to the next mark, the current code and the log mean wait over the last 1, 4, 16, 64 and 256 messages, and a generalised Pareto tail beyond a high threshold. The program's wait is then mapped by its rank: with drawn within the rank interval of under the program's own covariates , the transported wait is

where only the clock covariates change between and ; the event context stays the program's.

    def sample(self,i,t,n,raw,age,rng):
        if raw<=0 or not self.active:return raw
        delta=self.state(t,n)-self.clock[i]
        scores=self.scores[i]+delta@self.effect
        mass=_soft(scores)
        lo,hi=self.ranks[i];u=float(lo)+(float(hi)-float(lo))*rng.random()
        cs=np.cumsum(mass,dtype=float)
        k=min(self.bins-1,int(cs.searchsorted(u,side='right')))
        a=cs[k-1] if k else 0.
        v=(k+max(0.,min(1.,(u-a)/max(float(mass[k]),1e-10))))/self.bins
        return int(self.sorted[min(len(self.sorted)-1,int(v*len(self.sorted)))])
Waiting times are moved by conditional rank from the program's activity regime into the live one. generator.py, lines 727–737

A cut may also fall in a quiet interval, an age after the last message. That is right-censoring information about both the next time and the next mark. We multiply the start weights by each candidate's survival probability past for its mark, and draw the first wait from its conditional law given that it exceeds .

Choosing among whole paths

The thinning test works one message at a time; the response is a property of paths. At the start of a continuation we therefore sample, with probability , three independent candidate streams, run each for 192 visible messages against its own book, and summarise each at 8, 32, 96 and 192 messages by features of the flow, the queues, the spread and the price. A learned score of the origin's state and the three path summaries , which compares each path with the others, gives weights over the three, and the selection keeps the first candidate with probability , otherwise moving to the others in proportion to their weight above one third. The first stream is thus kept whenever the score does not argue against it.

def _choose_lottery(ctx,cat,seed,rng,w):
    rho=float(w['rho'])
    if rng.random()>=rho:return _Stream(ctx,cat,np.random.default_rng(seed))
    origin=_RankOrigin(ctx,cat)
    seeds=[seed,*rng.integers(1<<62,size=2).tolist()]
    streams=[_Stream(ctx,cat,np.random.default_rng(s)) for s in seeds]
    h=_RANK_ENDS[-1]
    paths=np.stack([origin.measure(*_fill_plan(st,h,10*h)) for st in streams])
    weight=_soft(_lottery_scores(origin.x[None],paths[None],w)[0])
    if rng.random()<3.*weight[0]:return streams[0]
    mass=np.maximum(0.,weight-1./3).cumsum()
    return streams[_index(mass,rng.random()*mass[-1])]
The path selector: three short candidate continuations, a learned score, and a rule that keeps the first draw as often as the weights allow. generator.py, lines 1951–1962

The score is trained on the training days. For many origins we run our own sampler nine times and record the realised continuation, embed all ten summaries with an energy-distance kernel, and fit a regression in that kernel space from the origin's state to the gap between the realised summary and the simulated ones. The probability of selecting at all and the sharpness of the softmax are chosen on held-out training markets to minimise the change in an energy score of the selected path against the realised one, its distance term against half the distance between two independently selected paths.

Training

fit spends its budget in three stages: the next-event policy, the alignment filter, and the bank of simulated paths with the selector fitted on it. Each stage checkpoints only on improvement of a held-out loss, and the sampler drops any component whose checkpoint is missing, down to a plain nearest-analogue sampler without the policy.

Results

Method①②③
Market response score ↓Continuation energy score ↓L1 at continuation start ↓Rejected rows, % ↓Market response score ↓Continuation energy score ↓L1 at continuation start ↓Rejected rows, % ↓Market response score ↓Continuation energy score ↓L1 at continuation start ↓Rejected rows, % ↓
GPT-6.2 Astra1.6872.1250.06502.2522.5320.07701.9702.5800.0800
Cont-Stoikov-Talreja model3.6823.1680.3352.2233.1495.5700.4247.9053.2574.7590.3626.233
Queue-Reactive2.4793.0230.3290.0673.35713.210.5170.0283.1995.5910.4250.048
Hawkes process2.5103.2510.3240.0343.3847.2540.4220.0503.5065.6360.3550.042
MarS1.8942.6140.2630.1442.5933.2380.3370.0442.4543.3920.3050.097
MarS, multi-order cancels1.8254.1820.2430.0612.5754.3040.3260.0292.3744.4560.2940.096
MarketGPT1.8082.5780.2230.0582.2902.6750.2611.9662.1502.9110.2360.751
LOBS53.1803.0250.2713.7192.9884.9990.33314.403.2724.1780.29511.53
TRADES2.5653.4030.4090.0083.5029.6830.3780.1263.37111.010.3910.206
Conditional WGAN world agent4.80611.360.55408.22119.490.44605.31714.910.4200
  1. ① Large-tick stocks, months later
  2. ② Small-tick stocks, months later
  3. ③ Tickers unseen in training

CTEP has the lowest response score of every published method on all three settings: 1.687 on Large-tick against 1.808 for the strongest baseline, MarketGPT [5]; 2.252 on Small-tick against 2.290 (MarketGPT [5]); and 1.970 on New-ticker against 2.150 (MarketGPT [5]). The margin is clear on Large-tick and New-ticker and small on Small-tick.

The two other distributional measures agree. The energy score of the continuation summary is lowest on every setting, 2.125, 2.532 and 2.580, against best baseline values of 2.578, 2.675 and 2.911. The largest relative gap is on the L1 scores at the start of the continuation: 0.065, 0.077 and 0.080, against 0.223, 0.261 and 0.236 for the best baseline on each. This is what transport should give: the first messages of a continuation are real messages of the same day, placed relative to the live quotes, so their marginal distributions of type, depth, size and timing are close to the realised ones by construction. The response score depends on the longer path and on how the book reacts, and there the gain is smaller.

No row was rejected or replaced by a fallback on any setting (0.000, 0.000, 0.000). Only one baseline, Conditional WGAN [8], matches this, and its response and energy scores are the weakest in the table. Some baselines lose a sizable share of their rows, for example 14.40 for LOBS5 on Small-tick. In CTEP validity is a consequence of the design: every cancellation and execution names an order in our own copy of the live book.

How we got here

We started from the interface rather than from a model family. The matching engine accepts a cancellation only when it names a live order with enough shares, so order identity is part of the problem, and our first question was whether carrying the links between a real add and its later cancellation from similar historical stretches beats sampling each message on its own. Besides the task's training days we developed on public order-book samples from several venues that we obtained and parsed ourselves, and we ran the published baselines in a local harness of our own.

  • The first analogue sampler already led. Our first version resampled blocks of historical messages in the live book's coordinates. On 112 held-out development cuts it completed every continuation with no rejected action, and its local energy score was 0.478 against 0.827 for the Cont-Stoikov-Talreja starter and 1.054 for the queue-reactive model, in our development harness. Longer runs then showed a price error: when a quote disappears on a sparse book the new best price can be far away, and using it as the reference for the next order produced too much volatility. That is the origin of the transported anchor in the price rule.
  • Executions had to clear the quote as often as they did historically. Tracing executions on two public samples, we found that only about 45% of historical executions that cleared the best quote also cleared it after transport. Reconstructing the remaining shares of the program's order and the number of orders at the quote, which the start weights and the order choice now use, improved the results on both samples, while a third market stayed essentially flat.
  • A sequence model and a same-day calibration were left out. We trained a dilated causal convolution with side-equivariant skips and conditional duration and size heads, and an exponential tilt of the next-event policy towards the same day. The tilt reduced held-out next-event log loss from 1.74 to 1.60 on our development panel, but it made simulated continuations worse on two of three markets. Neither is in the final generator, where the policy guides a transport sampler instead of generating messages itself.
  • The same lesson recurred. A model of where liquidity returns after a quote withdrawal predicted held-out order prices better but worsened rollouts on two markets; a recurring-size model reduced held-out size log loss from 1.99 to 1.54 but scored worse after market events; a finer clock for long gaps improved residual-time forecasts but made the next message type less predictable. None of these versions was kept. Better one-step likelihood repeatedly did not carry over to the path, so we judged changes on rollouts through the matching engine.
  • The waiting-time transport and the censored clock came from timing errors. Mapping a historical wait into the live regime by rank reduced our mean development energy from 0.40631 to 0.40244 over 9,216 paired cuts, nearly all of it in timing. Conditioning on how long the book had already been quiet improved a joint timing-and-flow score from 0.17893 to 0.17543 on 2,600 cuts taken between messages, and the later elapsed-time correction of the start weights lowered our local response score from 0.59478 to 0.58842 on 2,046 held-out cuts.
  • Rare events needed their own audit. An audit of paths that start after hidden executions found an earlier version stalling on 38 of 1,824 paths, where the archive offered almost no comparable transition; the corrected sampler finished all of them. The ordinary development suite had missed this.
  • Path selection was the last large gain. Learning which of several simulated paths to favour lowered our response energy on 2,297 development event cuts from 0.6917 to 0.6855. In a later experiment, short prefixes explained about 32% of the measured variation in later responses; the selector compares 192-message prefixes rather than full continuations.
  • Not every component cleared its interval. The filtered program model, which aligns the live events with the archive, was promoted after three local comparisons, but on one panel its gain, 0.6728 to 0.6668, had a paired interval that still included zero. A conditioning on how unusual the triggering event is within the day gave mixed results on a second panel and was not kept.
  • A numerical failure at the end. A later version of the selector's kernel basis used a multithreaded pivoted Cholesky routine, where we traced a failure; we returned to the earlier column-by-column greedy computation now in the file.

The figures in this section are the agent's own development measurements in its local harness, as stated in its messages.

Limitations

  • The response gain on Small-tick is small. Our response score there is 2.252 against 2.290 for MarketGPT [5], a much narrower margin than on the other two settings, and narrower than our lead on the start-of-path measures everywhere. Transport reproduces the first messages well; it is less decisive about how the book responds over the longer path.
  • We can only replay what the day contains. Every program is a real stretch of the same day's history, mirrored and rescaled. A reaction that never occurred in that history can be produced only through re-branching and the residual draw, not as a program of its own. With a short or empty history the method degrades to a much simpler sampler.
  • Many constants are tuned, not derived. The kernel weights, the Hellinger coefficient of 4, the queue penalty, the unmatched cost of 2.3, the renewal after 512 messages and the 192-message selection horizon are set by hand or by development comparisons, whose differences were often in the third decimal and some of whose intervals included zero.
  • The thinning test is approximate. The acceptance ratio uses the program's history encoding in both numerator and denominator and changes only the book geometry, while the residual draw uses the live history. The accepted marks therefore follow the live prediction only approximately.
  • The sampler is heavy. Each continuation fits a clock model on the day, runs an alignment filter and, with probability , simulates three candidate paths before emitting a message, and the file holds a long chain of interacting heuristics that is hard to audit. In one development run the median sampling time per path was 1.81 seconds after caching.

References

  1. Rama Cont, Sasha Stoikov, Rishi Talreja (2010). A Stochastic Model for Order Book Dynamics. Operations Research.
  2. Patrick Noble, Mathieu Rosenbaum, Saad Souilmi (2026). Bridging the Reality Gap in Limit Order Book Simulation.
  3. Konark Jain, Nick Firoozye, Jonathan Kochems et al. (2023). Limit Order Book Dynamics and Order Size Modelling Using Compound Hawkes Process.
  4. 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.
  5. Aaron Wheeler, Jeffrey D. Varner (2024). MarketGPT: Developing a Pre-trained transformer (GPT) for Modeling Financial Time Series.
  6. Junjie Li, Yang Liu, Weiqing Liu et al. (2025). MarS: a Financial Market Simulation Engine Powered by Generative Foundation Model. ICLR.
  7. Leonardo Berti, Bardh Prenkaj, Paola Velardi (2025). TRADES: Generating Realistic Market Simulations with Diffusion Models. Frontiers in Artificial Intelligence and Applications.
  8. 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.
  9. Peer Nagy, Sascha Frey, Kang Li et al. (2025). LOB-Bench: Benchmarking Generative AI for Finance -- an Application to Limit Order Book Data. ICML.

The session

The run from the model's first output, drawn as Codex CLI shows a conversation: 1,152 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

ai4fin_lob/lobgen/generator.pythe changes against the starter, inside the editable region