|
| 1 | +"""Price-feed latency — how delayed the data we trade on actually is. |
| 2 | +
|
| 3 | +Two signals feed one in-memory registry, with no DB writes on the hot path: |
| 4 | +
|
| 5 | +- *Feed latency*: Binance stream payloads carry the exchange event time |
| 6 | + (`E`, ms). On receipt the hub records `local_clock − event_time`. |
| 7 | +- *REST round-trip*: each candle refresh records how long the HTTP call took. |
| 8 | +
|
| 9 | +Per `(market, symbol, kind)` a rolling window of recent samples backs the |
| 10 | +current / p50 / p95 / max stats the API serves. A 1-minute rollup row is |
| 11 | +persisted by the engine tick so history survives restarts. The freshness |
| 12 | +module's hard freeze is unchanged — latency adds the softer "degraded" |
| 13 | +signal (default threshold 2 s) that warns before staleness trips. |
| 14 | +""" |
| 15 | + |
| 16 | +import logging |
| 17 | +import threading |
| 18 | +from collections import deque |
| 19 | +from dataclasses import dataclass |
| 20 | +from datetime import UTC, datetime |
| 21 | +from decimal import Decimal |
| 22 | + |
| 23 | +from sqlmodel import Field, Session, SQLModel |
| 24 | + |
| 25 | +log = logging.getLogger("capital.marketdata.latency") |
| 26 | + |
| 27 | +_AMT = {"max_digits": 12, "decimal_places": 2} |
| 28 | + |
| 29 | +#: Feed latency above this is *degraded* — surfaced, but trading continues. |
| 30 | +DEFAULT_WARN_MS = 2000.0 |
| 31 | + |
| 32 | +_WINDOW = 500 # samples kept per key for the rolling stats |
| 33 | + |
| 34 | + |
| 35 | +class FeedLatency(SQLModel, table=True): |
| 36 | + """One persisted minute-rollup of feed latency for one key.""" |
| 37 | + |
| 38 | + __tablename__ = "feed_latency" |
| 39 | + |
| 40 | + id: int | None = Field(default=None, primary_key=True) |
| 41 | + market: str = Field(max_length=8, index=True) |
| 42 | + symbol: str = Field(max_length=24, index=True) |
| 43 | + kind: str = Field(max_length=8) # ws | rest |
| 44 | + samples: int = Field(default=0) |
| 45 | + avg_ms: Decimal = Field(default=Decimal(0), **_AMT) |
| 46 | + p95_ms: Decimal = Field(default=Decimal(0), **_AMT) |
| 47 | + max_ms: Decimal = Field(default=Decimal(0), **_AMT) |
| 48 | + recorded_at: datetime = Field(index=True) |
| 49 | + |
| 50 | + |
| 51 | +@dataclass |
| 52 | +class LatencyStats: |
| 53 | + """The rolling-window view for one `(market, symbol, kind)`.""" |
| 54 | + |
| 55 | + market: str |
| 56 | + symbol: str |
| 57 | + kind: str |
| 58 | + current_ms: float |
| 59 | + p50_ms: float |
| 60 | + p95_ms: float |
| 61 | + max_ms: float |
| 62 | + samples: int |
| 63 | + degraded: bool |
| 64 | + |
| 65 | + |
| 66 | +def _percentile(ordered: list[float], q: float) -> float: |
| 67 | + if not ordered: |
| 68 | + return 0.0 |
| 69 | + idx = min(len(ordered) - 1, max(0, round(q * (len(ordered) - 1)))) |
| 70 | + return ordered[idx] |
| 71 | + |
| 72 | + |
| 73 | +class LatencyRegistry: |
| 74 | + """Thread-safe in-memory latency samples (stream + engine threads write).""" |
| 75 | + |
| 76 | + def __init__(self, *, window: int = _WINDOW) -> None: |
| 77 | + self._window = window |
| 78 | + self._lock = threading.Lock() |
| 79 | + self._samples: dict[tuple[str, str, str], deque[float]] = {} |
| 80 | + # Samples since the last rollup flush, per key. |
| 81 | + self._pending: dict[tuple[str, str, str], list[float]] = {} |
| 82 | + |
| 83 | + def record(self, market: str, symbol: str, kind: str, latency_ms: float) -> None: |
| 84 | + """Record one sample. Negative values (clock skew) clamp to zero.""" |
| 85 | + value = max(0.0, float(latency_ms)) |
| 86 | + key = (market, symbol, kind) |
| 87 | + with self._lock: |
| 88 | + window = self._samples.get(key) |
| 89 | + if window is None: |
| 90 | + window = self._samples[key] = deque(maxlen=self._window) |
| 91 | + window.append(value) |
| 92 | + self._pending.setdefault(key, []).append(value) |
| 93 | + |
| 94 | + def stats(self, *, warn_ms: float = DEFAULT_WARN_MS) -> list[LatencyStats]: |
| 95 | + """Rolling-window stats for every key seen so far.""" |
| 96 | + with self._lock: |
| 97 | + items = [(key, list(window)) for key, window in self._samples.items()] |
| 98 | + out: list[LatencyStats] = [] |
| 99 | + for (market, symbol, kind), values in sorted(items): |
| 100 | + ordered = sorted(values) |
| 101 | + current = values[-1] if values else 0.0 |
| 102 | + p95 = _percentile(ordered, 0.95) |
| 103 | + out.append( |
| 104 | + LatencyStats( |
| 105 | + market=market, |
| 106 | + symbol=symbol, |
| 107 | + kind=kind, |
| 108 | + current_ms=round(current, 1), |
| 109 | + p50_ms=round(_percentile(ordered, 0.50), 1), |
| 110 | + p95_ms=round(p95, 1), |
| 111 | + max_ms=round(ordered[-1] if ordered else 0.0, 1), |
| 112 | + samples=len(values), |
| 113 | + degraded=current > warn_ms or p95 > warn_ms, |
| 114 | + ) |
| 115 | + ) |
| 116 | + return out |
| 117 | + |
| 118 | + def degraded(self, *, warn_ms: float = DEFAULT_WARN_MS) -> bool: |
| 119 | + """Whether any feed is currently above the warn threshold.""" |
| 120 | + return any(s.degraded for s in self.stats(warn_ms=warn_ms)) |
| 121 | + |
| 122 | + def flush_rollups(self, session: Session) -> int: |
| 123 | + """Persist (and clear) the pending samples as one rollup row per key.""" |
| 124 | + with self._lock: |
| 125 | + pending, self._pending = self._pending, {} |
| 126 | + now = datetime.now(UTC).replace(tzinfo=None) |
| 127 | + written = 0 |
| 128 | + for (market, symbol, kind), values in pending.items(): |
| 129 | + if not values: |
| 130 | + continue |
| 131 | + ordered = sorted(values) |
| 132 | + session.add( |
| 133 | + FeedLatency( |
| 134 | + market=market, |
| 135 | + symbol=symbol, |
| 136 | + kind=kind, |
| 137 | + samples=len(values), |
| 138 | + avg_ms=Decimal(str(round(sum(values) / len(values), 2))), |
| 139 | + p95_ms=Decimal(str(round(_percentile(ordered, 0.95), 2))), |
| 140 | + max_ms=Decimal(str(round(ordered[-1], 2))), |
| 141 | + recorded_at=now, |
| 142 | + ) |
| 143 | + ) |
| 144 | + written += 1 |
| 145 | + if written: |
| 146 | + session.commit() |
| 147 | + return written |
| 148 | + |
| 149 | + |
| 150 | +#: Process-wide registry — the stream hubs and candle refresh write into it. |
| 151 | +registry = LatencyRegistry() |
| 152 | + |
| 153 | + |
| 154 | +def record_event_time( |
| 155 | + market: str, symbol: str, event_time_ms: object, *, now_ms: float | None = None |
| 156 | +) -> None: |
| 157 | + """Record feed latency from an exchange event timestamp (ms since epoch).""" |
| 158 | + try: |
| 159 | + event_ms = float(event_time_ms) # type: ignore[arg-type] |
| 160 | + except (TypeError, ValueError): |
| 161 | + return |
| 162 | + if event_ms <= 0: |
| 163 | + return |
| 164 | + local = now_ms if now_ms is not None else datetime.now(UTC).timestamp() * 1000 |
| 165 | + registry.record(market, symbol, "ws", local - event_ms) |
0 commit comments