Changelog¶
1.0.0¶
The first stable release. From here on microbook follows Semantic Versioning: the public API, defined in the stability policy, changes incompatibly only in a major release, and deprecated names keep working until then. Seeded results reproduce the numbers published for 0.4.0. It adds a documentation site with tested examples, a comparison with real market data, and the files a community project needs.
Changed¶
- Version 1.0.0; the package classifier is now "Development Status :: 5 - Production/Stable".
Added¶
- Python 3.14 support: tested in CI (3.10–3.14), and the native build is tested on 3.10 and 3.14.
- pre-commit hooks (ruff lint and format, YAML/TOML checks);
pre-commitis in thedevextra. - A coverage floor:
pytest --covfails below 90% branch coverage. - Docstrings on every public module, class, function and method, enforced by ruff's
D1rules onsrc/. microbook.simnow exportsFlowConfig,PoissonOrderFlow,imbalance,inventory_stats,max_drawdownandmid_at, which were reachable only through submodules.microbook.replayexportsPRICE_SCALE.__all__inmicrobook.book,microbook.orderandmicrobook.types.- A stability policy (README, "Stability and versioning"): SemVer from 1.0, a definition of the public API, deprecation rules and a reproducibility promise.
- A documentation site (MkDocs Material,
pip install -e ".[docs]",mkdocs serve) with an API reference generated from the docstrings. CI builds it with--strict, so a broken link or cross-reference fails the build, andtests/test_docs.pychecks that the reference lists every public name. - Docstrings on every field of the public dataclasses and named tuples (configs, records, results), so the reference documents every setting. Cross-references in docstrings now use Markdown links instead of Sphinx roles.
tests/test_public_api.pypins every public name and checks each one is documented. Golden digests of two seeded runs (tests/test_sim_determinism.py) check that results are identical on every supported Python and on the compiled build.- Documentation pages: Getting started; concepts (matching engine, simulation time and latency, the market model, realism and the stylized facts, metrics); guides (comparing strategies, replaying LOBSTER data, reinforcement learning, performance and the native build).
tests/test_docs_snippets.pyruns every Python snippet in the docs and checks that it prints the output shown under it, so the documentation cannot drift from the code.- The GitHub Pages site now serves the documentation at its root and the Market Maker Playground at
/playground/. The package metadata has aDocumentationURL. examples/real_data_facts.py: downloads a fixed day of public Kraken BTC/USD trades (cached after the first run) and measures the same stylized facts asexamples/stylized_facts.py, side by side with the realistic preset. Its parsing and paging are tested offline on a fixture (tests/test_real_data_facts.py).- A simulator-vs-real-market table (README and the Realism page): the realistic preset next to one day of Kraken BTC/USD, with the caveats of the comparison.
CONTRIBUTING.md,CODE_OF_CONDUCT.md(Contributor Covenant 2.1),SECURITY.md, issue forms for bug reports and feature requests, a pull-request template, andCITATION.cffwith a "Citing" section in the README.
Deprecated¶
AdaptiveMMConfigis nowAdaptiveConfig, named like every other config (NoiseConfig,AvellanedaStoikovConfig, ...). The old name still works and warns.TimeSeries.sprandTimeSeries.imbare nowTimeSeries.spreadandTimeSeries.imbalance, matching the keys ofTimeSeries.as_dict(). The old attributes still work and warn. Constructing aTimeSerieswith the keywordsspr=orimb=no longer works.
All deprecated names will be removed in 2.0.
Fixed¶
hill_tail_indexreturned a division-by-zero error instead of NaN when the largest values in the tail were all equal, as happens with returns of prices on a coarse tick grid.
Removed¶
microbook.sim.metrics.spread, a wrapper aroundLimitOrderBook.spread(); use the method.microbook.sim.agents.poissonis now private (_poisson). It is an internal sampler, not part of the API.
0.4.0¶
Replays historical data, adds a reinforcement-learning environment and a browser demo, and completes the realistic market: it now reproduces order-sign memory and square-root impact as well.
Added¶
- Historical replay (
microbook.replay): LOBSTER message/orderbook readers and writer,HistoricalFlow(replays messages into aMarketSimulator, so any strategy can trade against real order flow),build_replay, andcheck_reconstruction(rebuilt book vs the recorded snapshot after every message). A strategy is filled when history reaches its queue position, and the historical book is corrected so passive strategies leave it intact. synthetic_day(): LOBSTER-format days from an independent FIFO reference model, for trying the pipeline and testing without licensed data. Reconstruction of these is exact.LimitOrderBook.reduce(order_id, qty)(cancel-by-size, keeps priority) andAction.reduce. Covered by the model-based differential test.Strategy.same_time_timers: lets a strategy schedule a timer at the current time (used by the replay to apply one message per wake-up).examples/replay_lobster.py.- Reinforcement learning (
microbook.rl.MarketMakingEnv, optional extra[rl]): a Gymnasium environment for market making in the closed-loop market, passing Gymnasium's environment checker.examples/rl_market_making.pytrains a linear policy with the cross-entropy method; on held-out seeds it matches the hand-writtenMarketMakerrule. - Tests: 146 → 172 (replay, RL environment,
reducein the model-based test, order-sign memory and impact of the realistic preset). - Release workflow: tag
vX.Y.Zto build, check and publish to PyPI (trusted publishing) and create a GitHub release. - Browser demo (
docs/demo/, published to GitHub Pages by.github/workflows/pages.yml): the Market Maker Playground runs the simulator client-side with Pyodide in a Web Worker. You choose the market, the market maker, latency and informed flow, and it charts price vs fundamental, PnL, inventory and markouts. Light and dark themes, keyboard-accessible charts and a data table view. - Optional native build:
HATCH_BUILD_HOOK_ENABLE_MYPYC=true pip install ...compiles the engine with mypyc (throughput 521k → 597k msg/s; 10–20% end to end). Off by default; CI tests the compiled wheel on Python 3.10 and 3.13.
Changed¶
MarketConfig.realistic()now reproduces the two facts 0.3 missed. Order-sign autocorrelation decays aslag^-0.52(0.39 / 0.31 / 0.05 / 0.02 at lags 1 / 10 / 100 / 1000; was 0.16 / 0.12 / 0.01 / 0.00), and the impact prefactor isY = 0.49 ± 0.02(was 0.08), with a concave impact curve (exponent 0.51). Metaorders now split into 2-share children sent every step (MetaorderConfig(rate=0.03, size_alpha=1.4, child_qty=2, child_rate=1.0)), informed arrivals are less frequent (rate=0.3) and noise orders cancel faster (cancel_prob=0.03). Return statistics hold: Hill index 2.7, lag-1 autocorrelation of 100-step returns −0.01, volatility clustering unchanged. Runs with the preset are not reproducible across 0.3 → 0.4.- Known limitation: Y scales with metaorder execution speed in this model, unlike real markets.
LimitOrderBook: the market-order stop key is an integer sentinel instead of-inf(needed by mypyc; no behaviour change).
0.3.0¶
Makes the closed-loop market statistically realistic and adds the tools to check it.
Added¶
microbook.stylized: return sampling, autocorrelation, excess kurtosis, Hill tail index, aggressor-sign series, power-law fits, metaorder impact curves and a one-callstylized_facts()summary. The functions are pure and work on plain sequences, so they apply to historical data too.- Stochastic volatility in
FundamentalValue(vol_of_vol,vol_persistence): log-volatility is a mean-reverting AR(1), normalized so the average variance is unchanged. Withvol_of_vol=0the path is identical to 0.2. HawkesProcess/HawkesConfig: self-exciting noise market orders (NoiseConfig.market_hawkes) at the same mean rate.MetaorderTrader/MetaorderConfig: institutions splitting Pareto-sized orders into child market orders. Completed metaorders are exposed asMarket.metaordersfor impact measurement.InformedConfig.qty_per_tick/max_qty: informed trade size can scale with the mispricing.MarketConfig.realistic(): a calibrated preset with all of the above. It reproduces fat tails (Hill index ≈ 3), aggregational Gaussianity, near-zero return autocorrelation and volatility clustering.examples/stylized_facts.pyanddocs/figures/stylized_facts.png.- Dependabot updates for GitHub Actions and pip.
- Tests: 121 → 146.
Known gaps¶
- Order-sign autocorrelation decays faster than the empirical
lag^-0.5. - Metaorder impact is about six times below the square-root law (
Y ≈ 0.08vs 0.5–1).
0.2.0¶
A rewrite of the matching engine and a major extension of the simulator.
Fixed¶
- Duplicate order ids orphaned the earlier order (still matchable, no longer cancelable). They are now rejected.
modify()that crossed the spread discarded its fills, so trades never reached portfolios or metrics. Fills are now returned in theExecutionReportand attributed by the simulator.- Invalid
modify()destroyed the order (e.g.new_qty=-3cancelled it, then returnedFalse). Requests are validated first and rejections leave the order untouched. - A no-op
modify()(same price and quantity) lost queue priority. - Fees were deducted from cash but missing from mark-to-market PnL.
- Slippage vs arrival was diluted by fills without a registered arrival mid (the denominator used all fills). Spread capture had the same defect.
TWAPExecutortraded into a one-sided book and recorded an arrival mid of0.0, producing slippage of about 100.AdaptiveMarketMaker"skew" widened or narrowed the spread instead of shifting it. When short it quoted a crossed market (bid above ask), and the imbalance lean had the wrong sign.- Bid-level insertion copied the whole price list on every insert, and cancel rebuilt the whole queue (O(n)).
SimResult.pnl_seriesdid not exist unless a SNAPSHOT event had fired.examples/run_mm_vs_flow.pyhad a syntax error.
Added¶
- Integer tick grid (
LimitOrderBook(tick_size=...)); off-grid prices are rejected. - Order types and time-in-force:
MARKET,LIMIT×GTC/IOC/FOK, pluspost_only. - Self-trade prevention (
STPMode.CANCEL_RESTING/CANCEL_INCOMING), keyed onOrder.owner. submit()returning anExecutionReport(status, fills, resting / cancelled quantity, reason).- Book queries:
spread,microprice,queue_ahead,volume_at,get_order,check_invariants. - Simulator: order-entry latency per strategy, strategy timers,
on_start/on_fill/on_reporthooks, unique-name validation,schedule_snapshots, mid-price path, and inventory series. - Closed-loop market agents:
FundamentalValue,NoiseTrader(zero-intelligence),InformedTrader;build_market()scenario. AvellanedaStoikovMarketMaker(finite and rolling horizon) and theTwoSidedQuoterbase class.- Analytics: markouts, PnL statistics (drawdown, Sharpe), inventory statistics,
strategy_report,format_table. - Maker/taker fee schedule in
Portfolio. - Tests: model-based differential testing against a reference book (Hypothesis), property tests for PnL accounting, zero-sum and determinism checks (38 → 121 tests).
- Tooling: hatchling build, ruff, mypy
--strict, coverage, and GitHub Actions CI on Python 3.10–3.13.
Changed (breaking)¶
LimitOrderBook.modify()returns anExecutionReportinstead ofbool; use.accepted.- Market orders are
Order.market(...)/order_type=OrderType.MARKET. Thesetattr(order, "_is_market", True)hack no longer works (Orderuses slots). place_limit/place_marketraiseOrderRejectedwhen the book refuses an order.FillandExecutionReportareNamedTuples. Construction is about 2× faster than frozen dataclasses on the matching hot path.Portfolio.fee_per_shareis replaced bymaker_fee/taker_fee;mark_to_marketis now net of fees.MarketMaker.tick_sizeandAdaptiveMMConfig.tick_sizedefault to the book's tick (was1.0).- Market makers are post-only and never quote through the opposite touch; unchanged quotes keep their queue priority.
- Spread capture is measured against the pre-trade mid (was the post-trade mid).
MarketSimulator()with no book now uses self-trade prevention (CANCEL_RESTING).MarketSimulator.run()accumulates intosim.resultacross calls.Strategy.on_fills(an unused stub) is replaced byon_fill;_next_tsis replaced bynext_order_id.- Removed
microbook.sim.runner(useMarketSimulator.schedule_snapshots) and the emptymicrobook.matching. - Examples and benchmarks moved out of the installed package into
examples/andbenchmarks/.
Performance¶
On a realistic message mix (55% adds, 35% cancels, 10% aggressive), Apple M2, Python 3.12: throughput 139k → 484k msg/s; cancel p50 13.8 µs → 0.5 µs.