Perps-Terminal / backend /engine /bulk_fetcher.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
17.5 kB
"""
Bulk Market Pre-Fetcher (Tier 1 Architecture)
==============================================
Provides high-performance, single-call pre-fetching of market-wide data
across Binance USDⓈ-M and Bybit Linear Perpetuals.
Benefits:
- Slashes individual REST API calls by 70–80% across all monitored pairs.
- Eliminates per-symbol rate-limit bottlenecks on /premiumIndex and /tickers.
- Supplies instantaneous in-memory mark price, index price, funding rates,
and 24h price extremes.
- Thread/coroutine safe with async locking and automatic TTL cache (15s).
"""
import asyncio
import logging
import time
from typing import Any
import httpx
from config import BINANCE_FUTURES_BASE_URL, BYBIT_BASE_URL, PROXY_URL
from engine.doh_resolver import enable_doh_bypass
from engine.symbol_resolver import get_symbol_variations
enable_doh_bypass()
logger = logging.getLogger(__name__)
class BulkMarketFetcher:
"""Singleton pre-fetcher for bulk exchange market snapshots."""
_instance: "BulkMarketFetcher | None" = None
def __new__(cls) -> "BulkMarketFetcher":
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._init_client()
return cls._instance
def _init_client(self) -> None:
client_kwargs = {
"timeout": httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=10.0),
"limits": httpx.Limits(max_connections=80, max_keepalive_connections=30, 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)
try:
self._client_loop = asyncio.get_running_loop()
except RuntimeError:
self._client_loop = None
self._binance_premium: dict[str, dict[str, Any]] = {}
self._binance_24h: dict[str, dict[str, Any]] = {}
self._binance_funding_intervals: dict[str, float] = {}
self._bybit_tickers: dict[str, dict[str, Any]] = {}
self._binance_premium_ts: float | None = None
self._binance_24h_ts: float | None = None
self._binance_funding_info_ts: float = 0.0
self._bybit_tickers_ts: float | None = None
self._binance_premium_ref: dict[str, dict[str, Any]] | None = None
self._binance_24h_ref: dict[str, dict[str, Any]] | None = None
self._bybit_tickers_ref: dict[str, dict[str, Any]] | None = None
self._last_refresh_time: float = 0.0
self._ttl_seconds: float = 15.0
self._locks_by_loop: dict[int, asyncio.Lock] = {}
def _get_lock(self) -> asyncio.Lock:
try:
loop = asyncio.get_running_loop()
loop_id = id(loop)
except RuntimeError:
loop_id = 0
lock = self._locks_by_loop.get(loop_id)
if lock is None:
lock = asyncio.Lock()
self._locks_by_loop[loop_id] = lock
return lock
def _ensure_client(self) -> None:
try:
current_loop = asyncio.get_running_loop()
except RuntimeError:
current_loop = None
if self._client_loop is None and current_loop is not None:
self._client_loop = current_loop
loop_changed = (
self._client_loop is not None
and (self._client_loop.is_closed() or (current_loop is not None and self._client_loop is not current_loop))
)
if self._client is None or self._client.is_closed or loop_changed:
client_kwargs = {
"timeout": httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=10.0),
"limits": httpx.Limits(max_connections=80, max_keepalive_connections=30, 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._client_loop = current_loop
def _is_feed_expired(
self,
feed_ts: float | None,
feed_dict: dict[str, Any] | None = None,
ref_dict: dict[str, Any] | None = None,
) -> bool:
if ref_dict is not None and feed_dict is not ref_dict:
return False
return feed_ts is not None and (time.time() - feed_ts) > self._ttl_seconds
async def refresh_if_stale(self, force: bool = False) -> None:
"""Refresh bulk data if cache TTL expired or force is True."""
self._ensure_client()
now = time.time()
if not force and (now - self._last_refresh_time < self._ttl_seconds):
return
async with self._get_lock():
self._ensure_client()
now = time.time()
if not force and (now - self._last_refresh_time < self._ttl_seconds):
return
tasks = [
self._fetch_binance_premium(),
self._fetch_binance_24h(),
self._fetch_bybit_linear_tickers(),
]
if (now - getattr(self, "_binance_funding_info_ts", 0.0)) >= 3600.0:
tasks.append(self._fetch_binance_funding_info())
results = await asyncio.gather(*tasks, return_exceptions=True)
any_succeeded = False
for idx, res in enumerate(results):
if isinstance(res, Exception):
logger.debug("Bulk fetch task %d failed: %s", idx, res)
elif res is True:
any_succeeded = True
if any_succeeded:
self._last_refresh_time = time.time()
async def _fetch_binance_premium(self) -> bool:
"""Binance /fapi/v1/premiumIndex without symbol returns all USD-M perpetuals (weight=1)."""
try:
url = f"{BINANCE_FUTURES_BASE_URL}/fapi/v1/premiumIndex"
r = await self._client.get(url, timeout=5.0)
if r.status_code == 200:
data = r.json()
new_map = {}
for item in data:
sym = item.get("symbol")
if sym:
new_map[sym.upper()] = item
if new_map:
self._binance_premium = new_map
self._binance_premium_ref = new_map
self._binance_premium_ts = time.time()
return True
except Exception as exc:
logger.debug("[BulkFetcher] Binance premiumIndex error: %s", exc)
return False
async def _fetch_binance_funding_info(self) -> bool:
"""Binance /fapi/v1/fundingInfo returns settlement intervals (1h, 2h, 4h, 8h)."""
try:
url = f"{BINANCE_FUTURES_BASE_URL}/fapi/v1/fundingInfo"
r = await self._client.get(url, timeout=4.0)
if r.status_code == 200:
items = r.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._binance_funding_intervals = intervals
self._binance_funding_info_ts = time.time()
return True
except Exception as exc:
logger.debug("[BulkFetcher] Binance fundingInfo error: %s", exc)
return False
async def _fetch_binance_24h(self) -> bool:
"""Binance /fapi/v1/ticker/24hr without symbol returns 24h ticker for all pairs (weight=40)."""
try:
url = f"{BINANCE_FUTURES_BASE_URL}/fapi/v1/ticker/24hr"
r = await self._client.get(url, timeout=6.0)
if r.status_code == 200:
data = r.json()
new_map = {}
for item in data:
sym = item.get("symbol")
if sym:
new_map[sym.upper()] = item
if new_map:
self._binance_24h = new_map
self._binance_24h_ref = new_map
self._binance_24h_ts = time.time()
return True
except Exception as exc:
logger.debug("[BulkFetcher] Binance ticker/24hr error: %s", exc)
return False
async def _fetch_bybit_linear_tickers(self) -> bool:
"""Bybit /v5/market/tickers?category=linear returns all linear perp tickers in 1 call."""
try:
url = f"{BYBIT_BASE_URL}/v5/market/tickers"
r = await self._client.get(url, params={"category": "linear"}, timeout=6.0)
if r.status_code == 200:
data = r.json()
items = data.get("result", {}).get("list", [])
new_map = {}
for item in items:
sym = item.get("symbol")
if sym:
new_map[sym.upper()] = item
if new_map:
self._bybit_tickers = new_map
self._bybit_tickers_ref = new_map
self._bybit_tickers_ts = time.time()
return True
except Exception as exc:
logger.debug("[BulkFetcher] Bybit linear tickers error: %s", exc)
return False
def _resolve_key(self, symbol: str, cache_dict: dict[str, Any]) -> str | None:
"""Resolve exact or candidate variation key in dictionary."""
sym = symbol.upper().strip()
if sym in cache_dict:
return sym
for var in get_symbol_variations(symbol):
v_up = var.upper()
if v_up in cache_dict:
return v_up
return None
# ─────────────────────────────────────────────────────────────────────────
# Public In-Memory Accessors
# ─────────────────────────────────────────────────────────────────────────
def get_binance_mark_price(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_binance_premium_ts", None),
self._binance_premium,
getattr(self, "_binance_premium_ref", None),
):
return None
k = self._resolve_key(symbol, self._binance_premium)
if not k:
return None
item = self._binance_premium[k]
try:
mark = float(item["markPrice"])
if mark <= 0:
return None
index = float(item["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),
}
except (KeyError, ValueError, TypeError):
return None
def get_binance_funding_rate(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_binance_premium_ts", None),
self._binance_premium,
getattr(self, "_binance_premium_ref", None),
):
return None
k = self._resolve_key(symbol, self._binance_premium)
if not k:
return None
item = self._binance_premium[k]
try:
fr_val = float(item["lastFundingRate"])
intervals = getattr(self, "_binance_funding_intervals", {})
normalized_8h = False
if intervals:
interval_h = float(intervals.get(k, 8.0))
if 0 < interval_h <= 24 and interval_h != 8.0:
fr_val = fr_val * (8.0 / interval_h)
normalized_8h = True
return {
"funding_rate": fr_val,
"next_funding_time": item.get("nextFundingTime"),
"normalized_8h": normalized_8h,
}
except (KeyError, ValueError, TypeError):
return None
def get_binance_24h(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_binance_24h_ts", None),
self._binance_24h,
getattr(self, "_binance_24h_ref", None),
):
return None
k = self._resolve_key(symbol, self._binance_24h)
if not k:
return None
item = self._binance_24h[k]
try:
return {
"high_24h": float(item["highPrice"]),
"low_24h": float(item["lowPrice"]),
"volume_24h": float(item["volume"]),
"quote_volume_24h": float(item["quoteVolume"]),
"price_change_pct": float(item.get("priceChangePercent", 0.0)),
}
except (KeyError, ValueError, TypeError):
return None
def get_bybit_mark_price(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_bybit_tickers_ts", None),
self._bybit_tickers,
getattr(self, "_bybit_tickers_ref", None),
):
return None
k = self._resolve_key(symbol, self._bybit_tickers)
if not k:
return None
item = self._bybit_tickers[k]
try:
mark = float(item.get("markPrice", 0))
if mark <= 0:
return None
index = float(item.get("indexPrice", 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),
}
except (KeyError, ValueError, TypeError):
return None
def get_bybit_funding_rate(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_bybit_tickers_ts", None),
self._bybit_tickers,
getattr(self, "_bybit_tickers_ref", None),
):
return None
k = self._resolve_key(symbol, self._bybit_tickers)
if not k:
return None
item = self._bybit_tickers[k]
try:
fr_raw = item.get("fundingRate")
if fr_raw is None or fr_raw == "":
return None
fr_val = float(fr_raw)
interval_raw = item.get("fundingIntervalHour")
if interval_raw not in (None, ""):
interval_h = float(interval_raw)
if 0 < interval_h < 24 and interval_h != 8.0:
fr_val = fr_val * (8.0 / interval_h)
nft = item.get("nextFundingTime")
if nft and isinstance(nft, str) and nft.isdigit():
nft = int(nft)
return {
"funding_rate": fr_val,
"next_funding_time": nft,
}
except (KeyError, ValueError, TypeError):
return None
def get_bybit_24h_and_oi(self, symbol: str) -> dict[str, Any] | None:
if self._is_feed_expired(
getattr(self, "_bybit_tickers_ts", None),
self._bybit_tickers,
getattr(self, "_bybit_tickers_ref", None),
):
return None
k = self._resolve_key(symbol, self._bybit_tickers)
if not k:
return None
item = self._bybit_tickers[k]
try:
raw_oi = item.get("singleOpenInterest")
if raw_oi in (None, ""):
raw_oi = item.get("openInterest")
raw_oi_val = item.get("singleOpenInterestValue")
if raw_oi_val in (None, ""):
raw_oi_val = item.get("openInterestValue")
return {
"high_24h": float(item.get("highPrice24h", 0)) if item.get("highPrice24h") else None,
"low_24h": float(item.get("lowPrice24h", 0)) if item.get("lowPrice24h") else None,
"turnover_24h": float(item.get("turnover24h", 0)) if item.get("turnover24h") else None,
"open_interest": float(raw_oi) if raw_oi not in (None, "") else 0.0,
"open_interest_value": float(raw_oi_val) if raw_oi_val not in (None, "") else None,
}
except (KeyError, ValueError, TypeError):
return None
async def close(self) -> None:
if self._client and not self._client.is_closed:
await self._client.aclose()
# Global shared instance
bulk_fetcher = BulkMarketFetcher()