Skip to content

Simulation: time, events and latency

MarketSimulator is a discrete-event simulator built around one LimitOrderBook. Every participant, including the background market, is a Strategy that reads the book and asks for things to happen. The simulator decides when they happen.

flowchart LR
    Q[("event heap<br/>(time, seq)")] -->|SUBMIT / CANCEL / MODIFY| B[LimitOrderBook]
    B -->|ExecutionReport + fills| S[MarketSimulator]
    S -->|portfolio, metrics| P[Portfolio / ExecutionMetrics]
    S -->|on_fill / on_report| ST[Strategies and agents]
    Q -->|SNAPSHOT → on_tick<br/>TIMER → on_timer| ST
    ST -->|Actions, delayed by latency| Q

The clock

Time is an integer. It has no unit of its own: the background market moves once per step, so in a build_market() run a step reads naturally as "one second" or "one event slot", and in a historical replay you choose the unit (for example 1 ms). Nothing happens between steps.

Events

Everything that happens is an Event on a min-heap:

Event What it does
SUBMIT sends an order to the book
CANCEL cancels a resting order
MODIFY changes or reduces a resting order
TIMER calls one strategy's on_timer
SNAPSHOT samples the book and every strategy's PnL and inventory, then calls every strategy's on_tick

Events are ordered by (time, seq), where seq is a global counter incremented each time anything is scheduled. Events at the same time are therefore processed in the order they were scheduled (first in, first out), and a run is exactly reproducible: the same seed and settings give the same fills, bit for bit, on every supported Python and with or without the compiled engine. Golden digests in tests/test_sim_determinism.py check this in CI.

run(until) processes every event with time <= until and can be called again to continue the same run; results accumulate.

Actions and latency

A strategy never calls the book. Each hook returns a list of Actions, and the simulator turns them into events:

  • An order message (Action.submit, cancel, modify, reduce) decided at time t reaches the book at t + latency, where latency is the strategy's own order-entry delay. Meanwhile the book keeps moving, so a slow strategy acts on stale information.
  • A timer (Action.timer(t)) fires exactly at t, with no latency. It must be in the future, unless the strategy sets same_time_timers.

Here one strategy rests an offer, and another decides at t = 5 to buy, with a latency of 3 steps:

from microbook import Order, Side
from microbook.sim import Action, MarketSimulator, Strategy


class Liquidity(Strategy):
    def on_start(self, now, lob):
        return [Action.submit(Order.limit(self.next_order_id(), Side.SELL, 100.01, 10), now)]


class Taker(Strategy):
    def on_start(self, now, lob):
        return [Action.timer(5)]

    def on_timer(self, now, lob):
        print(f"t={now}: decide to buy")
        return [Action.submit(Order.market(self.next_order_id(), Side.BUY, 3), now)]

    def on_fill(self, now, fill, side, is_maker, lob):
        print(f"t={now}: filled {fill.qty} @ {fill.price}")
        return []


sim = MarketSimulator(strategies=[Liquidity("lp"), Taker("taker", latency=3)])
sim.run(100)
# t=5: decide to buy
# t=8: filled 3 @ 100.01
print(sim.strategy("taker").portfolio.position, sim.strategy("lp").portfolio.position)
# 3 -3

What a strategy sees, and when

  • The hooks receive the live book. Reading it is free and instantaneous; only order messages pay latency. Treat it as read-only: calling submit or cancel on it directly bypasses latency, fill attribution and the metrics.
  • on_fill and on_report are called when the message is processed at the book, that is, after the latency. A strategy learns about its own fills with no extra delay.
  • For each message, every on_fill runs before the on_report of the strategy that sent it.
  • build_market() schedules all its SNAPSHOT events before the run starts, so at any time t the snapshot comes first: its on_tick sees the book as it was at the end of t - 1.

Arrival price includes latency

When a strategy submits an order, the simulator records the midprice at the decision time as the order's arrival price. Slippage against arrival (Metrics) therefore includes what the market did during the latency, as implementation shortfall does in practice.

Who owns an order

The simulator fills in each order's owner with the name of the strategy that sent it, and its default book uses STPMode.CANCEL_RESTING, so no strategy can trade with itself. Every fill is attributed to both sides: the strategy that owned the resting order (the maker) and the one that sent the incoming order (the taker). Each side's Portfolio and ExecutionMetrics are updated before its on_fill is called.

Because every participant is a strategy, money is conserved: the total PnL of all participants is exactly zero, and the test suite checks it.

What a run records

SimResult, returned by run and kept in sim.result, holds:

Field Contents
fills every fill in the market, in execution order
mid_path (time, mid) each time the midprice changes; NaN while the book is one-sided
pnl_t, pnl_series, inventory_series each strategy's PnL (marked to mid) and position at every SNAPSHOT
snapshots an L2 snapshot per SNAPSHOT, when record_snapshots is on

sim.ts (TimeSeries) holds the mid, spread and top-of-book imbalance at every snapshot, and sim.exec_metrics[name] each strategy's execution metrics. strategy_report() combines all of these into one row per strategy.

Comparing strategies fairly

build_market() seeds every background agent from MarketConfig.seed, with separate random streams for arrivals (when orders come and how big they are) and for state-dependent choices. The fundamental path and the exogenous order arrivals therefore do not depend on which strategies you add. Running two strategies with the same seed compares them on the same "day", which removes most of the noise from the comparison (common random numbers). Their own trading still changes the book, so the background agents' reactions differ: that is the effect being measured.

Comparing strategies shows the method in full.