Skip to content

Market and agents

The closed-loop market: its configuration, the background agents and the open-loop order flow. Importable from microbook.sim.

MarketConfig dataclass

MarketConfig(seed: int = 0, tick_size: float = 0.01, start_price: float = 100.0, fundamental_vol: float = 0.005, jump_rate: float = 0.0, jump_size: float = 0.0, vol_of_vol: float = 0.0, vol_persistence: float = 0.999, noise: NoiseConfig = NoiseConfig(), informed: InformedConfig | None = InformedConfig(), metaorders: MetaorderConfig | None = None, snapshot_every: int = 10, record_snapshots: bool = False)

A noise + informed-flow market around a latent random-walk fundamental.

The defaults are the simple v0.2 market (Poisson flow, fixed-size informed trades). realistic() returns the calibrated preset that reproduces the stylized facts of real markets (see examples/stylized_facts.py).

seed class-attribute instance-attribute

seed: int = 0

Seed of the fundamental path and of every background agent's random stream.

tick_size class-attribute instance-attribute

tick_size: float = 0.01

Tick size of the book.

start_price class-attribute instance-attribute

start_price: float = 100.0

Initial fundamental value.

fundamental_vol class-attribute instance-attribute

fundamental_vol: float = 0.005

Standard deviation of the fundamental's change per step, in price units (on average, with stochastic volatility).

jump_rate class-attribute instance-attribute

jump_rate: float = 0.0

Probability of a fundamental jump per step.

jump_size class-attribute instance-attribute

jump_size: float = 0.0

Size of each jump, up or down with equal probability, in price units.

vol_of_vol class-attribute instance-attribute

vol_of_vol: float = 0.0

Volatility of log-volatility. Above 0, the fundamental's volatility is stochastic.

vol_persistence class-attribute instance-attribute

vol_persistence: float = 0.999

Per-step persistence of log-volatility (its AR(1) coefficient).

noise class-attribute instance-attribute

noise: NoiseConfig = field(default_factory=NoiseConfig)

The noise-trader population.

informed class-attribute instance-attribute

informed: InformedConfig | None = field(default_factory=InformedConfig)

The informed trader; None for none.

metaorders class-attribute instance-attribute

metaorders: MetaorderConfig | None = None

Institutional metaorder flow; None for none.

snapshot_every class-attribute instance-attribute

snapshot_every: int = 10

Time between SNAPSHOT events, which sample the book and PnL and call every strategy's on_tick.

record_snapshots class-attribute instance-attribute

record_snapshots: bool = False

Keep an L2 snapshot for every SNAPSHOT (memory-heavy on long runs).

realistic classmethod

realistic(seed: int = 0, **overrides: Any) -> MarketConfig

Calibrated market with the stylized facts of real markets.

Compared with the defaults it adds stochastic volatility in the fundamental, self-exciting (Hawkes) noise market orders, metaorder splitting, and arbitrage capital that scales with the mispricing. That last change removes the strong short-horizon momentum of the simple market (lag-1 autocorrelation of 100-step returns ~0.5 -> ~0).

Metaorders are split into many small children (2 shares, one per step), so one metaorder spans many trades: that is what gives order signs their long memory and lets a metaorder move the price faster than arbitrage pulls it back.

Calibration on seeds 1-8, 200k steps each (examples/stylized_facts.py): Hill tail index ~2.7, excess kurtosis ~40 / 4 / 1.6 at 10 / 100 / 1000-step horizons, |return| autocorrelation decaying over ~1000 steps, order-sign autocorrelation ~ lag^-0.5, and metaorder impact ~ 0.5 sigma sqrt(Q/V). Checked on held-out seeds 11-18.

Market dataclass

Market(sim: MarketSimulator, fundamental: FundamentalValue, background: list[str])

A built market: the simulator, the fundamental value and the background agents' names.

sim instance-attribute

The simulator, holding the background agents and your strategies.

fundamental instance-attribute

fundamental: FundamentalValue

The latent value the agents trade around.

background instance-attribute

background: list[str]

Names of the background agents.

metaorders property

metaorders: list[MetaorderRecord]

Completed background metaorders (empty unless MarketConfig.metaorders is set).

run

run(until: int) -> MarketSimulator

Run the simulation up to time until and return the simulator.

build_market

build_market(cfg: MarketConfig, strategies: Sequence[Strategy] = (), *, horizon: int) -> Market

Assemble a simulator with background agents plus strategies.

The fundamental path and the agents' arrival streams depend only on cfg.seed, so runs with different strategies see the same exogenous flow (common random numbers) and can be compared fairly.

FundamentalValue

