Бот теперь спрашивает биржу "что открыто?" перед каждым решением. DB → журнал для trailing state, а не source of truth. - _get_exchange_position: получает позицию с биржи (futures/spot/paper) - _adopt_orphan: биржа имеет, DB нет → создаёт запись (только futures) - _close_phantom: DB имеет, биржа нет → закрывает с Bybit PnL - _sync_position_size: синхронизирует size при расхождении >2% - _inline_reconcile: оркестрирует три предыдущие функции - run_cycle/update_stops: exchange-first → inline reconcile → решения - Удалён reconcile_positions (логика встроена в основной flow) - 8 новых тестов, все 55 проходят Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
912 lines
36 KiB
Python
912 lines
36 KiB
Python
"""Integration tests for executor — calls real prod functions with mocked exchange/model."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
import sys
|
|
from datetime import date, datetime, timedelta, timezone
|
|
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),
|
|
],
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def cfg_futures_1h():
|
|
"""Futures 1h config for testing cooldown, time_exit, SHORT."""
|
|
return Config(
|
|
mode="paper",
|
|
initial_capital=60.0,
|
|
timeframe="1h",
|
|
risk=RiskConfig(
|
|
per_trade=0.05, max_position_pct=0.40,
|
|
max_open_positions=3, leverage=1,
|
|
time_exit=True,
|
|
),
|
|
assets=[
|
|
AssetConfig(
|
|
ticker="UNI-USD", symbol="UNI/USDT:USDT",
|
|
market_type="futures", retrain_enabled=False,
|
|
K=2, shift=14, lr=0.005, stop_mult=1.25, stop_scale=0.75,
|
|
cooldown_bars=3, shape_confirm=False, weight=0.34,
|
|
timeframe="1h",
|
|
),
|
|
],
|
|
)
|
|
|
|
|
|
def _make_prices(n=200, base=4.0, noise=0.02):
|
|
"""Generate synthetic price series."""
|
|
np.random.seed(42)
|
|
return base + np.cumsum(np.random.randn(n) * noise)
|
|
|
|
|
|
def _make_dates(n=200):
|
|
"""Generate date list matching prices."""
|
|
start = date(2025, 1, 1)
|
|
return [start + timedelta(days=i) for i in range(n)]
|
|
|
|
|
|
def _mock_model():
|
|
"""Create mock that replaces model_mod.load_model and predict."""
|
|
mock_mdl = MagicMock()
|
|
# predict returns array with upward trend (LONG signal)
|
|
def fake_predict(mdl, norm_input):
|
|
n = len(norm_input) + 14 # window + shift
|
|
return np.linspace(0, 1, n)
|
|
return mock_mdl, fake_predict
|
|
|
|
|
|
def _mock_model_short():
|
|
"""Model that produces SHORT signal (downward trend)."""
|
|
mock_mdl = MagicMock()
|
|
def fake_predict(mdl, norm_input):
|
|
n = len(norm_input) + 14
|
|
return np.linspace(1, 0, n) # downward
|
|
return mock_mdl, fake_predict
|
|
|
|
|
|
# ===========================================================================
|
|
# Cooldown — calls real _check_signal
|
|
# ===========================================================================
|
|
|
|
class TestCooldownIntegration:
|
|
"""Cooldown tests that call real _check_signal."""
|
|
|
|
def test_cooldown_blocks_on_1h_tf(self, db, cfg_futures_1h):
|
|
"""After stop 1h ago on 1h TF, cooldown_bars=3 should SKIP."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
# Simulate stop 1 hour ago
|
|
stop_time = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
|
update_asset(db, "UNI-USD", last_stop_date=stop_time)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_futures_1h.assets[0], cfg_futures_1h)
|
|
assert result is not None
|
|
assert "cooldown" in result
|
|
assert "SKIP" in result
|
|
|
|
def test_cooldown_allows_after_enough_hours(self, db, cfg_futures_1h):
|
|
"""After stop 4h ago on 1h TF, cooldown_bars=3 should ALLOW."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
# Simulate stop 4 hours ago (> cooldown_bars=3)
|
|
stop_time = (datetime.now(timezone.utc) - timedelta(hours=4)).isoformat()
|
|
update_asset(db, "UNI-USD", last_stop_date=stop_time)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model()
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod:
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_futures_1h.assets[0], cfg_futures_1h)
|
|
|
|
# Should NOT be a cooldown skip
|
|
assert result is None or "cooldown" not in result
|
|
|
|
def test_cooldown_regression_not_stuck_24h(self, db, cfg_futures_1h):
|
|
"""REGRESSION: 1h TF cooldown=3 must NOT wait 24h."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
# Stop 5 hours ago — well past cooldown=3 on 1h
|
|
stop_time = (datetime.now(timezone.utc) - timedelta(hours=5)).isoformat()
|
|
update_asset(db, "UNI-USD", last_stop_date=stop_time)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model()
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod:
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_futures_1h.assets[0], cfg_futures_1h)
|
|
|
|
# Must not be "cooldown ... SKIP"
|
|
if result:
|
|
assert "cooldown" not in result, \
|
|
f"5h after stop on 1h TF should not be blocked: {result}"
|
|
|
|
def test_cooldown_legacy_date_format(self, db, cfg_futures_1h):
|
|
"""Legacy last_stop_date as date string '2026-03-13' still works."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
# Legacy format: date string 2 days ago
|
|
update_asset(db, "UNI-USD", last_stop_date=str(date.today() - timedelta(days=2)))
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model()
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod:
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
# Should not crash on legacy date format
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_futures_1h.assets[0], cfg_futures_1h)
|
|
|
|
# 2 days ago = 48h, cooldown=3 on 1h → 48 candles → should pass
|
|
if result:
|
|
assert "cooldown" not in result
|
|
|
|
|
|
# ===========================================================================
|
|
# SHORT signal — calls real _check_signal
|
|
# ===========================================================================
|
|
|
|
class TestShortSignalRouting:
|
|
"""SHORT signals: blocked on live spot, allowed on live futures."""
|
|
|
|
def test_short_blocked_live_spot(self, db, cfg_live):
|
|
"""Live spot must skip SHORT signals — calls real _check_signal."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 84.0)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model_short()
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod:
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_live.assets[0], cfg_live)
|
|
|
|
assert result is not None
|
|
assert "SHORT" in result and "SKIP" in result
|
|
|
|
def test_short_allowed_live_futures(self, db):
|
|
"""Live futures must allow SHORT signals."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
cfg = Config(
|
|
mode="live",
|
|
initial_capital=60.0,
|
|
timeframe="1h",
|
|
risk=RiskConfig(per_trade=0.05, max_position_pct=0.40, leverage=1),
|
|
assets=[
|
|
AssetConfig(
|
|
ticker="UNI-USD", symbol="UNI/USDT:USDT",
|
|
market_type="futures", K=2, shift=14,
|
|
stop_mult=1.25, stop_scale=0.75,
|
|
cooldown_bars=3, shape_confirm=False, weight=0.34,
|
|
timeframe="1h",
|
|
),
|
|
],
|
|
)
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model_short()
|
|
|
|
mock_executor = MagicMock()
|
|
mock_executor.get_balance.return_value = 100.0
|
|
mock_executor.open_short.return_value = {
|
|
"id": "test_order_1", "side": "sell", "amount": 15.0,
|
|
"price": 4.0, "cost": 60.0, "average": 4.0, "filled": 15.0,
|
|
"fee": {"cost": 0.033, "currency": "USDT"}, "dry_run": False,
|
|
}
|
|
mock_executor.get_position.return_value = {"size": 15.0, "side": "short"}
|
|
mock_executor.place_safety_stop.return_value = {"id": "safety_1"}
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod, \
|
|
patch("remizov_trader.core.executor._get_executor", return_value=mock_executor):
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg.assets[0], cfg)
|
|
|
|
# Should open SHORT, not skip it
|
|
if result:
|
|
assert "SHORT" not in result or "SKIP" not in result
|
|
|
|
def test_long_allowed_live_spot(self, db, cfg_live):
|
|
"""LONG signals should pass through on live spot."""
|
|
from remizov_trader.core.executor import _check_signal
|
|
|
|
upsert_asset(db, "UNI-USD", 84.0)
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
mock_mdl, fake_predict = _mock_model()
|
|
|
|
order_dict = {
|
|
"id": "test_buy_1", "side": "buy", "amount": 20.0,
|
|
"price": 4.0, "cost": 80.0, "average": 4.0, "filled": 20.0,
|
|
"fee": {"cost": 0.08, "currency": "USDC"}, "dry_run": False,
|
|
}
|
|
mock_spot = MagicMock()
|
|
mock_spot.get_balance.side_effect = lambda coin: 100.0
|
|
mock_spot.buy.return_value = order_dict
|
|
mock_spot.get_price.return_value = 4.0
|
|
mock_spot.place_safety_stop.return_value = {"id": "safety_2"}
|
|
|
|
with patch("remizov_trader.core.executor.model_mod") as mock_model_mod, \
|
|
patch("remizov_trader.core.executor._get_executor", return_value=mock_spot):
|
|
mock_model_mod.load_model.return_value = mock_mdl
|
|
mock_model_mod.predict.side_effect = fake_predict
|
|
result = _check_signal(db, "UNI-USD", prices, dates, asset,
|
|
cfg_live.assets[0], cfg_live)
|
|
|
|
# LONG on live spot should succeed (open position)
|
|
if result:
|
|
assert "SKIP" not in result or "SHORT" not in result
|
|
|
|
|
|
# ===========================================================================
|
|
# Position check — calls real _check_position
|
|
# ===========================================================================
|
|
|
|
class TestCheckPosition:
|
|
"""Tests that call real _check_position with mocked time."""
|
|
|
|
def test_stop_closes_position(self, db, cfg_paper):
|
|
"""Price below stop triggers close via _check_position."""
|
|
from remizov_trader.core.executor import _check_position
|
|
|
|
upsert_asset(db, "UNI-USD", 100.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=20.0, pos_value=80.0,
|
|
)
|
|
pos = get_open_position(db, "UNI-USD")
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
# Price dropped below stop
|
|
prices = _make_prices(200, base=3.7, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
result = _check_position(db, pos, prices, dates, asset,
|
|
cfg_paper.assets[0], cfg_paper)
|
|
|
|
# Position should be closed
|
|
assert result is not None
|
|
assert "CLOSED" in result or "stop" in result.lower()
|
|
assert get_open_position(db, "UNI-USD") is None
|
|
|
|
def test_no_close_when_price_above_stop(self, db, cfg_paper):
|
|
"""Price above stop — position stays open."""
|
|
from remizov_trader.core.executor import _check_position
|
|
|
|
upsert_asset(db, "UNI-USD", 100.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=20.0, pos_value=80.0,
|
|
)
|
|
pos = get_open_position(db, "UNI-USD")
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
# Price above stop
|
|
prices = _make_prices(200, base=4.2, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
result = _check_position(db, pos, prices, dates, asset,
|
|
cfg_paper.assets[0], cfg_paper)
|
|
|
|
# Should NOT close
|
|
assert result is None
|
|
assert get_open_position(db, "UNI-USD") is not None
|
|
|
|
def test_time_exit_closes_position(self, db, cfg_futures_1h):
|
|
"""Time exit: position held > shift-K bars should close."""
|
|
from remizov_trader.core.executor import _check_position
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
# Position opened 13 hours ago, shift=14, K=2, max_hold=12 bars
|
|
created = (datetime.now(timezone.utc) - timedelta(hours=13)).isoformat()
|
|
pos_id = open_position(
|
|
db, ticker="UNI-USD", direction=1, entry_price=4.0,
|
|
entry_date="2026-03-13", stop_price=3.5, stop_dist=0.5,
|
|
best_price=4.0, pos_size=15.0, pos_value=60.0, k_used=2,
|
|
)
|
|
# Set created_at to 13h ago
|
|
db.execute("UPDATE positions SET created_at=? WHERE id=?", (created, pos_id))
|
|
db.commit()
|
|
|
|
pos = get_open_position(db, "UNI-USD")
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
# Price above stop (no stop trigger)
|
|
prices = _make_prices(200, base=4.1, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
result = _check_position(db, pos, prices, dates, asset,
|
|
cfg_futures_1h.assets[0], cfg_futures_1h)
|
|
|
|
assert result is not None
|
|
assert "time" in result.lower() or "CLOSED" in result
|
|
assert get_open_position(db, "UNI-USD") is None
|
|
|
|
def test_trailing_stop_ratchets_up(self, db, cfg_paper):
|
|
"""Trailing stop should move up when price rises."""
|
|
from remizov_trader.core.executor import _check_position
|
|
|
|
cfg_trail = 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,
|
|
trailing_stop=True),
|
|
],
|
|
)
|
|
|
|
upsert_asset(db, "UNI-USD", 100.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=20.0, pos_value=80.0,
|
|
)
|
|
pos = get_open_position(db, "UNI-USD")
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
# Price went up to 4.5 — well above entry and stop
|
|
prices = _make_prices(200, base=4.5, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
result = _check_position(db, pos, prices, dates, asset,
|
|
cfg_trail.assets[0], cfg_trail)
|
|
|
|
# Should NOT close (price above stop)
|
|
assert result is None
|
|
# But stop should have ratcheted up
|
|
pos_after = get_open_position(db, "UNI-USD")
|
|
assert pos_after["stop_price"] > 3.8 # trailing moved up
|
|
assert pos_after["best_price"] > 4.0 # best updated
|
|
|
|
|
|
# ===========================================================================
|
|
# Circuit breaker — calls real run_cycle
|
|
# ===========================================================================
|
|
|
|
class TestCircuitBreakerIntegration:
|
|
"""CB tests using real run_cycle with mocked fetch_prices."""
|
|
|
|
def test_cb_blocks_new_signal_in_run_cycle(self, db, cfg_paper):
|
|
"""When CB is active, run_cycle should skip signal generation."""
|
|
upsert_asset(db, "UNI-USD", 100.0)
|
|
update_asset(db, "UNI-USD", cb_active=1, cb_reason="atr_spike")
|
|
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, "signals") as mock_signals:
|
|
mock_signals.fetch_prices.return_value = (prices, dates)
|
|
from remizov_trader.core.executor import run_cycle
|
|
# Mock circuit breaker to keep it active
|
|
with patch.object(exc_mod.risk, "check_circuit_breaker",
|
|
return_value=(True, "atr_spike", {})):
|
|
logs = run_cycle(db, cfg_paper)
|
|
|
|
# Should see CB skip message, no signal
|
|
log_text = " ".join(logs)
|
|
assert "CB active" in log_text or "cb" in log_text.lower()
|
|
|
|
def test_cb_does_not_block_stop_check(self, db, cfg_paper):
|
|
"""CB active should NOT prevent closing stopped positions."""
|
|
upsert_asset(db, "UNI-USD", 100.0)
|
|
update_asset(db, "UNI-USD", cb_active=1, cb_reason="atr_spike")
|
|
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,
|
|
)
|
|
|
|
# Price below stop
|
|
prices = _make_prices(200, base=3.7, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, "signals") as mock_signals:
|
|
mock_signals.fetch_prices.return_value = (prices, dates)
|
|
with patch.object(exc_mod.risk, "check_circuit_breaker",
|
|
return_value=(True, "atr_spike", {})):
|
|
from remizov_trader.core.executor import run_cycle
|
|
logs = run_cycle(db, cfg_paper)
|
|
|
|
# Position should be closed despite CB active
|
|
assert get_open_position(db, "UNI-USD") is None
|
|
|
|
|
|
# ===========================================================================
|
|
# Reconciliation with exchange — unchanged, already integration tests
|
|
# ===========================================================================
|
|
|
|
class TestReconcilePositions:
|
|
"""Inline reconcile (via _inline_reconcile) syncs DB with exchange."""
|
|
|
|
def test_skipped_in_paper_mode(self, db, cfg_paper):
|
|
"""Paper mode: _inline_reconcile not called (exchange_pos=None)."""
|
|
from remizov_trader.core.executor import _get_exchange_position
|
|
result = _get_exchange_position(cfg_paper, cfg_paper.assets[0])
|
|
assert result is None
|
|
|
|
def test_external_close_detected(self, db, cfg_live):
|
|
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,
|
|
safety_stop_order_id="fake_order_123",
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
|
|
mock_spot = MagicMock()
|
|
mock_spot.get_price.return_value = 4.10
|
|
mock_spot.cancel_order.return_value = True
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
from remizov_trader.core.executor import _close_phantom
|
|
with patch.object(exc_mod, '_get_spot', return_value=mock_spot):
|
|
msg = _close_phantom(db, db_pos, "UNI-USD",
|
|
cfg_live.assets[0], cfg_live)
|
|
|
|
assert get_open_position(db, "UNI-USD") is None
|
|
assert "PHANTOM" in msg and "externally" in msg
|
|
mock_spot.cancel_order.assert_called_once_with("UNI/USDC", "fake_order_123")
|
|
|
|
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):
|
|
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,
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
exchange_pos = {
|
|
"size": 18.0, "side": "long",
|
|
"entryPrice": 4.05, "direction": 1,
|
|
}
|
|
|
|
from remizov_trader.core.executor import _sync_position_size
|
|
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
|
|
|
pos = get_open_position(db, "UNI-USD")
|
|
assert pos["pos_size"] == pytest.approx(18.0)
|
|
assert msg is not None
|
|
assert "SIZE synced" in msg
|
|
|
|
def test_no_change_when_position_matches(self, db, cfg_live):
|
|
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,
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
exchange_pos = {
|
|
"size": 22.0, "side": "long",
|
|
"entryPrice": 4.0, "direction": 1,
|
|
}
|
|
|
|
from remizov_trader.core.executor import _sync_position_size
|
|
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
|
|
|
assert msg is None
|
|
assert get_open_position(db, "UNI-USD") is not None
|
|
|
|
|
|
# ===========================================================================
|
|
# Update stops — unchanged, already integration tests
|
|
# ===========================================================================
|
|
|
|
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):
|
|
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,
|
|
safety_stop_order_id="old_stop_123",
|
|
)
|
|
|
|
mock_spot = MagicMock()
|
|
mock_spot.get_balance.return_value = 22.0
|
|
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")
|
|
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"
|
|
mock_spot.cancel_order.assert_called_with("UNI/USDC", "old_stop_123")
|
|
|
|
def test_no_update_when_price_drops(self, db, cfg_live):
|
|
upsert_asset(db, "UNI-USD", 84.0)
|
|
upsert_asset(db, "ATOM-USD", 84.0)
|
|
upsert_asset(db, "NEAR-USD", 84.0)
|
|
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_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)
|
|
assert pos["best_price"] == pytest.approx(4.2)
|
|
|
|
|
|
# ===========================================================================
|
|
# Stop last_stop_date written as ISO datetime (not date)
|
|
# ===========================================================================
|
|
|
|
class TestStopDateFormat:
|
|
"""When stop triggers, last_stop_date must be ISO datetime."""
|
|
|
|
def test_stop_writes_iso_datetime(self, db, cfg_paper):
|
|
"""After stop close, last_stop_date should be full ISO datetime."""
|
|
from remizov_trader.core.executor import _check_position
|
|
|
|
upsert_asset(db, "UNI-USD", 100.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=20.0, pos_value=80.0,
|
|
)
|
|
pos = get_open_position(db, "UNI-USD")
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
|
|
# Price below stop
|
|
prices = _make_prices(200, base=3.7, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
_check_position(db, pos, prices, dates, asset,
|
|
cfg_paper.assets[0], cfg_paper)
|
|
|
|
asset_after = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
last_stop = asset_after["last_stop_date"]
|
|
assert last_stop is not None
|
|
# Must be ISO datetime, not just date
|
|
assert "T" in last_stop, f"Expected ISO datetime, got: {last_stop}"
|
|
# Must be parseable
|
|
dt = datetime.fromisoformat(last_stop)
|
|
assert dt.tzinfo is not None # must be timezone-aware
|
|
|
|
|
|
# ===========================================================================
|
|
# Exchange as Source of Truth — new tests
|
|
# ===========================================================================
|
|
|
|
@pytest.fixture
|
|
def cfg_futures_live():
|
|
"""Live futures config for exchange-first tests."""
|
|
return Config(
|
|
mode="live",
|
|
initial_capital=60.0,
|
|
timeframe="1h",
|
|
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/USDT:USDT",
|
|
market_type="futures", retrain_enabled=False,
|
|
K=2, shift=14, lr=0.005, stop_mult=1.25, stop_scale=0.75,
|
|
cooldown_bars=3, shape_confirm=False, weight=0.34,
|
|
timeframe="1h",
|
|
),
|
|
],
|
|
)
|
|
|
|
|
|
class TestExchangeFirst:
|
|
"""Exchange as source of truth — inline reconcile tests."""
|
|
|
|
def test_api_error_skips_asset(self, db, cfg_futures_live):
|
|
"""API_ERROR → skip asset, no crash, no decisions."""
|
|
from remizov_trader.core.executor import _get_exchange_position
|
|
|
|
mock_executor = MagicMock()
|
|
mock_executor.get_position.return_value = "API_ERROR"
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, '_get_futures', return_value=mock_executor):
|
|
result = _get_exchange_position(cfg_futures_live, cfg_futures_live.assets[0])
|
|
|
|
assert result == "API_ERROR"
|
|
|
|
def test_phantom_closed(self, db, cfg_futures_live):
|
|
"""DB open, exchange empty → DB closed with Bybit PnL."""
|
|
from remizov_trader.core.executor import _close_phantom
|
|
|
|
upsert_asset(db, "UNI-USD", 60.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=15.0, pos_value=60.0,
|
|
safety_stop_order_id="position_sl",
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
|
|
mock_executor = MagicMock()
|
|
mock_executor.get_price.return_value = 4.20
|
|
mock_executor.get_closed_pnl.return_value = {
|
|
"exitPrice": 4.20, "entryPrice": 4.0,
|
|
"closedPnl": 2.85, "qty": 15.0, "side": "Buy",
|
|
}
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, '_get_futures', return_value=mock_executor):
|
|
msg = _close_phantom(db, db_pos, "UNI-USD",
|
|
cfg_futures_live.assets[0], cfg_futures_live)
|
|
|
|
assert "PHANTOM" in msg
|
|
assert get_open_position(db, "UNI-USD") is None
|
|
|
|
asset = dict(db.execute("SELECT * FROM assets WHERE ticker='UNI-USD'").fetchone())
|
|
assert asset["trades_count"] == 1
|
|
assert asset["equity"] > 60.0 # profitable close
|
|
|
|
def test_orphan_adopted(self, db, cfg_futures_live):
|
|
"""Exchange open, DB empty → DB record created."""
|
|
from remizov_trader.core.executor import _adopt_orphan
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
exchange_pos = {
|
|
"size": 15.0, "side": "long",
|
|
"entryPrice": 4.0, "direction": 1,
|
|
}
|
|
|
|
msg = _adopt_orphan(db, "UNI-USD", exchange_pos,
|
|
cfg_futures_live.assets[0], cfg_futures_live)
|
|
|
|
assert "ADOPT" in msg
|
|
pos = get_open_position(db, "UNI-USD")
|
|
assert pos is not None
|
|
assert pos["pos_size"] == 15.0
|
|
assert pos["entry_price"] == 4.0
|
|
assert pos["direction"] == 1
|
|
|
|
def test_no_duplicate_open(self, db, cfg_futures_live):
|
|
"""Exchange has position → _check_signal not called (no duplicate)."""
|
|
from remizov_trader.core.executor import run_cycle
|
|
|
|
upsert_asset(db, "UNI-USD", 60.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=15.0, pos_value=60.0,
|
|
)
|
|
|
|
prices = _make_prices(200, base=4.1, noise=0.001)
|
|
dates = _make_dates(len(prices))
|
|
|
|
mock_executor = MagicMock()
|
|
mock_executor.get_position.return_value = {
|
|
"size": 15.0, "side": "long", "entryPrice": 4.0,
|
|
"unrealizedPnl": 1.5,
|
|
}
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, "signals") as mock_signals, \
|
|
patch.object(exc_mod, '_get_futures', return_value=mock_executor), \
|
|
patch.object(exc_mod.risk, "check_circuit_breaker",
|
|
return_value=(False, None, {})):
|
|
mock_signals.fetch_prices.return_value = (prices, dates)
|
|
logs = run_cycle(db, cfg_futures_live)
|
|
|
|
# Should be holding, NOT opening a new signal
|
|
log_text = " ".join(logs)
|
|
assert "SIGNAL" not in log_text
|
|
assert "holding" in log_text or "CLOSED" in log_text
|
|
|
|
def test_paper_mode_unchanged(self, db, cfg_paper):
|
|
"""Paper mode = DB source of truth, no exchange calls."""
|
|
from remizov_trader.core.executor import _get_exchange_position
|
|
|
|
result = _get_exchange_position(cfg_paper, cfg_paper.assets[0])
|
|
assert result is None # paper mode returns None (use DB)
|
|
|
|
def test_inline_reconcile_sync_size(self, db, cfg_futures_live):
|
|
"""Both exist but size diverges → sync from exchange."""
|
|
from remizov_trader.core.executor import _sync_position_size
|
|
|
|
upsert_asset(db, "UNI-USD", 60.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=15.0, pos_value=60.0,
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
|
|
exchange_pos = {
|
|
"size": 12.0, "side": "long",
|
|
"entryPrice": 4.0, "direction": 1,
|
|
}
|
|
|
|
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
|
|
|
assert msg is not None
|
|
assert "SIZE synced" in msg
|
|
pos = get_open_position(db, "UNI-USD")
|
|
assert pos["pos_size"] == pytest.approx(12.0)
|
|
|
|
def test_inline_reconcile_no_sync_when_close(self, db, cfg_futures_live):
|
|
"""Size within 2% → no sync needed."""
|
|
from remizov_trader.core.executor import _sync_position_size
|
|
|
|
upsert_asset(db, "UNI-USD", 60.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=15.0, pos_value=60.0,
|
|
)
|
|
db_pos = get_open_position(db, "UNI-USD")
|
|
|
|
exchange_pos = {
|
|
"size": 15.1, "side": "long",
|
|
"entryPrice": 4.0, "direction": 1,
|
|
}
|
|
|
|
msg = _sync_position_size(db, db_pos, exchange_pos, "UNI-USD")
|
|
assert msg is None # within 2% tolerance
|
|
|
|
def test_run_cycle_exchange_first_skips_on_api_error(self, db, cfg_futures_live):
|
|
"""run_cycle skips asset entirely on API error."""
|
|
from remizov_trader.core.executor import run_cycle
|
|
|
|
upsert_asset(db, "UNI-USD", 60.0)
|
|
prices = _make_prices()
|
|
dates = _make_dates(len(prices))
|
|
|
|
mock_executor = MagicMock()
|
|
mock_executor.get_position.return_value = "API_ERROR"
|
|
|
|
from remizov_trader.core import executor as exc_mod
|
|
with patch.object(exc_mod, "signals") as mock_signals, \
|
|
patch.object(exc_mod, '_get_futures', return_value=mock_executor), \
|
|
patch.object(exc_mod.risk, "check_circuit_breaker",
|
|
return_value=(False, None, {})):
|
|
mock_signals.fetch_prices.return_value = (prices, dates)
|
|
logs = run_cycle(db, cfg_futures_live)
|
|
|
|
log_text = " ".join(logs)
|
|
assert "API error" in log_text
|
|
assert "SIGNAL" not in log_text # no trading decision made
|