"""Small signed Bybit V5 client used by the optional live-trading mode. API credentials are held only in memory and are never written to disk or logs. """ from __future__ import annotations import hashlib import hmac import json import time import urllib.error import urllib.parse import urllib.request import uuid from decimal import Decimal, ROUND_DOWN, ROUND_UP class BybitAPIError(RuntimeError): pass class BybitLiveClient: def __init__(self, api_key: str, api_secret: str, testnet: bool = True) -> None: if not api_key.strip() or not api_secret.strip(): raise ValueError("Введите API key и API secret") self.api_key = api_key.strip() self._secret = api_secret.strip().encode("utf-8") self.testnet = testnet self.base_url = "https://api-testnet.bybit.com" if testnet else "https://api.bybit.com" self.recv_window = "5000" def _request(self, method: str, path: str, params: dict | None = None) -> dict: params = params or {} timestamp = str(int(time.time() * 1000)) if method == "GET": query = urllib.parse.urlencode(sorted((key, str(value)) for key, value in params.items())) body = "" payload = None else: query = "" body = json.dumps(params, separators=(",", ":"), ensure_ascii=False) payload = body.encode("utf-8") signature_input = f"{timestamp}{self.api_key}{self.recv_window}{query or body}" signature = hmac.new(self._secret, signature_input.encode("utf-8"), hashlib.sha256).hexdigest() headers = { "X-BAPI-API-KEY": self.api_key, "X-BAPI-SIGN": signature, "X-BAPI-TIMESTAMP": timestamp, "X-BAPI-RECV-WINDOW": self.recv_window, "Content-Type": "application/json", "User-Agent": "RealtimePaperSimulator/1.0", } url = f"{self.base_url}{path}" + (f"?{query}" if query else "") request = urllib.request.Request(url, data=payload, headers=headers, method=method) try: with urllib.request.urlopen(request, timeout=10) as response: result = json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as exc: raw_details = exc.read() try: details = json.loads(raw_details.decode("utf-8")) except Exception: details = {} # Keep the useful Bybit error code and request context, but never # include request headers, signatures, API keys, or secrets. ret_code = details.get("retCode") if isinstance(details, dict) else None ret_msg = details.get("retMsg") if isinstance(details, dict) else None endpoint = "тестовой сети" if self.testnet else "основной сети" context = f"{method} {path} ({endpoint})" if ret_code is not None: message = f"Bybit API HTTP {exc.code}, retCode {ret_code}: {ret_msg or 'ошибка запроса'}" hints = { 10002: "Проверьте синхронизацию часов Windows.", 10003: "Ключ не подходит к выбранному домену: сверьте Testnet/Mainnet с сетью, где создан API-ключ.", 10004: "Bybit отклонил подпись. Проверьте API Secret и отсутствие лишних пробелов при вставке.", 10005: "Проверьте права API-ключа для чтения аккаунта и торговли контрактами.", 10009: "Bybit ограничил доступ к API для региона аккаунта или подключения.", 10010: "IP компьютера не совпадает с IP, разрешённым в настройках API-ключа.", } if ret_code in hints: message += f" {hints[ret_code]}" elif exc.code == 401: message = ( f"Bybit вернул HTTP 401 для {context}: запрос авторизации отклонён. " "Проверьте, что API-ключ создан в выбранной сети (Testnet/Mainnet), " "ключ и секрет скопированы полностью без пробелов, а IP компьютера " "разрешён в настройках ключа. Секрет приложения не выводит." ) else: message = f"Bybit API HTTP {exc.code} для {context}" raise BybitAPIError(message) from None except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc: raise BybitAPIError(f"Не удалось связаться с Bybit: {exc}") from None if result.get("retCode") != 0: raise BybitAPIError(f"Bybit API {result.get('retCode')}: {result.get('retMsg', 'ошибка запроса')}") return result.get("result", {}) def get_wallet(self) -> dict[str, float]: result = self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED", "coin": "USDT"}) rows = result.get("list", []) if not rows: raise BybitAPIError("Bybit не вернул Unified USDT-баланс; проверьте тип аккаунта и права API") row = rows[0] available_raw = row.get("totalAvailableBalance") if available_raw in (None, ""): equity = float(row.get("totalEquity") or 0) initial_margin = float(row.get("totalInitialMargin") or 0) available = max(0.0, equity - initial_margin) else: available = float(available_raw) return { "wallet": float(row.get("totalWalletBalance") or 0), "equity": float(row.get("totalEquity") or 0), "available": available, "unrealized_pnl": float(row.get("totalPerpUPL") or 0), } def get_instrument(self, symbol: str) -> dict[str, str]: result = self._request("GET", "/v5/market/instruments-info", {"category": "linear", "symbol": symbol}) rows = result.get("list", []) if not rows: raise BybitAPIError(f"Контракт {symbol} не найден на Bybit linear") row = rows[0] lot = row.get("lotSizeFilter", {}) if row.get("status") != "Trading": raise BybitAPIError(f"Контракт {symbol} сейчас не торгуется") return { "qty_step": lot.get("qtyStep", "0"), "min_qty": lot.get("minOrderQty", "0"), "min_notional": lot.get("minNotionalValue", "0"), "max_market_qty": lot.get("maxMktOrderQty", lot.get("maxMarketOrderQty", "0")), "tick_size": row.get("priceFilter", {}).get("tickSize", "0"), } def get_taker_fee_pct(self, symbol: str) -> float: result = self._request("GET", "/v5/account/fee-rate", {"category": "linear", "symbol": symbol}) rows = result.get("list", []) if not rows: raise BybitAPIError(f"Bybit не вернул комиссию для {symbol}") return float(rows[0]["takerFeeRate"]) * 100 def get_positions(self, symbol: str) -> list[dict]: result = self._request("GET", "/v5/position/list", {"category": "linear", "symbol": symbol}) return result.get("list", []) def get_open_positions(self) -> list[dict]: """Return all open USDT-settled linear positions for account overview.""" result = self._request("GET", "/v5/position/list", { "category": "linear", "settleCoin": "USDT", "limit": 200, }) return [row for row in result.get("list", []) if float(row.get("size") or 0) > 0] def get_order_history(self, limit: int = 50) -> list[dict]: """Return recent linear-contract order records (read-only).""" result = self._request("GET", "/v5/order/history", { "category": "linear", "settleCoin": "USDT", "limit": max(1, min(int(limit), 50)), }) return result.get("list", []) def get_closed_pnl_history(self, limit: int = 50) -> list[dict]: """Return recent realized PnL records for linear contracts.""" result = self._request("GET", "/v5/position/closed-pnl", { "category": "linear", "limit": max(1, min(int(limit), 100)), }) return result.get("list", []) def get_open_position(self, symbol: str) -> dict | None: for row in self.get_positions(symbol): if float(row.get("size") or 0) > 0: return row return None def get_order(self, symbol: str, order_id: str) -> dict | None: """Read the exchange state of an accepted order for safe reconciliation.""" params = {"category": "linear", "symbol": symbol, "orderId": order_id} for path in ("/v5/order/realtime", "/v5/order/history"): result = self._request("GET", path, params) rows = result.get("list", []) if rows: return rows[0] return None def get_latest_closed_pnl(self, symbol: str, opened_at_ms: int) -> dict | None: result = self._request("GET", "/v5/position/closed-pnl", { "category": "linear", "symbol": symbol, "startTime": opened_at_ms, "limit": 50, }) rows = result.get("list", []) return max(rows, key=lambda row: int(row.get("updatedTime", 0))) if rows else None def set_leverage(self, symbol: str, leverage: float) -> None: try: self._request("POST", "/v5/position/set-leverage", { "category": "linear", "symbol": symbol, "buyLeverage": str(leverage), "sellLeverage": str(leverage), }) except BybitAPIError as exc: # Bybit returns 110043 if the requested leverage is already active. if "110043" not in str(exc): raise @staticmethod def floor_qty(raw_qty: float, spec: dict[str, str]) -> str: step = Decimal(spec["qty_step"]) if step <= 0: raise BybitAPIError("Bybit вернул некорректный шаг количества") qty = (Decimal(str(raw_qty)) / step).to_integral_value(rounding=ROUND_DOWN) * step if qty < Decimal(spec["min_qty"]): raise BybitAPIError(f"Размер заявки меньше минимального: {spec['min_qty']}") maximum = Decimal(spec.get("max_market_qty") or "0") if maximum > 0 and qty > maximum: raise BybitAPIError(f"Рыночная заявка превышает максимум {maximum}; уменьшите ставку или плечо") return format(qty, "f") @staticmethod def format_price(raw_price: float, tick_size: str) -> str: tick = Decimal(tick_size) if tick <= 0: return format(Decimal(str(raw_price)), "f") price = (Decimal(str(raw_price)) / tick).to_integral_value(rounding=ROUND_UP) * tick return format(price, "f") def place_market_buy(self, symbol: str, qty: str, take_profit: float, stop_loss: float, tick_size: str, order_id: str | None = None) -> str: body = { "category": "linear", "symbol": symbol, "side": "Buy", "orderType": "Market", "qty": qty, "positionIdx": 0, "timeInForce": "IOC", "tpslMode": "Full", "tpOrderType": "Market", "slOrderType": "Market", "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", "orderLinkId": order_id or f"rps-{uuid.uuid4().hex[:28]}", } result = self._request("POST", "/v5/order/create", body) return result.get("orderId", "") def update_position_stops(self, symbol: str, take_profit: float, stop_loss: float, tick_size: str) -> None: try: self._request("POST", "/v5/position/trading-stop", { "category": "linear", "symbol": symbol, "tpslMode": "Full", "positionIdx": 0, "takeProfit": self.format_price(take_profit, tick_size) if take_profit > 0 else "0", "stopLoss": self.format_price(stop_loss, tick_size) if stop_loss > 0 else "0", "tpTriggerBy": "MarkPrice", "slTriggerBy": "MarkPrice", "tpOrderType": "Market", "slOrderType": "Market", }) except BybitAPIError as exc: # Bybit's 34040 is an idempotent response: the requested TP/SL is # already active (or no value changed), so there is nothing to do. if "34040" not in str(exc): raise def close_long_market(self, symbol: str, qty: str) -> str: result = self._request("POST", "/v5/order/create", { "category": "linear", "symbol": symbol, "side": "Sell", "orderType": "Market", "qty": qty, "positionIdx": 0, "timeInForce": "IOC", "reduceOnly": True, "closeOnTrigger": True, "orderLinkId": f"rps-close-{uuid.uuid4().hex[:24]}", }) return result.get("orderId", "")