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,81 @@
|
|
|
1
|
+
"""The engine's output: an ordered stream of immutable events.
|
|
2
|
+
|
|
3
|
+
Every event carries the ``seq`` and ``ts`` of the command that caused it, so a
|
|
4
|
+
consumer can line events up with the WAL and deduplicate after a reconnect.
|
|
5
|
+
The event list returned for one command is the complete, ordered effect of
|
|
6
|
+
that command; nothing about the book changes that is not in it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
import msgspec
|
|
14
|
+
|
|
15
|
+
from matching_engine.domain import OrderType, Side, TimeInForce
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RejectReason(StrEnum):
|
|
19
|
+
INVALID_QUANTITY = "invalid_quantity"
|
|
20
|
+
INVALID_PRICE = "invalid_price"
|
|
21
|
+
INVALID_TIME_IN_FORCE = "invalid_time_in_force"
|
|
22
|
+
DUPLICATE_ORDER_ID = "duplicate_order_id"
|
|
23
|
+
FOK_NOT_FILLABLE = "fok_not_fillable"
|
|
24
|
+
POST_ONLY_WOULD_CROSS = "post_only_would_cross"
|
|
25
|
+
UNKNOWN_ORDER = "unknown_order"
|
|
26
|
+
NOT_ORDER_OWNER = "not_order_owner"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CancelReason(StrEnum):
|
|
30
|
+
USER = "user" # an explicit CancelOrder
|
|
31
|
+
UNFILLED = "unfilled" # IOC or market remainder with nothing left to cross
|
|
32
|
+
SELF_TRADE = "self_trade" # removed by self-trade prevention
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class OrderAccepted(msgspec.Struct, frozen=True, gc=False, tag="order_accepted"):
|
|
36
|
+
seq: int
|
|
37
|
+
ts: int
|
|
38
|
+
order_id: int
|
|
39
|
+
account: int
|
|
40
|
+
side: Side
|
|
41
|
+
order_type: OrderType
|
|
42
|
+
tif: TimeInForce
|
|
43
|
+
price: int
|
|
44
|
+
qty: int
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Trade(msgspec.Struct, frozen=True, gc=False, tag="trade"):
|
|
48
|
+
"""A fill. Always at the maker's (resting) price."""
|
|
49
|
+
|
|
50
|
+
seq: int
|
|
51
|
+
ts: int
|
|
52
|
+
trade_id: int
|
|
53
|
+
price: int
|
|
54
|
+
qty: int
|
|
55
|
+
taker_side: Side
|
|
56
|
+
taker_order_id: int
|
|
57
|
+
taker_account: int
|
|
58
|
+
maker_order_id: int
|
|
59
|
+
maker_account: int
|
|
60
|
+
maker_remaining: int
|
|
61
|
+
taker_remaining: int
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class OrderCancelled(msgspec.Struct, frozen=True, gc=False, tag="order_cancelled"):
|
|
65
|
+
seq: int
|
|
66
|
+
ts: int
|
|
67
|
+
order_id: int
|
|
68
|
+
account: int
|
|
69
|
+
remaining: int
|
|
70
|
+
reason: CancelReason
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class OrderRejected(msgspec.Struct, frozen=True, gc=False, tag="order_rejected"):
|
|
74
|
+
seq: int
|
|
75
|
+
ts: int
|
|
76
|
+
order_id: int
|
|
77
|
+
account: int
|
|
78
|
+
reason: RejectReason
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
type Event = OrderAccepted | Trade | OrderCancelled | OrderRejected
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""FastAPI application: REST order entry, book views and a WebSocket feed per market."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import itertools
|
|
7
|
+
from collections.abc import AsyncIterator
|
|
8
|
+
from contextlib import asynccontextmanager
|
|
9
|
+
from typing import Annotated
|
|
10
|
+
|
|
11
|
+
import msgspec
|
|
12
|
+
from fastapi import APIRouter, FastAPI, HTTPException, Path, Query, Request, WebSocket, status
|
|
13
|
+
|
|
14
|
+
from matching_engine import __version__
|
|
15
|
+
from matching_engine.domain import MAX_INT64, CancelOrder, Side
|
|
16
|
+
from matching_engine.events import OrderCancelled
|
|
17
|
+
from matching_engine.gateway.config import Settings
|
|
18
|
+
from matching_engine.gateway.marketdata import MarketDataHub, Subscriber
|
|
19
|
+
from matching_engine.gateway.schemas import (
|
|
20
|
+
BookOrder,
|
|
21
|
+
BookResponse,
|
|
22
|
+
CancelResponse,
|
|
23
|
+
DepthResponse,
|
|
24
|
+
MarketInfo,
|
|
25
|
+
OrderRequest,
|
|
26
|
+
OrderResponse,
|
|
27
|
+
order_outcome,
|
|
28
|
+
render_depth,
|
|
29
|
+
render_event,
|
|
30
|
+
)
|
|
31
|
+
from matching_engine.gateway.worker import MarketUnavailableError, MarketWorker
|
|
32
|
+
from matching_engine.journal import Journal
|
|
33
|
+
|
|
34
|
+
Symbol = Annotated[str, Path(description="Market symbol, e.g. BTC-USDT")]
|
|
35
|
+
|
|
36
|
+
router = APIRouter()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def create_app(settings: Settings | None = None) -> FastAPI:
|
|
40
|
+
settings = settings or Settings.from_env()
|
|
41
|
+
|
|
42
|
+
@asynccontextmanager
|
|
43
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
44
|
+
workers = open_markets(settings)
|
|
45
|
+
for worker in workers.values():
|
|
46
|
+
worker.start()
|
|
47
|
+
app.state.workers = workers
|
|
48
|
+
try:
|
|
49
|
+
yield
|
|
50
|
+
finally:
|
|
51
|
+
for worker in workers.values():
|
|
52
|
+
await worker.stop()
|
|
53
|
+
|
|
54
|
+
app = FastAPI(
|
|
55
|
+
title="Matching Engine Gateway",
|
|
56
|
+
version=__version__,
|
|
57
|
+
summary="Price-time priority order entry and market data.",
|
|
58
|
+
lifespan=lifespan,
|
|
59
|
+
)
|
|
60
|
+
app.include_router(router)
|
|
61
|
+
return app
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def open_markets(settings: Settings) -> dict[str, MarketWorker]:
|
|
65
|
+
"""Recover every configured market from its own directory."""
|
|
66
|
+
workers = {}
|
|
67
|
+
for spec in settings.markets:
|
|
68
|
+
journal = Journal(settings.data_dir / spec.symbol, fsync=settings.fsync)
|
|
69
|
+
engine, report = journal.recover()
|
|
70
|
+
hub = MarketDataHub(
|
|
71
|
+
spec, depth_levels=settings.depth_levels, subscriber_queue=settings.subscriber_queue
|
|
72
|
+
)
|
|
73
|
+
workers[spec.symbol] = MarketWorker(
|
|
74
|
+
spec,
|
|
75
|
+
journal,
|
|
76
|
+
engine,
|
|
77
|
+
report,
|
|
78
|
+
hub,
|
|
79
|
+
batch_max=settings.batch_max,
|
|
80
|
+
queue_max=settings.queue_max,
|
|
81
|
+
snapshot_every=settings.snapshot_every,
|
|
82
|
+
)
|
|
83
|
+
return workers
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _market(request: Request, symbol: str) -> MarketWorker:
|
|
87
|
+
worker: MarketWorker | None = request.app.state.workers.get(symbol)
|
|
88
|
+
if worker is None:
|
|
89
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, f"unknown market {symbol}")
|
|
90
|
+
return worker
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@router.get("/healthz")
|
|
94
|
+
async def health(request: Request) -> dict[str, str]:
|
|
95
|
+
failed = [s for s, w in request.app.state.workers.items() if w.failure is not None]
|
|
96
|
+
if failed:
|
|
97
|
+
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, f"failed: {failed}")
|
|
98
|
+
return {"status": "ok"}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@router.get("/markets")
|
|
102
|
+
async def list_markets(request: Request) -> list[MarketInfo]:
|
|
103
|
+
infos = []
|
|
104
|
+
for worker in request.app.state.workers.values():
|
|
105
|
+
spec, book = worker.spec, worker.engine.book
|
|
106
|
+
bid, ask = book.best_bid(), book.best_ask()
|
|
107
|
+
infos.append(
|
|
108
|
+
MarketInfo(
|
|
109
|
+
symbol=spec.symbol,
|
|
110
|
+
tick_size=str(spec.tick_size),
|
|
111
|
+
lot_size=str(spec.lot_size),
|
|
112
|
+
last_seq=worker.engine.last_seq,
|
|
113
|
+
best_bid=None if bid is None else spec.price(bid),
|
|
114
|
+
best_ask=None if ask is None else spec.price(ask),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
return infos
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@router.post("/markets/{symbol}/orders")
|
|
121
|
+
async def place_order(request: Request, symbol: Symbol, body: OrderRequest) -> OrderResponse:
|
|
122
|
+
worker = _market(request, symbol)
|
|
123
|
+
try:
|
|
124
|
+
template = body.to_command(worker.spec, order_id=0)
|
|
125
|
+
except ValueError as exc:
|
|
126
|
+
raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, str(exc)) from exc
|
|
127
|
+
try:
|
|
128
|
+
# The order id is the sequence number, assigned inside the worker.
|
|
129
|
+
sc, events = await worker.submit(
|
|
130
|
+
lambda seq: msgspec.structs.replace(template, order_id=seq)
|
|
131
|
+
)
|
|
132
|
+
except MarketUnavailableError as exc:
|
|
133
|
+
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from exc
|
|
134
|
+
order = msgspec.structs.replace(template, order_id=sc.seq)
|
|
135
|
+
outcome, filled = order_outcome(order, events)
|
|
136
|
+
return OrderResponse(
|
|
137
|
+
order_id=order.order_id,
|
|
138
|
+
seq=sc.seq,
|
|
139
|
+
status=outcome,
|
|
140
|
+
filled_quantity=worker.spec.qty(filled),
|
|
141
|
+
events=[render_event(worker.spec, e) for e in events],
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@router.delete("/markets/{symbol}/orders/{order_id}")
|
|
146
|
+
async def cancel_order(
|
|
147
|
+
request: Request,
|
|
148
|
+
symbol: Symbol,
|
|
149
|
+
order_id: Annotated[int, Path(ge=1, le=MAX_INT64)],
|
|
150
|
+
account: Annotated[int, Query(ge=1, le=MAX_INT64)],
|
|
151
|
+
) -> CancelResponse:
|
|
152
|
+
worker = _market(request, symbol)
|
|
153
|
+
try:
|
|
154
|
+
sc, events = await worker.submit(lambda _seq: CancelOrder(order_id, account))
|
|
155
|
+
except MarketUnavailableError as exc:
|
|
156
|
+
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, str(exc)) from exc
|
|
157
|
+
cancelled = any(isinstance(e, OrderCancelled) for e in events)
|
|
158
|
+
return CancelResponse(
|
|
159
|
+
order_id=order_id,
|
|
160
|
+
seq=sc.seq,
|
|
161
|
+
status="cancelled" if cancelled else "rejected",
|
|
162
|
+
events=[render_event(worker.spec, e) for e in events],
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@router.get("/markets/{symbol}/depth")
|
|
167
|
+
async def depth(
|
|
168
|
+
request: Request, symbol: Symbol, levels: Annotated[int, Query(ge=1, le=1_000)] = 20
|
|
169
|
+
) -> DepthResponse:
|
|
170
|
+
worker = _market(request, symbol)
|
|
171
|
+
return render_depth(worker.spec, worker.engine.last_seq, worker.engine.book.depth(levels))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@router.get("/markets/{symbol}/book")
|
|
175
|
+
async def book(
|
|
176
|
+
request: Request, symbol: Symbol, limit: Annotated[int, Query(ge=1, le=10_000)] = 1_000
|
|
177
|
+
) -> BookResponse:
|
|
178
|
+
"""L3: resting orders in priority order, up to ``limit`` per side. Accounts stay private."""
|
|
179
|
+
worker = _market(request, symbol)
|
|
180
|
+
spec, entries = worker.spec, worker.engine.book.entries
|
|
181
|
+
orders = [
|
|
182
|
+
BookOrder(
|
|
183
|
+
order_id=e.order_id, side=e.side, price=spec.price(e.price), quantity=spec.qty(e.qty)
|
|
184
|
+
)
|
|
185
|
+
for side in Side
|
|
186
|
+
for e in itertools.islice(entries(side), limit)
|
|
187
|
+
]
|
|
188
|
+
return BookResponse(symbol=spec.symbol, seq=worker.engine.last_seq, orders=orders)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@router.websocket("/markets/{symbol}/ws")
|
|
192
|
+
async def feed(ws: WebSocket, symbol: str) -> None:
|
|
193
|
+
"""Depth snapshot on connect, then trades and depth changes as they happen."""
|
|
194
|
+
worker: MarketWorker | None = ws.app.state.workers.get(symbol)
|
|
195
|
+
if worker is None:
|
|
196
|
+
await ws.close(code=status.WS_1008_POLICY_VIOLATION, reason=f"unknown market {symbol}")
|
|
197
|
+
return
|
|
198
|
+
await ws.accept()
|
|
199
|
+
subscriber, snapshot = worker.hub.subscribe(worker.engine)
|
|
200
|
+
try:
|
|
201
|
+
await ws.send_text(snapshot)
|
|
202
|
+
pump = asyncio.create_task(_pump(ws, subscriber))
|
|
203
|
+
hangup = asyncio.create_task(_wait_for_disconnect(ws))
|
|
204
|
+
_, pending = await asyncio.wait({pump, hangup}, return_when=asyncio.FIRST_COMPLETED)
|
|
205
|
+
for task in pending:
|
|
206
|
+
task.cancel()
|
|
207
|
+
finally:
|
|
208
|
+
worker.hub.unsubscribe(subscriber)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
async def _pump(ws: WebSocket, subscriber: Subscriber) -> None:
|
|
212
|
+
while (message := await subscriber.queue.get()) is not None:
|
|
213
|
+
await ws.send_text(message)
|
|
214
|
+
# The hub dropped us for falling behind: say so, and let the client resync.
|
|
215
|
+
await ws.close(code=status.WS_1013_TRY_AGAIN_LATER, reason="subscriber too slow")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def _wait_for_disconnect(ws: WebSocket) -> None:
|
|
219
|
+
"""The feed is one-way; anything the client sends is ignored until it leaves."""
|
|
220
|
+
while (await ws.receive())["type"] != "websocket.disconnect":
|
|
221
|
+
pass
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Gateway settings, read from ``ME_*`` environment variables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from matching_engine.market import MarketSpec
|
|
11
|
+
|
|
12
|
+
DEFAULT_MARKETS = "BTC-USDT:0.01:0.00001,ETH-USDT:0.01:0.0001"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Settings:
|
|
17
|
+
data_dir: Path = Path("data")
|
|
18
|
+
markets: tuple[MarketSpec, ...] = tuple(MarketSpec.parse(m) for m in DEFAULT_MARKETS.split(","))
|
|
19
|
+
fsync: bool = True
|
|
20
|
+
batch_max: int = 512 # commands per group commit
|
|
21
|
+
queue_max: int = 10_000 # pending commands per market before new ones get 503
|
|
22
|
+
snapshot_every: int = 100_000 # commands between checkpoints
|
|
23
|
+
depth_levels: int = 20 # L2 levels pushed to WebSocket subscribers
|
|
24
|
+
subscriber_queue: int = 1_000 # messages buffered per subscriber before it is dropped
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def from_env(cls, env: Mapping[str, str] = os.environ) -> Settings:
|
|
28
|
+
defaults = cls()
|
|
29
|
+
markets = env.get("ME_MARKETS")
|
|
30
|
+
return cls(
|
|
31
|
+
data_dir=Path(env.get("ME_DATA_DIR", str(defaults.data_dir))),
|
|
32
|
+
markets=(
|
|
33
|
+
tuple(MarketSpec.parse(m) for m in markets.split(",") if m.strip())
|
|
34
|
+
if markets
|
|
35
|
+
else defaults.markets
|
|
36
|
+
),
|
|
37
|
+
fsync=env.get("ME_FSYNC", "1").lower() not in {"0", "false", "no", "off"},
|
|
38
|
+
batch_max=int(env.get("ME_BATCH_MAX", defaults.batch_max)),
|
|
39
|
+
queue_max=int(env.get("ME_QUEUE_MAX", defaults.queue_max)),
|
|
40
|
+
snapshot_every=int(env.get("ME_SNAPSHOT_EVERY", defaults.snapshot_every)),
|
|
41
|
+
depth_levels=int(env.get("ME_DEPTH_LEVELS", defaults.depth_levels)),
|
|
42
|
+
subscriber_queue=int(env.get("ME_SUBSCRIBER_QUEUE", defaults.subscriber_queue)),
|
|
43
|
+
)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Public market data fan-out: trades and L2 depth for WebSocket subscribers.
|
|
2
|
+
|
|
3
|
+
The matching loop must never wait for a reader. Each subscriber gets a
|
|
4
|
+
bounded queue; publishing is ``put_nowait``, and a subscriber whose queue is
|
|
5
|
+
full is disconnected rather than allowed to slow the market down or grow
|
|
6
|
+
memory without bound. A client that reconnects gets a fresh depth snapshot,
|
|
7
|
+
which is always a correct place to resume from.
|
|
8
|
+
|
|
9
|
+
Depth is pushed as a full top-``n`` snapshot after any batch that changed it.
|
|
10
|
+
That costs more bandwidth than incremental deltas, but a client can never
|
|
11
|
+
apply one out of order or miss one and drift.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
|
|
19
|
+
import msgspec
|
|
20
|
+
|
|
21
|
+
from matching_engine.book import Depth, DepthLevel
|
|
22
|
+
from matching_engine.engine import MatchingEngine
|
|
23
|
+
from matching_engine.events import Event, Trade
|
|
24
|
+
from matching_engine.market import MarketSpec
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Subscriber:
|
|
28
|
+
__slots__ = ("queue",)
|
|
29
|
+
|
|
30
|
+
def __init__(self, maxsize: int) -> None:
|
|
31
|
+
# ``None`` is the hang-up sentinel: the hub dropped this subscriber.
|
|
32
|
+
self.queue: asyncio.Queue[str | None] = asyncio.Queue(maxsize + 1)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class MarketDataHub:
|
|
36
|
+
def __init__(self, spec: MarketSpec, *, depth_levels: int, subscriber_queue: int) -> None:
|
|
37
|
+
self.spec = spec
|
|
38
|
+
self._depth_levels = depth_levels
|
|
39
|
+
self._subscriber_queue = subscriber_queue
|
|
40
|
+
self._subscribers: set[Subscriber] = set()
|
|
41
|
+
self._last_depth: Depth | None = None
|
|
42
|
+
self.dropped = 0 # subscribers disconnected for falling behind
|
|
43
|
+
|
|
44
|
+
def subscribe(self, engine: MatchingEngine) -> tuple[Subscriber, str]:
|
|
45
|
+
"""Register a subscriber and return the depth snapshot to send it first."""
|
|
46
|
+
subscriber = Subscriber(self._subscriber_queue)
|
|
47
|
+
self._subscribers.add(subscriber)
|
|
48
|
+
depth = engine.book.depth(self._depth_levels)
|
|
49
|
+
self._last_depth = depth
|
|
50
|
+
return subscriber, self._depth_message(engine.last_seq, depth)
|
|
51
|
+
|
|
52
|
+
def unsubscribe(self, subscriber: Subscriber) -> None:
|
|
53
|
+
self._subscribers.discard(subscriber)
|
|
54
|
+
|
|
55
|
+
def publish(self, events: Iterable[Event], engine: MatchingEngine) -> None:
|
|
56
|
+
"""Push one batch's trades, then the new depth if it changed."""
|
|
57
|
+
if not self._subscribers:
|
|
58
|
+
return
|
|
59
|
+
spec = self.spec
|
|
60
|
+
for e in events:
|
|
61
|
+
if type(e) is Trade:
|
|
62
|
+
trade = {
|
|
63
|
+
"type": "trade",
|
|
64
|
+
"symbol": spec.symbol,
|
|
65
|
+
"seq": e.seq,
|
|
66
|
+
"ts": e.ts,
|
|
67
|
+
"trade_id": e.trade_id,
|
|
68
|
+
"price": spec.price(e.price),
|
|
69
|
+
"qty": spec.qty(e.qty),
|
|
70
|
+
"taker_side": e.taker_side,
|
|
71
|
+
}
|
|
72
|
+
self._broadcast(msgspec.json.encode(trade).decode())
|
|
73
|
+
depth = engine.book.depth(self._depth_levels)
|
|
74
|
+
if depth != self._last_depth:
|
|
75
|
+
self._last_depth = depth
|
|
76
|
+
self._broadcast(self._depth_message(engine.last_seq, depth))
|
|
77
|
+
|
|
78
|
+
def _depth_message(self, seq: int, depth: Depth) -> str:
|
|
79
|
+
spec = self.spec
|
|
80
|
+
|
|
81
|
+
def side(levels: list[DepthLevel]) -> list[list[object]]:
|
|
82
|
+
return [[spec.price(lvl.price), spec.qty(lvl.qty), lvl.orders] for lvl in levels]
|
|
83
|
+
|
|
84
|
+
message = {
|
|
85
|
+
"type": "depth",
|
|
86
|
+
"symbol": spec.symbol,
|
|
87
|
+
"seq": seq,
|
|
88
|
+
"bids": side(depth.bids),
|
|
89
|
+
"asks": side(depth.asks),
|
|
90
|
+
}
|
|
91
|
+
return msgspec.json.encode(message).decode()
|
|
92
|
+
|
|
93
|
+
def _broadcast(self, message: str) -> None:
|
|
94
|
+
for subscriber in list(self._subscribers):
|
|
95
|
+
queue = subscriber.queue
|
|
96
|
+
if queue.qsize() >= self._subscriber_queue:
|
|
97
|
+
self._drop(subscriber)
|
|
98
|
+
else:
|
|
99
|
+
queue.put_nowait(message)
|
|
100
|
+
|
|
101
|
+
def _drop(self, subscriber: Subscriber) -> None:
|
|
102
|
+
self._subscribers.discard(subscriber)
|
|
103
|
+
self.dropped += 1
|
|
104
|
+
subscriber.queue.put_nowait(None) # the spare slot reserved for exactly this
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Wire formats: request validation and rendering integers back into decimals.
|
|
2
|
+
|
|
3
|
+
Prices and quantities cross the wire as decimal *strings* in both directions.
|
|
4
|
+
JSON numbers are binary floats in most client libraries, and a price that
|
|
5
|
+
arrives as ``0.30000000000000004`` is exactly the bug integer ticks exist to
|
|
6
|
+
prevent.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from decimal import Decimal
|
|
12
|
+
from typing import Any, Literal
|
|
13
|
+
|
|
14
|
+
import msgspec
|
|
15
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
16
|
+
|
|
17
|
+
from matching_engine.book import Depth
|
|
18
|
+
from matching_engine.domain import (
|
|
19
|
+
MAX_INT64,
|
|
20
|
+
NewOrder,
|
|
21
|
+
OrderType,
|
|
22
|
+
SelfTradePrevention,
|
|
23
|
+
Side,
|
|
24
|
+
TimeInForce,
|
|
25
|
+
)
|
|
26
|
+
from matching_engine.events import Event, OrderCancelled, OrderRejected, Trade
|
|
27
|
+
from matching_engine.market import MarketSpec
|
|
28
|
+
|
|
29
|
+
_PRICE_FIELDS = frozenset({"price"})
|
|
30
|
+
_QTY_FIELDS = frozenset({"qty", "remaining", "maker_remaining", "taker_remaining"})
|
|
31
|
+
|
|
32
|
+
OrderStatus = Literal["resting", "partially_filled", "filled", "cancelled", "rejected"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class OrderRequest(BaseModel):
|
|
36
|
+
model_config = ConfigDict(extra="forbid")
|
|
37
|
+
|
|
38
|
+
account: int = Field(ge=1, le=MAX_INT64)
|
|
39
|
+
side: Side
|
|
40
|
+
type: OrderType = OrderType.LIMIT
|
|
41
|
+
price: Decimal | None = Field(default=None, description="Required for limit orders")
|
|
42
|
+
quantity: Decimal
|
|
43
|
+
time_in_force: TimeInForce | None = Field(
|
|
44
|
+
default=None, description="Defaults to gtc for limit orders and ioc for market orders"
|
|
45
|
+
)
|
|
46
|
+
post_only: bool = False
|
|
47
|
+
self_trade_prevention: SelfTradePrevention = SelfTradePrevention.CANCEL_TAKER
|
|
48
|
+
|
|
49
|
+
def to_command(self, spec: MarketSpec, order_id: int) -> NewOrder:
|
|
50
|
+
"""Convert to engine units. Raises ``ValueError`` for off-grid or missing values."""
|
|
51
|
+
if self.type is OrderType.LIMIT:
|
|
52
|
+
if self.price is None:
|
|
53
|
+
raise ValueError("a limit order needs a price")
|
|
54
|
+
price = spec.to_ticks(self.price)
|
|
55
|
+
tif = self.time_in_force or TimeInForce.GTC
|
|
56
|
+
else:
|
|
57
|
+
if self.price is not None:
|
|
58
|
+
raise ValueError("a market order takes no price")
|
|
59
|
+
price = 0
|
|
60
|
+
tif = self.time_in_force or TimeInForce.IOC
|
|
61
|
+
return NewOrder(
|
|
62
|
+
order_id,
|
|
63
|
+
self.account,
|
|
64
|
+
self.side,
|
|
65
|
+
price,
|
|
66
|
+
spec.to_lots(self.quantity),
|
|
67
|
+
self.type,
|
|
68
|
+
tif,
|
|
69
|
+
self.post_only,
|
|
70
|
+
self.self_trade_prevention,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class OrderResponse(BaseModel):
|
|
75
|
+
order_id: int
|
|
76
|
+
seq: int
|
|
77
|
+
status: OrderStatus
|
|
78
|
+
filled_quantity: str
|
|
79
|
+
events: list[dict[str, Any]]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class CancelResponse(BaseModel):
|
|
83
|
+
order_id: int
|
|
84
|
+
seq: int
|
|
85
|
+
status: Literal["cancelled", "rejected"]
|
|
86
|
+
events: list[dict[str, Any]]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class MarketInfo(BaseModel):
|
|
90
|
+
symbol: str
|
|
91
|
+
tick_size: str
|
|
92
|
+
lot_size: str
|
|
93
|
+
last_seq: int
|
|
94
|
+
best_bid: str | None
|
|
95
|
+
best_ask: str | None
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DepthResponse(BaseModel):
|
|
99
|
+
symbol: str
|
|
100
|
+
seq: int
|
|
101
|
+
bids: list[tuple[str, str, int]]
|
|
102
|
+
asks: list[tuple[str, str, int]]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class BookOrder(BaseModel):
|
|
106
|
+
order_id: int
|
|
107
|
+
side: Side
|
|
108
|
+
price: str
|
|
109
|
+
quantity: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class BookResponse(BaseModel):
|
|
113
|
+
symbol: str
|
|
114
|
+
seq: int
|
|
115
|
+
orders: list[BookOrder]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def render_event(spec: MarketSpec, event: Event) -> dict[str, Any]:
|
|
119
|
+
"""An event as a JSON-ready dict, integers converted back to decimal strings."""
|
|
120
|
+
out: dict[str, Any] = {"type": type(event).__struct_config__.tag}
|
|
121
|
+
for name, value in msgspec.structs.asdict(event).items():
|
|
122
|
+
if name in _PRICE_FIELDS:
|
|
123
|
+
out[name] = spec.price(value) if value else None # 0 is a market order: no price
|
|
124
|
+
elif name in _QTY_FIELDS:
|
|
125
|
+
out[name] = spec.qty(value)
|
|
126
|
+
else:
|
|
127
|
+
out[name] = value
|
|
128
|
+
return out
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def render_depth(spec: MarketSpec, seq: int, depth: Depth) -> DepthResponse:
|
|
132
|
+
def side(levels: list[Any]) -> list[tuple[str, str, int]]:
|
|
133
|
+
return [(spec.price(lvl.price), spec.qty(lvl.qty), lvl.orders) for lvl in levels]
|
|
134
|
+
|
|
135
|
+
return DepthResponse(symbol=spec.symbol, seq=seq, bids=side(depth.bids), asks=side(depth.asks))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def order_outcome(order: NewOrder, events: list[Event]) -> tuple[OrderStatus, int]:
|
|
139
|
+
"""Summarize what happened to a new order: its status and filled lots."""
|
|
140
|
+
filled = 0
|
|
141
|
+
status: OrderStatus | None = None
|
|
142
|
+
for e in events:
|
|
143
|
+
if isinstance(e, OrderRejected):
|
|
144
|
+
return "rejected", 0
|
|
145
|
+
if isinstance(e, Trade) and e.taker_order_id == order.order_id:
|
|
146
|
+
filled += e.qty
|
|
147
|
+
elif isinstance(e, OrderCancelled) and e.order_id == order.order_id:
|
|
148
|
+
status = "cancelled"
|
|
149
|
+
if status is None:
|
|
150
|
+
status = "filled" if filled == order.qty else "partially_filled" if filled else "resting"
|
|
151
|
+
return status, filled
|