Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download backend/exchanges/okx.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 32.9 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/exchanges/okx.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/exchanges/okx.py
-
curl -L -o okx.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/exchanges/okx.py
32.9 kB
| """ | |
| OKX Public V5 REST client (Async, read-only). | |
| Docs: https://www.okx.com/docs-v5/en/ | |
| Provides: | |
| - Perpetual swap ticker, mark price, index price | |
| - 8h Funding Rate | |
| - Open Interest (coin & USD value) | |
| - Recent trades for multi-exchange CVD comparison | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| from typing import Any | |
| import httpx | |
| from config import PROXY_URL | |
| from engine.doh_resolver import enable_doh_bypass | |
| from engine.symbol_resolver import get_symbol_variations | |
| from exchanges.base import BaseExchange | |
| enable_doh_bypass() | |
| logger = logging.getLogger(__name__) | |
| OKX_BASE_URL = "https://www.okx.com" | |
| TF_MAP = { | |
| "1m": "1m", | |
| "3m": "3m", | |
| "5m": "5m", | |
| "15m": "15m", | |
| "30m": "30m", | |
| "1h": "1H", | |
| "2h": "2H", | |
| "4h": "4H", | |
| "1d": "1D", | |
| } | |
| class OKXClient(BaseExchange): | |
| name = "okx" | |
| def __init__(self) -> None: | |
| client_kwargs = { | |
| "base_url": OKX_BASE_URL, | |
| "timeout": 10.0, | |
| "limits": httpx.Limits( | |
| max_keepalive_connections=15, | |
| max_connections=30, | |
| keepalive_expiry=20.0, | |
| ), | |
| "headers": { | |
| "Accept": "application/json", | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", | |
| }, | |
| "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._inst_map: dict[str, str] = {} | |
| self._negative_cache: dict[str, float] = {} | |
| self._contract_spec_cache: dict[str, tuple[float, bool]] = {} | |
| self._funding_interval_cache: dict[str, float] = {} | |
| def _to_float(val: Any, default: float = 0.0) -> float: | |
| if val is None or val == "": | |
| return default | |
| try: | |
| out = float(val) | |
| return out if out == out else default | |
| except (ValueError, TypeError): | |
| return default | |
| def _to_int(val: Any, default: int | None = None) -> int | None: | |
| if val is None or val == "": | |
| return default | |
| try: | |
| return int(float(val)) | |
| except (ValueError, TypeError): | |
| return default | |
| def resolve_inst_id(self, symbol: str) -> str | None: | |
| """Resolve any user or cross-exchange ticker to OKX's exact instId.""" | |
| sym = symbol.upper().strip() | |
| if sym in self._inst_map: | |
| return self._inst_map[sym] | |
| for v in get_symbol_variations(symbol): | |
| if v.upper() in self._inst_map: | |
| return self._inst_map[v.upper()] | |
| return None | |
| def _to_inst_id(self, symbol: str) -> str: | |
| """Convert any symbol (e.g. BTCUSDT, BTC/USDC, 1000PEPEUSDT) -> OKX instId.""" | |
| resolved = self.resolve_inst_id(symbol) | |
| if resolved: | |
| return resolved | |
| raw_upper = symbol.upper().strip() | |
| if raw_upper.endswith("-SWAP") and "-" in raw_upper[:-5]: | |
| return raw_upper | |
| sym = raw_upper.replace("/", "").replace("-", "").replace("_", "").replace(" ", "") | |
| for quote in ("USDT", "USDC", "USD", "EUR"): | |
| if sym.endswith(quote) and len(sym) > len(quote): | |
| base = sym[:-len(quote)] | |
| return f"{base}-{quote}-SWAP" | |
| return f"{sym}-SWAP" | |
| 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() | |
| code = data.get("code", "0") | |
| if code != "0": | |
| raise RuntimeError(f"OKX API error {code}: {data.get('msg')}") | |
| return data.get("data", []) | |
| except Exception as e: | |
| logger.warning("[OKX] Request to %s failed: %s", path, e) | |
| raise | |
| async def _load_symbols(self) -> None: | |
| if self._universe_loaded and self._known_symbols: | |
| return | |
| try: | |
| items = await self._get("/api/v5/public/instruments", {"instType": "SWAP"}) | |
| if not isinstance(items, list): | |
| return | |
| base_priority: dict[str, int] = {} | |
| quote_rank = {"USDT": 0, "USDC": 1, "USD": 2} | |
| for it in items: | |
| if it.get("state", "live") != "live": | |
| continue | |
| inst_id = it.get("instId", "") | |
| parts = inst_id.split("-") | |
| if len(parts) >= 3 and parts[-1] == "SWAP": | |
| base = parts[0].upper() | |
| quote = parts[1].upper() | |
| sym_standard = f"{base}{quote}" | |
| self._known_symbols.add(sym_standard) | |
| self._known_symbols.add(inst_id) | |
| self._inst_map[sym_standard] = inst_id | |
| self._inst_map[inst_id] = inst_id | |
| rank = quote_rank.get(quote, 3) | |
| if rank < base_priority.get(base, 99): | |
| self._inst_map[base] = inst_id | |
| base_priority[base] = rank | |
| ct_val = self._to_float(it.get("ctVal"), 0.0) | |
| ct_mult = self._to_float(it.get("ctMult"), 1.0) | |
| if ct_mult <= 0: | |
| ct_mult = 1.0 | |
| if ct_val > 0: | |
| ct_type = str(it.get("ctType", "")).lower() | |
| is_inv = ct_type == "inverse" or (not ct_type and inst_id.upper().endswith("-USD-SWAP")) | |
| spec = (ct_val * ct_mult, is_inv) | |
| self._contract_spec_cache[inst_id] = spec | |
| try: | |
| from engine.ws_trade_stream import trade_stream_buffer | |
| trade_stream_buffer.set_okx_contract_spec(inst_id, spec[0], spec[1]) | |
| except Exception: | |
| pass | |
| self._universe_loaded = True | |
| except Exception as exc: | |
| logger.warning("[OKX] Symbol discovery failed: %s", exc) | |
| async def check_symbol_exists(self, symbol: str) -> bool: | |
| # 1. Fast in-memory check | |
| if self.resolve_inst_id(symbol): | |
| return True | |
| sym_key = symbol.strip().upper().replace("/", "").replace("-", "") | |
| # Check negative cache to avoid spamming failed probes on every 60s loop | |
| import time | |
| now = time.time() | |
| if sym_key in self._negative_cache and (now - self._negative_cache[sym_key] < 900): | |
| return False | |
| # 2. Ensure full swap universe is loaded via single bulk call | |
| if not self._universe_loaded: | |
| await self._load_symbols() | |
| if self.resolve_inst_id(symbol): | |
| return True | |
| # 3. Direct lightweight probe fallback (only target most probable instrument IDs) | |
| from engine.symbol_resolver import strip_multiplier_prefix | |
| clean = sym_key | |
| stripped = strip_multiplier_prefix(clean) | |
| base = clean[:-4] if clean.endswith("USDT") or clean.endswith("USDC") else clean | |
| stripped_base = stripped[:-4] if stripped.endswith("USDT") or stripped.endswith("USDC") else stripped | |
| candidates: list[str] = [] | |
| for cand in (f"{base}-USDT-SWAP", f"{stripped_base}-USDT-SWAP", f"{clean}-SWAP"): | |
| if cand not in candidates: | |
| candidates.append(cand) | |
| for inst_cand in candidates: | |
| try: | |
| resp = await self._client.get( | |
| "/api/v5/market/ticker", | |
| params={"instId": inst_cand}, | |
| timeout=3.0, | |
| ) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| if data.get("code") == "0" and len(data.get("data", [])) > 0: | |
| self._probed_symbols.add(sym_key) | |
| self._known_symbols.add(sym_key) | |
| self._inst_map[sym_key] = inst_cand | |
| self._negative_cache.pop(sym_key, None) | |
| return True | |
| except Exception: | |
| pass | |
| self._negative_cache[sym_key] = now | |
| return False | |
| async def get_mark_price(self, symbol: str) -> dict[str, Any]: | |
| inst_id = self._to_inst_id(symbol) | |
| # Fetch ticker and mark-price in parallel (1 RTT instead of 2 sequential RTTs) | |
| ticker_res, mp_res = await asyncio.gather( | |
| self._get("/api/v5/market/ticker", {"instId": inst_id}), | |
| self._get("/api/v5/public/mark-price", {"instId": inst_id, "instType": "SWAP"}), | |
| return_exceptions=True, | |
| ) | |
| if isinstance(ticker_res, Exception): | |
| raise ticker_res | |
| if not ticker_res: | |
| raise ValueError(f"No OKX ticker for {symbol}") | |
| t = ticker_res[0] | |
| last = self._to_float(t.get("last"), 0.0) | |
| index = last | |
| if not isinstance(mp_res, Exception) and mp_res: | |
| raw_mark = self._to_float(mp_res[0].get("markPx"), 0.0) | |
| mark = raw_mark if raw_mark > 0 else last | |
| raw_idx = self._to_float(mp_res[0].get("idxPx"), 0.0) | |
| if raw_idx > 0: | |
| index = raw_idx | |
| else: | |
| mark = last | |
| basis_pct = ((mark - index) / index * 100) if index else 0.0 | |
| high_24h = self._to_float(t.get("high24h"), 0.0) | |
| low_24h = self._to_float(t.get("low24h"), 0.0) | |
| vol_ccy_24h = self._to_float(t.get("volCcy24h"), 0.0) | |
| quote_vol_24h = (vol_ccy_24h * mark) if (vol_ccy_24h > 0 and mark > 0) else 0.0 | |
| return { | |
| "mark_price": mark, | |
| "index_price": index, | |
| "basis_pct": round(basis_pct, 6), | |
| "high_24h": high_24h, | |
| "low_24h": low_24h, | |
| "quote_volume_24h": round(quote_vol_24h, 2), | |
| } | |
| async def get_funding_rate(self, symbol: str) -> dict[str, Any]: | |
| inst_id = self._to_inst_id(symbol) | |
| data = await self._get("/api/v5/public/funding-rate", {"instId": inst_id}) | |
| if not data: | |
| raise ValueError(f"No OKX funding rate for {symbol}") | |
| row = data[0] | |
| fr = self._to_float(row.get("fundingRate"), 0.0) | |
| ft = self._to_int(row.get("fundingTime")) | |
| nft = self._to_int(row.get("nextFundingTime")) | |
| pft = self._to_int(row.get("prevFundingTime")) | |
| # OKX fundingTime is the upcoming settlement timestamp; nextFundingTime is the cycle after. | |
| upcoming_ts = ft if (ft is not None and ft > 0) else (nft if (nft is not None and nft > 0) else None) | |
| interval_h = self._funding_interval_cache.get(inst_id, 8.0) | |
| if ft is not None and pft is not None and ft > pft: | |
| calc_h = (ft - pft) / 3_600_000.0 | |
| if 1.0 <= calc_h <= 24.0: | |
| interval_h = calc_h | |
| self._funding_interval_cache[inst_id] = interval_h | |
| elif ft is not None and nft is not None and nft > ft: | |
| calc_h = (nft - ft) / 3_600_000.0 | |
| if 1.0 <= calc_h <= 24.0: | |
| interval_h = calc_h | |
| self._funding_interval_cache[inst_id] = interval_h | |
| fr_8h = round(fr * (8.0 / interval_h), 10) if interval_h > 0 and interval_h != 8.0 else fr | |
| return { | |
| "funding_rate": fr_8h, | |
| "next_funding_time": upcoming_ts, | |
| } | |
| async def get_funding_rate_history(self, symbol: str, limit: int = 50) -> list[dict]: | |
| """Fetch historical funding rates from OKX (/api/v5/public/funding-rate-history).""" | |
| inst_id = self._to_inst_id(symbol) | |
| try: | |
| data = await self._get( | |
| "/api/v5/public/funding-rate-history", | |
| {"instId": inst_id, "limit": str(min(limit, 100))}, | |
| ) | |
| if not data or not isinstance(data, list): | |
| return [] | |
| out = [] | |
| for item in data: | |
| ts = self._to_int(item.get("fundingTime"), 0) or 0 | |
| fr = self._to_float(item.get("fundingRate"), 0.0) | |
| if ts > 0: | |
| out.append({ | |
| "timestamp": ts, | |
| "funding_rate": fr, | |
| }) | |
| out.sort(key=lambda x: x["timestamp"]) | |
| interval_h = self._funding_interval_cache.get(inst_id) | |
| if interval_h is None and len(out) >= 2: | |
| diffs = [ | |
| (out[i]["timestamp"] - out[i - 1]["timestamp"]) / 3_600_000.0 | |
| for i in range(1, len(out)) | |
| if 1.0 <= (out[i]["timestamp"] - out[i - 1]["timestamp"]) / 3_600_000.0 <= 24.0 | |
| ] | |
| if diffs: | |
| diffs.sort() | |
| interval_h = diffs[len(diffs) // 2] | |
| if interval_h and interval_h > 0 and abs(interval_h - 8.0) > 0.05: | |
| scale = 8.0 / interval_h | |
| for entry in out: | |
| entry["funding_rate"] = round(entry["funding_rate"] * scale, 10) | |
| return out | |
| except Exception as exc: | |
| logger.debug("[OKX] Failed to fetch funding history for %s: %s", symbol, exc) | |
| return [] | |
| async def get_spot_trades(self, symbol: str, limit: int = 100) -> list[dict]: | |
| """Fetch spot trades from OKX Spot market for Spot vs Futures CVD divergence analysis.""" | |
| import httpx | |
| from engine.symbol_resolver import strip_multiplier_prefix | |
| norm = strip_multiplier_prefix(symbol) | |
| base = norm | |
| for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): | |
| if base.endswith(q) and len(base) > len(q): | |
| base = base[:-len(q)] | |
| break | |
| if not base or self._is_spot_unlisted(base): | |
| return [] | |
| probe_inst_ids = [f"{base}-USDT", f"{base}-USDC"] | |
| saw_permanent_miss = False | |
| saw_transient_error = False | |
| for inst_id in probe_inst_ids: | |
| try: | |
| data = await self._get( | |
| "/api/v5/market/trades", | |
| {"instId": inst_id, "limit": str(min(limit, 100))}, | |
| ) | |
| if not data or not isinstance(data, list): | |
| saw_permanent_miss = True | |
| continue | |
| trades = [] | |
| for t in data: | |
| try: | |
| side = str(t.get("side", "buy")).lower() | |
| is_buyer_maker = (side == "sell") | |
| trades.append({ | |
| "price": float(t["px"]), | |
| "qty": float(t["sz"]), | |
| "is_buyer_maker": is_buyer_maker, | |
| "time": int(t["ts"]), | |
| "venue": "okx_spot", | |
| }) | |
| except (KeyError, ValueError, TypeError): | |
| continue | |
| if trades: | |
| self._clear_spot_unlisted(base) | |
| trades.sort(key=lambda x: x["time"]) | |
| return trades | |
| saw_permanent_miss = True | |
| except httpx.HTTPStatusError as exc: | |
| if exc.response is not None and 400 <= exc.response.status_code < 500: | |
| saw_permanent_miss = True | |
| else: | |
| saw_transient_error = True | |
| continue | |
| except RuntimeError as exc: | |
| msg = str(exc).lower() | |
| if "51001" in msg or "does not exist" in msg or "not listed" in msg or "invalid" in msg: | |
| saw_permanent_miss = True | |
| else: | |
| saw_transient_error = True | |
| continue | |
| except Exception: | |
| saw_transient_error = True | |
| continue | |
| if saw_permanent_miss and not saw_transient_error: | |
| self._mark_spot_unlisted(base) | |
| return [] | |
| async def get_open_interest(self, symbol: str) -> dict[str, Any]: | |
| inst_id = self._to_inst_id(symbol) | |
| tasks = [ | |
| self._get("/api/v5/public/open-interest", {"instType": "SWAP", "instId": inst_id}), | |
| self._get("/api/v5/rubik/stat/contracts/open-interest-history", {"instId": inst_id, "period": "5m", "limit": "49"}), | |
| ] | |
| res_oi, res_hist = await asyncio.gather(*tasks, return_exceptions=True) | |
| if isinstance(res_oi, Exception) or not res_oi or not isinstance(res_oi, list): | |
| return {"open_interest": 0.0, "open_interest_value": None, "oi_change_pct": None} | |
| oi = self._to_float(res_oi[0].get("oiCcy"), 0.0) | |
| # OKX returns oi (contracts), oiCcy (base coins), and oiUsd (USD notional value) | |
| raw_oi_usd = res_oi[0].get("oiUsd") | |
| oi_val = self._to_float(raw_oi_usd, -1.0) | |
| if oi_val < 0: | |
| oi_val = None | |
| oi_change_pct = None | |
| oi_change_1h_pct = None | |
| oi_change_4h_pct = None | |
| oi_horizon = None | |
| oi_window_sec = None | |
| if not isinstance(res_hist, Exception) and isinstance(res_hist, list) and len(res_hist) >= 4: | |
| try: | |
| sorted_hist = sorted(res_hist, key=lambda x: int(x[0])) | |
| oi_series = [] | |
| for it in sorted_hist: | |
| if len(it) > 2 and it[2] is not None and it[2] != "": | |
| oi_series.append(float(it[2])) | |
| elif len(it) > 1 and it[1] is not None and it[1] != "": | |
| oi_series.append(float(it[1])) | |
| if len(oi_series) >= 4: | |
| curr_oi = oi_series[-1] | |
| prev_15m = oi_series[-4] | |
| if prev_15m > 0: | |
| oi_change_pct = round((curr_oi - prev_15m) / prev_15m * 100.0, 4) | |
| if len(oi_series) >= 13: | |
| prev_1h = oi_series[-13] | |
| if prev_1h > 0: | |
| oi_change_1h_pct = round((curr_oi - prev_1h) / prev_1h * 100.0, 4) | |
| if len(oi_series) >= 49: | |
| prev_4h = oi_series[-49] | |
| if prev_4h > 0: | |
| oi_change_4h_pct = round((curr_oi - prev_4h) / prev_4h * 100.0, 4) | |
| oi_horizon = "15m" | |
| oi_window_sec = 900.0 | |
| except Exception as exc: | |
| logger.debug("[OKX] OI history parse error for %s: %s", symbol, exc) | |
| if oi_horizon is None: | |
| oi_change_pct, oi_window_sec = self._record_oi_change_with_meta(inst_id, oi) | |
| oi_horizon = "rolling" | |
| return { | |
| "open_interest": oi, | |
| "open_interest_value": oi_val, | |
| "oi_change_pct": oi_change_pct, | |
| "oi_change_1h_pct": oi_change_1h_pct, | |
| "oi_change_4h_pct": oi_change_4h_pct, | |
| "oi_horizon": oi_horizon, | |
| "oi_window_sec": oi_window_sec, | |
| } | |
| async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]: | |
| """OKX Long/Short account ratio & top-trader position ratio via rubik stat.""" | |
| from engine.symbol_resolver import strip_multiplier_prefix | |
| norm = strip_multiplier_prefix(symbol) | |
| base_ccy = norm | |
| for q in ("USDT", "USDC", "USD", "BUSD", "EUR"): | |
| if base_ccy.endswith(q) and len(base_ccy) > len(q): | |
| base_ccy = base_ccy[:-len(q)] | |
| break | |
| okx_period = {"5m": "5m", "15m": "5m", "30m": "5m", "1h": "1H", "4h": "1H", "1d": "1D"}.get( | |
| (period or "1h").lower(), "1H" | |
| ) | |
| inst_id = self._to_inst_id(symbol) | |
| tasks = [ | |
| self._get("/api/v5/rubik/stat/contracts/long-short-account-ratio", {"ccy": base_ccy, "period": okx_period}), | |
| self._get("/api/v5/rubik/stat/contracts/long-short-position-ratio-contract-top-trader", {"instId": inst_id, "period": okx_period, "limit": "1"}), | |
| ] | |
| res_acct, res_pos = await asyncio.gather(*tasks, return_exceptions=True) | |
| saw_invalid_neg_acct = False | |
| retail_long_ratio = None | |
| if not isinstance(res_acct, Exception) and res_acct and len(res_acct) > 0: | |
| try: | |
| item = res_acct[0] | |
| ratio_val = float(item[1]) if isinstance(item, (list, tuple)) else float(item.get("ratio", item.get("longShortRatio", 1.0))) | |
| if ratio_val < 0: | |
| saw_invalid_neg_acct = True | |
| else: | |
| retail_long_ratio = round(ratio_val / (1.0 + ratio_val), 4) | |
| except Exception as exc: | |
| logger.debug("[OKX] Account L/S ratio parse error for %s: %s", symbol, exc) | |
| top_pos_ratio = None | |
| if not isinstance(res_pos, Exception) and res_pos and len(res_pos) > 0: | |
| try: | |
| item = res_pos[0] | |
| if isinstance(item, (list, tuple)) and len(item) >= 2: | |
| r = float(item[1]) | |
| if r >= 0: | |
| top_pos_ratio = round(r / (1.0 + r), 4) | |
| elif isinstance(item, dict): | |
| if "longPos" in item and "shortPos" in item: | |
| lp, sp = float(item["longPos"]), float(item["shortPos"]) | |
| if lp + sp > 0: | |
| top_pos_ratio = round(lp / (lp + sp), 4) | |
| elif "ratio" in item: | |
| r = float(item["ratio"]) | |
| if r >= 0: | |
| top_pos_ratio = round(r / (1.0 + r), 4) | |
| elif "longShortRatio" in item: | |
| r = float(item["longShortRatio"]) | |
| if r >= 0: | |
| top_pos_ratio = round(r / (1.0 + r), 4) | |
| except Exception as exc: | |
| logger.debug("[OKX] Top position L/S ratio parse error for %s: %s", symbol, exc) | |
| if saw_invalid_neg_acct and top_pos_ratio is None: | |
| return None | |
| if retail_long_ratio is not None and top_pos_ratio is not None: | |
| whale_retail_delta = round(top_pos_ratio - retail_long_ratio, 4) | |
| return { | |
| "long_ratio": top_pos_ratio, | |
| "short_ratio": round(1.0 - top_pos_ratio, 4), | |
| "top_position_long_ratio": top_pos_ratio, | |
| "retail_long_ratio": retail_long_ratio, | |
| "whale_retail_delta": whale_retail_delta, | |
| "source": "smart_money", | |
| } | |
| if top_pos_ratio is not None: | |
| return { | |
| "long_ratio": top_pos_ratio, | |
| "short_ratio": round(1.0 - top_pos_ratio, 4), | |
| "top_position_long_ratio": top_pos_ratio, | |
| "retail_long_ratio": None, | |
| "whale_retail_delta": None, | |
| "source": "top_trader", | |
| } | |
| if retail_long_ratio is not None: | |
| return { | |
| "long_ratio": retail_long_ratio, | |
| "short_ratio": round(1.0 - retail_long_ratio, 4), | |
| "top_position_long_ratio": None, | |
| "retail_long_ratio": retail_long_ratio, | |
| "whale_retail_delta": None, | |
| "source": "retail", | |
| } | |
| return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} | |
| async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]: | |
| inst_id = self._to_inst_id(symbol) | |
| bar = TF_MAP.get(timeframe, "1H") | |
| tasks = [ | |
| self._get( | |
| "/api/v5/market/candles", | |
| {"instId": inst_id, "bar": bar, "limit": min(limit, 100)}, | |
| ), | |
| ] | |
| fetch_taker = timeframe in ("15m", "1h") | |
| if fetch_taker: | |
| okx_taker_period = {"15m": "15m", "1h": "1H"}.get(timeframe, "15m") | |
| tasks.append( | |
| self._get( | |
| "/api/v5/rubik/stat/taker-volume-contract", | |
| {"instId": inst_id, "period": okx_taker_period, "unit": "0"}, | |
| ) | |
| ) | |
| results = await asyncio.gather(*tasks, return_exceptions=True) | |
| data = results[0] | |
| if isinstance(data, Exception) or not data or not isinstance(data, list): | |
| return [] | |
| taker_map: dict[int, tuple[float, float | None]] = {} | |
| if fetch_taker and len(results) > 1 and not isinstance(results[1], Exception) and isinstance(results[1], list): | |
| for row in results[1]: | |
| try: | |
| if isinstance(row, (list, tuple)): | |
| ts = int(row[0]) | |
| # OKX Rubik taker-volume format: [ts, sellVol, buyVol] | |
| if len(row) >= 3: | |
| sell_v = float(row[1]) | |
| buy_v = float(row[2]) | |
| else: | |
| sell_v = None | |
| buy_v = float(row[1]) | |
| else: | |
| ts = int(row.get("ts", 0)) | |
| buy_v = float(row.get("buyVol", row.get("buyVolume", 0.0))) | |
| raw_sell = row.get("sellVol", row.get("sellVolume")) | |
| sell_v = float(raw_sell) if raw_sell is not None else None | |
| taker_map[ts] = (buy_v, sell_v) | |
| except (IndexError, ValueError, TypeError): | |
| continue | |
| candles = [] | |
| interval_ms = {"15m": 900_000, "1h": 3_600_000}.get(timeframe, 900_000) | |
| for k in reversed(data): | |
| # OKX returns: [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm] | |
| # Use k[6] (volCcy) so candle volume is in normalized base coins matching Binance & Bybit | |
| vol = float(k[6]) if len(k) > 6 and k[6] else float(k[5]) | |
| c_ts = int(k[0]) | |
| c_dict = { | |
| "timestamp": c_ts, | |
| "open": float(k[1]), | |
| "high": float(k[2]), | |
| "low": float(k[3]), | |
| "close": float(k[4]), | |
| "volume": vol, | |
| } | |
| matched_tb = BaseExchange._match_taker_buy_volume(taker_map, c_ts, interval_ms, vol) | |
| if matched_tb is not None: | |
| c_dict["taker_buy_volume"] = matched_tb | |
| candles.append(c_dict) | |
| return candles | |
| async def _get_contract_spec(self, inst_id: str) -> tuple[float, bool]: | |
| """Fetch and cache (ctVal * ctMult, is_inverse) without caching transient fallback 1.0.""" | |
| if inst_id in self._contract_spec_cache: | |
| return self._contract_spec_cache[inst_id] | |
| try: | |
| data = await self._get("/api/v5/public/instruments", {"instType": "SWAP", "instId": inst_id}) | |
| if data and len(data) > 0: | |
| row = data[0] | |
| ct_val = self._to_float(row.get("ctVal"), 0.0) | |
| ct_mult = self._to_float(row.get("ctMult"), 1.0) | |
| if ct_mult <= 0: | |
| ct_mult = 1.0 | |
| if ct_val > 0: | |
| ct_type = str(row.get("ctType", "")).lower() | |
| is_inverse = ct_type == "inverse" or (not ct_type and inst_id.upper().endswith("-USD-SWAP")) | |
| spec = (ct_val * ct_mult, is_inverse) | |
| self._contract_spec_cache[inst_id] = spec | |
| try: | |
| from engine.ws_trade_stream import trade_stream_buffer | |
| trade_stream_buffer.set_okx_contract_spec(inst_id, spec[0], spec[1]) | |
| except Exception: | |
| pass | |
| return spec | |
| except Exception: | |
| pass | |
| is_inverse_guess = inst_id.upper().endswith("-USD-SWAP") | |
| return (1.0, is_inverse_guess) | |
| async def _get_ct_val(self, inst_id: str) -> float: | |
| """Backward-compatible wrapper returning contract multiplier (ctVal * ctMult).""" | |
| factor, _ = await self._get_contract_spec(inst_id) | |
| return factor | |
| async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]: | |
| inst_id = self._to_inst_id(symbol) | |
| data = await self._get("/api/v5/market/trades", {"instId": inst_id, "limit": min(limit, 100)}) | |
| ct_factor, is_inverse = await self._get_contract_spec(inst_id) | |
| trades = [] | |
| for t in data: | |
| px = self._to_float(t.get("px"), 0.0) | |
| sz = self._to_float(t.get("sz"), 0.0) | |
| if px <= 0 or sz <= 0: | |
| continue | |
| qty = (sz * ct_factor / px) if is_inverse else (sz * ct_factor) | |
| side = str(t.get("side", "buy")).lower() | |
| # taker sell means buyer is maker | |
| is_buyer_maker = (side == "sell") | |
| trades.append( | |
| { | |
| "price": px, | |
| "qty": qty, | |
| "is_buyer_maker": is_buyer_maker, | |
| "time": int(t["ts"]), | |
| } | |
| ) | |
| trades.sort(key=lambda x: x["time"]) | |
| return trades | |
| async def get_liquidations(self, symbol: str, limit: int = 100) -> list[dict]: | |
| """ | |
| Fetch recent liquidation orders from OKX (/api/v5/public/liquidation-orders). | |
| Returns list of normalized liquidation dicts: | |
| {"price": float, "qty": float, "is_long_liq": bool, "time": int, "venue": "okx"} | |
| """ | |
| inst_id = self._to_inst_id(symbol) | |
| parts = inst_id.split("-") | |
| inst_family = f"{parts[0]}-{parts[1]}" if len(parts) >= 2 else inst_id | |
| try: | |
| # OKX /api/v5/public/liquidation-orders requires uly or instFamily (instId-only returns code 50015) | |
| params = {"instType": "SWAP", "instFamily": inst_family, "state": "filled", "limit": str(min(limit, 100))} | |
| data = await self._get("/api/v5/public/liquidation-orders", params) | |
| if not data or not isinstance(data, list): | |
| return [] | |
| ct_factor, is_inverse = await self._get_contract_spec(inst_id) | |
| liquidations: list[dict] = [] | |
| for item in data: | |
| item_inst = str(item.get("instId") or "").upper() | |
| if item_inst and item_inst != inst_id.upper(): | |
| continue | |
| details = item.get("details") | |
| detail_list = details if (isinstance(details, list) and details) else [item] | |
| for d in detail_list: | |
| d_inst = str(d.get("instId") or "").upper() | |
| if d_inst and d_inst != inst_id.upper(): | |
| continue | |
| bk_px = self._to_float(d.get("bkPx") or d.get("price") or item.get("bkPx"), 0.0) | |
| sz = self._to_float(d.get("sz") or item.get("sz"), 0.0) | |
| ts = self._to_int(d.get("ts") or item.get("ts"), 0) or 0 | |
| pos_side = str(d.get("posSide", "")).lower() | |
| side = str(d.get("side", "")).lower() | |
| is_long_liq = (pos_side == "long") or (side == "sell") | |
| if bk_px > 0 and sz > 0: | |
| qty = (sz * ct_factor / bk_px) if is_inverse else (sz * ct_factor) | |
| liquidations.append({ | |
| "price": bk_px, | |
| "qty": qty, | |
| "is_long_liq": is_long_liq, | |
| "time": ts, | |
| "venue": "okx", | |
| }) | |
| liquidations.sort(key=lambda x: x["time"]) | |
| return liquidations | |
| except Exception as exc: | |
| logger.debug("[OKX] Liquidation fetch failed for %s: %s", symbol, exc) | |
| return [] | |
| async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: | |
| inst_id = self._to_inst_id(symbol) | |
| sz = max(1, min(int(depth), 400)) | |
| data = await self._get("/api/v5/market/books", {"instId": inst_id, "sz": sz}) | |
| if not data: | |
| return {"bids": [], "asks": []} | |
| b = data[0] | |
| ct_factor, is_inverse = await self._get_contract_spec(inst_id) | |
| bids = [] | |
| for entry in b.get("bids", [])[:depth]: | |
| p = self._to_float(entry[0], 0.0) | |
| q = self._to_float(entry[1], 0.0) | |
| if p > 0 and q > 0: | |
| bids.append([p, (q * ct_factor / p) if is_inverse else (q * ct_factor)]) | |
| asks = [] | |
| for entry in b.get("asks", [])[:depth]: | |
| p = self._to_float(entry[0], 0.0) | |
| q = self._to_float(entry[1], 0.0) | |
| if p > 0 and q > 0: | |
| asks.append([p, (q * ct_factor / p) if is_inverse else (q * ct_factor)]) | |
| return {"bids": bids, "asks": asks} | |
| async def close(self) -> None: | |
| await self._client.aclose() | |