matching-engine 0.1.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.
- matching_engine/__init__.py +26 -0
- matching_engine/__main__.py +5 -0
- matching_engine/book.py +221 -0
- matching_engine/cli.py +73 -0
- matching_engine/domain.py +81 -0
- matching_engine/engine.py +271 -0
- matching_engine/events.py +81 -0
- matching_engine/gateway/__init__.py +6 -0
- matching_engine/gateway/app.py +221 -0
- matching_engine/gateway/config.py +43 -0
- matching_engine/gateway/marketdata.py +104 -0
- matching_engine/gateway/schemas.py +151 -0
- matching_engine/gateway/worker.py +176 -0
- matching_engine/journal.py +187 -0
- matching_engine/market.py +54 -0
- matching_engine/py.typed +0 -0
- matching_engine/sequencer.py +41 -0
- matching_engine/snapshot.py +75 -0
- matching_engine/wal.py +258 -0
- matching_engine/workload.py +62 -0
- matching_engine-0.1.0.dist-info/METADATA +307 -0
- matching_engine-0.1.0.dist-info/RECORD +25 -0
- matching_engine-0.1.0.dist-info/WHEEL +4 -0
- matching_engine-0.1.0.dist-info/entry_points.txt +2 -0
- matching_engine-0.1.0.dist-info/licenses/LICENSE +21 -0
matching_engine/wal.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Write-ahead log segments: length-framed, checksummed, fixed-layout records.
|
|
2
|
+
|
|
3
|
+
Segment layout::
|
|
4
|
+
|
|
5
|
+
MAGIC (8 bytes)
|
|
6
|
+
record*
|
|
7
|
+
|
|
8
|
+
record = length:u32 | crc:u32 | payload[length]
|
|
9
|
+
crc = CRC32(length bytes || payload)
|
|
10
|
+
payload = kind:u8 | seq:u64 | ts:i64 | body (little-endian, no padding)
|
|
11
|
+
|
|
12
|
+
The CRC covers the length as well as the payload, so a flipped bit in the
|
|
13
|
+
length field cannot silently re-frame the rest of the file.
|
|
14
|
+
|
|
15
|
+
Recovery rules (see ``docs/adr/0002-wal-format-and-fsync-policy.md``):
|
|
16
|
+
|
|
17
|
+
* A record that runs past end-of-file is a *torn write*: the process died in
|
|
18
|
+
the middle of an append. Everything from that record on is discarded.
|
|
19
|
+
* A checksum failure on the **last** record (nothing but end-of-file or zero
|
|
20
|
+
fill after it) is also a torn write — the sector reached the disk only
|
|
21
|
+
partly.
|
|
22
|
+
* A checksum failure with valid-looking data *after* it is not a crash
|
|
23
|
+
artefact but corruption of acknowledged data. That is never repaired
|
|
24
|
+
silently: :class:`WalCorruptionError` is raised and an operator decides.
|
|
25
|
+
|
|
26
|
+
Writing is batched: :meth:`SegmentWriter.append` only buffers, and
|
|
27
|
+
:meth:`SegmentWriter.sync` issues one ``write`` and one ``fsync`` for the
|
|
28
|
+
whole batch (group commit).
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import os
|
|
34
|
+
import struct
|
|
35
|
+
import zlib
|
|
36
|
+
from collections.abc import Iterator
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
from typing import BinaryIO
|
|
39
|
+
|
|
40
|
+
import msgspec
|
|
41
|
+
|
|
42
|
+
from matching_engine.domain import (
|
|
43
|
+
CancelOrder,
|
|
44
|
+
NewOrder,
|
|
45
|
+
OrderType,
|
|
46
|
+
SelfTradePrevention,
|
|
47
|
+
SequencedCommand,
|
|
48
|
+
Side,
|
|
49
|
+
TimeInForce,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
MAGIC = b"MEWAL01\n"
|
|
53
|
+
|
|
54
|
+
_LENGTH = struct.Struct("<I")
|
|
55
|
+
_FRAME = struct.Struct("<II")
|
|
56
|
+
# kind, seq, ts, order_id, account, side, type, tif | stp << 4, flags, price, qty
|
|
57
|
+
_NEW = struct.Struct("<BQqQQBBBBqq")
|
|
58
|
+
# kind, seq, ts, order_id, account
|
|
59
|
+
_CANCEL = struct.Struct("<BQqQQ")
|
|
60
|
+
_MAX_PAYLOAD = max(_NEW.size, _CANCEL.size)
|
|
61
|
+
|
|
62
|
+
_KIND_NEW = 1
|
|
63
|
+
_KIND_CANCEL = 2
|
|
64
|
+
_FLAG_POST_ONLY = 0x01
|
|
65
|
+
|
|
66
|
+
# Enum <-> byte code tables. Codes are positions in these tuples, so new
|
|
67
|
+
# members may only ever be appended — reordering would reinterpret old logs.
|
|
68
|
+
_SIDES = (Side.BUY, Side.SELL)
|
|
69
|
+
_TYPES = (OrderType.LIMIT, OrderType.MARKET)
|
|
70
|
+
_TIFS = (TimeInForce.GTC, TimeInForce.IOC, TimeInForce.FOK)
|
|
71
|
+
_STPS = (
|
|
72
|
+
SelfTradePrevention.NONE,
|
|
73
|
+
SelfTradePrevention.CANCEL_TAKER,
|
|
74
|
+
SelfTradePrevention.CANCEL_MAKER,
|
|
75
|
+
SelfTradePrevention.CANCEL_BOTH,
|
|
76
|
+
)
|
|
77
|
+
_SIDE_CODE = {m: i for i, m in enumerate(_SIDES)}
|
|
78
|
+
_TYPE_CODE = {m: i for i, m in enumerate(_TYPES)}
|
|
79
|
+
_TIF_CODE = {m: i for i, m in enumerate(_TIFS)}
|
|
80
|
+
_STP_CODE = {m: i for i, m in enumerate(_STPS)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class WalCorruptionError(Exception):
|
|
84
|
+
"""The log is damaged somewhere other than a torn tail. Needs a human."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class TornTail(msgspec.Struct, frozen=True):
|
|
88
|
+
"""An incomplete write at the end of a segment, found during a scan."""
|
|
89
|
+
|
|
90
|
+
offset: int # where the damaged record starts; the valid log ends here
|
|
91
|
+
discarded: int # bytes from ``offset`` to end-of-file
|
|
92
|
+
reason: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def encode(sc: SequencedCommand) -> bytes:
|
|
96
|
+
"""Frame one command as a complete record, header included."""
|
|
97
|
+
cmd = sc.command
|
|
98
|
+
if type(cmd) is NewOrder:
|
|
99
|
+
payload = _NEW.pack(
|
|
100
|
+
_KIND_NEW,
|
|
101
|
+
sc.seq,
|
|
102
|
+
sc.ts,
|
|
103
|
+
cmd.order_id,
|
|
104
|
+
cmd.account,
|
|
105
|
+
_SIDE_CODE[cmd.side],
|
|
106
|
+
_TYPE_CODE[cmd.order_type],
|
|
107
|
+
_TIF_CODE[cmd.tif] | (_STP_CODE[cmd.stp] << 4),
|
|
108
|
+
_FLAG_POST_ONLY if cmd.post_only else 0,
|
|
109
|
+
cmd.price,
|
|
110
|
+
cmd.qty,
|
|
111
|
+
)
|
|
112
|
+
else:
|
|
113
|
+
assert type(cmd) is CancelOrder
|
|
114
|
+
payload = _CANCEL.pack(_KIND_CANCEL, sc.seq, sc.ts, cmd.order_id, cmd.account)
|
|
115
|
+
length = len(payload)
|
|
116
|
+
return _FRAME.pack(length, zlib.crc32(payload, zlib.crc32(_LENGTH.pack(length)))) + payload
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def decode(payload: bytes) -> SequencedCommand:
|
|
120
|
+
kind = payload[0]
|
|
121
|
+
if kind == _KIND_NEW and len(payload) == _NEW.size:
|
|
122
|
+
_, seq, ts, oid, account, side, otype, tif_stp, flags, price, qty = _NEW.unpack(payload)
|
|
123
|
+
command: NewOrder | CancelOrder = NewOrder(
|
|
124
|
+
oid,
|
|
125
|
+
account,
|
|
126
|
+
_SIDES[side],
|
|
127
|
+
price,
|
|
128
|
+
qty,
|
|
129
|
+
_TYPES[otype],
|
|
130
|
+
_TIFS[tif_stp & 0x0F],
|
|
131
|
+
bool(flags & _FLAG_POST_ONLY),
|
|
132
|
+
_STPS[tif_stp >> 4],
|
|
133
|
+
)
|
|
134
|
+
elif kind == _KIND_CANCEL and len(payload) == _CANCEL.size:
|
|
135
|
+
_, seq, ts, oid, account = _CANCEL.unpack(payload)
|
|
136
|
+
command = CancelOrder(oid, account)
|
|
137
|
+
else:
|
|
138
|
+
raise WalCorruptionError(f"unknown record kind {kind} with {len(payload)} bytes")
|
|
139
|
+
return SequencedCommand(seq, ts, command)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _is_blank(data: bytes, start: int) -> bool:
|
|
143
|
+
"""True if nothing but zero bytes (or nothing at all) follows ``start``.
|
|
144
|
+
|
|
145
|
+
Some filesystems extend a file with zeros before the data lands, so a
|
|
146
|
+
crash can leave a zero-filled tail rather than a short one.
|
|
147
|
+
"""
|
|
148
|
+
return not data[start:].strip(b"\0")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class SegmentReader:
|
|
152
|
+
"""Iterate the valid records of one segment, then report how it ended.
|
|
153
|
+
|
|
154
|
+
After iteration, ``valid_end`` is the byte offset just past the last good
|
|
155
|
+
record and ``torn`` describes any incomplete tail (``None`` if clean).
|
|
156
|
+
"""
|
|
157
|
+
|
|
158
|
+
def __init__(self, path: Path) -> None:
|
|
159
|
+
self.path = path
|
|
160
|
+
self.valid_end = 0
|
|
161
|
+
self.torn: TornTail | None = None
|
|
162
|
+
|
|
163
|
+
def __iter__(self) -> Iterator[SequencedCommand]:
|
|
164
|
+
data = self.path.read_bytes()
|
|
165
|
+
size = len(data)
|
|
166
|
+
header = len(MAGIC)
|
|
167
|
+
if size < header:
|
|
168
|
+
# The process died while creating the segment.
|
|
169
|
+
if size:
|
|
170
|
+
self.torn = TornTail(0, size, "incomplete segment header")
|
|
171
|
+
return
|
|
172
|
+
if data[:header] != MAGIC:
|
|
173
|
+
raise WalCorruptionError(f"{self.path}: not a WAL segment")
|
|
174
|
+
|
|
175
|
+
frame_size = _FRAME.size
|
|
176
|
+
unpack_frame = _FRAME.unpack_from
|
|
177
|
+
crc32 = zlib.crc32
|
|
178
|
+
pos = self.valid_end = header
|
|
179
|
+
while pos < size:
|
|
180
|
+
if size - pos < frame_size:
|
|
181
|
+
self._tear(pos, size, "incomplete record header")
|
|
182
|
+
return
|
|
183
|
+
length, crc = unpack_frame(data, pos)
|
|
184
|
+
start = pos + frame_size
|
|
185
|
+
end = start + length
|
|
186
|
+
if not 0 < length <= _MAX_PAYLOAD:
|
|
187
|
+
if _is_blank(data, pos):
|
|
188
|
+
self._tear(pos, size, "zero-filled tail")
|
|
189
|
+
return
|
|
190
|
+
raise WalCorruptionError(f"{self.path}: bad record length {length} at {pos}")
|
|
191
|
+
if end > size:
|
|
192
|
+
self._tear(pos, size, "incomplete record")
|
|
193
|
+
return
|
|
194
|
+
payload = data[start:end]
|
|
195
|
+
if crc32(payload, crc32(data[pos : pos + 4])) != crc:
|
|
196
|
+
if _is_blank(data, end):
|
|
197
|
+
self._tear(pos, size, "checksum mismatch in the last record")
|
|
198
|
+
return
|
|
199
|
+
raise WalCorruptionError(
|
|
200
|
+
f"{self.path}: checksum mismatch at offset {pos} with records after it"
|
|
201
|
+
)
|
|
202
|
+
yield decode(payload)
|
|
203
|
+
pos = self.valid_end = end
|
|
204
|
+
|
|
205
|
+
def _tear(self, offset: int, size: int, reason: str) -> None:
|
|
206
|
+
self.torn = TornTail(offset, size - offset, reason)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class SegmentWriter:
|
|
210
|
+
"""Append-only writer for one segment with explicit group commit."""
|
|
211
|
+
|
|
212
|
+
def __init__(self, path: Path, *, fsync: bool = True) -> None:
|
|
213
|
+
self.path = path
|
|
214
|
+
self._fsync = fsync
|
|
215
|
+
self._buffer = bytearray()
|
|
216
|
+
self.pending = 0 # records buffered since the last sync
|
|
217
|
+
self._file: BinaryIO = path.open("ab")
|
|
218
|
+
if self._file.tell() == 0:
|
|
219
|
+
self._file.write(MAGIC)
|
|
220
|
+
self._flush()
|
|
221
|
+
fsync_directory(path.parent)
|
|
222
|
+
|
|
223
|
+
def append(self, sc: SequencedCommand) -> None:
|
|
224
|
+
self._buffer += encode(sc)
|
|
225
|
+
self.pending += 1
|
|
226
|
+
|
|
227
|
+
def sync(self) -> None:
|
|
228
|
+
"""Make every appended record durable: one write, one fsync."""
|
|
229
|
+
if not self._buffer:
|
|
230
|
+
return
|
|
231
|
+
self._file.write(self._buffer)
|
|
232
|
+
self._buffer.clear()
|
|
233
|
+
self.pending = 0
|
|
234
|
+
self._flush()
|
|
235
|
+
|
|
236
|
+
def close(self) -> None:
|
|
237
|
+
self.sync()
|
|
238
|
+
self._file.close()
|
|
239
|
+
|
|
240
|
+
def _flush(self) -> None:
|
|
241
|
+
self._file.flush()
|
|
242
|
+
if self._fsync:
|
|
243
|
+
os.fsync(self._file.fileno())
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def fsync_directory(path: Path) -> None:
|
|
247
|
+
"""Persist a directory entry (a new or renamed file) on POSIX.
|
|
248
|
+
|
|
249
|
+
Windows has no way to open a directory for fsync; NTFS journals metadata
|
|
250
|
+
itself, so there the call is a no-op.
|
|
251
|
+
"""
|
|
252
|
+
if os.name == "nt":
|
|
253
|
+
return
|
|
254
|
+
fd = os.open(path, os.O_RDONLY)
|
|
255
|
+
try:
|
|
256
|
+
os.fsync(fd)
|
|
257
|
+
finally:
|
|
258
|
+
os.close(fd)
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Synthetic, reproducible order flow for benchmarks, soak runs and crash tests.
|
|
2
|
+
|
|
3
|
+
The mix is roughly what a liquid market looks like from the engine's side:
|
|
4
|
+
mostly passive limit orders near the touch, a steady stream of cancels, and a
|
|
5
|
+
minority of aggressive orders that cross. The randomness lives here, in the
|
|
6
|
+
load generator, never in the engine: the same seed always yields the same
|
|
7
|
+
commands, so a run can be replayed and compared by state hash.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import random
|
|
13
|
+
from collections.abc import Iterator
|
|
14
|
+
|
|
15
|
+
from matching_engine.domain import (
|
|
16
|
+
CancelOrder,
|
|
17
|
+
Command,
|
|
18
|
+
NewOrder,
|
|
19
|
+
OrderType,
|
|
20
|
+
Side,
|
|
21
|
+
TimeInForce,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
CANCEL_SHARE = 0.25
|
|
25
|
+
MARKET_SHARE = 0.05
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def order_flow(
|
|
29
|
+
seed: int,
|
|
30
|
+
count: int,
|
|
31
|
+
*,
|
|
32
|
+
accounts: int = 1_000,
|
|
33
|
+
mid: int = 100_000,
|
|
34
|
+
depth_ticks: int = 50,
|
|
35
|
+
cross_ticks: int = 5,
|
|
36
|
+
) -> Iterator[Command]:
|
|
37
|
+
"""Yield ``count`` commands; command ``i`` (1-based) uses order id ``i``.
|
|
38
|
+
|
|
39
|
+
Limit prices land within ``depth_ticks`` of ``mid`` on the passive side and
|
|
40
|
+
up to ``cross_ticks`` through it, so about one limit in ten takes liquidity.
|
|
41
|
+
Cancels target a random earlier order with its owner's account; some of
|
|
42
|
+
those orders will have filled already, so a realistic share of cancels is
|
|
43
|
+
rejected as unknown.
|
|
44
|
+
"""
|
|
45
|
+
rng = random.Random(seed)
|
|
46
|
+
placed: list[tuple[int, int]] = [] # (order_id, account) of every limit so far
|
|
47
|
+
for order_id in range(1, count + 1):
|
|
48
|
+
roll = rng.random()
|
|
49
|
+
if roll < CANCEL_SHARE and placed:
|
|
50
|
+
victim, owner = placed[rng.randrange(len(placed))]
|
|
51
|
+
yield CancelOrder(victim, owner)
|
|
52
|
+
continue
|
|
53
|
+
side = Side.BUY if rng.random() < 0.5 else Side.SELL
|
|
54
|
+
account = rng.randint(1, accounts)
|
|
55
|
+
qty = rng.randint(1, 100)
|
|
56
|
+
if roll < CANCEL_SHARE + MARKET_SHARE:
|
|
57
|
+
yield NewOrder(order_id, account, side, 0, qty, OrderType.MARKET, TimeInForce.IOC)
|
|
58
|
+
continue
|
|
59
|
+
offset = rng.randint(-cross_ticks, depth_ticks)
|
|
60
|
+
price = mid - offset if side is Side.BUY else mid + offset
|
|
61
|
+
placed.append((order_id, account))
|
|
62
|
+
yield NewOrder(order_id, account, side, price, qty)
|
|
@@ -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
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
matching_engine/__init__.py,sha256=VqydE8UJFQ6ORs5iqEWL5qakqZVXdIkmz6uAHmc6bnQ,438
|
|
2
|
+
matching_engine/__main__.py,sha256=2npZS8cLPikmeI1dgWJBo3RHnkioEjhnWkbXQ_0iB_I,67
|
|
3
|
+
matching_engine/book.py,sha256=CPW9_eE2XtFhZRigr0l9Vrktdiz2BXgJr7IjpzytKgg,7233
|
|
4
|
+
matching_engine/cli.py,sha256=ifaZo7ZU91suI8DptsY_81ahQYoZSc-4EcFOPLykFgo,2410
|
|
5
|
+
matching_engine/domain.py,sha256=5QYJ9JS0xbDA4DAWZhCn6du5Qjh-EZo5v7q4W4VmGE0,2455
|
|
6
|
+
matching_engine/engine.py,sha256=mFhU1xHMg1vGDIQOd5AGEN6WShtAD7O99hVgcWdOgHc,9976
|
|
7
|
+
matching_engine/events.py,sha256=Hic8KsXeq_Whz1SrY-G54CG_fqSEh4FDAW3XatjtJB0,2128
|
|
8
|
+
matching_engine/journal.py,sha256=vJxUdlc1zhqXaSUHPdn52m5dY9pIXpNWfzuETElAJ-U,7658
|
|
9
|
+
matching_engine/market.py,sha256=dQgdbyIURG_fKg-GCcjv9BMsrAg_LEDdrQY9-1p0Gdw,1991
|
|
10
|
+
matching_engine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
|
+
matching_engine/sequencer.py,sha256=Y7FSSNJ_mqnCYqNC1S5MK4_tMjr1kODJVf9ND62VnrM,1238
|
|
12
|
+
matching_engine/snapshot.py,sha256=GJvgixtshl8VFa59TvsmOCg0rmmvClv2WDQlnkgyuuQ,2584
|
|
13
|
+
matching_engine/wal.py,sha256=-LnJbh2kr1NwEmOy-PzcAh9YMbvCiGuUv13euZuZn1I,8631
|
|
14
|
+
matching_engine/workload.py,sha256=WVSsLWIxJ7SPPoHqBzvi57m8UQhV_980CvSc4RLrN4M,2200
|
|
15
|
+
matching_engine/gateway/__init__.py,sha256=iDWadm3aGNQIt8TZYaEsojIhvGQ3h9w0VZ0axEukDXA,210
|
|
16
|
+
matching_engine/gateway/app.py,sha256=gMFuxs_9-GDmwu-YYBu_ksJS0OjOpkFDjhTbjm_a358,7961
|
|
17
|
+
matching_engine/gateway/config.py,sha256=n8xNdWJlSt8IvqBOPkUD6I6JklfdBI2fOYGUrS9Ofxs,1835
|
|
18
|
+
matching_engine/gateway/marketdata.py,sha256=JzoH1yrgu0CJBPlQmKn1U9tOS64RpvqVXAuOlmoX8aM,4037
|
|
19
|
+
matching_engine/gateway/schemas.py,sha256=8YRqaYCUI7TdOpW0w4vr0gjO81us0lGboV7flUDbyjg,4737
|
|
20
|
+
matching_engine/gateway/worker.py,sha256=pPKSmlyQ7lceMsRfxz52DCX46CI01-EsvpaApuPBi4o,6819
|
|
21
|
+
matching_engine-0.1.0.dist-info/METADATA,sha256=a3a8t8wjSKw2VezLkhTdppvTzqZ-q6TGj13dBhnYsi0,13875
|
|
22
|
+
matching_engine-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
23
|
+
matching_engine-0.1.0.dist-info/entry_points.txt,sha256=n5mFNLN7VqJGnAoEDm3JIijIAJGoUkYBPFBOMOke9oU,61
|
|
24
|
+
matching_engine-0.1.0.dist-info/licenses/LICENSE,sha256=Sbv9pl9_ETVlujgjfKKScL5g2LKfUqdKT5xWMrVqOPA,1071
|
|
25
|
+
matching_engine-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|