feat: futures long+short 1x 1h — FuturesExecutor, routing, time_exit в барах

- Новый FuturesExecutor (ccxt bybit linear): open_long/short, close_position,
  place_safety_stop с side, ensure_leverage (cached)
- Config: market_type, retrain_enabled, is_futures(), commission_for()
- Executor: routing spot/futures, SHORT разрешён для futures,
  time_exit в барах (не днях), commission по типу рынка
- Notify: USDT balance, skip futures в coin positions, dynamic timeframe
- Config.yaml: UNI+ATOM+SUI futures 1h, mode=paper
- 26 новых тестов (всего 97)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-15 03:55:17 +10:00
co-authored by Claude Opus 4.6
parent 52ce9a71a6
commit 0b2602600e
6 changed files with 771 additions and 89 deletions
+24 -18
View File
@@ -1,26 +1,28 @@
# RemizovTrader Configuration
mode: live # paper | live
mode: paper # paper | live — start with paper for futures validation
capital:
initial: 16.0 # per-asset (new assets)
total: 254.0 # actual total capital deposited
currency: USDC
total: 177.0 # actual total capital deposited
currency: USDT
risk:
per_trade: 0.05 # 5% risk per trade
max_position_pct: 0.40 # max 40% of equity (min $5 Bybit limit)
max_open_positions: 3 # 3 assets: UNI+ATOM+NEAR (autoresearch grid)
max_open_positions: 3 # 3 assets: UNI+ATOM+SUI
leverage: 1 # 1x — grid search best results all at leverage=1
stop_scale: 1.0 # global default; per-asset overrides below
time_exit: false # grid search: hold until stop
time_exit: true # CRITICAL: backtest uses time exit for futures
safety_stop_pct: 0.10 # 10% hard stop on exchange (flash crash protection)
min_confidence: 0.0 # grid search best: no confidence filter
assets:
# Grid search top-3 (OOS confirmed): exact params from autoresearch
# Futures long+short 1x 1h — backtest Sharpe 4-6x
- ticker: UNI-USD
symbol: UNI/USDC
symbol: "UNI/USDT:USDT"
market_type: futures
retrain_enabled: false
window_size: 64
weight: 0.34
leverage: 1
@@ -34,15 +36,17 @@ assets:
min_confidence: 0.0
shape_confirm: false
corr_thresh: 0.5
timeframe: 4h
timeframe: 1h
- ticker: ATOM-USD
symbol: ATOM/USDC
symbol: "ATOM/USDT:USDT"
market_type: futures
retrain_enabled: false
window_size: 64
weight: 0.33
leverage: 1
K: 3
shift: 14
shift: 10 # backtest: shift 10 beats 14 for ATOM
epochs: 300
lr: 0.005
stop_mult: 0.75
@@ -51,24 +55,26 @@ assets:
min_confidence: 0.0
shape_confirm: false
corr_thresh: 0.5
timeframe: 4h
timeframe: 1h
- ticker: NEAR-USD
symbol: NEAR/USDC
- ticker: SUI-USD
symbol: "SUI/USDT:USDT"
market_type: futures
retrain_enabled: false
window_size: 64
weight: 0.33
leverage: 1
K: 2
shift: 16
shift: 10
epochs: 300
lr: 0.01
lr: 0.005
stop_mult: 1.0
stop_scale: 1.0
cooldown_bars: -1 # -1 = use shift (16) as cooldown, matches test behavior
cooldown_bars: 3
min_confidence: 0.0
shape_confirm: false
corr_thresh: 0.5
timeframe: 4h
timeframe: 1h
model:
window_size: 64
@@ -109,5 +115,5 @@ llm:
sentiment_threshold: -0.3
schedule:
timeframe: 4h # 4h — matches grid search test timeframe
timeframe: 1h # 1h — matches futures backtest timeframe
check_time: "22:00" # UTC (used for daily, ignored for interval)
+10
View File
@@ -32,6 +32,8 @@ class AssetConfig:
cooldown_bars: int = -1 # -1 = use shift as cooldown; >=0 = explicit
min_confidence: float = -1.0 # -1 = use global; >=0 = per-asset override
shape_confirm: bool = True # False = skip correlation check entirely
market_type: str = "spot" # "spot" or "futures"
retrain_enabled: bool = True # False = frozen model (no retrain on losses)
@dataclass
@@ -137,6 +139,14 @@ class Config:
"""Get leverage: per-asset override or global."""
return asset.leverage or self.risk.leverage
def is_futures(self, asset: AssetConfig) -> bool:
"""Check if asset trades on futures market."""
return asset.market_type == "futures"
def commission_for(self, asset: AssetConfig) -> float:
"""Get commission rate: 0.055% for futures, 0.1% for spot."""
return 0.00055 if self.is_futures(asset) else 0.001
def load_config(path: Path | None = None) -> Config:
"""Load configuration from YAML file + environment variables."""
+161 -67
View File
@@ -20,8 +20,9 @@ from . import risk, signals
log = logging.getLogger(__name__)
# Singleton spot executor (created once on first live trade)
# Singleton executors (created once on first live trade)
_spot_executor = None
_futures_executor = None
def _get_spot(cfg: Config):
@@ -33,6 +34,22 @@ def _get_spot(cfg: Config):
return _spot_executor
def _get_futures(cfg: Config):
"""Get or create FuturesExecutor singleton."""
global _futures_executor
if _futures_executor is None:
from .futures import FuturesExecutor
_futures_executor = FuturesExecutor(cfg.exchange, leverage=cfg.risk.leverage)
return _futures_executor
def _get_executor(cfg: Config, asset_cfg: AssetConfig):
"""Get appropriate executor based on asset market_type."""
if cfg.is_futures(asset_cfg):
return _get_futures(cfg)
return _get_spot(cfg)
def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
"""Sync DB positions with actual exchange state.
@@ -44,17 +61,26 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
if cfg.mode != "live":
return logs
spot = _get_spot(cfg)
for asset_cfg in cfg.assets:
ticker = asset_cfg.ticker
pos = get_open_position(conn, ticker)
if pos is None:
continue
# Check actual coin balance on exchange
coin = asset_cfg.symbol.split("/")[0]
coin_balance = spot.get_balance(coin)
executor = _get_executor(cfg, asset_cfg)
if cfg.is_futures(asset_cfg):
# Futures: check position via fetch_positions
fut_pos = executor.get_position(asset_cfg.symbol)
if fut_pos is None:
coin_balance = 0.0 # no position = closed
else:
coin_balance = fut_pos["size"]
else:
# Spot: check coin balance
coin = asset_cfg.symbol.split("/")[0]
coin_balance = executor.get_balance(coin)
if coin_balance is None:
log.warning(f"{ticker}: reconcile skipped — balance API error")
logs.append(f"{ticker}: RECONCILE skipped — balance API error")
@@ -63,13 +89,15 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
if coin_balance < min_threshold:
# Position was closed externally (user sold on exchange)
current_price = spot.get_price(asset_cfg.symbol)
current_price = executor.get_price(asset_cfg.symbol)
if current_price is None:
current_price = pos["entry_price"] # fallback
commission = cfg.commission_for(asset_cfg)
pnl_net, pnl_pct = risk.calculate_pnl(
pos["entry_price"], current_price, pos["direction"],
pos["pos_size"], pos["pos_value"],
commission=commission,
)
close_position(conn, pos["id"],
@@ -93,7 +121,7 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
# Cancel orphaned safety stop
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
spot.cancel_order(asset_cfg.symbol, safety_id)
executor.cancel_order(asset_cfg.symbol, safety_id)
dir_str = "LONG" if pos["direction"] == 1 else "SHORT"
log.warning(f"{ticker}: reconcile — {dir_str} closed externally "
@@ -103,7 +131,7 @@ def reconcile_positions(conn: sqlite3.Connection, cfg: Config) -> list[str]:
else:
# Position exists — update DB with actual size if different
if abs(coin_balance - pos["pos_size"]) > pos["pos_size"] * 0.02:
current_price = spot.get_price(asset_cfg.symbol) or pos["entry_price"]
current_price = executor.get_price(asset_cfg.symbol) or pos["entry_price"]
update_position(conn, pos["id"],
pos_size=coin_balance,
pos_value=coin_balance * current_price)
@@ -216,8 +244,8 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
if asset.get("last_atr_regime") != current_regime:
update_asset(conn, ticker, last_atr_regime=current_regime)
# Event-driven retrain check
if asset:
# Event-driven retrain check (skip if retrain_enabled=false)
if asset and getattr(asset_cfg, 'retrain_enabled', True):
retrain_reason = _should_retrain(asset, prices, len(prices) - 1)
if retrain_reason:
_retrain(conn, ticker, prices, cfg)
@@ -341,9 +369,23 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
last_price = float(prices[-1])
last_date = str(dates[-1])
# Days held
from datetime import date as d
days_held = (d.fromisoformat(last_date) - d.fromisoformat(entry_date)).days
# Bars held: use created_at (full datetime) for sub-daily timeframes
from datetime import datetime as dt_cls
created_at = pos.get("created_at")
if created_at:
try:
entry_dt = dt_cls.fromisoformat(created_at)
except (ValueError, TypeError):
from datetime import date as d
entry_dt = dt_cls.combine(d.fromisoformat(entry_date), dt_cls.min.time())
else:
from datetime import date as d
entry_dt = dt_cls.combine(d.fromisoformat(entry_date), dt_cls.min.time())
tf_str = asset_cfg.timeframe or cfg.timeframe
tf_hours = int(tf_str.replace("h", "").replace("d", "")) if "d" not in tf_str else 24
hours_held = (dt_cls.utcnow() - entry_dt).total_seconds() / 3600
bars_held = hours_held / tf_hours
# Check stop FIRST (before trailing update, matches backtest)
stopped = risk.is_stopped(last_price, stop_price, direction)
@@ -365,14 +407,16 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
if cfg.risk.time_exit:
asset_model_cfg = cfg.model_for(asset_cfg)
max_hold = asset_model_cfg.shift - pos["k_used"]
time_exit = days_held >= max_hold
time_exit = bars_held >= max_hold
if stopped or time_exit:
exit_price = last_price # always use market price (stop_price was optimistic)
exit_reason = "stop" if stopped else "time"
commission = cfg.commission_for(asset_cfg)
pnl_net, pnl_pct = risk.calculate_pnl(
entry_price, exit_price, direction, pos_size, pos_value,
commission=commission,
)
close_position(conn, pos["id"],
@@ -406,31 +450,41 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
msg = (f"CLOSED {dir_str} ${entry_price:,.2f}→${exit_price:,.2f} "
f"({exit_reason}) PnL ${pnl_net:+,.2f} [{win_str}]")
# Live execution: cancel safety stop + sell on exchange
if cfg.mode == "live" and direction == 1:
spot = _get_spot(cfg)
# Live execution: cancel safety stop + close on exchange
if cfg.mode == "live":
executor = _get_executor(cfg, asset_cfg)
# Cancel safety stop order if exists
safety_id = pos.get("safety_stop_order_id")
if safety_id and safety_id != "dry_run":
spot.cancel_order(asset_cfg.symbol, safety_id)
order = spot.sell(asset_cfg.symbol)
executor.cancel_order(asset_cfg.symbol, safety_id)
if cfg.is_futures(asset_cfg):
side = "long" if direction == 1 else "short"
order = executor.close_position(asset_cfg.symbol, side)
elif direction == 1:
order = executor.sell(asset_cfg.symbol)
else:
order = None # spot short not supported
if order:
fee = order.get("fee") or {}
fee_cost = fee.get("cost")
fee_cur = fee.get("currency", "")
if fee_cost and fee_cur != "USDC":
if fee_cost and fee_cur not in ("USDC", "USDT"):
fee_usd = float(fee_cost) * exit_price
fee_str = f" fee=${fee_usd:.2f}"
elif fee_cost:
fee_str = f" fee=${float(fee_cost):.2f}"
else:
fee_str = ""
msg += f" [LIVE SELL OK{fee_str}]"
log_order(conn, pos["id"], "sell", asset_cfg.symbol, exit_price, order)
msg += f" [LIVE CLOSE OK{fee_str}]"
log_order(conn, pos["id"], "close", asset_cfg.symbol, exit_price, order)
elif order is None and not cfg.is_futures(asset_cfg) and direction == -1:
pass # spot short — no exchange action needed
else:
msg += " [LIVE SELL FAILED]"
log_order(conn, pos["id"], "sell", asset_cfg.symbol, exit_price, None, failed=True)
log.error(f"{asset_cfg.ticker}: live sell failed on close")
msg += " [LIVE CLOSE FAILED]"
log_order(conn, pos["id"], "close", asset_cfg.symbol, exit_price, None, failed=True)
log.error(f"{asset_cfg.ticker}: live close failed")
return msg
@@ -517,8 +571,8 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
if direction is None:
return "indeterminate direction"
# Live spot mode: skip SHORT signals (can't short on spot)
if cfg.mode == "live" and direction == -1:
# Live spot mode: skip SHORT signals (can't short on spot; futures can)
if cfg.mode == "live" and direction == -1 and not cfg.is_futures(asset_cfg):
log_signal(conn, ticker=ticker, date=str(dates[-1]),
correlation=corr, direction=direction, action="skip_spot_short",
details="SHORT not available in live spot mode")
@@ -549,22 +603,23 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
total_equity = cfg.total_capital if cfg.total_capital > 0 else asset["equity"]
pos_value = total_equity * asset_cfg.weight * leverage
# Cap by free USDC (Bybit available balance < free due to haircut + IM)
# Cap by free balance (Bybit available balance < free due to haircut + IM)
if cfg.mode == "live":
spot = _get_spot(cfg)
free_usdc = spot.get_balance("USDC")
if free_usdc is None:
executor = _get_executor(cfg, asset_cfg)
quote_coin = "USDT" if cfg.is_futures(asset_cfg) else "USDC"
free_quote = executor.get_balance(quote_coin)
if free_quote is None:
log.warning(f"{ticker}: balance API error during position sizing")
return "margin skip: balance API error — SKIP"
# 15% buffer: Bybit deducts haircut (CVR) + spot IM from available
max_margin = free_usdc * 0.85
max_margin = free_quote * 0.85
max_pos_value = max_margin * leverage
if pos_value > max_pos_value:
if max_pos_value < 5.0:
return (f"margin skip: free ${free_usdc:.2f}, "
return (f"margin skip: free ${free_quote:.2f}, "
f"max pos ${max_pos_value:.2f} < $5 — SKIP")
log.info(f"{ticker}: capped pos_value ${pos_value:.2f} → "
f"${max_pos_value:.2f} (free USDC: ${free_usdc:.2f})")
f"${max_pos_value:.2f} (free {quote_coin}: ${free_quote:.2f})")
pos_value = max_pos_value
if pos_value < 5.0: # Bybit min order
@@ -609,15 +664,27 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
msg = (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
f"stop ${stop_price:,.2f} corr={corr:.3f} size=${pos_value:,.2f}")
# Live execution: buy on exchange
if cfg.mode == "live" and direction == 1:
spot = _get_spot(cfg)
order = spot.buy(asset_cfg.symbol, pos_value)
# Live execution: open position on exchange
if cfg.mode == "live":
executor = _get_executor(cfg, asset_cfg)
if cfg.is_futures(asset_cfg):
# Futures: open_long or open_short
if direction == 1:
order = executor.open_long(asset_cfg.symbol, pos_value)
else:
order = executor.open_short(asset_cfg.symbol, pos_value)
elif direction == 1:
# Spot: only long
order = executor.buy(asset_cfg.symbol, pos_value)
else:
order = None # spot short — paper only
if order:
fee = order.get("fee") or {}
fee_cost = fee.get("cost")
fee_cur = fee.get("currency", "")
if fee_cost and fee_cur != "USDC":
if fee_cost and fee_cur not in ("USDC", "USDT"):
fee_usd = float(fee_cost) * entry_price
fee_str = f" fee=${fee_usd:.2f}"
elif fee_cost:
@@ -638,37 +705,56 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
entry_price = actual_price
fee_str += f" adjusted=${actual_cost:.2f}"
msg += f" [LIVE BUY OK{fee_str}]"
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, order)
action = "OPEN" if cfg.is_futures(asset_cfg) else "BUY"
msg += f" [LIVE {action} OK{fee_str}]"
log_order(conn, pos_id, action.lower(), asset_cfg.symbol, entry_price, order)
# Update pos_size to actual balance (fee in coin reduces it)
coin = asset_cfg.symbol.split("/")[0]
actual_bal = spot.get_balance(coin)
if actual_bal and actual_bal < pos_size:
log.info(f"{ticker}: pos_size adjusted for fee: "
f"{pos_size:.4f} -> {actual_bal:.4f}")
update_position(conn, pos_id, pos_size=actual_bal)
pos_size = actual_bal
if cfg.is_futures(asset_cfg):
# Futures: pos_size from exchange position
fut_pos = executor.get_position(asset_cfg.symbol)
if fut_pos and fut_pos["size"] > 0:
update_position(conn, pos_id, pos_size=fut_pos["size"])
pos_size = fut_pos["size"]
else:
# Spot: pos_size from coin balance (fee in coin reduces it)
coin = asset_cfg.symbol.split("/")[0]
actual_bal = executor.get_balance(coin)
if actual_bal and actual_bal < pos_size:
log.info(f"{ticker}: pos_size adjusted for fee: "
f"{pos_size:.4f} -> {actual_bal:.4f}")
update_position(conn, pos_id, pos_size=actual_bal)
pos_size = actual_bal
# Place safety stop on exchange (hard protection against flash crash)
if cfg.risk.safety_stop_pct > 0:
safety_price = entry_price * (1.0 - cfg.risk.safety_stop_pct)
safety_size = actual_bal if actual_bal else pos_size
safety_order = spot.place_safety_stop(
asset_cfg.symbol, safety_size, safety_price)
if cfg.is_futures(asset_cfg):
side = "long" if direction == 1 else "short"
if direction == 1:
safety_price = entry_price * (1.0 - cfg.risk.safety_stop_pct)
else:
safety_price = entry_price * (1.0 + cfg.risk.safety_stop_pct)
safety_order = executor.place_safety_stop(
asset_cfg.symbol, side, pos_size, safety_price)
else:
safety_price = entry_price * (1.0 - cfg.risk.safety_stop_pct)
safety_size = pos_size
safety_order = executor.place_safety_stop(
asset_cfg.symbol, safety_size, safety_price)
if safety_order:
safety_id = safety_order.get("id") or "dry_run"
update_position(conn, pos_id, safety_stop_order_id=safety_id)
msg += f" [SAFETY STOP ${safety_price:,.2f}]"
elif order is None and not cfg.is_futures(asset_cfg) and direction == -1:
pass # spot short — paper only, no exchange action
else:
# Rollback paper position — no phantom positions
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, None, failed=True)
log_order(conn, pos_id, "open", asset_cfg.symbol, entry_price, None, failed=True)
close_position(conn, pos_id,
exit_price=entry_price, exit_date=str(dates[-1]),
exit_reason="live_buy_failed", pnl_net=0, pnl_pct=0)
msg = (f"SIGNAL {dir_str} @ ${entry_price:,.2f} "
f"[LIVE BUY FAILED — position rolled back]")
log.error(f"{ticker}: live buy failed, paper position rolled back")
f"[LIVE OPEN FAILED — position rolled back]")
log.error(f"{ticker}: live open failed, paper position rolled back")
return msg
@@ -749,16 +835,16 @@ def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
recon_logs = reconcile_positions(conn, cfg)
logs.extend(recon_logs)
spot = _get_spot(cfg)
for asset_cfg in cfg.assets:
ticker = asset_cfg.ticker
pos = get_open_position(conn, ticker)
if pos is None:
continue
executor = _get_executor(cfg, asset_cfg)
# Fetch current price from exchange
current_price = spot.get_price(asset_cfg.symbol)
current_price = executor.get_price(asset_cfg.symbol)
if current_price is None:
logs.append(f"{ticker}: price fetch failed — skip stop update")
continue
@@ -795,17 +881,25 @@ def update_stops(conn: sqlite3.Connection, cfg: Config) -> list[str]:
safety_missing = not safety_id or safety_id == "dry_run"
if stop_changed or safety_missing:
active_stop = new_stop if stop_changed else stop_price
# Use actual coin balance for safety stop (fee reduces pos_size)
coin = asset_cfg.symbol.split("/")[0]
actual_size = spot.get_balance(coin)
safety_size = actual_size if actual_size else pos["pos_size"]
new_safety = spot.place_safety_stop(
asset_cfg.symbol, safety_size, active_stop)
if cfg.is_futures(asset_cfg):
fut_pos = executor.get_position(asset_cfg.symbol)
safety_size = fut_pos["size"] if fut_pos else pos["pos_size"]
side = "long" if direction == 1 else "short"
new_safety = executor.place_safety_stop(
asset_cfg.symbol, side, safety_size, active_stop)
else:
coin = asset_cfg.symbol.split("/")[0]
actual_size = executor.get_balance(coin)
safety_size = actual_size if actual_size else pos["pos_size"]
new_safety = executor.place_safety_stop(
asset_cfg.symbol, safety_size, active_stop)
if new_safety:
new_safety_id = new_safety.get("id") or "dry_run"
# Cancel old only after new is confirmed
if not safety_missing:
spot.cancel_order(asset_cfg.symbol, safety_id)
executor.cancel_order(asset_cfg.symbol, safety_id)
update_position(conn, pos["id"],
safety_stop_order_id=new_safety_id)
action = "restored" if safety_missing else "moved"
+242
View File
@@ -0,0 +1,242 @@
"""Futures trading executor for Bybit linear perpetuals via ccxt.
Same safety-first approach as SpotExecutor:
- Balance checks before every trade
- Min order validation
- Dry-run mode (testnet=true)
- No retries on failure
- reduceOnly for closes
"""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from ..config import ExchangeConfig
log = logging.getLogger(__name__)
class FuturesExecutor:
"""Execute linear perpetual futures 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,
"options": {
"recvWindow": 30000,
"defaultType": "linear",
},
})
self.dry_run = exchange_cfg.testnet
self.leverage = leverage
self._markets_loaded = False
self._leverage_set: set[str] = set() # cache per-symbol
mode = "DRY RUN" if self.dry_run else "LIVE"
log.info(f"FuturesExecutor: {mode} mode (leverage={leverage}x)")
def _ensure_markets(self):
if not self._markets_loaded:
self.exchange.load_markets()
self._markets_loaded = True
def ensure_leverage(self, symbol: str, leverage: int | None = None):
"""Set leverage for symbol (cached — only calls API once per symbol)."""
lev = leverage or self.leverage
if symbol in self._leverage_set:
return
if self.dry_run:
self._leverage_set.add(symbol)
return
try:
self.exchange.set_leverage(lev, symbol)
self._leverage_set.add(symbol)
log.info(f"Leverage set: {symbol} = {lev}x")
except Exception as e:
# Bybit returns error if leverage already set to same value
if "leverage not modified" in str(e).lower() or "same" in str(e).lower():
self._leverage_set.add(symbol)
else:
log.warning(f"Set leverage {symbol} failed: {e}")
def get_balance(self, quote: str = "USDT") -> float | None:
"""Get free balance for quote currency."""
try:
b = self.exchange.fetch_balance()
return float(b.get(quote, {}).get("free", 0) or 0)
except Exception as e:
log.error(f"Balance fetch failed: {e}")
return None
def get_position(self, symbol: str) -> dict | None:
"""Fetch open position for symbol.
Returns dict with keys: size, side, entryPrice, or None if no position.
"""
self._ensure_markets()
try:
positions = self.exchange.fetch_positions([symbol])
for p in positions:
size = abs(float(p.get("contracts", 0) or 0))
if size > 0:
return {
"size": size,
"side": p.get("side"), # "long" or "short"
"entryPrice": float(p.get("entryPrice", 0) or 0),
"unrealizedPnl": float(p.get("unrealizedPnl", 0) or 0),
}
return None
except Exception as e:
log.error(f"Fetch position {symbol} failed: {e}")
return None
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 open_long(self, symbol: str, quote_amount: float) -> dict | None:
"""Open long position with quote_amount USDT."""
self._ensure_markets()
self.ensure_leverage(symbol)
return self._open(symbol, "buy", quote_amount)
def open_short(self, symbol: str, quote_amount: float) -> dict | None:
"""Open short position with quote_amount USDT."""
self._ensure_markets()
self.ensure_leverage(symbol)
return self._open(symbol, "sell", quote_amount)
def _open(self, symbol: str, side: str, quote_amount: float) -> dict | None:
"""Internal: create market order for opening position."""
price = self.get_price(symbol)
if price is None:
return None
market = self.exchange.market(symbol)
amount = quote_amount / price
amount = float(self.exchange.amount_to_precision(symbol, amount))
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"{side.upper()} {symbol}: amount {amount} < min {min_amount}")
return None
if quote_amount < min_cost:
log.error(f"{side.upper()} {symbol}: cost ${quote_amount:.2f} < min ${min_cost}")
return None
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] {side.upper()} {amount} {symbol} @ ~${price:,.2f} "
f"(${quote_amount:.2f}) at {ts}")
return {"dry_run": True, "side": side, "symbol": symbol,
"amount": amount, "price": price, "cost": quote_amount,
"id": "dry_run"}
try:
order = self.exchange.create_order(symbol, "market", side, amount)
filled = float(order.get("filled") or amount)
avg = float(order.get("average") or price)
log.info(f"{side.upper()} OK: {filled} {symbol} @ ${avg:,.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,
amount: float | None = None) -> dict | None:
"""Close position with reduceOnly market order.
side: "long" or "short" (the position side being closed).
"""
self._ensure_markets()
if amount is None:
pos = self.get_position(symbol)
if pos is None:
log.warning(f"CLOSE {symbol}: no position found")
return None
amount = pos["size"]
# To close long, sell; to close short, buy
close_side = "sell" if side == "long" else "buy"
amount = float(self.exchange.amount_to_precision(symbol, amount))
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] CLOSE {close_side.upper()} {amount} {symbol} "
f"(reduceOnly) at {ts}")
return {"dry_run": True, "side": close_side, "symbol": symbol,
"amount": amount, "reduceOnly": True, "id": "dry_run"}
try:
order = self.exchange.create_order(
symbol, "market", close_side, amount,
params={"reduceOnly": True},
)
log.info(f"CLOSE OK: {close_side} {amount} {symbol} "
f"order={order.get('id')}")
return order
except Exception as e:
log.error(f"CLOSE {symbol} FAILED: {e}")
return None
def place_safety_stop(self, symbol: str, side: str, amount: float,
trigger_price: float) -> dict | None:
"""Place stop-market reduceOnly order as safety net.
side: position side ("long" or "short").
For long: trigger_price below entry (sell stop).
For short: trigger_price above entry (buy stop).
"""
self._ensure_markets()
close_side = "sell" if side == "long" else "buy"
amount = float(self.exchange.amount_to_precision(symbol, amount))
trigger_price = float(self.exchange.price_to_precision(symbol, trigger_price))
ts = datetime.now(timezone.utc).isoformat()
if self.dry_run:
log.info(f"[DRY RUN] SAFETY STOP {close_side} {amount} {symbol} "
f"trigger=${trigger_price:,.2f} at {ts}")
return {"dry_run": True, "side": close_side, "type": "stop",
"symbol": symbol, "amount": amount,
"triggerPrice": trigger_price, "id": "dry_run"}
try:
order = self.exchange.create_order(
symbol, "market", close_side, amount,
params={
"triggerPrice": str(trigger_price),
"reduceOnly": True,
},
)
log.info(f"SAFETY STOP placed: {close_side} {amount} {symbol} "
f"trigger=${trigger_price:,.2f} order={order.get('id')}")
return order
except Exception as e:
log.warning(f"SAFETY STOP {symbol} failed: {e}")
return None
def cancel_order(self, symbol: str, order_id: str) -> bool:
"""Cancel an open order."""
if self.dry_run:
log.info(f"[DRY RUN] CANCEL order {order_id} on {symbol}")
return True
try:
self.exchange.cancel_order(order_id, symbol)
log.info(f"CANCEL OK: order {order_id} on {symbol}")
return True
except Exception as e:
log.error(f"CANCEL order {order_id} FAILED: {e}")
return False
+11 -4
View File
@@ -58,10 +58,11 @@ def _get_exchange_balance(cfg) -> float | None:
spot._ensure_markets()
b = spot.exchange.fetch_balance()
total = 0.0
# Build coin list from configured assets + stablecoins
# Build coin list from configured spot assets + stablecoins
coins = {"USDC", "USDT"}
for a in cfg.assets:
coins.add(a.symbol.split("/")[0])
if a.market_type != "futures":
coins.add(a.symbol.split("/")[0])
for coin in sorted(coins):
amt = float(b.get(coin, {}).get("total", 0) or 0)
if amt < 0.0001:
@@ -71,6 +72,8 @@ def _get_exchange_balance(cfg) -> float | None:
else:
price = spot.get_price(f"{coin}/USDC")
total += amt * price if price else 0
# Bybit UTA: futures PnL is reflected in USDT equity
# (already counted above via USDT balance)
return total
except Exception:
return None
@@ -83,7 +86,8 @@ def _get_current_price(cfg, ticker):
for a in cfg.assets:
if a.ticker == ticker:
from .core.signals import fetch_prices_ccxt
prices, _ = fetch_prices_ccxt(a.symbol, "4h", "1d", cfg.exchange)
tf = a.timeframe or cfg.timeframe
prices, _ = fetch_prices_ccxt(a.symbol, tf, "1d", cfg.exchange)
if prices is not None and len(prices) > 0:
return float(prices[-1])
return None
@@ -699,7 +703,10 @@ def format_cycle_report(logs: list[str], cfg=None) -> str:
spot = SpotExecutor(cfg.exchange, leverage=cfg.risk.leverage)
spot._ensure_markets()
b = spot.exchange.fetch_balance()
free_usdc = float(b.get("USDC", {}).get("free", 0) or 0)
# Use USDT if any futures assets, otherwise USDC
has_futures = any(a.market_type == "futures" for a in cfg.assets)
quote_coin = "USDT" if has_futures else "USDC"
free_usdc = float(b.get(quote_coin, {}).get("free", 0) or 0)
total_balance = _get_exchange_balance(cfg)
if total_balance is not None:
in_positions = total_balance - free_usdc
+323
View File
@@ -0,0 +1,323 @@
"""Tests for futures executor, time_exit in bars, routing, and commission."""
from __future__ import annotations
import sys
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remizov_trader.config import AssetConfig, Config, RiskConfig
from remizov_trader.core.risk import calculate_pnl
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def futures_asset():
return AssetConfig(
ticker="UNI-USD", symbol="UNI/USDT:USDT",
market_type="futures", retrain_enabled=False,
K=2, shift=14, timeframe="1h",
weight=0.34, stop_mult=1.25, stop_scale=0.75,
shape_confirm=False, corr_thresh=0.5,
)
@pytest.fixture
def spot_asset():
return AssetConfig(
ticker="BTC-USD", symbol="BTC/USDC",
market_type="spot", retrain_enabled=True,
K=2, shift=14, timeframe="4h",
)
@pytest.fixture
def cfg_futures(futures_asset):
return Config(
mode="live",
initial_capital=16.0,
total_capital=177.0,
currency="USDT",
timeframe="1h",
risk=RiskConfig(
per_trade=0.05, max_position_pct=0.40,
max_open_positions=3, leverage=1,
time_exit=True, safety_stop_pct=0.10,
),
assets=[futures_asset],
)
@pytest.fixture
def cfg_spot(spot_asset):
return Config(
mode="live",
initial_capital=100.0,
timeframe="4h",
risk=RiskConfig(time_exit=False),
assets=[spot_asset],
)
# ---------------------------------------------------------------------------
# TestFuturesExecutor — mock ccxt
# ---------------------------------------------------------------------------
class TestFuturesExecutor:
"""Test FuturesExecutor with mocked ccxt."""
def _make_executor(self):
from remizov_trader.config import ExchangeConfig
mock_exchange = MagicMock()
with patch.dict("sys.modules", {"ccxt": MagicMock(bybit=MagicMock(return_value=mock_exchange))}):
# Re-import to pick up mocked ccxt
import importlib
import remizov_trader.core.futures as fut_mod
importlib.reload(fut_mod)
cfg = ExchangeConfig(testnet=True)
exe = fut_mod.FuturesExecutor(cfg, leverage=1)
return exe, mock_exchange
def test_init_dry_run(self):
exe, _ = self._make_executor()
assert exe.dry_run is True
assert exe.leverage == 1
def test_get_balance(self):
exe, mock_ex = self._make_executor()
mock_ex.fetch_balance.return_value = {"USDT": {"free": 177.0}}
bal = exe.get_balance("USDT")
assert bal == 177.0
def test_get_balance_error(self):
exe, mock_ex = self._make_executor()
mock_ex.fetch_balance.side_effect = Exception("API error")
assert exe.get_balance("USDT") is None
def test_get_position(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.fetch_positions.return_value = [{
"contracts": 10.0,
"side": "long",
"entryPrice": 5.5,
"unrealizedPnl": 0.5,
}]
pos = exe.get_position("UNI/USDT:USDT")
assert pos is not None
assert pos["size"] == 10.0
assert pos["side"] == "long"
assert pos["entryPrice"] == 5.5
def test_get_position_empty(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.fetch_positions.return_value = [{
"contracts": 0, "side": None, "entryPrice": 0, "unrealizedPnl": 0,
}]
assert exe.get_position("UNI/USDT:USDT") is None
def test_open_long_dry_run(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.fetch_ticker.return_value = {"last": 5.0}
mock_ex.market.return_value = {
"limits": {"amount": {"min": 0.1}, "cost": {"min": 1.0}},
}
mock_ex.amount_to_precision.return_value = 10.0
order = exe.open_long("UNI/USDT:USDT", 50.0)
assert order is not None
assert order["dry_run"] is True
assert order["side"] == "buy"
def test_open_short_dry_run(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.fetch_ticker.return_value = {"last": 5.0}
mock_ex.market.return_value = {
"limits": {"amount": {"min": 0.1}, "cost": {"min": 1.0}},
}
mock_ex.amount_to_precision.return_value = 10.0
order = exe.open_short("UNI/USDT:USDT", 50.0)
assert order is not None
assert order["dry_run"] is True
assert order["side"] == "sell"
def test_close_position_dry_run(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.amount_to_precision.return_value = 10.0
mock_ex.fetch_positions.return_value = [{
"contracts": 10.0, "side": "long", "entryPrice": 5.0,
"unrealizedPnl": 0,
}]
order = exe.close_position("UNI/USDT:USDT", "long")
assert order is not None
assert order["reduceOnly"] is True
def test_safety_stop_long(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.amount_to_precision.return_value = 10.0
mock_ex.price_to_precision.return_value = 4.5
order = exe.place_safety_stop("UNI/USDT:USDT", "long", 10.0, 4.5)
assert order is not None
assert order["side"] == "sell" # close long = sell
def test_safety_stop_short(self):
exe, mock_ex = self._make_executor()
mock_ex.load_markets.return_value = {}
mock_ex.amount_to_precision.return_value = 10.0
mock_ex.price_to_precision.return_value = 5.5
order = exe.place_safety_stop("UNI/USDT:USDT", "short", 10.0, 5.5)
assert order is not None
assert order["side"] == "buy" # close short = buy
def test_cancel_order_dry_run(self):
exe, _ = self._make_executor()
assert exe.cancel_order("UNI/USDT:USDT", "order123") is True
# ---------------------------------------------------------------------------
# TestTimeExitBars — time exit in bars not days
# ---------------------------------------------------------------------------
class TestTimeExitBars:
"""Test that time_exit works in bars (hours) for sub-daily timeframes."""
def test_1h_time_exit_bars_held(self):
"""With 1h TF, shift=14, K=2: max_hold=12 bars = 12 hours."""
shift = 14
K = 2
max_hold = shift - K # 12 bars
# Position opened 10 hours ago → 10 bars on 1h → not yet
tf_hours = 1
hours_held = 10
bars_held = hours_held / tf_hours
assert bars_held < max_hold
# Position opened 13 hours ago → 13 bars → should exit
hours_held = 13
bars_held = hours_held / tf_hours
assert bars_held >= max_hold
def test_4h_time_exit_bars_held(self):
"""With 4h TF, shift=14, K=2: max_hold=12 bars = 48 hours."""
shift = 14
K = 2
max_hold = shift - K # 12 bars
tf_hours = 4
# 40 hours = 10 bars → not yet
hours_held = 40
bars_held = hours_held / tf_hours
assert bars_held < max_hold
# 50 hours = 12.5 bars → should exit
hours_held = 50
bars_held = hours_held / tf_hours
assert bars_held >= max_hold
# ---------------------------------------------------------------------------
# TestExecutorRouting
# ---------------------------------------------------------------------------
class TestExecutorRouting:
"""Test that futures assets route to FuturesExecutor, spot to SpotExecutor."""
def test_is_futures(self, cfg_futures, futures_asset):
assert cfg_futures.is_futures(futures_asset) is True
def test_is_spot(self, cfg_spot, spot_asset):
assert cfg_spot.is_futures(spot_asset) is False
def test_short_allowed_futures(self, cfg_futures, futures_asset):
"""SHORT signals should NOT be blocked for futures assets."""
# The condition: skip short only if NOT futures
direction = -1
skip = (cfg_futures.mode == "live" and direction == -1
and not cfg_futures.is_futures(futures_asset))
assert skip is False
def test_short_blocked_spot(self, cfg_spot, spot_asset):
"""SHORT signals should be blocked for spot assets in live mode."""
direction = -1
skip = (cfg_spot.mode == "live" and direction == -1
and not cfg_spot.is_futures(spot_asset))
assert skip is True
def test_retrain_disabled(self, futures_asset):
assert futures_asset.retrain_enabled is False
def test_retrain_enabled_spot(self, spot_asset):
assert spot_asset.retrain_enabled is True
# ---------------------------------------------------------------------------
# TestCommission
# ---------------------------------------------------------------------------
class TestCommission:
"""Test commission rates for spot vs futures."""
def test_futures_commission(self, cfg_futures, futures_asset):
assert cfg_futures.commission_for(futures_asset) == 0.00055
def test_spot_commission(self, cfg_spot, spot_asset):
assert cfg_spot.commission_for(spot_asset) == 0.001
def test_pnl_with_futures_commission(self):
"""Futures commission 0.055% should be lower than spot 0.1%."""
entry, exit_p = 5.0, 5.5
pos_size, pos_value = 10.0, 50.0
pnl_futures, _ = calculate_pnl(entry, exit_p, 1, pos_size, pos_value,
commission=0.00055)
pnl_spot, _ = calculate_pnl(entry, exit_p, 1, pos_size, pos_value,
commission=0.001)
# Futures should have higher net PnL (lower commission)
assert pnl_futures > pnl_spot
def test_pnl_short_direction(self):
"""Short PnL: profit when price goes down."""
entry, exit_p = 5.5, 5.0
pos_size, pos_value = 10.0, 55.0
pnl, pct = calculate_pnl(entry, exit_p, -1, pos_size, pos_value,
commission=0.00055)
assert pnl > 0 # price went down, short = profit
# ---------------------------------------------------------------------------
# TestReconcileFutures
# ---------------------------------------------------------------------------
class TestReconcileFutures:
"""Test reconcile_positions with futures."""
def test_config_market_type_default(self):
"""Default market_type should be 'spot'."""
a = AssetConfig(ticker="X", symbol="X/USDT")
assert a.market_type == "spot"
def test_config_futures_symbol(self, futures_asset):
"""Futures symbol format: COIN/USDT:USDT."""
assert ":USDT" in futures_asset.symbol
def test_config_loads_new_fields(self):
"""Ensure AssetConfig accepts market_type and retrain_enabled."""
a = AssetConfig(
ticker="SUI-USD", symbol="SUI/USDT:USDT",
market_type="futures", retrain_enabled=False,
)
assert a.market_type == "futures"
assert a.retrain_enabled is False