"""Tests for core risk management and state management.""" from __future__ import annotations import sqlite3 import sys from pathlib import Path import numpy as np import pytest sys.path.insert(0, str(Path(__file__).parent.parent / "src")) from remizov_trader.config import CircuitBreakerConfig, RiskConfig from remizov_trader.core.risk import ( calculate_pnl, calculate_position, calculate_stop, compute_atr, is_stopped, kelly_fraction, update_trailing_stop, ) from remizov_trader.state import ( close_position, detect_deposit, get_asset, get_open_position, get_trade_history, init_db, log_balance_snapshot, open_position, update_asset, upsert_asset, ) # --------------------------------------------------------------------------- # Fixtures # --------------------------------------------------------------------------- @pytest.fixture def db(): """In-memory SQLite database with all tables initialized.""" conn = sqlite3.connect(":memory:") conn.row_factory = sqlite3.Row init_db(conn) yield conn conn.close() @pytest.fixture def btc_prices(): """Realistic BTC 4h close prices (~60k range, 100 bars).""" rng = np.random.default_rng(42) base = 60000.0 # Random walk with small steps returns = rng.normal(0, 0.005, 100) prices = base * np.cumprod(1 + returns) return prices @pytest.fixture def risk_cfg(): return RiskConfig(per_trade=0.05, max_position_pct=0.50, leverage=1) @pytest.fixture def risk_cfg_leveraged(): return RiskConfig(per_trade=0.05, max_position_pct=0.50, leverage=3) # =========================================================================== # risk.py tests # =========================================================================== class TestComputeATR: def test_basic_atr(self, btc_prices): """ATR at idx=50 should be a reasonable fraction of price.""" atr = compute_atr(btc_prices, 50, period=14) price = btc_prices[50] assert atr > 0 # ATR should be roughly 0.5%-3% of price for crypto assert atr < price * 0.10 def test_fallback_for_short_history(self, btc_prices): """When idx < period+1, should return 2% of current price.""" atr = compute_atr(btc_prices, 5, period=14) assert atr == pytest.approx(btc_prices[5] * 0.02) def test_different_periods(self, btc_prices): """Longer period ATR should generally be smoother (non-zero).""" atr14 = compute_atr(btc_prices, 80, period=14) atr50 = compute_atr(btc_prices, 80, period=50) assert atr14 > 0 assert atr50 > 0 class TestCalculatePosition: def test_basic_sizing(self, risk_cfg): """Position size respects risk-per-trade limit (not capped).""" # Use values where risk-based size stays under max_position cap: # equity=10000, entry=100 (SOL), stop_dist=50 # risk_amount = 10000 * 0.05 = 500 # pos_size = 500 / 50 = 10, pos_value = 10 * 100 = 1000 # max_pos = 10000 * 0.50 = 5000 → 1000 < 5000 → not capped equity = 10000.0 entry = 100.0 stop_dist = 50.0 pos_size, pos_value = calculate_position(equity, entry, stop_dist, risk_cfg) assert pos_size == pytest.approx(10.0) assert pos_value == pytest.approx(1000.0) def test_max_position_cap(self, risk_cfg): """Position should be capped at max_position_pct of equity.""" equity = 1000.0 entry = 60000.0 stop_dist = 10.0 # very tight stop -> huge position -> should be capped pos_size, pos_value = calculate_position(equity, entry, stop_dist, risk_cfg) max_val = equity * risk_cfg.max_position_pct assert pos_value == pytest.approx(max_val) assert pos_size == pytest.approx(max_val / entry) def test_leverage_increases_buying_power(self, risk_cfg_leveraged): """With 3x leverage, max position = equity * 3 * max_position_pct.""" equity = 1000.0 entry = 60000.0 stop_dist = 10.0 # tight stop -> capped pos_size, pos_value = calculate_position(equity, entry, stop_dist, risk_cfg_leveraged) max_val = equity * 3 * risk_cfg_leveraged.max_position_pct assert pos_value == pytest.approx(max_val) def test_leverage_does_not_change_risk_amount(self, risk_cfg_leveraged): """Risk per trade stays the same regardless of leverage.""" # equity=10000, entry=100, stop_dist=50, leverage=3 # risk_amount = 10000 * 0.05 = 500 # pos_size = 500/50 = 10, pos_value = 1000 # max_pos = 10000 * 3 * 0.50 = 15000 → not capped equity = 10000.0 entry = 100.0 stop_dist = 50.0 pos_size, pos_value = calculate_position(equity, entry, stop_dist, risk_cfg_leveraged) assert pos_size == pytest.approx(500.0 / 50.0) class TestCalculateStop: def test_long_stop_below_entry(self, btc_prices): entry = btc_prices[50] stop_dist, stop_price = calculate_stop(btc_prices, 50, entry, direction=1) assert stop_dist > 0 assert stop_price < entry def test_short_stop_above_entry(self, btc_prices): entry = btc_prices[50] stop_dist, stop_price = calculate_stop(btc_prices, 50, entry, direction=-1) assert stop_dist > 0 assert stop_price > entry def test_min_stop_distance(self, btc_prices): """Stop dist is at least 0.5% of entry.""" entry = btc_prices[50] stop_dist, _ = calculate_stop(btc_prices, 50, entry, direction=1) assert stop_dist >= entry * 0.005 class TestTrailingStop: def test_long_trailing_stop_ratchets_up(self): """Trailing stop on long should only move up.""" stop_price = 58000.0 stop_dist = 1200.0 best = 60000.0 # Price goes up new_best, new_stop = update_trailing_stop(61000.0, best, stop_price, stop_dist, 1) assert new_best == 61000.0 assert new_stop == 61000.0 - 1200.0 assert new_stop > stop_price # ratcheted up def test_long_trailing_stop_does_not_decrease(self): """Trailing stop should never go down on a long.""" stop_price = 59800.0 stop_dist = 1200.0 best = 61000.0 # Price drops new_best, new_stop = update_trailing_stop(59900.0, best, stop_price, stop_dist, 1) assert new_best == 61000.0 # best unchanged assert new_stop == stop_price # stop unchanged def test_short_trailing_stop_ratchets_down(self): """Trailing stop on short should only move down.""" stop_price = 62000.0 stop_dist = 1200.0 best = 60000.0 # Price drops further new_best, new_stop = update_trailing_stop(59000.0, best, stop_price, stop_dist, -1) assert new_best == 59000.0 assert new_stop == 59000.0 + 1200.0 assert new_stop < stop_price # ratcheted down def test_short_trailing_stop_does_not_increase(self): """Trailing stop should never go up on a short.""" stop_price = 60200.0 stop_dist = 1200.0 best = 59000.0 # Price bounces up new_best, new_stop = update_trailing_stop(60100.0, best, stop_price, stop_dist, -1) assert new_best == 59000.0 assert new_stop == stop_price class TestIsStopped: def test_long_stopped(self): assert is_stopped(58000.0, 58500.0, direction=1) is True def test_long_not_stopped(self): assert is_stopped(59000.0, 58500.0, direction=1) is False def test_long_at_stop(self): assert is_stopped(58500.0, 58500.0, direction=1) is True def test_short_stopped(self): assert is_stopped(62000.0, 61500.0, direction=-1) is True def test_short_not_stopped(self): assert is_stopped(61000.0, 61500.0, direction=-1) is False class TestCalculatePnL: def test_profitable_long(self): pnl_net, pnl_pct = calculate_pnl( entry_price=60000.0, exit_price=63000.0, direction=1, pos_size=0.05, pos_value=3000.0, ) # gross = 0.05 * 3000 = 150 # commission = 3000 * 0.001 * 2 = 6 # net = 144 assert pnl_net == pytest.approx(144.0) assert pnl_pct == pytest.approx(144.0 / 3000.0 * 100) def test_losing_long(self): pnl_net, pnl_pct = calculate_pnl( entry_price=60000.0, exit_price=58000.0, direction=1, pos_size=0.05, pos_value=3000.0, ) # gross = 0.05 * (-2000) = -100 # commission = 6 # net = -106 assert pnl_net == pytest.approx(-106.0) assert pnl_pct < 0 def test_profitable_short(self): pnl_net, pnl_pct = calculate_pnl( entry_price=60000.0, exit_price=57000.0, direction=-1, pos_size=0.05, pos_value=3000.0, ) # gross = 0.05 * (57000 - 60000) * (-1) = 150 assert pnl_net == pytest.approx(144.0) def test_zero_pos_value(self): pnl_net, pnl_pct = calculate_pnl(60000.0, 61000.0, 1, 0.0, 0.0) assert pnl_pct == 0.0 def test_custom_commission(self): pnl_net, _ = calculate_pnl( entry_price=60000.0, exit_price=63000.0, direction=1, pos_size=0.05, pos_value=3000.0, commission=0.0005, ) # commission = 3000 * 0.0005 * 2 = 3 assert pnl_net == pytest.approx(150.0 - 3.0) class TestKellyFraction: def test_typical_crypto_stats(self): """Typical crypto momentum: 45% WR, 2:1 RR.""" f = kelly_fraction(win_rate=0.45, avg_win=200.0, avg_loss=100.0) # b = 2.0, f* = (0.45*2 - 0.55)/2 = 0.175, half = 0.0875 assert 0.05 < f < 0.15 def test_high_win_rate(self): f = kelly_fraction(win_rate=0.65, avg_win=150.0, avg_loss=100.0) assert f > 0.05 def test_negative_kelly_clamps_to_minimum(self): """Bad stats should return minimum 1%.""" f = kelly_fraction(win_rate=0.2, avg_win=50.0, avg_loss=100.0) assert f == 0.01 def test_zero_avg_loss_returns_fallback(self): f = kelly_fraction(win_rate=0.5, avg_win=100.0, avg_loss=0.0) assert f == 0.02 def test_zero_win_rate_returns_fallback(self): f = kelly_fraction(win_rate=0.0, avg_win=100.0, avg_loss=100.0) assert f == 0.02 def test_cap_at_max_fraction(self): f = kelly_fraction(win_rate=0.90, avg_win=500.0, avg_loss=10.0, max_fraction=0.15) assert f <= 0.15 # =========================================================================== # state.py tests # =========================================================================== class TestUpsertAsset: def test_insert_new_asset(self, db): upsert_asset(db, "BTC-USD", 500.0) asset = get_asset(db, "BTC-USD") assert asset is not None assert asset["equity"] == 500.0 assert asset["peak_equity"] == 500.0 def test_upsert_does_not_overwrite(self, db): """Second upsert with different equity should NOT overwrite (DO NOTHING).""" upsert_asset(db, "BTC-USD", 500.0) upsert_asset(db, "BTC-USD", 999.0) asset = get_asset(db, "BTC-USD") assert asset["equity"] == 500.0 # unchanged def test_multiple_assets(self, db): upsert_asset(db, "BTC-USD", 500.0) upsert_asset(db, "ETH-USD", 300.0) btc = get_asset(db, "BTC-USD") eth = get_asset(db, "ETH-USD") assert btc["equity"] == 500.0 assert eth["equity"] == 300.0 class TestUpdateAsset: def test_update_equity(self, db): upsert_asset(db, "BTC-USD", 500.0) update_asset(db, "BTC-USD", equity=600.0, peak_equity=600.0) asset = get_asset(db, "BTC-USD") assert asset["equity"] == 600.0 assert asset["peak_equity"] == 600.0 def test_update_cb_fields(self, db): upsert_asset(db, "BTC-USD", 500.0) update_asset(db, "BTC-USD", cb_active=1, cb_reason="drawdown") asset = get_asset(db, "BTC-USD") assert asset["cb_active"] == 1 assert asset["cb_reason"] == "drawdown" def test_update_trade_counters(self, db): upsert_asset(db, "BTC-USD", 500.0) update_asset(db, "BTC-USD", trades_count=5, wins=3, losses=2) asset = get_asset(db, "BTC-USD") assert asset["trades_count"] == 5 assert asset["wins"] == 3 class TestOpenClosePosition: def test_open_and_get(self, db): upsert_asset(db, "BTC-USD", 500.0) pos_id = open_position( db, ticker="BTC-USD", direction=1, entry_price=60000.0, entry_date="2025-01-15", stop_price=58800.0, stop_dist=1200.0, best_price=60000.0, pos_size=0.04, pos_value=2400.0, correlation=0.65, ) assert pos_id > 0 pos = get_open_position(db, "BTC-USD") assert pos is not None assert pos["direction"] == 1 assert pos["entry_price"] == 60000.0 assert pos["status"] == "open" def test_close_position(self, db): upsert_asset(db, "BTC-USD", 500.0) pos_id = open_position( db, ticker="BTC-USD", direction=1, entry_price=60000.0, entry_date="2025-01-15", stop_price=58800.0, stop_dist=1200.0, best_price=60000.0, pos_size=0.04, pos_value=2400.0, ) close_position( db, pos_id, exit_price=62000.0, exit_date="2025-01-20", exit_reason="stop", pnl_net=74.0, pnl_pct=3.08, ) # No open position after closing assert get_open_position(db, "BTC-USD") is None # Should appear in trade history history = get_trade_history(db, "BTC-USD") assert len(history) == 1 assert history[0]["exit_reason"] == "stop" assert history[0]["pnl_net"] == 74.0 def test_no_open_position_returns_none(self, db): upsert_asset(db, "BTC-USD", 500.0) assert get_open_position(db, "BTC-USD") is None def test_get_latest_open_position(self, db): """If multiple open positions exist, get_open_position returns the latest.""" upsert_asset(db, "BTC-USD", 500.0) open_position( db, ticker="BTC-USD", direction=1, entry_price=59000.0, entry_date="2025-01-10", stop_price=57800.0, stop_dist=1200.0, best_price=59000.0, pos_size=0.04, pos_value=2360.0, ) pos_id2 = open_position( db, ticker="BTC-USD", direction=-1, entry_price=61000.0, entry_date="2025-01-15", stop_price=62200.0, stop_dist=1200.0, best_price=61000.0, pos_size=0.04, pos_value=2440.0, ) pos = get_open_position(db, "BTC-USD") assert pos["id"] == pos_id2 assert pos["direction"] == -1 class TestDetectDeposit: def test_no_previous_snapshot(self, db): """First run — no previous balance, should return None.""" result = detect_deposit(db, exchange_balance=1000.0) assert result is None def test_deposit_detected(self, db): """Add 200 USDT deposit between snapshots.""" log_balance_snapshot(db, "2025-01-15", 1000.0, 1000.0) # Exchange now shows 1200 but no PnL was realized deposit = detect_deposit(db, exchange_balance=1200.0, realized_pnl_since=0.0) assert deposit == pytest.approx(200.0) def test_withdrawal_detected(self, db): log_balance_snapshot(db, "2025-01-15", 1000.0, 1000.0) deposit = detect_deposit(db, exchange_balance=800.0, realized_pnl_since=0.0) assert deposit == pytest.approx(-200.0) def test_pnl_not_confused_with_deposit(self, db): """Balance change from trading should not be flagged as deposit.""" log_balance_snapshot(db, "2025-01-15", 1000.0, 1000.0) # Made 50 USDT profit, balance is now 1050 deposit = detect_deposit( db, exchange_balance=1050.0, realized_pnl_since=50.0, ) assert deposit is None # diff = 0, below threshold def test_small_change_below_threshold(self, db): """Changes below threshold are ignored (noise from unrealized PnL).""" log_balance_snapshot(db, "2025-01-15", 1000.0, 1000.0) deposit = detect_deposit( db, exchange_balance=1005.0, realized_pnl_since=0.0, threshold=10.0, ) assert deposit is None # =========================================================================== # Reconciliation logic (exchange position sync) tests # =========================================================================== class TestReconciliation: """Tests for exchange position sync scenarios. These test the state layer's ability to detect mismatches between DB positions and exchange positions, which the reconciliation logic should handle. """ def test_db_has_position_exchange_does_not(self, db): """DB shows open position but exchange has none -> stale position. The reconciliation should force-close such positions. """ upsert_asset(db, "UNI-USD", 200.0) pos_id = open_position( db, ticker="UNI-USD", direction=1, entry_price=10.0, entry_date="2025-01-15", stop_price=9.0, stop_dist=1.0, best_price=10.0, pos_size=20.0, pos_value=200.0, ) # Simulate reconciliation: exchange says no position exchange_positions = {} # empty pos = get_open_position(db, "UNI-USD") assert pos is not None # Reconciliation action: force close at last known price if pos and "UNI-USD" not in exchange_positions: close_position( db, pos_id, exit_price=10.5, exit_date="2025-01-16", exit_reason="reconciliation", pnl_net=0.0, pnl_pct=0.0, ) assert get_open_position(db, "UNI-USD") is None history = get_trade_history(db, "UNI-USD") assert history[0]["exit_reason"] == "reconciliation" def test_exchange_has_position_db_does_not(self, db): """Exchange has a position but DB doesn't -> need to record it. This can happen after a manual trade on exchange or DB reset. """ upsert_asset(db, "NEAR-USD", 200.0) # DB says no position assert get_open_position(db, "NEAR-USD") is None # Exchange says there's a long 50 NEAR at $5 exchange_pos = {"side": "long", "size": 50.0, "entry_price": 5.0} # Reconciliation action: record the position if exchange_pos: pos_id = open_position( db, ticker="NEAR-USD", direction=1 if exchange_pos["side"] == "long" else -1, entry_price=exchange_pos["entry_price"], entry_date="2025-01-16", stop_price=exchange_pos["entry_price"] * 0.90, # safety stop stop_dist=exchange_pos["entry_price"] * 0.10, best_price=exchange_pos["entry_price"], pos_size=exchange_pos["size"], pos_value=exchange_pos["size"] * exchange_pos["entry_price"], ) pos = get_open_position(db, "NEAR-USD") assert pos is not None assert pos["pos_size"] == 50.0 assert pos["entry_price"] == 5.0 def test_position_size_mismatch(self, db): """DB and exchange both have position but sizes differ. Reconciliation should update DB to match exchange reality. """ upsert_asset(db, "ATOM-USD", 200.0) pos_id = open_position( db, ticker="ATOM-USD", direction=1, entry_price=8.0, entry_date="2025-01-15", stop_price=7.2, stop_dist=0.8, best_price=8.0, pos_size=25.0, pos_value=200.0, ) # Exchange shows only 20 ATOM (partial fill or partial close) exchange_size = 20.0 pos = get_open_position(db, "ATOM-USD") if pos and abs(pos["pos_size"] - exchange_size) > 0.01: from remizov_trader.state import update_position update_position( db, pos_id, pos_size=exchange_size, pos_value=exchange_size * pos["entry_price"], ) pos = get_open_position(db, "ATOM-USD") assert pos["pos_size"] == pytest.approx(20.0) assert pos["pos_value"] == pytest.approx(160.0) def test_equity_divergence_tracking(self, db): """Track divergence between exchange balance and DB equity.""" log_balance_snapshot(db, "2025-01-15", 1000.0, 980.0) row = db.execute( "SELECT * FROM balance_snapshots ORDER BY id DESC LIMIT 1" ).fetchone() assert row is not None # divergence = (1000 - 980) / 980 * 100 ~ 2.04% assert row["divergence_pct"] == pytest.approx(2.04, abs=0.1) def test_full_reconciliation_flow(self, db): """End-to-end: open position, detect deposit, close with reconciliation.""" upsert_asset(db, "BTC-USD", 500.0) # Open a position pos_id = open_position( db, ticker="BTC-USD", direction=1, entry_price=60000.0, entry_date="2025-01-15", stop_price=58800.0, stop_dist=1200.0, best_price=60000.0, pos_size=0.04, pos_value=2400.0, ) # Log initial balance log_balance_snapshot(db, "2025-01-15", 500.0, 500.0) # Next cycle: exchange balance jumped (deposit detected) deposit = detect_deposit(db, exchange_balance=700.0, realized_pnl_since=0.0) assert deposit == pytest.approx(200.0) # Update equity with deposit update_asset(db, "BTC-USD", equity=700.0, peak_equity=700.0) asset = get_asset(db, "BTC-USD") assert asset["equity"] == 700.0 # Close position with profit pnl_net, pnl_pct = calculate_pnl(60000.0, 62000.0, 1, 0.04, 2400.0) close_position( db, pos_id, exit_price=62000.0, exit_date="2025-01-20", exit_reason="stop", pnl_net=pnl_net, pnl_pct=pnl_pct, ) assert get_open_position(db, "BTC-USD") is None history = get_trade_history(db, "BTC-USD") assert len(history) == 1 assert history[0]["pnl_net"] > 0