matching-engine 0.1.0__tar.gz

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.
Files changed (78) hide show
  1. matching_engine-0.1.0/.dockerignore +11 -0
  2. matching_engine-0.1.0/.gitattributes +2 -0
  3. matching_engine-0.1.0/.github/dependabot.yml +26 -0
  4. matching_engine-0.1.0/.github/workflows/ci.yml +43 -0
  5. matching_engine-0.1.0/.github/workflows/release.yml +60 -0
  6. matching_engine-0.1.0/.gitignore +29 -0
  7. matching_engine-0.1.0/.python-version +1 -0
  8. matching_engine-0.1.0/CHANGELOG.md +39 -0
  9. matching_engine-0.1.0/CONTRIBUTING.md +42 -0
  10. matching_engine-0.1.0/Dockerfile +26 -0
  11. matching_engine-0.1.0/LICENSE +21 -0
  12. matching_engine-0.1.0/Makefile +44 -0
  13. matching_engine-0.1.0/PKG-INFO +307 -0
  14. matching_engine-0.1.0/README.md +280 -0
  15. matching_engine-0.1.0/SECURITY.md +32 -0
  16. matching_engine-0.1.0/bench/_common.py +45 -0
  17. matching_engine-0.1.0/bench/bench_engine.py +79 -0
  18. matching_engine-0.1.0/bench/bench_gateway.py +164 -0
  19. matching_engine-0.1.0/bench/bench_recovery.py +105 -0
  20. matching_engine-0.1.0/docker-compose.yml +17 -0
  21. matching_engine-0.1.0/docs/adr/0001-single-threaded-engine-per-market.md +53 -0
  22. matching_engine-0.1.0/docs/adr/0002-wal-format-and-fsync-policy.md +99 -0
  23. matching_engine-0.1.0/docs/adr/0003-integer-ticks-and-lots.md +43 -0
  24. matching_engine-0.1.0/docs/adr/0004-python-first-with-a-rust-path.md +46 -0
  25. matching_engine-0.1.0/pyproject.toml +88 -0
  26. matching_engine-0.1.0/requirements.txt +44 -0
  27. matching_engine-0.1.0/src/matching_engine/__init__.py +26 -0
  28. matching_engine-0.1.0/src/matching_engine/__main__.py +5 -0
  29. matching_engine-0.1.0/src/matching_engine/book.py +221 -0
  30. matching_engine-0.1.0/src/matching_engine/cli.py +73 -0
  31. matching_engine-0.1.0/src/matching_engine/domain.py +81 -0
  32. matching_engine-0.1.0/src/matching_engine/engine.py +271 -0
  33. matching_engine-0.1.0/src/matching_engine/events.py +81 -0
  34. matching_engine-0.1.0/src/matching_engine/gateway/__init__.py +6 -0
  35. matching_engine-0.1.0/src/matching_engine/gateway/app.py +221 -0
  36. matching_engine-0.1.0/src/matching_engine/gateway/config.py +43 -0
  37. matching_engine-0.1.0/src/matching_engine/gateway/marketdata.py +104 -0
  38. matching_engine-0.1.0/src/matching_engine/gateway/schemas.py +151 -0
  39. matching_engine-0.1.0/src/matching_engine/gateway/worker.py +176 -0
  40. matching_engine-0.1.0/src/matching_engine/journal.py +187 -0
  41. matching_engine-0.1.0/src/matching_engine/market.py +54 -0
  42. matching_engine-0.1.0/src/matching_engine/py.typed +0 -0
  43. matching_engine-0.1.0/src/matching_engine/sequencer.py +41 -0
  44. matching_engine-0.1.0/src/matching_engine/snapshot.py +75 -0
  45. matching_engine-0.1.0/src/matching_engine/wal.py +258 -0
  46. matching_engine-0.1.0/src/matching_engine/workload.py +62 -0
  47. matching_engine-0.1.0/tests/conftest.py +26 -0
  48. matching_engine-0.1.0/tests/crash_writer.py +39 -0
  49. matching_engine-0.1.0/tests/golden/cancel_after_partial_fill.json +25 -0
  50. matching_engine-0.1.0/tests/golden/cancel_rejections.json +28 -0
  51. matching_engine-0.1.0/tests/golden/fok_reject_then_fill.json +26 -0
  52. matching_engine-0.1.0/tests/golden/ioc_partial_then_cancel.json +22 -0
  53. matching_engine-0.1.0/tests/golden/market_order_partial_then_cancel.json +23 -0
  54. matching_engine-0.1.0/tests/golden/partial_fill_rests_remainder.json +17 -0
  55. matching_engine-0.1.0/tests/golden/post_only_reject_and_rest.json +20 -0
  56. matching_engine-0.1.0/tests/golden/stp_cancel_both.json +22 -0
  57. matching_engine-0.1.0/tests/golden/stp_cancel_maker.json +22 -0
  58. matching_engine-0.1.0/tests/golden/stp_cancel_taker.json +22 -0
  59. matching_engine-0.1.0/tests/golden/sweep_levels_with_price_improvement.json +26 -0
  60. matching_engine-0.1.0/tests/golden/time_priority_at_one_price.json +27 -0
  61. matching_engine-0.1.0/tests/golden/validation_rejects.json +32 -0
  62. matching_engine-0.1.0/tests/helpers.py +48 -0
  63. matching_engine-0.1.0/tests/test_book.py +86 -0
  64. matching_engine-0.1.0/tests/test_cli.py +35 -0
  65. matching_engine-0.1.0/tests/test_crash.py +54 -0
  66. matching_engine-0.1.0/tests/test_domain.py +22 -0
  67. matching_engine-0.1.0/tests/test_gateway.py +221 -0
  68. matching_engine-0.1.0/tests/test_golden.py +74 -0
  69. matching_engine-0.1.0/tests/test_market.py +39 -0
  70. matching_engine-0.1.0/tests/test_marketdata.py +104 -0
  71. matching_engine-0.1.0/tests/test_matching.py +148 -0
  72. matching_engine-0.1.0/tests/test_properties.py +141 -0
  73. matching_engine-0.1.0/tests/test_protections.py +128 -0
  74. matching_engine-0.1.0/tests/test_recovery.py +214 -0
  75. matching_engine-0.1.0/tests/test_sequencer.py +25 -0
  76. matching_engine-0.1.0/tests/test_time_in_force.py +93 -0
  77. matching_engine-0.1.0/tests/test_wal.py +178 -0
  78. matching_engine-0.1.0/uv.lock +940 -0
