The market model¶
build_market() puts your strategies into a
closed-loop market: the background participants react to the book, including
to your orders, and prices are discovered rather than replayed. The market is
built from four parts, all configured by one
MarketConfig.
The fundamental value¶
FundamentalValue is a hidden "true" price. It
follows a Gaussian random walk, with optional jumps and optional stochastic
volatility:
With vol_of_vol > 0, log σ follows a mean-reverting AR(1) process
(persistence vol_persistence), normalised so the average variance per step
stays fundamental_vol². Calm and busy periods then alternate, as news arrival
makes them alternate in real markets.
Nobody on the book sees V except the informed traders. The book only learns it
through their trading, which is what makes it lag the fundamental.
The background participants¶
| Agent | Role |
|---|---|
NoiseTrader |
supplies most of the liquidity and most of the random trading |
InformedTrader |
pulls the book toward the fundamental; the source of adverse selection |
MetaorderTrader |
institutions splitting large orders; optional, on in the realistic preset |
Noise traders¶
A zero-intelligence population, in the spirit of Smith, Farmer, Gillemot and Krishnamurthy (2003). Each step:
- Limit orders arrive as a Poisson process (
limit_rateper step), on a random side, with a uniform size in[min_qty, max_qty]. Each is placed1 + Geometricticks behind the opposite touch (meanmean_offset_ticks), so some land inside the spread and improve it, and most rest deeper in the book. - Market orders arrive at
market_rateper step, on a random side. They are either Poisson or, withmarket_hawkes, self-exciting: each market order raises the chance of more in the next steps (aHawkesProcesswith a mixture of exponential kernels). The mean rate is the same either way; only the clustering changes. - Cancellations: each resting noise order is cancelled with probability
cancel_probper step.
The run starts with initial_levels levels of initial_qty on each side of the
fundamental, so the book is two-sided from the first step. Each noise order has
its own owner, so the population never trips self-trade prevention against
itself.
On its own this flow random-walks the price with no anchor. The informed traders provide the anchor.
Informed traders¶
On each arrival (rate per step) an informed trader compares the book with the
fundamental. If the best ask is below V − threshold, it buys with an
immediate-or-cancel order limited at V − threshold; if the best bid is above
V + threshold, it sells. It never pays more than the fundamental minus its
edge. The size is qty, plus qty_per_tick per tick of mispricing beyond the
threshold, so large gaps attract more capital and close faster.
For a liquidity provider these are the dangerous counterparties. They trade only when the quote is stale, and afterwards the price moves against the fill. That loss, measured by markouts, is adverse selection.
Metaorder traders¶
Uninformed institutions that need to buy or sell a large quantity and split it
into many small market orders. New metaorders arrive as a Poisson process
(rate); their total sizes follow a Pareto law with tail exponent size_alpha.
Each active metaorder sends a child_qty market order with probability
child_rate per step until it is done.
Splitting is the mechanism behind two stylized facts: one metaorder spans many
trades on the same side, which gives trade signs their long memory (Lillo, Mike
and Farmer 2005), and it pushes the price in one direction long enough for its
impact to be measured. Completed metaorders are listed in
Market.metaorders.
Two presets¶
MarketConfig() is the simple market: Poisson flow, a constant-volatility
fundamental and fixed-size informed trades. It is quick, easy to reason about and
the default for the strategy comparisons.
MarketConfig.realistic() is calibrated
to reproduce the statistical signatures of real markets. Compared with the
defaults it turns on:
| Change | Setting | Effect |
|---|---|---|
| Stochastic volatility | vol_of_vol=0.02 |
volatility clustering, fat tails at every horizon |
| Self-exciting market orders | market_hawkes=HawkesConfig(branching=0.8) |
bursts of activity |
| Metaorder splitting | metaorders=MetaorderConfig(rate=0.03, size_alpha=1.4, child_qty=2, child_rate=1.0) |
long memory in order signs, square-root impact |
| Arbitrage that scales with the gap | informed=InformedConfig(rate=0.3, qty=2, qty_per_tick=20) |
removes the short-horizon momentum of the simple market |
Realism shows what each preset reproduces. Both take keyword
overrides, for example MarketConfig.realistic(seed=3, snapshot_every=1_000).
Running a market¶
With no strategies, build_market() runs the
background market alone. This 20,000-step run takes about a second:
import math
import statistics
from microbook.sim import MarketConfig, build_market
market = build_market(MarketConfig(seed=7), horizon=20_000)
sim = market.run(20_000)
spreads = [s for s in sim.ts.spread if not math.isnan(s)]
gaps = [abs(m - market.fundamental.at(t)) for t, m in zip(sim.ts.t, sim.ts.mid) if not math.isnan(m)]
print(
f"{len(sim.result.fills)} fills, mean spread {statistics.fmean(spreads):.4f}, "
f"mean |mid - fundamental| {statistics.fmean(gaps):.4f}"
)
# 14448 fills, mean spread 0.0114, mean |mid - fundamental| 0.0531
print(market.background)
# ['noise', 'informed']
The spread is a little over one tick, and the mid stays about five ticks from the fundamental on average: the book tracks the hidden value, with a lag.
horizon in build_market() is how far ahead SNAPSHOT events are scheduled;
run the market to the same time. Snapshots come every snapshot_every steps (10
by default) and drive both the strategies' on_tick and the PnL and inventory
series. On long runs, raise it to save memory.
Limits of the model¶
- One instrument, one book, an integer clock. No hidden or iceberg orders. Fees are per share.
- The agents are stylized, and their parameters are chosen for plausible depth, spread and tracking, not fitted to market data. Results are qualitative mechanisms, not calibrated estimates.
- In this model a metaorder's impact is a race between its execution and the arbitrageurs, so its size depends on execution speed more than it does in real markets. Realism has the numbers.