Spaces:
Sleeping
Sleeping
File size: 22,653 Bytes
712f4ea 48f60d7 712f4ea d87b18a 9ec99c1 712f4ea 48f60d7 712f4ea 80df99b 712f4ea 80df99b 712f4ea 80df99b 712f4ea b445d0e e8a9462 740fcec 712f4ea 05163ad 712f4ea 48f60d7 7e6906e c224e9c 48f60d7 712f4ea 05163ad 712f4ea 7e6906e 48f60d7 712f4ea 48f60d7 e8cea05 7e6906e e8cea05 b20d302 7e6906e d87b18a 7e6906e 48f60d7 7e6906e e8cea05 712f4ea 48f60d7 d87b18a 48f60d7 b445d0e 48f60d7 b445d0e 48f60d7 b445d0e d87b18a 712f4ea 48f60d7 b445d0e 48f60d7 b445d0e b20d302 c224e9c 80df99b c224e9c 48f60d7 c224e9c b445d0e c224e9c 48f60d7 b20d302 48f60d7 b20d302 c224e9c 7e6906e b445d0e c224e9c b20d302 80df99b 7e6906e 712f4ea 9ec99c1 d87b18a 712f4ea 48f60d7 9ec99c1 48f60d7 d87b18a 48f60d7 712f4ea 48f60d7 712f4ea 80df99b b445d0e 80df99b 712f4ea 80df99b 712f4ea 80df99b 712f4ea 80df99b 712f4ea 48f60d7 712f4ea 80df99b 48f60d7 712f4ea b445d0e 712f4ea d87b18a 712f4ea 48f60d7 712f4ea 80df99b 712f4ea 80df99b b445d0e 712f4ea 80df99b 712f4ea 80df99b 48f60d7 80df99b 712f4ea d87b18a 712f4ea d87b18a 712f4ea 80df99b 48f60d7 80df99b 712f4ea d87b18a 712f4ea 48f60d7 80df99b 712f4ea 48f60d7 712f4ea 80df99b cea524b 05163ad cea524b 712f4ea 80df99b 712f4ea 05163ad 712f4ea d87b18a 48f60d7 712f4ea 48f60d7 712f4ea bf49534 48f60d7 bf49534 48f60d7 bf49534 48f60d7 bf49534 48f60d7 bf49534 712f4ea 05163ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | """
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()
|