""" Abstract base class for exchange clients. Each concrete client must implement all abstract methods. All methods are async-first and must NOT block the event loop. """ from abc import ABC, abstractmethod import time from typing import Any class BaseExchange(ABC): """Minimal contract every exchange adapter must fulfil.""" name: str = "base" # ------------------------------------------------------------------ # Market info # ------------------------------------------------------------------ @abstractmethod async def get_mark_price(self, symbol: str) -> dict[str, Any]: """ Return: { "mark_price": float, "index_price": float, "basis_pct": float, } """ @abstractmethod async def get_funding_rate(self, symbol: str) -> dict[str, Any]: """ Return: { "funding_rate": float, # e.g. 0.0001 "next_funding_time": int | None, } """ @abstractmethod async def get_open_interest(self, symbol: str) -> dict[str, Any]: """ Return: { "open_interest": float, # in USD notional "open_interest_value": float | None, } """ @abstractmethod async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: """ Top-trader account long/short ratio. Return: { "long_ratio": float, # 0.0–1.0 "short_ratio": float, "source": "top_trader" | "global", } """ @abstractmethod async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]: """ Return list of candles: [{"timestamp": int, "open": float, "high": float, "low": float, "close": float, "volume": float}, ...] """ @abstractmethod async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]: """ Return list: [{"price": float, "qty": float, "is_buyer_maker": bool, "time": int}, ...] """ @abstractmethod async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: """ Return: { "bids": [[price, qty], ...], # best bid first "asks": [[price, qty], ...], # best ask first } """ @abstractmethod async def check_symbol_exists(self, symbol: str) -> bool: """Return True if the perpetual symbol exists on this exchange.""" # ------------------------------------------------------------------ # Convenience # ------------------------------------------------------------------ @staticmethod def record_oi_change_with_meta( snaps_map: dict[str, list[tuple[float, float]]], symbol_key: str, current_oi: float, window_sec: float = 300.0, min_sample_gap_sec: float = 30.0, max_age_sec: float = 3600.0, ) -> tuple[float | None, float | None]: """Compute percentage OI change against rolling baseline and return (oi_change_pct, window_sec).""" if current_oi <= 0: return None, None now_ts = time.time() raw_snaps = snaps_map.get(symbol_key, []) # Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps snaps = [(ts, val) for ts, val in raw_snaps if (now_ts - ts) <= max_age_sec and val > 0] snaps_map[symbol_key] = snaps oi_change_pct = None window_sec_actual = None if snaps: anchor_pair = next(((ts, val) for ts, val in reversed(snaps) if (now_ts - ts) >= window_sec), snaps[0]) anchor_ts, anchor_val = anchor_pair if anchor_val > 0: oi_change_pct = round((current_oi - anchor_val) / anchor_val * 100.0, 4) window_sec_actual = round(now_ts - anchor_ts, 2) if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec: snaps.append((now_ts, current_oi)) if len(snaps) > 64: del snaps[:-64] return oi_change_pct, window_sec_actual def _record_oi_change_with_meta( self, symbol_key: str, current_oi: float, window_sec: float = 300.0, min_sample_gap_sec: float = 30.0, max_age_sec: float = 3600.0, ) -> tuple[float | None, float | None]: snaps_map = getattr(self, "_oi_snapshots", None) if snaps_map is None: snaps_map = {} self._oi_snapshots = snaps_map return self.record_oi_change_with_meta( snaps_map, symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec ) def _record_oi_change( self, symbol_key: str, current_oi: float, window_sec: float = 300.0, min_sample_gap_sec: float = 30.0, max_age_sec: float = 3600.0, ) -> float | None: """Compute percentage OI change against a rolling ~5m (or oldest recent) baseline.""" pct, _ = self._record_oi_change_with_meta( symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec ) return pct @staticmethod def _compute_oi_horizons( oi_series_oldest_first: list[float], ) -> tuple[float | None, float | None, float | None]: """Compute 15m, 1h (>=5 bars), and 4h (>=17 bars) OI % changes without mislabeling short history.""" if len(oi_series_oldest_first) < 2: return None, None, None curr_oi = oi_series_oldest_first[-1] prev_15m = oi_series_oldest_first[-2] oi_15m = round(((curr_oi - prev_15m) / prev_15m) * 100.0, 4) if prev_15m > 0 else None oi_1h = None if len(oi_series_oldest_first) >= 5: prev_1h = oi_series_oldest_first[-5] if prev_1h > 0: oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4) oi_4h = None if len(oi_series_oldest_first) >= 17: prev_4h = oi_series_oldest_first[-17] if prev_4h > 0: oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4) return oi_15m, oi_1h, oi_4h def _is_spot_unlisted(self, symbol_key: str, ttl_sec: float = 1800.0) -> bool: cache = getattr(self, "_spot_negative_cache", None) if not cache: return False ts = cache.get(symbol_key.upper()) if ts is None: return False if (time.time() - ts) < ttl_sec: return True cache.pop(symbol_key.upper(), None) return False def _mark_spot_unlisted(self, symbol_key: str) -> None: cache = getattr(self, "_spot_negative_cache", None) if cache is None: cache = {} self._spot_negative_cache = cache cache[symbol_key.upper()] = time.time() def _clear_spot_unlisted(self, symbol_key: str) -> None: cache = getattr(self, "_spot_negative_cache", None) if cache: cache.pop(symbol_key.upper(), None) @staticmethod def _normalize_taker_buy_volume( buy_vol: float, sell_vol: float | None, candle_vol: float, ) -> float: """ Convert exchange taker buy/sell stats into base-coin candle volume units. When both buy and sell volumes exist (even in USD or contracts), preserve the exact taker buy share proportionally onto candle_vol and clamp safely to [0, candle_vol]. """ b = max(0.0, float(buy_vol or 0.0)) c_vol = max(0.0, float(candle_vol or 0.0)) if sell_vol is not None: s = max(0.0, float(sell_vol or 0.0)) tot = b + s if tot > 0 and c_vol > 0: return round(min(c_vol, (b / tot) * c_vol), 8) if c_vol > 0: return round(min(c_vol, b), 8) return round(b, 8) @staticmethod def _match_taker_buy_volume( taker_map: dict[int, tuple[float, float | None]], candle_ts: int, interval_ms: int, candle_vol: float, ) -> float | None: """Match closest taker volume entry to candle_ts and return normalized base-coin buy volume.""" if not taker_map: return None if candle_ts in taker_map: tb_buy, tb_sell = taker_map[candle_ts] return BaseExchange._normalize_taker_buy_volume(tb_buy, tb_sell, candle_vol) best_pair = None min_diff = interval_ms for t_ts, pair_vals in taker_map.items(): diff = abs(candle_ts - t_ts) if diff < min_diff: min_diff = diff best_pair = pair_vals if best_pair is not None: return BaseExchange._normalize_taker_buy_volume(best_pair[0], best_pair[1], candle_vol) return None async def get_full_snapshot(self, symbol: str) -> dict[str, Any]: """ Collect all data for a symbol in one call. Partial failures are tolerated – missing keys will be None. """ import asyncio results: dict[str, Any] = { "symbol": symbol, "exchange": self.name, "mark_price_data": None, "funding_rate_data": None, "open_interest_data": None, "ls_ratio_data": None, "ohlcv": {}, "trades": [], "spot_trades": [], "orderbook": None, "liquidations": [], } async def safe(coro, key): try: results[key] = await coro except Exception as exc: results[key] = None timeframes = ["1m", "5m", "15m", "1h", "4h", "1d"] tasks = [ safe(self.get_mark_price(symbol), "mark_price_data"), safe(self.get_funding_rate(symbol), "funding_rate_data"), safe(self.get_open_interest(symbol), "open_interest_data"), safe(self.get_long_short_ratio(symbol), "ls_ratio_data"), safe(self.get_recent_trades(symbol, limit=500), "trades"), safe(self.get_orderbook(symbol, depth=20), "orderbook"), ] if hasattr(self, "get_spot_trades"): tasks.append(safe(self.get_spot_trades(symbol, limit=500), "spot_trades")) if hasattr(self, "get_liquidations"): tasks.append(safe(self.get_liquidations(symbol, limit=100), "liquidations")) # OHLCV per timeframe (30 recent 1m bars for FakeDetector, 100 bars for higher TFs) ohlcv_results: dict[str, list] = {} for tf in timeframes: async def _fetch_ohlcv(tf=tf): try: tf_limit = 30 if tf == "1m" else 100 ohlcv_results[tf] = await self.get_ohlcv(symbol, tf, limit=tf_limit) except Exception: ohlcv_results[tf] = [] tasks.append(_fetch_ohlcv()) await asyncio.gather(*tasks, return_exceptions=True) results["ohlcv"] = ohlcv_results return results