"""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.price_to_precision.return_value = 4.5 result = exe.place_safety_stop("UNI/USDT:USDT", "long", 10.0, 4.5) assert result is not None assert result["id"] == "position_sl" # SL on position, not separate order assert result["side"] == "long" def test_safety_stop_short(self): exe, mock_ex = self._make_executor() mock_ex.load_markets.return_value = {} mock_ex.price_to_precision.return_value = 5.5 result = exe.place_safety_stop("UNI/USDT:USDT", "short", 10.0, 5.5) assert result is not None assert result["id"] == "position_sl" assert result["side"] == "short" 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 futures config fields.""" 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