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
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""One asyncio task per market: the only code that touches that market's engine.
|
|
2
|
+
|
|
3
|
+
Per batch, the worker
|
|
4
|
+
|
|
5
|
+
1. drains up to ``batch_max`` queued requests without waiting,
|
|
6
|
+
2. stamps each one through the sequencer (order ids are the sequence number),
|
|
7
|
+
3. appends them all to the WAL and makes them durable with **one** fsync,
|
|
8
|
+
4. only then applies them to the engine, resolves each caller's future and
|
|
9
|
+
hands the batch's events to the market-data hub.
|
|
10
|
+
|
|
11
|
+
Nothing is acknowledged before it is on disk, and while one fsync is in
|
|
12
|
+
flight the next batch fills up behind it — group commit falls out of the loop
|
|
13
|
+
shape rather than needing a timer.
|
|
14
|
+
|
|
15
|
+
The engine is mutated only between awaits, on the event-loop thread, so
|
|
16
|
+
request handlers may read it (depth, L3) without locks: they can never observe
|
|
17
|
+
a half-applied command.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import logging
|
|
24
|
+
import time
|
|
25
|
+
from collections.abc import Callable
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
|
|
28
|
+
from matching_engine.domain import Command, SequencedCommand
|
|
29
|
+
from matching_engine.engine import MatchingEngine
|
|
30
|
+
from matching_engine.events import Event
|
|
31
|
+
from matching_engine.gateway.marketdata import MarketDataHub
|
|
32
|
+
from matching_engine.journal import Journal, RecoveryReport
|
|
33
|
+
from matching_engine.market import MarketSpec
|
|
34
|
+
from matching_engine.sequencer import Sequencer
|
|
35
|
+
from matching_engine.snapshot import encode_snapshot
|
|
36
|
+
|
|
37
|
+
log = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class MarketUnavailableError(Exception):
|
|
41
|
+
"""The market cannot take the request: overloaded, stopping, or failed."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(slots=True)
|
|
45
|
+
class _Request:
|
|
46
|
+
build: Callable[[int], Command] # receives the seq, so a new order can use it as its id
|
|
47
|
+
future: asyncio.Future[tuple[SequencedCommand, list[Event]]] = field(
|
|
48
|
+
default_factory=lambda: asyncio.get_running_loop().create_future()
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_STOP = object()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class MarketWorker:
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
spec: MarketSpec,
|
|
59
|
+
journal: Journal,
|
|
60
|
+
engine: MatchingEngine,
|
|
61
|
+
report: RecoveryReport,
|
|
62
|
+
hub: MarketDataHub,
|
|
63
|
+
*,
|
|
64
|
+
batch_max: int,
|
|
65
|
+
queue_max: int,
|
|
66
|
+
snapshot_every: int,
|
|
67
|
+
clock: Callable[[], int] = time.time_ns,
|
|
68
|
+
) -> None:
|
|
69
|
+
self.spec = spec
|
|
70
|
+
self.engine = engine
|
|
71
|
+
self.hub = hub
|
|
72
|
+
self._journal = journal
|
|
73
|
+
self._sequencer = Sequencer(report.last_seq + 1, report.last_ts, clock)
|
|
74
|
+
self._queue: asyncio.Queue[_Request | object] = asyncio.Queue(maxsize=queue_max)
|
|
75
|
+
self._batch_max = batch_max
|
|
76
|
+
self._snapshot_every = snapshot_every
|
|
77
|
+
self._since_snapshot = report.replayed
|
|
78
|
+
self._task: asyncio.Task[None] | None = None
|
|
79
|
+
self._accepting = False
|
|
80
|
+
self.failure: BaseException | None = None
|
|
81
|
+
|
|
82
|
+
def start(self) -> None:
|
|
83
|
+
self._journal.open(self._sequencer.next_seq)
|
|
84
|
+
self._accepting = True
|
|
85
|
+
self._task = asyncio.create_task(self._run(), name=f"market:{self.spec.symbol}")
|
|
86
|
+
|
|
87
|
+
async def stop(self) -> None:
|
|
88
|
+
"""Finish everything already queued, checkpoint, and close the log."""
|
|
89
|
+
self._accepting = False
|
|
90
|
+
if self._task is not None and not self._task.done():
|
|
91
|
+
await self._queue.put(_STOP)
|
|
92
|
+
await self._task
|
|
93
|
+
if self.failure is None: # a failed log is left exactly as it was for inspection
|
|
94
|
+
if self._since_snapshot:
|
|
95
|
+
await self._checkpoint()
|
|
96
|
+
self._journal.close()
|
|
97
|
+
|
|
98
|
+
async def submit(self, build: Callable[[int], Command]) -> tuple[SequencedCommand, list[Event]]:
|
|
99
|
+
"""Queue one command and wait until it is durable and applied."""
|
|
100
|
+
if not self._accepting:
|
|
101
|
+
raise MarketUnavailableError(f"{self.spec.symbol} is not accepting orders")
|
|
102
|
+
request = _Request(build)
|
|
103
|
+
try:
|
|
104
|
+
self._queue.put_nowait(request)
|
|
105
|
+
except asyncio.QueueFull:
|
|
106
|
+
raise MarketUnavailableError(f"{self.spec.symbol} is overloaded") from None
|
|
107
|
+
return await request.future
|
|
108
|
+
|
|
109
|
+
async def _run(self) -> None:
|
|
110
|
+
batch: list[_Request] = []
|
|
111
|
+
try:
|
|
112
|
+
while True:
|
|
113
|
+
item = await self._queue.get()
|
|
114
|
+
stop = item is _STOP
|
|
115
|
+
if not stop:
|
|
116
|
+
assert isinstance(item, _Request)
|
|
117
|
+
batch.append(item)
|
|
118
|
+
while not stop and len(batch) < self._batch_max:
|
|
119
|
+
try:
|
|
120
|
+
item = self._queue.get_nowait()
|
|
121
|
+
except asyncio.QueueEmpty:
|
|
122
|
+
break
|
|
123
|
+
if item is _STOP:
|
|
124
|
+
stop = True
|
|
125
|
+
else:
|
|
126
|
+
assert isinstance(item, _Request)
|
|
127
|
+
batch.append(item)
|
|
128
|
+
if batch:
|
|
129
|
+
await self._commit(batch)
|
|
130
|
+
batch.clear()
|
|
131
|
+
if self._since_snapshot >= self._snapshot_every:
|
|
132
|
+
await self._checkpoint()
|
|
133
|
+
if stop:
|
|
134
|
+
return
|
|
135
|
+
except Exception as exc:
|
|
136
|
+
# Fail-stop: a market that cannot write its log must not keep matching.
|
|
137
|
+
log.critical("market %s stopped: %r", self.spec.symbol, exc)
|
|
138
|
+
self.failure = exc
|
|
139
|
+
self._accepting = False
|
|
140
|
+
for request in batch:
|
|
141
|
+
if not request.future.done():
|
|
142
|
+
request.future.set_exception(MarketUnavailableError(str(exc)))
|
|
143
|
+
self._fail_queued(exc)
|
|
144
|
+
|
|
145
|
+
async def _commit(self, batch: list[_Request]) -> None:
|
|
146
|
+
sequencer, journal = self._sequencer, self._journal
|
|
147
|
+
stamped = [sequencer.stamp(r.build(sequencer.next_seq)) for r in batch]
|
|
148
|
+
for sc in stamped:
|
|
149
|
+
journal.append(sc)
|
|
150
|
+
if journal.fsync:
|
|
151
|
+
await asyncio.to_thread(journal.sync)
|
|
152
|
+
else:
|
|
153
|
+
journal.sync()
|
|
154
|
+
process = self.engine.process
|
|
155
|
+
published: list[Event] = []
|
|
156
|
+
for request, sc in zip(batch, stamped, strict=True):
|
|
157
|
+
events = process(sc)
|
|
158
|
+
published += events
|
|
159
|
+
if not request.future.done(): # the caller may have disconnected
|
|
160
|
+
request.future.set_result((sc, events))
|
|
161
|
+
self.hub.publish(published, self.engine)
|
|
162
|
+
self._since_snapshot += len(batch)
|
|
163
|
+
|
|
164
|
+
async def _checkpoint(self) -> None:
|
|
165
|
+
blob = encode_snapshot(self.engine, self._sequencer.last_ts)
|
|
166
|
+
await asyncio.to_thread(self._journal.checkpoint, blob, self.engine.last_seq)
|
|
167
|
+
self._since_snapshot = 0
|
|
168
|
+
|
|
169
|
+
def _fail_queued(self, exc: BaseException) -> None:
|
|
170
|
+
while True:
|
|
171
|
+
try:
|
|
172
|
+
item = self._queue.get_nowait()
|
|
173
|
+
except asyncio.QueueEmpty:
|
|
174
|
+
return
|
|
175
|
+
if isinstance(item, _Request) and not item.future.done():
|
|
176
|
+
item.future.set_exception(MarketUnavailableError(str(exc)))
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""A market's durable history: WAL segments plus the snapshots that bound replay.
|
|
2
|
+
|
|
3
|
+
Directory layout::
|
|
4
|
+
|
|
5
|
+
<root>/wal/00000000000000000001.wal first seq in each segment
|
|
6
|
+
<root>/wal/00000000000000500001.wal
|
|
7
|
+
<root>/snapshots/00000000000000500000.snap state after that seq
|
|
8
|
+
|
|
9
|
+
Every checkpoint writes a snapshot at ``seq`` and starts a new segment at
|
|
10
|
+
``seq + 1``, so segment boundaries line up with snapshots and old history can
|
|
11
|
+
be dropped a whole file at a time.
|
|
12
|
+
|
|
13
|
+
Recovery loads the newest snapshot that verifies (falling back to older ones
|
|
14
|
+
if it does not), then replays every later record in order, checking that
|
|
15
|
+
sequence numbers are gap-free across segments. A torn tail is legal only in
|
|
16
|
+
the newest segment; it is truncated away so the writer appends onto a clean
|
|
17
|
+
end.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import itertools
|
|
23
|
+
import logging
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import msgspec
|
|
27
|
+
|
|
28
|
+
from matching_engine.domain import SequencedCommand
|
|
29
|
+
from matching_engine.engine import MatchingEngine
|
|
30
|
+
from matching_engine.snapshot import SnapshotError, read_snapshot, write_snapshot
|
|
31
|
+
from matching_engine.wal import SegmentReader, SegmentWriter, TornTail, WalCorruptionError
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
_SEGMENT_SUFFIX = ".wal"
|
|
36
|
+
_SNAPSHOT_SUFFIX = ".snap"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RecoveryReport(msgspec.Struct, frozen=True):
|
|
40
|
+
snapshot_seq: int # 0 when recovery started from an empty engine
|
|
41
|
+
replayed: int # records applied on top of the snapshot
|
|
42
|
+
last_seq: int
|
|
43
|
+
last_ts: int
|
|
44
|
+
torn: TornTail | None # the incomplete write that was (or would be) cut off
|
|
45
|
+
rejected_snapshots: list[str] # snapshots skipped because they failed to verify
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Journal:
|
|
49
|
+
def __init__(self, root: Path, *, fsync: bool = True, keep_snapshots: int = 2) -> None:
|
|
50
|
+
if keep_snapshots < 1:
|
|
51
|
+
raise ValueError("keep at least one snapshot")
|
|
52
|
+
self.root = root
|
|
53
|
+
self.fsync = fsync
|
|
54
|
+
self.keep_snapshots = keep_snapshots
|
|
55
|
+
self.wal_dir = root / "wal"
|
|
56
|
+
self.snapshot_dir = root / "snapshots"
|
|
57
|
+
self.wal_dir.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
self.snapshot_dir.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
self._writer: SegmentWriter | None = None
|
|
60
|
+
self._segment_first_seq = 0
|
|
61
|
+
|
|
62
|
+
# -- recovery -----------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
def recover(self, *, repair: bool = True) -> tuple[MatchingEngine, RecoveryReport]:
|
|
65
|
+
"""Rebuild the engine from disk.
|
|
66
|
+
|
|
67
|
+
With ``repair`` (the default) a torn tail is truncated so the log can
|
|
68
|
+
be appended to; without it the files are left untouched, which is
|
|
69
|
+
what an offline ``verify`` wants.
|
|
70
|
+
"""
|
|
71
|
+
engine, last_ts, rejected = self._load_snapshot()
|
|
72
|
+
snapshot_seq = engine.last_seq
|
|
73
|
+
segments = self._segments()
|
|
74
|
+
replayed = 0
|
|
75
|
+
torn: TornTail | None = None
|
|
76
|
+
for i, (first_seq, path) in enumerate(segments):
|
|
77
|
+
is_last = i == len(segments) - 1
|
|
78
|
+
if not is_last and segments[i + 1][0] - 1 <= engine.last_seq:
|
|
79
|
+
continue # every record here is already inside the snapshot
|
|
80
|
+
reader = SegmentReader(path)
|
|
81
|
+
expected = first_seq
|
|
82
|
+
for sc in reader:
|
|
83
|
+
if sc.seq != expected:
|
|
84
|
+
raise WalCorruptionError(f"{path}: expected seq {expected}, found {sc.seq}")
|
|
85
|
+
expected += 1
|
|
86
|
+
if sc.seq <= engine.last_seq:
|
|
87
|
+
continue
|
|
88
|
+
if sc.seq != engine.last_seq + 1:
|
|
89
|
+
raise WalCorruptionError(
|
|
90
|
+
f"{path}: history is missing between seq {engine.last_seq} and {sc.seq}"
|
|
91
|
+
)
|
|
92
|
+
engine.process(sc)
|
|
93
|
+
last_ts = sc.ts
|
|
94
|
+
replayed += 1
|
|
95
|
+
if reader.torn is not None:
|
|
96
|
+
if not is_last:
|
|
97
|
+
raise WalCorruptionError(f"{path}: torn write inside a sealed segment")
|
|
98
|
+
torn = reader.torn
|
|
99
|
+
log.warning("torn WAL tail in %s: %s", path.name, torn)
|
|
100
|
+
if repair:
|
|
101
|
+
with path.open("r+b") as f:
|
|
102
|
+
f.truncate(reader.valid_end)
|
|
103
|
+
report = RecoveryReport(snapshot_seq, replayed, engine.last_seq, last_ts, torn, rejected)
|
|
104
|
+
return engine, report
|
|
105
|
+
|
|
106
|
+
def _load_snapshot(self) -> tuple[MatchingEngine, int, list[str]]:
|
|
107
|
+
rejected: list[str] = []
|
|
108
|
+
for _, path in reversed(self._snapshots()):
|
|
109
|
+
try:
|
|
110
|
+
engine, snap = read_snapshot(path)
|
|
111
|
+
except SnapshotError as exc:
|
|
112
|
+
log.error("skipping snapshot: %s", exc)
|
|
113
|
+
rejected.append(path.name)
|
|
114
|
+
continue
|
|
115
|
+
return engine, snap.last_ts, rejected
|
|
116
|
+
return MatchingEngine(), 0, rejected
|
|
117
|
+
|
|
118
|
+
# -- writing ------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
def open(self, next_seq: int) -> None:
|
|
121
|
+
"""Start appending after recovery: onto the newest segment, or a new one."""
|
|
122
|
+
segments = self._segments()
|
|
123
|
+
if segments:
|
|
124
|
+
self._segment_first_seq, path = segments[-1]
|
|
125
|
+
else:
|
|
126
|
+
self._segment_first_seq, path = next_seq, self._segment_path(next_seq)
|
|
127
|
+
self._writer = SegmentWriter(path, fsync=self.fsync)
|
|
128
|
+
|
|
129
|
+
def append(self, sc: SequencedCommand) -> None:
|
|
130
|
+
assert self._writer is not None, "open() the journal before appending"
|
|
131
|
+
self._writer.append(sc)
|
|
132
|
+
|
|
133
|
+
def sync(self) -> None:
|
|
134
|
+
"""Group commit: make every appended record durable at once."""
|
|
135
|
+
assert self._writer is not None
|
|
136
|
+
self._writer.sync()
|
|
137
|
+
|
|
138
|
+
def checkpoint(self, blob: bytes, seq: int) -> None:
|
|
139
|
+
"""Persist an encoded snapshot taken at ``seq`` and roll to a new segment.
|
|
140
|
+
|
|
141
|
+
The caller encodes the snapshot (see ``snapshot.encode_snapshot``)
|
|
142
|
+
while the engine is quiescent; this part only does I/O, so it can run
|
|
143
|
+
on a worker thread.
|
|
144
|
+
"""
|
|
145
|
+
assert self._writer is not None
|
|
146
|
+
write_snapshot(self._snapshot_path(seq), blob, fsync=self.fsync)
|
|
147
|
+
if self._segment_first_seq != seq + 1:
|
|
148
|
+
self._writer.close()
|
|
149
|
+
self._segment_first_seq = seq + 1
|
|
150
|
+
self._writer = SegmentWriter(self._segment_path(seq + 1), fsync=self.fsync)
|
|
151
|
+
self._prune()
|
|
152
|
+
|
|
153
|
+
def close(self) -> None:
|
|
154
|
+
if self._writer is not None:
|
|
155
|
+
self._writer.close()
|
|
156
|
+
self._writer = None
|
|
157
|
+
|
|
158
|
+
def _prune(self) -> None:
|
|
159
|
+
"""Drop snapshots beyond the retention count and segments none of them need."""
|
|
160
|
+
snapshots = self._snapshots()
|
|
161
|
+
for _, path in snapshots[: -self.keep_snapshots]:
|
|
162
|
+
path.unlink()
|
|
163
|
+
oldest_kept = snapshots[-self.keep_snapshots :][0][0]
|
|
164
|
+
segments = self._segments()
|
|
165
|
+
for (_, path), (next_first, _) in itertools.pairwise(segments):
|
|
166
|
+
if next_first - 1 <= oldest_kept:
|
|
167
|
+
path.unlink()
|
|
168
|
+
|
|
169
|
+
# -- layout -------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
def _segment_path(self, first_seq: int) -> Path:
|
|
172
|
+
return self.wal_dir / f"{first_seq:020d}{_SEGMENT_SUFFIX}"
|
|
173
|
+
|
|
174
|
+
def _snapshot_path(self, seq: int) -> Path:
|
|
175
|
+
return self.snapshot_dir / f"{seq:020d}{_SNAPSHOT_SUFFIX}"
|
|
176
|
+
|
|
177
|
+
def _segments(self) -> list[tuple[int, Path]]:
|
|
178
|
+
return _numbered(self.wal_dir, _SEGMENT_SUFFIX)
|
|
179
|
+
|
|
180
|
+
def _snapshots(self) -> list[tuple[int, Path]]:
|
|
181
|
+
return _numbered(self.snapshot_dir, _SNAPSHOT_SUFFIX)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _numbered(directory: Path, suffix: str) -> list[tuple[int, Path]]:
|
|
185
|
+
"""Files named ``<number><suffix>``, sorted by number."""
|
|
186
|
+
found = [(int(p.stem), p) for p in directory.glob(f"*{suffix}") if p.stem.isdigit()]
|
|
187
|
+
return sorted(found)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Market specification: the one place decimals are turned into ticks and lots.
|
|
2
|
+
|
|
3
|
+
Clients speak decimal strings (``"64250.50"``); the engine speaks integers.
|
|
4
|
+
Conversion happens once at the edge, and it is strict: a price that is not a
|
|
5
|
+
whole number of ticks is refused rather than rounded, because silently moving
|
|
6
|
+
someone's limit price is worse than rejecting the order.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from decimal import Decimal, InvalidOperation
|
|
13
|
+
|
|
14
|
+
from matching_engine.domain import MAX_INT64
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True, slots=True)
|
|
18
|
+
class MarketSpec:
|
|
19
|
+
symbol: str
|
|
20
|
+
tick_size: Decimal # price increment: price = ticks * tick_size
|
|
21
|
+
lot_size: Decimal # quantity increment: qty = lots * lot_size
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def parse(cls, text: str) -> MarketSpec:
|
|
25
|
+
"""Parse ``SYMBOL:TICK:LOT``, e.g. ``BTC-USDT:0.01:0.00001``."""
|
|
26
|
+
try:
|
|
27
|
+
symbol, tick, lot = text.strip().split(":")
|
|
28
|
+
spec = cls(symbol, Decimal(tick), Decimal(lot))
|
|
29
|
+
except (ValueError, InvalidOperation) as exc:
|
|
30
|
+
raise ValueError(f"expected SYMBOL:TICK:LOT, got {text!r}") from exc
|
|
31
|
+
if not symbol or spec.tick_size <= 0 or spec.lot_size <= 0:
|
|
32
|
+
raise ValueError(f"invalid market spec {text!r}")
|
|
33
|
+
return spec
|
|
34
|
+
|
|
35
|
+
def to_ticks(self, price: Decimal) -> int:
|
|
36
|
+
return _to_units(price, self.tick_size, "price")
|
|
37
|
+
|
|
38
|
+
def to_lots(self, qty: Decimal) -> int:
|
|
39
|
+
return _to_units(qty, self.lot_size, "quantity")
|
|
40
|
+
|
|
41
|
+
def price(self, ticks: int) -> str:
|
|
42
|
+
return f"{self.tick_size * ticks:f}"
|
|
43
|
+
|
|
44
|
+
def qty(self, lots: int) -> str:
|
|
45
|
+
return f"{self.lot_size * lots:f}"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _to_units(value: Decimal, step: Decimal, what: str) -> int:
|
|
49
|
+
units = value / step
|
|
50
|
+
if units != units.to_integral_value():
|
|
51
|
+
raise ValueError(f"{what} {value} is not a multiple of {step}")
|
|
52
|
+
if not 0 < units <= MAX_INT64:
|
|
53
|
+
raise ValueError(f"{what} {value} is out of range")
|
|
54
|
+
return int(units)
|
matching_engine/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""The sequencer: the one place where time and ordering enter the system.
|
|
2
|
+
|
|
3
|
+
Everything downstream — the WAL, the engine, market data — sees commands in
|
|
4
|
+
the order and with the timestamps the sequencer gave them. Keeping the clock
|
|
5
|
+
here, outside the engine, is what makes replay deterministic.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
from matching_engine.domain import Command, SequencedCommand
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Sequencer:
|
|
17
|
+
"""Assigns gap-free sequence numbers and non-decreasing timestamps.
|
|
18
|
+
|
|
19
|
+
The wall clock can step backwards (NTP slew, a VM migration); timestamps
|
|
20
|
+
are clamped so the log never shows time running in reverse.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
__slots__ = ("_clock", "last_ts", "next_seq")
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
next_seq: int = 1,
|
|
28
|
+
last_ts: int = 0,
|
|
29
|
+
clock: Callable[[], int] = time.time_ns,
|
|
30
|
+
) -> None:
|
|
31
|
+
self.next_seq = next_seq
|
|
32
|
+
self.last_ts = last_ts
|
|
33
|
+
self._clock = clock
|
|
34
|
+
|
|
35
|
+
def stamp(self, command: Command) -> SequencedCommand:
|
|
36
|
+
ts = self._clock()
|
|
37
|
+
ts = max(ts, self.last_ts)
|
|
38
|
+
self.last_ts = ts
|
|
39
|
+
seq = self.next_seq
|
|
40
|
+
self.next_seq = seq + 1
|
|
41
|
+
return SequencedCommand(seq, ts, command)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Point-in-time snapshots of an engine, so recovery replays a tail, not a history.
|
|
2
|
+
|
|
3
|
+
File layout::
|
|
4
|
+
|
|
5
|
+
MAGIC (8 bytes) | crc:u32 | length:u64 | body[length]
|
|
6
|
+
body = MessagePack(Snapshot)
|
|
7
|
+
|
|
8
|
+
A snapshot is written to a temporary name, fsynced, then atomically renamed,
|
|
9
|
+
so a crash leaves either the old snapshot set or the new one — never half a
|
|
10
|
+
file under a final name. The stored state hash is re-checked after loading:
|
|
11
|
+
a snapshot that decodes but rebuilds a different book is rejected, too.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import struct
|
|
18
|
+
import zlib
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import msgspec
|
|
22
|
+
|
|
23
|
+
from matching_engine.engine import EngineState, MatchingEngine
|
|
24
|
+
from matching_engine.wal import fsync_directory
|
|
25
|
+
|
|
26
|
+
MAGIC = b"MESNAP1\n"
|
|
27
|
+
_HEADER = struct.Struct("<IQ")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SnapshotError(Exception):
|
|
31
|
+
"""A snapshot file is unreadable or does not reproduce its recorded state."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Snapshot(msgspec.Struct, frozen=True):
|
|
35
|
+
state: EngineState
|
|
36
|
+
state_hash: str
|
|
37
|
+
last_ts: int # the sequencer resumes from here so timestamps stay monotonic
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def encode_snapshot(engine: MatchingEngine, last_ts: int) -> bytes:
|
|
41
|
+
"""Serialize the engine. Must run while nothing is mutating it."""
|
|
42
|
+
body = msgspec.msgpack.encode(Snapshot(engine.export_state(), engine.state_hash(), last_ts))
|
|
43
|
+
return MAGIC + _HEADER.pack(zlib.crc32(body), len(body)) + body
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def write_snapshot(path: Path, blob: bytes, *, fsync: bool = True) -> None:
|
|
47
|
+
"""Durably place an encoded snapshot at ``path``. Safe to run off-thread."""
|
|
48
|
+
tmp = path.with_name(path.name + ".tmp")
|
|
49
|
+
with tmp.open("wb") as f:
|
|
50
|
+
f.write(blob)
|
|
51
|
+
f.flush()
|
|
52
|
+
if fsync:
|
|
53
|
+
os.fsync(f.fileno())
|
|
54
|
+
tmp.replace(path)
|
|
55
|
+
if fsync:
|
|
56
|
+
fsync_directory(path.parent)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def read_snapshot(path: Path) -> tuple[MatchingEngine, Snapshot]:
|
|
60
|
+
data = path.read_bytes()
|
|
61
|
+
head = len(MAGIC) + _HEADER.size
|
|
62
|
+
if len(data) < head or data[: len(MAGIC)] != MAGIC:
|
|
63
|
+
raise SnapshotError(f"{path}: not a snapshot")
|
|
64
|
+
crc, length = _HEADER.unpack_from(data, len(MAGIC))
|
|
65
|
+
body = data[head:]
|
|
66
|
+
if len(body) != length or zlib.crc32(body) != crc:
|
|
67
|
+
raise SnapshotError(f"{path}: checksum or length mismatch")
|
|
68
|
+
try:
|
|
69
|
+
snap = msgspec.msgpack.decode(body, type=Snapshot)
|
|
70
|
+
except msgspec.DecodeError as exc:
|
|
71
|
+
raise SnapshotError(f"{path}: {exc}") from exc
|
|
72
|
+
engine = MatchingEngine.restore(snap.state)
|
|
73
|
+
if engine.state_hash() != snap.state_hash:
|
|
74
|
+
raise SnapshotError(f"{path}: rebuilt state does not match the recorded hash")
|
|
75
|
+
return engine, snap
|