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/replay.py ADDED
@@ -0,0 +1,673 @@
1
+ """Replay historical order-book data through the matching engine.
2
+
3
+ The input is order-by-order (L3) data in the LOBSTER format (lobsterdata.com),
4
+ the standard academic reconstruction of NASDAQ TotalView-ITCH: a *message* file
5
+ with one row per book event and an *orderbook* file with the top ``N`` price
6
+ levels after each message.
7
+
8
+ Replaying a day does two things:
9
+
10
+ * **Reconstruction.** [`check_reconstruction()`][microbook.replay.check_reconstruction] rebuilds the book message by
11
+ message and compares it with the exchange's own snapshots. It is a direct
12
+ test of the engine's price-time priority against real exchange behaviour.
13
+ * **Strategy backtests.** [`build_replay()`][microbook.replay.build_replay] puts a
14
+ [`HistoricalFlow`][microbook.replay.HistoricalFlow] agent into a
15
+ [`MarketSimulator`][microbook.sim.MarketSimulator], so any
16
+ [`Strategy`][microbook.sim.Strategy] (with its latency, timers and analytics) can
17
+ trade against the historical order flow.
18
+
19
+ How messages become book operations
20
+ -----------------------------------
21
+
22
+ ==================== =========================================================
23
+ LOBSTER event Replayed as
24
+ ==================== =========================================================
25
+ 1 new limit order a GTC limit order
26
+ 2 partial cancel ``reduce`` (cancel-by-size, keeps priority)
27
+ 3 deletion cancel
28
+ 4 visible execution an IOC from the *aggressor's* side at the execution price,
29
+ so it matches by price-time priority and can hit a
30
+ strategy's order that is ahead in the queue
31
+ 5 hidden execution nothing (hidden liquidity is not in the visible book)
32
+ 6 auction cross nothing
33
+ 7 trading halt nothing
34
+ ==================== =========================================================
35
+
36
+ Orders resting before the first message are unknown individually: the book is
37
+ seeded with one aggregate order per price level from the first snapshot, and
38
+ later messages about such orders act on that level's aggregate.
39
+
40
+ Backtest assumptions
41
+ --------------------
42
+
43
+ The historical flow does not react to the strategy (no market impact
44
+ feedback), and the recorded book is kept intact around the strategy's orders:
45
+
46
+ * when a replayed execution fills a strategy's order ahead of the historical
47
+ order it hit, that historical order is reduced by the same amount, so the
48
+ strategy is filled exactly when history reaches its place in the queue;
49
+ * when a new historical limit order crosses a strategy's quote on arrival (in
50
+ history it rested), the strategy keeps the fill and the order's resting
51
+ size is restored.
52
+
53
+ With these rules a passive strategy whose orders are small next to the
54
+ historical ones leaves the recorded book exactly as it was (tested). The
55
+ replay becomes counterfactual when a strategy takes liquidity, or when its
56
+ quote swallows a whole incoming order, which then never rests; the
57
+ ``stats`` of [`HistoricalFlow`][microbook.replay.HistoricalFlow] count both (``unfilled_execution_qty``,
58
+ ``rejected``).
59
+ """
60
+
61
+ from __future__ import annotations
62
+
63
+ import csv
64
+ import math
65
+ import os
66
+ import random
67
+ from collections import Counter
68
+ from collections.abc import Sequence
69
+ from dataclasses import dataclass
70
+ from enum import IntEnum
71
+ from itertools import pairwise
72
+ from typing import NamedTuple
73
+
74
+ from .book import LimitOrderBook
75
+ from .order import Order
76
+ from .sim.events import EventType
77
+ from .sim.simulator import MarketSimulator
78
+ from .sim.strategy import Action, Strategy
79
+ from .types import ExecutionReport, Fill, OrderStatus, Side, STPMode, TimeInForce
80
+
81
+ __all__ = [
82
+ "PRICE_SCALE",
83
+ "BookSnapshot",
84
+ "HistoricalFlow",
85
+ "LobsterDay",
86
+ "Message",
87
+ "MessageType",
88
+ "ReconstructionReport",
89
+ "Replay",
90
+ "build_replay",
91
+ "check_reconstruction",
92
+ "load_lobster",
93
+ "read_lobster_messages",
94
+ "read_lobster_orderbook",
95
+ "synthetic_day",
96
+ "write_lobster",
97
+ ]
98
+
99
+ PRICE_SCALE = 10_000.0 # LOBSTER prices are dollars x 10,000
100
+ _DUMMY_ASK = 9_999_999_999
101
+ _DUMMY_BID = -9_999_999_999
102
+
103
+ PathLike = str | os.PathLike[str]
104
+
105
+
106
+ class MessageType(IntEnum):
107
+ """LOBSTER event types."""
108
+
109
+ SUBMIT = 1
110
+ CANCEL = 2 # partial cancellation
111
+ DELETE = 3 # full deletion
112
+ EXECUTE = 4 # execution of a visible limit order
113
+ EXECUTE_HIDDEN = 5
114
+ CROSS = 6 # auction trade
115
+ HALT = 7
116
+
117
+
118
+ class Message(NamedTuple):
119
+ """One row of a LOBSTER message file."""
120
+
121
+ time: float
122
+ """Seconds after midnight."""
123
+ kind: int
124
+ """Event type, a `MessageType` value."""
125
+ order_id: int
126
+ """Exchange order id."""
127
+ size: int
128
+ """Shares."""
129
+ price: float
130
+ """Price, in dollars."""
131
+ direction: int
132
+ """+1 for a buy limit order, -1 for a sell; for an execution, the side of the resting order."""
133
+
134
+
135
+ class BookSnapshot(NamedTuple):
136
+ """Visible price levels, best first, as ``(price, size)``."""
137
+
138
+ bids: tuple[tuple[float, int], ...]
139
+ """Bid levels, best first, as `(price, size)`."""
140
+ asks: tuple[tuple[float, int], ...]
141
+ """Ask levels, best first, as `(price, size)`."""
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class LobsterDay:
146
+ """A replayable day: the book before ``messages[0]`` and the book after each message."""
147
+
148
+ messages: list[Message]
149
+ """The day's messages, in order."""
150
+ initial_book: BookSnapshot
151
+ """The book before the first message."""
152
+ snapshots: list[BookSnapshot]
153
+ """The book after each message: `snapshots[i]` follows `messages[i]`."""
154
+
155
+ @property
156
+ def levels(self) -> int:
157
+ """Number of price levels per side the snapshots carry."""
158
+ return max((max(len(s.bids), len(s.asks)) for s in self.snapshots), default=0)
159
+
160
+
161
+ # --------------------------------------------------------------------------- #
162
+ # LOBSTER files #
163
+ # --------------------------------------------------------------------------- #
164
+
165
+
166
+ def read_lobster_messages(path: PathLike, *, price_scale: float = PRICE_SCALE) -> list[Message]:
167
+ """Parse a LOBSTER message file (``*_message_N.csv``; no header)."""
168
+ out: list[Message] = []
169
+ with open(path, newline="") as f:
170
+ for row in csv.reader(f):
171
+ if not row:
172
+ continue
173
+ out.append(
174
+ Message(float(row[0]), int(row[1]), int(row[2]), int(row[3]), int(row[4]) / price_scale, int(row[5]))
175
+ )
176
+ return out
177
+
178
+
179
+ def read_lobster_orderbook(path: PathLike, *, price_scale: float = PRICE_SCALE) -> list[BookSnapshot]:
180
+ """Parse a LOBSTER orderbook file (``*_orderbook_N.csv``; no header).
181
+
182
+ Each row holds ``ask price, ask size, bid price, bid size`` for levels
183
+ 1..N. Empty levels (LOBSTER's dummy prices, or size 0) are dropped.
184
+ """
185
+ out: list[BookSnapshot] = []
186
+ with open(path, newline="") as f:
187
+ for row in csv.reader(f):
188
+ if not row:
189
+ continue
190
+ vals = [int(x) for x in row]
191
+ if len(vals) % 4:
192
+ raise ValueError(f"orderbook row has {len(vals)} columns, expected a multiple of 4")
193
+ asks: list[tuple[float, int]] = []
194
+ bids: list[tuple[float, int]] = []
195
+ for i in range(0, len(vals), 4):
196
+ ap, asz, bp, bsz = vals[i : i + 4]
197
+ if asz > 0 and ap != _DUMMY_ASK:
198
+ asks.append((ap / price_scale, asz))
199
+ if bsz > 0 and bp != _DUMMY_BID:
200
+ bids.append((bp / price_scale, bsz))
201
+ out.append(BookSnapshot(tuple(bids), tuple(asks)))
202
+ return out
203
+
204
+
205
+ def load_lobster(
206
+ message_path: PathLike,
207
+ orderbook_path: PathLike,
208
+ *,
209
+ price_scale: float = PRICE_SCALE,
210
+ max_messages: int | None = None,
211
+ ) -> LobsterDay:
212
+ """Load a LOBSTER message/orderbook pair as a [`LobsterDay`][microbook.replay.LobsterDay].
213
+
214
+ The book after the first message seeds the replay, which then starts at
215
+ the second message (the orders resting at the open are not in the file).
216
+ """
217
+ messages = read_lobster_messages(message_path, price_scale=price_scale)
218
+ snapshots = read_lobster_orderbook(orderbook_path, price_scale=price_scale)
219
+ if len(messages) != len(snapshots):
220
+ raise ValueError(f"{len(messages)} messages but {len(snapshots)} orderbook rows")
221
+ if not messages:
222
+ raise ValueError("empty LOBSTER files")
223
+ if max_messages is not None:
224
+ messages, snapshots = messages[: max_messages + 1], snapshots[: max_messages + 1]
225
+ return LobsterDay(messages[1:], snapshots[0], snapshots[1:])
226
+
227
+
228
+ def write_lobster(
229
+ day: LobsterDay,
230
+ message_path: PathLike,
231
+ orderbook_path: PathLike,
232
+ *,
233
+ levels: int | None = None,
234
+ price_scale: float = PRICE_SCALE,
235
+ ) -> None:
236
+ """Write ``day.messages`` and ``day.snapshots`` in the LOBSTER file format."""
237
+ n = levels if levels is not None else day.levels
238
+ with open(message_path, "w", newline="") as f:
239
+ w = csv.writer(f)
240
+ for m in day.messages:
241
+ w.writerow([f"{m.time:.9f}", m.kind, m.order_id, m.size, round(m.price * price_scale), m.direction])
242
+ with open(orderbook_path, "w", newline="") as f:
243
+ w = csv.writer(f)
244
+ for s in day.snapshots:
245
+ row: list[int] = []
246
+ for i in range(n):
247
+ ap, asz = (round(s.asks[i][0] * price_scale), s.asks[i][1]) if i < len(s.asks) else (_DUMMY_ASK, 0)
248
+ bp, bsz = (round(s.bids[i][0] * price_scale), s.bids[i][1]) if i < len(s.bids) else (_DUMMY_BID, 0)
249
+ row += [ap, asz, bp, bsz]
250
+ w.writerow(row)
251
+
252
+
253
+ # --------------------------------------------------------------------------- #
254
+ # Replay agent #
255
+ # --------------------------------------------------------------------------- #
256
+
257
+
258
+ class HistoricalFlow(Strategy):
259
+ """Replays historical messages into a [`MarketSimulator`][microbook.sim.MarketSimulator].
260
+
261
+ Message times map onto the integer clock as
262
+ ``1 + round((time - first_time) / time_unit)`` (``time_unit`` in seconds,
263
+ default 1 ms), so strategy latencies, timers and snapshot intervals are in
264
+ the same unit. Messages that share a clock tick are applied in file order.
265
+
266
+ ``stats`` counts replayed message types plus ``rejected`` (operations the
267
+ book refused, e.g. a cancel for an order a strategy already consumed) and
268
+ ``unfilled_execution_qty`` (historical executions that found less
269
+ liquidity than recorded). Both are zero for an exact reconstruction.
270
+ """
271
+
272
+ same_time_timers = True
273
+
274
+ def __init__(
275
+ self,
276
+ messages: Sequence[Message],
277
+ *,
278
+ initial_book: BookSnapshot | None = None,
279
+ tick_size: float = 0.01,
280
+ time_unit: float = 1e-3,
281
+ name: str = "hist",
282
+ ) -> None:
283
+ super().__init__(name)
284
+ if time_unit <= 0 or not math.isfinite(time_unit):
285
+ raise ValueError("time_unit must be positive")
286
+ self.messages = list(messages)
287
+ self.initial_book = initial_book
288
+ self.tick_size = tick_size
289
+ self.time_unit = time_unit
290
+ self.t0 = self.messages[0].time if self.messages else 0.0
291
+ self._times = [self.to_sim_time(m.time) for m in self.messages]
292
+ if any(b < a for a, b in pairwise(self._times)):
293
+ raise ValueError("messages must be in time order")
294
+ self._next = 0
295
+ self._prefix = f"{name}:"
296
+ self._known: set[int] = set() # order ids submitted during the replay
297
+ self._ioc_target: dict[str, str] = {} # replayed execution -> historical order it hit
298
+ self._n_exec = 0
299
+ self.stats: Counter[str] = Counter()
300
+
301
+ # --- clock ----------------------------------------------------------------
302
+
303
+ def to_sim_time(self, seconds: float) -> int:
304
+ """Simulator time step of a LOBSTER timestamp (seconds after midnight)."""
305
+ return 1 + round((seconds - self.t0) / self.time_unit)
306
+
307
+ @property
308
+ def horizon(self) -> int:
309
+ """Simulation time of the last message."""
310
+ return self._times[-1] if self._times else 0
311
+
312
+ # --- translation (also used by check_reconstruction) ----------------------
313
+
314
+ def _seed_id(self, side: Side, price: float) -> str:
315
+ return f"{self._prefix}seed:{side.value[0]}{round(price / self.tick_size)}"
316
+
317
+ def is_historical(self, order_id: str) -> bool:
318
+ """Whether ``order_id`` belongs to the replayed history rather than to a strategy."""
319
+ return order_id.startswith(self._prefix)
320
+
321
+ def seed_actions(self, now: int) -> list[Action]:
322
+ """One aggregate order per visible level of ``initial_book``."""
323
+ if self.initial_book is None:
324
+ return []
325
+ actions: list[Action] = []
326
+ for side, levels in ((Side.BUY, self.initial_book.bids), (Side.SELL, self.initial_book.asks)):
327
+ for px, qty in levels:
328
+ oid = self._seed_id(side, px)
329
+ actions.append(Action.submit(Order.limit(oid, side, px, qty, ts=now, owner=oid), now))
330
+ return actions
331
+
332
+ def translate(self, m: Message, now: int) -> list[Action]:
333
+ """Book operations for one message (see the module docstring)."""
334
+ kind = m.kind
335
+ try:
336
+ self.stats[MessageType(kind).name.lower()] += 1
337
+ except ValueError:
338
+ self.stats["unknown"] += 1
339
+ return []
340
+ if kind > MessageType.EXECUTE:
341
+ return [] # hidden executions, auction crosses and halts leave the visible book unchanged
342
+ side = Side.BUY if m.direction > 0 else Side.SELL
343
+ if kind == MessageType.SUBMIT:
344
+ self._known.add(m.order_id)
345
+ oid = f"{self._prefix}{m.order_id}"
346
+ return [Action.submit(Order.limit(oid, side, m.price, m.size, ts=now, owner=oid), now)]
347
+
348
+ known = m.order_id in self._known
349
+ target = f"{self._prefix}{m.order_id}" if known else self._seed_id(side, m.price)
350
+ if kind == MessageType.CANCEL:
351
+ return [Action.reduce(target, now, m.size)]
352
+ if kind == MessageType.DELETE:
353
+ return [Action.cancel(target, now) if known else Action.reduce(target, now, m.size)]
354
+ # EXECUTE: replay the aggressor, so the fill goes to whoever has priority
355
+ self._n_exec += 1
356
+ xid = f"{self._prefix}x{self._n_exec}"
357
+ self._ioc_target[xid] = target
358
+ ioc = Order.limit(xid, side.opposite, m.price, m.size, ts=now, tif=TimeInForce.IOC, owner=xid)
359
+ return [Action.submit(ioc, now)]
360
+
361
+ # --- strategy hooks -------------------------------------------------------
362
+
363
+ def on_start(self, now: int, lob: LimitOrderBook) -> list[Action]:
364
+ """Seed the book with the initial snapshot and schedule the first message."""
365
+ actions = self.seed_actions(now)
366
+ if self.messages:
367
+ actions.append(Action.timer(self._times[0]))
368
+ return actions
369
+
370
+ def on_timer(self, now: int, lob: LimitOrderBook) -> list[Action]:
371
+ """Apply the next historical message and schedule a wake-up for the one after."""
372
+ # One message per wake-up, even when several share a clock tick: the
373
+ # corrections issued in on_fill/on_report for message k must reach the
374
+ # book before message k+1 (same_time_timers makes the next timer queue
375
+ # behind them).
376
+ i = self._next
377
+ actions = self.translate(self.messages[i], now)
378
+ self._next = i + 1
379
+ if self._next < len(self.messages):
380
+ actions.append(Action.timer(self._times[self._next]))
381
+ return actions
382
+
383
+ def on_fill(self, now: int, fill: Fill, side: Side, is_maker: bool, lob: LimitOrderBook) -> list[Action]:
384
+ """When a replayed execution fills a strategy's order, shrink the historical order it was meant for."""
385
+ if is_maker or self.is_historical(fill.maker_order_id):
386
+ return []
387
+ target = self._ioc_target.get(fill.taker_order_id)
388
+ if target is None:
389
+ return []
390
+ # A replayed execution filled a strategy's order ahead of the historical
391
+ # one; remove the same quantity from the historical order so the
392
+ # historical book is preserved.
393
+ return [Action.reduce(target, now, fill.qty)]
394
+
395
+ def on_report(self, now: int, report: ExecutionReport) -> list[Action]:
396
+ """Track execution outcomes and restore historical orders that crossed a strategy's quote."""
397
+ if self._record(report) or not report.fills or report.resting_qty == 0:
398
+ return []
399
+ # A historical limit order crossed a strategy's quote on arrival (in history
400
+ # it rested in full). The strategy keeps its fill; the order's resting size
401
+ # is restored so the historical book is preserved. It was the newest order
402
+ # at its price, so re-queueing it at the back keeps its priority.
403
+ crossed = sum(f.qty for f in report.fills if not self.is_historical(f.maker_order_id))
404
+ if not crossed:
405
+ return []
406
+ self.stats["crossed_strategy_qty"] += crossed
407
+ return [Action.modify(report.order_id, now, new_qty=report.resting_qty + crossed)]
408
+
409
+ def _record(self, report: ExecutionReport) -> bool:
410
+ """Update ``stats``; returns whether ``report`` is for a replayed execution."""
411
+ is_exec = self._ioc_target.pop(report.order_id, None) is not None
412
+ if report.status is OrderStatus.REJECTED:
413
+ self.stats["rejected"] += 1
414
+ elif is_exec and report.canceled_qty:
415
+ self.stats["unfilled_execution_qty"] += report.canceled_qty
416
+ return is_exec
417
+
418
+
419
+ @dataclass
420
+ class Replay:
421
+ """A simulator wired to replay one day (see [`build_replay()`][microbook.replay.build_replay])."""
422
+
423
+ sim: MarketSimulator
424
+ """The simulator, holding the historical flow and your strategies."""
425
+ flow: HistoricalFlow
426
+ """The agent that replays the historical messages."""
427
+
428
+ def run(self, until: int | None = None) -> MarketSimulator:
429
+ """Run to ``until`` (default: the last message)."""
430
+ self.sim.run(self.flow.horizon if until is None else until)
431
+ return self.sim
432
+
433
+
434
+ def build_replay(
435
+ day: LobsterDay,
436
+ strategies: Sequence[Strategy] = (),
437
+ *,
438
+ tick_size: float = 0.01,
439
+ time_unit: float = 1e-3,
440
+ snapshot_every: int = 100,
441
+ record_snapshots: bool = False,
442
+ name: str = "hist",
443
+ ) -> Replay:
444
+ """A simulator that replays ``day`` with ``strategies`` trading alongside.
445
+
446
+ ``snapshot_every`` (in ``time_unit``s; default 100 ms) sets how often
447
+ SNAPSHOT events fire, which drives ``on_tick`` and the PnL series.
448
+ """
449
+ flow = HistoricalFlow(
450
+ day.messages, initial_book=day.initial_book, tick_size=tick_size, time_unit=time_unit, name=name
451
+ )
452
+ lob = LimitOrderBook(tick_size, stp=STPMode.CANCEL_RESTING)
453
+ sim = MarketSimulator(lob, [flow, *strategies], record_snapshots=record_snapshots)
454
+ sim.schedule_snapshots(0, flow.horizon, snapshot_every)
455
+ return Replay(sim, flow)
456
+
457
+
458
+ # --------------------------------------------------------------------------- #
459
+ # Reconstruction check #
460
+ # --------------------------------------------------------------------------- #
461
+
462
+
463
+ @dataclass(frozen=True)
464
+ class ReconstructionReport:
465
+ """How closely the replayed book tracks the recorded snapshots."""
466
+
467
+ messages: int
468
+ """Number of messages replayed."""
469
+ levels: int
470
+ """Price levels per side compared."""
471
+ top_of_book_match: float
472
+ """Fraction of messages after which the best bid and ask (price and size) match."""
473
+ depth_match: float
474
+ """Fraction of messages after which all `levels` levels on both sides match."""
475
+ first_mismatch: int | None
476
+ """Index of the first message whose snapshot differs; `None` if all match."""
477
+ rejected: int
478
+ """Messages the engine rejected."""
479
+ unfilled_execution_qty: int
480
+ """Shares of historical executions that found less resting quantity than recorded."""
481
+
482
+
483
+ def _apply(lob: LimitOrderBook, a: Action) -> ExecutionReport | None:
484
+ kw = a.kwargs
485
+ if a.etype is EventType.SUBMIT:
486
+ return lob.submit(kw["order"])
487
+ if a.etype is EventType.CANCEL:
488
+ lob.cancel(kw["order_id"])
489
+ return None
490
+ mod = kw["modify"]
491
+ if "reduce_by" in mod:
492
+ return lob.reduce(kw["order_id"], mod["reduce_by"])
493
+ return lob.modify(kw["order_id"], **mod)
494
+
495
+
496
+ def check_reconstruction(
497
+ day: LobsterDay, *, tick_size: float = 0.01, levels: int | None = None
498
+ ) -> ReconstructionReport:
499
+ """Rebuild the book from ``day.messages`` and compare it with ``day.snapshots``."""
500
+ n_levels = levels if levels is not None else day.levels
501
+ flow = HistoricalFlow(day.messages, initial_book=day.initial_book, tick_size=tick_size)
502
+ lob = LimitOrderBook(tick_size, stp=STPMode.CANCEL_RESTING)
503
+ for a in flow.seed_actions(0):
504
+ _apply(lob, a)
505
+
506
+ def ticks(levels_: Sequence[tuple[float, int]]) -> list[tuple[int, int]]:
507
+ return [(round(p / tick_size), q) for p, q in levels_[:n_levels]]
508
+
509
+ top = full = 0
510
+ first: int | None = None
511
+ for k, (m, snap) in enumerate(zip(day.messages, day.snapshots, strict=True)):
512
+ for a in flow.translate(m, 0):
513
+ report = _apply(lob, a)
514
+ if report is not None:
515
+ flow._record(report)
516
+ depth = lob.depth(n_levels)
517
+ got_b, got_a = ticks(depth["bids"]), ticks(depth["asks"])
518
+ want_b, want_a = ticks(snap.bids), ticks(snap.asks)
519
+ if got_b[:1] == want_b[:1] and got_a[:1] == want_a[:1]:
520
+ top += 1
521
+ if got_b == want_b and got_a == want_a:
522
+ full += 1
523
+ elif first is None:
524
+ first = k
525
+ n = len(day.messages)
526
+ return ReconstructionReport(
527
+ messages=n,
528
+ levels=n_levels,
529
+ top_of_book_match=top / n if n else math.nan,
530
+ depth_match=full / n if n else math.nan,
531
+ first_mismatch=first,
532
+ rejected=flow.stats["rejected"],
533
+ unfilled_execution_qty=flow.stats["unfilled_execution_qty"],
534
+ )
535
+
536
+
537
+ # --------------------------------------------------------------------------- #
538
+ # Synthetic data #
539
+ # --------------------------------------------------------------------------- #
540
+
541
+
542
+ def synthetic_day(
543
+ n_messages: int = 10_000,
544
+ *,
545
+ levels: int = 5,
546
+ seed: int = 0,
547
+ start_price: float = 100.0,
548
+ tick_size: float = 0.01,
549
+ start_time: float = 34_200.0,
550
+ ) -> LobsterDay:
551
+ """A LOBSTER-format day generated by a small FIFO reference model.
552
+
553
+ Useful for trying the replay pipeline without licensed data, and as a test
554
+ oracle: the generator keeps its own order queues (it does not use
555
+ [`LimitOrderBook`][microbook.LimitOrderBook]), so
556
+ [`check_reconstruction()`][microbook.replay.check_reconstruction] on its
557
+ output must match exactly. Orders rest at the open on the first ``levels``
558
+ levels and are not in the message stream, like a real file that starts
559
+ mid-session.
560
+ """
561
+ if n_messages < 1 or levels < 1:
562
+ raise ValueError("n_messages and levels must be positive")
563
+ rng = random.Random(f"{seed}/synthetic_day")
564
+ decimals = max(0, -math.floor(math.log10(tick_size) + 1e-9))
565
+ queues: dict[int, dict[int, list[list[int]]]] = {1: {}, -1: {}} # direction -> tick -> FIFO [id, qty]
566
+ where: dict[int, tuple[int, int]] = {} # order id -> (direction, tick)
567
+ live: list[int] = []
568
+ pos: dict[int, int] = {}
569
+
570
+ def px(tick: int) -> float:
571
+ return round(tick * tick_size, decimals)
572
+
573
+ def add(oid: int, d: int, tick: int, qty: int) -> None:
574
+ queues[d].setdefault(tick, []).append([oid, qty])
575
+ where[oid] = (d, tick)
576
+ pos[oid] = len(live)
577
+ live.append(oid)
578
+
579
+ def drop(oid: int) -> None:
580
+ d, tick = where.pop(oid)
581
+ q = queues[d][tick]
582
+ q[:] = [e for e in q if e[0] != oid]
583
+ if not q:
584
+ del queues[d][tick]
585
+ i = pos.pop(oid)
586
+ last = live.pop()
587
+ if last != oid:
588
+ live[i] = last
589
+ pos[last] = i
590
+
591
+ def best(d: int) -> int | None:
592
+ q = queues[d]
593
+ if not q:
594
+ return None
595
+ return max(q) if d == 1 else min(q)
596
+
597
+ def snapshot() -> BookSnapshot:
598
+ def side(d: int) -> tuple[tuple[float, int], ...]:
599
+ ticks = sorted(queues[d], reverse=d == 1)[:levels]
600
+ return tuple((px(t), sum(e[1] for e in queues[d][t])) for t in ticks)
601
+
602
+ return BookSnapshot(side(1), side(-1))
603
+
604
+ center = round(start_price / tick_size)
605
+ next_id = 1
606
+ for k in range(levels):
607
+ for d, tick in ((1, center - 1 - k), (-1, center + 1 + k)):
608
+ for _ in range(rng.randint(1, 3)):
609
+ add(next_id, d, tick, 100 * rng.randint(1, 5))
610
+ next_id += 1
611
+ initial = snapshot()
612
+
613
+ messages: list[Message] = []
614
+ snapshots: list[BookSnapshot] = []
615
+ t = start_time
616
+ next_id = 10_000_000
617
+
618
+ def emit(kind: MessageType, oid: int, size: int, tick: int, d: int) -> None:
619
+ messages.append(Message(round(t, 9), int(kind), oid, size, px(tick), d))
620
+ snapshots.append(snapshot())
621
+
622
+ while len(messages) < n_messages:
623
+ t += rng.expovariate(20.0) # ~20 events per second
624
+ u = rng.random()
625
+ empty = best(1) is None or best(-1) is None
626
+ if u < 0.47 or empty or len(live) < 4:
627
+ d = 1 if (best(1) is None or (best(-1) is not None and rng.random() < 0.5)) else -1
628
+ opp = best(-d)
629
+ own = best(d)
630
+ ref = opp if opp is not None else (own + d if own is not None else center + d)
631
+ tick = ref - d * rng.choice((1, 1, 1, 2, 2, 3, 4, 6, 9))
632
+ if tick <= 0:
633
+ continue
634
+ qty = 100 * rng.randint(1, 5)
635
+ add(next_id, d, tick, qty)
636
+ emit(MessageType.SUBMIT, next_id, qty, tick, d)
637
+ next_id += 1
638
+ elif u < 0.52:
639
+ oid = live[int(rng.random() * len(live))]
640
+ d, tick = where[oid]
641
+ entry = next(e for e in queues[d][tick] if e[0] == oid)
642
+ if entry[1] < 2:
643
+ continue
644
+ cut = rng.randint(1, entry[1] - 1)
645
+ entry[1] -= cut
646
+ emit(MessageType.CANCEL, oid, cut, tick, d)
647
+ elif u < 0.87:
648
+ oid = live[int(rng.random() * len(live))]
649
+ d, tick = where[oid]
650
+ size = next(e[1] for e in queues[d][tick] if e[0] == oid)
651
+ drop(oid)
652
+ emit(MessageType.DELETE, oid, size, tick, d)
653
+ elif u < 0.98:
654
+ d = 1 if rng.random() < 0.5 else -1 # side of the resting orders being hit
655
+ top = best(d)
656
+ assert top is not None
657
+ remaining = rng.randint(1, sum(e[1] for e in queues[d][top]) + 300)
658
+ while remaining > 0 and (level := best(d)) is not None:
659
+ maker = queues[d][level][0]
660
+ q = min(remaining, maker[1])
661
+ remaining -= q
662
+ if q == maker[1]:
663
+ drop(maker[0])
664
+ else:
665
+ maker[1] -= q
666
+ emit(MessageType.EXECUTE, maker[0], q, level, d)
667
+ else:
668
+ bid, ask = best(1), best(-1)
669
+ assert bid is not None
670
+ assert ask is not None
671
+ direction = 1 if rng.random() < 0.5 else -1
672
+ emit(MessageType.EXECUTE_HIDDEN, 0, 100 * rng.randint(1, 3), (bid + ask) // 2, direction)
673
+ return LobsterDay(messages[:n_messages], initial, snapshots[:n_messages])