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.
Files changed (36) hide show
  1. tracebook/__init__.py +38 -0
  2. tracebook/_version.py +3 -0
  3. tracebook/benchmarks/__init__.py +1 -0
  4. tracebook/benchmarks/runner.py +234 -0
  5. tracebook/core/__init__.py +0 -0
  6. tracebook/core/matching_engine.py +497 -0
  7. tracebook/core/order.py +436 -0
  8. tracebook/core/orderbook.py +1038 -0
  9. tracebook/core/price_level.py +309 -0
  10. tracebook/core/replay.py +173 -0
  11. tracebook/events/__init__.py +21 -0
  12. tracebook/events/cli.py +83 -0
  13. tracebook/events/market_replay.py +587 -0
  14. tracebook/profiling/__init__.py +0 -0
  15. tracebook/profiling/magic_trace_wrapper.py +595 -0
  16. tracebook/profiling/performance_monitor.py +615 -0
  17. tracebook/profiling/trace_analyzer.py +534 -0
  18. tracebook/profiling/trace_visualizer.py +475 -0
  19. tracebook/py.typed +1 -0
  20. tracebook/simulation/__init__.py +0 -0
  21. tracebook/simulation/order_generator.py +960 -0
  22. tracebook/simulation/simulation_engine.py +701 -0
  23. tracebook/utils/__init__.py +0 -0
  24. tracebook/visualization/__init__.py +0 -0
  25. tracebook/visualization/dashboard.py +698 -0
  26. tracebook/visualization/web/__init__.py +1 -0
  27. tracebook/visualization/web/app.js +146 -0
  28. tracebook/visualization/web/index.html +66 -0
  29. tracebook/visualization/web/styles.css +312 -0
  30. tracebook/visualization/web_server.py +258 -0
  31. tracebook_sim-0.2.0.dist-info/METADATA +627 -0
  32. tracebook_sim-0.2.0.dist-info/RECORD +36 -0
  33. tracebook_sim-0.2.0.dist-info/WHEEL +5 -0
  34. tracebook_sim-0.2.0.dist-info/entry_points.txt +6 -0
  35. tracebook_sim-0.2.0.dist-info/licenses/LICENSE +21 -0
  36. tracebook_sim-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,497 @@
