mdp-outbox 0.1.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.
- mdp/__init__.py +3 -0
- mdp/aggregation.py +272 -0
- mdp/aggregator.py +310 -0
- mdp/api.py +186 -0
- mdp/backfill.py +252 -0
- mdp/cli.py +200 -0
- mdp/config.py +55 -0
- mdp/hub.py +156 -0
- mdp/ingest.py +96 -0
- mdp/metrics.py +63 -0
- mdp/normalizer.py +93 -0
- mdp/py.typed +0 -0
- mdp/schema.py +89 -0
- mdp/sources/__init__.py +20 -0
- mdp/sources/binance.py +88 -0
- mdp/sources/engine.py +183 -0
- mdp/sources/kraken.py +102 -0
- mdp/sources/synthetic.py +121 -0
- mdp/sources/ws.py +102 -0
- mdp/storage/__init__.py +57 -0
- mdp/storage/memory.py +114 -0
- mdp/storage/schema.sql +76 -0
- mdp/storage/timescale.py +234 -0
- mdp/streams.py +57 -0
- mdp/timeframes.py +57 -0
- mdp_outbox-0.1.0.dist-info/METADATA +449 -0
- mdp_outbox-0.1.0.dist-info/RECORD +30 -0
- mdp_outbox-0.1.0.dist-info/WHEEL +4 -0
- mdp_outbox-0.1.0.dist-info/entry_points.txt +2 -0
- mdp_outbox-0.1.0.dist-info/licenses/LICENSE +21 -0
mdp/__init__.py
ADDED
mdp/aggregation.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""The aggregation service: Redis stream in, candles out.
|
|
2
|
+
|
|
3
|
+
Per batch read from the consumer group:
|
|
4
|
+
|
|
5
|
+
1. decode, and let the aggregator split late trades from on-time ones;
|
|
6
|
+
2. in **one database transaction**: log the on-time trades (the log reports
|
|
7
|
+
which are new), fold only the new ones into the candles, write the changed
|
|
8
|
+
candles and the aggregator's checkpoint;
|
|
9
|
+
3. dead-letter the refused messages, publish the candles, acknowledge the batch.
|
|
10
|
+
|
|
11
|
+
A crash before step 2 commits rolls everything back and leaves the batch
|
|
12
|
+
pending, so it is read again. A crash after the commit but before the
|
|
13
|
+
acknowledgement redelivers a batch whose trades are already logged: the insert
|
|
14
|
+
reports none of them as new, and nothing is counted twice. Restart state comes
|
|
15
|
+
from the checkpoint committed with the candles, so it always matches them.
|
|
16
|
+
|
|
17
|
+
One consumer owns a symbol at a time — the consumer group is used for durable
|
|
18
|
+
offsets and redelivery, not to spread one symbol's trades across workers,
|
|
19
|
+
which would split its candles. See ADR 0003.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import logging
|
|
25
|
+
import time
|
|
26
|
+
from collections.abc import Callable, Sequence
|
|
27
|
+
from typing import Any, cast
|
|
28
|
+
|
|
29
|
+
import redis.asyncio as aioredis
|
|
30
|
+
from redis.exceptions import ResponseError
|
|
31
|
+
|
|
32
|
+
from mdp.aggregator import Aggregator
|
|
33
|
+
from mdp.metrics import (
|
|
34
|
+
BATCH_SECONDS,
|
|
35
|
+
CANDLES_WRITTEN,
|
|
36
|
+
DEAD_LETTERS,
|
|
37
|
+
DUPLICATES,
|
|
38
|
+
STREAM_LAG,
|
|
39
|
+
STREAM_PENDING,
|
|
40
|
+
TRADE_LAG_SECONDS,
|
|
41
|
+
TRADES_AGGREGATED,
|
|
42
|
+
WATERMARK_DELAY,
|
|
43
|
+
)
|
|
44
|
+
from mdp.normalizer import Rejected, RejectReason
|
|
45
|
+
from mdp.schema import Candle, Trade
|
|
46
|
+
from mdp.storage import Store, StoreTransaction
|
|
47
|
+
from mdp.streams import DLQ_STREAM, candle_channel, dead_letter, decode_trade, trades_stream
|
|
48
|
+
from mdp.timeframes import from_ms
|
|
49
|
+
|
|
50
|
+
log = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
type Entry = tuple[bytes, bytes, dict[bytes, bytes]] # (stream, message id, fields)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _text(value: bytes | str) -> str:
|
|
56
|
+
return value.decode() if isinstance(value, bytes) else value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _wall_clock_ms() -> int:
|
|
60
|
+
return time.time_ns() // 1_000_000
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AggregationService:
|
|
64
|
+
def __init__(
|
|
65
|
+
self,
|
|
66
|
+
redis: aioredis.Redis,
|
|
67
|
+
store: Store,
|
|
68
|
+
symbols: Sequence[str],
|
|
69
|
+
*,
|
|
70
|
+
group: str = "aggregator",
|
|
71
|
+
consumer: str = "aggregator-1",
|
|
72
|
+
allowed_lateness_ms: int = 5_000,
|
|
73
|
+
idle_grace_ms: int | None = 2_000,
|
|
74
|
+
batch_size: int = 1_000,
|
|
75
|
+
dlq_maxlen: int = 100_000,
|
|
76
|
+
clock_ms: Callable[[], int] = _wall_clock_ms,
|
|
77
|
+
) -> None:
|
|
78
|
+
self._redis = redis
|
|
79
|
+
self._store = store
|
|
80
|
+
self._symbols = list(symbols)
|
|
81
|
+
self._streams = [trades_stream(s) for s in self._symbols]
|
|
82
|
+
self._group = group
|
|
83
|
+
self._consumer = consumer
|
|
84
|
+
self._idle_grace_ms = idle_grace_ms
|
|
85
|
+
self._batch_size = batch_size
|
|
86
|
+
self._dlq_maxlen = dlq_maxlen
|
|
87
|
+
self._clock_ms = clock_ms
|
|
88
|
+
self._aggregator = Aggregator(allowed_lateness_ms=allowed_lateness_ms)
|
|
89
|
+
self._pending_drained = False
|
|
90
|
+
|
|
91
|
+
async def start(self) -> None:
|
|
92
|
+
"""Create the groups, restore the checkpoint, and take over orphaned messages."""
|
|
93
|
+
for stream in self._streams:
|
|
94
|
+
try:
|
|
95
|
+
# From "0", not "$": a new group first works through whatever
|
|
96
|
+
# the ingester wrote before it existed. The trade log makes
|
|
97
|
+
# re-reading already-counted trades harmless.
|
|
98
|
+
await self._redis.xgroup_create(stream, self._group, id="0", mkstream=True)
|
|
99
|
+
except ResponseError as exc:
|
|
100
|
+
if "BUSYGROUP" not in str(exc):
|
|
101
|
+
raise
|
|
102
|
+
await self._claim_orphans(stream)
|
|
103
|
+
for symbol, state in (await self._store.load_states(self._symbols)).items():
|
|
104
|
+
self._aggregator.restore_state(symbol, state)
|
|
105
|
+
log.info("resumed %s at watermark %s", symbol, from_ms(state["watermark"]))
|
|
106
|
+
|
|
107
|
+
async def _claim_orphans(self, stream: str) -> None:
|
|
108
|
+
# Messages delivered to a consumer that died (say, one renamed on
|
|
109
|
+
# redeploy) sit in its pending list forever unless someone claims them.
|
|
110
|
+
# This service owns the symbol outright, so it claims them all.
|
|
111
|
+
# (Not JUSTID: redis-py drops the cursor from that form of the reply.)
|
|
112
|
+
cursor: Any = "0-0"
|
|
113
|
+
while True:
|
|
114
|
+
reply = await self._redis.xautoclaim(
|
|
115
|
+
stream, self._group, self._consumer, min_idle_time=0, start_id=cursor, count=1000
|
|
116
|
+
)
|
|
117
|
+
cursor = reply[0]
|
|
118
|
+
if cursor in (b"0-0", "0-0"):
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
async def run(self, block_ms: int = 1_000, probe_every_s: float = 5.0) -> None:
|
|
122
|
+
await self.start()
|
|
123
|
+
next_probe = 0.0
|
|
124
|
+
while True:
|
|
125
|
+
await self.poll(block_ms)
|
|
126
|
+
if time.monotonic() >= next_probe:
|
|
127
|
+
await self.probe_lag()
|
|
128
|
+
next_probe = time.monotonic() + probe_every_s
|
|
129
|
+
|
|
130
|
+
async def probe_lag(self) -> None:
|
|
131
|
+
"""Export how far the group trails each stream, and the watermarks."""
|
|
132
|
+
now = self._clock_ms()
|
|
133
|
+
for symbol, stream in zip(self._symbols, self._streams, strict=True):
|
|
134
|
+
for info in await self._redis.xinfo_groups(stream):
|
|
135
|
+
if _text(info["name"]) == self._group:
|
|
136
|
+
# "lag" is Redis 7+, and null while it cannot be computed cheaply.
|
|
137
|
+
STREAM_LAG.labels(symbol).set(info.get("lag") or 0)
|
|
138
|
+
STREAM_PENDING.labels(symbol).set(info["pending"])
|
|
139
|
+
watermark = self._aggregator.watermark(symbol)
|
|
140
|
+
if watermark is not None:
|
|
141
|
+
WATERMARK_DELAY.labels(symbol).set((now - watermark) / 1000)
|
|
142
|
+
|
|
143
|
+
async def poll(self, block_ms: int | None = None) -> int:
|
|
144
|
+
"""Read and process one batch; return how many messages it held.
|
|
145
|
+
|
|
146
|
+
Pending messages (delivered before a crash, never acknowledged) are
|
|
147
|
+
worked through first, then new ones. An empty read still runs a batch:
|
|
148
|
+
it is the wall-clock tick that closes candles in a quiet market.
|
|
149
|
+
"""
|
|
150
|
+
if not self._pending_drained:
|
|
151
|
+
entries = await self._read("0", block_ms=None)
|
|
152
|
+
if not entries:
|
|
153
|
+
self._pending_drained = True
|
|
154
|
+
if self._pending_drained:
|
|
155
|
+
entries = await self._read(">", block_ms)
|
|
156
|
+
await self.process(entries)
|
|
157
|
+
return len(entries)
|
|
158
|
+
|
|
159
|
+
async def _read(self, cursor: str, block_ms: int | None) -> list[Entry]:
|
|
160
|
+
reply = cast(
|
|
161
|
+
"list[tuple[bytes, list[tuple[bytes, dict[bytes, bytes] | None]]]] | None",
|
|
162
|
+
await self._redis.xreadgroup(
|
|
163
|
+
self._group,
|
|
164
|
+
self._consumer,
|
|
165
|
+
dict.fromkeys(self._streams, cursor),
|
|
166
|
+
count=self._batch_size,
|
|
167
|
+
block=block_ms,
|
|
168
|
+
),
|
|
169
|
+
)
|
|
170
|
+
return [
|
|
171
|
+
# A pending entry whose message has since been trimmed comes back
|
|
172
|
+
# with no fields. It is kept so that it still gets acknowledged.
|
|
173
|
+
(stream, message_id, fields or {})
|
|
174
|
+
for stream, messages in reply or []
|
|
175
|
+
for message_id, fields in messages
|
|
176
|
+
]
|
|
177
|
+
|
|
178
|
+
async def process(self, entries: Sequence[Entry]) -> list[Candle]:
|
|
179
|
+
with BATCH_SECONDS.time():
|
|
180
|
+
return await self._process(entries)
|
|
181
|
+
|
|
182
|
+
async def _process(self, entries: Sequence[Entry]) -> list[Candle]:
|
|
183
|
+
trades: list[Trade] = []
|
|
184
|
+
rejected: list[Rejected] = []
|
|
185
|
+
for _, _, fields in entries:
|
|
186
|
+
if not fields:
|
|
187
|
+
continue
|
|
188
|
+
decoded = decode_trade(fields)
|
|
189
|
+
if isinstance(decoded, Trade):
|
|
190
|
+
trades.append(decoded)
|
|
191
|
+
else:
|
|
192
|
+
rejected.append(decoded)
|
|
193
|
+
|
|
194
|
+
on_time, late = self._aggregator.observe(trades)
|
|
195
|
+
touched = {t.symbol for t in trades}
|
|
196
|
+
fresh: list[Trade] = []
|
|
197
|
+
if on_time:
|
|
198
|
+
async with self._store.transaction() as tx:
|
|
199
|
+
fresh = await tx.insert_trades(on_time)
|
|
200
|
+
self._aggregator.apply(fresh)
|
|
201
|
+
candles = self._close()
|
|
202
|
+
await self._checkpoint(tx, candles, touched)
|
|
203
|
+
else:
|
|
204
|
+
# Nothing to log: only open a transaction if the clock closed something.
|
|
205
|
+
candles = self._close()
|
|
206
|
+
if candles or touched:
|
|
207
|
+
async with self._store.transaction() as tx:
|
|
208
|
+
await self._checkpoint(tx, candles, touched)
|
|
209
|
+
|
|
210
|
+
rejected.extend(self._late(trade) for trade in late)
|
|
211
|
+
await self._finish(entries, candles, rejected)
|
|
212
|
+
self._record(on_time, fresh, candles, rejected)
|
|
213
|
+
return candles
|
|
214
|
+
|
|
215
|
+
def _record(
|
|
216
|
+
self,
|
|
217
|
+
on_time: Sequence[Trade],
|
|
218
|
+
fresh: Sequence[Trade],
|
|
219
|
+
candles: Sequence[Candle],
|
|
220
|
+
rejected: Sequence[Rejected],
|
|
221
|
+
) -> None:
|
|
222
|
+
DUPLICATES.labels("aggregate").inc(len(on_time) - len(fresh))
|
|
223
|
+
for item in rejected:
|
|
224
|
+
DEAD_LETTERS.labels("aggregate", item.reason.value).inc()
|
|
225
|
+
for candle in candles:
|
|
226
|
+
CANDLES_WRITTEN.labels(candle.tf.value, "closed" if candle.closed else "open").inc()
|
|
227
|
+
published = self._clock_ms()
|
|
228
|
+
for trade in fresh:
|
|
229
|
+
TRADES_AGGREGATED.labels(trade.symbol).inc()
|
|
230
|
+
TRADE_LAG_SECONDS.observe((published - trade.ts_ms) / 1000)
|
|
231
|
+
|
|
232
|
+
def _close(self) -> list[Candle]:
|
|
233
|
+
if self._idle_grace_ms is not None:
|
|
234
|
+
self._aggregator.advance(self._clock_ms(), self._idle_grace_ms)
|
|
235
|
+
return self._aggregator.flush()
|
|
236
|
+
|
|
237
|
+
async def _checkpoint(
|
|
238
|
+
self, tx: StoreTransaction, candles: Sequence[Candle], touched: set[str]
|
|
239
|
+
) -> None:
|
|
240
|
+
await tx.upsert_candles(candles)
|
|
241
|
+
for symbol in touched | {c.symbol for c in candles}:
|
|
242
|
+
state = self._aggregator.export_state(symbol)
|
|
243
|
+
if state is not None:
|
|
244
|
+
await tx.save_state(symbol, state)
|
|
245
|
+
|
|
246
|
+
def _late(self, trade: Trade) -> Rejected:
|
|
247
|
+
watermark = self._aggregator.watermark(trade.symbol)
|
|
248
|
+
detail = f"watermark {from_ms(watermark).isoformat()}" if watermark is not None else ""
|
|
249
|
+
return Rejected(trade.source, RejectReason.LATE, trade.model_dump_json(), detail)
|
|
250
|
+
|
|
251
|
+
async def _finish(
|
|
252
|
+
self, entries: Sequence[Entry], candles: Sequence[Candle], rejected: Sequence[Rejected]
|
|
253
|
+
) -> None:
|
|
254
|
+
"""Dead-letter, publish and acknowledge in one round trip, after the commit."""
|
|
255
|
+
if not entries and not candles:
|
|
256
|
+
return
|
|
257
|
+
pipe = self._redis.pipeline(transaction=False)
|
|
258
|
+
for item in rejected:
|
|
259
|
+
pipe.xadd(
|
|
260
|
+
DLQ_STREAM,
|
|
261
|
+
dead_letter(item, "aggregate"), # type: ignore[arg-type]
|
|
262
|
+
maxlen=self._dlq_maxlen,
|
|
263
|
+
approximate=True,
|
|
264
|
+
)
|
|
265
|
+
for candle in candles:
|
|
266
|
+
pipe.publish(candle_channel(candle.symbol, candle.tf), candle.model_dump_json())
|
|
267
|
+
by_stream: dict[bytes, list[bytes]] = {}
|
|
268
|
+
for stream, message_id, _ in entries:
|
|
269
|
+
by_stream.setdefault(stream, []).append(message_id)
|
|
270
|
+
for stream, ids in by_stream.items():
|
|
271
|
+
pipe.xack(stream, self._group, *ids)
|
|
272
|
+
await pipe.execute()
|
mdp/aggregator.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""The stateful candle aggregator: trades in, OHLCV snapshots out.
|
|
2
|
+
|
|
3
|
+
Buckets are assigned by **event time** (the exchange's timestamp), never by
|
|
4
|
+
when a trade happened to reach us, so a replay of the same trades produces the
|
|
5
|
+
same candles however they were delayed or reordered on the way.
|
|
6
|
+
|
|
7
|
+
A bucket stays open until the symbol's **watermark** passes its end. The
|
|
8
|
+
watermark trails the newest event time seen by ``allowed_lateness``: it is the
|
|
9
|
+
pipeline's claim that nothing older is still in flight. Until then trades may
|
|
10
|
+
arrive in any order and land in the right bucket; ``open`` and ``close`` are
|
|
11
|
+
decided by event time (see ``_order_key``), not arrival order.
|
|
12
|
+
|
|
13
|
+
Every timeframe is computed directly from the trades rather than rolled up from
|
|
14
|
+
1m candles, so a 1d candle is live-updated on the same trade that moves the 1m
|
|
15
|
+
one. A trade is judged against its 1m bucket, the first to close; once it is
|
|
16
|
+
accepted it is folded into every timeframe, so no two timeframes ever disagree
|
|
17
|
+
about which trades they contain.
|
|
18
|
+
|
|
19
|
+
A quiet market produces no trades to push the watermark, so ``advance`` also
|
|
20
|
+
moves it on the wall clock: once ``allowed_lateness + idle_grace`` has passed
|
|
21
|
+
with nothing newer, the last candle closes on time instead of waiting for the
|
|
22
|
+
next trade. The trade-off — a source whose clock runs behind ours by more than
|
|
23
|
+
the grace has its trades judged late — is discussed in ADR 0001.
|
|
24
|
+
|
|
25
|
+
The aggregator is synchronous and does no I/O. The service around it decides
|
|
26
|
+
when to commit, publish and acknowledge; this class only decides what the
|
|
27
|
+
candles are.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
from collections.abc import Iterable, Sequence
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from decimal import Decimal
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from mdp.schema import Candle, Trade
|
|
38
|
+
from mdp.timeframes import BASE_TIMEFRAME, TIMEFRAMES, Timeframe
|
|
39
|
+
|
|
40
|
+
type OrderKey = tuple[int, int, str, str]
|
|
41
|
+
# (bucket width in ms, bucket start). The width stands in for the timeframe
|
|
42
|
+
# because an int hashes in C, and an Enum member hashes in Python.
|
|
43
|
+
type BucketKey = tuple[int, int]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
_BASE_MS = BASE_TIMEFRAME.ms
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _order_key(trade: Trade) -> OrderKey:
|
|
50
|
+
"""Event-time order, with a deterministic tie-break for equal timestamps.
|
|
51
|
+
|
|
52
|
+
Exchanges stamp in milliseconds, so ties are common. Ids break them: most
|
|
53
|
+
sources issue increasing numeric ids, and comparing ``(len, id)`` orders
|
|
54
|
+
"9" before "10" the way the numbers do without assuming ids are numeric.
|
|
55
|
+
"""
|
|
56
|
+
return (trade.ts_ms, len(trade.trade_id), trade.trade_id, trade.source)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(slots=True)
|
|
60
|
+
class CandleBuilder:
|
|
61
|
+
symbol: str
|
|
62
|
+
tf: Timeframe
|
|
63
|
+
start: int
|
|
64
|
+
open: Decimal
|
|
65
|
+
high: Decimal
|
|
66
|
+
low: Decimal
|
|
67
|
+
close: Decimal
|
|
68
|
+
volume: Decimal
|
|
69
|
+
quote_volume: Decimal
|
|
70
|
+
trades: int
|
|
71
|
+
first: OrderKey
|
|
72
|
+
last: OrderKey
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_trade(
|
|
76
|
+
cls, trade: Trade, tf: Timeframe, key: OrderKey, notional: Decimal
|
|
77
|
+
) -> CandleBuilder:
|
|
78
|
+
return cls(
|
|
79
|
+
symbol=trade.symbol,
|
|
80
|
+
tf=tf,
|
|
81
|
+
start=tf.floor(trade.ts_ms),
|
|
82
|
+
open=trade.price,
|
|
83
|
+
high=trade.price,
|
|
84
|
+
low=trade.price,
|
|
85
|
+
close=trade.price,
|
|
86
|
+
volume=trade.qty,
|
|
87
|
+
quote_volume=notional,
|
|
88
|
+
trades=1,
|
|
89
|
+
first=key,
|
|
90
|
+
last=key,
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def end(self) -> int:
|
|
95
|
+
return self.start + self.tf.ms
|
|
96
|
+
|
|
97
|
+
def add(self, trade: Trade, key: OrderKey, notional: Decimal) -> None:
|
|
98
|
+
price = trade.price
|
|
99
|
+
# Explicit comparisons rather than max()/min(): this runs once per
|
|
100
|
+
# trade per timeframe, and the call overhead shows.
|
|
101
|
+
if price > self.high:
|
|
102
|
+
self.high = price
|
|
103
|
+
elif price < self.low:
|
|
104
|
+
self.low = price
|
|
105
|
+
if key < self.first:
|
|
106
|
+
self.first, self.open = key, price
|
|
107
|
+
if key >= self.last:
|
|
108
|
+
self.last, self.close = key, price
|
|
109
|
+
self.volume += trade.qty
|
|
110
|
+
self.quote_volume += notional
|
|
111
|
+
self.trades += 1
|
|
112
|
+
|
|
113
|
+
def to_state(self) -> dict[str, Any]:
|
|
114
|
+
return {
|
|
115
|
+
"tf": self.tf.value,
|
|
116
|
+
"start": self.start,
|
|
117
|
+
"ohlc": [str(self.open), str(self.high), str(self.low), str(self.close)],
|
|
118
|
+
"volume": str(self.volume),
|
|
119
|
+
"quote_volume": str(self.quote_volume),
|
|
120
|
+
"trades": self.trades,
|
|
121
|
+
"first": list(self.first),
|
|
122
|
+
"last": list(self.last),
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
@classmethod
|
|
126
|
+
def from_state(cls, symbol: str, data: dict[str, Any]) -> CandleBuilder:
|
|
127
|
+
o, h, lo, c = (Decimal(v) for v in data["ohlc"])
|
|
128
|
+
first, last = data["first"], data["last"]
|
|
129
|
+
return cls(
|
|
130
|
+
symbol=symbol,
|
|
131
|
+
tf=Timeframe(data["tf"]),
|
|
132
|
+
start=data["start"],
|
|
133
|
+
open=o,
|
|
134
|
+
high=h,
|
|
135
|
+
low=lo,
|
|
136
|
+
close=c,
|
|
137
|
+
volume=Decimal(data["volume"]),
|
|
138
|
+
quote_volume=Decimal(data["quote_volume"]),
|
|
139
|
+
trades=data["trades"],
|
|
140
|
+
first=(first[0], first[1], first[2], first[3]),
|
|
141
|
+
last=(last[0], last[1], last[2], last[3]),
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def snapshot(self, *, closed: bool) -> Candle:
|
|
145
|
+
return Candle(
|
|
146
|
+
symbol=self.symbol,
|
|
147
|
+
tf=self.tf,
|
|
148
|
+
time=self.start,
|
|
149
|
+
open=self.open,
|
|
150
|
+
high=self.high,
|
|
151
|
+
low=self.low,
|
|
152
|
+
close=self.close,
|
|
153
|
+
volume=self.volume,
|
|
154
|
+
quote_volume=self.quote_volume,
|
|
155
|
+
trades=self.trades,
|
|
156
|
+
closed=closed,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass(slots=True)
|
|
161
|
+
class _SymbolState:
|
|
162
|
+
watermark: int | None = None # None until the first trade: nothing can be late yet
|
|
163
|
+
max_event: int | None = None
|
|
164
|
+
open: dict[BucketKey, CandleBuilder] = field(default_factory=dict)
|
|
165
|
+
# Keys of the trades folded into each open 1m bucket. A duplicate always
|
|
166
|
+
# lands in the same bucket as its original, so this is all the memory
|
|
167
|
+
# dedup needs, and it is dropped the moment the bucket closes.
|
|
168
|
+
seen: dict[int, set[tuple[str, str]]] = field(default_factory=dict)
|
|
169
|
+
dirty: set[BucketKey] = field(default_factory=set)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True, slots=True)
|
|
173
|
+
class BatchResult:
|
|
174
|
+
candles: list[Candle]
|
|
175
|
+
late: list[Trade]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Aggregator:
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
*,
|
|
182
|
+
allowed_lateness_ms: int = 5_000,
|
|
183
|
+
timeframes: Sequence[Timeframe] = TIMEFRAMES,
|
|
184
|
+
) -> None:
|
|
185
|
+
if allowed_lateness_ms < 0:
|
|
186
|
+
raise ValueError("allowed lateness cannot be negative")
|
|
187
|
+
if BASE_TIMEFRAME not in timeframes:
|
|
188
|
+
raise ValueError(f"{BASE_TIMEFRAME} is required: lateness is judged against it")
|
|
189
|
+
self._lateness = allowed_lateness_ms
|
|
190
|
+
self._timeframes = tuple(tf for tf in TIMEFRAMES if tf in timeframes)
|
|
191
|
+
self._symbols: dict[str, _SymbolState] = {}
|
|
192
|
+
|
|
193
|
+
def watermark(self, symbol: str) -> int | None:
|
|
194
|
+
state = self._symbols.get(symbol)
|
|
195
|
+
return state.watermark if state else None
|
|
196
|
+
|
|
197
|
+
def advance(self, now_ms: int, idle_grace_ms: int) -> None:
|
|
198
|
+
"""Move every watermark up to ``now - lateness - grace`` on the wall clock.
|
|
199
|
+
|
|
200
|
+
Symbols that have never traded are left alone: they have nothing open,
|
|
201
|
+
and starting their watermark here would mark a slow first trade late.
|
|
202
|
+
"""
|
|
203
|
+
floor = now_ms - self._lateness - idle_grace_ms
|
|
204
|
+
for state in self._symbols.values():
|
|
205
|
+
if state.watermark is not None and floor > state.watermark:
|
|
206
|
+
state.watermark = floor
|
|
207
|
+
|
|
208
|
+
def observe(self, trades: Iterable[Trade]) -> tuple[list[Trade], list[Trade]]:
|
|
209
|
+
"""Split trades into on-time and late, advancing watermarks as it goes.
|
|
210
|
+
|
|
211
|
+
Order matters: a trade is judged against the watermark as it stood when
|
|
212
|
+
the trade arrived, exactly as if trades were fed one at a time. Buckets
|
|
213
|
+
are not closed here — ``flush`` does that after ``apply`` — so an early
|
|
214
|
+
trade in a batch still lands in a bucket that a later trade in the same
|
|
215
|
+
batch pushes past the watermark.
|
|
216
|
+
"""
|
|
217
|
+
on_time: list[Trade] = []
|
|
218
|
+
late: list[Trade] = []
|
|
219
|
+
lateness = self._lateness
|
|
220
|
+
for trade in trades:
|
|
221
|
+
state = self._symbols.get(trade.symbol)
|
|
222
|
+
if state is None:
|
|
223
|
+
state = self._symbols[trade.symbol] = _SymbolState()
|
|
224
|
+
ts = trade.ts_ms
|
|
225
|
+
if state.watermark is not None and ts - ts % _BASE_MS + _BASE_MS <= state.watermark:
|
|
226
|
+
late.append(trade)
|
|
227
|
+
continue
|
|
228
|
+
on_time.append(trade)
|
|
229
|
+
if state.max_event is None or ts > state.max_event:
|
|
230
|
+
state.max_event = ts
|
|
231
|
+
candidate = ts - lateness
|
|
232
|
+
if state.watermark is None or candidate > state.watermark:
|
|
233
|
+
state.watermark = candidate
|
|
234
|
+
return on_time, late
|
|
235
|
+
|
|
236
|
+
def apply(self, trades: Iterable[Trade]) -> None:
|
|
237
|
+
"""Fold trades that ``observe`` accepted into their open buckets."""
|
|
238
|
+
# The hot loop: widths are looked up once, not per trade and timeframe.
|
|
239
|
+
widths = [(tf, tf.ms) for tf in self._timeframes]
|
|
240
|
+
for trade in trades:
|
|
241
|
+
state = self._symbols[trade.symbol]
|
|
242
|
+
ts = trade.ts_ms
|
|
243
|
+
seen = state.seen.setdefault(ts - ts % _BASE_MS, set())
|
|
244
|
+
identity = trade.key
|
|
245
|
+
if identity in seen:
|
|
246
|
+
continue
|
|
247
|
+
seen.add(identity)
|
|
248
|
+
key = _order_key(trade)
|
|
249
|
+
notional = trade.price * trade.qty
|
|
250
|
+
for tf, width in widths:
|
|
251
|
+
bucket = (width, ts - ts % width)
|
|
252
|
+
builder = state.open.get(bucket)
|
|
253
|
+
if builder is None:
|
|
254
|
+
state.open[bucket] = CandleBuilder.from_trade(trade, tf, key, notional)
|
|
255
|
+
else:
|
|
256
|
+
builder.add(trade, key, notional)
|
|
257
|
+
state.dirty.add(bucket)
|
|
258
|
+
|
|
259
|
+
def flush(self) -> list[Candle]:
|
|
260
|
+
"""Close every bucket the watermark has passed; snapshot what changed.
|
|
261
|
+
|
|
262
|
+
Returns one snapshot per candle touched since the last flush — however
|
|
263
|
+
many trades touched it — so downstream writes scale with candles, not
|
|
264
|
+
trades. Closed candles are always included, marked ``closed=True``.
|
|
265
|
+
"""
|
|
266
|
+
out: list[Candle] = []
|
|
267
|
+
for state in self._symbols.values():
|
|
268
|
+
watermark = state.watermark
|
|
269
|
+
if watermark is not None:
|
|
270
|
+
for bucket in [b for b, c in state.open.items() if c.end <= watermark]:
|
|
271
|
+
out.append(state.open.pop(bucket).snapshot(closed=True))
|
|
272
|
+
state.dirty.discard(bucket)
|
|
273
|
+
for start in [s for s in state.seen if s + BASE_TIMEFRAME.ms <= watermark]:
|
|
274
|
+
del state.seen[start]
|
|
275
|
+
out.extend(state.open[bucket].snapshot(closed=False) for bucket in state.dirty)
|
|
276
|
+
state.dirty.clear()
|
|
277
|
+
out.sort(key=lambda c: (c.symbol, c.time, c.tf.ms))
|
|
278
|
+
return out
|
|
279
|
+
|
|
280
|
+
def export_state(self, symbol: str) -> dict[str, Any] | None:
|
|
281
|
+
"""Everything needed to resume ``symbol`` after a restart, as plain JSON types.
|
|
282
|
+
|
|
283
|
+
Call it straight after ``flush``: the open builders are then exactly the
|
|
284
|
+
candles the watermark has not passed, which is what a restart must
|
|
285
|
+
rebuild. The dedup keys are deliberately left out — after a restart the
|
|
286
|
+
trade log's unique key catches replays, and it is the only dedup that
|
|
287
|
+
survives a crash anyway.
|
|
288
|
+
"""
|
|
289
|
+
state = self._symbols.get(symbol)
|
|
290
|
+
if state is None or state.watermark is None:
|
|
291
|
+
return None
|
|
292
|
+
return {
|
|
293
|
+
"watermark": state.watermark,
|
|
294
|
+
"max_event": state.max_event,
|
|
295
|
+
"open": [builder.to_state() for builder in state.open.values()],
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
def restore_state(self, symbol: str, data: dict[str, Any]) -> None:
|
|
299
|
+
builders = [CandleBuilder.from_state(symbol, item) for item in data["open"]]
|
|
300
|
+
self._symbols[symbol] = _SymbolState(
|
|
301
|
+
watermark=data["watermark"],
|
|
302
|
+
max_event=data["max_event"],
|
|
303
|
+
open={(b.tf.ms, b.start): b for b in builders if b.tf in self._timeframes},
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
def process(self, trades: Iterable[Trade]) -> BatchResult:
|
|
307
|
+
"""``observe``, ``apply`` and ``flush`` in one step, when no store sits between."""
|
|
308
|
+
on_time, late = self.observe(trades)
|
|
309
|
+
self.apply(on_time)
|
|
310
|
+
return BatchResult(self.flush(), late)
|