Files
remizov-trader/tests/test_executor.py
T
anorandClaude Opus 4.6 db17365bbb feat: тесты (71) + backtest long-only для честных спот-результатов
- tests/test_core.py: 50 тестов (risk, state, reconciliation)
- tests/test_executor.py: 21 тест (SHORT skip, cooldown, CB, reconcile, update_stops, balance sync)
- backtest_prod.py: LONG_ONLY=True по умолчанию (шорты на споте невозможны), NEAR cd=3

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 21:50:05 +10:00

447 lines
17 KiB
Python

"""Tests for executor logic — signal filtering, position checks, reconciliation."""
from __future__ import annotations
import sqlite3
import sys
from datetime import date, timedelta
from pathlib import Path
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from remizov_trader.config import AssetConfig, Config, ModelConfig, RiskConfig
from remizov_trader.core.risk import (
calculate_pnl,
is_stopped,
update_trailing_stop,
)
from remizov_trader.state import (
close_position,
get_open_position,
init_db,
open_position,
update_asset,
update_position,
upsert_asset,
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
init_db(conn)
yield conn
conn.close()
@pytest.fixture
def cfg_live():
"""Live config with 3 spot assets."""
return Config(
mode="live",
initial_capital=84.0,
total_capital=254.0,
timeframe="4h",
risk=RiskConfig(
per_trade=0.05, max_position_pct=0.40,
max_open_positions=3, leverage=1,
time_exit=False, safety_stop_pct=0.10,
),
assets=[
AssetConfig(ticker="UNI-USD", symbol="UNI/USDC", K=2, shift=14,
lr=0.005, stop_mult=1.25, stop_scale=0.75,
cooldown_bars=3, shape_confirm=False, weight=0.34),
AssetConfig(ticker="ATOM-USD", symbol="ATOM/USDC", K=3, shift=14,
lr=0.005, stop_mult=0.75, stop_scale=1.0,
cooldown_bars=3, shape_confirm=False, weight=0.33),
AssetConfig(ticker="NEAR-USD", symbol="NEAR/USDC", K=2, shift=16,
lr=0.01, stop_mult=1.0, stop_scale=1.0,
cooldown_bars=3, shape_confirm=False, weight=0.33),
],
)
@pytest.fixture
def cfg_paper():
"""Paper config for non-live tests."""
return Config(
mode="paper",
initial_capital=100.0,
timeframe="4h",
risk=RiskConfig(per_trade=0.05, max_position_pct=0.40, leverage=1),
assets=[
AssetConfig(ticker="UNI-USD", symbol="UNI/USDC", K=2, shift=14,
cooldown_bars=3, shape_confirm=False, weight=0.34),
],
)
# ===========================================================================
# SHORT on spot — skip
# ===========================================================================
class TestSpotShortSkip:
"""Live spot mode must skip SHORT signals."""
def test_short_signal_skipped_in_live_mode(self, db, cfg_live):
"""When model says SHORT on spot, bot should skip (can't short spot)."""
# This tests the logic at executor.py:505-510
# Simulating: direction == -1 and cfg.mode == "live"
mode = cfg_live.mode
direction = -1 # SHORT
assert mode == "live"
assert direction == -1
# The condition that triggers skip:
skip = (mode == "live" and direction == -1)
assert skip is True
def test_long_signal_not_skipped_in_live_mode(self):
"""LONG signals should pass through in live mode."""
mode = "live"
direction = 1
skip = (mode == "live" and direction == -1)
assert skip is False
def test_short_allowed_in_paper_mode(self):
"""Paper mode allows SHORT (for backtesting)."""
mode = "paper"
direction = -1
skip = (mode == "live" and direction == -1)
assert skip is False
# ===========================================================================
# Cooldown after stop
# ===========================================================================
class TestCooldownAfterStop:
"""After a stop-loss, bot should wait cooldown_bars before next signal."""
def test_cooldown_blocks_signal(self):
"""Within cooldown period, signal should be skipped."""
last_stop_date = str(date.today())
current_date = str(date.today()) # same day
tf_hours = 4
days_since = 0
candles_since = days_since * 24 // tf_hours # 0
cooldown_bars = 3
assert candles_since < cooldown_bars # should skip
def test_cooldown_expired_allows_signal(self):
"""After cooldown period expires, signal should proceed."""
last_stop_date = str(date.today() - timedelta(days=2))
current_date = str(date.today())
tf_hours = 4
days_since = 2
candles_since = days_since * 24 // tf_hours # 12
cooldown_bars = 3
assert candles_since >= cooldown_bars # should proceed
def test_cooldown_minus_one_uses_shift(self):
"""cooldown_bars=-1 means use shift as cooldown."""
cooldown_bars = -1
shift = 16
effective_cooldown = cooldown_bars if cooldown_bars >= 0 else shift
assert effective_cooldown == 16
# ===========================================================================
# Circuit breaker
# ===========================================================================
class TestCircuitBreaker:
"""Circuit breaker pauses trading during high volatility or drawdown."""
def test_cb_blocks_new_signals(self, db):
"""When CB is active, no new positions should open."""
upsert_asset(db, "UNI-USD", 84.0)
update_asset(db, "UNI-USD", cb_active=1, cb_reason="atr_spike")
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
assert asset["cb_active"] == 1
# In run_cycle: if pos is None and not cb_active → check signal
# If cb_active → skip
should_check_signal = (not bool(asset["cb_active"]))
assert should_check_signal is False
def test_cb_does_not_block_stop_checks(self, db):
"""CB should NOT prevent checking/closing existing positions."""
upsert_asset(db, "UNI-USD", 84.0)
update_asset(db, "UNI-USD", cb_active=1)
pos_id = open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
best_price=4.0, pos_size=20.0, pos_value=80.0,
)
# Position should still be checkable
pos = get_open_position(db, "UNI-USD")
assert pos is not None
# The check_position function is called regardless of CB state
# CB only blocks _check_signal
# ===========================================================================
# Reconciliation with exchange
# ===========================================================================
class TestReconcilePositions:
"""reconcile_positions syncs DB with actual exchange balances."""
def test_skipped_in_paper_mode(self, db, cfg_paper):
"""Reconciliation should not run in paper mode."""
from remizov_trader.core.executor import reconcile_positions
logs = reconcile_positions(db, cfg_paper)
assert logs == []
def test_external_close_detected(self, db, cfg_live):
"""If user closes position on exchange, DB should be updated."""
upsert_asset(db, "UNI-USD", 84.0)
pos_id = open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
best_price=4.0, pos_size=22.0, pos_value=88.0,
safety_stop_order_id="fake_order_123",
)
# Mock exchange: UNI balance = 0 (user sold)
mock_spot = MagicMock()
mock_spot.get_balance.return_value = 0.0
mock_spot.get_price.return_value = 4.10
mock_spot.cancel_order.return_value = True
from remizov_trader.core import executor as exc_mod
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
from remizov_trader.core.executor import reconcile_positions
logs = reconcile_positions(db, cfg_live)
# Position should be closed
assert get_open_position(db, "UNI-USD") is None
assert any("RECONCILE" in log and "externally" in log for log in logs)
# Safety stop should be cancelled
mock_spot.cancel_order.assert_called_once_with("UNI/USDC", "fake_order_123")
# Asset equity should be updated
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
assert asset["trades_count"] == 1
def test_size_adjusted_when_different(self, db, cfg_live):
"""If exchange has different size than DB, update DB."""
upsert_asset(db, "UNI-USD", 84.0)
pos_id = open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
best_price=4.0, pos_size=22.0, pos_value=88.0,
)
# Mock exchange: UNI balance = 18.0 (partial close)
mock_spot = MagicMock()
mock_spot.get_balance.return_value = 18.0
mock_spot.get_price.return_value = 4.05
from remizov_trader.core import executor as exc_mod
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
from remizov_trader.core.executor import reconcile_positions
logs = reconcile_positions(db, cfg_live)
pos = get_open_position(db, "UNI-USD")
assert pos["pos_size"] == pytest.approx(18.0)
assert pos["pos_value"] == pytest.approx(18.0 * 4.05)
assert any("size adjusted" in log for log in logs)
def test_no_change_when_position_matches(self, db, cfg_live):
"""If exchange and DB agree, no reconciliation actions."""
upsert_asset(db, "UNI-USD", 84.0)
open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
best_price=4.0, pos_size=22.0, pos_value=88.0,
)
# Mock exchange: UNI balance matches DB
mock_spot = MagicMock()
mock_spot.get_balance.return_value = 22.0
from remizov_trader.core import executor as exc_mod
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
from remizov_trader.core.executor import reconcile_positions
logs = reconcile_positions(db, cfg_live)
assert logs == [] # no changes needed
assert get_open_position(db, "UNI-USD") is not None # still open
# ===========================================================================
# Update stops (trailing stop + safety stop on exchange)
# ===========================================================================
class TestUpdateStops:
"""update_stops cycle should refresh trailing stops and safety orders."""
def test_skipped_in_paper_mode(self, db, cfg_paper):
from remizov_trader.core.executor import update_stops
logs = update_stops(db, cfg_paper)
assert logs == []
def test_trailing_stop_updated_when_price_rises(self, db, cfg_live):
"""If price rose, trailing stop should move up."""
upsert_asset(db, "UNI-USD", 84.0)
pos_id = open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=3.8, stop_dist=0.2,
best_price=4.0, pos_size=22.0, pos_value=88.0,
safety_stop_order_id="old_stop_123",
)
# Mock exchange: price went up to 4.30
mock_spot = MagicMock()
mock_spot.get_balance.return_value = 22.0 # reconcile: position exists
mock_spot.get_price.return_value = 4.30
mock_spot.cancel_order.return_value = True
mock_spot.place_safety_stop.return_value = {"id": "new_stop_456"}
from remizov_trader.core import executor as exc_mod
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
from remizov_trader.core.executor import update_stops
logs = update_stops(db, cfg_live)
pos = get_open_position(db, "UNI-USD")
# best_price should be 4.30, stop should be 4.30 - 0.2 = 4.10
assert pos["best_price"] == pytest.approx(4.30)
assert pos["stop_price"] == pytest.approx(4.10)
assert pos["safety_stop_order_id"] == "new_stop_456"
# Old safety stop should be cancelled
mock_spot.cancel_order.assert_called_with("UNI/USDC", "old_stop_123")
def test_no_update_when_price_drops(self, db, cfg_live):
"""If price dropped, trailing stop should NOT move down."""
upsert_asset(db, "UNI-USD", 84.0)
upsert_asset(db, "ATOM-USD", 84.0)
upsert_asset(db, "NEAR-USD", 84.0)
# best=4.2, dist=0.2 → stop should already be at 4.0
# Set stop=4.0 (consistent with trailing logic)
open_position(
db, ticker="UNI-USD", direction=1, entry_price=4.0,
entry_date="2026-03-13", stop_price=4.0, stop_dist=0.2,
best_price=4.2, pos_size=22.0, pos_value=88.0,
)
# Mock exchange: price dropped to 4.05 (above stop 4.0, below best 4.2)
mock_spot = MagicMock()
mock_spot.get_balance.return_value = 22.0
mock_spot.get_price.return_value = 4.05
mock_spot.place_safety_stop.return_value = None
from remizov_trader.core import executor as exc_mod
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
from remizov_trader.core.executor import update_stops
logs = update_stops(db, cfg_live)
pos = get_open_position(db, "UNI-USD")
assert pos["stop_price"] == pytest.approx(4.0) # unchanged — price didn't exceed best
assert pos["best_price"] == pytest.approx(4.2) # unchanged
# ===========================================================================
# Balance sync on deposit/withdrawal
# ===========================================================================
class TestBalanceSync:
"""When deposit/withdrawal detected, equity should be adjusted."""
def test_withdrawal_adjusts_equity_proportionally(self, db):
"""After withdrawal, equity of all assets should decrease proportionally."""
upsert_asset(db, "UNI-USD", 100.0)
upsert_asset(db, "ATOM-USD", 80.0)
upsert_asset(db, "NEAR-USD", 70.0)
total = 250.0
# Simulate withdrawal of $50
withdrawal = -50.0
for ticker in ["UNI-USD", "ATOM-USD", "NEAR-USD"]:
asset = dict(db.execute(
"SELECT * FROM assets WHERE ticker=?", (ticker,)
).fetchone())
share = asset["equity"] / total
adj = withdrawal * share
new_eq = max(asset["equity"] + adj, 0.0)
update_asset(db, ticker, equity=new_eq)
uni = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
atom = dict(db.execute("SELECT * FROM assets WHERE ticker='ATOM-USD'").fetchone())
near = dict(db.execute("SELECT * FROM assets WHERE ticker='NEAR-USD'").fetchone())
# UNI: 100 - 50*(100/250) = 100 - 20 = 80
assert uni["equity"] == pytest.approx(80.0)
# ATOM: 80 - 50*(80/250) = 80 - 16 = 64
assert atom["equity"] == pytest.approx(64.0)
# NEAR: 70 - 50*(70/250) = 70 - 14 = 56
assert near["equity"] == pytest.approx(56.0)
new_total = uni["equity"] + atom["equity"] + near["equity"]
assert new_total == pytest.approx(200.0)
# ===========================================================================
# Position check — stop and time exit
# ===========================================================================
class TestPositionCheck:
"""Tests for position close conditions."""
def test_stop_triggered(self):
"""Price below stop should trigger close."""
assert is_stopped(3.70, 3.80, direction=1) is True
def test_stop_not_triggered(self):
"""Price above stop should not trigger close."""
assert is_stopped(4.10, 3.80, direction=1) is False
def test_time_exit_disabled(self, cfg_live):
"""With time_exit=False, position held until stop."""
assert cfg_live.risk.time_exit is False
# When time_exit is False, the condition `if cfg.risk.time_exit` is False
# so time_exit will never trigger
def test_trailing_stop_ratchets_with_price(self):
"""Trailing stop should follow price up for long."""
best = 4.0
stop = 3.8
dist = 0.2
# Price goes to 4.3
new_best, new_stop = update_trailing_stop(4.3, best, stop, dist, 1)
assert new_best == 4.3
assert new_stop == pytest.approx(4.1)
# Price drops to 4.1 — stop stays
new_best2, new_stop2 = update_trailing_stop(4.1, new_best, new_stop, dist, 1)
assert new_best2 == 4.3
assert new_stop2 == pytest.approx(4.1) # unchanged
def test_pnl_on_stop_close(self):
"""PnL calculation on stop-loss close."""
pnl_net, pnl_pct = calculate_pnl(
entry_price=4.001, exit_price=3.976,
direction=1, pos_size=22.45, pos_value=89.84,
)
# gross = 22.45 * (3.976 - 4.001) = 22.45 * (-0.025) = -0.56125
# commission = 89.84 * 0.001 * 2 = 0.17968
# net = -0.56125 - 0.17968 = -0.74093
assert pnl_net < 0
assert pnl_pct < 0