config.yaml + config.py: конфигурация с YAML + env var overrides state.py: SQLite state (equity, sessions, positions, orders) exchange.py: Bybit linear futures executor (dry-run + live) executor.py: торговый цикл — fetch candles → run_day() → reconcile cli.py: Click CLI (run, status, history, daemon с APScheduler 5m) notify.py: Telegram alerts (entry, exit, OR) Существующие backtest-скрипты не затронуты. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
253 lines
9.4 KiB
Python
253 lines
9.4 KiB
Python
"""Bybit linear futures executor via ccxt.
|
|
|
|
Safety-first: balance checks, min order validation, dry-run mode,
|
|
no retries on failure.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from datetime import datetime, timezone
|
|
|
|
from config import ExchangeConfig
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
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,
|
|
"options": {
|
|
"defaultType": "linear",
|
|
"recvWindow": 30000,
|
|
},
|
|
})
|
|
self.dry_run = not exchange_cfg.api_key
|
|
self.leverage = leverage
|
|
self._markets_loaded = False
|
|
self._leverage_set = False
|
|
|
|
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:
|
|
self.exchange.load_markets()
|
|
self._markets_loaded = True
|
|
|
|
def setup(self, symbol: str) -> None:
|
|
"""Set leverage and position mode (call once per symbol)."""
|
|
if 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 = True
|
|
|
|
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
|
|
|
|
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
|
|
|
|
def get_position(self, symbol: str) -> dict | None:
|
|
"""Get current exchange position for reconciliation."""
|
|
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
|
|
|
|
def open_long(self, symbol: str, usdt_amount: float) -> dict | None:
|
|
"""Market long (buy). Returns order dict or None."""
|
|
return self._open(symbol, usdt_amount, "buy")
|
|
|
|
def open_short(self, symbol: str, usdt_amount: float) -> dict | None:
|
|
"""Market short (sell). 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] {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:
|
|
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"{side.upper()} OK: {filled} {symbol} @ ${avg_price:,.2f} "
|
|
f"order={order.get('id')}")
|
|
return order
|
|
except Exception as e:
|
|
log.error(f"{side.upper()} {symbol} FAILED: {e}")
|
|
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."""
|
|
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,
|
|
)
|
|
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
|