fix: utcnow() naive/aware crash + перепись тестов на интеграционные

- executor.py: utcnow() → now(utc) + ensure entry_dt is aware
  (предотвращает TypeError при aware created_at)
- test_executor.py: все тесты переписаны — вызывают реальные
  _check_signal, _check_position, run_cycle с мокнутой моделью/биржей
  Раньше тесты проверяли арифметику в изоляции (assert 0 < 3)
- 21 интеграционный тест включая regression на cooldown 1h

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-15 04:22:02 +10:00
co-authored by Claude Opus 4.6
parent 59eadc9f9c
commit 91234187ff
2 changed files with 465 additions and 228 deletions
+6 -1
View File
@@ -384,7 +384,12 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
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
from datetime import timezone as tz
now_utc = dt_cls.now(tz.utc)
# Ensure both are aware for subtraction
if entry_dt.tzinfo is None:
entry_dt = entry_dt.replace(tzinfo=tz.utc)
hours_held = (now_utc - entry_dt).total_seconds() / 3600
bars_held = hours_held / tf_hours
# Check stop FIRST (before trailing update, matches backtest)
+459 -227
View File
@@ -1,10 +1,10 @@
"""Tests for executor logic — signal filtering, position checks, reconciliation."""
"""Integration tests for executor — calls real prod functions with mocked exchange/model."""
from __future__ import annotations
import sqlite3
import sys
from datetime import date, timedelta
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -85,166 +85,468 @@ def cfg_paper():
)
# ===========================================================================
# SHORT on spot — skip
# ===========================================================================
@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",
),
],
)
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
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)
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 _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 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
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 after stop
# Cooldown — calls real _check_signal
# ===========================================================================
class TestCooldownAfterStop:
"""After a stop-loss, bot should wait cooldown_bars before next signal."""
class TestCooldownIntegration:
"""Cooldown tests that call real _check_signal."""
def _calc_cooldown(self, last_stop_iso: str, tf_hours: int):
"""Replicate prod cooldown logic (hours-based)."""
from datetime import datetime as dt_cls, timezone as tz
try:
stop_dt = dt_cls.fromisoformat(last_stop_iso)
if stop_dt.tzinfo is None:
stop_dt = stop_dt.replace(tzinfo=tz.utc)
except (ValueError, TypeError):
stop_dt = dt_cls.combine(date.fromisoformat(last_stop_iso),
dt_cls.min.time(), tzinfo=tz.utc)
hours_since = (dt_cls.now(tz.utc) - stop_dt).total_seconds() / 3600
return int(hours_since / tf_hours)
def test_cooldown_blocks_signal(self):
"""Within cooldown period, signal should be skipped."""
from datetime import datetime as dt_cls, timezone as tz
# Stop happened 1 hour ago
last_stop = (dt_cls.now(tz.utc) - timedelta(hours=1)).isoformat()
candles_since = self._calc_cooldown(last_stop, tf_hours=1)
assert candles_since < 3 # 1h < 3 bars → should skip
def test_cooldown_expired_allows_signal(self):
"""After cooldown period expires, signal should proceed."""
from datetime import datetime as dt_cls, timezone as tz
# Stop happened 5 hours ago, cooldown=3 bars on 1h TF
last_stop = (dt_cls.now(tz.utc) - timedelta(hours=5)).isoformat()
candles_since = self._calc_cooldown(last_stop, tf_hours=1)
assert candles_since >= 3 # 5h >= 3 bars → should proceed
def test_cooldown_1h_not_stuck_for_full_day(self):
"""REGRESSION: cooldown must NOT block for 24h on 1h TF.
Old bug: cooldown used .days (whole days), so on 1h TF with
cooldown_bars=3, bot waited 24h instead of 3h.
"""
from datetime import datetime as dt_cls, timezone as tz
# Stop 4 hours ago — should be past cooldown_bars=3 on 1h TF
last_stop = (dt_cls.now(tz.utc) - timedelta(hours=4)).isoformat()
candles_since = self._calc_cooldown(last_stop, tf_hours=1)
assert candles_since >= 3, \
f"4h after stop on 1h TF = {candles_since} candles, expected >= 3"
def test_cooldown_legacy_date_format(self):
"""Legacy last_stop_date as date string should still work."""
from datetime import datetime as dt_cls, timezone as tz
# Legacy: stored as date "2026-03-13" (2 days ago)
last_stop = str(date.today() - timedelta(days=2))
candles_since = self._calc_cooldown(last_stop, tf_hours=4)
assert candles_since >= 3 # 2 days = 48h / 4h = 12 candles >= 3
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")
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())
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."""
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)
update_asset(db, "UNI-USD", cb_active=1)
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,
)
# 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
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
# ===========================================================================
# Reconciliation with exchange
# 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:
"""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(
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
@@ -255,27 +557,21 @@ class TestReconcilePositions:
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(
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
@@ -291,7 +587,6 @@ class TestReconcilePositions:
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,
@@ -299,7 +594,6 @@ class TestReconcilePositions:
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
@@ -308,12 +602,12 @@ class TestReconcilePositions:
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
assert logs == []
assert get_open_position(db, "UNI-USD") is not None
# ===========================================================================
# Update stops (trailing stop + safety stop on exchange)
# Update stops — unchanged, already integration tests
# ===========================================================================
class TestUpdateStops:
@@ -325,18 +619,16 @@ class TestUpdateStops:
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(
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_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"}
@@ -347,28 +639,21 @@ class TestUpdateStops:
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
@@ -380,95 +665,42 @@ class TestUpdateStops:
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
assert pos["stop_price"] == pytest.approx(4.0)
assert pos["best_price"] == pytest.approx(4.2)
# ===========================================================================
# Balance sync on deposit/withdrawal
# Stop last_stop_date written as ISO datetime (not date)
# ===========================================================================
class TestBalanceSync:
"""When deposit/withdrawal detected, equity should be adjusted."""
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
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,
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,
)
# 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
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