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.
@@ -0,0 +1,274 @@
1
+ """Discrete-event market simulator.
2
+
3
+ Events live in a min-heap keyed by ``(time, seq)`` where ``seq`` is a global
4
+ scheduling counter, so simultaneous events are processed FIFO and every run is
5
+ exactly reproducible. Strategies interact only through [`Action`][microbook.sim.Action] objects;
6
+ order messages they send arrive at the book after the strategy's ``latency``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import heapq
12
+ import math
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ from microbook import ExecutionReport, LimitOrderBook, Order, OrderStatus, Side, STPMode
17
+ from microbook.types import Fill
18
+
19
+ from .analytics import TimeSeries, mid_at
20
+ from .events import Event, EventType
21
+ from .execution_metrics import ExecutionMetrics
22
+ from .strategy import Action, Strategy
23
+
24
+
25
+ @dataclass
26
+ class SimResult:
27
+ """Everything recorded during a run. Accumulates across successive ``run`` calls."""
28
+
29
+ fills: list[Fill] = field(default_factory=list)
30
+ """Every fill in the market, in execution order."""
31
+ snapshots: list[dict[str, Any]] = field(default_factory=list)
32
+ """L2 snapshots, one per `SNAPSHOT` event, when `record_snapshots` is on."""
33
+ pnl_t: list[int] = field(default_factory=list)
34
+ """Times of the PnL and inventory samples (one per `SNAPSHOT`)."""
35
+ pnl_series: dict[str, list[float]] = field(default_factory=dict)
36
+ """Total PnL of each strategy, by name, marked to mid at `pnl_t`; NaN while the book is one-sided."""
37
+ inventory_series: dict[str, list[int]] = field(default_factory=dict)
38
+ """Position of each strategy, by name, at `pnl_t`."""
39
+ mid_path: list[tuple[int, float]] = field(default_factory=list)
40
+ """`(time, mid)`, appended whenever the midprice changes; the mid is NaN while the book is one-sided."""
41
+
42
+ def mid_at(self, t: int) -> float | None:
43
+ """Midprice in force at the end of time ``t`` (``None`` if undefined)."""
44
+ return mid_at(self.mid_path, t)
45
+
46
+
47
+ class MarketSimulator:
48
+ """Discrete-event simulator hosting a book and any number of strategies.
49
+
50
+ Parameters
51
+ ----------
52
+ lob:
53
+ The order book. Defaults to a 0.01-tick book with self-trade
54
+ prevention (``CANCEL_RESTING``) so no participant can wash-trade.
55
+ strategies:
56
+ Participants. Names must be unique (they key metrics and series).
57
+ record_snapshots:
58
+ Keep an L2 snapshot dict for every SNAPSHOT event (disable for long runs).
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ lob: LimitOrderBook | None = None,
64
+ strategies: list[Strategy] | None = None,
65
+ *,
66
+ record_snapshots: bool = True,
67
+ ) -> None:
68
+ self.lob = lob if lob is not None else LimitOrderBook(stp=STPMode.CANCEL_RESTING)
69
+ self.strategies: list[Strategy] = list(strategies or [])
70
+ names = [s.name for s in self.strategies]
71
+ if len(set(names)) != len(names):
72
+ raise ValueError(f"strategy names must be unique, got {names}")
73
+ self.record_snapshots = record_snapshots
74
+
75
+ self._pq: list[tuple[int, int, Event]] = []
76
+ self._seq = 0
77
+ self.now = 0
78
+ self.events_processed = 0
79
+ self._started = False
80
+ self._last_mid: float | None = None
81
+
82
+ # live order_id -> (strategy index, side), for fill attribution
83
+ self._order_owner: dict[str, tuple[int, Side]] = {}
84
+
85
+ self.ts = TimeSeries()
86
+ self.exec_metrics: dict[str, ExecutionMetrics] = {s.name: ExecutionMetrics() for s in self.strategies}
87
+ self.result = SimResult(
88
+ pnl_series={s.name: [] for s in self.strategies},
89
+ inventory_series={s.name: [] for s in self.strategies},
90
+ )
91
+
92
+ # ------------------------------------------------------------------ #
93
+ # Scheduling #
94
+ # ------------------------------------------------------------------ #
95
+
96
+ def schedule(self, time: int, etype: EventType, **kwargs: Any) -> None:
97
+ """Schedule an event. ``kwargs`` are [`Event`][microbook.sim.Event] fields (``order``,
98
+ ``order_id``, ``modify``)."""
99
+ if time < self.now:
100
+ raise ValueError(f"cannot schedule at t={time} < now={self.now}")
101
+ self._seq += 1
102
+ heapq.heappush(self._pq, (time, self._seq, Event(time, self._seq, etype, **kwargs)))
103
+
104
+ def schedule_snapshots(self, start: int, end: int, every: int = 1) -> None:
105
+ """SNAPSHOT events at ``start, start+every, ..., <= end`` (these drive ``on_tick``)."""
106
+ if every <= 0:
107
+ raise ValueError("every must be positive")
108
+ for t in range(start, end + 1, every):
109
+ self.schedule(t, EventType.SNAPSHOT)
110
+
111
+ def strategy(self, name: str) -> Strategy:
112
+ """The strategy called ``name``; raises ``KeyError`` if there is none."""
113
+ for s in self.strategies:
114
+ if s.name == name:
115
+ return s
116
+ raise KeyError(name)
117
+
118
+ # ------------------------------------------------------------------ #
119
+ # Main loop #
120
+ # ------------------------------------------------------------------ #
121
+
122
+ def run(self, until: int) -> SimResult:
123
+ """Process every event with ``time <= until``; returns the (cumulative) result."""
124
+ if not self._started:
125
+ self._started = True
126
+ for i, s in enumerate(self.strategies):
127
+ self._dispatch(i, s.on_start(self.now, self.lob))
128
+
129
+ pq = self._pq
130
+ while pq and pq[0][0] <= until:
131
+ t, _, ev = heapq.heappop(pq)
132
+ self.now = t
133
+ self.events_processed += 1
134
+ et = ev.etype
135
+ if et is EventType.SUBMIT:
136
+ self._on_submit(ev)
137
+ elif et is EventType.CANCEL:
138
+ if ev.order_id is None:
139
+ raise ValueError("CANCEL event requires order_id")
140
+ self.lob.cancel(ev.order_id)
141
+ self._order_owner.pop(ev.order_id, None)
142
+ self._record_mid()
143
+ elif et is EventType.MODIFY:
144
+ self._on_modify(ev)
145
+ elif et is EventType.SNAPSHOT:
146
+ self._on_snapshot()
147
+ elif et is EventType.TIMER:
148
+ if ev.owner is None:
149
+ raise ValueError("TIMER event requires an owner")
150
+ self._dispatch(ev.owner, self.strategies[ev.owner].on_timer(t, self.lob))
151
+ else: # pragma: no cover
152
+ raise ValueError(f"unknown event type {et}")
153
+ self.now = max(self.now, until)
154
+ return self.result
155
+
156
+ # ------------------------------------------------------------------ #
157
+ # Event handlers #
158
+ # ------------------------------------------------------------------ #
159
+
160
+ def _on_submit(self, ev: Event) -> None:
161
+ order = ev.order
162
+ if order is None:
163
+ raise ValueError("SUBMIT event requires an order")
164
+ idx = ev.owner if ev.owner is not None else self._lookup_owner(order.order_id)
165
+ if idx is not None and order.owner is None:
166
+ order.owner = self.strategies[idx].name
167
+ order.ts = self.now
168
+
169
+ mid_before = self.lob.midprice()
170
+ report = self.lob.submit(order)
171
+ if idx is not None and report.accepted:
172
+ self._order_owner[order.order_id] = (idx, order.side)
173
+ self._process_report(report, mid_before, idx)
174
+
175
+ def _on_modify(self, ev: Event) -> None:
176
+ if ev.order_id is None or ev.modify is None:
177
+ raise ValueError("MODIFY event requires order_id and modify")
178
+ owner = self._order_owner.get(ev.order_id)
179
+ mid_before = self.lob.midprice()
180
+ if "reduce_by" in ev.modify:
181
+ report = self.lob.reduce(ev.order_id, ev.modify["reduce_by"])
182
+ else:
183
+ report = self.lob.modify(ev.order_id, ts=self.now, **ev.modify)
184
+ idx = ev.owner if ev.owner is not None else (owner[0] if owner else None)
185
+ self._process_report(report, mid_before, idx)
186
+
187
+ def _on_snapshot(self) -> None:
188
+ now, lob, res = self.now, self.lob, self.result
189
+ self.ts.record(now, lob)
190
+ if self.record_snapshots:
191
+ res.snapshots.append({"t": now, "top": lob.top_of_book(), "depth": lob.depth(levels=5)})
192
+
193
+ for i, strat in enumerate(self.strategies):
194
+ self._dispatch(i, strat.on_tick(now, lob))
195
+
196
+ mid = lob.midprice()
197
+ res.pnl_t.append(now)
198
+ for s in self.strategies:
199
+ res.pnl_series[s.name].append(s.portfolio.total_pnl(mid) if mid is not None else math.nan)
200
+ res.inventory_series[s.name].append(s.portfolio.position)
201
+
202
+ def _process_report(self, report: ExecutionReport, mid_before: float | None, submitter: int | None) -> None:
203
+ now, lob = self.now, self.lob
204
+ owners = self._order_owner
205
+ fills = report.fills
206
+ if fills:
207
+ self.result.fills.extend(fills)
208
+ for m in self.exec_metrics.values():
209
+ m.record_market_volume(fills)
210
+ for f in fills:
211
+ for oid, is_maker in ((f.maker_order_id, True), (f.taker_order_id, False)):
212
+ entry = owners.get(oid)
213
+ if entry is None:
214
+ continue
215
+ idx, side = entry
216
+ strat = self.strategies[idx]
217
+ strat.portfolio.on_fill(f, oid, side, is_maker=is_maker)
218
+ self.exec_metrics[strat.name].on_fill(f, side, is_maker, mid=mid_before, time=now)
219
+ self._dispatch(idx, strat.on_fill(now, f, side, is_maker, lob))
220
+ if is_maker and oid not in lob:
221
+ del owners[oid]
222
+
223
+ for oid in report.stp_canceled:
224
+ owners.pop(oid, None)
225
+
226
+ if submitter is not None:
227
+ if report.status is OrderStatus.REJECTED:
228
+ self.exec_metrics[self.strategies[submitter].name].orders_rejected += 1
229
+ self._dispatch(submitter, self.strategies[submitter].on_report(now, report))
230
+ if report.status is not OrderStatus.REJECTED and report.order_id not in lob:
231
+ owners.pop(report.order_id, None)
232
+ self._record_mid()
233
+
234
+ # ------------------------------------------------------------------ #
235
+ # Helpers #
236
+ # ------------------------------------------------------------------ #
237
+
238
+ def _dispatch(self, idx: int, actions: list[Action]) -> None:
239
+ if not actions:
240
+ return
241
+ strat = self.strategies[idx]
242
+ now = self.now
243
+ arrival_mid: float | None = None
244
+ have_mid = False
245
+ for a in actions:
246
+ et = a.etype
247
+ if et is EventType.TIMER:
248
+ if a.time < now or (a.time == now and not strat.same_time_timers):
249
+ raise ValueError(f"{strat.name}: timers must be scheduled in the future (t={a.time}, now={now})")
250
+ t = a.time
251
+ else:
252
+ t = max(a.time, now) + strat.latency
253
+ if et is EventType.SUBMIT:
254
+ order: Order = a.kwargs["order"]
255
+ if order.owner is None:
256
+ order.owner = strat.name
257
+ if not have_mid:
258
+ arrival_mid, have_mid = self.lob.midprice(), True
259
+ self.exec_metrics[strat.name].record_order(order.order_id, order.side, order.qty, arrival_mid)
260
+ self._seq += 1
261
+ heapq.heappush(self._pq, (t, self._seq, Event(t, self._seq, et, owner=idx, **a.kwargs)))
262
+
263
+ def _lookup_owner(self, order_id: str) -> int | None:
264
+ """Attribution for orders scheduled directly via ``schedule``."""
265
+ for i, s in enumerate(self.strategies):
266
+ if order_id in s.my_order_ids:
267
+ return i
268
+ return None
269
+
270
+ def _record_mid(self) -> None:
271
+ m = self.lob.midprice()
272
+ if m != self._last_mid:
273
+ self._last_mid = m
274
+ self.result.mid_path.append((self.now, m if m is not None else math.nan))
@@ -0,0 +1,190 @@
1
+ """Market-making strategies beyond the symmetric baseline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections import deque
7
+ from dataclasses import dataclass
8
+ from itertools import pairwise
9
+
10
+ from microbook import LimitOrderBook
11
+ from microbook.sim.metrics import imbalance
12
+ from microbook.sim.strategy import TwoSidedQuoter
13
+
14
+ Quotes = tuple[float | None, float | None, int, int]
15
+
16
+
17
+ @dataclass
18
+ class AdaptiveConfig:
19
+ """Parameters of [`AdaptiveMarketMaker`][microbook.sim.AdaptiveMarketMaker]."""
20
+
21
+ tick_size: float | None = None
22
+ """Quoting unit, in price; `None` uses the book's tick. The other `*_ticks` and `*_k` settings are in this unit."""
23
+ base_half_spread_ticks: float = 1.0
24
+ """Half-spread before volatility widening."""
25
+ size: int = 5
26
+ """Shares quoted on each side."""
27
+ tick_interval: int = 10
28
+ """Minimum time between requotes."""
29
+ latency: int = 0
30
+ """Order-entry latency, in time units."""
31
+
32
+ inv_target: int = 0
33
+ """Inventory the quotes skew toward."""
34
+ inv_limit: int = 25
35
+ """Stop quoting the side that would take |inventory| beyond this many shares."""
36
+ inv_k: float = 0.08
37
+ """Quote shift per share of inventory away from `inv_target`."""
38
+ max_skew_ticks: float = 6.0
39
+ """Cap on the combined inventory and imbalance shift."""
40
+
41
+ vol_window: int = 30
42
+ """Refreshes in the volatility estimate (mean absolute mid change per refresh)."""
43
+ vol_k: float = 3.0
44
+ """Half-spread widening per unit of the volatility estimate."""
45
+
46
+ imb_k: float = 2.0
47
+ """Shift toward the heavier side of the top-3 book at full imbalance."""
48
+
49
+
50
+ class AdaptiveMarketMaker(TwoSidedQuoter):
51
+ """Heuristic market maker with three controls:
52
+
53
+ * **volatility-aware spread** — the half-spread widens with the mean
54
+ absolute mid change over the last ``vol_window`` refreshes;
55
+ * **inventory skew** — both quotes shift *against* the position
56
+ (long -> lower, to sell; short -> higher, to buy), plus a hard limit;
57
+ * **imbalance lean** — both quotes shift *toward* the heavier side of the
58
+ top-3 book (bid-heavy -> higher), anticipating the next price move.
59
+
60
+ Skews shift the quote *centre*; they never change the spread width, so the
61
+ bid stays strictly below the ask.
62
+ """
63
+
64
+ def __init__(self, cfg: AdaptiveConfig | None = None, name: str = "amm") -> None:
65
+ cfg = cfg or AdaptiveConfig()
66
+ super().__init__(name, tick_interval=cfg.tick_interval, latency=cfg.latency)
67
+ self.cfg = cfg
68
+ self._mid_hist: deque[float] = deque(maxlen=max(2, cfg.vol_window))
69
+
70
+ def _vol_proxy(self) -> float:
71
+ h = self._mid_hist
72
+ if len(h) < 2:
73
+ return 0.0
74
+ return sum(abs(b - a) for a, b in pairwise(h)) / (len(h) - 1)
75
+
76
+ def compute_quotes(self, now: int, lob: LimitOrderBook) -> Quotes | None:
77
+ """Volatility-widened quotes around the mid, shifted against inventory and toward the heavier book side."""
78
+ mid = lob.midprice()
79
+ if mid is None:
80
+ return None
81
+ cfg = self.cfg
82
+ self._mid_hist.append(mid)
83
+ q = cfg.tick_size or lob.tick_size
84
+
85
+ half = (cfg.base_half_spread_ticks + cfg.vol_k * self._vol_proxy() / q) * q
86
+
87
+ inv = self.portfolio.position
88
+ im = imbalance(lob, levels=3) or 0.0
89
+ shift_down = cfg.inv_k * (inv - cfg.inv_target) - cfg.imb_k * im
90
+ shift_down = max(-cfg.max_skew_ticks, min(cfg.max_skew_ticks, shift_down))
91
+ center = mid - shift_down * q
92
+
93
+ bid = center - half if inv < cfg.inv_limit else None
94
+ ask = center + half if inv > -cfg.inv_limit else None
95
+ return bid, ask, cfg.size, cfg.size
96
+
97
+
98
+ @dataclass
99
+ class AvellanedaStoikovConfig:
100
+ """Parameters of [`AvellanedaStoikovMarketMaker`][microbook.sim.AvellanedaStoikovMarketMaker]."""
101
+
102
+ gamma: float = 0.1
103
+ """Risk aversion γ."""
104
+ k: float = 100.0
105
+ """Fill-intensity decay: λ(δ) = A·exp(−kδ), with δ in price units."""
106
+ horizon: int = 10_000
107
+ """Terminal time T of the finite-horizon form."""
108
+ rolling_tau: int | None = None
109
+ """If set, a constant time to horizon τ used instead of T − t: the stationary "rolling horizon" variant, whose
110
+ skew does not fade."""
111
+ sigma: float | None = None
112
+ """Mid volatility per √(time unit); `None` estimates it online from sampled mids."""
113
+ vol_window: int = 50
114
+ """Mid samples in the online volatility estimate."""
115
+ size: int = 5
116
+ """Shares quoted on each side."""
117
+ tick_interval: int = 10
118
+ """Minimum time between requotes."""
119
+ inv_limit: int = 50
120
+ """Stop quoting the side that would take |inventory| beyond this many shares."""
121
+ min_half_spread_ticks: float = 0.5
122
+ """Lower bound on the half-spread, in ticks."""
123
+ latency: int = 0
124
+ """Order-entry latency, in time units."""
125
+
126
+
127
+ class AvellanedaStoikovMarketMaker(TwoSidedQuoter):
128
+ """Avellaneda & Stoikov (2008), *High-frequency trading in a limit order book*.
129
+
130
+ With inventory ``q``, mid ``s``, volatility ``sigma`` and time to horizon
131
+ ``tau = T - t``, the optimal quotes are centred on the reservation price::
132
+
133
+ r = s - q * gamma * sigma^2 * tau
134
+ delta = gamma * sigma^2 * tau + (2 / gamma) * ln(1 + gamma / k) # total spread
135
+
136
+ so inventory risk is managed by moving the centre (not by widening). In
137
+ the finite-horizon form the skew fades as ``t -> T``; with
138
+ ``rolling_tau`` set, ``tau`` is held constant instead.
139
+ """
140
+
141
+ def __init__(self, cfg: AvellanedaStoikovConfig | None = None, name: str = "as") -> None:
142
+ cfg = cfg or AvellanedaStoikovConfig()
143
+ if cfg.gamma <= 0 or cfg.k <= 0:
144
+ raise ValueError("gamma and k must be positive")
145
+ super().__init__(name, tick_interval=cfg.tick_interval, latency=cfg.latency)
146
+ self.cfg = cfg
147
+ self._samples: deque[tuple[int, float]] = deque(maxlen=max(2, cfg.vol_window))
148
+
149
+ def sigma(self) -> float | None:
150
+ """Configured sigma, or realized volatility per sqrt(time unit) of sampled mids."""
151
+ if self.cfg.sigma is not None:
152
+ return self.cfg.sigma
153
+ s = self._samples
154
+ if len(s) < 3:
155
+ return None
156
+ pts = list(s)
157
+ sq = sum((b[1] - a[1]) ** 2 for a, b in pairwise(pts))
158
+ dt = pts[-1][0] - pts[0][0]
159
+ return math.sqrt(sq / dt) if dt > 0 else None
160
+
161
+ def tau(self, now: int) -> int:
162
+ """Time left to the horizon, ``T - t``, or the constant ``rolling_tau`` if set."""
163
+ if self.cfg.rolling_tau is not None:
164
+ return self.cfg.rolling_tau
165
+ return max(self.cfg.horizon - now, 0)
166
+
167
+ def reservation_price(self, mid: float, inventory: int, now: int, sigma: float) -> float:
168
+ """Reservation price ``r = mid - q * gamma * sigma^2 * tau``."""
169
+ return mid - inventory * self.cfg.gamma * sigma**2 * self.tau(now)
170
+
171
+ def optimal_spread(self, now: int, sigma: float) -> float:
172
+ """Optimal total spread ``gamma * sigma^2 * tau + (2 / gamma) * ln(1 + gamma / k)``."""
173
+ g, k = self.cfg.gamma, self.cfg.k
174
+ return g * sigma**2 * self.tau(now) + (2.0 / g) * math.log1p(g / k)
175
+
176
+ def compute_quotes(self, now: int, lob: LimitOrderBook) -> Quotes | None:
177
+ """Quotes around the reservation price, at least ``min_half_spread_ticks`` from it on each side."""
178
+ mid = lob.midprice()
179
+ if mid is None:
180
+ return None
181
+ cfg = self.cfg
182
+ self._samples.append((now, mid))
183
+ sigma = self.sigma() or 0.0
184
+ inv = self.portfolio.position
185
+
186
+ r = self.reservation_price(mid, inv, now, sigma)
187
+ half = max(self.optimal_spread(now, sigma) / 2.0, cfg.min_half_spread_ticks * lob.tick_size)
188
+ bid = r - half if inv < cfg.inv_limit else None
189
+ ask = r + half if inv > -cfg.inv_limit else None
190
+ return bid, ask, cfg.size, cfg.size