FundamentalValue(start: float, vol_per_step: float, *, jump_rate: float = 0.0, jump_size: float = 0.0, vol_of_vol: float = 0.0, vol_persistence: float = 0.999, seed: int = 0)

Latent value process on the integer clock.

V[t] = V[t-1] + sigma[t] * Z + J, where Z ~ N(0, 1) and J = +/-jump_size with probability jump_rate per step.

With vol_of_vol > 0 the volatility is stochastic: log sigma follows a mean-reverting AR(1) around log vol_per_step with per-step persistence vol_persistence, normalized so the average variance stays vol_per_step ** 2. This produces volatility clustering and fat tails at every horizon, as news arrival does in real markets.

The path is generated lazily but deterministically: the value at t does not depend on query order.

at

at(t: int) -> float

Fundamental value at time t, generated on first request and then fixed.

NoiseTrader

NoiseTrader(cfg: NoiseConfig, fundamental: FundamentalValue, *, name: str = 'noise', seed: int = 0)

Bases: Strategy

Zero-intelligence liquidity population (see module docstring).

Its orders represent many anonymous traders, so each carries a unique owner and the population never triggers self-trade prevention against itself. portfolio holds the aggregate position of the population.

on_start

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

Build the initial book: initial_levels levels per side around the fundamental.

on_timer

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

One step of noise flow: new limit orders, market orders and random cancellations.

on_fill

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

Stop tracking resting orders that have been filled completely.

NoiseConfig dataclass

NoiseConfig(limit_rate: float = 2.0, market_rate: float = 0.15, cancel_prob: float = 0.02, min_qty: int = 1, max_qty: int = 10, mean_offset_ticks: float = 4.0, initial_levels: int = 10, initial_qty: int = 15, market_hawkes: HawkesConfig | None = None)

Parameters of the NoiseTrader population.

limit_rate class-attribute instance-attribute

limit_rate: float = 2.0

Expected limit orders per time step.

market_rate class-attribute instance-attribute

market_rate: float = 0.15

Expected market orders per time step (the mean rate when market_hawkes is set).

cancel_prob class-attribute instance-attribute

cancel_prob: float = 0.02

Per-step probability that each resting noise order is cancelled.

min_qty class-attribute instance-attribute

min_qty: int = 1

Smallest order size.

max_qty class-attribute instance-attribute

max_qty: int = 10

Largest order size.

mean_offset_ticks class-attribute instance-attribute

mean_offset_ticks: float = 4.0

Mean distance of a limit price from the opposite touch, in ticks (1 + a geometric draw).

initial_levels class-attribute instance-attribute

initial_levels: int = 10

Price levels per side in the initial book, around the fundamental.

initial_qty class-attribute instance-attribute

initial_qty: int = 15

Size of each initial order.

market_hawkes class-attribute instance-attribute

market_hawkes: HawkesConfig | None = None

Self-exciting market orders; None gives Poisson arrivals at market_rate.

InformedTrader

InformedTrader(cfg: InformedConfig, fundamental: FundamentalValue, *, name: str = 'informed', seed: int = 0)

Bases: Strategy

Trades on the gap between the book and the fundamental value.

On each arrival it buys with an IOC limit at V - threshold if the best ask is below that, or sells at V + threshold if the best bid is above it. It never pays more than the fundamental minus its required edge. The size is qty plus qty_per_tick per tick of mispricing beyond the threshold (capped at max_qty).

on_start

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

Start the arrival clock (one wake-up per step).

on_timer

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

On an arrival, trade if the book is mispriced by more than the threshold.

InformedConfig dataclass

InformedConfig(rate: float = 0.4, qty: int = 5, threshold_ticks: float = 1.0, qty_per_tick: float = 0.0, max_qty: int = 1000)

Parameters of InformedTrader.

rate class-attribute instance-attribute

rate: float = 0.4

Expected arrivals per time step.

qty class-attribute instance-attribute

qty: int = 5

Base order size.

threshold_ticks class-attribute instance-attribute

threshold_ticks: float = 1.0

Minimum mispricing against the fundamental before trading, in ticks. The trader also keeps this edge on its limit price.

qty_per_tick class-attribute instance-attribute

qty_per_tick: float = 0.0

Extra shares per tick of mispricing beyond the threshold (0 = fixed size). Arbitrage capital that scales with the opportunity closes large gaps fast.

max_qty class-attribute instance-attribute

max_qty: int = 1000

Cap on the order size.

MetaorderTrader

MetaorderTrader(cfg: MetaorderConfig, *, name: str = 'meta', seed: int = 0)

Bases: Strategy

Background population executing metaorders (see MetaorderConfig).

