microstructure-sim 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,615 @@
1
+ Metadata-Version: 2.5
2
+ Name: microstructure-sim
3
+ Version: 1.0.0
4
+ Summary: Price-time priority limit order book and event-driven market microstructure simulator
5
+ Project-URL: Documentation, https://space-paragon1.github.io/Market-Microstructure-Simulator/
6
+ Project-URL: Repository, https://github.com/Space-Paragon1/Market-Microstructure-Simulator
7
+ Project-URL: Changelog, https://github.com/Space-Paragon1/Market-Microstructure-Simulator/blob/main/CHANGELOG.md
8
+ Project-URL: Issues, https://github.com/Space-Paragon1/Market-Microstructure-Simulator/issues
9
+ Author: Alex Chidera Umeasalugo
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: backtesting,market making,market microstructure,matching engine,order book,simulation
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Office/Business :: Financial :: Investment
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Provides-Extra: dev
26
+ Requires-Dist: gymnasium>=1.0; extra == 'dev'
27
+ Requires-Dist: hypothesis>=6.100; extra == 'dev'
28
+ Requires-Dist: matplotlib>=3.7; extra == 'dev'
29
+ Requires-Dist: mypy>=1.10; extra == 'dev'
30
+ Requires-Dist: pre-commit>=3; extra == 'dev'
31
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Provides-Extra: docs
35
+ Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
36
+ Requires-Dist: mkdocs<2,>=1.6; extra == 'docs'
37
+ Requires-Dist: mkdocstrings[python]>=0.26; extra == 'docs'
38
+ Provides-Extra: plot
39
+ Requires-Dist: matplotlib>=3.7; extra == 'plot'
40
+ Provides-Extra: rl
41
+ Requires-Dist: gymnasium>=1.0; extra == 'rl'
42
+ Description-Content-Type: text/markdown
43
+
44
+ # Market Microstructure Simulator
45
+
46
+ [![CI](https://github.com/Space-Paragon1/Market-Microstructure-Simulator/actions/workflows/ci.yml/badge.svg)](https://github.com/Space-Paragon1/Market-Microstructure-Simulator/actions/workflows/ci.yml)
47
+ ![Python](https://img.shields.io/badge/python-3.10%E2%80%933.14-blue)
48
+ ![Typed](https://img.shields.io/badge/mypy-strict-blue)
49
+ ![License](https://img.shields.io/badge/license-MIT-green)
50
+
51
+ A **price-time priority matching engine** and an **event-driven market simulator**
52
+ for studying liquidity provision, execution quality and adverse selection, in pure
53
+ Python with no runtime dependencies.
54
+
55
+ - **Matching engine.** Integer tick grid, O(1) cancel, `GTC`/`IOC`/`FOK`, market and
56
+ post-only orders, self-trade prevention, exchange-style modify semantics and
57
+ FIX-like execution reports. Its correctness is checked against an independent
58
+ reference model with property-based testing.
59
+ - **Closed-loop market.** Zero-intelligence noise traders and informed traders
60
+ around a latent fundamental value, so prices are *discovered* and liquidity
61
+ providers face real adverse selection.
62
+ - **Realistic preset.** Stochastic volatility, self-exciting order flow and
63
+ institutions splitting large orders. `MarketConfig.realistic()` reproduces fat
64
+ tails, volatility clustering, uncorrelated returns, long memory in order signs
65
+ and square-root price impact, measured with the `microbook.stylized` toolkit.
66
+ - **Research layer.** Order-entry latency, strategy timers and callbacks; four market
67
+ makers including Avellaneda–Stoikov; markouts, slippage vs arrival, spread
68
+ capture, PnL and inventory analytics; deterministic, seed-controlled experiments.
69
+
70
+ **Documentation: [space-paragon1.github.io/Market-Microstructure-Simulator](https://space-paragon1.github.io/Market-Microstructure-Simulator/)**
71
+ (getting started, concepts, guides and the API reference).
72
+
73
+ ```bash
74
+ pip install microstructure-sim # the import name is microbook
75
+ pip install "microstructure-sim[plot]" # plus matplotlib, for the example figures
76
+ pip install "microstructure-sim[rl]" # plus gymnasium, for the RL environment
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Try it in your browser
82
+
83
+ The [Market Maker Playground](https://space-paragon1.github.io/Market-Microstructure-Simulator/playground/)
84
+ runs the simulator in the page, with no server, using [Pyodide](https://pyodide.org)
85
+ (CPython compiled to WebAssembly). Pick a market maker and a market, add latency or
86
+ informed traders, and see PnL, inventory and markouts; 20,000 steps take about a
87
+ second. The source is in [`docs/demo/`](docs/demo/).
88
+
89
+ [![Market Maker Playground](https://raw.githubusercontent.com/Space-Paragon1/Market-Microstructure-Simulator/main/docs/figures/demo.png)](https://space-paragon1.github.io/Market-Microstructure-Simulator/playground/)
90
+
91
+ ## Results
92
+
93
+ `examples/compare_market_makers.py` runs every strategy in the same market over
94
+ 16 seeds × 20,000 time steps. For a given seed, every strategy faces the identical
95
+ fundamental path and exogenous order arrivals (common random numbers). The 192
96
+ simulations take about 26 s on a laptop.
97
+
98
+ ![Market-maker experiments](https://raw.githubusercontent.com/Space-Paragon1/Market-Microstructure-Simulator/main/docs/figures/mm_experiments.png)
99
+
100
+ **1. Strategy comparison** (latency 0; `t` = ticks per share)
101
+
102
+ | Strategy | PnL | s.e. | Sharpe | Mean \|inv\| | Spread capture | Markout @1 | Markout @100 |
103
+ |---|---:|---:|---:|---:|---:|---:|---:|
104
+ | Symmetric MM | 4.43 | 0.16 | 6.47 | 1.88 | 0.56 t | 0.44 t | 0.29 t |
105
+ | **Adaptive MM** | **5.04** | 0.21 | **6.89** | 1.97 | 0.59 t | 0.49 t | 0.35 t |
106
+ | Adaptive MM, no imbalance lean | 4.46 | 0.22 | 5.97 | 1.98 | 0.61 t | 0.50 t | 0.34 t |
107
+ | Avellaneda–Stoikov (rolling τ) | 4.53 | 0.17 | 6.38 | 1.81 | 0.58 t | 0.46 t | 0.31 t |
108
+
109
+ **2. Latency** (Adaptive MM)
110
+
111
+ | Latency (steps) | 0 | 5 | 20 | 50 |
112
+ |---|---:|---:|---:|---:|
113
+ | PnL | 5.04 ± 0.21 | 1.59 ± 0.26 | −7.27 ± 0.59 | −18.63 ± 1.19 |
114
+ | Markout @100 | 0.35 t | 0.33 t | 0.18 t | −0.26 t |
115
+
116
+ **3. Informed flow** (Adaptive MM)
117
+
118
+ | Informed arrivals / step | 0.0 | 0.2 | 0.4 | 0.8 |
119
+ |---|---:|---:|---:|---:|
120
+ | PnL | 5.50 ± 0.09 | 6.78 ± 0.13 | 5.04 ± 0.21 | 0.52 ± 0.22 |
121
+ | Sharpe | 16.3 | 12.4 | 6.9 | 0.5 |
122
+ | Markout @100 | 0.48 t | 0.41 t | 0.35 t | 0.16 t |
123
+
124
+ What the experiments show:
125
+
126
+ - **Markouts decay with horizon for every maker.** Part of the spread earned at
127
+ the fill is given back as the price moves against it. That is adverse
128
+ selection, measured directly.
129
+ - **The order-book-imbalance signal is worth about +0.6 PnL** (5.04 vs 4.46). It is
130
+ the only difference between those two runs.
131
+ - **Latency is ruinous for a liquidity provider.** Slow quotes become stale. At
132
+ 50 steps the 100-step markout turns negative: the maker is systematically picked
133
+ off.
134
+ - **Informed flow cuts both ways.** It brings volume, so PnL first rises, but
135
+ Sharpe and markouts fall monotonically, and at high intensity adverse selection
136
+ overwhelms the spread.
137
+ - Avellaneda–Stoikov needs γ calibrated to the *realized* mid volatility, which
138
+ is about 3.6× lower than the fundamental's, because the book lags and smooths
139
+ the latent value. With a γ chosen against the fundamental, its inventory skew
140
+ is negligible and it carries inventory through trends.
141
+
142
+ ![Single run](https://raw.githubusercontent.com/Space-Paragon1/Market-Microstructure-Simulator/main/docs/figures/market_run.png)
143
+
144
+ *Single seed. The book tracks the latent fundamental with a lag; the Adaptive MM's
145
+ inventory mean-reverts around zero. Rankings on one seed differ from the 16-seed
146
+ averages above.*
147
+
148
+ ### Does the simulated market look real?
149
+
150
+ Real markets share a set of statistical signatures, the *stylized facts* (Cont
151
+ 2001; Bouchaud et al. 2018). `examples/stylized_facts.py` measures them in the
152
+ default market and in `MarketConfig.realistic()` (8 seeds × 200,000 steps, read
153
+ as seconds; 20 s on a laptop):
154
+
155
+ | Statistic | `MarketConfig()` | `.realistic()` | Real markets |
156
+ |---|---:|---:|---:|
157
+ | Tail index (Hill, 10-step returns) | 7.1 | **2.7** | ≈ 3 (2–5) |
158
+ | Excess kurtosis at 10 / 100 / 1,000 steps | 4.5 / 0.2 / −0.6 | 40 / 4.0 / 1.6 | large, falling with horizon |
159
+ | Return autocorrelation, lag 1 (100-step returns) | 0.52 | **−0.01** | ≈ 0 |
160
+ | Return autocorrelation, lag 1 (10-step returns) | 0.04 | −0.08 | ≈ 0 or slightly < 0 (bid-ask bounce) |
161
+ | \|Return\| autocorrelation at 10 / 100 / 1,000 steps | 0.11 / 0.02 / 0.00 | 0.32 / 0.10 / 0.03 | > 0, slow decay |
162
+ | Order-sign autocorrelation, lag 1 / 10 / 100 / 1,000 | 0.39 / 0.36 / 0.14 / −0.01 | 0.39 / 0.31 / 0.05 / 0.02 | ≈ c·lag^−0.5 |
163
+ | Order-sign decay, fitted exponent | – | **0.52** | ≈ 0.5 |
164
+ | Impact prefactor Y in I = Yσ√(Q/V) | – | **0.49 ± 0.02** | 0.5–1 |
165
+
166
+ ![Stylized facts](https://raw.githubusercontent.com/Space-Paragon1/Market-Microstructure-Simulator/main/docs/figures/stylized_facts.png)
167
+
168
+ The preset reproduces every fact in the table, and held-out seeds (11–18) give
169
+ the same numbers within their error bars. Long memory in order signs comes
170
+ from metaorders split into many small child orders. One metaorder then spans
171
+ hundreds of trades, as institutional executions do. The same splitting lets a
172
+ metaorder move the price faster than arbitrage pulls it back, which gives a
173
+ concave, square-root impact curve (fitted exponent 0.51).
174
+
175
+ What it does not capture: in this model the impact of a metaorder is a race
176
+ between its execution and arbitrage, so Y is roughly proportional to execution
177
+ speed. With one child order every 10 / 4 / 2 / 1 steps, Y is 0.0 / 0.14 /
178
+ 0.27 / 0.49, with everything else fixed. In real markets the participation rate
179
+ matters much less. The preset matches the square-root law at its calibrated
180
+ speed, but the law does not emerge at every speed. The tail index (2.7) is also
181
+ slightly below the typical 3.
182
+
183
+ #### Against real data
184
+
185
+ The literature values above come from many markets and studies.
186
+ `examples/real_data_facts.py` measures one real market directly, with the same
187
+ code: every public BTC/USD trade on Kraken on 4 June 2024 (UTC), 26,649 trades
188
+ from 15,976 aggressive orders, downloaded from Kraken's public API (the date is
189
+ fixed, so anyone gets the same data):
190
+
191
+ <!-- --8<-- [start:real-data] -->
192
+ | Statistic | Simulator (`.realistic()`) | Kraken BTC/USD, 2024-06-04 |
193
+ |---|---:|---:|
194
+ | Tail index (Hill, 10 s returns) | 2.74 | 3.04 |
195
+ | Excess kurtosis at 10 s / 100 s / 1,000 s | 40.1 / 4.0 / 1.6 | 28.0 / 6.7 / 0.9 |
196
+ | Return autocorrelation, lag 1 (100 s returns) | −0.01 | 0.05 |
197
+ | Return autocorrelation, lag 1 (10 s returns) | −0.08 | 0.11 |
198
+ | \|Return\| autocorrelation at 10 s / 100 s / 1,000 s | 0.32 / 0.10 / 0.03 | 0.14 / 0.10 / 0.08 |
199
+ | Order-sign autocorrelation, lag 1 / 10 / 100 / 1,000 | 0.39 / 0.31 / 0.05 / 0.02 | 0.28 / 0.17 / 0.03 / 0.02 |
200
+ | Order-sign decay, fitted exponent | 0.53 | 0.46 |
201
+
202
+ The simulator column averages 8 seeds of 200,000 steps, a step read as one
203
+ second; the Kraken column is one day. They agree on every fact: fat tails that
204
+ thin out with the horizon, little linear autocorrelation, volatility
205
+ clustering, and order signs with long memory decaying at about lag^−0.5. The
206
+ magnitudes differ, and some differences are in the data rather than the model:
207
+
208
+ - **Crypto, not equities.** The preset is calibrated to equity-like statistics.
209
+ Bitcoin trades around the clock, with no open or close, and one exchange sees
210
+ only part of the market's flow.
211
+ - **Trade prices, not mids.** The public data has trades but no quotes, so the
212
+ real price path is the last trade price. On a day with one aggressive order
213
+ every five seconds, many 10-second intervals have no trade and the price is
214
+ stale; stale prices give the positive lag-1 autocorrelation of 10-second
215
+ returns (0.11). The simulator's mid moves with every quote and shows the usual
216
+ small negative value from bid-ask bounce.
217
+ - **Clock time vs trade time.** Both columns sample on a clock in seconds, but
218
+ the simulator's activity is the same at every hour, while real activity follows
219
+ the time of day: it is busiest when the US and European markets are open. That
220
+ daily pattern alone keeps the autocorrelation of |returns| positive at long
221
+ lags, which is part of why it is higher in the real data at 1,000 s (0.08
222
+ against 0.03).
223
+ - **One day is one sample.** The Kraken numbers carry the noise of a single
224
+ day; the fitted exponent and the long-lag autocorrelations move from day to
225
+ day. Run another day with `--start`.
226
+ <!-- --8<-- [end:real-data] -->
227
+
228
+ Price impact is not compared: it needs metaorders, and public trade data does
229
+ not say which trades belong to one.
230
+
231
+ ---
232
+
233
+ ## Matching engine
234
+
235
+ ```python
236
+ from microbook import LimitOrderBook, Order, Side, STPMode, TimeInForce
237
+
238
+ lob = LimitOrderBook(tick_size=0.01, stp=STPMode.CANCEL_RESTING)
239
+ lob.submit(Order.limit("a1", Side.SELL, 100.02, 5, owner="mm"))
240
+ lob.submit(Order.limit("a2", Side.SELL, 100.03, 10))
241
+
242
+ r = lob.submit(Order.limit("b1", Side.BUY, 100.03, 20)) # sweeps 2 levels, rests 5
243
+ print(r.status, [(f.price, f.qty) for f in r.fills], r.resting_qty)
244
+ # OrderStatus.PARTIALLY_FILLED [(100.02, 5), (100.03, 10)] 5
245
+
246
+ r = lob.submit(Order.limit("b2", Side.SELL, 100.03, 8, tif=TimeInForce.IOC))
247
+ print(r.status, r.filled_qty, r.canceled_qty) # CANCELED 5 3
248
+
249
+ r = lob.modify("b1", new_qty=0) # cancel via modify
250
+ print(lob.depth(), lob.check_invariants())
251
+ ```
252
+
253
+ `examples/quickstart.py` tours every feature.
254
+
255
+ | Message | Semantics |
256
+ |---|---|
257
+ | `LIMIT` `GTC` | match while crossing, rest the remainder |
258
+ | `LIMIT` `IOC` | match while crossing, cancel the remainder |
259
+ | `LIMIT` `FOK` | fill completely or do nothing (pre-checked, no side effects) |
260
+ | `MARKET` | sweep the opposite side, never rests |
261
+ | `post_only` | rejected if it would take liquidity |
262
+ | `modify` reduce | same price, smaller size: amended in place, **keeps priority** |
263
+ | `modify` reprice / increase | loses priority (cancel/replace); a crossing reprice trades and returns its fills |
264
+ | self-trade | `NONE`, `CANCEL_RESTING` or `CANCEL_INCOMING`, keyed on `Order.owner` |
265
+ | invalid input | duplicate id, off-tick price, bad modify → `REJECTED`, book untouched |
266
+
267
+ **Data structures.** Prices are stored as integer ticks, so float keys can never
268
+ alias and off-grid prices are rejected. Each side keeps a sorted list of price
269
+ keys with the best price at the *end*, so reading or removing the touch is O(1).
270
+ Each level is an `OrderedDict` (FIFO, O(1) removal by id) with an incrementally
271
+ maintained aggregate size.
272
+
273
+ **Correctness.** `tests/test_book_model.py` drives random sequences of submits,
274
+ cancels, modifies and duplicate submits through the engine and through a
275
+ deliberately naive reference book (a flat list re-sorted on every message), under
276
+ all three STP modes. After every step the two must agree exactly on fills,
277
+ statuses and depth, and `check_invariants()` must pass. Injecting a FIFO
278
+ violation, an off-by-one in the crossing test, or a stale level-size cache each
279
+ makes the test fail.
280
+
281
+ **Performance** (`benchmarks/bench_book.py`: 200k messages, 55% passive adds, 35%
282
+ cancels, 10% aggressive; Apple M2, CPython 3.12):
283
+
284
+ | | v0.1 | v0.2 |
285
+ |---|---:|---:|
286
+ | Throughput | 139k msg/s | **484k msg/s** |
287
+ | Cancel p50 / p99 | 13.8 µs / 44.4 µs | **0.50 µs / 1.08 µs** |
288
+ | Aggressive p50 | 2.00 µs | 1.96 µs |
289
+ | Passive add p50 | 0.54 µs | 0.88 µs |
290
+
291
+ Passive adds are slower because they now pay for duplicate-id protection, tick
292
+ validation and an execution report. Cancels dominate real message traffic, so
293
+ throughput still improves 3.5×. The full simulator, including agents and
294
+ analytics, runs at about 200k events/s (`benchmarks/bench_sim.py`).
295
+
296
+ **Optional native build.** The engine (`book.py`, `order.py`, `types.py`) can be
297
+ compiled with [mypyc](https://mypyc.readthedocs.io/). This needs a C compiler:
298
+
299
+ ```bash
300
+ HATCH_BUILD_HOOK_ENABLE_MYPYC=true pip install --no-binary microstructure-sim microstructure-sim
301
+
302
+ # from a checkout: build through the sdist, which compiles in a temporary copy
303
+ HATCH_BUILD_HOOK_ENABLE_MYPYC=true python -m build -o native/ && pip install native/*.whl
304
+ ```
305
+
306
+ Avoid `pip install .` and `python -m build --wheel` with the hook enabled: mypyc
307
+ compiles in place and leaves `.so` files in `src/microbook/`. Those shadow the
308
+ Python sources, so an editable install would silently ignore your edits.
309
+
310
+ The code is the same and CI runs the whole test suite against the compiled
311
+ wheel, including the golden digests, so seeded results are identical. One
312
+ difference: mypyc drops class docstrings, so `help(LimitOrderBook)` is empty in a
313
+ compiled install (the documentation site has them). Best of 7 runs of the benchmark above:
314
+
315
+ | | pure Python | compiled |
316
+ |---|---:|---:|
317
+ | Throughput | 521k msg/s | **597k msg/s** |
318
+ | Passive add p50 | 0.83 µs | **0.58 µs** |
319
+ | Aggressive p50 | 1.88 µs | **1.46 µs** |
320
+ | Cancel p50 | 0.38 µs | **0.33 µs** |
321
+
322
+ The whole simulator gains only 10–20%, because agents and strategies stay
323
+ interpreted (they are meant to be subclassed). The gain is too small to justify
324
+ platform-specific wheels, so the published wheel is pure Python.
325
+
326
+ ---
327
+
328
+ ## Simulator
329
+
330
+ ```mermaid
331
+ flowchart LR
332
+ Q[("event heap<br/>(time, seq)")] -->|SUBMIT / CANCEL / MODIFY| B[LimitOrderBook]
333
+ B -->|ExecutionReport + fills| S[MarketSimulator]
334
+ S -->|portfolio, metrics| P[Portfolio / ExecutionMetrics]
335
+ S -->|on_fill / on_report| ST[Strategies & agents]
336
+ Q -->|SNAPSHOT → on_tick<br/>TIMER → on_timer| ST
337
+ ST -->|Actions, delayed by latency| Q
338
+ ```
339
+
340
+ - **Deterministic.** Events are ordered by `(time, seq)`, ties resolve FIFO, and
341
+ every random stream is seeded per agent. The test suite asserts bit-identical
342
+ reruns.
343
+ - **Strategies never touch the book.** They read it and return `Action`s; order
344
+ messages arrive after the strategy's `latency`, while decisions use the
345
+ then-current book. Arrival mid is recorded at *decision* time, so implementation
346
+ shortfall includes latency.
347
+ - **Accounting.** Fills are attributed to the maker and the taker. `Portfolio`
348
+ uses average cost with maker/taker fees. Every participant is an agent, so total
349
+ PnL is exactly zero-sum, and that is tested.
350
+
351
+ **Market agents** (`microbook.sim.agents`, assembled by `build_market`):
352
+
353
+ | Agent | Behaviour |
354
+ |---|---|
355
+ | `FundamentalValue` | latent Gaussian random walk, optional jumps and stochastic volatility; invisible to the book |
356
+ | `NoiseTrader` | zero-intelligence population (Smith, Farmer et al., 2003): Poisson limit orders placed relative to the opposite touch, Poisson or self-exciting (`HawkesProcess`) market orders, proportional random cancellation |
357
+ | `InformedTrader` | IOC orders when the book is mispriced vs the fundamental by more than a threshold, optionally sized by the mispricing |
358
+ | `MetaorderTrader` | uninformed institutions splitting Pareto-sized orders into child market orders (Lillo, Mike & Farmer 2005); completed metaorders feed the impact analysis |
359
+
360
+ **Strategies:**
361
+
362
+ | Strategy | Idea |
363
+ |---|---|
364
+ | `MarketMaker` | symmetric quotes around mid, fixed inventory skew |
365
+ | `AdaptiveMarketMaker` | volatility-scaled spread, inventory skew, order-book-imbalance lean, hard limits |
366
+ | `AvellanedaStoikovMarketMaker` | reservation price `s − qγσ²τ` and optimal spread `γσ²τ + (2/γ)ln(1+γ/k)`, finite or rolling horizon, online σ |
367
+ | `TWAPExecutor` | time-sliced market orders; unfilled remainder rescheduled |
368
+
369
+ Market makers derive from `TwoSidedQuoter`, which rounds passively onto the grid,
370
+ never quotes through the opposite touch (post-only), and leaves unchanged quotes
371
+ alone so they keep queue priority.
372
+
373
+ ### Writing a strategy
374
+
375
+ ```python
376
+ from microbook import Order, Side
377
+ from microbook.sim import Action, MarketConfig, Strategy, build_market, strategy_report
378
+
379
+
380
+ class WideSpreadBuyer(Strategy):
381
+ """Buy 5 shares whenever the spread is wider than one tick; check every 50 steps."""
382
+
383
+ def on_start(self, now, lob):
384
+ return [Action.timer(now + 50)]
385
+
386
+ def on_timer(self, now, lob):
387
+ actions = [Action.timer(now + 50)]
388
+ spread = lob.spread()
389
+ if spread is not None and spread > 1.5 * lob.tick_size: # 2+ ticks, robust to float round-off
390
+ actions.append(Action.submit(Order.market(self.next_order_id(), Side.BUY, 5), now))
391
+ return actions
392
+
393
+
394
+ market = build_market(MarketConfig(seed=1), [WideSpreadBuyer("wsb", latency=2)], horizon=10_000)
395
+ sim = market.run(10_000)
396
+ print(strategy_report(sim, ["wsb"])["wsb"])
397
+ ```
398
+
399
+ Hooks: `on_start`, `on_tick` (every `SNAPSHOT`), `on_timer`, `on_fill(now, fill, side, is_maker, lob)`
400
+ and `on_report(now, report)`. Each returns a list of `Action`s.
401
+
402
+ ### Metrics
403
+
404
+ | Metric | Definition |
405
+ |---|---|
406
+ | Slippage vs arrival | fill VWAP − mid at decision time (buys; mirrored for sells), over orders with a known arrival mid |
407
+ | Spread capture | maker fills: distance from the **pre-trade** mid, per share |
408
+ | Markout @h | `side × (mid(t+h) − fill price)`, volume-weighted; its decay with *h* measures adverse selection |
409
+ | Fill ratio / participation | filled ÷ submitted; own volume ÷ market volume |
410
+ | PnL stats | final, max drawdown, per-sample PnL volatility, Sharpe (mean/std of increments × √n, not annualised) |
411
+
412
+ ---
413
+
414
+ ## Replaying historical data
415
+
416
+ `microbook.replay` feeds order-by-order exchange data through the matching engine.
417
+ It reads the [LOBSTER](https://lobsterdata.com) format, the standard academic
418
+ reconstruction of NASDAQ TotalView-ITCH (academic sample days are available on
419
+ request from LOBSTER).
420
+
421
+ ```python
422
+ from microbook.replay import build_replay, check_reconstruction, load_lobster
423
+ from microbook.sim import AdaptiveMarketMaker, AdaptiveConfig, strategy_report
424
+
425
+ day = load_lobster("AAPL_2012-06-21_message_10.csv", "AAPL_2012-06-21_orderbook_10.csv")
426
+ print(check_reconstruction(day)) # rebuilt book vs the exchange's snapshots
427
+
428
+ mm = AdaptiveMarketMaker(AdaptiveConfig(size=50, latency=5), name="mm")
429
+ replay = build_replay(day, [mm], time_unit=1e-3) # 1 clock unit = 1 ms
430
+ sim = replay.run()
431
+ print(strategy_report(sim, ["mm"], horizons=(100, 1_000, 10_000))["mm"])
432
+ ```
433
+
434
+ - **Reconstruction.** New orders, partial cancels and deletions are applied as
435
+ they are. An execution is replayed as an IOC from the aggressor's side, so it
436
+ is matched by the engine's own price-time priority. Orders resting before the
437
+ file starts are seeded as one aggregate order per level. `check_reconstruction`
438
+ compares the rebuilt book with the recorded snapshot after every message.
439
+ - **Backtests.** Any `Strategy` trades alongside the historical flow, with its
440
+ latency and analytics. A strategy is filled when history reaches its place in
441
+ the queue, or when an incoming order crosses its quote. The historical book is
442
+ then corrected, so a passive strategy with small orders leaves the recorded
443
+ book exactly intact (tested). The flow does not react to the strategy, so
444
+ market impact is ignored. Taking liquidity, or swallowing a whole incoming
445
+ order, makes the rest of the replay counterfactual; `HistoricalFlow.stats`
446
+ counts both.
447
+ - **Validation without licensed data.** `synthetic_day()` generates
448
+ LOBSTER-format days from an independent FIFO reference model (it does not use
449
+ the engine), and `write_lobster()` saves them. On these the reconstruction is
450
+ exact at all levels after every message.
451
+
452
+ `examples/replay_lobster.py` runs all three steps (reconstruction, a market-maker
453
+ latency sweep, the day's stylized facts) on LOBSTER files, or on a synthetic day
454
+ if none are given.
455
+
456
+ ---
457
+
458
+ ## Reinforcement learning
459
+
460
+ `microbook.rl.MarketMakingEnv` is a [Gymnasium](https://gymnasium.farama.org)
461
+ environment (`pip install "microstructure-sim[rl]"`). Every `decision_interval`
462
+ steps the agent picks how many ticks behind the touch to quote on each side.
463
+ Observations are inventory, spread, book imbalance, the last mid move,
464
+ volatility and time left. The reward is the PnL change in ticks, minus an
465
+ optional quadratic inventory penalty. Quote handling is shared with the
466
+ library's market makers (post-only, queue-preserving, inventory limit), so a
467
+ policy trained here is directly comparable to them. The environment works with
468
+ any Gymnasium-compatible library.
469
+
470
+ ```python
471
+ from microbook.rl import MarketMakingEnv
472
+ from microbook.sim import MarketConfig
473
+
474
+ env = MarketMakingEnv(MarketConfig.realistic(), horizon=5_000, inventory_penalty=2e-5)
475
+ obs, info = env.reset(seed=0)
476
+ obs, reward, terminated, truncated, info = env.step(env.action_space.sample())
477
+ ```
478
+
479
+ `examples/rl_market_making.py` trains a 7-parameter linear policy with the
480
+ cross-entropy method (numpy only, about a minute) and evaluates it on 32
481
+ held-out seeds:
482
+
483
+ | Policy | PnL per episode ($) | Mean peak \|inventory\| |
484
+ |---|---:|---:|
485
+ | Random offsets | −5.57 ± 1.11 | 37.5 |
486
+ | Always join the touch | −11.01 ± 1.12 | 43.8 |
487
+ | Hand-written `MarketMaker` rule (shift 2 ticks against inventory) | 1.00 ± 0.07 | 6.2 |
488
+ | **Learned** | **1.10 ± 0.05** | 6.7 |
489
+
490
+ Starting from "1 tick out, no skew", the learner rediscovers the 2-tick
491
+ inventory shift and adds a strong order-book-imbalance lean and volatility
492
+ widening. Paired by seed, it is ahead of the hand-written rule by 9.8 ± 7.2
493
+ ticks, which is not a significant difference. Quoting without inventory control
494
+ loses money to informed traders.
495
+
496
+ ---
497
+
498
+ ## Project layout
499
+
500
+ ```
501
+ src/microbook/
502
+ ├── book.py # LimitOrderBook: matching engine
503
+ ├── order.py, types.py # Order, Side, Fill, ExecutionReport, enums
504
+ ├── stylized.py # stylized facts: tails, ACFs, order-sign memory, impact
505
+ ├── replay.py # LOBSTER I/O, historical replay, reconstruction check
506
+ ├── rl.py # Gymnasium market-making environment (optional extra)
507
+ └── sim/
508
+ ├── simulator.py # MarketSimulator: event loop, latency, attribution
509
+ ├── strategy.py # Strategy, Action, TwoSidedQuoter, MarketMaker, TWAPExecutor
510
+ ├── strategies_mm.py # AdaptiveMarketMaker, AvellanedaStoikovMarketMaker
511
+ ├── agents.py # FundamentalValue, Noise/Informed/MetaorderTrader, HawkesProcess
512
+ ├── scenarios.py # MarketConfig (+ realistic preset), build_market
513
+ ├── portfolio.py # average-cost PnL with maker/taker fees
514
+ ├── execution_metrics.py, analytics.py, metrics.py
515
+ └── orderflow.py # open-loop Poisson flow (controlled tests)
516
+ examples/ # quickstart, static_flow, compare_market_makers, stylized_facts,
517
+ # real_data_facts, replay_lobster, rl_market_making
518
+ benchmarks/ # bench_book, bench_sim, profile_book
519
+ docs/demo/ # browser demo: index.html, worker.js (Pyodide), demo.py
520
+ tests/ # model-based, property-based, API-snapshot and docs-snippet tests
521
+ ```
522
+
523
+ ## Development
524
+
525
+ ```bash
526
+ python -m venv .venv && source .venv/bin/activate
527
+ pip install -e ".[dev]"
528
+ pre-commit install # ruff lint + format on every commit
529
+
530
+ pytest --cov # tests + coverage (95% branch)
531
+ ruff check . && ruff format --check . # lint / format
532
+ mypy # strict type checking
533
+
534
+ python examples/compare_market_makers.py --plot docs/figures # regenerate results
535
+ python examples/stylized_facts.py --plot docs/figures # regenerate realism figure
536
+ python benchmarks/bench_book.py # engine benchmark
537
+ ```
538
+
539
+ ## Stability and versioning
540
+
541
+ <!-- --8<-- [start:stability] -->
542
+ From 1.0.0, microbook follows [Semantic Versioning](https://semver.org): a patch
543
+ release fixes bugs, a minor release adds features, and only a major release removes
544
+ or changes public API. Until 1.0.0, a minor release may break the API, and every
545
+ break is listed in the [changelog](https://github.com/Space-Paragon1/Market-Microstructure-Simulator/blob/main/CHANGELOG.md)
546
+ with what to use instead.
547
+
548
+ **The public API** is every name in `__all__` of `microbook`, `microbook.sim`,
549
+ `microbook.stylized`, `microbook.replay` and `microbook.rl`, together with the
550
+ documented parameters, attributes and return values of those names. Nothing else is
551
+ public:
552
+
553
+ - Import from the packages above, not from submodules such as `microbook.sim.agents`.
554
+ The submodule layout can change in any release.
555
+ - Names starting with an underscore are internal.
556
+ - The text formatting of reports and tables (`format_table`, the examples' output)
557
+ can change in any release.
558
+
559
+ `tests/test_public_api.py` pins the public names, so an accidental change fails CI.
560
+
561
+ **Deprecation.** A public name that is renamed or replaced keeps working, with a
562
+ `DeprecationWarning` that names its replacement, for at least one minor release, and
563
+ is removed only in the next major release. The changelog lists every deprecation.
564
+
565
+ **Reproducibility.** A given version, seed and configuration produces identical
566
+ fills on every supported Python, with or without the compiled build. Golden digests
567
+ in `tests/test_sim_determinism.py` check this in CI. A release that changes seeded
568
+ output (a recalibration or a bug fix) says so in the changelog. Simulated numbers
569
+ from different minor versions are therefore not guaranteed to match.
570
+
571
+ **Python versions.** The supported CPython versions are the ones tested in CI and
572
+ listed in the package classifiers. Support for a version is dropped only in a minor
573
+ release, with a changelog note.
574
+ <!-- --8<-- [end:stability] -->
575
+
576
+ ## Limitations
577
+
578
+ - Single instrument, discrete integer clock, and no hidden or iceberg orders. Fees
579
+ are per share.
580
+ - The agents are stylized and their parameters are chosen for plausible depth,
581
+ spread and tracking. They are **not** fitted to market data, so treat the results
582
+ as qualitative mechanisms rather than calibrated estimates.
583
+ - Pure Python (optionally compiled with mypyc): fast enough for research loops
584
+ (hundreds of thousands of messages per second), not a production matching engine.
585
+
586
+ What is planned, and what is deliberately out of scope, is in [ROADMAP.md](ROADMAP.md).
587
+
588
+ ## Contributing
589
+
590
+ Bug reports, questions and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md)
591
+ covers setup, the checks a change must pass, and how to add a strategy or an agent.
592
+ Everyone taking part follows the [code of conduct](CODE_OF_CONDUCT.md); security
593
+ problems are reported privately, as [SECURITY.md](SECURITY.md) describes.
594
+
595
+ ## Citing
596
+
597
+ If you use microbook in your research, please cite it. GitHub's "Cite this
598
+ repository" button reads [CITATION.cff](CITATION.cff), or use:
599
+
600
+ ```bibtex
601
+ @software{umeasalugo_microbook,
602
+ author = {Umeasalugo, Alex Chidera},
603
+ title = {microbook: a price-time priority matching engine and event-driven market microstructure simulator},
604
+ url = {https://github.com/Space-Paragon1/Market-Microstructure-Simulator},
605
+ version = {1.0.0},
606
+ license = {MIT}
607
+ }
608
+ ```
609
+
610
+ Cite the version you used, so others can reproduce your numbers: seeded results
611
+ are identical within a version.
612
+
613
+ ## License
614
+
615
+ MIT. For education and research; it does not connect to any market.
@@ -0,0 +1,24 @@
1
+ microbook/__init__.py,sha256=AeTGJpUQDMw-HeaxyeXN2G4pV_V7xvCykJR-6tSZf6Y,525
2
+ microbook/book.py,sha256=2zospP9AylaLY9TRBYeOWXq9_AzcRCBSHK9PcXgd0vo,22918
3
+ microbook/order.py,sha256=DW9wfV4jYIfG1pM4FfeCMYXpVhpfjRor6P9eN5tc2KY,2967
4
+ microbook/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ microbook/replay.py,sha256=AG8FWsRWJZE7cpCGj0J6ClBrE_i6-19z1zVaaz8PzRE,27405
6
+ microbook/rl.py,sha256=s6c3ITwk01J1fde4Q61ChIX58LM6KLpoZpSioZQGUgU,9555
7
+ microbook/stylized.py,sha256=jjGW3EEDovHfCdYw_Mhpz1QOGutKip4w8NdpIKFXhN0,12237
8
+ microbook/types.py,sha256=9q83uoDbPUhpiSxbgYV2TEKMk-XJXprpyn_t1wOxZ-s,4155
9
+ microbook/sim/__init__.py,sha256=Y3fS5QrGbLqgXPWxudzyV91DhBRAV37ym1ZxkBj-UeQ,2271
10
+ microbook/sim/agents.py,sha256=Gyd7yiXtSKiQPrq3iynbPJPqFzv9OolkhZ3Wbj4VT24,20607
11
+ microbook/sim/analytics.py,sha256=2lt_0ghXem5g60_36J4ZNROGjwMno88eJ-_OGX6W5tU,7729
12
+ microbook/sim/events.py,sha256=ghQbajjKcJOad8q0TKr_JqidunY4qqK2Pwvgr6phq9I,1503
13
+ microbook/sim/execution_metrics.py,sha256=h6uukyPFw8VdBNyv6MhuGIPwawFPvlf6c02-caD9778,8400
14
+ microbook/sim/metrics.py,sha256=nb0CR8ajEkR9JqUNNzxRVe821QZTmI7V-s4sNubMofg,601
15
+ microbook/sim/orderflow.py,sha256=mjyaVR4WBTuwxoz69DlnL1-oy5ftkwVOn44aspTuUMA,2617
16
+ microbook/sim/portfolio.py,sha256=DWvFvz6jgjhbfEjP5E64WYsIWlp4nGdpKQqLlGPFhPk,3188
17
+ microbook/sim/scenarios.py,sha256=VscnUKytj-hP5Bbth-GtUwC4eQgcNsXnwiRHQyLtX0g,6126
18
+ microbook/sim/simulator.py,sha256=_izmIREqf5W0mvsn7RXrJRCJEOa7AirWTqoHhKov4Xk,12057
19
+ microbook/sim/strategies_mm.py,sha256=vV--Xh3bhtaDyuTrjWmwuCNrsTkm-s4CdCEZA73QPkI,7858
20
+ microbook/sim/strategy.py,sha256=pvUNfF15ZSASbLhxov3c0r63pw65LMQRiDcrtlQ5vq8,14450
21
+ microstructure_sim-1.0.0.dist-info/METADATA,sha256=zRIo3b-uBcI8AC5VcH-e3XTQNHLNCv3mkc9OzodjhoU,31071
22
+ microstructure_sim-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
23
+ microstructure_sim-1.0.0.dist-info/licenses/LICENSE,sha256=qejYYGphIDhN1At_r2Ajvw4qBLuhSLmIbfJv0i3yJTo,1080
24
+ microstructure_sim-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Chidera Umeasalugo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.