tracebook-sim 0.2.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.
- tracebook/__init__.py +38 -0
- tracebook/_version.py +3 -0
- tracebook/benchmarks/__init__.py +1 -0
- tracebook/benchmarks/runner.py +234 -0
- tracebook/core/__init__.py +0 -0
- tracebook/core/matching_engine.py +497 -0
- tracebook/core/order.py +436 -0
- tracebook/core/orderbook.py +1038 -0
- tracebook/core/price_level.py +309 -0
- tracebook/core/replay.py +173 -0
- tracebook/events/__init__.py +21 -0
- tracebook/events/cli.py +83 -0
- tracebook/events/market_replay.py +587 -0
- tracebook/profiling/__init__.py +0 -0
- tracebook/profiling/magic_trace_wrapper.py +595 -0
- tracebook/profiling/performance_monitor.py +615 -0
- tracebook/profiling/trace_analyzer.py +534 -0
- tracebook/profiling/trace_visualizer.py +475 -0
- tracebook/py.typed +1 -0
- tracebook/simulation/__init__.py +0 -0
- tracebook/simulation/order_generator.py +960 -0
- tracebook/simulation/simulation_engine.py +701 -0
- tracebook/utils/__init__.py +0 -0
- tracebook/visualization/__init__.py +0 -0
- tracebook/visualization/dashboard.py +698 -0
- tracebook/visualization/web/__init__.py +1 -0
- tracebook/visualization/web/app.js +146 -0
- tracebook/visualization/web/index.html +66 -0
- tracebook/visualization/web/styles.css +312 -0
- tracebook/visualization/web_server.py +258 -0
- tracebook_sim-0.2.0.dist-info/METADATA +627 -0
- tracebook_sim-0.2.0.dist-info/RECORD +36 -0
- tracebook_sim-0.2.0.dist-info/WHEEL +5 -0
- tracebook_sim-0.2.0.dist-info/entry_points.txt +6 -0
- tracebook_sim-0.2.0.dist-info/licenses/LICENSE +21 -0
- tracebook_sim-0.2.0.dist-info/top_level.txt +1 -0
tracebook/core/order.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Order data structures.
|
|
3
|
+
|
|
4
|
+
Order and Trade are plain ``__slots__`` classes. They were previously Numba
|
|
5
|
+
``jitclass`` types, but the order book drives them from pure Python -- every
|
|
6
|
+
construction paid ``inspect``-based argument binding and every field access was
|
|
7
|
+
boxed across the Python/Numba boundary -- so the JIT wrapper was a net cost. See
|
|
8
|
+
docs/performance.md for the measured before/after.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from enum import IntEnum
|
|
12
|
+
from numbers import Integral, Real
|
|
13
|
+
import math
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OrderSide(IntEnum):
|
|
19
|
+
"""Order side enumeration for efficient comparison."""
|
|
20
|
+
|
|
21
|
+
BUY = 1
|
|
22
|
+
SELL = -1
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class OrderType(IntEnum):
|
|
26
|
+
"""Order type enumeration."""
|
|
27
|
+
|
|
28
|
+
MARKET = 1
|
|
29
|
+
LIMIT = 2
|
|
30
|
+
IOC = 3 # Immediate or Cancel
|
|
31
|
+
FOK = 4 # Fill or Kill
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Sentinel owner id meaning "no owner"; such orders never trigger self-trade
|
|
35
|
+
# prevention (anonymous orders are free to trade with one another).
|
|
36
|
+
NO_OWNER = -1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class SelfTradePolicy(IntEnum):
|
|
40
|
+
"""How the engine handles an order that would match its own owner's resting order.
|
|
41
|
+
|
|
42
|
+
NONE: disabled (default) -- self-trades are allowed.
|
|
43
|
+
CANCEL_RESTING: cancel the same-owner resting order; the incoming order
|
|
44
|
+
continues matching against everyone else.
|
|
45
|
+
CANCEL_INCOMING: cancel the incoming order's unmatched remainder on first
|
|
46
|
+
contact with a same-owner resting order (it does not rest).
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
NONE = 0
|
|
50
|
+
CANCEL_RESTING = 1
|
|
51
|
+
CANCEL_INCOMING = 2
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def normalize_symbol(symbol: str) -> str:
|
|
55
|
+
"""Validate and normalize a trading symbol."""
|
|
56
|
+
if not isinstance(symbol, str):
|
|
57
|
+
raise ValueError(f"Order symbol must be a non-empty string: {symbol!r}")
|
|
58
|
+
|
|
59
|
+
normalized_symbol = symbol.strip()
|
|
60
|
+
if not normalized_symbol:
|
|
61
|
+
raise ValueError("Order symbol must be a non-empty string")
|
|
62
|
+
|
|
63
|
+
return normalized_symbol
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Order:
|
|
67
|
+
"""A single order. Plain ``__slots__`` class for cheap construction and access."""
|
|
68
|
+
|
|
69
|
+
__slots__ = (
|
|
70
|
+
"order_id",
|
|
71
|
+
"symbol",
|
|
72
|
+
"side",
|
|
73
|
+
"order_type",
|
|
74
|
+
"price",
|
|
75
|
+
"quantity",
|
|
76
|
+
"remaining_quantity",
|
|
77
|
+
"timestamp",
|
|
78
|
+
"priority",
|
|
79
|
+
"owner",
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def __init__(self, order_id, symbol, side, order_type, price, quantity, timestamp, owner):
|
|
83
|
+
self.order_id = order_id
|
|
84
|
+
self.symbol = symbol
|
|
85
|
+
self.side = side
|
|
86
|
+
self.order_type = order_type
|
|
87
|
+
self.price = price
|
|
88
|
+
self.quantity = quantity
|
|
89
|
+
self.remaining_quantity = quantity
|
|
90
|
+
self.timestamp = timestamp
|
|
91
|
+
self.priority = timestamp # FIFO priority based on timestamp
|
|
92
|
+
self.owner = owner # participant id for self-trade prevention
|
|
93
|
+
|
|
94
|
+
def is_buy(self):
|
|
95
|
+
"""Check if order is a buy order."""
|
|
96
|
+
return self.side == OrderSide.BUY
|
|
97
|
+
|
|
98
|
+
def is_sell(self):
|
|
99
|
+
"""Check if order is a sell order."""
|
|
100
|
+
return self.side == OrderSide.SELL
|
|
101
|
+
|
|
102
|
+
def is_market_order(self):
|
|
103
|
+
"""Check if order is a market order."""
|
|
104
|
+
return self.order_type == OrderType.MARKET
|
|
105
|
+
|
|
106
|
+
def is_limit_order(self):
|
|
107
|
+
"""Check if order is a limit order."""
|
|
108
|
+
return self.order_type == OrderType.LIMIT
|
|
109
|
+
|
|
110
|
+
def is_filled(self):
|
|
111
|
+
"""Check if order is completely filled."""
|
|
112
|
+
return self.remaining_quantity <= 1e-12
|
|
113
|
+
|
|
114
|
+
def is_ioc_order(self):
|
|
115
|
+
"""Check if order is an Immediate-or-Cancel order."""
|
|
116
|
+
return self.order_type == OrderType.IOC
|
|
117
|
+
|
|
118
|
+
def is_fok_order(self):
|
|
119
|
+
"""Check if order is a Fill-or-Kill order."""
|
|
120
|
+
return self.order_type == OrderType.FOK
|
|
121
|
+
|
|
122
|
+
def can_rest(self):
|
|
123
|
+
"""Return True if any unfilled quantity may remain on the book."""
|
|
124
|
+
return self.order_type == OrderType.LIMIT
|
|
125
|
+
|
|
126
|
+
def can_match_price(self, other_price):
|
|
127
|
+
"""
|
|
128
|
+
Check if this order can match with another price.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
other_price: Price to check against
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
bool: True if prices can match
|
|
135
|
+
"""
|
|
136
|
+
if self.is_market_order():
|
|
137
|
+
return True
|
|
138
|
+
|
|
139
|
+
if self.is_buy():
|
|
140
|
+
return self.price >= other_price
|
|
141
|
+
else:
|
|
142
|
+
return self.price <= other_price
|
|
143
|
+
|
|
144
|
+
def fill(self, quantity):
|
|
145
|
+
"""
|
|
146
|
+
Fill part of the order.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
quantity: Quantity to fill
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
float: Actual quantity filled
|
|
153
|
+
"""
|
|
154
|
+
fill_qty = min(quantity, self.remaining_quantity)
|
|
155
|
+
self.remaining_quantity -= fill_qty
|
|
156
|
+
return fill_qty
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class Trade:
|
|
160
|
+
"""Trade execution result. Plain ``__slots__`` class."""
|
|
161
|
+
|
|
162
|
+
__slots__ = ("buy_order_id", "sell_order_id", "price", "quantity", "timestamp")
|
|
163
|
+
|
|
164
|
+
def __init__(self, buy_order_id, sell_order_id, price, quantity, timestamp):
|
|
165
|
+
self.buy_order_id = buy_order_id
|
|
166
|
+
self.sell_order_id = sell_order_id
|
|
167
|
+
self.price = price
|
|
168
|
+
self.quantity = quantity
|
|
169
|
+
self.timestamp = timestamp
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class OrderFactory:
|
|
173
|
+
"""Factory for creating orders with automatic ID generation."""
|
|
174
|
+
|
|
175
|
+
def __init__(self):
|
|
176
|
+
self._next_id = 1
|
|
177
|
+
self._lock = threading.Lock()
|
|
178
|
+
|
|
179
|
+
def _allocate_order_id(self) -> int:
|
|
180
|
+
"""Allocate a unique order id."""
|
|
181
|
+
with self._lock:
|
|
182
|
+
if self._next_id >= 2**63:
|
|
183
|
+
raise OverflowError("Order id allocator exhausted the positive int64 range")
|
|
184
|
+
order_id = self._next_id
|
|
185
|
+
self._next_id += 1
|
|
186
|
+
return order_id
|
|
187
|
+
|
|
188
|
+
def advance_past(self, order_id: int):
|
|
189
|
+
"""Advance the allocator beyond a caller-supplied order id."""
|
|
190
|
+
with self._lock:
|
|
191
|
+
if order_id >= self._next_id:
|
|
192
|
+
self._next_id = order_id + 1
|
|
193
|
+
|
|
194
|
+
def _validate_side(self, side: OrderSide):
|
|
195
|
+
"""Validate and normalize an order side."""
|
|
196
|
+
if isinstance(side, bool) or not isinstance(side, Integral):
|
|
197
|
+
raise ValueError(f"Unsupported order side: {side}")
|
|
198
|
+
side_value = int(side)
|
|
199
|
+
|
|
200
|
+
if side_value not in (int(OrderSide.BUY), int(OrderSide.SELL)):
|
|
201
|
+
raise ValueError(f"Unsupported order side: {side}")
|
|
202
|
+
return OrderSide(side_value)
|
|
203
|
+
|
|
204
|
+
def _validate_order_type(self, order_type: OrderType):
|
|
205
|
+
"""Validate and normalize an order type."""
|
|
206
|
+
if isinstance(order_type, bool) or not isinstance(order_type, Integral):
|
|
207
|
+
raise ValueError(f"Unsupported order type: {order_type}")
|
|
208
|
+
order_type_value = int(order_type)
|
|
209
|
+
|
|
210
|
+
valid_types = (
|
|
211
|
+
int(OrderType.MARKET),
|
|
212
|
+
int(OrderType.LIMIT),
|
|
213
|
+
int(OrderType.IOC),
|
|
214
|
+
int(OrderType.FOK),
|
|
215
|
+
)
|
|
216
|
+
if order_type_value not in valid_types:
|
|
217
|
+
raise ValueError(f"Unsupported order type: {order_type}")
|
|
218
|
+
return OrderType(order_type_value)
|
|
219
|
+
|
|
220
|
+
def _validate_quantity(self, quantity: float):
|
|
221
|
+
"""Validate that quantity is positive."""
|
|
222
|
+
if isinstance(quantity, bool) or not isinstance(quantity, Real):
|
|
223
|
+
raise ValueError(f"Order quantity must be positive: {quantity!r}")
|
|
224
|
+
quantity = float(quantity)
|
|
225
|
+
if not math.isfinite(quantity) or quantity <= 0:
|
|
226
|
+
raise ValueError(f"Order quantity must be positive: {quantity}")
|
|
227
|
+
return quantity
|
|
228
|
+
|
|
229
|
+
def _validate_owner(self, owner: int):
|
|
230
|
+
"""Validate an owner id (an int64; NO_OWNER means anonymous)."""
|
|
231
|
+
if isinstance(owner, bool) or not isinstance(owner, Integral):
|
|
232
|
+
raise ValueError(f"Order owner must be an integer id: {owner!r}")
|
|
233
|
+
owner = int(owner)
|
|
234
|
+
if not (-(2**63) <= owner < 2**63):
|
|
235
|
+
raise ValueError(f"Order owner id is out of range for int64: {owner}")
|
|
236
|
+
return owner
|
|
237
|
+
|
|
238
|
+
def _validate_price(self, price: float):
|
|
239
|
+
"""Validate that limit-style order price is positive."""
|
|
240
|
+
if isinstance(price, bool) or not isinstance(price, Real):
|
|
241
|
+
raise ValueError(f"Order price must be positive: {price!r}")
|
|
242
|
+
price = float(price)
|
|
243
|
+
if not math.isfinite(price) or price <= 0:
|
|
244
|
+
raise ValueError(f"Order price must be positive: {price}")
|
|
245
|
+
return price
|
|
246
|
+
|
|
247
|
+
def create_order(
|
|
248
|
+
self,
|
|
249
|
+
symbol: str,
|
|
250
|
+
side: OrderSide,
|
|
251
|
+
order_type: OrderType,
|
|
252
|
+
price: float,
|
|
253
|
+
quantity: float,
|
|
254
|
+
owner: int = NO_OWNER,
|
|
255
|
+
) -> Order:
|
|
256
|
+
"""Create an order of the specified type."""
|
|
257
|
+
order_type = self._validate_order_type(order_type)
|
|
258
|
+
if order_type == OrderType.LIMIT:
|
|
259
|
+
return self.create_limit_order(symbol, side, price, quantity, owner)
|
|
260
|
+
elif order_type == OrderType.MARKET:
|
|
261
|
+
return self.create_market_order(symbol, side, quantity, owner)
|
|
262
|
+
elif order_type == OrderType.IOC:
|
|
263
|
+
return self.create_ioc_order(symbol, side, price, quantity, owner)
|
|
264
|
+
elif order_type == OrderType.FOK:
|
|
265
|
+
return self.create_fok_order(symbol, side, price, quantity, owner)
|
|
266
|
+
else:
|
|
267
|
+
raise ValueError(f"Unsupported order type: {order_type}")
|
|
268
|
+
|
|
269
|
+
def create_limit_order(
|
|
270
|
+
self, symbol: str, side: OrderSide, price: float, quantity: float, owner: int = NO_OWNER
|
|
271
|
+
) -> Order:
|
|
272
|
+
"""Create a limit order."""
|
|
273
|
+
symbol = normalize_symbol(symbol)
|
|
274
|
+
side = self._validate_side(side)
|
|
275
|
+
price = self._validate_price(price)
|
|
276
|
+
quantity = self._validate_quantity(quantity)
|
|
277
|
+
owner = self._validate_owner(owner)
|
|
278
|
+
order_id = self._allocate_order_id()
|
|
279
|
+
timestamp = time.time_ns()
|
|
280
|
+
|
|
281
|
+
return Order(
|
|
282
|
+
order_id=order_id,
|
|
283
|
+
symbol=symbol,
|
|
284
|
+
side=int(side),
|
|
285
|
+
order_type=int(OrderType.LIMIT),
|
|
286
|
+
price=price,
|
|
287
|
+
quantity=quantity,
|
|
288
|
+
timestamp=timestamp,
|
|
289
|
+
owner=owner,
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
def create_market_order(
|
|
293
|
+
self, symbol: str, side: OrderSide, quantity: float, owner: int = NO_OWNER
|
|
294
|
+
) -> Order:
|
|
295
|
+
"""Create a market order."""
|
|
296
|
+
symbol = normalize_symbol(symbol)
|
|
297
|
+
side = self._validate_side(side)
|
|
298
|
+
quantity = self._validate_quantity(quantity)
|
|
299
|
+
owner = self._validate_owner(owner)
|
|
300
|
+
order_id = self._allocate_order_id()
|
|
301
|
+
timestamp = time.time_ns()
|
|
302
|
+
|
|
303
|
+
return Order(
|
|
304
|
+
order_id=order_id,
|
|
305
|
+
symbol=symbol,
|
|
306
|
+
side=int(side),
|
|
307
|
+
order_type=int(OrderType.MARKET),
|
|
308
|
+
price=0.0, # Market orders don't have a price limit
|
|
309
|
+
quantity=quantity,
|
|
310
|
+
timestamp=timestamp,
|
|
311
|
+
owner=owner,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
def create_ioc_order(
|
|
315
|
+
self, symbol: str, side: OrderSide, price: float, quantity: float, owner: int = NO_OWNER
|
|
316
|
+
) -> Order:
|
|
317
|
+
"""Create an Immediate or Cancel order."""
|
|
318
|
+
symbol = normalize_symbol(symbol)
|
|
319
|
+
side = self._validate_side(side)
|
|
320
|
+
price = self._validate_price(price)
|
|
321
|
+
quantity = self._validate_quantity(quantity)
|
|
322
|
+
owner = self._validate_owner(owner)
|
|
323
|
+
order_id = self._allocate_order_id()
|
|
324
|
+
timestamp = time.time_ns()
|
|
325
|
+
|
|
326
|
+
return Order(
|
|
327
|
+
order_id=order_id,
|
|
328
|
+
symbol=symbol,
|
|
329
|
+
side=int(side),
|
|
330
|
+
order_type=int(OrderType.IOC),
|
|
331
|
+
price=price,
|
|
332
|
+
quantity=quantity,
|
|
333
|
+
timestamp=timestamp,
|
|
334
|
+
owner=owner,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
def create_fok_order(
|
|
338
|
+
self, symbol: str, side: OrderSide, price: float, quantity: float, owner: int = NO_OWNER
|
|
339
|
+
) -> Order:
|
|
340
|
+
"""Create a Fill or Kill order."""
|
|
341
|
+
symbol = normalize_symbol(symbol)
|
|
342
|
+
side = self._validate_side(side)
|
|
343
|
+
price = self._validate_price(price)
|
|
344
|
+
quantity = self._validate_quantity(quantity)
|
|
345
|
+
owner = self._validate_owner(owner)
|
|
346
|
+
order_id = self._allocate_order_id()
|
|
347
|
+
timestamp = time.time_ns()
|
|
348
|
+
|
|
349
|
+
return Order(
|
|
350
|
+
order_id=order_id,
|
|
351
|
+
symbol=symbol,
|
|
352
|
+
side=int(side),
|
|
353
|
+
order_type=int(OrderType.FOK),
|
|
354
|
+
price=price,
|
|
355
|
+
quantity=quantity,
|
|
356
|
+
timestamp=timestamp,
|
|
357
|
+
owner=owner,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
# Utility functions for order manipulation
|
|
362
|
+
def get_current_timestamp_ns():
|
|
363
|
+
"""Get current timestamp in nanoseconds."""
|
|
364
|
+
return time.time_ns()
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def orders_can_match(buy_order: Order, sell_order: Order) -> bool:
|
|
368
|
+
"""
|
|
369
|
+
Check if two orders can match.
|
|
370
|
+
|
|
371
|
+
Args:
|
|
372
|
+
buy_order: Buy order
|
|
373
|
+
sell_order: Sell order
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
bool: True if orders can match
|
|
377
|
+
"""
|
|
378
|
+
if buy_order.symbol != sell_order.symbol:
|
|
379
|
+
return False
|
|
380
|
+
|
|
381
|
+
if buy_order.is_filled() or sell_order.is_filled():
|
|
382
|
+
return False
|
|
383
|
+
|
|
384
|
+
# Market orders can always match
|
|
385
|
+
if buy_order.is_market_order() or sell_order.is_market_order():
|
|
386
|
+
return True
|
|
387
|
+
|
|
388
|
+
# Limit orders match if buy price >= sell price
|
|
389
|
+
return buy_order.price >= sell_order.price
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def calculate_match_quantity(buy_order: Order, sell_order: Order) -> float:
|
|
393
|
+
"""
|
|
394
|
+
Calculate the execution quantity for matching orders.
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
buy_order: Buy order
|
|
398
|
+
sell_order: Sell order
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
float: Execution quantity
|
|
402
|
+
"""
|
|
403
|
+
return min(buy_order.remaining_quantity, sell_order.remaining_quantity)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def copy_order(order: Order) -> Order:
|
|
407
|
+
"""Return a detached copy of an order.
|
|
408
|
+
|
|
409
|
+
The matching engine intentionally mutates order state while processing fills.
|
|
410
|
+
Public APIs use detached copies so callers and callbacks cannot mutate the
|
|
411
|
+
live price-level indexes through a returned ``Order`` reference.
|
|
412
|
+
"""
|
|
413
|
+
copied = Order(
|
|
414
|
+
order_id=order.order_id,
|
|
415
|
+
symbol=order.symbol,
|
|
416
|
+
side=order.side,
|
|
417
|
+
order_type=order.order_type,
|
|
418
|
+
price=order.price,
|
|
419
|
+
quantity=order.quantity,
|
|
420
|
+
timestamp=order.timestamp,
|
|
421
|
+
owner=order.owner,
|
|
422
|
+
)
|
|
423
|
+
copied.remaining_quantity = order.remaining_quantity
|
|
424
|
+
copied.priority = order.priority
|
|
425
|
+
return copied
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def copy_trade(trade: Trade) -> Trade:
|
|
429
|
+
"""Return a detached copy of a trade record."""
|
|
430
|
+
return Trade(
|
|
431
|
+
buy_order_id=trade.buy_order_id,
|
|
432
|
+
sell_order_id=trade.sell_order_id,
|
|
433
|
+
price=trade.price,
|
|
434
|
+
quantity=trade.quantity,
|
|
435
|
+
timestamp=trade.timestamp,
|
|
436
|
+
)
|