@@ -0,0 +1,11 @@
1
+ .git
2
+ .venv
3
+ data
4
+ docs
5
+ bench
6
+ tests
7
+ **/__pycache__
8
+ .mypy_cache
9
+ .pytest_cache
10
+ .ruff_cache
11
+ .hypothesis
@@ -0,0 +1,2 @@
1
+ * text=auto eol=lf
2
+ *.bin binary
@@ -0,0 +1,26 @@
1
+ # Actions first: an unpinned or abandoned action is the most direct route into
2
+ # a pipeline that can execute code in this repository.
3
+ version: 2
4
+ updates:
5
+ - package-ecosystem: github-actions
6
+ directory: "/"
7
+ schedule:
8
+ interval: weekly
9
+ groups:
10
+ actions:
11
+ patterns: ["*"]
12
+
13
+ # uv.lock and pyproject.toml. After a bump, regenerate requirements.txt
14
+ # with `make requirements` so CI audits the same pins.
15
+ - package-ecosystem: uv
16
+ directory: "/"
17
+ schedule:
18
+ interval: weekly
19
+ groups:
20
+ python-minor:
21
+ update-types: [minor, patch]
22
+
23
+ - package-ecosystem: docker
24
+ directory: "/"
25
+ schedule:
26
+ interval: weekly
@@ -0,0 +1,43 @@
1
+ # The gate in front of main. The checks themselves live in
2
+ # CtrlAltDevelop/ci-workflows, so every project runs the same ones.
3
+ name: CI
4
+
5
+ on:
6
+ pull_request:
7
+ branches: [main]
8
+ push:
9
+ branches: [main]
10
+
11
+ concurrency:
12
+ group: ci-${{ github.ref }}
13
+ cancel-in-progress: true
14
+
15
+ permissions: {}
16
+
17
+ jobs:
18
+ backend:
19
+ name: Backend
20
+ uses: CtrlAltDevelop/ci-workflows/.github/workflows/python-backend.yml@v1.1.1
21
+ permissions:
22
+ contents: read
23
+ with:
24
+ python-version: "3.14"
25
+ # Runtime pins from `make requirements` (uv export). The project itself
26
+ # is installed below, not listed there, so pip-audit only audits what
27
+ # comes from PyPI.
28
+ requirements: requirements.txt
29
+ # The engine keeps its state in files: no database, no cache.
30
+ postgres: false
31
+ redis: false
32
+ mypy: true
33
+ test-requirements: "pytest hypothesis httpx2 sortedcontainers-stubs -e ."
34
+
35
+ security:
36
+ name: Security
37
+ uses: CtrlAltDevelop/ci-workflows/.github/workflows/security.yml@v1.1.1
38
+ permissions:
39
+ contents: read
40
+ security-events: write
41
+ pull-requests: write
42
+ with:
43
+ languages: '["python"]'
@@ -0,0 +1,60 @@
1
+ # =============================================================================
2
+ # Release: build once, publish to PyPI with trusted publishing.
3
+ # =============================================================================
4
+ # Runs on a version tag. No API token exists anywhere: PyPI trusts this
5
+ # workflow's OIDC identity, configured once under the project's "Publishing"
6
+ # settings (owner CtrlAltDevelop, repo matching-engine, workflow release.yml,
7
+ # environment pypi).
8
+
9
+ name: Release
10
+
11
+ on:
12
+ push:
13
+ tags: ["v*"]
14
+
15
+ permissions: {}
16
+
17
+ jobs:
18
+ build:
19
+ name: Build
20
+ runs-on: ubuntu-latest
21
+ timeout-minutes: 10
22
+ permissions:
23
+ contents: read
24
+ steps:
25
+ - uses: actions/checkout@v7
26
+ with:
27
+ persist-credentials: false
28
+ - uses: astral-sh/setup-uv@v7
29
+ with:
30
+ python-version: "3.13"
31
+ - name: Tag matches the package version
32
+ run: |
33
+ version=$(uv version --short)
34
+ if [ "v$version" != "$GITHUB_REF_NAME" ]; then
35
+ echo "::error::Tag $GITHUB_REF_NAME does not match version $version in pyproject.toml"
36
+ exit 1
37
+ fi
38
+ - run: uv build
39
+ - uses: actions/upload-artifact@v5
40
+ with:
41
+ name: dist
42
+ path: dist/
43
+ if-no-files-found: error
44
+
45
+ publish:
46
+ name: Publish to PyPI
47
+ needs: build
48
+ runs-on: ubuntu-latest
49
+ timeout-minutes: 10
50
+ environment:
51
+ name: pypi
52
+ url: https://pypi.org/project/matching-engine/
53
+ permissions:
54
+ id-token: write # the OIDC token PyPI exchanges for a short-lived upload credential
55
+ steps:
56
+ - uses: actions/download-artifact@v6
57
+ with:
58
+ name: dist
59
+ path: dist/
60
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,29 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .venv/
8
+
9
+ # Tooling caches
10
+ .mypy_cache/
11
+ .pytest_cache/
12
+ .ruff_cache/
13
+ .hypothesis/
14
+ .coverage
15
+ htmlcov/
16
+
17
+ # Engine state: WAL segments and snapshots are runtime data, never source
18
+ data/
19
+ *.wal
20
+ *.log
21
+ *.snap
22
+ profile.*
23
+ *.svg
24
+
25
+ # Editors / OS
26
+ .idea/
27
+ .vscode/
28
+ .DS_Store
29
+ Thumbs.db
@@ -0,0 +1 @@
1
+ 3.14
@@ -0,0 +1,39 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html). For this project
6
+ the WAL and snapshot formats are part of the public interface: a release that
7
+ cannot read the previous release's files is a major version.
8
+
9
+ ## [Unreleased]
10
+
11
+ ## [0.1.0] — 2026-09-29
12
+
13
+ ### Added
14
+
15
+ - Price-time priority order book: sorted price levels of intrusive FIFO
16
+ queues, O(1) cancel through an order-id index, integer ticks and lots.
17
+ - Limit and market orders; GTC, IOC and FOK; post-only; self-trade
18
+ prevention (cancel taker, cancel maker, cancel both, or allow); owner-only
19
+ cancels.
20
+ - An ordered event stream per command: `OrderAccepted`, `Trade`,
21
+ `OrderCancelled`, `OrderRejected`, each carrying the command's `seq`/`ts`.
22
+ - A sequencer that is the only source of time and ordering, so the engine is
23
+ deterministic and `state_hash()` identifies a book exactly.
24
+ - Write-ahead log: length-framed records with a CRC32 over length and
25
+ payload, group commit with one fsync per batch, torn-tail detection and
26
+ repair, refusal to "repair" corruption that is followed by valid records.
27
+ - Snapshots written atomically and verified by state hash on load; recovery
28
+ from the newest valid snapshot with fallback to older ones; segment rolling
29
+ and retention.
30
+ - FastAPI gateway: REST order entry and cancel, L2 depth, L3 book, health;
31
+ one sequenced worker per market; 503 instead of unbounded queueing.
32
+ - WebSocket market data: depth snapshot on connect, then trades and depth
33
+ changes; slow subscribers are dropped instead of slowing the market.
34
+ - `matching-engine verify` to inspect a market directory without changing it.
35
+ - Golden, property-based, replay, crash (killed subprocess) and gateway tests;
36
+ engine, recovery and end-to-end benchmarks.
37
+
38
+ [Unreleased]: https://github.com/CtrlAltDevelop/matching-engine/compare/v0.1.0...HEAD
39
+ [0.1.0]: https://github.com/CtrlAltDevelop/matching-engine/releases/tag/v0.1.0
@@ -0,0 +1,42 @@
1
+ # Contributing
2
+
3
+ ## Setup
4
+
5
+ ```bash
6
+ uv sync --all-extras # or: make install
7
+ make check # ruff, ruff format --check, mypy --strict, pytest
8
+ ```
9
+
10
+ Python 3.12 or newer. CI runs on 3.14.
11
+
12
+ ## Rules of the house
13
+
14
+ - **The engine stays deterministic.** No clock, randomness, I/O or
15
+ threading inside `engine.py` or `book.py`. Time and ordering come from the
16
+ sequencer. If a change needs the time, it goes on the command, stamped
17
+ before it is logged.
18
+ - **No floats or `Decimal` past the gateway.** Prices are ticks, quantities
19
+ are lots, both `int`.
20
+ - **The WAL format is append-only.** New record kinds and new enum members
21
+ may be added at the end; existing codes and layouts never change, or old
22
+ logs stop replaying. A format change that cannot follow this rule bumps the
23
+ segment magic and ships a reader for the old one.
24
+ - **Behaviour changes update the golden files on purpose.** Run
25
+ `UPDATE_GOLDEN=1 uv run pytest tests/test_golden.py` and review the diff
26
+ line by line, as you would code. A golden diff nobody can explain is a bug.
27
+ - **Benchmark numbers are measured, never estimated.** If a change affects
28
+ performance, rerun `make bench-full` and update the README table with the
29
+ machine it ran on.
30
+ - Typed code (`mypy --strict` passes), focused modules, tests next to the
31
+ behaviour they pin.
32
+
33
+ ## Commits
34
+
35
+ [Conventional Commits](https://www.conventionalcommits.org/), short and in the
36
+ imperative: `fix: reject a post-only order that would cross`. One coherent
37
+ change per commit, each one passing `make check`.
38
+
39
+ ## Architecture decisions
40
+
41
+ Significant design changes get an ADR in `docs/adr/`, numbered in sequence.
42
+ Say what problem it solves, what was decided, and what it costs.
@@ -0,0 +1,26 @@
1
+ # syntax=docker/dockerfile:1
2
+ FROM python:3.14-slim AS build
3
+ COPY --from=ghcr.io/astral-sh/uv:0.12 /uv /usr/local/bin/uv
4
+ WORKDIR /app
5
+ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
6
+ # Dependencies first, so a source change does not reinstall them.
7
+ COPY pyproject.toml uv.lock README.md LICENSE ./
8
+ RUN uv sync --frozen --no-dev --extra gateway --no-install-project
9
+ COPY src ./src
10
+ RUN uv sync --frozen --no-dev --extra gateway --no-editable
11
+
12
+ FROM python:3.14-slim
13
+ RUN useradd --system --uid 10001 --home-dir /nonexistent engine \
14
+ && mkdir /data && chown engine /data
15
+ COPY --from=build /app/.venv /app/.venv
16
+ ENV PATH=/app/.venv/bin:$PATH \
17
+ PYTHONUNBUFFERED=1 \
18
+ ME_DATA_DIR=/data
19
+ USER engine
20
+ VOLUME ["/data"]
21
+ EXPOSE 8000
22
+ HEALTHCHECK --interval=10s --timeout=3s \
23
+ CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz')"]
24
+ # SIGTERM lets each market finish its queue, checkpoint and close its log.
25
+ STOPSIGNAL SIGTERM
26
+ CMD ["matching-engine", "serve", "--host", "0.0.0.0", "--port", "8000"]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mohammad Zarif
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.
@@ -0,0 +1,44 @@
1
+ .PHONY: install lint format typecheck test test-fast check bench bench-full requirements serve docker profile
2
+
3
+ install: ## Create .venv with every extra and the dev tools
4
+ uv sync --all-extras
5
+
6
+ lint:
7
+ uv run ruff check .
8
+ uv run ruff format --check .
9
+
10
+ format:
11
+ uv run ruff check --fix .
12
+ uv run ruff format .
13
+
14
+ typecheck:
15
+ uv run mypy
16
+
17
+ test:
18
+ uv run pytest
19
+
20
+ test-fast: ## Skip the subprocess crash test
21
+ uv run pytest -m "not slow"
22
+
23
+ check: lint typecheck test ## Everything CI runs, locally
24
+
25
+ bench: ## Quick benchmark pass
26
+ uv run python bench/bench_engine.py --orders 200000
27
+ uv run python bench/bench_recovery.py --events 200000 --tail 20000
28
+
29
+ bench-full: ## The numbers published in the README
30
+ uv run python bench/bench_engine.py --orders 1000000 --runs 3
31
+ uv run python bench/bench_recovery.py --events 1000000 --tail 100000
32
+ uv run python bench/bench_gateway.py
33
+
34
+ profile: ## cProfile the engine benchmark; open profile.pstats with snakeviz or similar
35
+ uv run python -m cProfile -o profile.pstats bench/bench_engine.py --orders 200000 --runs 1
36
+
37
+ requirements: ## Regenerate the pinned runtime requirements CI installs and audits
38
+ uv export --no-dev --all-extras --no-hashes --no-emit-project --format requirements-txt -o requirements.txt
39
+
40
+ serve:
41
+ uv run matching-engine serve
42
+
43
+ docker:
44
+ docker compose up --build
@@ -0,0 +1,307 @@
1
+ Metadata-Version: 2.5
2
+ Name: matching-engine
3
+ Version: 0.1.0
4
+ Summary: A deterministic price-time priority matching engine with a checksummed write-ahead log, snapshots and a FastAPI gateway.
5
+ Author: Mohammad Zarif
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: exchange,matching-engine,order-book,trading,write-ahead-log
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Topic :: Office/Business :: Financial :: Investment
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: msgspec>=0.19
20
+ Requires-Dist: sortedcontainers>=2.4
21
+ Provides-Extra: gateway
22
+ Requires-Dist: fastapi>=0.115; extra == 'gateway'
23
+ Requires-Dist: httptools>=0.6; extra == 'gateway'
24
+ Requires-Dist: uvicorn>=0.30; extra == 'gateway'
25
+ Requires-Dist: websockets>=13; extra == 'gateway'
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Matching Engine
29
+
30
+ A price-time priority order book that matches deterministically, survives a
31
+ crash with every acknowledged order intact, and publishes measured numbers
32
+ rather than claimed ones.
33
+
34
+ - **Deterministic:** no clock or randomness inside the engine. The same log
35
+ always rebuilds the same book, down to queue position, checked by a state
36
+ hash.
37
+ - **Durable:** checksummed, length-framed write-ahead log with group commit;
38
+ torn writes are detected and cut off, corruption is refused, snapshots
39
+ bound replay time.
40
+ - **Exact:** integer ticks and lots from the gateway inwards; decimals only
41
+ on the wire, as strings.
42
+ - **Tested the way it can fail:** golden files, property-based invariants,
43
+ replay determinism, and a real process killed mid-load.
44
+
45
+ Pure, typed Python (3.12+, `mypy --strict`), with the engine boundary drawn so
46
+ a Rust/PyO3 core can replace it later ([ADR 4](docs/adr/0004-python-first-with-a-rust-path.md)).
47
+
48
+ ## Architecture
49
+
50
+ ```mermaid
51
+ flowchart LR
52
+ C[Clients] -- "REST: place / cancel" --> G[Gateway<br/>FastAPI]
53
+ C <-- "WebSocket: trades, L2" --- MD
54
+ G -- "per-market queue<br/>(bounded, 503 when full)" --> W
55
+
56
+ subgraph W["Market worker (one per market, one thread of control)"]
57
+ S[Sequencer<br/>seq + ts] --> J[(WAL segment<br/>group commit)]
58
+ J -- "after fsync" --> E[Matching engine<br/>pure, deterministic]
59
+ E --> EV[Events]
60
+ end
61
+
62
+ EV -- "response to caller" --> G
63
+ EV --> MD[Market-data hub<br/>bounded queue per subscriber]
64
+ E -. "checkpoint" .-> SN[(Snapshots)]
65
+ SN -. "recover: newest valid snapshot" .-> E
66
+ J -. "recover: replay the tail" .-> E
67
+ ```
68
+
69
+ Each market has its own worker, sequencer, WAL, snapshots and book; markets
70
+ share nothing ([ADR 1](docs/adr/0001-single-threaded-engine-per-market.md)).
71
+
72
+ ### One order, end to end
73
+
74
+ ```mermaid
75
+ sequenceDiagram
76
+ participant Client
77
+ participant Gateway
78
+ participant Worker as Market worker
79
+ participant WAL
80
+ participant Engine
81
+ participant Feed as WS subscribers
82
+
83
+ Client->>Gateway: POST /markets/BTC-USDT/orders {"price": "64250.50", ...}
84
+ Gateway->>Gateway: decimal to ticks/lots (off-grid is a 422)
85
+ Gateway->>Worker: enqueue
86
+ Worker->>Worker: drain up to batch_max requests
87
+ Worker->>Worker: stamp seq + ts (order id = seq)
88
+ Worker->>WAL: append the batch, then ONE fsync
89
+ WAL-->>Worker: durable
90
+ Worker->>Engine: process(seq, ts, command) for each
91
+ Engine-->>Worker: OrderAccepted, Trade..., OrderCancelled
92
+ Worker-->>Gateway: events for this order
93
+ Gateway-->>Client: 200 {status, filled_quantity, events}
94
+ Worker-)Feed: trades, then L2 depth if it changed
95
+ ```
96
+
97
+ Nothing is acknowledged before it is on disk. While one fsync runs, the next
98
+ batch queues up behind it, so batches grow with load and no timer is needed
99
+ ([ADR 2](docs/adr/0002-wal-format-and-fsync-policy.md)).
100
+
101
+ ## Order book
102
+
103
+ Each side is a `SortedList` of price keys plus `dict[key, PriceLevel]`; each
104
+ level is an intrusive doubly linked FIFO of orders; the book keeps
105
+ `dict[order_id, node]`. Bid keys are negated prices, so on both sides
106
+ `keys[0]` is the best level and "crosses the limit" is one comparison.
107
+
108
+ | Operation | Complexity |
109
+ |---|---|
110
+ | Add at an existing price level | O(1) |
111
+ | Add at a new price level | O(log L) |
112
+ | Cancel (level stays non-empty) | O(1) |
113
+ | Cancel (last order at its level) | O(log L) |
114
+ | Best bid / ask | O(1) |
115
+ | Fill against the head of the best level | O(1) per fill |
116
+ | L2 depth, top *n* levels | O(n) |
117
+ | FOK fillability check | O(levels crossed), no mutation |
118
+
119
+ *L* is the number of distinct price levels on one side. A `deque` per level
120
+ would make cancel O(n) in the queue length; the linked list with an id index
121
+ is what makes it O(1).
122
+
123
+ ## Order types and rules
124
+
125
+ | Feature | Behaviour |
126
+ |---|---|
127
+ | Limit | Matches at the resting price (price improvement for the taker); the remainder rests if GTC |
128
+ | Market | Sweeps the book; must be IOC or FOK, since a market order has no price to rest at |
129
+ | GTC / IOC / FOK | Rest / cancel the unfilled part / fill completely or reject with no trades |
130
+ | Post-only | Rejected if it would take liquidity; must be GTC |
131
+ | Self-trade prevention | `cancel_taker` (default), `cancel_maker`, `cancel_both`, or `none` |
132
+ | Cancel | Owner only; cancelling a filled or unknown order is rejected |
133
+
134
+ Every command produces an ordered list of events — `order_accepted`, `trade`,
135
+ `order_cancelled` (reason `user`, `unfilled` or `self_trade`),
136
+ `order_rejected` (with a reason) — each carrying the command's `seq` and `ts`.
137
+
138
+ ## Quickstart
139
+
140
+ ```bash
141
+ uv sync --all-extras
142
+ uv run matching-engine serve # http://127.0.0.1:8000/docs
143
+ ```
144
+
145
+ ```bash
146
+ # rest a sell, then take part of it with a market buy
147
+ curl -s localhost:8000/markets/BTC-USDT/orders -H 'content-type: application/json' \
148
+ -d '{"account": 2, "side": "sell", "price": "64000.50", "quantity": "0.5"}'
149
+ curl -s localhost:8000/markets/BTC-USDT/orders -H 'content-type: application/json' \
150
+ -d '{"account": 1, "side": "buy", "type": "market", "quantity": "0.2"}'
151
+
152
+ curl -s localhost:8000/markets/BTC-USDT/depth # L2
153
+ curl -s localhost:8000/markets/BTC-USDT/book # L3
154
+ curl -s -X DELETE 'localhost:8000/markets/BTC-USDT/orders/1?account=2'
155
+ # live feed: ws://localhost:8000/markets/BTC-USDT/ws
156
+ ```
157
+
158
+ Or with Docker: `docker compose up --build`. State lives in the
159
+ `engine-data` volume.
160
+
161
+ To inspect a market's files without changing them (after a crash, say):
162
+
163
+ ```bash
164
+ uv run matching-engine verify data/BTC-USDT
165
+ ```
166
+
167
+ It prints the snapshot used, the records replayed, any torn tail found, and
168
+ the state hash.
169
+
170
+ ### Configuration
171
+
172
+ | Variable | Default | Meaning |
173
+ |---|---|---|
174
+ | `ME_DATA_DIR` | `data` | One subdirectory per market: `wal/`, `snapshots/` |
175
+ | `ME_MARKETS` | `BTC-USDT:0.01:0.00001,ETH-USDT:0.01:0.0001` | `SYMBOL:TICK:LOT`, comma-separated |
176
+ | `ME_FSYNC` | `1` | `0` leaves flushing to the OS (ADR 2 says what that risks) |
177
+ | `ME_BATCH_MAX` | `512` | Commands per group commit |
178
+ | `ME_QUEUE_MAX` | `10000` | Pending commands per market before 503 |
179
+ | `ME_SNAPSHOT_EVERY` | `100000` | Commands between checkpoints |
180
+ | `ME_DEPTH_LEVELS` | `20` | L2 levels pushed over WebSocket |
181
+ | `ME_SUBSCRIBER_QUEUE` | `1000` | Messages buffered per subscriber before it is dropped |
182
+
183
+ ## Tests
184
+
185
+ ```bash
186
+ make check # ruff, ruff format --check, mypy --strict, pytest
187
+ ```
188
+
189
+ | Suite | What it proves |
190
+ |---|---|
191
+ | `test_golden.py` + `tests/golden/*.json` | Exact event streams for partial fills, level sweeps, time priority, market and IOC remainders, FOK reject then fill, cancel after partial, cancel rejections, post-only, all three STP modes, validation |
192
+ | `test_properties.py` (Hypothesis) | After any random flow: the book is never crossed, levels and index agree, every accepted lot is filled, cancelled or still resting, no fill is worse than the taker's limit, and export/restore mid-flow changes nothing |
193
+ | `test_recovery.py` | The same WAL twice gives the same state hash; a truncated or corrupted last record is dropped and repaired; mid-log corruption and missing segments are refused; snapshot fallback; segment rolling and pruning |
194
+ | `test_crash.py` | A real writer process is killed (`TerminateProcess`/`SIGKILL`) mid-load; every acknowledged seq is recovered and the state matches an in-memory replay |
195
+ | `test_gateway.py`, `test_marketdata.py` | REST contract, decimal handling, 422s, owner-only cancel, a restart resumes book and sequence, concurrent orders get unique seqs, a full queue gives 503, WebSocket snapshot then trades and depth, a slow subscriber is dropped |
196
+
197
+ ## Benchmarks
198
+
199
+ Measured, not estimated. Machine: **Windows 11 (build 28000), Intel Core
200
+ i7-7700HQ @ 2.80 GHz (4 cores / 8 threads, laptop), 32 GB RAM, SATA SSD,
201
+ CPython 3.14.7**. Workload: `matching_engine.workload.order_flow(seed=42)`:
202
+ 25% cancels, 5% market orders, the rest limit orders within 50 ticks of mid,
203
+ about 1 in 10 crossing. This laptop's results vary a lot between runs
204
+ (thermal throttling, background load), so two separate sessions are shown
205
+ and every figure is the median of several runs with its range.
206
+
207
+ **Engine, in-process** (`bench/bench_engine.py --orders 1000000`), 1M
208
+ commands, 189,443 trades, 411,172 orders resting at the end:
209
+
210
+ | | Session 1 | Session 2 |
211
+ |---|---|---|
212
+ | Throughput | 195,906–241,845 cmd/s (3 runs) | median 206,717 cmd/s (185,755–227,466, 5 runs) |
213
+ | Latency p50 | 3.1 µs | 4.6 µs |
214
+ | Latency p99 | 21.5 µs | 26.6 µs |
215
+ | Latency p99.9 | 45.1 µs | 104.4 µs |
216
+
217
+ **Recovery** (`bench/bench_recovery.py --events 1000000`), 56.0 MB of WAL,
218
+ 7.1 MB snapshot. Recovery includes reading, checking every CRC and sequence
219
+ number, decoding and re-running the engine:
220
+
221
+ | | Session 1 (1 run) | Session 2 (median of 3, range) |
222
+ |---|---|---|
223
+ | Full replay, 1M records, no snapshot | 12.27 s | 21.56 s (12.04–22.47) |
224
+ | Snapshot at 900k + 100k-record tail | 3.31 s | 4.32 s (3.82–6.02) |
225
+
226
+ A separate spot check on an idle machine gave 6.9 s and 1.9 s, which shows
227
+ how much of the spread is the machine. The snapshot path is consistently
228
+ 3–5× faster.
229
+
230
+ **WAL group commit** (append + `fsync` every *n* records):
231
+
232
+ | fsync every | Session 1 | Session 2 |
233
+ |---|---|---|
234
+ | 1 record | 906 rec/s | 741 rec/s |
235
+ | 64 records | 47,818 rec/s | 5,430 rec/s |
236
+ | 512 records | 171,843 rec/s | 80,938 rec/s |
237
+
238
+ **End to end over HTTP** (`bench/bench_gateway.py`: real uvicorn +
239
+ httptools on loopback, 2,000 sequential orders, then 20,000 orders from 64
240
+ connections spread over 4 client processes on the same machine):
241
+
242
+ | | 1 client p50 | p99 | p99.9 | 64 clients |
243
+ |---|---|---|---|---|
244
+ | fsync on | 3.8 ms | 7.1 ms | 10.0 ms | 894 orders/s |
245
+ | fsync off | 1.9 ms | 3.3 ms | 5.3 ms | 1,320 orders/s |
246
+
247
+ The engine does an order in microseconds; the gateway takes milliseconds. A
248
+ bare ASGI "hello" app measured about 1.3 ms per round trip on this machine, so
249
+ the HTTP stack (and the load generator sharing the CPU) is the ceiling, not
250
+ matching or the WAL. With fsync on, group commit keeps throughput within
251
+ about a third of fsync off. The next step is a binary protocol or a
252
+ process per market, not a faster book.
253
+
254
+ ### Profiling
255
+
256
+ ```bash
257
+ make profile # cProfile -> profile.pstats
258
+ uv tool run snakeviz profile.pstats # browse it
259
+ # flamegraph (Linux/macOS, or Windows as admin):
260
+ uv tool run py-spy record -o flame.svg -- python bench/bench_engine.py --orders 200000 --runs 1
261
+ ```
262
+
263
+ ## Roadmap
264
+
265
+ - **Rust core via PyO3.** Replace `engine.py`/`book.py` behind the same
266
+ boundary (`process`, `export_state`, `restore`, `state_hash`), then publish
267
+ both sets of numbers side by side. The golden, property and replay suites
268
+ become the acceptance tests: same WAL in, same events and hash out.
269
+ - **A process per market**, fed over a ring buffer or shared-memory queue, so
270
+ markets stop sharing one GIL (or run on a free-threaded interpreter).
271
+ - **Client order ids** for idempotent retries after a timeout.
272
+ - **Stop and stop-limit orders**, and amend (price/quantity) with defined
273
+ priority rules.
274
+ - **Ledger integration:** place a hold before sequencing and settle on
275
+ `trade` events, so an account cannot trade funds it does not have.
276
+ - **Replication:** acknowledge once a follower has the WAL record, to take
277
+ the fsync out of the latency path without losing durability.
278
+ - **Incremental L2/L3 feed** with sequence numbers for gap detection, instead
279
+ of full depth snapshots.
280
+
281
+ ## Known limitations
282
+
283
+ - **No authentication, risk checks or balances**; see [SECURITY.md](SECURITY.md).
284
+ The `account` field is trusted as sent.
285
+ - **All markets share one Python process and GIL.** They share no state, so
286
+ this limits aggregate throughput, not correctness.
287
+ - **Throughput is bounded by the HTTP stack**, not the engine; see the
288
+ benchmarks.
289
+ - **Order ids are only checked for uniqueness among live orders** inside the
290
+ engine; the gateway makes them globally unique by using the sequence number.
291
+ - **Tick and lot size are fixed per market**; changing them would
292
+ reinterpret stored orders.
293
+ - **Depth over WebSocket is a full top-*n* snapshot per change**: simple and
294
+ impossible to drift, but heavier than deltas.
295
+ - **A checkpoint pauses its market while the snapshot is encoded**; only the
296
+ file write runs off-thread.
297
+
298
+ ## Architecture decisions
299
+
300
+ 1. [One single-threaded engine per market](docs/adr/0001-single-threaded-engine-per-market.md)
301
+ 2. [WAL format, group commit and what a crash can lose](docs/adr/0002-wal-format-and-fsync-policy.md)
302
+ 3. [Integer ticks and lots instead of floats or Decimal](docs/adr/0003-integer-ticks-and-lots.md)
303
+ 4. [Python first, with a clean path to a Rust core](docs/adr/0004-python-first-with-a-rust-path.md)
304
+
305
+ ## License
306
+
307
+ [MIT](LICENSE) © 2026 Mohammad Zarif