Files
remizov-trader/src/remizov_trader/core/spot.py
T
anorandClaude Opus 4.6 10a0ca05e9 feat: поддержка spot margin (leverage) — выключено по умолчанию
- config: leverage=1 в RiskConfig (1=off, 2-10=spot margin)
- risk.py: buying_power = equity × leverage в position sizing
- spot.py: _ensure_margin() включает маржу на бирже при leverage > 1
- executor.py: передача leverage в SpotExecutor

При leverage=1 поведение не меняется.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 06:31:30 +10:00

224 lines
8.4 KiB
Python

"""Spot trading executor for Bybit via ccxt.
Safety-first design:
- Balance checks before every trade
- Min order validation
- Dry-run mode (testnet=true in config)
- No retries on failure (prevents double orders)
- Comprehensive logging
"""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from ..config import ExchangeConfig
log = logging.getLogger(__name__)
class SpotExecutor:
"""Execute spot trades on Bybit."""
def __init__(self, exchange_cfg: ExchangeConfig, leverage: int = 1):
import ccxt
self.exchange = ccxt.bybit({
"apiKey": exchange_cfg.api_key,
"secret": exchange_cfg.api_secret,
"enableRateLimit": True,
})
self.dry_run = exchange_cfg.testnet
self.leverage = leverage
self._markets_loaded = False
self._margin_enabled = False
if self.dry_run:
log.info("SpotExecutor: DRY RUN mode (testnet=true)")
else:
log.info(f"SpotExecutor: LIVE mode (leverage={leverage}x)")
def _ensure_markets(self):
if not self._markets_loaded:
self.exchange.load_markets()
self._markets_loaded = True
def _ensure_margin(self, symbol: str):
"""Enable spot margin for symbol if leverage > 1."""
if self.leverage <= 1 or self._margin_enabled:
return
try:
self.exchange.set_leverage(self.leverage, symbol, params={
"category": "spot",
})
self._margin_enabled = True
log.info(f"Spot margin enabled: {self.leverage}x for {symbol}")
except Exception as e:
log.warning(f"Could not set margin {self.leverage}x: {e}")
def get_balance(self, coin: str) -> float:
"""Get free balance for a coin."""
try:
b = self.exchange.fetch_balance()
return float(b.get(coin, {}).get("free", 0) or 0)
except Exception as e:
log.error(f"Balance fetch failed: {e}")
return 0.0
def _fetch_order_details(self, order: dict, symbol: str,
amount: float, price: float,
cost: float) -> dict:
"""Fetch full order details (Bybit v5 returns None fields on create)."""
import time
order_id = order.get("id")
if order_id is None:
return order
try:
time.sleep(1) # wait for order to settle
full = self.exchange.fetch_order(order_id, symbol)
return full
except Exception as e:
log.warning(f"Could not fetch order details {order_id}: {e}")
return order
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 buy(self, symbol: str, quote_amount: float) -> dict | None:
"""Market buy with specified quote currency amount.
If leverage > 1, uses spot margin (borrows funds automatically).
Returns order dict or None on failure.
Does NOT retry on failure (prevents double orders).
"""
self._ensure_markets()
self._ensure_margin(symbol)
coin = symbol.split("/")[0]
quote = symbol.split("/")[1] # USDT, USDC, etc.
# 1. Get price
price = self.get_price(symbol)
if price is None:
return None
# 2. Calculate amount
market = self.exchange.market(symbol)
amount = quote_amount / price
amount = float(self.exchange.amount_to_precision(symbol, amount))
# 3. Validate minimums
min_amount = float(market["limits"]["amount"]["min"] or 0)
min_cost = float(market["limits"]["cost"]["min"] or 5.0)
if amount < min_amount:
log.error(f"BUY {symbol}: amount {amount} < min {min_amount}")
return None
if quote_amount < min_cost:
log.error(f"BUY {symbol}: cost ${quote_amount:.2f} < min ${min_cost}")
return None
# 4. Check balance (strict)
quote_free = self.get_balance(quote)
if quote_free < quote_amount:
# Try to buy what we can afford
if quote_free >= min_cost:
log.warning(f"BUY {symbol}: {quote} {quote_free:.2f} < requested {quote_amount:.2f}, "
f"reducing to {quote_free:.2f}")
quote_amount = quote_free
amount = quote_amount / price
amount = float(self.exchange.amount_to_precision(symbol, amount))
else:
log.error(f"BUY {symbol}: {quote} {quote_free:.2f} < min ${min_cost}")
return None
# 5. Execute
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] BUY {amount} {coin} @ ~${price:,.2f} "
f"(${quote_amount:.2f}) at {ts}")
return {"dry_run": True, "side": "buy", "symbol": symbol,
"amount": amount, "price": price, "cost": quote_amount}
try:
order = self.exchange.create_market_buy_order(symbol, amount)
order = self._fetch_order_details(order, symbol, amount, price, quote_amount)
fee = order.get("fee") or {}
fee_str = f" fee={fee.get('cost', '?')} {fee.get('currency', '')}" if fee else ""
filled = float(order.get("filled") or amount)
avg_price = float(order.get("average") or price)
cost = float(order.get("cost") or quote_amount)
log.info(f"BUY OK: {filled} {coin} @ ${avg_price:,.2f} "
f"(${cost:.2f}){fee_str} order={order['id']}")
return order
except Exception as e:
log.error(f"BUY {symbol} FAILED: {e}")
return None
def sell(self, symbol: str, amount: float | None = None) -> dict | None:
"""Market sell. If amount is None, sell entire balance.
Returns order dict or None on failure.
Does NOT retry on failure (prevents double orders).
"""
self._ensure_markets()
coin = symbol.split("/")[0]
# 1. Determine amount
if amount is None:
amount = self.get_balance(coin)
if amount <= 0:
log.warning(f"SELL {symbol}: nothing to sell ({coin} balance=0)")
return None
# 2. Precision
amount = float(self.exchange.amount_to_precision(symbol, amount))
# 3. Validate minimum
market = self.exchange.market(symbol)
min_amount = float(market["limits"]["amount"]["min"] or 0)
if amount < min_amount:
log.warning(f"SELL {symbol}: amount {amount} < min {min_amount}")
return None
# 4. Check balance
coin_free = self.get_balance(coin)
if coin_free < amount:
log.warning(f"SELL {symbol}: balance {coin_free} < requested {amount}, "
f"selling available")
amount = float(self.exchange.amount_to_precision(symbol, coin_free))
if amount < min_amount:
return None
# 5. Execute
price = self.get_price(symbol)
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
cost = amount * (price or 0)
log.info(f"[DRY RUN] SELL {amount} {coin} @ ~${price:,.2f} "
f"(~${cost:.2f}) at {ts}")
return {"dry_run": True, "side": "sell", "symbol": symbol,
"amount": amount, "price": price, "cost": cost}
try:
order = self.exchange.create_market_sell_order(symbol, amount)
order = self._fetch_order_details(order, symbol, amount, price, amount * (price or 0))
fee = order.get("fee") or {}
fee_str = f" fee={fee.get('cost', '?')} {fee.get('currency', '')}" if fee else ""
filled = float(order.get("filled") or amount)
avg_price = float(order.get("average") or price or 0)
cost = float(order.get("cost") or (filled * avg_price))
log.info(f"SELL OK: {filled} {coin} @ ${avg_price:,.2f} "
f"(${cost:.2f}){fee_str} order={order['id']}")
return order
except Exception as e:
log.error(f"SELL {symbol} FAILED: {e}")
return None