File size: 6,947 Bytes
c6262df | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | """
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
|