Getting started¶
This page takes you from installation to a strategy of your own trading in a simulated market. It takes about ten minutes.
Install¶
microbook needs Python 3.10 or newer and has no runtime dependencies.
Optional extras add what some features need:
| Extra | Adds | For |
|---|---|---|
plot |
matplotlib | the figures drawn by the examples |
rl |
gymnasium | the reinforcement-learning environment |
docs |
MkDocs Material, mkdocstrings | building this site |
dev |
pytest, hypothesis, ruff, mypy, pre-commit | working on microbook itself |
To get the latest code, or to run the examples and benchmarks, install from a checkout:
git clone https://github.com/Space-Paragon1/Market-Microstructure-Simulator.git
cd Market-Microstructure-Simulator
pip install -e ".[dev]"
Trade against an order book¶
A LimitOrderBook matches orders by price, then time.
Prices live on a tick grid, and every message returns an
ExecutionReport instead of raising.
from microbook import LimitOrderBook, Order, Side, TimeInForce
lob = LimitOrderBook(tick_size=0.01)
lob.submit(Order.limit("a1", Side.SELL, 100.02, 5))
lob.submit(Order.limit("a2", Side.SELL, 100.03, 10))
# A buy at 100.03 sweeps both ask levels and rests the remaining 5.
report = lob.submit(Order.limit("b1", Side.BUY, 100.03, 20))
print(report.status, [(f.price, f.qty) for f in report.fills], report.resting_qty)
# OrderStatus.PARTIALLY_FILLED [(100.02, 5), (100.03, 10)] 5
print(lob.best_bid(), lob.best_ask())
# 100.03 None
# An immediate-or-cancel sell for 8 takes the 5 resting shares; the other 3 are cancelled.
report = lob.submit(Order.limit("s1", Side.SELL, 100.03, 8, tif=TimeInForce.IOC))
print(report.status, report.filled_qty, report.canceled_qty)
# OrderStatus.CANCELED 5 3
Matching engine describes every order type and the modify, cancel and self-trade rules.
Run a simulated market¶
build_market() assembles a market around a hidden
"fundamental" value. Noise traders supply and take liquidity at random, and
informed traders trade whenever the book strays from the fundamental. Add your
strategies to it, run it, and analyse the result.
from microbook.sim import (
AdaptiveConfig,
AdaptiveMarketMaker,
MarketConfig,
build_market,
format_table,
strategy_report,
)
mm = AdaptiveMarketMaker(
AdaptiveConfig(base_half_spread_ticks=0.5, inv_k=0.3, inv_limit=50, vol_k=1.0, imb_k=1.0),
name="mm",
)
market = build_market(MarketConfig(seed=1), [mm], horizon=20_000)
sim = market.run(20_000)
report = strategy_report(sim, ["mm"])
print(format_table(report, ["final", "sharpe", "mean_abs_inventory", "markout_1", "markout_100"]))
The table shows the market maker's final PnL, its Sharpe ratio, how much inventory it carried, and its markouts: how far the price moved in its favour 1 and 100 steps after each fill. The 100-step markout is smaller than the 1-step one because informed traders pick off part of what the spread earned; that gap is adverse selection. Metrics defines each column.
Runs are deterministic: the same seed and settings give the same fills, every
time and on every supported Python. Change seed to see another day.
Write your own strategy¶
A strategy subclasses Strategy and reacts to hooks.
It never touches the book directly: each hook returns a list of
Actions (submit, cancel, modify, or a timer), and the
simulator delivers them after the strategy's latency.
This one checks the spread every 50 steps and buys 5 shares at market when the spread is wider than one tick:
from microbook import Order, Side
from microbook.sim import Action, MarketConfig, Strategy, build_market, strategy_report
class WideSpreadBuyer(Strategy):
"""Buy 5 shares whenever the spread is wider than one tick; check every 50 steps."""
def on_start(self, now, lob):
return [Action.timer(now + 50)]
def on_timer(self, now, lob):
actions = [Action.timer(now + 50)] # keep the clock running
spread = lob.spread()
if spread is not None and spread > 1.5 * lob.tick_size: # 2+ ticks, robust to float round-off
order = Order.market(self.next_order_id(), Side.BUY, 5)
actions.append(Action.submit(order, now))
return actions
buyer = WideSpreadBuyer("wsb", latency=2) # orders reach the book 2 steps after the decision
market = build_market(MarketConfig(seed=1), [buyer], horizon=10_000)
sim = market.run(10_000)
stats = strategy_report(sim, ["wsb"])["wsb"]
print(stats["volume"], stats["final_inventory"])
The hooks are:
| Hook | Called |
|---|---|
on_start(now, lob) |
once, when the run starts |
on_tick(now, lob) |
at every book snapshot (every MarketConfig.snapshot_every steps) |
on_timer(now, lob) |
when a timer the strategy set goes off |
on_fill(now, fill, side, is_maker, lob) |
for each fill of one of the strategy's orders |
on_report(now, report) |
for each execution report of a message the strategy sent |
Each hook returns a list of actions; return [] to do nothing. Every strategy
keeps its own Portfolio and execution metrics, which
strategy_report() summarises.
Next steps¶
- Concepts explain how the engine, the clock and the market model work: matching engine, simulation, the market model, metrics.
- Guides walk through larger tasks: comparing strategies, replaying LOBSTER data, reinforcement learning and performance and the native build.
- The API reference documents every public name.
- The Market Maker Playground runs the simulator in your browser.