Skip to content

Simulator

The event loop, the strategy interface and the actions strategies return. Importable from microbook.sim.

MarketSimulator

MarketSimulator(lob: LimitOrderBook | None = None, strategies: list[Strategy] | None = None, *, record_snapshots: bool = True)

Discrete-event simulator hosting a book and any number of strategies.

Parameters:

  • lob (LimitOrderBook | None, default: None ) –

    The order book. Defaults to a 0.01-tick book with self-trade prevention (CANCEL_RESTING) so no participant can wash-trade.

  • strategies (list[Strategy] | None, default: None ) –

    Participants. Names must be unique (they key metrics and series).

  • record_snapshots (bool, default: True ) –

    Keep an L2 snapshot dict for every SNAPSHOT event (disable for long runs).

schedule

schedule(time: int, etype: EventType, **kwargs: Any) -> None

Schedule an event. kwargs are Event fields (order, order_id, modify).

schedule_snapshots

schedule_snapshots(start: int, end: int, every: int = 1) -> None

SNAPSHOT events at start, start+every, ..., <= end (these drive on_tick).

strategy

strategy(name: str) -> Strategy

The strategy called name; raises KeyError if there is none.

run

run(until: int) -> SimResult

Process every event with time <= until; returns the (cumulative) result.

SimResult dataclass

SimResult(fills: list[Fill] = list(), snapshots: list[dict[str, Any]] = list(), pnl_t: list[int] = list(), pnl_series: dict[str, list[float]] = dict(), inventory_series: dict[str, list[int]] = dict(), mid_path: list[tuple[int, float]] = list())

Everything recorded during a run. Accumulates across successive run calls.

fills class-attribute instance-attribute

fills: list[Fill] = field(default_factory=list)

Every fill in the market, in execution order.

snapshots class-attribute instance-attribute

snapshots: list[dict[str, Any]] = field(default_factory=list)

L2 snapshots, one per SNAPSHOT event, when record_snapshots is on.

pnl_t class-attribute instance-attribute

pnl_t: list[int] = field(default_factory=list)

Times of the PnL and inventory samples (one per SNAPSHOT).

pnl_series class-attribute instance-attribute

pnl_series: dict[str, list[float]] = field(default_factory=dict)

Total PnL of each strategy, by name, marked to mid at pnl_t; NaN while the book is one-sided.

inventory_series class-attribute instance-attribute

inventory_series: dict[str, list[int]] = field(default_factory=dict)

Position of each strategy, by name, at pnl_t.

mid_path class-attribute instance-attribute

mid_path: list[tuple[int, float]] = field(default_factory=list)

(time, mid), appended whenever the midprice changes; the mid is NaN while the book is one-sided.

mid_at

mid_at(t: int) -> float | None

Midprice in force at the end of time t (None if undefined).

Strategy

Strategy(name: str, portfolio: Portfolio | None = None, *, latency: int = 0)

Base strategy. Override any of the hooks; each returns a list of actions.

=================== ========================================================== on_start once, when the simulation starts on_tick on every SNAPSHOT event on_timer on a TIMER this strategy scheduled (Action.timer) on_fill for each fill of one of this strategy's orders on_report for each execution report of a message this strategy sent =================== ==========================================================

latency delays every order message (submit/cancel/modify) by that many time units between the decision and its arrival at the book.

Timers must be in the future unless a subclass sets same_time_timers: then a timer at the current time is allowed and fires after everything already queued for that time (the strategy must make progress each time, or the run never ends).

same_time_timers class-attribute instance-attribute

same_time_timers: bool = False

Allow timers at the current time; they fire after everything already queued for that time.

next_order_id

next_order_id(tag: str = 'o') -> str

A fresh order id, unique within this strategy.

on_start

on_start(now: int, lob: LimitOrderBook) -> list[Action]

Called once when the simulation starts.

on_tick

on_tick(now: int, lob: LimitOrderBook) -> list[Action]

Called on every SNAPSHOT event.

on_timer

on_timer(now: int, lob: LimitOrderBook) -> list[Action]

Called on a timer this strategy scheduled with Action.timer().

on_fill

on_fill(now: int, fill: Fill, side: Side, is_maker: bool, lob: LimitOrderBook) -> list[Action]

Called for each fill of one of this strategy's orders.

Runs before on_report() for the same message.

side is this strategy's side of the trade and is_maker whether its order was resting.

on_report

on_report(now: int, report: ExecutionReport) -> list[Action]

Called with the execution report of each message this strategy sent.

Action dataclass

Action(time: int, etype: EventType, kwargs: dict[str, Any] = dict())

A request from a strategy: an order message or a timer.

time instance-attribute

time: int

Decision time. An order message reaches the book latency later; a timer fires at this time.

etype instance-attribute

etype: EventType

SUBMIT, CANCEL, MODIFY or TIMER.

kwargs class-attribute instance-attribute

kwargs: dict[str, Any] = field(default_factory=dict)

Event fields of the message (order, order_id or modify), filled in by the constructors.

submit classmethod

submit(order: Order, time: int) -> Action

Send order to the book at time (plus the strategy's latency).

cancel classmethod

cancel(order_id: str, time: int) -> Action

Cancel the resting order order_id.

modify classmethod

modify(order_id: str, time: int, *, new_price: float | None = None, new_qty: int | None = None) -> Action

Change a resting order's price and/or quantity.

See LimitOrderBook.modify().

reduce classmethod

reduce(order_id: str, time: int, qty: int) -> Action

Partial cancel of qty shares, resolved when the message reaches the book (see LimitOrderBook.reduce()); keeps queue priority.

timer classmethod

timer(time: int) -> Action

Wake this strategy's Strategy.on_timer() at time.

Event dataclass

Event(time: int, seq: int, etype: EventType, order: Order | None = None, order_id: str | None = None, modify: dict[str, Any] | None = None, owner: int | None = None)

A scheduled simulator event. Ordered by (time, seq); seq is the global scheduling sequence, which makes ties deterministic (FIFO).

time instance-attribute

time: int

When the event fires.

seq instance-attribute

seq: int

Global scheduling sequence number. It breaks ties at equal time in FIFO order.

etype class-attribute instance-attribute

etype: EventType = field(compare=False)

Kind of event.

order class-attribute instance-attribute

order: Order | None = field(default=None, compare=False)

The order, for SUBMIT.

order_id class-attribute instance-attribute

order_id: str | None = field(default=None, compare=False)

Target order id, for CANCEL and MODIFY.

modify class-attribute instance-attribute

modify: dict[str, Any] | None = field(default=None, compare=False)

new_price and/or new_qty, for MODIFY.

owner class-attribute instance-attribute

owner: int | None = field(default=None, compare=False)

Index of the strategy that sent the event; None for events scheduled directly.

EventType

Bases: str, Enum

Kinds of simulator event.