""" 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()