1
+ """
2
+ Order matching engine.
3
+
4
+ Implements the core FIFO and pro-rata matching logic in plain Python over
5
+ dict-backed price levels. (Earlier versions used Numba; profiling showed the
6
+ JIT wrapper was a net cost when driven from the Python matching loop -- see
7
+ docs/performance.md.)
8
+ """
9
+
10
+ from collections import deque
11
+ from typing import Deque, List, Optional, Tuple
12
+ import time
13
+ from .order import (
14
+ NO_OWNER,
15
+ Order,
16
+ SelfTradePolicy,
17
+ Trade,
18
+ calculate_match_quantity,
19
+ orders_can_match,
20
+ )
21
+ from .price_level import PriceLevelManager, MarketDataSnapshot
22
+
23
+ EPSILON = 1e-12
24
+
25
+
26
+ class MatchingEngine:
27
+ """
28
+ Matching engine supporting multiple algorithms.
29
+
30
+ Features:
31
+ - FIFO and pro-rata matching
32
+ - Integer-tick price levels with O(1) in-level insert/removal
33
+ - Optional self-trade prevention
34
+ - Nanosecond-precision timing
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ symbol: str,
40
+ matching_algorithm: str = "fifo",
41
+ tick_size: float = 0.01,
42
+ self_trade_policy: SelfTradePolicy = SelfTradePolicy.NONE,
43
+ ):
44
+ self.symbol = symbol
45
+ self.matching_algorithm = matching_algorithm.lower()
46
+ self.tick_size = tick_size
47
+ self.self_trade_policy = SelfTradePolicy(self_trade_policy)
48
+
49
+ # Price level managers for each side
50
+ self.buy_side = PriceLevelManager(is_buy_side=True, tick_size=tick_size)
51
+ self.sell_side = PriceLevelManager(is_buy_side=False, tick_size=tick_size)
52
+
53
+ # Trade history: bounded so a long-running book doesn't leak memory.
54
+ # get_recent_trades reads the tail; total_matches tracks the true total.
55
+ self._trade_history_cap = 10000
56
+ self.trades: Deque[Trade] = deque(maxlen=self._trade_history_cap)
57
+ self.trade_count = 0
58
+
59
+ # Performance metrics
60
+ self.total_orders_processed = 0
61
+ self.total_matches = 0
62
+ self.self_trades_prevented = 0
63
+ self.last_trade_time = 0
64
+
65
+ # Validate matching algorithm
66
+ if self.matching_algorithm not in ["fifo", "pro_rata"]:
67
+ raise ValueError(f"Unsupported matching algorithm: {matching_algorithm}")
68
+
69
+ def _is_self_trade(self, incoming_order: Order, resting_order: Order) -> bool:
70
+ """Return True if the two orders share a non-anonymous owner."""
71
+ if self.self_trade_policy == SelfTradePolicy.NONE:
72
+ return False
73
+ return incoming_order.owner != NO_OWNER and incoming_order.owner == resting_order.owner
74
+
75
+ def add_order(self, order: Order) -> List[Trade]:
76
+ """
77
+ Add an order to the book and execute any possible matches.
78
+
79
+ Args:
80
+ order: Order to add
81
+
82
+ Returns:
83
+ List[Trade]: List of executed trades
84
+ """
85
+ self.total_orders_processed += 1
86
+ trades: List[Trade] = []
87
+
88
+ # FOK orders must be completely executable before touching resting liquidity.
89
+ if order.is_fok_order() and not self._can_fully_fill(order):
90
+ return trades
91
+
92
+ if order.is_buy():
93
+ trades = self._match_buy_order(order)
94
+ else:
95
+ trades = self._match_sell_order(order)
96
+
97
+ # Add remaining quantity to book if not fully filled
98
+ if order.remaining_quantity > EPSILON and order.can_rest():
99
+ if order.is_buy():
100
+ self.buy_side.add_order(order)
101
+ else:
102
+ self.sell_side.add_order(order)
103
+
104
+ # Update metrics
105
+ self.total_matches += len(trades)
106
+ if trades:
107
+ self.last_trade_time = trades[-1].timestamp
108
+
109
+ return trades
110
+
111
+ def cancel_order(self, order_id: int) -> bool:
112
+ """
113
+ Cancel an order by ID.
114
+
115
+ Args:
116
+ order_id: ID of order to cancel
117
+
118
+ Returns:
119
+ bool: True if order was found and cancelled
120
+ """
121
+ # Try buy side first
122
+ if self.buy_side.remove_order(order_id):
123
+ return True
124
+
125
+ # Try sell side
126
+ return self.sell_side.remove_order(order_id)
127
+
128
+ def _match_buy_order(self, buy_order: Order) -> List[Trade]:
129
+ """Match a buy order against sell side."""
130
+ trades = []
131
+
132
+ while buy_order.remaining_quantity > EPSILON:
133
+ best_sell_level = self.sell_side.get_best_price_level()
134
+ if best_sell_level is None:
135
+ break
136
+
137
+ # Check if prices can match
138
+ if not buy_order.can_match_price(best_sell_level.price):
139
+ break
140
+
141
+ # Execute matches at this price level
142
+ level_trades, progressed = self._execute_matches_at_level(
143
+ buy_order, best_sell_level, self.sell_side
144
+ )
145
+ trades.extend(level_trades)
146
+
147
+ # No trade and nothing cancelled here means no further progress is
148
+ # possible (guards against looping when a level only holds own orders).
149
+ if not progressed:
150
+ break
151
+
152
+ return trades
153
+
154
+ def _match_sell_order(self, sell_order: Order) -> List[Trade]:
155
+ """Match a sell order against buy side."""
156
+ trades = []
157
+
158
+ while sell_order.remaining_quantity > EPSILON:
159
+ best_buy_level = self.buy_side.get_best_price_level()
160
+ if best_buy_level is None:
161
+ break
162
+
163
+ # Check if prices can match
164
+ if not sell_order.can_match_price(best_buy_level.price):
165
+ break
166
+
167
+ # Execute matches at this price level
168
+ level_trades, progressed = self._execute_matches_at_level(
169
+ sell_order, best_buy_level, self.buy_side
170
+ )
171
+ trades.extend(level_trades)
172
+
173
+ if not progressed:
174
+ break
175
+
176
+ return trades
177
+
178
+ def _execute_matches_at_level(
179
+ self, incoming_order: Order, price_level, side_manager
180
+ ) -> Tuple[List[Trade], bool]:
181
+ """Execute matches at a price level. Returns (trades, progressed).
182
+
183
+ `progressed` is True if any trade executed or any resting order was
184
+ cancelled by self-trade prevention, so a level that only holds the
185
+ incoming owner's orders does not stall the outer matching loop.
186
+ """
187
+ if self.matching_algorithm == "pro_rata":
188
+ return self._execute_pro_rata_matches_at_level(
189
+ incoming_order, price_level, side_manager
190
+ )
191
+
192
+ trades = []
193
+ progressed = False
194
+
195
+ # Iterate by repeatedly taking the FIFO head (O(1)) rather than copying
196
+ # the whole level per aggressive order. A matched head is removed by
197
+ # update_order_quantity when fully filled, advancing the head; a partial
198
+ # fill of the incoming order exits the loop with the head still resting.
199
+ while incoming_order.remaining_quantity > EPSILON:
200
+ order_id = price_level.get_first_order_id()
201
+ if order_id == -1:
202
+ break
203
+
204
+ resting_order = side_manager.get_order(order_id)
205
+ if resting_order is None or resting_order.remaining_quantity <= EPSILON:
206
+ # Stale/spent head (unreachable under the level/orders invariant):
207
+ # evict it, cleaning the index if the level empties, then keep
208
+ # matching the depth behind it rather than stalling at this price.
209
+ side_manager.discard_from_level(order_id, price_level)
210
+ progressed = True
211
+ continue
212
+
213
+ if self._is_self_trade(incoming_order, resting_order):
214
+ if self.self_trade_policy == SelfTradePolicy.CANCEL_RESTING:
215
+ side_manager.remove_order(order_id)
216
+ self.self_trades_prevented += 1
217
+ progressed = True
218
+ continue
219
+ # CANCEL_INCOMING: drop the aggressor's remainder and stop here
220
+ # so it never rests into a self-cross.
221
+ self.self_trades_prevented += 1
222
+ incoming_order.remaining_quantity = 0.0
223
+ progressed = True
224
+ break
225
+
226
+ trade = self._execute_fifo_match(incoming_order, resting_order)
227
+ if trade is None:
228
+ break # no progress possible (guards against a stuck head)
229
+
230
+ trades.append(trade)
231
+ fill_qty = trade.quantity
232
+ incoming_order.fill(fill_qty)
233
+ side_manager.update_order_quantity(order_id, fill_qty)
234
+ progressed = True
235
+
236
+ return trades, progressed
237
+
238
+ def _execute_pro_rata_matches_at_level(
239
+ self, incoming_order: Order, price_level, side_manager
240
+ ) -> Tuple[List[Trade], bool]:
241
+ """Allocate the incoming order proportionally across resting orders at a level.
242
+
243
+ Returns (trades, progressed). Same-owner resting orders are excluded from
244
+ the allocation under self-trade prevention (and cancelled under
245
+ CANCEL_RESTING); CANCEL_INCOMING drops the aggressor's remainder once it
246
+ has contacted any same-owner order at the level.
247
+ """
248
+ trades: List[Trade] = []
249
+ progressed = False
250
+ resting_orders = []
251
+ self_trade_seen = False
252
+
253
+ for order_id in list(price_level.orders):
254
+ resting_order = side_manager.get_order(order_id)
255
+ if resting_order is None or resting_order.remaining_quantity <= EPSILON:
256
+ continue
257
+
258
+ if not orders_can_match(
259
+ incoming_order if incoming_order.is_buy() else resting_order,
260
+ resting_order if resting_order.is_sell() else incoming_order,
261
+ ):
262
+ continue
263
+
264
+ if self._is_self_trade(incoming_order, resting_order):
265
+ self_trade_seen = True
266
+ if self.self_trade_policy == SelfTradePolicy.CANCEL_RESTING:
267
+ side_manager.remove_order(order_id)
268
+ self.self_trades_prevented += 1
269
+ progressed = True
270
+ # Either way the own order is excluded from the allocation.
271
+ continue
272
+
273
+ resting_orders.append(resting_order)
274
+
275
+ available_quantity = sum(order.remaining_quantity for order in resting_orders)
276
+ if available_quantity <= EPSILON:
277
+ if self_trade_seen and self.self_trade_policy == SelfTradePolicy.CANCEL_INCOMING:
278
+ self.self_trades_prevented += 1
279
+ incoming_order.remaining_quantity = 0.0
280
+ progressed = True
281
+ return trades, progressed
282
+
283
+ total_fill = min(incoming_order.remaining_quantity, available_quantity)
284
+ remaining_fill = total_fill
285
+
286
+ for index, resting_order in enumerate(resting_orders):
287
+ if incoming_order.remaining_quantity <= EPSILON or remaining_fill <= EPSILON:
288
+ break
289
+
290
+ if index == len(resting_orders) - 1:
291
+ fill_qty = min(resting_order.remaining_quantity, remaining_fill)
292
+ else:
293
+ allocation = total_fill * (resting_order.remaining_quantity / available_quantity)
294
+ fill_qty = min(resting_order.remaining_quantity, allocation, remaining_fill)
295
+
296
+ if fill_qty <= EPSILON:
297
+ continue
298
+
299
+ if incoming_order.is_buy():
300
+ buy_order_id = incoming_order.order_id
301
+ sell_order_id = resting_order.order_id
302
+ else:
303
+ buy_order_id = resting_order.order_id
304
+ sell_order_id = incoming_order.order_id
305
+
306
+ # Matches always execute at the resting (maker) order's price. When a
307
+ # market order is involved the resting side is always the limit order,
308
+ # so this yields the same value the old price-time rule produced --
309
+ # the book now has a single, consistent execution-price rule.
310
+ execution_price = resting_order.price
311
+
312
+ trade = Trade(
313
+ buy_order_id=buy_order_id,
314
+ sell_order_id=sell_order_id,
315
+ price=execution_price,
316
+ quantity=fill_qty,
317
+ timestamp=time.time_ns(),
318
+ )
319
+ self.trades.append(trade)
320
+ trades.append(trade)
321
+
322
+ incoming_order.fill(fill_qty)
323
+ side_manager.update_order_quantity(resting_order.order_id, fill_qty)
324
+ remaining_fill -= fill_qty
325
+ progressed = True
326
+
327
+ # Having contacted a same-owner order, CANCEL_INCOMING drops the remainder
328
+ # after allocating to everyone else at this level.
329
+ if self_trade_seen and self.self_trade_policy == SelfTradePolicy.CANCEL_INCOMING:
330
+ self.self_trades_prevented += 1
331
+ incoming_order.remaining_quantity = 0.0
332
+ progressed = True
333
+
334
+ return trades, progressed
335
+
336
+ def _execute_fifo_match(self, incoming_order: Order, resting_order: Order) -> Optional[Trade]:
337
+ """Execute a FIFO match between two orders."""
338
+ if not orders_can_match(
339
+ incoming_order if incoming_order.is_buy() else resting_order,
340
+ resting_order if resting_order.is_sell() else incoming_order,
341
+ ):
342
+ return None
343
+
344
+ buy_order = incoming_order if incoming_order.is_buy() else resting_order
345
+ sell_order = resting_order if resting_order.is_sell() else incoming_order
346
+
347
+ # Executions use the resting order's price. This keeps matching
348
+ # deterministic even when caller-supplied timestamps are unusual.
349
+ execution_price = resting_order.price
350
+ execution_quantity = calculate_match_quantity(buy_order, sell_order)
351
+
352
+ if incoming_order.is_buy():
353
+ buy_order_id = incoming_order.order_id
354
+ sell_order_id = resting_order.order_id
355
+ else:
356
+ buy_order_id = resting_order.order_id
357
+ sell_order_id = incoming_order.order_id
358
+
359
+ if execution_quantity > EPSILON:
360
+ trade = Trade(
361
+ buy_order_id=buy_order_id,
362
+ sell_order_id=sell_order_id,
363
+ price=execution_price,
364
+ quantity=execution_quantity,
365
+ timestamp=time.time_ns(),
366
+ )
367
+ self.trades.append(trade)
368
+ return trade
369
+
370
+ return None
371
+
372
+ def _can_fully_fill(self, order: Order) -> bool:
373
+ """Return True if the visible opposite book can fill the full order.
374
+
375
+ The accounting mirrors how each self-trade policy actually matches so a
376
+ FOK is never misreported as fillable:
377
+ - NONE: all resting quantity counts.
378
+ - CANCEL_RESTING: the order's own resting quantity is skipped (it would
379
+ be cancelled), and matching continues past it.
380
+ - CANCEL_INCOMING: FIFO matching halts at the first same-owner order;
381
+ pro-rata can use all non-self liquidity at that price level before the
382
+ incoming remainder is cancelled.
383
+ """
384
+ remaining_needed = order.remaining_quantity
385
+ side_manager = self.sell_side if order.is_buy() else self.buy_side
386
+ policy = self.self_trade_policy
387
+ owner_aware = policy != SelfTradePolicy.NONE and order.owner != NO_OWNER
388
+
389
+ for tick in list(side_manager.sorted_ticks):
390
+ level = side_manager.price_levels[tick]
391
+ if not order.can_match_price(level.price):
392
+ break
393
+
394
+ if not owner_aware:
395
+ remaining_needed -= level.total_quantity
396
+ if remaining_needed <= EPSILON:
397
+ return True
398
+ continue
399
+
400
+ # Pro-rata considers every resting order at a level together. Under
401
+ # CANCEL_INCOMING it allocates against all non-self liquidity at that
402
+ # level, then cancels only an unfilled remainder if self liquidity was
403
+ # present. FOK preflight must mirror that level-wide behavior rather
404
+ # than inheriting FIFO insertion-order semantics.
405
+ if self.matching_algorithm == "pro_rata" and policy == SelfTradePolicy.CANCEL_INCOMING:
406
+ self_trade_seen = False
407
+ for resting_id in level.orders:
408
+ resting = side_manager.get_order(resting_id)
409
+ if resting is None:
410
+ continue
411
+ if resting.owner == order.owner:
412
+ self_trade_seen = True
413
+ else:
414
+ remaining_needed -= resting.remaining_quantity
415
+ if remaining_needed <= EPSILON:
416
+ return True
417
+ if self_trade_seen:
418
+ return False
419
+ continue
420
+
421
+ for resting_id in level.orders:
422
+ resting = side_manager.get_order(resting_id)
423
+ if resting is None:
424
+ continue
425
+ if resting.owner == order.owner:
426
+ if policy == SelfTradePolicy.CANCEL_INCOMING:
427
+ # Matching would stop here; nothing beyond is reachable.
428
+ return False
429
+ # CANCEL_RESTING: own order is skipped, keep scanning.
430
+ continue
431
+ remaining_needed -= resting.remaining_quantity
432
+ if remaining_needed <= EPSILON:
433
+ return True
434
+
435
+ return False
436
+
437
+ def can_fully_fill(self, order: Order) -> bool:
438
+ """Return True if an incoming order could fully fill immediately."""
439
+ return self._can_fully_fill(order)
440
+
441
+ def get_market_data_snapshot(self) -> MarketDataSnapshot:
442
+ """Get current market data snapshot."""
443
+ snapshot = MarketDataSnapshot(self.symbol, time.time_ns())
444
+
445
+ # Get bid levels (buy side)
446
+ snapshot.set_bid_levels(self.buy_side.get_price_levels_snapshot())
447
+
448
+ # Get ask levels (sell side)
449
+ snapshot.set_ask_levels(self.sell_side.get_price_levels_snapshot())
450
+
451
+ # Calculate derived metrics
452
+ snapshot.calculate_derived_metrics()
453
+
454
+ return snapshot
455
+
456
+ def get_order_book_depth(self, levels: int = 5) -> dict:
457
+ """Get order book depth up to specified levels."""
458
+ if levels < 0:
459
+ raise ValueError("levels must be non-negative")
460
+
461
+ bid_levels = self.buy_side.get_price_levels_snapshot()[:levels]
462
+ ask_levels = self.sell_side.get_price_levels_snapshot()[:levels]
463
+
464
+ return {
465
+ "symbol": self.symbol,
466
+ "timestamp": time.time_ns(),
467
+ "bids": bid_levels,
468
+ "asks": ask_levels,
469
+ }
470
+
471
+ def get_statistics(self) -> dict:
472
+ """Get matching engine statistics."""
473
+ return {
474
+ "symbol": self.symbol,
475
+ "matching_algorithm": self.matching_algorithm,
476
+ "self_trade_policy": self.self_trade_policy.name,
477
+ "total_orders_processed": self.total_orders_processed,
478
+ "total_matches": self.total_matches,
479
+ "total_trades": self.total_matches, # cumulative; self.trades is a bounded tail
480
+ "self_trades_prevented": self.self_trades_prevented,
481
+ "buy_side_orders": self.buy_side.get_total_orders(),
482
+ "sell_side_orders": self.sell_side.get_total_orders(),
483
+ "buy_side_quantity": self.buy_side.get_total_quantity(),
484
+ "sell_side_quantity": self.sell_side.get_total_quantity(),
485
+ "last_trade_time": self.last_trade_time,
486
+ }
487
+
488
+ def clear(self):
489
+ """Clear all orders and trades."""
490
+ self.buy_side.clear()
491
+ self.sell_side.clear()
492
+ self.trades.clear()
493
+ self.trade_count = 0
494
+ self.total_orders_processed = 0
495
+ self.total_matches = 0
496
+ self.self_trades_prevented = 0
497
+ self.last_trade_time = 0