"""Bybit linear futures executor via ccxt. Safety-first: balance checks, min order validation, dry-run mode, retry on network errors. """ from __future__ import annotations import logging import time from datetime import datetime, timezone from config import ExchangeConfig log = logging.getLogger(__name__) # Retry config for network errors MAX_RETRIES = 3 RETRY_BACKOFF = [2, 4, 8] # seconds between retries def _is_network_error(e: Exception) -> bool: """Check if exception is a retriable network error.""" import ccxt return isinstance(e, ( ccxt.NetworkError, # base: timeout, DNS, connection reset ccxt.RequestTimeout, ccxt.ExchangeNotAvailable, ConnectionError, TimeoutError, )) class FuturesExecutor: """Execute linear futures trades on Bybit.""" def __init__(self, exchange_cfg: ExchangeConfig, leverage: int = 10): import ccxt self.exchange = ccxt.bybit({ "apiKey": exchange_cfg.api_key, "secret": exchange_cfg.api_secret, "enableRateLimit": True, "timeout": 30000, # 30s (default 10s too short) "options": { "defaultType": "linear", "recvWindow": 30000, }, }) self.dry_run = not exchange_cfg.api_key self.leverage = leverage self._markets_loaded = False self._leverage_set: set[str] = set() if self.dry_run: log.info("FuturesExecutor: DRY RUN mode (no API key)") else: log.info(f"FuturesExecutor: LIVE mode (leverage={leverage}x)") def _ensure_markets(self): if not self._markets_loaded: for attempt in range(MAX_RETRIES): try: self.exchange.load_markets() self._markets_loaded = True return except Exception as e: if _is_network_error(e) and attempt < MAX_RETRIES - 1: wait = RETRY_BACKOFF[attempt] log.warning("load_markets failed (attempt %d/%d), retry in %ds: %s", attempt + 1, MAX_RETRIES, wait, e) time.sleep(wait) else: raise def setup(self, symbol: str) -> None: """Set leverage and position mode (call once per symbol).""" if symbol in self._leverage_set or self.dry_run: return self._ensure_markets() try: self.exchange.set_leverage(self.leverage, symbol) log.info(f"Leverage set to {self.leverage}x for {symbol}") except Exception as e: log.warning(f"Set leverage failed (may already be set): {e}") self._leverage_set.add(symbol) def get_balance(self) -> float: """Get free USDT balance with retry.""" for attempt in range(MAX_RETRIES): try: b = self.exchange.fetch_balance() return float(b.get("USDT", {}).get("free", 0) or 0) except Exception as e: if _is_network_error(e) and attempt < MAX_RETRIES - 1: wait = RETRY_BACKOFF[attempt] log.warning("Balance fetch failed (attempt %d/%d), retry in %ds: %s", attempt + 1, MAX_RETRIES, wait, e) time.sleep(wait) else: log.error("Balance fetch failed: %s", e) return 0.0 return 0.0 def get_price(self, symbol: str) -> float | None: """Get current market price with retry.""" for attempt in range(MAX_RETRIES): try: ticker = self.exchange.fetch_ticker(symbol) return float(ticker["last"]) except Exception as e: if _is_network_error(e) and attempt < MAX_RETRIES - 1: wait = RETRY_BACKOFF[attempt] log.warning("Price fetch %s failed (attempt %d/%d), retry in %ds: %s", symbol, attempt + 1, MAX_RETRIES, wait, e) time.sleep(wait) else: log.error("Price fetch %s failed: %s", symbol, e) return None return None def get_position(self, symbol: str) -> dict | None: """Get current exchange position for reconciliation with retry.""" if self.dry_run: return None for attempt in range(MAX_RETRIES): try: positions = self.exchange.fetch_positions([symbol]) for p in positions: qty = float(p.get("contracts") or 0) if qty > 0: return { "side": p["side"], "qty": qty, "entry_price": float(p.get("entryPrice") or 0), "unrealized_pnl": float(p.get("unrealizedPnl") or 0), } return None except Exception as e: if _is_network_error(e) and attempt < MAX_RETRIES - 1: wait = RETRY_BACKOFF[attempt] log.warning("Position fetch %s failed (attempt %d/%d), retry in %ds: %s", symbol, attempt + 1, MAX_RETRIES, wait, e) time.sleep(wait) else: log.error("Position fetch %s failed: %s", symbol, e) return None return None def open_long(self, symbol: str, usdt_amount: float) -> dict | None: """Limit long (buy), fallback to market. Returns order dict or None.""" return self._open(symbol, usdt_amount, "buy") def open_short(self, symbol: str, usdt_amount: float) -> dict | None: """Limit short (sell), fallback to market. Returns order dict or None.""" return self._open(symbol, usdt_amount, "sell") def _open(self, symbol: str, usdt_amount: float, side: str) -> dict | None: self._ensure_markets() self.setup(symbol) price = self.get_price(symbol) if price is None: return None market = self.exchange.market(symbol) amount = usdt_amount / price amount = float(self.exchange.amount_to_precision(symbol, amount)) min_amount = float(market["limits"]["amount"]["min"] or 0) if amount < min_amount: log.error(f"{side.upper()} {symbol}: amount {amount} < min {min_amount}") return None ts = datetime.now(timezone.utc).isoformat() if self.dry_run: log.info(f"[DRY RUN] LIMIT {side.upper()} {amount} {symbol} @ ~${price:,.2f} " f"(${usdt_amount:.2f}) at {ts}") return {"dry_run": True, "side": side, "symbol": symbol, "amount": amount, "price": price, "cost": usdt_amount} # Try limit postOnly first (maker fee) order = self._try_limit(symbol, side, amount, price) if order: return order # Fallback: market order (taker fee) log.warning(f"Limit failed, fallback to market {side.upper()} {symbol}") try: order = self.exchange.create_order(symbol, "market", side, amount) order = self._fetch_order_details(order, symbol) filled = float(order.get("filled") or amount) avg_price = float(order.get("average") or price) log.info(f"MARKET {side.upper()} OK: {filled} {symbol} @ ${avg_price:,.2f}") return order except Exception as e: log.error(f"MARKET {side.upper()} {symbol} FAILED: {e}") return None def _try_limit(self, symbol: str, side: str, amount: float, price: float, wait_sec: int = 10) -> dict | None: """Try postOnly limit order. Returns filled order or None.""" import time # Place at bid (buy) or ask (sell) for maker execution try: book = self.exchange.fetch_order_book(symbol, limit=1) if side == "buy": limit_price = float(book["bids"][0][0]) if book["bids"] else price else: limit_price = float(book["asks"][0][0]) if book["asks"] else price except Exception: limit_price = price limit_price = float(self.exchange.price_to_precision(symbol, limit_price)) try: order = self.exchange.create_order( symbol, "limit", side, amount, limit_price, params={"postOnly": True}, ) except Exception as e: log.warning(f"LIMIT {side.upper()} {symbol} rejected: {e}") return None order_id = order.get("id") if not order_id: return None # Wait for fill for _ in range(wait_sec): time.sleep(1) try: status = self.exchange.fetch_order(order_id, symbol) if status.get("status") == "closed": log.info(f"LIMIT {side.upper()} FILLED: {amount} {symbol} " f"@ ${limit_price:,.2f} (maker)") return status except Exception: pass # Not filled — cancel and check for partial fill try: self.exchange.cancel_order(order_id, symbol) except Exception as e: log.warning(f"Cancel limit order failed: {e}") # Check if partially filled try: final = self.exchange.fetch_order(order_id, symbol) filled = float(final.get("filled") or 0) if filled > 0: log.info(f"LIMIT {side.upper()} PARTIAL: {filled}/{amount} {symbol} " f"@ ${limit_price:,.2f} (maker)") return final except Exception: pass log.info(f"LIMIT {side.upper()} cancelled (not filled in {wait_sec}s)") return None def close_position(self, symbol: str, side: str, qty: float) -> dict | None: """Close position with reduceOnly order.""" close_side = "sell" if side == "buy" else "buy" if self.dry_run: price = self.get_price(symbol) or 0 log.info(f"[DRY RUN] CLOSE {close_side} {qty} {symbol} @ ~${price:,.2f}") return {"dry_run": True, "side": close_side, "symbol": symbol, "amount": qty, "price": price, "cost": qty * price} try: order = self.exchange.create_order( symbol, "market", close_side, qty, params={"reduceOnly": True}, ) order = self._fetch_order_details(order, symbol) log.info(f"CLOSE OK: {close_side} {qty} {symbol} order={order.get('id')}") return order except Exception as e: log.error(f"CLOSE {symbol} FAILED: {e}") return None def place_sl_tp(self, symbol: str, side: str, qty: float, sl_price: float, tp_price: float) -> tuple[dict | None, dict | None]: """Place SL and TP conditional orders. Returns (sl_order, tp_order).""" close_side = "sell" if side == "buy" else "buy" sl_price = float(self.exchange.price_to_precision(symbol, sl_price)) tp_price = float(self.exchange.price_to_precision(symbol, tp_price)) if self.dry_run: log.info(f"[DRY RUN] SL {close_side} {qty} {symbol} @ ${sl_price:,.2f}") log.info(f"[DRY RUN] TP {close_side} {qty} {symbol} @ ${tp_price:,.2f}") sl = {"dry_run": True, "id": "sl_dry", "stopPrice": sl_price} tp = {"dry_run": True, "id": "tp_dry", "stopPrice": tp_price} return sl, tp sl_order = tp_order = None try: sl_order = self.exchange.create_order( symbol, "market", close_side, qty, params={ "triggerPrice": str(sl_price), "reduceOnly": True, "triggerDirection": 2 if side == "buy" else 1, }, ) log.info(f"SL placed: {symbol} @ ${sl_price:,.2f} id={sl_order.get('id')}") except Exception as e: log.error(f"SL {symbol} FAILED: {e}") try: tp_order = self.exchange.create_order( symbol, "market", close_side, qty, params={ "triggerPrice": str(tp_price), "reduceOnly": True, "triggerDirection": 1 if side == "buy" else 2, }, ) log.info(f"TP placed: {symbol} @ ${tp_price:,.2f} id={tp_order.get('id')}") except Exception as e: log.error(f"TP {symbol} FAILED: {e}") return sl_order, tp_order def cancel_orders(self, symbol: str, *order_ids: str) -> None: """Cancel conditional orders (SL/TP on position close).""" for oid in order_ids: if not oid: continue if self.dry_run: log.info(f"[DRY RUN] CANCEL order {oid} on {symbol}") continue try: self.exchange.cancel_order(oid, symbol, params={"stop": True}) log.info(f"CANCEL OK: {oid} on {symbol}") except Exception as e: log.warning(f"CANCEL {oid} failed: {e}") def fetch_candles(self, symbol: str, timeframe: str, since_ms: int) -> list[list]: """Fetch OHLCV candles from exchange with retry on network errors.""" self._ensure_markets() all_candles = [] bar_ms = {"1m": 60_000, "5m": 300_000, "15m": 900_000}.get(timeframe, 300_000) while True: batch = None for attempt in range(MAX_RETRIES): try: batch = self.exchange.fetch_ohlcv( symbol, timeframe, since=since_ms, limit=1000, ) break except Exception as e: if _is_network_error(e) and attempt < MAX_RETRIES - 1: wait = RETRY_BACKOFF[attempt] log.warning("fetch_ohlcv %s failed (attempt %d/%d), retry in %ds: %s", symbol, attempt + 1, MAX_RETRIES, wait, e) time.sleep(wait) else: log.error("fetch_ohlcv %s failed after %d attempts: %s", symbol, attempt + 1, e) return all_candles # return what we have so far if not batch: break all_candles.extend(batch) since_ms = batch[-1][0] + bar_ms if len(batch) < 1000: break return all_candles def _fetch_order_details(self, order: dict, symbol: str) -> dict: """Fetch full order details (Bybit v5 may return None fields).""" import time order_id = order.get("id") if order_id is None: return order try: time.sleep(1) return self.exchange.fetch_closed_order(order_id, symbol) except Exception: try: return self.exchange.fetch_order(order_id, symbol) except Exception: return order