""" ExchangeClient interface (spec §12.1: "Build this abstraction from day one"). OKX is the one implemented backend (the only free, geo-reachable source that exposes all four layers). The ABC is kept deliberately: it documents the data contract and lets a second source be added later without touching the engine. Data is returned in normalized shapes regardless of upstream JSON quirks. The seven core methods are abstract (any backend must implement them). The universe/taker helpers are optional (default NotImplementedError) so a future minimal backend can be added without implementing the full surface — the active source (OKX) implements everything. """ from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import AsyncIterator @dataclass class LiqEvent: """One liquidation order, normalized across exchanges. liquidated_side: 'long' -> a long position was force-closed (a forced SELL) 'short' -> a short position was force-closed (a forced BUY) notional: price * qty in USD(T). ts_ms: event time, unix milliseconds. """ symbol: str liquidated_side: str # 'long' | 'short' price: float qty: float notional: float ts_ms: int @dataclass class Ticker: """A perp ticker row used by the universe funnel (spec §2.4, D5).""" symbol: str # exchange-native instrument id (e.g. 'BTC-USDT-SWAP') last: float # last price turnover_usd: float # 24h turnover in USD (liquidity ranking key) class ExchangeClient(ABC): """Async interface every exchange backend must implement.""" name: str = "base" # ── REST: market data (core, required) ────────────────────────────────── @abstractmethod async def funding_rate(self, symbol: str) -> float: """Current funding rate (fraction, e.g. 0.0001 = 0.01%).""" @abstractmethod async def funding_history(self, symbol: str, limit: int) -> list[float]: """Historical funding rates (oldest→newest) for rolling z-score.""" @abstractmethod async def open_interest(self, symbol: str) -> float: """Current open interest in USD value.""" @abstractmethod async def oi_history(self, symbol: str, period: str, limit: int) -> list[float]: """Historical OI (USD) oldest→newest for percentile computation.""" @abstractmethod async def klines(self, symbol: str, interval: str, limit: int) -> list[dict]: """OHLCV bars oldest→newest. Each: {ts, open, high, low, close, volume, taker_buy_volume}.""" @abstractmethod async def mark_price(self, symbol: str) -> float: """Current mark price.""" # ── REST: universe & order-flow (optional — used by the active source) ─── async def tickers_universe(self) -> list[Ticker]: """All USDT-perp tickers for the dynamic-universe funnel (spec §2.4/D5).""" raise NotImplementedError(f"{self.name} has no tickers_universe()") async def open_interest_map(self) -> dict[str, float]: """Batch {symbol: oi_base} for all perps (one call) to avoid N requests.""" raise NotImplementedError(f"{self.name} has no open_interest_map()") async def taker_volume(self, symbol: str, period: str, limit: int) -> list[dict]: """Taker buy/sell volume bars (oldest→newest) for L3. Each: {ts, buy, sell}.""" raise NotImplementedError(f"{self.name} has no taker_volume()") # ── WebSocket: liquidations (spec §2.1) ───────────────────────────────── @abstractmethod def liquidation_stream(self) -> AsyncIterator[LiqEvent]: """Async generator yielding normalized LiqEvents for ALL symbols. Implementations must auto-reconnect with exponential backoff.""" @abstractmethod async def aclose(self) -> None: """Release HTTP/WS resources.""" def get_client(exchange: str, watchlist: list[str], timeout: float): """Factory: return the configured ExchangeClient. Only OKX is implemented in v1.0 — Binance/Bybit are geo-blocked on free hosts (verified: HTTP 451/403) and were removed. Branch here to add a new source. """ exchange = (exchange or "okx").lower().strip() if exchange == "okx": from .okx import OKXClient return OKXClient(watchlist=watchlist, timeout=timeout) raise ValueError( f"EXCHANGE={exchange!r} is not supported in v1.0 (only 'okx'). " f"Binance/Bybit are geo-blocked on free hosts." )