Completed metaorders are logged in completed as MetaorderRecord (side, size, start, end), the data needed to measure price impact. All draws are state-independent, so the flow is identical across strategy variants (common random numbers).

draw_size

draw_size() -> int

Inverse-CDF sample of the truncated Pareto size distribution.

on_start

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

Start the arrival clock (one wake-up per step).

on_timer

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

Start new metaorders, then send one child order for each active metaorder with probability child_rate.

MetaorderConfig dataclass

MetaorderConfig(rate: float = 0.01, size_alpha: float = 1.5, min_size: int = 10, max_size: int = 10000, child_qty: int = 5, child_rate: float = 0.1)

Uninformed institutions splitting large orders into child market orders.

Metaorders arrive as a Poisson process. Total sizes follow a Pareto law P(Q > q) ~ q^-size_alpha truncated to [min_size, max_size]; with 1 < size_alpha < 2 the trade-sign autocorrelation decays as lag^-(size_alpha - 1) (Lillo, Mike & Farmer 2005). Each active metaorder sends a child market order of child_qty shares with probability child_rate per step until it is done.

rate class-attribute instance-attribute

rate: float = 0.01

Expected new metaorders per step.

size_alpha class-attribute instance-attribute

size_alpha: float = 1.5

Pareto tail exponent of metaorder sizes. Values in (1, 2) give long memory in order signs.

min_size class-attribute instance-attribute

min_size: int = 10

Smallest metaorder, in shares.

max_size class-attribute instance-attribute

max_size: int = 10000

Largest metaorder, in shares.

child_qty class-attribute instance-attribute

child_qty: int = 5

Shares per child market order.

child_rate class-attribute instance-attribute

child_rate: float = 0.1

Probability per step that an active metaorder sends a child order, in (0, 1].

HawkesProcess

HawkesProcess(mean_rate: float, cfg: HawkesConfig, rng: Random)

Discrete-time Hawkes process: counts per step N_t ~ Poisson(lambda_t) with lambda_t = mu + sum_k sum_{s<t} a_k * d_k^(t-s) * N_s.

Each kernel component k has decay d_k = exp(-1/tau_k) and weight a_k = (branching / K) * (1 - d_k) / d_k so that the total expected offspring per event equals branching.

intensity property

intensity: float

Expected number of arrivals in the next step.

step

step() -> int

Draw this step's number of arrivals and update the self-excitation.

HawkesConfig dataclass

HawkesConfig(branching: float = 0.8, timescales: tuple[float, ...] = (10.0, 100.0, 1000.0))

Self-excitation of noise market orders.

branching is the expected number of extra orders each order triggers (must be < 1). The kernel is an equal-weight mixture of exponentials with the given timescales (in steps), a standard approximation of the slowly decaying kernels estimated on real data. The mean arrival rate is kept equal to NoiseConfig.market_rate, so turning excitation on changes how activity clusters, not how much there is.

branching class-attribute instance-attribute

branching: float = 0.8

Expected number of extra orders each order triggers; must be in [0, 1).

timescales class-attribute instance-attribute

timescales: tuple[float, ...] = (10.0, 100.0, 1000.0)

Decay times of the kernel's exponential components, in steps.

PoissonOrderFlow

PoissonOrderFlow(cfg: FlowConfig)

Bernoulli-thinned arrivals on the integer clock (a discrete-time approximation of a Poisson process: each unit holds at most one order).

iter_orders

iter_orders(*, start: int, end: int, ref_mid: float) -> Iterator[tuple[int, Order]]

Yield (time, order) for each arrival in [start, end].

Limit prices are 1 to max_ticks_away ticks from ref_mid.

FlowConfig dataclass

FlowConfig(seed: int = 7, intensity_per_100: float = 20.0, min_qty: int = 1, max_qty: int = 10, tick: float = 1.0, max_ticks_away: int = 5, p_market: float = 0.05)

Parameters of PoissonOrderFlow.

seed class-attribute instance-attribute

seed: int = 7

Seed of the order stream.

intensity_per_100 class-attribute instance-attribute

intensity_per_100: float = 20.0

Average orders per 100 time units (at most one order per unit).

min_qty class-attribute instance-attribute

min_qty: int = 1

Smallest order size (sizes are uniform).

max_qty class-attribute instance-attribute

max_qty: int = 10

Largest order size.

tick class-attribute instance-attribute

tick: float = 1.0

Price step between placement levels.

max_ticks_away class-attribute instance-attribute

max_ticks_away: int = 5

Limit prices are 1 to this many ticks from the reference mid.

p_market class-attribute instance-attribute

p_market: float = 0.05

Probability that an order is a market order.