""" DataCollector – aggregates raw market data across Binance, Bybit, OKX, and Hyperliquid. Returns a unified dict used by the signal engine: { "symbol": str, "binance": dict | None, "bybit": dict | None, "okx": dict | None, "hyperliquid": dict | None, } """ import asyncio import logging import re import time from typing import Any import httpx from config import BYBIT_BASE_URL, PROXY_URL from engine.symbol_resolver import strip_multiplier_prefix from exchanges.binance import BinanceClient from exchanges.bybit import BybitClient from exchanges.okx import OKXClient from exchanges.hyperliquid import HyperliquidClient from exchanges.bitget import BitgetClient logger = logging.getLogger(__name__) # Cache spot availability across Binance, Bybit, and OKX spot markets: (has_spot: bool, timestamp: float) _SPOT_VERIFICATION_CACHE: dict[str, tuple[bool, float]] = {} _spot_cache_lock = asyncio.Lock() _SPOT_HTTP_CLIENT: httpx.AsyncClient | None = None _SPOT_HTTP_LOOP: asyncio.AbstractEventLoop | None = None def _get_spot_http_client() -> httpx.AsyncClient: """Return a loop-safe persistent AsyncClient for spot existence probes.""" global _SPOT_HTTP_CLIENT, _SPOT_HTTP_LOOP try: current_loop = asyncio.get_running_loop() except RuntimeError: current_loop = None loop_changed = ( _SPOT_HTTP_LOOP is not None and (_SPOT_HTTP_LOOP.is_closed() or (current_loop is not None and _SPOT_HTTP_LOOP is not current_loop)) ) if _SPOT_HTTP_CLIENT is None or _SPOT_HTTP_CLIENT.is_closed or loop_changed: kwargs: dict[str, Any] = { "timeout": 2.5, "verify": True, "limits": httpx.Limits( max_keepalive_connections=10, max_connections=25, keepalive_expiry=20.0, ), } if PROXY_URL: kwargs["proxy"] = PROXY_URL _SPOT_HTTP_CLIENT = httpx.AsyncClient(**kwargs) _SPOT_HTTP_LOOP = current_loop return _SPOT_HTTP_CLIENT def _clean_spot_symbol(symbol: str) -> str: """ Strip futures multiplier prefixes (1000, 10000, 1000000, known meme k-prefixes) to match spot tickers without mangling tokens like KAVAUSDT or KASUSDT. """ return strip_multiplier_prefix(symbol) async def check_spot_market_exists(symbol: str) -> bool: """ Check if a symbol exists on Binance Spot, Bybit Spot, or OKX Spot market. Supports both raw tickers (BTCUSDT, 1000SATSUSDT) and cleaned tickers (PEPEUSDT for 1000PEPEUSDT). - If verified True: cached permanently in memory. - If False: re-checks automatically every 1 hour in case a spot market is newly listed. """ sym = symbol.upper().strip().replace("/", "").replace("-", "") now = time.time() async with _spot_cache_lock: if sym in _SPOT_VERIFICATION_CACHE: cached_has_spot, timestamp = _SPOT_VERIFICATION_CACHE[sym] # Permanent True or cached False within 1 hour if cached_has_spot or (now - timestamp < 3600): return cached_has_spot clean_symbol = _clean_spot_symbol(sym) symbols_to_try = [sym] if clean_symbol and clean_symbol != sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")): symbols_to_try.append(clean_symbol) client = _get_spot_http_client() # Run Spot checks across Binance, Bybit, and OKX in parallel using shared connection pool. # Distinguish definitive misses (404 / empty listing) from transient HTTP/network failures. async def _check_binance() -> tuple[bool, bool]: had_transient = False for s_cand in symbols_to_try: try: r = await client.get(f"https://api.binance.com/api/v3/ticker/price?symbol={s_cand}") if r.status_code == 200: return True, False if r.status_code >= 500 or r.status_code == 429 or r.status_code == 451: had_transient = True except Exception: had_transient = True return False, had_transient async def _check_bybit() -> tuple[bool, bool]: had_transient = False for s_cand in symbols_to_try: try: r = await client.get(f"{BYBIT_BASE_URL}/v5/market/instruments-info?category=spot&symbol={s_cand}") if r.status_code == 200: data = r.json() if len(data.get("result", {}).get("list", [])) > 0: return True, False elif r.status_code >= 500 or r.status_code == 429: had_transient = True except Exception: had_transient = True return False, had_transient async def _check_okx() -> tuple[bool, bool]: had_transient = False for s_cand in symbols_to_try: inst_id = None for quote in ("USDT", "USDC", "USD", "BUSD", "EUR"): if s_cand.endswith(quote) and len(s_cand) > len(quote): inst_id = f"{s_cand[:-len(quote)]}-{quote}" break if inst_id: try: r = await client.get(f"https://www.okx.com/api/v5/public/instruments?instType=SPOT&instId={inst_id}") if r.status_code == 200: data = r.json() if len(data.get("data", [])) > 0: return True, False elif r.status_code >= 500 or r.status_code == 429: had_transient = True except Exception: had_transient = True return False, had_transient results = await asyncio.gather(_check_binance(), _check_bybit(), _check_okx(), return_exceptions=True) has_spot = any(isinstance(res, tuple) and res[0] is True for res in results) any_transient = any( isinstance(res, Exception) or (isinstance(res, tuple) and res[1] is True) for res in results ) if has_spot or not any_transient: async with _spot_cache_lock: _SPOT_VERIFICATION_CACHE[sym] = (has_spot, now) return has_spot class DataCollector: def __init__( self, binance: BinanceClient | None = None, bybit: BybitClient | None = None, okx: OKXClient | None = None, hyperliquid: HyperliquidClient | None = None, bitget: BitgetClient | None = None, ) -> None: self._binance = binance or BinanceClient() self._bybit = bybit or BybitClient() self._okx = okx or OKXClient() self._hyperliquid = hyperliquid or HyperliquidClient() self._bitget = bitget or BitgetClient() async def collect( self, symbol: str, on_binance: bool = True, on_bybit: bool = True, on_okx: bool = True, on_hyperliquid: bool = True, on_bitget: bool = True, ) -> dict[str, Any]: """ Collect market snapshot from Binance, Bybit, OKX, Hyperliquid, and Bitget. Partial failures are tolerated gracefully. """ tasks: dict[str, Any] = {} if on_binance: tasks["binance"] = self._binance.get_full_snapshot(symbol) if on_bybit: tasks["bybit"] = self._bybit.get_full_snapshot(symbol) # OKX Triangulation async def _fetch_okx(): try: exists = await self._okx.check_symbol_exists(symbol) if not exists: return None return await self._okx.get_full_snapshot(symbol) except Exception as exc: logger.debug("[%s] OKX collect error: %s", symbol, exc) return None # Bitget Triangulation async def _fetch_bitget(): try: exists = await self._bitget.check_symbol_exists(symbol) if not exists: return None return await self._bitget.get_full_snapshot(symbol) except Exception as exc: logger.debug("[%s] Bitget collect error: %s", symbol, exc) return None # Hyperliquid On-Chain DEX async def _fetch_hl(): try: market_data, orderbook, hl_trades, ohlcv_5m, ohlcv_15m = await asyncio.gather( self._hyperliquid.get_market_data(symbol), self._hyperliquid.get_orderbook(symbol, depth=20), self._hyperliquid.get_recent_trades(symbol), self._hyperliquid.get_ohlcv(symbol, timeframe="5m", limit=30), self._hyperliquid.get_ohlcv(symbol, timeframe="15m", limit=30), return_exceptions=True, ) if isinstance(market_data, Exception) or not market_data: return None market_data["orderbook"] = orderbook if not isinstance(orderbook, Exception) else None market_data["trades"] = hl_trades if (not isinstance(hl_trades, Exception) and isinstance(hl_trades, list)) else [] market_data["ohlcv"] = { "5m": ohlcv_5m if (not isinstance(ohlcv_5m, Exception) and isinstance(ohlcv_5m, list)) else [], "15m": ohlcv_15m if (not isinstance(ohlcv_15m, Exception) and isinstance(ohlcv_15m, list)) else [], } return market_data except Exception as exc: logger.debug("[%s] Hyperliquid collect error: %s", symbol, exc) return None if on_okx: tasks["okx"] = _fetch_okx() if on_bitget: tasks["bitget"] = _fetch_bitget() if on_hyperliquid: tasks["hyperliquid"] = _fetch_hl() tasks["has_spot"] = check_spot_market_exists(symbol) results: dict[str, Any] = { "symbol": symbol, "binance": None, "bybit": None, "okx": None, "bitget": None, "hyperliquid": None, "has_spot": False, } gathered = await asyncio.gather(*tasks.values(), return_exceptions=True) for key, val in zip(tasks.keys(), gathered): if isinstance(val, Exception): logger.warning("[%s] %s data collection failed: %s", symbol, key, val) results[key] = False if key == "has_spot" else None else: results[key] = val # Secondary confirmation: If binance returned actual spot trades, definitely has spot if results.get("binance") and results["binance"].get("spot_trades"): results["has_spot"] = True # Drop 100% empty-shell snapshots (e.g. unlisted coins where every sub-endpoint failed) for exch_key in ("binance", "bybit", "okx", "bitget"): snap = results.get(exch_key) if isinstance(snap, dict) and ( snap.get("mark_price_data") is None and snap.get("funding_rate_data") is None and snap.get("open_interest_data") is None and snap.get("ls_ratio_data") is None and snap.get("orderbook") is None and not snap.get("trades") and not snap.get("spot_trades") and not any((snap.get("ohlcv") or {}).values()) ): results[exch_key] = None # Enrich trade and liquidation feeds across 5 venues from rolling multi-minute WebSocket buffer when active try: from engine.ws_trade_stream import merge_trade_feeds, trade_stream_buffer venue_clients = ( ("binance", self._binance), ("bybit", self._bybit), ("okx", self._okx), ("bitget", self._bitget), ("hyperliquid", self._hyperliquid), ) for exch_key, exch_client in venue_clients: snap = results.get(exch_key) if isinstance(snap, dict): resolved_sym = None resolve_fn = getattr(exch_client, "resolve_symbol", None) or getattr(exch_client, "resolve_coin", None) if callable(resolve_fn): try: resolved_sym = resolve_fn(symbol) except Exception: resolved_sym = None lookup_sym = resolved_sym or symbol buf_trades = trade_stream_buffer.get_recent_trades(exch_key, lookup_sym) if not buf_trades and resolved_sym and resolved_sym != symbol: buf_trades = trade_stream_buffer.get_recent_trades(exch_key, symbol) if buf_trades: snap["trades"] = merge_trade_feeds(snap.get("trades"), buf_trades) buf_liqs = trade_stream_buffer.get_recent_liquidations(exch_key, lookup_sym) if not buf_liqs and resolved_sym and resolved_sym != symbol: buf_liqs = trade_stream_buffer.get_recent_liquidations(exch_key, symbol) if buf_liqs: existing_liqs = list(snap.get("liquidations") or []) combined_liqs = existing_liqs + list(buf_liqs) combined_liqs.sort(key=lambda x: int(x.get("time") or 0)) snap["liquidations"] = combined_liqs[-200:] except Exception as ws_exc: logger.debug("[%s] WS trade/liquidation buffer enrichment skipped: %s", symbol, ws_exc) return results async def get_ohlcv_merged( self, symbol: str, timeframes: tuple[str, ...] = ("15m",), limit: int = 120, ) -> dict[str, list[dict]]: """ Fetch OHLCV candles for a symbol across fallback venues (Binance -> Bybit -> OKX -> Bitget) for background tape/outcome evaluation. """ out: dict[str, list[dict]] = {} clients = (self._binance, self._bybit, self._okx, self._bitget) for tf in timeframes: bars: list[dict] = [] for client in clients: if not client or not callable(getattr(client, "get_ohlcv", None)): continue try: res = await client.get_ohlcv(symbol, timeframe=tf, limit=limit) if isinstance(res, list) and res: bars = res break except Exception as exc: logger.debug("[%s] get_ohlcv_merged(%s) fallback skip: %s", symbol, tf, exc) continue out[tf] = bars return out