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,26 @@
|
|
|
1
|
+
"""A deterministic price-time priority matching engine."""
|
|
2
|
+
|
|
3
|
+
from matching_engine.domain import (
|
|
4
|
+
CancelOrder,
|
|
5
|
+
Command,
|
|
6
|
+
NewOrder,
|
|
7
|
+
OrderType,
|
|
8
|
+
SelfTradePrevention,
|
|
9
|
+
SequencedCommand,
|
|
10
|
+
Side,
|
|
11
|
+
TimeInForce,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"CancelOrder",
|
|
18
|
+
"Command",
|
|
19
|
+
"NewOrder",
|
|
20
|
+
"OrderType",
|
|
21
|
+
"SelfTradePrevention",
|
|
22
|
+
"SequencedCommand",
|
|
23
|
+
"Side",
|
|
24
|
+
"TimeInForce",
|
|
25
|
+
"__version__",
|
|
26
|
+
]
|
matching_engine/book.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""The order book: two sides of price levels, each level a FIFO queue.
|
|
2
|
+
|
|
3
|
+
Layout
|
|
4
|
+
------
|
|
5
|
+
Each side keeps
|
|
6
|
+
|
|
7
|
+
* ``levels``: ``dict[key, PriceLevel]`` — O(1) lookup of an existing level;
|
|
8
|
+
* ``keys``: a ``SortedList`` of the same keys — ordered, best first.
|
|
9
|
+
|
|
10
|
+
The *key* is the price for asks and the negated price for bids, so on both
|
|
11
|
+
sides ``keys[0]`` is the best level and "does this level cross a limit" is the
|
|
12
|
+
single comparison ``key <= limit_key``. The matcher never branches on side
|
|
13
|
+
inside its loop.
|
|
14
|
+
|
|
15
|
+
A level is an intrusive doubly linked list of :class:`RestingOrder` nodes, and
|
|
16
|
+
the book holds ``dict[order_id, RestingOrder]``. Together they make cancel O(1):
|
|
17
|
+
find the node by id, unlink it, no scan of the queue. A ``deque`` would give
|
|
18
|
+
O(1) append and pop-left, but removal from the middle is O(n).
|
|
19
|
+
|
|
20
|
+
===================================== ==========
|
|
21
|
+
Operation Complexity
|
|
22
|
+
===================================== ==========
|
|
23
|
+
Add to an existing level O(1)
|
|
24
|
+
Add at a new price level O(log L)
|
|
25
|
+
Cancel (level stays non-empty) O(1)
|
|
26
|
+
Cancel (last order at its level) O(log L)
|
|
27
|
+
Best bid / ask O(1)
|
|
28
|
+
Fill against the head of best level O(1)
|
|
29
|
+
L2 depth, top ``n`` levels O(n)
|
|
30
|
+
===================================== ==========
|
|
31
|
+
|
|
32
|
+
``L`` is the number of distinct price levels on one side, which in practice is
|
|
33
|
+
far smaller than the number of orders.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
from collections.abc import Iterator
|
|
39
|
+
|
|
40
|
+
import msgspec
|
|
41
|
+
from sortedcontainers import SortedList
|
|
42
|
+
|
|
43
|
+
from matching_engine.domain import Side
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RestingOrder:
|
|
47
|
+
"""A live order on the book. Mutable: fills decrement ``remaining`` in place."""
|
|
48
|
+
|
|
49
|
+
__slots__ = ("account", "next", "order_id", "prev", "price", "remaining", "side")
|
|
50
|
+
|
|
51
|
+
def __init__(self, order_id: int, account: int, side: Side, price: int, remaining: int) -> None:
|
|
52
|
+
self.order_id = order_id
|
|
53
|
+
self.account = account
|
|
54
|
+
self.side = side
|
|
55
|
+
self.price = price
|
|
56
|
+
self.remaining = remaining
|
|
57
|
+
self.prev: RestingOrder | None = None
|
|
58
|
+
self.next: RestingOrder | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PriceLevel:
|
|
62
|
+
"""All resting orders at one price, oldest first."""
|
|
63
|
+
|
|
64
|
+
__slots__ = ("count", "head", "price", "qty", "tail")
|
|
65
|
+
|
|
66
|
+
def __init__(self, price: int) -> None:
|
|
67
|
+
self.price = price
|
|
68
|
+
self.qty = 0 # sum of ``remaining`` over the queue, kept for O(1) L2 depth
|
|
69
|
+
self.count = 0
|
|
70
|
+
self.head: RestingOrder | None = None
|
|
71
|
+
self.tail: RestingOrder | None = None
|
|
72
|
+
|
|
73
|
+
def append(self, order: RestingOrder) -> None:
|
|
74
|
+
tail = self.tail
|
|
75
|
+
order.prev = tail
|
|
76
|
+
order.next = None
|
|
77
|
+
if tail is None:
|
|
78
|
+
self.head = order
|
|
79
|
+
else:
|
|
80
|
+
tail.next = order
|
|
81
|
+
self.tail = order
|
|
82
|
+
self.qty += order.remaining
|
|
83
|
+
self.count += 1
|
|
84
|
+
|
|
85
|
+
def unlink(self, order: RestingOrder) -> None:
|
|
86
|
+
prev, nxt = order.prev, order.next
|
|
87
|
+
if prev is None:
|
|
88
|
+
self.head = nxt
|
|
89
|
+
else:
|
|
90
|
+
prev.next = nxt
|
|
91
|
+
if nxt is None:
|
|
92
|
+
self.tail = prev
|
|
93
|
+
else:
|
|
94
|
+
nxt.prev = prev
|
|
95
|
+
order.prev = order.next = None
|
|
96
|
+
self.qty -= order.remaining
|
|
97
|
+
self.count -= 1
|
|
98
|
+
|
|
99
|
+
def __iter__(self) -> Iterator[RestingOrder]:
|
|
100
|
+
node = self.head
|
|
101
|
+
while node is not None:
|
|
102
|
+
yield node
|
|
103
|
+
node = node.next
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class BookSide:
|
|
107
|
+
"""One side of the book. See the module docstring for the key convention."""
|
|
108
|
+
|
|
109
|
+
__slots__ = ("keys", "levels", "side", "sign")
|
|
110
|
+
|
|
111
|
+
def __init__(self, side: Side) -> None:
|
|
112
|
+
self.side = side
|
|
113
|
+
self.sign = -1 if side is Side.BUY else 1
|
|
114
|
+
self.levels: dict[int, PriceLevel] = {}
|
|
115
|
+
self.keys: SortedList[int] = SortedList()
|
|
116
|
+
|
|
117
|
+
def key(self, price: int) -> int:
|
|
118
|
+
return price * self.sign
|
|
119
|
+
|
|
120
|
+
def best(self) -> PriceLevel | None:
|
|
121
|
+
return self.levels[self.keys[0]] if self.keys else None
|
|
122
|
+
|
|
123
|
+
def add(self, order: RestingOrder) -> None:
|
|
124
|
+
key = order.price * self.sign
|
|
125
|
+
level = self.levels.get(key)
|
|
126
|
+
if level is None:
|
|
127
|
+
level = self.levels[key] = PriceLevel(order.price)
|
|
128
|
+
self.keys.add(key)
|
|
129
|
+
level.append(order)
|
|
130
|
+
|
|
131
|
+
def remove(self, order: RestingOrder) -> None:
|
|
132
|
+
key = order.price * self.sign
|
|
133
|
+
level = self.levels[key]
|
|
134
|
+
level.unlink(order)
|
|
135
|
+
if level.head is None:
|
|
136
|
+
del self.levels[key]
|
|
137
|
+
self.keys.remove(key)
|
|
138
|
+
|
|
139
|
+
def __iter__(self) -> Iterator[PriceLevel]:
|
|
140
|
+
"""Levels from best to worst."""
|
|
141
|
+
levels = self.levels
|
|
142
|
+
for key in self.keys:
|
|
143
|
+
yield levels[key]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class DepthLevel(msgspec.Struct, frozen=True, array_like=True):
|
|
147
|
+
"""One aggregated L2 level: ``[price, qty, orders]`` on the wire."""
|
|
148
|
+
|
|
149
|
+
price: int
|
|
150
|
+
qty: int
|
|
151
|
+
orders: int
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class Depth(msgspec.Struct, frozen=True):
|
|
155
|
+
"""L2 view: price levels aggregated, best first on each side."""
|
|
156
|
+
|
|
157
|
+
bids: list[DepthLevel]
|
|
158
|
+
asks: list[DepthLevel]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class BookEntry(msgspec.Struct, frozen=True, array_like=True):
|
|
162
|
+
"""One L3 entry: an individual resting order, in queue position."""
|
|
163
|
+
|
|
164
|
+
order_id: int
|
|
165
|
+
account: int
|
|
166
|
+
side: Side
|
|
167
|
+
price: int
|
|
168
|
+
qty: int
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class OrderBook:
|
|
172
|
+
"""Both sides plus the order-id index. Knows nothing about matching rules."""
|
|
173
|
+
|
|
174
|
+
__slots__ = ("asks", "bids", "orders")
|
|
175
|
+
|
|
176
|
+
def __init__(self) -> None:
|
|
177
|
+
self.bids = BookSide(Side.BUY)
|
|
178
|
+
self.asks = BookSide(Side.SELL)
|
|
179
|
+
self.orders: dict[int, RestingOrder] = {}
|
|
180
|
+
|
|
181
|
+
def side(self, side: Side) -> BookSide:
|
|
182
|
+
return self.bids if side is Side.BUY else self.asks
|
|
183
|
+
|
|
184
|
+
def opposite(self, side: Side) -> BookSide:
|
|
185
|
+
return self.asks if side is Side.BUY else self.bids
|
|
186
|
+
|
|
187
|
+
def add(self, order: RestingOrder) -> None:
|
|
188
|
+
self.orders[order.order_id] = order
|
|
189
|
+
self.side(order.side).add(order)
|
|
190
|
+
|
|
191
|
+
def remove(self, order: RestingOrder) -> None:
|
|
192
|
+
del self.orders[order.order_id]
|
|
193
|
+
self.side(order.side).remove(order)
|
|
194
|
+
|
|
195
|
+
def best_bid(self) -> int | None:
|
|
196
|
+
level = self.bids.best()
|
|
197
|
+
return None if level is None else level.price
|
|
198
|
+
|
|
199
|
+
def best_ask(self) -> int | None:
|
|
200
|
+
level = self.asks.best()
|
|
201
|
+
return None if level is None else level.price
|
|
202
|
+
|
|
203
|
+
def depth(self, levels: int | None = None) -> Depth:
|
|
204
|
+
"""L2 depth, at most ``levels`` per side (all levels when ``None``)."""
|
|
205
|
+
return Depth(bids=_aggregate(self.bids, levels), asks=_aggregate(self.asks, levels))
|
|
206
|
+
|
|
207
|
+
def entries(self, side: Side | None = None) -> Iterator[BookEntry]:
|
|
208
|
+
"""L3 view: resting orders in priority order, bids then asks (or one side)."""
|
|
209
|
+
for book_side in (self.bids, self.asks) if side is None else (self.side(side),):
|
|
210
|
+
for level in book_side:
|
|
211
|
+
for o in level:
|
|
212
|
+
yield BookEntry(o.order_id, o.account, o.side, o.price, o.remaining)
|
|
213
|
+
|
|
214
|
+
def __len__(self) -> int:
|
|
215
|
+
return len(self.orders)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _aggregate(side: BookSide, limit: int | None) -> list[DepthLevel]:
|
|
219
|
+
keys = side.keys if limit is None else side.keys.islice(0, limit)
|
|
220
|
+
levels = side.levels
|
|
221
|
+
return [DepthLevel(lvl.price, lvl.qty, lvl.count) for lvl in (levels[k] for k in keys)]
|
matching_engine/cli.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Command-line entry point: run the gateway, or verify a market's files offline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import msgspec
|
|
12
|
+
|
|
13
|
+
from matching_engine.journal import Journal
|
|
14
|
+
from matching_engine.snapshot import SnapshotError
|
|
15
|
+
from matching_engine.wal import WalCorruptionError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def serve(host: str, port: int, *, access_log: bool) -> None:
|
|
19
|
+
import uvicorn # noqa: PLC0415 - the gateway extra is optional for engine-only installs
|
|
20
|
+
|
|
21
|
+
from matching_engine.gateway import create_app # noqa: PLC0415
|
|
22
|
+
|
|
23
|
+
uvicorn.run(
|
|
24
|
+
create_app(),
|
|
25
|
+
host=host,
|
|
26
|
+
port=port,
|
|
27
|
+
log_level="info",
|
|
28
|
+
access_log=access_log,
|
|
29
|
+
http="httptools",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def verify(market_dir: Path) -> int:
|
|
34
|
+
"""Recover a market read-only and print what was found. Exit 1 on corruption."""
|
|
35
|
+
try:
|
|
36
|
+
engine, report = Journal(market_dir, fsync=False).recover(repair=False)
|
|
37
|
+
except (WalCorruptionError, SnapshotError) as exc:
|
|
38
|
+
print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
|
|
39
|
+
return 1
|
|
40
|
+
summary = {
|
|
41
|
+
"ok": True,
|
|
42
|
+
"report": msgspec.to_builtins(report),
|
|
43
|
+
"state_hash": engine.state_hash(),
|
|
44
|
+
"resting_orders": len(engine.book),
|
|
45
|
+
"best_bid": engine.book.best_bid(),
|
|
46
|
+
"best_ask": engine.book.best_ask(),
|
|
47
|
+
}
|
|
48
|
+
print(json.dumps(summary, indent=2))
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main(argv: list[str] | None = None) -> int:
|
|
53
|
+
parser = argparse.ArgumentParser(prog="matching-engine")
|
|
54
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
55
|
+
serve_cmd = commands.add_parser("serve", help="run the HTTP/WebSocket gateway")
|
|
56
|
+
serve_cmd.add_argument("--host", default="127.0.0.1")
|
|
57
|
+
serve_cmd.add_argument("--port", type=int, default=8000)
|
|
58
|
+
serve_cmd.add_argument(
|
|
59
|
+
"--access-log", action="store_true", help="log every request (costs throughput)"
|
|
60
|
+
)
|
|
61
|
+
verify_cmd = commands.add_parser("verify", help="check a market directory without repairing")
|
|
62
|
+
verify_cmd.add_argument("market_dir", type=Path)
|
|
63
|
+
args = parser.parse_args(argv)
|
|
64
|
+
|
|
65
|
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
|
66
|
+
if args.command == "serve":
|
|
67
|
+
serve(args.host, args.port, access_log=args.access_log)
|
|
68
|
+
return 0
|
|
69
|
+
return verify(args.market_dir)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
sys.exit(main())
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Order-entry vocabulary: the enums and commands the engine accepts.
|
|
2
|
+
|
|
3
|
+
Prices are integer *ticks* and quantities integer *lots*. Converting from the
|
|
4
|
+
human decimal form happens once, at the gateway boundary (see ``market.py``);
|
|
5
|
+
nothing past that point ever sees a float or a ``Decimal``.
|
|
6
|
+
|
|
7
|
+
Commands are frozen ``msgspec`` structs: immutable like a frozen dataclass,
|
|
8
|
+
but several times cheaper to construct, and they encode straight to JSON or
|
|
9
|
+
MessagePack without a hand-written serializer.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from enum import StrEnum
|
|
15
|
+
|
|
16
|
+
import msgspec
|
|
17
|
+
|
|
18
|
+
# Quantities and prices are packed as signed 64-bit integers in the WAL.
|
|
19
|
+
MAX_INT64 = (1 << 63) - 1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Side(StrEnum):
|
|
23
|
+
BUY = "buy"
|
|
24
|
+
SELL = "sell"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class OrderType(StrEnum):
|
|
28
|
+
LIMIT = "limit"
|
|
29
|
+
MARKET = "market"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TimeInForce(StrEnum):
|
|
33
|
+
GTC = "gtc" # good till cancelled: the remainder rests on the book
|
|
34
|
+
IOC = "ioc" # immediate or cancel: fill what crosses, cancel the rest
|
|
35
|
+
FOK = "fok" # fill or kill: fill completely at once, or not at all
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SelfTradePrevention(StrEnum):
|
|
39
|
+
"""What happens when an incoming order would trade with its own account."""
|
|
40
|
+
|
|
41
|
+
NONE = "none" # allow the self-trade
|
|
42
|
+
CANCEL_TAKER = "cancel_taker" # cancel the incoming remainder, keep the resting order
|
|
43
|
+
CANCEL_MAKER = "cancel_maker" # cancel the resting order and keep matching
|
|
44
|
+
CANCEL_BOTH = "cancel_both" # cancel both
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class NewOrder(msgspec.Struct, frozen=True, gc=False, tag="new"):
|
|
48
|
+
"""Place an order. ``price`` is ignored (and must be 0) for market orders."""
|
|
49
|
+
|
|
50
|
+
order_id: int
|
|
51
|
+
account: int
|
|
52
|
+
side: Side
|
|
53
|
+
price: int
|
|
54
|
+
qty: int
|
|
55
|
+
order_type: OrderType = OrderType.LIMIT
|
|
56
|
+
tif: TimeInForce = TimeInForce.GTC
|
|
57
|
+
post_only: bool = False
|
|
58
|
+
stp: SelfTradePrevention = SelfTradePrevention.CANCEL_TAKER
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class CancelOrder(msgspec.Struct, frozen=True, gc=False, tag="cancel"):
|
|
62
|
+
"""Cancel a resting order. Only the account that placed it may cancel it."""
|
|
63
|
+
|
|
64
|
+
order_id: int
|
|
65
|
+
account: int
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
type Command = NewOrder | CancelOrder
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class SequencedCommand(msgspec.Struct, frozen=True, gc=False):
|
|
72
|
+
"""A command stamped by the sequencer: the unit written to the WAL.
|
|
73
|
+
|
|
74
|
+
``seq`` is gap-free and strictly increasing per market; ``ts`` is wall-clock
|
|
75
|
+
nanoseconds taken by the sequencer, never by the engine, so replaying the
|
|
76
|
+
log reproduces every event bit for bit.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
seq: int
|
|
80
|
+
ts: int
|
|
81
|
+
command: Command
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""The matching engine for one market.
|
|
2
|
+
|
|
3
|
+
Single-threaded and deterministic by construction: no clock, no randomness,
|
|
4
|
+
no I/O. Its only input is a :class:`SequencedCommand` and its only output is
|
|
5
|
+
the list of events that command caused, so the same log replayed into a fresh
|
|
6
|
+
engine produces the same events and the same book, every time.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import struct
|
|
13
|
+
|
|
14
|
+
import msgspec
|
|
15
|
+
|
|
16
|
+
from matching_engine.book import BookEntry, BookSide, OrderBook, RestingOrder
|
|
17
|
+
from matching_engine.domain import (
|
|
18
|
+
MAX_INT64,
|
|
19
|
+
CancelOrder,
|
|
20
|
+
NewOrder,
|
|
21
|
+
OrderType,
|
|
22
|
+
SelfTradePrevention,
|
|
23
|
+
SequencedCommand,
|
|
24
|
+
Side,
|
|
25
|
+
TimeInForce,
|
|
26
|
+
)
|
|
27
|
+
from matching_engine.events import (
|
|
28
|
+
CancelReason,
|
|
29
|
+
Event,
|
|
30
|
+
OrderAccepted,
|
|
31
|
+
OrderCancelled,
|
|
32
|
+
OrderRejected,
|
|
33
|
+
RejectReason,
|
|
34
|
+
Trade,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# A market order crosses every level: compare its "limit key" as +infinity.
|
|
38
|
+
_NO_LIMIT = MAX_INT64
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_HASH_COUNTERS = struct.Struct("<QQ")
|
|
42
|
+
_HASH_ORDER = struct.Struct("<QQ?qq")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SequenceError(ValueError):
|
|
46
|
+
"""A command arrived with a sequence number that is not the next one."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class EngineState(msgspec.Struct, frozen=True):
|
|
50
|
+
"""Everything needed to rebuild an engine: counters plus the book in priority order."""
|
|
51
|
+
|
|
52
|
+
last_seq: int
|
|
53
|
+
next_trade_id: int
|
|
54
|
+
orders: list[BookEntry]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class MatchingEngine:
|
|
58
|
+
__slots__ = ("book", "last_seq", "next_trade_id")
|
|
59
|
+
|
|
60
|
+
def __init__(self) -> None:
|
|
61
|
+
self.book = OrderBook()
|
|
62
|
+
self.last_seq = 0
|
|
63
|
+
self.next_trade_id = 1
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def restore(cls, state: EngineState) -> MatchingEngine:
|
|
67
|
+
"""Rebuild an engine from :meth:`export_state`, queue positions included.
|
|
68
|
+
|
|
69
|
+
Entries arrive best level first and oldest first within a level, so
|
|
70
|
+
appending them in order recreates every FIFO queue exactly.
|
|
71
|
+
"""
|
|
72
|
+
engine = cls()
|
|
73
|
+
engine.last_seq = state.last_seq
|
|
74
|
+
engine.next_trade_id = state.next_trade_id
|
|
75
|
+
add = engine.book.add
|
|
76
|
+
for e in state.orders:
|
|
77
|
+
add(RestingOrder(e.order_id, e.account, e.side, e.price, e.qty))
|
|
78
|
+
return engine
|
|
79
|
+
|
|
80
|
+
def export_state(self) -> EngineState:
|
|
81
|
+
return EngineState(self.last_seq, self.next_trade_id, list(self.book.entries()))
|
|
82
|
+
|
|
83
|
+
def state_hash(self) -> str:
|
|
84
|
+
"""A fingerprint of the full engine state, queue order included.
|
|
85
|
+
|
|
86
|
+
Two engines with the same hash hold the same orders at the same queue
|
|
87
|
+
positions and will react identically to any future command, which is
|
|
88
|
+
what the replay and recovery tests compare.
|
|
89
|
+
"""
|
|
90
|
+
digest = hashlib.blake2b(
|
|
91
|
+
_HASH_COUNTERS.pack(self.last_seq, self.next_trade_id), digest_size=32
|
|
92
|
+
)
|
|
93
|
+
pack = _HASH_ORDER.pack
|
|
94
|
+
for e in self.book.entries():
|
|
95
|
+
digest.update(pack(e.order_id, e.account, e.side is Side.BUY, e.price, e.qty))
|
|
96
|
+
return digest.hexdigest()
|
|
97
|
+
|
|
98
|
+
def process(self, sc: SequencedCommand) -> list[Event]:
|
|
99
|
+
"""Apply one command and return everything it caused, in order."""
|
|
100
|
+
seq = sc.seq
|
|
101
|
+
if seq <= self.last_seq:
|
|
102
|
+
raise SequenceError(f"seq {seq} is not after {self.last_seq}")
|
|
103
|
+
self.last_seq = seq
|
|
104
|
+
cmd = sc.command
|
|
105
|
+
if type(cmd) is NewOrder:
|
|
106
|
+
return self._new_order(cmd, seq, sc.ts)
|
|
107
|
+
assert type(cmd) is CancelOrder
|
|
108
|
+
return self._cancel(cmd, seq, sc.ts)
|
|
109
|
+
|
|
110
|
+
def _new_order(self, o: NewOrder, seq: int, ts: int) -> list[Event]:
|
|
111
|
+
reason = self._validate(o)
|
|
112
|
+
if reason is not None:
|
|
113
|
+
return [OrderRejected(seq, ts, o.order_id, o.account, reason)]
|
|
114
|
+
|
|
115
|
+
opposite = self.book.opposite(o.side)
|
|
116
|
+
limit_key = _NO_LIMIT if o.order_type is OrderType.MARKET else opposite.key(o.price)
|
|
117
|
+
if o.post_only:
|
|
118
|
+
if opposite.keys and opposite.keys[0] <= limit_key:
|
|
119
|
+
reason = RejectReason.POST_ONLY_WOULD_CROSS
|
|
120
|
+
elif o.tif is TimeInForce.FOK and not self._can_fill(o, opposite, limit_key):
|
|
121
|
+
reason = RejectReason.FOK_NOT_FILLABLE
|
|
122
|
+
if reason is not None:
|
|
123
|
+
return [OrderRejected(seq, ts, o.order_id, o.account, reason)]
|
|
124
|
+
|
|
125
|
+
events: list[Event] = [
|
|
126
|
+
OrderAccepted(
|
|
127
|
+
seq, ts, o.order_id, o.account, o.side, o.order_type, o.tif, o.price, o.qty
|
|
128
|
+
)
|
|
129
|
+
]
|
|
130
|
+
remaining = self._match(o, opposite, limit_key, events, seq, ts)
|
|
131
|
+
if remaining:
|
|
132
|
+
if o.order_type is OrderType.LIMIT and o.tif is TimeInForce.GTC:
|
|
133
|
+
self.book.add(RestingOrder(o.order_id, o.account, o.side, o.price, remaining))
|
|
134
|
+
else:
|
|
135
|
+
events.append(
|
|
136
|
+
OrderCancelled(seq, ts, o.order_id, o.account, remaining, CancelReason.UNFILLED)
|
|
137
|
+
)
|
|
138
|
+
return events
|
|
139
|
+
|
|
140
|
+
def _validate(self, o: NewOrder) -> RejectReason | None:
|
|
141
|
+
if not 0 < o.qty <= MAX_INT64:
|
|
142
|
+
return RejectReason.INVALID_QUANTITY
|
|
143
|
+
if o.order_type is OrderType.MARKET:
|
|
144
|
+
if o.price != 0:
|
|
145
|
+
return RejectReason.INVALID_PRICE
|
|
146
|
+
if o.tif is TimeInForce.GTC: # nothing to rest at: market means IOC or FOK
|
|
147
|
+
return RejectReason.INVALID_TIME_IN_FORCE
|
|
148
|
+
elif not 0 < o.price <= MAX_INT64:
|
|
149
|
+
return RejectReason.INVALID_PRICE
|
|
150
|
+
if o.post_only and o.tif is not TimeInForce.GTC: # a maker-only order must rest
|
|
151
|
+
return RejectReason.INVALID_TIME_IN_FORCE
|
|
152
|
+
if o.order_id in self.book.orders:
|
|
153
|
+
return RejectReason.DUPLICATE_ORDER_ID
|
|
154
|
+
return None
|
|
155
|
+
|
|
156
|
+
def _can_fill(self, o: NewOrder, opposite: BookSide, limit_key: int) -> bool:
|
|
157
|
+
"""Whether ``o`` would fill completely right now. Reads, never mutates.
|
|
158
|
+
|
|
159
|
+
FOK must be all-or-nothing, so it is decided before the first fill
|
|
160
|
+
rather than by unwinding trades afterwards. The walk mirrors what
|
|
161
|
+
``_match`` would do with the same order's self-trade policy: an own
|
|
162
|
+
order either stops matching or is skipped (it would be cancelled).
|
|
163
|
+
"""
|
|
164
|
+
needed = o.qty
|
|
165
|
+
stp, account = o.stp, o.account
|
|
166
|
+
levels = opposite.levels
|
|
167
|
+
for key in opposite.keys:
|
|
168
|
+
if key > limit_key:
|
|
169
|
+
return False
|
|
170
|
+
level = levels[key]
|
|
171
|
+
if stp is SelfTradePrevention.NONE:
|
|
172
|
+
needed -= level.qty
|
|
173
|
+
else:
|
|
174
|
+
for maker in level:
|
|
175
|
+
if maker.account != account:
|
|
176
|
+
needed -= maker.remaining
|
|
177
|
+
elif stp is not SelfTradePrevention.CANCEL_MAKER:
|
|
178
|
+
return False
|
|
179
|
+
if needed <= 0:
|
|
180
|
+
return True
|
|
181
|
+
if needed <= 0:
|
|
182
|
+
return True
|
|
183
|
+
return False
|
|
184
|
+
|
|
185
|
+
def _match(
|
|
186
|
+
self,
|
|
187
|
+
o: NewOrder,
|
|
188
|
+
opposite: BookSide,
|
|
189
|
+
limit_key: int,
|
|
190
|
+
events: list[Event],
|
|
191
|
+
seq: int,
|
|
192
|
+
ts: int,
|
|
193
|
+
) -> int:
|
|
194
|
+
"""Cross ``o`` against the opposite side; return what is left to handle.
|
|
195
|
+
|
|
196
|
+
Always takes the head of the best level: price priority from the
|
|
197
|
+
sorted keys, time priority from the FIFO queue. Fills print at the
|
|
198
|
+
maker's price, so an aggressive limit gets price improvement.
|
|
199
|
+
|
|
200
|
+
When self-trade prevention cancels the taker, the cancel event is
|
|
201
|
+
emitted here and 0 is returned: there is nothing left to rest.
|
|
202
|
+
"""
|
|
203
|
+
book = self.book
|
|
204
|
+
keys, levels = opposite.keys, opposite.levels
|
|
205
|
+
account, stp = o.account, o.stp
|
|
206
|
+
remaining = o.qty
|
|
207
|
+
while remaining and keys:
|
|
208
|
+
key = keys[0]
|
|
209
|
+
if key > limit_key:
|
|
210
|
+
break
|
|
211
|
+
level = levels[key]
|
|
212
|
+
maker = level.head
|
|
213
|
+
assert maker is not None # empty levels are removed eagerly
|
|
214
|
+
if maker.account == account and stp is not SelfTradePrevention.NONE:
|
|
215
|
+
if stp is not SelfTradePrevention.CANCEL_TAKER:
|
|
216
|
+
book.remove(maker)
|
|
217
|
+
events.append(
|
|
218
|
+
OrderCancelled(
|
|
219
|
+
seq,
|
|
220
|
+
ts,
|
|
221
|
+
maker.order_id,
|
|
222
|
+
maker.account,
|
|
223
|
+
maker.remaining,
|
|
224
|
+
CancelReason.SELF_TRADE,
|
|
225
|
+
)
|
|
226
|
+
)
|
|
227
|
+
if stp is SelfTradePrevention.CANCEL_MAKER:
|
|
228
|
+
continue
|
|
229
|
+
events.append(
|
|
230
|
+
OrderCancelled(seq, ts, o.order_id, account, remaining, CancelReason.SELF_TRADE)
|
|
231
|
+
)
|
|
232
|
+
return 0
|
|
233
|
+
|
|
234
|
+
fill = remaining if remaining < maker.remaining else maker.remaining
|
|
235
|
+
remaining -= fill
|
|
236
|
+
maker.remaining -= fill
|
|
237
|
+
level.qty -= fill
|
|
238
|
+
trade_id = self.next_trade_id
|
|
239
|
+
self.next_trade_id = trade_id + 1
|
|
240
|
+
events.append(
|
|
241
|
+
Trade(
|
|
242
|
+
seq,
|
|
243
|
+
ts,
|
|
244
|
+
trade_id,
|
|
245
|
+
level.price,
|
|
246
|
+
fill,
|
|
247
|
+
o.side,
|
|
248
|
+
o.order_id,
|
|
249
|
+
account,
|
|
250
|
+
maker.order_id,
|
|
251
|
+
maker.account,
|
|
252
|
+
maker.remaining,
|
|
253
|
+
remaining,
|
|
254
|
+
)
|
|
255
|
+
)
|
|
256
|
+
if maker.remaining == 0:
|
|
257
|
+
book.remove(maker)
|
|
258
|
+
return remaining
|
|
259
|
+
|
|
260
|
+
def _cancel(self, c: CancelOrder, seq: int, ts: int) -> list[Event]:
|
|
261
|
+
order = self.book.orders.get(c.order_id)
|
|
262
|
+
if order is None:
|
|
263
|
+
return [OrderRejected(seq, ts, c.order_id, c.account, RejectReason.UNKNOWN_ORDER)]
|
|
264
|
+
if order.account != c.account:
|
|
265
|
+
return [OrderRejected(seq, ts, c.order_id, c.account, RejectReason.NOT_ORDER_OWNER)]
|
|
266
|
+
self.book.remove(order)
|
|
267
|
+
return [
|
|
268
|
+
OrderCancelled(
|
|
269
|
+
seq, ts, order.order_id, order.account, order.remaining, CancelReason.USER
|
|
270
|
+
)
|
|
271
|
+
]
|