Spaces:
Sleeping
Sleeping
File size: 23,784 Bytes
b38dd6b 80df99b b38dd6b 80df99b 6600dec 80df99b 6600dec b38dd6b 993c277 b38dd6b 740fcec b38dd6b 993c277 48f60d7 993c277 b38dd6b 80df99b b38dd6b 65ccdcd b38dd6b 054ee3f 65ccdcd 054ee3f b38dd6b 054ee3f 65ccdcd 054ee3f 65ccdcd b38dd6b 65ccdcd b38dd6b 054ee3f 65ccdcd 054ee3f 65ccdcd b38dd6b 65ccdcd b38dd6b 48f60d7 b38dd6b 993c277 b38dd6b 993c277 b38dd6b 993c277 b38dd6b 48f60d7 993c277 b38dd6b 48f60d7 b38dd6b 993c277 b38dd6b 48f60d7 b38dd6b 993c277 b38dd6b 48f60d7 b38dd6b 7d1f9da 48f60d7 7d1f9da 48f60d7 7d1f9da d6219d0 054ee3f d6219d0 65ccdcd 054ee3f d6219d0 65ccdcd 054ee3f d6219d0 054ee3f d6219d0 b38dd6b 80df99b b38dd6b 80df99b b38dd6b 80df99b d6219d0 80df99b b38dd6b 99c5a78 80df99b d6219d0 b38dd6b 99c5a78 b38dd6b 48f60d7 b38dd6b d6219d0 5b56d1b 48f60d7 d6219d0 48f60d7 d6219d0 48f60d7 d6219d0 48f60d7 d6219d0 13f15a5 d6219d0 b38dd6b 48f60d7 b38dd6b d6219d0 b38dd6b 054ee3f d6219d0 054ee3f d6219d0 b38dd6b d6219d0 b38dd6b d6219d0 054ee3f d6219d0 054ee3f d6219d0 054ee3f d6219d0 b38dd6b 80df99b b38dd6b 80df99b b38dd6b 80df99b b38dd6b | 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 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 | """
Bitget USDT-FUTURES API client.
Docs: https://www.bitget.com/api-doc/contract/market/Get-Tickers
"""
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__)
BITGET_BASE_URL = "https://api.bitget.com"
TIMEFRAME_MAP = {
"1m": "1m",
"3m": "3m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "1H",
"2h": "2H",
"4h": "4H",
"1d": "1Dutc",
}
class BitgetClient(BaseExchange):
name = "bitget"
def __init__(self) -> None:
client_kwargs = {
"base_url": BITGET_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._cache_time: float = 0
self._negative_cache: dict[str, float] = {}
self._funding_interval_cache: dict[str, int] = {}
self._mark_price_cache: dict[str, tuple[dict[str, Any], float]] = {}
self._mark_price_inflight: dict[str, asyncio.Task] = {}
self._lock = asyncio.Lock()
def resolve_symbol(self, symbol: str) -> str | None:
"""Resolve incoming ticker to Bitget's exact symbol name."""
sym = symbol.upper().strip()
if sym in self._known_symbols:
return sym
for v in get_symbol_variations(symbol):
if v.upper() in self._known_symbols:
return v.upper()
return None
def _to_bitget_symbol(self, symbol: str) -> str:
resolved = self.resolve_symbol(symbol)
if resolved:
return resolved
return symbol.upper().replace("/", "").replace("-", "").replace("_", "").replace(" ", "").strip()
async def _get_with_status(self, path: str, params: dict | None = None) -> tuple[Any, bool, bool]:
"""Fetch Bitget JSON payload returning (data, is_unlisted, is_transient) without shared mutable state."""
is_unlisted = False
is_transient = False
try:
resp = await self._client.get(path, params=params)
if 400 <= resp.status_code < 500:
is_unlisted = True
resp.raise_for_status()
resp.raise_for_status()
data = resp.json()
code = str(data.get("code", ""))
if code == "00000":
return data.get("data"), False, False
if code in ("40019", "40034", "40017", "40725"):
is_unlisted = True
logger.debug("[Bitget] Non-zero code for %s: %s", path, data.get("msg"))
return None, is_unlisted, False
except Exception as exc:
if isinstance(exc, httpx.HTTPStatusError) and exc.response is not None and 400 <= exc.response.status_code < 500:
is_unlisted = True
else:
is_transient = True
logger.debug("[Bitget] GET %s failed: %s", path, exc)
return None, is_unlisted, is_transient
async def _get(self, path: str, params: dict | None = None) -> Any:
data, _, _ = await self._get_with_status(path, params)
return data
async def _refresh_symbols_universe(self) -> None:
async with self._lock:
now = time.time()
if self._known_symbols and (now - self._cache_time < 3600):
return
try:
data = await self._get("/api/v2/mix/market/contracts", {"productType": "USDT-FUTURES"})
if isinstance(data, list):
known: set[str] = set()
intervals: dict[str, int] = {}
for item in data:
sym = str(item.get("symbol", "")).upper()
if not sym:
continue
status = str(item.get("symbolStatus", "normal")).lower()
if status != "normal":
continue
known.add(sym)
raw_iv = item.get("fundInterval")
if raw_iv is not None and raw_iv != "":
try:
iv = int(float(raw_iv))
if iv > 0:
intervals[sym] = iv
except (ValueError, TypeError):
pass
self._known_symbols = known
self._funding_interval_cache.update(intervals)
self._cache_time = now
except Exception as exc:
logger.warning("[Bitget] Failed to refresh contracts universe: %s", exc)
async def check_symbol_exists(self, symbol: str) -> bool:
if self.resolve_symbol(symbol) is not None:
return True
now = time.time()
sym_key = symbol.upper().strip()
if sym_key in self._negative_cache and (now - self._negative_cache[sym_key] < 900):
return False
await self._refresh_symbols_universe()
if self.resolve_symbol(symbol) is not None:
self._negative_cache.pop(sym_key, None)
return True
self._negative_cache[sym_key] = now
return False
async def _fetch_mark_price_raw(self, sym: str) -> dict[str, Any]:
data = await self._get("/api/v2/mix/market/ticker", {"productType": "USDT-FUTURES", "symbol": sym})
if not data or not isinstance(data, list) or len(data) == 0:
return {"mark_price": None, "index_price": None, "basis_pct": None}
ticker = data[0]
try:
mark_price = float(ticker.get("markPrice") or ticker.get("lastPr", 0.0))
index_price = float(ticker.get("indexPrice") or mark_price)
basis_pct = ((mark_price - index_price) / index_price * 100) if index_price else 0.0
high_24h = float(ticker.get("high24h") or 0.0)
low_24h = float(ticker.get("low24h") or 0.0)
quote_vol_24h = float(ticker.get("usdtVolume") or ticker.get("quoteVolume") or 0.0)
res = {
"mark_price": mark_price,
"index_price": index_price,
"basis_pct": round(basis_pct, 6),
"high_24h": high_24h,
"low_24h": low_24h,
"quote_volume_24h": round(quote_vol_24h, 2),
}
if mark_price > 0:
self._mark_price_cache[sym] = (res, time.time())
return res
except (ValueError, TypeError):
return {
"mark_price": None,
"index_price": None,
"basis_pct": None,
"high_24h": 0.0,
"low_24h": 0.0,
"quote_volume_24h": 0.0,
}
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
sym = self._to_bitget_symbol(symbol)
now = time.time()
# 1. Return from 5s micro-cache if fresh (prevents redundant double-fetch in get_open_interest)
cached = self._mark_price_cache.get(sym)
if cached and (now - cached[1] < 5.0):
return cached[0]
# 2. Deduplicate concurrent in-flight requests for the same symbol
inflight = self._mark_price_inflight.get(sym)
if inflight and not inflight.done():
return await inflight
task = asyncio.create_task(self._fetch_mark_price_raw(sym))
self._mark_price_inflight[sym] = task
try:
return await task
finally:
if self._mark_price_inflight.get(sym) is task:
self._mark_price_inflight.pop(sym, None)
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
sym = self._to_bitget_symbol(symbol)
data = await self._get("/api/v2/mix/market/current-fund-rate", {"productType": "USDT-FUTURES", "symbol": sym})
if not data or not isinstance(data, list) or len(data) == 0:
return {"funding_rate": None, "next_funding_time": None}
fr_info = data[0]
try:
funding_rate = float(fr_info.get("fundingRate", 0.0))
raw_nft = fr_info.get("nextUpdate") or fr_info.get("nextFundingTime")
next_funding_time = int(raw_nft) if raw_nft else None
raw_interval = fr_info.get("fundingRateInterval") or self._funding_interval_cache.get(sym)
interval_h = float(raw_interval) if raw_interval is not None and raw_interval != "" else 8.0
if 1.0 <= interval_h <= 24.0 and abs(interval_h - 8.0) > 0.05:
self._funding_interval_cache[sym] = int(round(interval_h))
funding_rate = round(funding_rate * (8.0 / interval_h), 10)
return {
"funding_rate": funding_rate,
"next_funding_time": next_funding_time,
}
except (ValueError, TypeError):
return {"funding_rate": None, "next_funding_time": None}
async def get_funding_rate_history(self, symbol: str, limit: int = 50) -> list[dict]:
"""Fetch historical funding rates from Bitget (/api/v2/mix/market/history-fund-rate)."""
sym = self._to_bitget_symbol(symbol)
try:
data = await self._get(
"/api/v2/mix/market/history-fund-rate",
{"symbol": sym, "productType": "USDT-FUTURES", "pageSize": str(min(limit, 100))},
)
if not data or not isinstance(data, list):
return []
out = []
for item in data:
try:
ts = int(item.get("fundingTime", 0) or 0)
fr = float(item.get("fundingRate", 0.0) or 0.0)
if ts > 0:
out.append({
"timestamp": ts,
"funding_rate": fr,
})
except (ValueError, TypeError):
continue
out.sort(key=lambda x: x["timestamp"])
interval_h: float | None = self._funding_interval_cache.get(sym)
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("[Bitget] 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 Bitget Spot market for Spot vs Futures CVD divergence analysis."""
from engine.symbol_resolver import strip_multiplier_prefix
clean_sym = strip_multiplier_prefix(symbol)
if not clean_sym or self._is_spot_unlisted(clean_sym):
return []
try:
if "_get" in self.__dict__:
# Preserve monkeypatched self._get in isolated unit tests
data = await self._get(
"/api/v2/spot/market/fills",
{
"symbol": clean_sym,
"limit": str(min(limit, 100)),
},
)
is_unlisted, is_transient = False, False
else:
data, is_unlisted, is_transient = await self._get_with_status(
"/api/v2/spot/market/fills",
{
"symbol": clean_sym,
"limit": str(min(limit, 100)),
},
)
if isinstance(data, list) and len(data) == 0:
self._mark_spot_unlisted(clean_sym)
return []
if not data or not isinstance(data, list):
if is_unlisted and not is_transient:
self._mark_spot_unlisted(clean_sym)
return []
trades = []
for f in data:
try:
trades.append(
{
"price": float(f["price"]),
"qty": float(f["size"]),
"is_buyer_maker": str(f.get("side", "")).strip().lower() == "sell",
"time": int(f.get("ts", 0)),
"venue": "bitget_spot",
}
)
except (KeyError, ValueError, TypeError):
continue
if trades:
self._clear_spot_unlisted(clean_sym)
trades.sort(key=lambda x: x["time"])
return trades
except Exception as exc:
logger.debug("[Bitget] Failed to fetch spot trades for %s: %s", clean_sym, exc)
return []
async def get_open_interest(self, symbol: str) -> dict[str, Any]:
sym = self._to_bitget_symbol(symbol)
data = await self._get("/api/v2/mix/market/open-interest", {"productType": "USDT-FUTURES", "symbol": sym})
if not data or not isinstance(data, dict):
return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
oi_list = data.get("openInterestList", [])
if not oi_list:
return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
try:
size_coins = float(oi_list[0].get("size", 0.0))
mp_data = await self.get_mark_price(symbol)
mp = mp_data.get("mark_price")
oi_usd = round(size_coins * float(mp), 2) if mp is not None and float(mp) > 0 else None
oi_change_pct, oi_window_sec = self._record_oi_change_with_meta(sym, size_coins)
return {
"open_interest": round(size_coins, 4),
"open_interest_value": oi_usd,
"oi_change_pct": oi_change_pct,
"oi_horizon": "rolling",
"oi_window_sec": oi_window_sec,
}
except (ValueError, TypeError):
return {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
@staticmethod
def _extract_ratio_field(item: dict[str, Any], *keys: str) -> float | None:
for key in keys:
raw = item.get(key)
if raw is not None and raw != "":
try:
val = float(raw)
if val == val:
return val
except (ValueError, TypeError):
continue
return None
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
"""Fetch Long/Short position ratio & account ratio from Bitget V2 mix market."""
sym = self._to_bitget_symbol(symbol)
bg_period = {"5m": "5m", "15m": "15m", "30m": "30m", "1h": "1H", "4h": "4H", "1d": "1D"}.get(
(period or "1h").lower(), "1H"
)
tasks = [
self._get("/api/v2/mix/market/position-long-short", {"symbol": sym, "productType": "USDT-FUTURES", "period": bg_period}),
self._get("/api/v2/mix/market/account-long-short", {"symbol": sym, "productType": "USDT-FUTURES", "period": bg_period}),
self._get("/api/v2/mix/market/long-short", {"symbol": sym, "productType": "USDT-FUTURES", "period": bg_period}),
]
results = await asyncio.gather(*tasks, return_exceptions=True)
res_pos, res_acct, res_ls = results[0], results[1], results[2]
top_pos_ratio = None
if not isinstance(res_pos, Exception) and isinstance(res_pos, list) and len(res_pos) > 0:
top_pos_ratio = self._extract_ratio_field(res_pos[-1], "longPositionRatio", "longRatio")
retail_ratio = None
if not isinstance(res_acct, Exception) and isinstance(res_acct, list) and len(res_acct) > 0:
retail_ratio = self._extract_ratio_field(res_acct[-1], "longAccountRatio", "longRatio")
if retail_ratio is None and not isinstance(res_ls, Exception) and isinstance(res_ls, list) and len(res_ls) > 0:
retail_ratio = self._extract_ratio_field(res_ls[-1], "longRatio", "longAccountRatio")
if top_pos_ratio is not None and retail_ratio is not None:
whale_retail_delta = round(top_pos_ratio - retail_ratio, 4)
return {
"long_ratio": round(top_pos_ratio, 4),
"short_ratio": round(1.0 - top_pos_ratio, 4),
"top_position_long_ratio": round(top_pos_ratio, 4),
"retail_long_ratio": round(retail_ratio, 4),
"whale_retail_delta": whale_retail_delta,
"source": "smart_money",
}
if top_pos_ratio is not None:
return {
"long_ratio": round(top_pos_ratio, 4),
"short_ratio": round(1.0 - top_pos_ratio, 4),
"top_position_long_ratio": round(top_pos_ratio, 4),
"retail_long_ratio": None,
"whale_retail_delta": None,
"source": "top_trader",
}
if retail_ratio is not None:
return {
"long_ratio": round(retail_ratio, 4),
"short_ratio": round(1.0 - retail_ratio, 4),
"top_position_long_ratio": None,
"retail_long_ratio": round(retail_ratio, 4),
"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]:
sym = self._to_bitget_symbol(symbol)
granularity = TIMEFRAME_MAP.get(timeframe, "5m")
tasks = [
self._get(
"/api/v2/mix/market/candles",
{
"productType": "USDT-FUTURES",
"symbol": sym,
"granularity": granularity,
"limit": str(min(limit, 100)),
},
),
]
fetch_taker = timeframe in ("15m", "1h")
if fetch_taker:
tasks.append(
self._get(
"/api/v2/mix/market/taker-buy-sell",
{
"symbol": sym,
"productType": "USDT-FUTURES",
"period": TIMEFRAME_MAP.get(timeframe, "15m"),
},
)
)
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, dict):
ts = int(row.get("ts", row.get("timestamp", 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
else:
ts = int(row[0])
buy_v = float(row[1])
sell_v = float(row[2]) if len(row) >= 3 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 c in data:
try:
c_ts = int(c[0])
c_vol = float(c[5])
c_dict = {
"timestamp": c_ts,
"open": float(c[1]),
"high": float(c[2]),
"low": float(c[3]),
"close": float(c[4]),
"volume": c_vol,
}
matched_tb = BaseExchange._match_taker_buy_volume(taker_map, c_ts, interval_ms, c_vol)
if matched_tb is not None:
c_dict["taker_buy_volume"] = matched_tb
candles.append(c_dict)
except (IndexError, ValueError, TypeError):
continue
# Bitget returns newest first; sort ascending
candles.sort(key=lambda x: x["timestamp"])
return candles
async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
sym = self._to_bitget_symbol(symbol)
data = await self._get(
"/api/v2/mix/market/fills",
{
"productType": "USDT-FUTURES",
"symbol": sym,
"limit": str(min(limit, 100)),
},
)
if not data or not isinstance(data, list):
return []
trades = []
for f in data:
try:
trades.append(
{
"price": float(f["price"]),
"qty": float(f["size"]),
"is_buyer_maker": str(f.get("side", "")).strip().lower() == "sell",
"time": int(f.get("ts", 0)),
}
)
except (KeyError, ValueError, TypeError):
continue
trades.sort(key=lambda x: x["time"])
return trades
async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
sym = self._to_bitget_symbol(symbol)
data = await self._get(
"/api/v2/mix/market/merge-depth",
{
"productType": "USDT-FUTURES",
"symbol": sym,
"limit": str(min(depth, 50)),
},
)
if not data or not isinstance(data, dict):
return {"bids": [], "asks": []}
try:
bids = sorted(
([float(b[0]), float(b[1])] for b in data.get("bids", []) if len(b) >= 2),
key=lambda x: x[0],
reverse=True,
)[:depth]
asks = sorted(
([float(a[0]), float(a[1])] for a in data.get("asks", []) if len(a) >= 2),
key=lambda x: x[0],
)[:depth]
return {"bids": bids, "asks": asks}
except (ValueError, TypeError):
return {"bids": [], "asks": []}
async def close(self) -> None:
await self._client.aclose()
|