Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download backend/exchanges/binance.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 22.7 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/exchanges/binance.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/exchanges/binance.py
-
curl -L -o binance.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/exchanges/binance.py
22.7 kB
| """ | |
| Binance Futures (USDⓈ-M) REST client using raw httpx (async). | |
| Docs: https://fapi.binance.com | |
| All calls use the PUBLIC endpoints (no signature required for read-only data). | |
| """ | |
| import asyncio | |
| import logging | |
| import time | |
| from typing import Any | |
| import httpx | |
| from config import BINANCE_FUTURES_BASE_URL, PROXY_URL | |
| from exchanges.base import BaseExchange | |
| from engine.doh_resolver import enable_doh_bypass | |
| from engine.symbol_resolver import get_symbol_variations | |
| from engine.bulk_fetcher import bulk_fetcher | |
| enable_doh_bypass() | |
| logger = logging.getLogger(__name__) | |
| _BINANCE_ORDERBOOK_LIMITS = (5, 10, 20, 50, 100, 500, 1000) | |
| # Timeframe mapping: our standard → Binance kline interval | |
| TF_MAP = { | |
| "1m": "1m", | |
| "3m": "3m", | |
| "5m": "5m", | |
| "15m": "15m", | |
| "30m": "30m", | |
| "1h": "1h", | |
| "2h": "2h", | |
| "4h": "4h", | |
| "1d": "1d", | |
| } | |
| class BinanceClient(BaseExchange): | |
| name = "binance" | |
| def __init__(self) -> None: | |
| client_kwargs = { | |
| "base_url": BINANCE_FUTURES_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", | |
| "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/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._last_symbols_load_time: float = 0.0 | |
| self._negative_cache: dict[str, float] = {} | |
| self._funding_intervals: dict[str, float] = {} | |
| self._last_funding_info_time: float = 0.0 | |
| # ------------------------------------------------------------------ | |
| # 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() | |
| return resp.json() | |
| except Exception as e: | |
| if "internetbaik" in str(e).lower() or "blocked" in str(e).lower(): | |
| logger.warning( | |
| "[Binance] Akses diblokir ISP/Internet Baik. Gunakan VPN/WARP atau set PROXY_URL di .env" | |
| ) | |
| raise | |
| async def _load_symbols(self, force: bool = False) -> None: | |
| 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): | |
| # Backoff 5 minutes if previous load failed (e.g. 451 geoblocked on Vercel) | |
| return | |
| self._last_symbols_load_time = now | |
| try: | |
| resp = await self._client.get("/fapi/v1/exchangeInfo", timeout=5.0) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| new_set = set() | |
| for s in data.get("symbols", []): | |
| if s.get("contractType") == "PERPETUAL": | |
| new_set.add(s["symbol"]) | |
| if new_set: | |
| self._known_symbols = new_set | |
| self._universe_loaded = True | |
| except Exception as exc: | |
| if "451" in str(exc): | |
| logger.warning("[Binance] Datacenter/Cloud IP diblokir Binance (HTTP 451). Sistem otomatis fallback ke OKX & Hyperliquid.") | |
| else: | |
| logger.warning("[Binance] Failed to load exchangeInfo: %s", exc) | |
| async def _get_funding_interval_hours(self, sym: str) -> float: | |
| """Return settlement interval in hours (1, 2, 4, or default 8) from /fapi/v1/fundingInfo.""" | |
| now = time.time() | |
| if "_get" not in self.__dict__ and (now - self._last_funding_info_time >= 3600): | |
| self._last_funding_info_time = now | |
| try: | |
| resp = await self._client.get("/fapi/v1/fundingInfo", timeout=3.0) | |
| if resp.status_code == 200: | |
| items = resp.json() | |
| if isinstance(items, list): | |
| intervals: dict[str, float] = {} | |
| for it in items: | |
| if isinstance(it, dict) and it.get("symbol") and it.get("fundingIntervalHours"): | |
| try: | |
| h = float(it["fundingIntervalHours"]) | |
| if 0 < h <= 24: | |
| intervals[str(it["symbol"]).upper()] = h | |
| except (TypeError, ValueError): | |
| continue | |
| if intervals: | |
| self._funding_intervals = intervals | |
| except Exception: | |
| pass | |
| return float(self._funding_intervals.get(sym.upper(), 8.0)) | |
| def resolve_symbol(self, symbol: str) -> str | None: | |
| """Resolve symbol or multiplier variations to Binance'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 (e.g. cold start / 451) | |
| 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 | |
| now = time.time() | |
| if sym in self._negative_cache and (now - self._negative_cache[sym] < 900): | |
| return False | |
| # 2. If full universe not yet 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 (kept separate from _known_symbols so full load isn't poisoned) | |
| for var in get_symbol_variations(symbol): | |
| if not (var.endswith("USDT") or var.endswith("USDC")): | |
| continue | |
| try: | |
| resp = await self._client.get("/fapi/v1/premiumIndex", params={"symbol": var}, timeout=4.0) | |
| if resp.status_code == 200: | |
| 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_binance_mark_price(symbol) | |
| if bulk_data: | |
| return bulk_data | |
| sym = self.resolve_symbol(symbol) or symbol | |
| data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym}) | |
| mark = float(data["markPrice"]) | |
| index = float(data["indexPrice"]) | |
| 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("-", "") | |
| interval_h = await self._get_funding_interval_hours(sym) | |
| bulk_data = bulk_fetcher.get_binance_funding_rate(symbol) | |
| if bulk_data: | |
| fr_val = float(bulk_data["funding_rate"]) | |
| if not bulk_data.get("normalized_8h") and interval_h != 8.0 and interval_h > 0: | |
| fr_val = fr_val * (8.0 / interval_h) | |
| return { | |
| "funding_rate": fr_val, | |
| "next_funding_time": bulk_data.get("next_funding_time"), | |
| } | |
| data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym}) | |
| fr_val = float(data.get("lastFundingRate") or 0.0) | |
| if interval_h != 8.0 and interval_h > 0: | |
| fr_val = fr_val * (8.0 / interval_h) | |
| return { | |
| "funding_rate": fr_val, | |
| "next_funding_time": data.get("nextFundingTime"), | |
| } | |
| async def get_open_interest(self, symbol: str) -> dict[str, Any]: | |
| """Fetch current and multi-horizon (15m, 1h, 4h) historical Open Interest to compute change %.""" | |
| 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, | |
| } | |
| try: | |
| hist = await self._get( | |
| "/futures/data/openInterestHist", | |
| {"symbol": sym, "period": "15m", "limit": 17}, | |
| ) | |
| if isinstance(hist, list) and len(hist) >= 2: | |
| # Binance returns oldest to newest: hist[-1] is curr, hist[-2] is prev 15m | |
| series = [float(item.get("sumOpenInterest", 0) or 0) for item in hist] | |
| curr_item = hist[-1] | |
| 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": float(curr_item.get("sumOpenInterestValue", 0)) if curr_item.get("sumOpenInterestValue") else None, | |
| } | |
| elif isinstance(hist, list) and len(hist) == 1: | |
| curr_oi = float(hist[0].get("sumOpenInterest") or 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": float(hist[0].get("sumOpenInterestValue") or 0) if hist[0].get("sumOpenInterestValue") else None, | |
| } | |
| except Exception as exc: | |
| logger.debug("[Binance] OI history fetch note for %s (%s), falling back to ticker OI", sym, exc) | |
| # Fallback to standard open interest endpoint | |
| data = await self._get("/fapi/v1/openInterest", {"symbol": sym}) | |
| return { | |
| "open_interest": float(data.get("openInterest") or 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]: | |
| """Fetch Whale Top-Trader Position/Account L/S ratios alongside Global Retail L/S ratio.""" | |
| sym = self.resolve_symbol(symbol) | |
| if not sym: | |
| return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} | |
| async def _fetch_ls(endpoint: str) -> tuple[float, float] | None: | |
| try: | |
| data = await self._get(endpoint, {"symbol": sym, "period": period, "limit": 1}) | |
| if isinstance(data, list) and data and "longAccount" in data[0]: | |
| return float(data[0]["longAccount"]), float(data[0]["shortAccount"]) | |
| except Exception: | |
| pass | |
| return None | |
| top_acc, global_acc, top_pos = await asyncio.gather( | |
| _fetch_ls("/futures/data/topLongShortAccountRatio"), | |
| _fetch_ls("/futures/data/globalLongShortAccountRatio"), | |
| _fetch_ls("/futures/data/topLongShortPositionRatio"), | |
| ) | |
| top_acc_long = top_acc[0] if top_acc else None | |
| global_acc_long = global_acc[0] if global_acc else None | |
| top_pos_long = top_pos[0] if top_pos else None | |
| # Align long_ratio semantics with OKX/Bitget: prefer whale top_pos/top_acc, | |
| # falling back to retail global_acc only when whale feeds are absent. | |
| if top_pos_long is not None: | |
| primary_long = top_pos_long | |
| primary_short = top_pos[1] if top_pos is not None else round(1.0 - primary_long, 4) | |
| source = "smart_money" if global_acc_long is not None else "top_trader" | |
| elif top_acc_long is not None: | |
| primary_long = top_acc_long | |
| primary_short = top_acc[1] if top_acc is not None else round(1.0 - primary_long, 4) | |
| source = "top_trader" | |
| elif global_acc_long is not None: | |
| primary_long = global_acc_long | |
| primary_short = global_acc[1] if global_acc is not None else round(1.0 - primary_long, 4) | |
| source = "global" | |
| else: | |
| return {"long_ratio": None, "short_ratio": None, "source": "unavailable"} | |
| whale_delta = ( | |
| round(top_pos_long - global_acc_long, 4) | |
| if (top_pos_long is not None and global_acc_long is not None) | |
| else 0.0 | |
| ) | |
| return { | |
| "long_ratio": primary_long, | |
| "short_ratio": primary_short, | |
| "top_position_long_ratio": top_pos_long, | |
| "top_account_long_ratio": top_acc_long, | |
| "retail_long_ratio": global_acc_long, | |
| "whale_retail_delta": whale_delta, | |
| "source": source, | |
| } | |
| 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) | |
| data = await self._get( | |
| "/fapi/v1/klines", | |
| {"symbol": sym, "interval": interval, "limit": limit}, | |
| ) | |
| candles = [] | |
| for k in data: | |
| c_dict: dict[str, Any] = { | |
| "timestamp": k[0], | |
| "open": float(k[1]), | |
| "high": float(k[2]), | |
| "low": float(k[3]), | |
| "close": float(k[4]), | |
| "volume": float(k[5]), | |
| } | |
| if len(k) > 8 and k[8] is not None: | |
| c_dict["trade_count"] = int(k[8]) | |
| if len(k) > 9 and k[9] is not None: | |
| c_dict["taker_buy_volume"] = float(k[9]) | |
| if len(k) > 7 and k[7] is not None: | |
| c_dict["quote_volume"] = float(k[7]) | |
| if len(k) > 10 and k[10] is not None: | |
| c_dict["taker_buy_quote_volume"] = float(k[10]) | |
| candles.append(c_dict) | |
| 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) | |
| data = await self._get("/fapi/v1/aggTrades", {"symbol": sym, "limit": limit}) | |
| trades = [] | |
| for t in data: | |
| px = t.get("p") if "p" in t else t.get("price") | |
| qty = t.get("q") if "q" in t else t.get("qty") | |
| ts = t.get("T") if "T" in t else t.get("time") | |
| is_maker = t.get("m") if "m" in t else t.get("isBuyerMaker", False) | |
| tid = t.get("a") if "a" in t else t.get("id") | |
| if px is None or qty is None or ts is None: | |
| continue | |
| entry: dict[str, Any] = { | |
| "price": float(px), | |
| "qty": float(qty), | |
| "is_buyer_maker": bool(is_maker), | |
| "time": int(ts), | |
| "venue": "binance", | |
| } | |
| if tid is not None: | |
| entry["trade_id"] = str(tid) | |
| trades.append(entry) | |
| 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 Binance Spot API for Spot CVD vs Futures CVD analysis.""" | |
| from engine.symbol_resolver import strip_multiplier_prefix | |
| raw_sym = symbol.upper().strip().replace("/", "").replace("-", "") | |
| clean_symbol = strip_multiplier_prefix(symbol) | |
| symbols_to_try = [raw_sym] | |
| if clean_symbol and clean_symbol != raw_sym and clean_symbol.endswith(("USDT", "USDC", "USD", "BUSD", "EUR")): | |
| symbols_to_try.append(clean_symbol) | |
| data = [] | |
| for sym in symbols_to_try: | |
| try: | |
| resp = await self._client.get( | |
| "https://api.binance.com/api/v3/trades", | |
| params={"symbol": sym, "limit": min(limit, 1000)}, | |
| ) | |
| if resp.status_code == 200: | |
| data = resp.json() | |
| break | |
| except Exception: | |
| pass | |
| if not data: | |
| return [] | |
| try: | |
| trades = [ | |
| { | |
| "price": float(t["price"]), | |
| "qty": float(t["qty"]), | |
| "is_buyer_maker": bool(t.get("isBuyerMaker", False)), | |
| "time": int(t["time"]), | |
| "venue": "binance_spot", | |
| } | |
| for t in data | |
| ] | |
| trades.sort(key=lambda t: t["time"]) | |
| return trades | |
| except Exception as exc: | |
| logger.warning("[Binance] Spot trades parse failed for %s: %s", symbol, exc) | |
| return [] | |
| async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]: | |
| sym = self.resolve_symbol(symbol) or symbol | |
| api_limit = next((d for d in _BINANCE_ORDERBOOK_LIMITS if d >= max(1, int(depth))), 1000) | |
| data = await self._get("/fapi/v1/depth", {"symbol": sym, "limit": api_limit}) | |
| return { | |
| "bids": [[float(p), float(q)] for p, q in data["bids"][:depth]], | |
| "asks": [[float(p), float(q)] for p, q in data["asks"][:depth]], | |
| } | |
| async def get_oi_history(self, symbol: str, timeframe: str = "15m", limit: int = 150) -> list[dict]: | |
| """Fetch historical Open Interest from Binance (/futures/data/openInterestHist).""" | |
| sym = self.resolve_symbol(symbol) or symbol | |
| period_map = { | |
| "1m": "5m", | |
| "3m": "5m", | |
| "5m": "5m", | |
| "15m": "15m", | |
| "30m": "30m", | |
| "1h": "1h", | |
| "2h": "2h", | |
| "4h": "4h", | |
| "1d": "1d", | |
| } | |
| period = period_map.get(timeframe, "15m") | |
| try: | |
| data = await self._get( | |
| "/futures/data/openInterestHist", | |
| {"symbol": sym, "period": period, "limit": min(limit, 500)}, | |
| ) | |
| if not isinstance(data, list): | |
| return [] | |
| results = [] | |
| for item in data: | |
| ts = int(item.get("timestamp", 0)) | |
| oi = float(item.get("sumOpenInterest", 0.0) or 0.0) | |
| oi_val = float(item.get("sumOpenInterestValue", 0.0) or 0.0) | |
| results.append({ | |
| "timestamp": ts, | |
| "open_interest": oi, | |
| "open_interest_usd": oi_val, | |
| }) | |
| results.sort(key=lambda x: x["timestamp"]) | |
| return results | |
| except Exception as exc: | |
| logger.debug("[Binance] 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 Binance (/fapi/v1/fundingRate), normalized to 8h equivalent.""" | |
| sym = self.resolve_symbol(symbol) or symbol | |
| try: | |
| data = await self._get( | |
| "/fapi/v1/fundingRate", | |
| {"symbol": sym, "limit": min(limit, 100)}, | |
| ) | |
| if not isinstance(data, list): | |
| return [] | |
| raw_items = sorted(data, key=lambda x: int(x.get("fundingTime", 0))) | |
| interval_h = await self._get_funding_interval_hours(sym) | |
| if interval_h == 8.0 and len(raw_items) >= 2: | |
| deltas = [ | |
| (int(raw_items[i].get("fundingTime", 0)) - int(raw_items[i - 1].get("fundingTime", 0))) / 3_600_000.0 | |
| for i in range(1, len(raw_items)) | |
| ] | |
| 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 raw_items: | |
| results.append({ | |
| "timestamp": int(item.get("fundingTime", 0)), | |
| "funding_rate": float(item.get("fundingRate", 0.0) or 0.0) * scale, | |
| "mark_price": float(item.get("markPrice", 0.0) or 0.0), | |
| }) | |
| return results | |
| except Exception as exc: | |
| logger.debug("[Binance] Failed to fetch funding history for %s: %s", sym, exc) | |
| return [] | |
| async def close(self) -> None: | |
| await self._client.aclose() | |