Spaces:
Sleeping
Sleeping
File size: 21,215 Bytes
712f4ea d87b18a 9ec99c1 712f4ea 80df99b 712f4ea 80df99b 712f4ea 80df99b 712f4ea b445d0e 712f4ea 740fcec 712f4ea 05163ad 712f4ea 48f60d7 7e6906e c224e9c 48f60d7 712f4ea 05163ad 712f4ea 7e6906e 48f60d7 712f4ea 48f60d7 e8cea05 7e6906e 48f60d7 7e6906e 48f60d7 7e6906e 712f4ea 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 d87b18a 712f4ea 80df99b 712f4ea 48f60d7 9ec99c1 d87b18a 712f4ea d87b18a 712f4ea 48f60d7 712f4ea 48f60d7 712f4ea 48f60d7 712f4ea 80df99b b445d0e 80df99b 712f4ea 80df99b 712f4ea 80df99b 48f60d7 80df99b 712f4ea 80df99b 712f4ea 48f60d7 712f4ea 80df99b 712f4ea b445d0e 9ec99c1 80df99b 9ec99c1 80df99b 712f4ea b445d0e 48f60d7 712f4ea 48f60d7 712f4ea 13f15a5 712f4ea 13f15a5 712f4ea 13f15a5 712f4ea b445d0e 712f4ea d87b18a 712f4ea d87b18a 712f4ea d87b18a 712f4ea d87b18a 712f4ea 48f60d7 712f4ea 691e38f 80df99b 691e38f 80df99b 691e38f 80df99b 691e38f 80df99b 691e38f 712f4ea d87b18a 712f4ea d87b18a 712f4ea bf49534 48f60d7 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 | """
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()
|