fix: retry с backoff на сетевые ошибки Bybit + top-level crash guard

- exchange: timeout 10s→30s, retry 3x с backoff [2,4,8]s на NetworkError
  для fetch_candles, load_markets, get_balance, get_price, get_position
- executor: run_cycle обёрнут в try/except — цикл никогда не крашит APScheduler
- Только сетевые ошибки ретраятся (ccxt.NetworkError, RequestTimeout,
  ExchangeNotAvailable), auth/perm ошибки пробрасываются сразу

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-13 23:53:25 +10:00
co-authored by Claude Opus 4.6
parent 4b9f3e0365
commit 0e06427648
2 changed files with 114 additions and 37 deletions
+105 -37
View File
@@ -1,18 +1,35 @@
"""Bybit linear futures executor via ccxt.
Safety-first: balance checks, min order validation, dry-run mode,
no retries on failure.
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."""
@@ -23,6 +40,7 @@ class FuturesExecutor:
"apiKey": exchange_cfg.api_key,
"secret": exchange_cfg.api_secret,
"enableRateLimit": True,
"timeout": 30000, # 30s (default 10s too short)
"options": {
"defaultType": "linear",
"recvWindow": 30000,
@@ -40,8 +58,19 @@ class FuturesExecutor:
def _ensure_markets(self):
if not self._markets_loaded:
self.exchange.load_markets()
self._markets_loaded = True
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)."""
@@ -56,42 +85,66 @@ class FuturesExecutor:
self._leverage_set.add(symbol)
def get_balance(self) -> float:
"""Get free USDT balance."""
try:
b = self.exchange.fetch_balance()
return float(b.get("USDT", {}).get("free", 0) or 0)
except Exception as e:
log.error(f"Balance fetch failed: {e}")
return 0.0
"""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."""
try:
ticker = self.exchange.fetch_ticker(symbol)
return float(ticker["last"])
except Exception as e:
log.error(f"Price fetch {symbol} failed: {e}")
return 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."""
"""Get current exchange position for reconciliation with retry."""
if self.dry_run:
return None
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:
log.error(f"Position fetch {symbol} failed: {e}")
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."""
@@ -284,15 +337,30 @@ class FuturesExecutor:
def fetch_candles(self, symbol: str, timeframe: str,
since_ms: int) -> list[list]:
"""Fetch OHLCV candles from exchange."""
"""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 = self.exchange.fetch_ohlcv(
symbol, timeframe, since=since_ms, limit=1000,
)
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)
+9
View File
@@ -90,6 +90,15 @@ def _risk_pct(t: Trade) -> float:
def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Run one trading cycle for all symbols. Returns list of log messages."""
try:
return _run_cycle_inner(conn, cfg)
except Exception as e:
log.error("Cycle crashed: %s", e, exc_info=True)
return [f"CYCLE ERROR: {e}"]
def _run_cycle_inner(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Inner cycle logic — wrapped by run_cycle for safety."""
global _sessions, _session_date
logs: list[str] = []
now_utc = datetime.now(timezone.utc)