""" Background asyncio workers (spec §8). Launched from app.py before demo.launch(). Step 1 (data foundation) ships three workers: • universe_refresher — rebuilds the dynamic universe via the funnel (hourly). • liq_consumer — drains the all-market liquidation WS into per-minute, per-symbol buckets; the strategy's L1 trigger source. • market_poller — every POLL_INTERVAL_SEC pulls funding/OI/mark for the current universe using BATCH calls where possible (one tickers call + one OI call for the whole market), then per-symbol funding → funding_z + oi_pctile → snapshot. The signal engine, active-signal monitor and alert dispatcher (Steps 2–3) attach to the same UniverseState + the liq buckets here. Heavy per-coin work (klines, taker delta, scoring) is deferred to the engine and is event-driven on flushes, so a wide universe stays cheap. """ from __future__ import annotations import asyncio import statistics import time import config from exchange.base import ExchangeClient from store import db import universe class UniverseState: """Shared, hot-swappable list of instruments the engine/poller operate on.""" def __init__(self, initial: list[str] | None = None): self.symbols: list[str] = initial or [] def set(self, syms: list[str]) -> None: self.symbols = syms # simple in-process caches (funding history changes every 8h; OI history hourly) _fhist_cache: dict[str, tuple[float, list[float]]] = {} _oihist_cache: dict[str, tuple[float, list[float]]] = {} _FHIST_TTL = 3600.0 _OIHIST_TTL = 1800.0 def _minute_ts(ms: int) -> int: return int(ms // 60000) async def universe_refresher(client: ExchangeClient, state: UniverseState, stop: asyncio.Event) -> None: while not stop.is_set(): try: syms = await universe.build(client) if syms: state.set(syms) print(f"[universe] {len(syms)} symbols " f"(mode={config.UNIVERSE_MODE}, min_turnover=${config.UNIVERSE_MIN_TURNOVER_USD:,.0f})", flush=True) except Exception as e: print(f"[universe] refresh error: {type(e).__name__}: {e}", flush=True) await _sleep_or_stop(stop, config.UNIVERSE_REFRESH_SEC) async def liq_consumer(client: ExchangeClient, stop: asyncio.Event) -> None: """Consume normalized liquidation events into minute buckets (spec §2.1).""" async for ev in client.liquidation_stream(): if stop.is_set(): break m = _minute_ts(ev.ts_ms) long_add = ev.notional if ev.liquidated_side == "long" else 0.0 short_add = ev.notional if ev.liquidated_side == "short" else 0.0 await asyncio.to_thread(db.upsert_liq_bucket, ev.symbol, m, long_add, short_add, 1, 1) async def market_poller(client: ExchangeClient, state: UniverseState, stop: asyncio.Event) -> None: """Poll REST market data for the current universe and persist snapshots.""" th = config.THRESHOLDS while not stop.is_set(): t0 = time.time() symbols = list(state.symbols) if not symbols: await _sleep_or_stop(stop, 5) continue # batch calls: last price (tickers) + OI base (one call each) last_map: dict[str, float] = {} oi_base_map: dict[str, float] = {} try: for t in await client.tickers_universe(): last_map[t.symbol] = t.last oi_base_map = await client.open_interest_map() except NotImplementedError: pass except Exception as e: print(f"[poller] batch error: {type(e).__name__}: {e}", flush=True) for sym in symbols: try: funding = await client.funding_rate(sym) fhist = await _cached(_fhist_cache, sym, _FHIST_TTL, lambda: client.funding_history(sym, th["funding_history_limit"])) oihist = await _cached(_oihist_cache, sym, _OIHIST_TTL, lambda: client.oi_history(sym, th["oi_history_period"], th["oi_history_limit"])) last = last_map.get(sym) or await client.mark_price(sym) oi_usd = oi_base_map.get(sym, 0.0) * last await asyncio.to_thread(db.save_market_snapshot, { "symbol": sym, "ts": int(time.time()), "funding_rate": funding, "funding_z": _zscore(funding, fhist), "oi_usd": oi_usd, "oi_pctile": _percentile_rank(oi_usd, oihist), "mark_price": last, "spot_price": None, }) except Exception as e: print(f"[poller] {sym} error: {type(e).__name__}: {e}", flush=True) await asyncio.sleep(0.12) # gentle pacing under OKX rate limits elapsed = time.time() - t0 await _sleep_or_stop(stop, max(1.0, config.POLL_INTERVAL_SEC - elapsed)) # ── helpers ────────────────────────────────────────────────────────────────── async def _cached(cache: dict, key: str, ttl: float, fetch): now = time.time() hit = cache.get(key) if hit and now - hit[0] < ttl: return hit[1] val = await fetch() cache[key] = (now, val) return val def _zscore(value: float, history: list[float]) -> float: pts = [h for h in history if h is not None] if len(pts) < 5: return 0.0 mu = statistics.fmean(pts) sd = statistics.pstdev(pts) return 0.0 if sd == 0 else (value - mu) / sd def _percentile_rank(value: float, history: list[float]) -> float: pts = [h for h in history if h is not None] if not pts: return 0.0 return sum(1 for h in pts if h <= value) / len(pts) async def _sleep_or_stop(stop: asyncio.Event, seconds: float) -> None: try: await asyncio.wait_for(stop.wait(), timeout=seconds) except asyncio.TimeoutError: pass async def start(client: ExchangeClient, stop: asyncio.Event) -> tuple[UniverseState, list[asyncio.Task]]: """Launch data-foundation workers; returns shared state + task handles.""" state = UniverseState() # seed the universe once before the poller starts so it has something to do try: state.set(await universe.build(client)) except Exception as e: print(f"[start] initial universe build failed: {type(e).__name__}: {e}", flush=True) tasks = [ asyncio.create_task(universe_refresher(client, state, stop), name="universe_refresher"), asyncio.create_task(liq_consumer(client, stop), name="liq_consumer"), asyncio.create_task(market_poller(client, state, stop), name="market_poller"), ] return state, tasks