microstructure-sim 1.0.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.
- microbook/__init__.py +30 -0
- microbook/book.py +553 -0
- microbook/order.py +86 -0
- microbook/py.typed +0 -0
- microbook/replay.py +673 -0
- microbook/rl.py +221 -0
- microbook/sim/__init__.py +93 -0
- microbook/sim/agents.py +495 -0
- microbook/sim/analytics.py +199 -0
- microbook/sim/events.py +41 -0
- microbook/sim/execution_metrics.py +217 -0
- microbook/sim/metrics.py +20 -0
- microbook/sim/orderflow.py +70 -0
- microbook/sim/portfolio.py +83 -0
- microbook/sim/scenarios.py +145 -0
- microbook/sim/simulator.py +274 -0
- microbook/sim/strategies_mm.py +190 -0
- microbook/sim/strategy.py +352 -0
- microbook/stylized.py +324 -0
- microbook/types.py +119 -0
- microstructure_sim-1.0.0.dist-info/METADATA +615 -0
- microstructure_sim-1.0.0.dist-info/RECORD +24 -0
- microstructure_sim-1.0.0.dist-info/WHEEL +4 -0
- microstructure_sim-1.0.0.dist-info/licenses/LICENSE +21 -0
microbook/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""microbook: a price-time priority limit order book and event-driven market simulator."""
|
|
2
|
+
|
|
3
|
+
from .book import LimitOrderBook
|
|
4
|
+
from .order import Order
|
|
5
|
+
from .types import (
|
|
6
|
+
ExecutionReport,
|
|
7
|
+
Fill,
|
|
8
|
+
OrderRejected,
|
|
9
|
+
OrderStatus,
|
|
10
|
+
OrderType,
|
|
11
|
+
Side,
|
|
12
|
+
STPMode,
|
|
13
|
+
TimeInForce,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
__version__ = "1.0.0"
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"ExecutionReport",
|
|
20
|
+
"Fill",
|
|
21
|
+
"LimitOrderBook",
|
|
22
|
+
"Order",
|
|
23
|
+
"OrderRejected",
|
|
24
|
+
"OrderStatus",
|
|
25
|
+
"OrderType",
|
|
26
|
+
"STPMode",
|
|
27
|
+
"Side",
|
|
28
|
+
"TimeInForce",
|
|
29
|
+
"__version__",
|
|
30
|
+
]
|
microbook/book.py
ADDED
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
"""Price-time priority central limit order book (CLOB).
|
|
2
|
+
|
|
3
|
+
Design notes
|
|
4
|
+
------------
|
|
5
|
+
* Prices are stored as **integer ticks**. Float prices are only used at the API
|
|
6
|
+
boundary, so there is no float-key aliasing (``0.1 + 0.2`` vs ``0.3``) and
|
|
7
|
+
off-grid prices are rejected rather than silently creating a new level.
|
|
8
|
+
* Each side keeps an ascending list of *sort keys* (``tick`` for bids,
|
|
9
|
+
``-tick`` for asks). The best price is always the **last** element, so reading
|
|
10
|
+
the touch and removing an exhausted touch level are both O(1).
|
|
11
|
+
* Each level is an ``OrderedDict`` keyed by order id: FIFO for matching and
|
|
12
|
+
O(1) removal for cancels.
|
|
13
|
+
* Aggregate quantity per level is maintained incrementally, so ``depth()`` is
|
|
14
|
+
O(levels requested).
|
|
15
|
+
|
|
16
|
+
Complexity (L = price levels on a side):
|
|
17
|
+
|
|
18
|
+
================== ===============================
|
|
19
|
+
add (new level) O(log L) search + O(L) memmove
|
|
20
|
+
add (existing) O(1)
|
|
21
|
+
cancel O(1), plus O(log L) if the level empties
|
|
22
|
+
modify (reduce) O(1), keeps queue priority
|
|
23
|
+
match O(1) per fill / per level crossed
|
|
24
|
+
================== ===============================
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import math
|
|
30
|
+
from bisect import bisect_left, insort
|
|
31
|
+
from collections import OrderedDict
|
|
32
|
+
from collections.abc import Iterator
|
|
33
|
+
from decimal import Decimal
|
|
34
|
+
|
|
35
|
+
from .order import Order
|
|
36
|
+
from .types import (
|
|
37
|
+
ExecutionReport,
|
|
38
|
+
Fill,
|
|
39
|
+
OrderRejected,
|
|
40
|
+
OrderStatus,
|
|
41
|
+
OrderType,
|
|
42
|
+
Side,
|
|
43
|
+
STPMode,
|
|
44
|
+
TimeInForce,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
__all__ = ["LimitOrderBook"]
|
|
48
|
+
|
|
49
|
+
# Sort key below every level (ticks come from float prices, so they stay far below
|
|
50
|
+
# 2**63): a market order's stop key, so it sweeps the whole side. An int, so key
|
|
51
|
+
# comparisons stay int-to-int (fast when compiled with mypyc).
|
|
52
|
+
_NO_STOP = -(1 << 63)
|
|
53
|
+
|
|
54
|
+
# Fast record construction for the hot path (bypasses NamedTuple.__new__'s
|
|
55
|
+
# Python-level argument handling; field order must match ExecutionReport).
|
|
56
|
+
_report = tuple.__new__
|
|
57
|
+
_ER = ExecutionReport
|
|
58
|
+
_NEW = OrderStatus.NEW
|
|
59
|
+
_PARTIAL = OrderStatus.PARTIALLY_FILLED
|
|
60
|
+
_FILLED = OrderStatus.FILLED
|
|
61
|
+
_CANCELED = OrderStatus.CANCELED
|
|
62
|
+
if ExecutionReport._fields != (
|
|
63
|
+
"order_id",
|
|
64
|
+
"status",
|
|
65
|
+
"fills",
|
|
66
|
+
"resting_qty",
|
|
67
|
+
"canceled_qty",
|
|
68
|
+
"stp_canceled",
|
|
69
|
+
"reason",
|
|
70
|
+
): # pragma: no cover - guards the positional construction above
|
|
71
|
+
raise ImportError("ExecutionReport field order changed; update book._execute")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _BookSide:
|
|
75
|
+
"""One side of the book, indexed by integer tick."""
|
|
76
|
+
|
|
77
|
+
__slots__ = ("keys", "levels", "qty", "side", "sign")
|
|
78
|
+
|
|
79
|
+
def __init__(self, side: Side) -> None:
|
|
80
|
+
self.side = side
|
|
81
|
+
self.sign = 1 if side is Side.BUY else -1
|
|
82
|
+
self.levels: dict[int, OrderedDict[str, Order]] = {}
|
|
83
|
+
self.keys: list[int] = [] # ascending sort keys; best price is keys[-1]
|
|
84
|
+
self.qty: dict[int, int] = {}
|
|
85
|
+
|
|
86
|
+
def best_tick(self) -> int | None:
|
|
87
|
+
return self.sign * self.keys[-1] if self.keys else None
|
|
88
|
+
|
|
89
|
+
def add(self, tick: int, order: Order) -> None:
|
|
90
|
+
level = self.levels.get(tick)
|
|
91
|
+
if level is None:
|
|
92
|
+
level = self.levels[tick] = OrderedDict()
|
|
93
|
+
insort(self.keys, self.sign * tick)
|
|
94
|
+
self.qty[tick] = 0
|
|
95
|
+
level[order.order_id] = order
|
|
96
|
+
self.qty[tick] += order.qty
|
|
97
|
+
|
|
98
|
+
def remove(self, tick: int, order: Order) -> None:
|
|
99
|
+
level = self.levels[tick]
|
|
100
|
+
del level[order.order_id]
|
|
101
|
+
self.qty[tick] -= order.qty
|
|
102
|
+
if not level:
|
|
103
|
+
self.drop_level(tick)
|
|
104
|
+
|
|
105
|
+
def drop_level(self, tick: int) -> None:
|
|
106
|
+
del self.levels[tick]
|
|
107
|
+
del self.qty[tick]
|
|
108
|
+
key = self.sign * tick
|
|
109
|
+
if self.keys[-1] == key:
|
|
110
|
+
self.keys.pop()
|
|
111
|
+
else:
|
|
112
|
+
del self.keys[bisect_left(self.keys, key)]
|
|
113
|
+
|
|
114
|
+
def ticks(self) -> Iterator[int]:
|
|
115
|
+
"""Ticks from best to worst."""
|
|
116
|
+
s = self.sign
|
|
117
|
+
for k in reversed(self.keys):
|
|
118
|
+
yield s * k
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class LimitOrderBook:
|
|
122
|
+
"""Price-time priority limit order book.
|
|
123
|
+
|
|
124
|
+
Parameters
|
|
125
|
+
----------
|
|
126
|
+
tick_size:
|
|
127
|
+
Minimum price increment. Limit prices must lie on this grid.
|
|
128
|
+
stp:
|
|
129
|
+
Self-trade prevention policy, applied when an incoming order would
|
|
130
|
+
trade against a resting order with the same (non-``None``) ``owner``.
|
|
131
|
+
|
|
132
|
+
Order entry
|
|
133
|
+
-----------
|
|
134
|
+
``submit(order)`` is the primary entry point and returns an
|
|
135
|
+
[`ExecutionReport`][microbook.ExecutionReport]; it never raises for business rejections.
|
|
136
|
+
``place_limit`` / ``place_market`` are conveniences that return the list of
|
|
137
|
+
fills and raise [`OrderRejected`][microbook.OrderRejected] if the book refuses the order.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(self, tick_size: float = 0.01, *, stp: STPMode = STPMode.NONE) -> None:
|
|
141
|
+
if not math.isfinite(tick_size) or tick_size <= 0:
|
|
142
|
+
raise ValueError("tick_size must be a positive finite number")
|
|
143
|
+
self.tick_size = float(tick_size)
|
|
144
|
+
self.stp = STPMode(stp)
|
|
145
|
+
exponent = Decimal(repr(self.tick_size)).normalize().as_tuple().exponent
|
|
146
|
+
self._decimals = max(0, -exponent) if isinstance(exponent, int) else 0
|
|
147
|
+
self._bids = _BookSide(Side.BUY)
|
|
148
|
+
self._asks = _BookSide(Side.SELL)
|
|
149
|
+
# order_id -> (order, tick) for every resting order
|
|
150
|
+
self._orders: dict[str, tuple[Order, int]] = {}
|
|
151
|
+
self._px_cache: dict[int, float] = {}
|
|
152
|
+
|
|
153
|
+
# ------------------------------------------------------------------ #
|
|
154
|
+
# Price grid #
|
|
155
|
+
# ------------------------------------------------------------------ #
|
|
156
|
+
|
|
157
|
+
def price_of(self, tick: int) -> float:
|
|
158
|
+
"""Float price of an integer tick, rounded to the grid's precision."""
|
|
159
|
+
px = self._px_cache.get(tick)
|
|
160
|
+
if px is None:
|
|
161
|
+
px = self._px_cache[tick] = round(tick * self.tick_size, self._decimals)
|
|
162
|
+
return px
|
|
163
|
+
|
|
164
|
+
def to_ticks(self, price: float) -> int:
|
|
165
|
+
"""Integer tick of an on-grid price. Raises ``ValueError`` if off-grid."""
|
|
166
|
+
tick = self._tick_or_none(price)
|
|
167
|
+
if tick is None:
|
|
168
|
+
raise ValueError(f"price {price!r} is not a multiple of tick size {self.tick_size}")
|
|
169
|
+
return tick
|
|
170
|
+
|
|
171
|
+
def round_price(self, price: float, side: Side) -> float:
|
|
172
|
+
"""Round a price onto the grid *passively*: bids down, asks up."""
|
|
173
|
+
x = price / self.tick_size
|
|
174
|
+
nearest = round(x)
|
|
175
|
+
if abs(x - nearest) <= 1e-6:
|
|
176
|
+
return self.price_of(int(nearest))
|
|
177
|
+
return self.price_of(math.floor(x) if side is Side.BUY else math.ceil(x))
|
|
178
|
+
|
|
179
|
+
def _tick_or_none(self, price: float) -> int | None:
|
|
180
|
+
x = price / self.tick_size
|
|
181
|
+
tick = round(x)
|
|
182
|
+
if abs(x - tick) > 1e-6:
|
|
183
|
+
return None
|
|
184
|
+
return int(tick)
|
|
185
|
+
|
|
186
|
+
# ------------------------------------------------------------------ #
|
|
187
|
+
# Market data #
|
|
188
|
+
# ------------------------------------------------------------------ #
|
|
189
|
+
|
|
190
|
+
def best_bid(self) -> float | None:
|
|
191
|
+
"""Highest bid price, or ``None`` if there are no bids."""
|
|
192
|
+
keys = self._bids.keys
|
|
193
|
+
return self.price_of(keys[-1]) if keys else None
|
|
194
|
+
|
|
195
|
+
def best_ask(self) -> float | None:
|
|
196
|
+
"""Lowest ask price, or ``None`` if there are no asks."""
|
|
197
|
+
keys = self._asks.keys
|
|
198
|
+
return self.price_of(-keys[-1]) if keys else None
|
|
199
|
+
|
|
200
|
+
def midprice(self) -> float | None:
|
|
201
|
+
"""Average of the best bid and best ask, or ``None`` if either side is empty."""
|
|
202
|
+
b, a = self._bids.keys, self._asks.keys
|
|
203
|
+
if not b or not a:
|
|
204
|
+
return None
|
|
205
|
+
return (self.price_of(b[-1]) + self.price_of(-a[-1])) / 2.0
|
|
206
|
+
|
|
207
|
+
def spread(self) -> float | None:
|
|
208
|
+
"""Best ask minus best bid, or ``None`` if either side is empty."""
|
|
209
|
+
b, a = self.best_bid(), self.best_ask()
|
|
210
|
+
if b is None or a is None:
|
|
211
|
+
return None
|
|
212
|
+
return round(a - b, self._decimals)
|
|
213
|
+
|
|
214
|
+
def microprice(self) -> float | None:
|
|
215
|
+
"""Size-weighted mid: leans toward the side with *less* resting size,
|
|
216
|
+
i.e. toward where the price is more likely to move next."""
|
|
217
|
+
bt, at = self._bids.best_tick(), self._asks.best_tick()
|
|
218
|
+
if bt is None or at is None:
|
|
219
|
+
return None
|
|
220
|
+
qb, qa = self._bids.qty[bt], self._asks.qty[at]
|
|
221
|
+
b, a = self.price_of(bt), self.price_of(at)
|
|
222
|
+
return (b * qa + a * qb) / (qa + qb)
|
|
223
|
+
|
|
224
|
+
def top_of_book(self) -> dict[str, float | None]:
|
|
225
|
+
"""Best bid, best ask and mid in one dict (``None`` where undefined)."""
|
|
226
|
+
return {"best_bid": self.best_bid(), "best_ask": self.best_ask(), "mid": self.midprice()}
|
|
227
|
+
|
|
228
|
+
def depth(self, levels: int = 5) -> dict[str, list[tuple[float, int]]]:
|
|
229
|
+
"""Aggregated L2 depth, best price first."""
|
|
230
|
+
out: dict[str, list[tuple[float, int]]] = {}
|
|
231
|
+
for name, side in (("bids", self._bids), ("asks", self._asks)):
|
|
232
|
+
rows: list[tuple[float, int]] = []
|
|
233
|
+
for tick in side.ticks():
|
|
234
|
+
if len(rows) >= levels:
|
|
235
|
+
break
|
|
236
|
+
rows.append((self.price_of(tick), side.qty[tick]))
|
|
237
|
+
out[name] = rows
|
|
238
|
+
return out
|
|
239
|
+
|
|
240
|
+
def volume_at(self, side: Side, price: float) -> int:
|
|
241
|
+
"""Total resting quantity at ``price`` on ``side`` (0 if none or off the tick grid)."""
|
|
242
|
+
tick = self._tick_or_none(price)
|
|
243
|
+
if tick is None:
|
|
244
|
+
return 0
|
|
245
|
+
book = self._bids if side is Side.BUY else self._asks
|
|
246
|
+
return book.qty.get(tick, 0)
|
|
247
|
+
|
|
248
|
+
def get_order(self, order_id: str) -> Order | None:
|
|
249
|
+
"""The resting order with this id, or ``None`` if it is not on the book.
|
|
250
|
+
|
|
251
|
+
This is the book's own object: treat it as read-only.
|
|
252
|
+
"""
|
|
253
|
+
entry = self._orders.get(order_id)
|
|
254
|
+
return entry[0] if entry is not None else None
|
|
255
|
+
|
|
256
|
+
def queue_ahead(self, order_id: str) -> int | None:
|
|
257
|
+
"""Quantity resting ahead of ``order_id`` at its price level (O(queue))."""
|
|
258
|
+
entry = self._orders.get(order_id)
|
|
259
|
+
if entry is None:
|
|
260
|
+
return None
|
|
261
|
+
order, tick = entry
|
|
262
|
+
book = self._bids if order.side is Side.BUY else self._asks
|
|
263
|
+
ahead = 0
|
|
264
|
+
for oid, o in book.levels[tick].items():
|
|
265
|
+
if oid == order_id:
|
|
266
|
+
return ahead
|
|
267
|
+
ahead += o.qty
|
|
268
|
+
raise AssertionError("order index out of sync with level") # pragma: no cover
|
|
269
|
+
|
|
270
|
+
def __contains__(self, order_id: object) -> bool:
|
|
271
|
+
return order_id in self._orders
|
|
272
|
+
|
|
273
|
+
def __len__(self) -> int:
|
|
274
|
+
return len(self._orders)
|
|
275
|
+
|
|
276
|
+
def __repr__(self) -> str:
|
|
277
|
+
return (
|
|
278
|
+
f"LimitOrderBook(tick_size={self.tick_size}, best_bid={self.best_bid()}, "
|
|
279
|
+
f"best_ask={self.best_ask()}, orders={len(self)})"
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# ------------------------------------------------------------------ #
|
|
283
|
+
# Order entry #
|
|
284
|
+
# ------------------------------------------------------------------ #
|
|
285
|
+
|
|
286
|
+
def submit(self, order: Order) -> ExecutionReport:
|
|
287
|
+
"""Process an order according to its ``order_type`` / ``tif`` / ``post_only``."""
|
|
288
|
+
return self._execute(order, market=order.order_type is OrderType.MARKET)
|
|
289
|
+
|
|
290
|
+
def place_limit(self, order: Order) -> list[Fill]:
|
|
291
|
+
"""Match a limit order and rest any remainder (subject to ``tif``)."""
|
|
292
|
+
report = self._execute(order, market=False)
|
|
293
|
+
if report.status is OrderStatus.REJECTED:
|
|
294
|
+
raise OrderRejected(report)
|
|
295
|
+
return list(report.fills)
|
|
296
|
+
|
|
297
|
+
def place_market(self, order: Order) -> list[Fill]:
|
|
298
|
+
"""Execute ``order`` as a market order (its price is ignored); never rests."""
|
|
299
|
+
report = self._execute(order, market=True)
|
|
300
|
+
if report.status is OrderStatus.REJECTED:
|
|
301
|
+
raise OrderRejected(report)
|
|
302
|
+
return list(report.fills)
|
|
303
|
+
|
|
304
|
+
def cancel(self, order_id: str) -> bool:
|
|
305
|
+
"""Remove a resting order. Returns ``False`` if it is not on the book."""
|
|
306
|
+
entry = self._orders.pop(order_id, None)
|
|
307
|
+
if entry is None:
|
|
308
|
+
return False
|
|
309
|
+
order, tick = entry
|
|
310
|
+
(self._bids if order.side is Side.BUY else self._asks).remove(tick, order)
|
|
311
|
+
return True
|
|
312
|
+
|
|
313
|
+
def reduce(self, order_id: str, qty: int) -> ExecutionReport:
|
|
314
|
+
"""Partial cancel: remove ``qty`` shares from a resting order, keeping its priority.
|
|
315
|
+
|
|
316
|
+
Reducing by the whole open quantity or more cancels the order. Unlike
|
|
317
|
+
``modify(new_qty=...)`` the amount is relative, so it is resolved against
|
|
318
|
+
the quantity resting when the message arrives (the semantics of an
|
|
319
|
+
exchange's cancel-by-size message, e.g. NASDAQ ITCH "order cancel").
|
|
320
|
+
"""
|
|
321
|
+
if qty <= 0:
|
|
322
|
+
return self._reject(order_id, "reduce qty must be positive")
|
|
323
|
+
entry = self._orders.get(order_id)
|
|
324
|
+
if entry is None:
|
|
325
|
+
return self._reject(order_id, "unknown order id")
|
|
326
|
+
return self.modify(order_id, new_qty=max(entry[0].qty - qty, 0))
|
|
327
|
+
|
|
328
|
+
def modify(
|
|
329
|
+
self,
|
|
330
|
+
order_id: str,
|
|
331
|
+
*,
|
|
332
|
+
new_price: float | None = None,
|
|
333
|
+
new_qty: int | None = None,
|
|
334
|
+
ts: int | None = None,
|
|
335
|
+
) -> ExecutionReport:
|
|
336
|
+
"""Amend a resting order with exchange-style priority semantics.
|
|
337
|
+
|
|
338
|
+
* same price and quantity reduced (or unchanged) -> amended in place, keeps priority
|
|
339
|
+
* price change or quantity increase -> loses priority (cancel/replace);
|
|
340
|
+
a new price that crosses the spread trades immediately and the fills
|
|
341
|
+
are returned in the report
|
|
342
|
+
* ``new_qty == 0`` -> cancel
|
|
343
|
+
|
|
344
|
+
Invalid requests are REJECTED and leave the order untouched.
|
|
345
|
+
"""
|
|
346
|
+
entry = self._orders.get(order_id)
|
|
347
|
+
if entry is None:
|
|
348
|
+
return self._reject(order_id, "unknown order id")
|
|
349
|
+
order, tick = entry
|
|
350
|
+
|
|
351
|
+
if new_qty is not None and new_qty < 0:
|
|
352
|
+
return self._reject(order_id, "new_qty must be >= 0")
|
|
353
|
+
new_tick = tick
|
|
354
|
+
if new_price is not None:
|
|
355
|
+
if not math.isfinite(new_price) or new_price <= 0:
|
|
356
|
+
return self._reject(order_id, "price must be positive")
|
|
357
|
+
parsed = self._tick_or_none(new_price)
|
|
358
|
+
if parsed is None:
|
|
359
|
+
return self._reject(order_id, "price not on tick grid")
|
|
360
|
+
new_tick = parsed
|
|
361
|
+
|
|
362
|
+
if new_qty == 0:
|
|
363
|
+
remaining = order.qty
|
|
364
|
+
self.cancel(order_id)
|
|
365
|
+
return ExecutionReport(order_id, OrderStatus.CANCELED, canceled_qty=remaining)
|
|
366
|
+
|
|
367
|
+
target = order.qty if new_qty is None else new_qty
|
|
368
|
+
book = self._bids if order.side is Side.BUY else self._asks
|
|
369
|
+
if new_tick == tick and target <= order.qty:
|
|
370
|
+
book.qty[tick] -= order.qty - target
|
|
371
|
+
order.qty = target
|
|
372
|
+
return ExecutionReport(order_id, OrderStatus.NEW, resting_qty=target)
|
|
373
|
+
|
|
374
|
+
if order.post_only:
|
|
375
|
+
opp = self._asks if order.side is Side.BUY else self._bids
|
|
376
|
+
if opp.keys and opp.keys[-1] >= opp.sign * new_tick:
|
|
377
|
+
return self._reject(order_id, "post-only order would cross")
|
|
378
|
+
|
|
379
|
+
self.cancel(order_id)
|
|
380
|
+
order.price = self.price_of(new_tick)
|
|
381
|
+
order.qty = target
|
|
382
|
+
if ts is not None:
|
|
383
|
+
order.ts = ts
|
|
384
|
+
return self._execute(order, market=False)
|
|
385
|
+
|
|
386
|
+
# ------------------------------------------------------------------ #
|
|
387
|
+
# Internals #
|
|
388
|
+
# ------------------------------------------------------------------ #
|
|
389
|
+
|
|
390
|
+
@staticmethod
|
|
391
|
+
def _reject(order_id: str, reason: str) -> ExecutionReport:
|
|
392
|
+
return ExecutionReport(order_id, OrderStatus.REJECTED, reason=reason)
|
|
393
|
+
|
|
394
|
+
def _execute(self, order: Order, *, market: bool) -> ExecutionReport:
|
|
395
|
+
# Hot path. Validation, the crossing test and resting are inlined, and
|
|
396
|
+
# reports are built with ``_report`` (tuple.__new__) to skip the
|
|
397
|
+
# Python-level NamedTuple constructor.
|
|
398
|
+
oid = order.order_id
|
|
399
|
+
orders = self._orders
|
|
400
|
+
if oid in orders:
|
|
401
|
+
return self._reject(oid, "duplicate order id")
|
|
402
|
+
if order.qty <= 0:
|
|
403
|
+
return self._reject(oid, "qty must be positive")
|
|
404
|
+
|
|
405
|
+
is_buy = order.side is Side.BUY
|
|
406
|
+
opp = self._asks if is_buy else self._bids
|
|
407
|
+
opp_keys = opp.keys
|
|
408
|
+
tick = 0
|
|
409
|
+
stop_key = _NO_STOP
|
|
410
|
+
if not market:
|
|
411
|
+
price = order.price
|
|
412
|
+
if price is None:
|
|
413
|
+
return self._reject(oid, "limit order requires a price")
|
|
414
|
+
x = price / self.tick_size
|
|
415
|
+
tick = round(x)
|
|
416
|
+
if abs(x - tick) > 1e-6:
|
|
417
|
+
return self._reject(oid, "price not on tick grid")
|
|
418
|
+
if tick <= 0:
|
|
419
|
+
return self._reject(oid, "price must be positive")
|
|
420
|
+
# A level crosses iff its sort key >= stop_key (see _BookSide).
|
|
421
|
+
stop_key = opp.sign * tick
|
|
422
|
+
if order.post_only and opp_keys and opp_keys[-1] >= stop_key:
|
|
423
|
+
return self._reject(oid, "post-only order would cross")
|
|
424
|
+
|
|
425
|
+
tif = order.tif
|
|
426
|
+
if tif is TimeInForce.FOK and not self._can_fill(order, opp, stop_key):
|
|
427
|
+
killed, order.qty = order.qty, 0
|
|
428
|
+
return _report(_ER, (oid, _CANCELED, (), 0, killed, (), None))
|
|
429
|
+
|
|
430
|
+
if opp_keys and opp_keys[-1] >= stop_key:
|
|
431
|
+
fill_list, stp_list, halted = self._match(order, opp, stop_key)
|
|
432
|
+
fills: tuple[Fill, ...] = tuple(fill_list)
|
|
433
|
+
stp_ids: tuple[str, ...] = tuple(stp_list) if stp_list else ()
|
|
434
|
+
else: # passive fast path: nothing to match against
|
|
435
|
+
fills, stp_ids, halted = (), (), False
|
|
436
|
+
|
|
437
|
+
remaining = order.qty
|
|
438
|
+
if remaining == 0:
|
|
439
|
+
return _report(_ER, (oid, _FILLED, fills, 0, 0, stp_ids, None))
|
|
440
|
+
if market or halted or tif is not TimeInForce.GTC:
|
|
441
|
+
order.qty = 0
|
|
442
|
+
return _report(_ER, (oid, _CANCELED, fills, 0, remaining, stp_ids, None))
|
|
443
|
+
|
|
444
|
+
order.price = self.price_of(tick)
|
|
445
|
+
book = self._bids if is_buy else self._asks
|
|
446
|
+
level = book.levels.get(tick)
|
|
447
|
+
if level is None:
|
|
448
|
+
book.add(tick, order)
|
|
449
|
+
else:
|
|
450
|
+
level[oid] = order
|
|
451
|
+
book.qty[tick] += remaining
|
|
452
|
+
orders[oid] = (order, tick)
|
|
453
|
+
return _report(_ER, (oid, _PARTIAL if fills else _NEW, fills, remaining, 0, stp_ids, None))
|
|
454
|
+
|
|
455
|
+
def _match(self, taker: Order, opp: _BookSide, stop_key: int) -> tuple[list[Fill], list[str], bool]:
|
|
456
|
+
"""Sweep ``opp`` from the touch while levels cross. Returns
|
|
457
|
+
``(fills, stp_canceled_ids, halted_by_stp)``. Hot path: keep it lean."""
|
|
458
|
+
fills: list[Fill] = []
|
|
459
|
+
stp_ids: list[str] = []
|
|
460
|
+
keys, levels, qtys, sign = opp.keys, opp.levels, opp.qty, opp.sign
|
|
461
|
+
orders = self._orders
|
|
462
|
+
owner = taker.owner
|
|
463
|
+
stp = self.stp
|
|
464
|
+
check_stp = owner is not None and stp is not STPMode.NONE
|
|
465
|
+
tid, tside, tts = taker.order_id, taker.side, taker.ts
|
|
466
|
+
|
|
467
|
+
while taker.qty and keys and keys[-1] >= stop_key:
|
|
468
|
+
tick = sign * keys[-1]
|
|
469
|
+
level = levels[tick]
|
|
470
|
+
price = self.price_of(tick)
|
|
471
|
+
while taker.qty and level:
|
|
472
|
+
maker = next(iter(level.values()))
|
|
473
|
+
if check_stp and maker.owner == owner:
|
|
474
|
+
if stp is STPMode.CANCEL_INCOMING:
|
|
475
|
+
return fills, stp_ids, True
|
|
476
|
+
level.popitem(last=False)
|
|
477
|
+
qtys[tick] -= maker.qty
|
|
478
|
+
del orders[maker.order_id]
|
|
479
|
+
stp_ids.append(maker.order_id)
|
|
480
|
+
continue
|
|
481
|
+
q = taker.qty if taker.qty < maker.qty else maker.qty
|
|
482
|
+
fills.append(Fill(tid, maker.order_id, price, q, tside, tts))
|
|
483
|
+
taker.qty -= q
|
|
484
|
+
maker.qty -= q
|
|
485
|
+
qtys[tick] -= q
|
|
486
|
+
if not maker.qty:
|
|
487
|
+
level.popitem(last=False)
|
|
488
|
+
del orders[maker.order_id]
|
|
489
|
+
if not level:
|
|
490
|
+
del levels[tick]
|
|
491
|
+
del qtys[tick]
|
|
492
|
+
keys.pop()
|
|
493
|
+
return fills, stp_ids, False
|
|
494
|
+
|
|
495
|
+
def _can_fill(self, taker: Order, opp: _BookSide, stop_key: int) -> bool:
|
|
496
|
+
"""Would ``taker`` be completely filled right now? (FOK pre-check, no side effects.)"""
|
|
497
|
+
need = taker.qty
|
|
498
|
+
owner = taker.owner
|
|
499
|
+
check_stp = owner is not None and self.stp is not STPMode.NONE
|
|
500
|
+
for key in reversed(opp.keys):
|
|
501
|
+
if key < stop_key:
|
|
502
|
+
break
|
|
503
|
+
tick = opp.sign * key
|
|
504
|
+
if not check_stp:
|
|
505
|
+
need -= opp.qty[tick]
|
|
506
|
+
if need <= 0:
|
|
507
|
+
return True
|
|
508
|
+
continue
|
|
509
|
+
for maker in opp.levels[tick].values():
|
|
510
|
+
if maker.owner == owner:
|
|
511
|
+
if self.stp is STPMode.CANCEL_INCOMING:
|
|
512
|
+
return False
|
|
513
|
+
continue
|
|
514
|
+
need -= maker.qty
|
|
515
|
+
if need <= 0:
|
|
516
|
+
return True
|
|
517
|
+
return False
|
|
518
|
+
|
|
519
|
+
# ------------------------------------------------------------------ #
|
|
520
|
+
# Debugging #
|
|
521
|
+
# ------------------------------------------------------------------ #
|
|
522
|
+
|
|
523
|
+
def check_invariants(self) -> None:
|
|
524
|
+
"""Verify internal consistency; raises ``AssertionError`` on corruption.
|
|
525
|
+
|
|
526
|
+
O(n) — intended for tests and debugging, not the hot path.
|
|
527
|
+
"""
|
|
528
|
+
|
|
529
|
+
def require(cond: bool, msg: str) -> None:
|
|
530
|
+
if not cond:
|
|
531
|
+
raise AssertionError(msg)
|
|
532
|
+
|
|
533
|
+
seen: set[str] = set()
|
|
534
|
+
for book in (self._bids, self._asks):
|
|
535
|
+
require(book.keys == sorted(set(book.keys)), f"{book.side} keys unsorted or duplicated")
|
|
536
|
+
ticks = {book.sign * k for k in book.keys}
|
|
537
|
+
require(ticks == set(book.levels) == set(book.qty), f"{book.side} level index mismatch")
|
|
538
|
+
for tick, level in book.levels.items():
|
|
539
|
+
require(len(level) > 0, f"{book.side} empty level at tick {tick}")
|
|
540
|
+
require(
|
|
541
|
+
book.qty[tick] == sum(o.qty for o in level.values()),
|
|
542
|
+
f"{book.side} cached qty mismatch at tick {tick}",
|
|
543
|
+
)
|
|
544
|
+
for oid, o in level.items():
|
|
545
|
+
require(o.order_id == oid, f"level key {oid!r} != order id {o.order_id!r}")
|
|
546
|
+
require(o.qty > 0, f"non-positive qty resting: {oid}")
|
|
547
|
+
require(o.side is book.side, f"order {oid} on wrong side")
|
|
548
|
+
entry = self._orders.get(oid)
|
|
549
|
+
require(entry is not None and entry[0] is o and entry[1] == tick, f"index mismatch for {oid}")
|
|
550
|
+
seen.add(oid)
|
|
551
|
+
require(seen == set(self._orders), "order index contains orders not on the book")
|
|
552
|
+
bb, ba = self._bids.best_tick(), self._asks.best_tick()
|
|
553
|
+
require(bb is None or ba is None or bb < ba, f"book is crossed: bid {bb} >= ask {ba}")
|
microbook/order.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Orders: the messages participants send to the book."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .types import OrderType, Side, TimeInForce
|
|
9
|
+
|
|
10
|
+
__all__ = ["Order"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(slots=True)
|
|
14
|
+
class Order:
|
|
15
|
+
"""An order message.
|
|
16
|
+
|
|
17
|
+
``qty`` is the *open* quantity: the book decrements it as the order trades,
|
|
18
|
+
so after a submit it equals the quantity left resting (0 if none).
|
|
19
|
+
|
|
20
|
+
``price`` is required for LIMIT orders and ignored for MARKET orders.
|
|
21
|
+
``ts`` is informational (the simulator stamps it with the arrival time);
|
|
22
|
+
queue priority is determined by arrival order at the book, not by ``ts``.
|
|
23
|
+
``owner`` identifies the participant for self-trade prevention.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
order_id: str
|
|
27
|
+
"""Unique id. The book rejects an id that is already live."""
|
|
28
|
+
side: Side
|
|
29
|
+
"""`BUY` or `SELL`."""
|
|
30
|
+
price: float | None
|
|
31
|
+
"""Limit price, on the book's tick grid; `None` for market orders."""
|
|
32
|
+
qty: int
|
|
33
|
+
"""Open quantity. The book decrements it as the order trades."""
|
|
34
|
+
ts: int = 0
|
|
35
|
+
"""Informational timestamp. Queue priority comes from arrival order at the book."""
|
|
36
|
+
order_type: OrderType = OrderType.LIMIT
|
|
37
|
+
"""`LIMIT` or `MARKET`."""
|
|
38
|
+
tif: TimeInForce = TimeInForce.GTC
|
|
39
|
+
"""Time in force: `GTC` rests the remainder, `IOC` cancels it, `FOK` fills completely or not at all."""
|
|
40
|
+
post_only: bool = False
|
|
41
|
+
"""Reject the order instead of letting it take liquidity."""
|
|
42
|
+
owner: str | None = None
|
|
43
|
+
"""Participant id for self-trade prevention; `None` is never treated as a self-trade."""
|
|
44
|
+
|
|
45
|
+
def __post_init__(self) -> None:
|
|
46
|
+
if self.qty <= 0:
|
|
47
|
+
raise ValueError("qty must be positive")
|
|
48
|
+
if self.order_type is OrderType.LIMIT:
|
|
49
|
+
if self.price is None or not math.isfinite(self.price) or self.price <= 0:
|
|
50
|
+
raise ValueError("price must be positive")
|
|
51
|
+
elif self.post_only:
|
|
52
|
+
raise ValueError("a market order cannot be post-only")
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def limit(
|
|
56
|
+
cls,
|
|
57
|
+
order_id: str,
|
|
58
|
+
side: Side,
|
|
59
|
+
price: float,
|
|
60
|
+
qty: int,
|
|
61
|
+
*,
|
|
62
|
+
ts: int = 0,
|
|
63
|
+
tif: TimeInForce = TimeInForce.GTC,
|
|
64
|
+
post_only: bool = False,
|
|
65
|
+
owner: str | None = None,
|
|
66
|
+
) -> Order:
|
|
67
|
+
"""A limit order (``GTC`` unless ``tif`` says otherwise)."""
|
|
68
|
+
return cls(order_id, side, price, qty, ts, OrderType.LIMIT, tif, post_only, owner)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def market(
|
|
72
|
+
cls,
|
|
73
|
+
order_id: str,
|
|
74
|
+
side: Side,
|
|
75
|
+
qty: int,
|
|
76
|
+
*,
|
|
77
|
+
ts: int = 0,
|
|
78
|
+
owner: str | None = None,
|
|
79
|
+
) -> Order:
|
|
80
|
+
"""A market order: trades immediately against the book; any unfilled rest is cancelled."""
|
|
81
|
+
return cls(order_id, side, None, qty, ts, OrderType.MARKET, TimeInForce.IOC, False, owner)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def is_market(self) -> bool:
|
|
85
|
+
"""Whether this is a market order."""
|
|
86
|
+
return self.order_type is OrderType.MARKET
|
microbook/py.typed
ADDED
|
File without changes
|