""" Bybit V5 REST client using raw httpx (async). Docs: https://bybit-exchange.github.io/docs/v5/intro All calls use the PUBLIC category=linear endpoints (USDT perps, no auth needed for read-only). """ import asyncio import logging from typing import Any import httpx from config import BYBIT_BASE_URL, PROXY_URL from exchanges.base import BaseExchange from engine.symbol_resolver import get_symbol_variations from engine.bulk_fetcher import bulk_fetcher logger = logging.getLogger(__name__) TF_MAP = { "1m": "1", "3m": "3", "5m": "5", "15m": "15", "30m": "30", "1h": "60", "2h": "120", "4h": "240", "1d": "D", } class BybitClient(BaseExchange): name = "bybit" def __init__(self) -> None: client_kwargs = { "base_url": BYBIT_BASE_URL, "timeout": httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=10.0), "limits": httpx.Limits(max_connections=150, max_keepalive_connections=40, keepalive_expiry=30.0), "headers": {"Accept": "application/json"}, "verify": True, } if PROXY_URL: client_kwargs["proxy"] = PROXY_URL self._client = httpx.AsyncClient(**client_kwargs) self._known_symbols: set[str] = set() self._probed_symbols: set[str] = set() self._universe_loaded: bool = False self._last_symbols_load_time: float = 0.0 self._negative_cache: dict[str, float] = {} self._funding_intervals: dict[str, float] = {} # ------------------------------------------------------------------ # Internal helpers # ------------------------------------------------------------------ async def _get(self, path: str, params: dict | None = None) -> Any: try: resp = await self._client.get(path, params=params) resp.raise_for_status() data = resp.json() ret_code = data.get("retCode", -1) if ret_code != 0: raise RuntimeError(f"Bybit API error {ret_code}: {data.get('retMsg')}") return data.get("result", {}) except Exception as e: if "internetbaik" in str(e).lower() or "blocked" in str(e).lower(): logger.warning( "[Bybit] Akses diblokir ISP/Internet Baik. Gunakan VPN/WARP atau set PROXY_URL di .env" ) raise async def _load_symbols(self, force: bool = False) -> None: import time now = time.time() if self._universe_loaded and not force and (now - self._last_symbols_load_time < 1800): return if not self._universe_loaded and not force and (now - self._last_symbols_load_time < 300): return self._last_symbols_load_time = now try: new_set: set[str] = set() new_intervals: dict[str, float] = {} cursor = "" for _ in range(10): params: dict[str, Any] = {"category": "linear", "limit": 1000} if cursor: params["cursor"] = cursor result = await self._get("/v5/market/instruments-info", params) for item in result.get("list", []): if item.get("contractType") == "LinearPerpetual" and item.get("symbol"): sym = str(item["symbol"]).upper() new_set.add(sym) raw_iv = item.get("fundingInterval") if raw_iv not in (None, ""): try: iv_h = float(raw_iv) / 60.0 if 0 < iv_h <= 24: new_intervals[sym] = iv_h except (TypeError, ValueError): pass next_cursor = str(result.get("nextPageCursor") or "").strip() if not next_cursor or next_cursor == cursor: break cursor = next_cursor if new_set: self._known_symbols = new_set self._universe_loaded = True if new_intervals: self._funding_intervals = new_intervals except Exception as exc: logger.warning("[Bybit] Failed to load instruments-info: %s", exc) def resolve_symbol(self, symbol: str) -> str | None: """Resolve symbol or multiplier variations to Bybit's native symbol.""" sym = symbol.upper().strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") all_known = self._known_symbols | self._probed_symbols if all_known: if sym in all_known: return sym for var in get_symbol_variations(symbol): if var in all_known: return var if self._universe_loaded or self._known_symbols: return None # Only fallback to cleaned symbol if full universe hasn't loaded return sym # ------------------------------------------------------------------ # BaseExchange implementation # ------------------------------------------------------------------ async def check_symbol_exists(self, symbol: str) -> bool: sym = symbol.upper().strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", "") all_known = self._known_symbols | self._probed_symbols # 1. Fast in-memory check if all_known: if sym in all_known: return True for var in get_symbol_variations(symbol): if var in all_known: return True # Check negative cache to avoid spamming failed probes on every 60s loop import time now = time.time() if sym in self._negative_cache and (now - self._negative_cache[sym] < 900): return False # 2. If full universe hasn't loaded, trigger bulk load first if not self._universe_loaded: await self._load_symbols() if self._known_symbols: if sym in self._known_symbols: return True for var in get_symbol_variations(symbol): if var in self._known_symbols: return True # 3. Direct lightweight probe fallback (50ms via tickers, kept out of _known_symbols) for var in get_symbol_variations(symbol): if not (var.endswith("USDT") or var.endswith("USDC")): continue try: resp = await self._client.get( "/v5/market/tickers", params={"category": "linear", "symbol": var}, timeout=4.0, ) if resp.status_code == 200: data = resp.json() if len(data.get("result", {}).get("list", [])) > 0: self._probed_symbols.add(var) return True except Exception: pass # 4. If cache is stale (>10 min), try reloading once if now - self._last_symbols_load_time > 600: await self._load_symbols(force=True) if self._known_symbols and sym in self._known_symbols: return True self._negative_cache[sym] = now return False async def get_mark_price(self, symbol: str) -> dict[str, Any]: bulk_data = bulk_fetcher.get_bybit_mark_price(symbol) if bulk_data: return bulk_data sym = self.resolve_symbol(symbol) or symbol result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym}) items = result.get("list", []) if not items: raise ValueError(f"No ticker data for {sym}") t = items[0] mark = float(t.get("markPrice") or 0) index = float(t.get("indexPrice") or 0) basis_pct = ((mark - index) / index * 100) if index else 0.0 return { "mark_price": mark, "index_price": index, "basis_pct": round(basis_pct, 6), } async def get_funding_rate(self, symbol: str) -> dict[str, Any]: sym = self.resolve_symbol(symbol) or symbol.upper().strip().replace("/", "").replace("-", "") bulk_data = bulk_fetcher.get_bybit_funding_rate(symbol) if bulk_data: return bulk_data result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym}) items = result.get("list", []) if not items: raise ValueError(f"No ticker data for {sym}") t = items[0] fr_val = float(t.get("fundingRate") or 0) interval_raw = t.get("fundingIntervalHour") interval_h = float(interval_raw) if interval_raw not in (None, "") else float(self._funding_intervals.get(sym, 8.0)) if 0 < interval_h < 24 and interval_h != 8.0: fr_val = fr_val * (8.0 / interval_h) nft_raw = t.get("nextFundingTime") nft_val = int(nft_raw) if (nft_raw not in (None, "") and str(nft_raw).isdigit()) else None return { "funding_rate": fr_val, "next_funding_time": nft_val, } @staticmethod def _extract_oi_size(item: dict[str, Any]) -> float: raw_single = item.get("singleOpenInterest") if raw_single not in (None, ""): return float(raw_single) return float(item.get("openInterest") or 0) async def get_open_interest(self, symbol: str) -> dict[str, Any]: """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest from Bybit.""" sym = self.resolve_symbol(symbol) if not sym: return { "open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": None, "oi_change_1h_pct": None, "oi_change_4h_pct": None, "open_interest_value": None, } bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol) bulk_oi_val = bulk_oi.get("open_interest_value") if bulk_oi else None try: result = await self._get( "/v5/market/open-interest", {"category": "linear", "symbol": sym, "intervalTime": "15min", "limit": 17}, ) items = result.get("list", []) if len(items) >= 2: # Bybit returns newest first: reverse to oldest->newest for shared horizon calculation series = [self._extract_oi_size(item) for item in reversed(items)] curr_oi = series[-1] prev_oi = series[-2] oi_15m, oi_1h, oi_4h = self._compute_oi_horizons(series) return { "open_interest": curr_oi, "prev_open_interest": prev_oi, "oi_change_pct": oi_15m, "oi_change_1h_pct": oi_1h, "oi_change_4h_pct": oi_4h, "open_interest_value": bulk_oi_val, } elif items: curr_oi = self._extract_oi_size(items[0]) return { "open_interest": curr_oi, "prev_open_interest": None, "oi_change_pct": None, "oi_change_1h_pct": None, "oi_change_4h_pct": None, "open_interest_value": bulk_oi_val, } except Exception as exc: logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc) # Fallback to bulk ticker OI if available if bulk_oi and bulk_oi.get("open_interest"): return { "open_interest": bulk_oi["open_interest"], "prev_open_interest": None, "oi_change_pct": None, "oi_change_1h_pct": None, "oi_change_4h_pct": None, "open_interest_value": bulk_oi_val, } return { "open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": None, "oi_change_1h_pct": None, "oi_change_4h_pct": None, "open_interest_value": None, } async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: """ Bybit provides account long/short ratio via /v5/market/account-ratio. Returns real ratio or None if unavailable. """ sym = self.resolve_symbol(symbol) if not sym: return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} bybit_period = { "5m": "5min", "5min": "5min", "15m": "15min", "15min": "15min", "30m": "30min", "30min": "30min", "1h": "1h", "2h": "1h", "4h": "4h", "1d": "1d", }.get((period or "1h").lower(), "1h") try: result = await self._get( "/v5/market/account-ratio", {"category": "linear", "symbol": sym, "period": bybit_period, "limit": 1}, ) items = result.get("list", []) if items: buy_r = items[0].get("buyRatio") sell_r = items[0].get("sellRatio") if buy_r is not None and sell_r is not None: long_r = float(buy_r) return { "long_ratio": long_r, "short_ratio": float(sell_r), "retail_long_ratio": long_r, "top_position_long_ratio": None, "source": "retail", } except Exception as exc: logger.debug("Bybit L/S ratio fetch note for %s: %s", sym, exc) return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]: sym = self.resolve_symbol(symbol) or symbol interval = TF_MAP.get(timeframe, timeframe) result = await self._get( "/v5/market/kline", {"category": "linear", "symbol": sym, "interval": interval, "limit": limit}, ) candles = [] for k in reversed(result.get("list", [])): # Bybit returns: [timestamp, open, high, low, close, volume, turnover] candles.append( { "timestamp": int(k[0]), "open": float(k[1]), "high": float(k[2]), "low": float(k[3]), "close": float(k[4]), "volume": float(k[5]), "taker_buy_volume": None, # not directly available } ) return candles async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]: sym = self.resolve_symbol(symbol) or symbol limit = min(limit, 1000) result = await self._get( "/v5/market/recent-trade", {"category": "linear", "symbol": sym, "limit": limit}, ) trades = [] for t in result.get("list", []): side = str(t.get("side", "Buy")).strip().lower() # "sell" = seller is taker = buyer maker is True is_buyer_maker = (side == "sell") entry: dict[str, Any] = { "price": float(t["price"]), "qty": float(t["size"]), "is_buyer_maker": is_buyer_maker, "time": int(t["time"]), } if t.get("execId"): entry["trade_id"] = str(t["execId"]) trades.append(entry) # Sort chronologically (oldest first) to ensure consistent ordering with Binance trades.sort(key=lambda t: t["time"]) return trades async def get_spot_trades(self, symbol: str, limit: int = 500) -> list[dict]: """Fetch spot trades from Bybit Spot market for Spot vs Futures CVD divergence analysis.""" from engine.data_collector import _clean_spot_symbol raw_sym = symbol.upper().replace("-", "").replace("/", "").replace("_", "").strip() spot_sym = _clean_spot_symbol(symbol) probe_syms = [raw_sym] if raw_sym == spot_sym else [raw_sym, spot_sym] limit = min(limit, 1000) for cand_sym in probe_syms: try: result = await self._get( "/v5/market/recent-trade", {"category": "spot", "symbol": cand_sym, "limit": limit}, ) raw_list = result.get("list") or [] if not raw_list: continue trades = [] for t in raw_list: side = str(t.get("side", "Buy")).strip().lower() is_buyer_maker = (side == "sell") trades.append( { "price": float(t["price"]), "qty": float(t["size"]), "is_buyer_maker": is_buyer_maker, "time": int(t["time"]), } ) trades.sort(key=lambda t: t["time"]) return trades except Exception: continue return [] async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: sym = self.resolve_symbol(symbol) or symbol result = await self._get( "/v5/market/orderbook", {"category": "linear", "symbol": sym, "limit": depth}, ) return { "bids": [[float(p), float(q)] for p, q in result.get("b", [])], "asks": [[float(p), float(q)] for p, q in result.get("a", [])], } async def get_oi_history(self, symbol: str, timeframe: str = "15m", limit: int = 150) -> list[dict]: """Fetch historical Open Interest from Bybit (/v5/market/open-interest).""" sym = self.resolve_symbol(symbol) or symbol interval_map = { "1m": "5min", "3m": "5min", "5m": "5min", "15m": "15min", "30m": "30min", "1h": "1h", "2h": "1h", "4h": "4h", "1d": "1d", } interval = interval_map.get(timeframe, "15min") try: res = await self._get( "/v5/market/open-interest", {"category": "linear", "symbol": sym, "intervalTime": interval, "limit": min(limit, 200)}, ) raw_list = res.get("list", []) if not isinstance(raw_list, list): return [] results = [] for item in raw_list: ts = int(item.get("timestamp", 0)) oi = self._extract_oi_size(item) results.append({ "timestamp": ts, "open_interest": oi, }) results.sort(key=lambda x: x["timestamp"]) return results except Exception as exc: logger.debug("[Bybit] Failed to fetch OI history for %s: %s", sym, exc) return [] async def get_funding_rate_history(self, symbol: str, limit: int = 50) -> list[dict]: """Fetch historical funding rates from Bybit (/v5/market/funding/history), normalized to 8h equivalent.""" sym = self.resolve_symbol(symbol) or symbol try: res = await self._get( "/v5/market/funding/history", {"category": "linear", "symbol": sym, "limit": min(limit, 100)}, ) raw_list = res.get("list", []) if not isinstance(raw_list, list): return [] ordered = sorted(raw_list, key=lambda x: int(x.get("fundingRateTimestamp", 0))) interval_h = float(self._funding_intervals.get(sym.upper(), 8.0)) if interval_h == 8.0 and len(ordered) >= 2: deltas = [ (int(ordered[i].get("fundingRateTimestamp", 0)) - int(ordered[i - 1].get("fundingRateTimestamp", 0))) / 3_600_000.0 for i in range(1, len(ordered)) ] pos_deltas = [round(d) for d in deltas if 0.5 <= d <= 24.0] if pos_deltas and pos_deltas[-1] in (1, 2, 4, 8): interval_h = float(pos_deltas[-1]) scale = (8.0 / interval_h) if (interval_h > 0 and interval_h != 8.0) else 1.0 results = [] for item in ordered: results.append({ "timestamp": int(item.get("fundingRateTimestamp", 0)), "funding_rate": float(item.get("fundingRate", 0.0) or 0.0) * scale, }) return results except Exception as exc: logger.debug("[Bybit] Failed to fetch funding history for %s: %s", sym, exc) return [] async def close(self) -> None: await self._client.aclose()