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>
This commit is contained in:
anor
2026-03-13 21:50:05 +10:00
co-authored by Claude Opus 4.6
parent af6885c3e7
commit db17365bbb
3 changed files with 1381 additions and 0 deletions
+307
View File
@@ -0,0 +1,307 @@
"""Walk-forward backtest with exact production config parameters.
Tests UNI, ATOM, NEAR with per-asset params from config.yaml.
"""
import sys
sys.path.insert(0, "src")
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig, RiskConfig
RISK_CFG = RiskConfig(
per_trade=0.05, max_position_pct=0.40,
max_open_positions=3, leverage=1,
)
INITIAL_CAPITAL = 254.0 # actual prod capital
TRAILING_STOP = True
TRAIN_RATIO = 0.3
LONG_ONLY = True # spot mode: can't short
# Per-asset configs from production config.yaml
ASSETS = [
{
"symbol": "UNI/USDC", "ticker": "UNI-USD",
"window_size": 64, "K": 2, "shift": 14,
"epochs": 300, "lr": 0.005,
"stop_mult": 1.25, "stop_scale": 0.75,
"cooldown_bars": 3, "shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.34,
},
{
"symbol": "ATOM/USDC", "ticker": "ATOM-USD",
"window_size": 64, "K": 3, "shift": 14,
"epochs": 300, "lr": 0.005,
"stop_mult": 0.75, "stop_scale": 1.0,
"cooldown_bars": 3, "shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.33,
},
{
"symbol": "NEAR/USDC", "ticker": "NEAR-USD",
"window_size": 64, "K": 2, "shift": 16,
"epochs": 300, "lr": 0.01,
"stop_mult": 1.0, "stop_scale": 1.0,
"cooldown_bars": 3, # updated from WF results (was -1)
"shape_confirm": False,
"corr_thresh": 0.5, "weight": 0.33,
},
]
def run_backtest(asset: dict, prices: np.ndarray):
"""Walk-forward backtest with exact prod params."""
ws = asset["window_size"]
shift = asset["shift"]
K = asset["K"]
corr_thresh = asset["corr_thresh"]
shape_confirm = asset["shape_confirm"]
stop_mult_base = asset["stop_mult"]
stop_scale = asset["stop_scale"]
cooldown_bars = asset["cooldown_bars"]
if cooldown_bars == -1:
cooldown_bars = shift
model_cfg = ModelConfig(
window_size=ws, n_steps=20, total_time=0.5,
shift=shift, epochs=asset["epochs"],
finetune_epochs=50, lr=asset["lr"],
)
data = signals.prepare_windows(prices, ws, shift)
if len(data) < 30:
print(f" Not enough windows: {len(data)}")
return None
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train_data = data[:n_train]
test_data = data[n_train:]
print(f" Windows: {len(data)} total, {n_train} train, {len(test_data)} test")
# Train
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
windows = np.array([d["norm_input"] for d in train_data])
targets = np.array([d["norm_target"] for d in train_data])
loss = model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr)
print(f" Train loss: {loss:.6f}")
# Simulate
capital = INITIAL_CAPITAL * asset["weight"]
equity = capital
trades = []
position = None
equity_curve = [equity]
cooldown_until = 0
for i, d in enumerate(test_data):
price_idx = d["price_idx"]
current_price = float(prices[price_idx])
# Check position
if position is not None:
p = position
if TRAILING_STOP:
p["best_price"], p["stop_price"] = risk.update_trailing_stop(
current_price, p["best_price"], p["stop_price"],
p["stop_dist"], p["direction"],
)
stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"])
bars_held = price_idx - p["entry_bar"]
time_exit = bars_held >= (shift - p["k_used"])
if stopped or time_exit:
exit_price = p["stop_price"] if stopped else current_price
reason = "stop" if stopped else "time"
pnl_net, pnl_pct = risk.calculate_pnl(
p["entry_price"], exit_price, p["direction"],
p["pos_size"], p["pos_value"],
)
equity += pnl_net
trades.append({
"direction": p["direction"],
"entry_price": p["entry_price"],
"exit_price": exit_price,
"pnl_net": pnl_net,
"pnl_pct": pnl_pct,
"reason": reason,
"equity_at_entry": p["equity_at_entry"],
"entry_idx": p["entry_bar"],
})
position = None
if stopped:
cooldown_until = price_idx + cooldown_bars
# New signal
if position is None and price_idx >= ws + K and price_idx >= cooldown_until:
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
equity_curve.append(equity)
continue
norm_input = (w - mu) / std
pred = model_mod.predict(mdl, norm_input)
pred_new = pred[-shift:]
# Shape confirmation (prod: disabled for all 3 assets)
if shape_confirm:
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, corr_thresh,
)
else:
confirmed = True
if confirmed:
direction = signals.get_direction(pred_new, K)
if direction is not None and not (LONG_ONLY and direction == -1):
entry_price = current_price
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult_base * stop_scale,
entry_price * 0.005)
stop_price = entry_price - direction * stop_dist
pos_size, pos_value = risk.calculate_position(
equity, entry_price, stop_dist, RISK_CFG,
)
position = {
"direction": direction,
"entry_price": entry_price,
"stop_price": stop_price,
"stop_dist": stop_dist,
"best_price": entry_price,
"pos_size": pos_size,
"pos_value": pos_value,
"entry_bar": price_idx,
"k_used": K,
"equity_at_entry": equity,
}
equity_curve.append(equity)
# Close remaining
if position is not None:
last_price = float(prices[-1])
pnl_net, pnl_pct = risk.calculate_pnl(
position["entry_price"], last_price, position["direction"],
position["pos_size"], position["pos_value"],
)
equity += pnl_net
trades.append({
"direction": position["direction"],
"entry_price": position["entry_price"],
"exit_price": last_price,
"pnl_net": pnl_net,
"pnl_pct": pnl_pct,
"reason": "end",
"equity_at_entry": position["equity_at_entry"],
"entry_idx": position["entry_bar"],
})
equity_curve.append(equity)
if not trades:
print(" No trades!")
return None
# Metrics
pnls = [t["pnl_net"] for t in trades]
wins = [t for t in trades if t["pnl_net"] > 0]
losses = [t for t in trades if t["pnl_net"] <= 0]
total_pnl = equity - capital
total_ret = total_pnl / capital * 100
first_bar = test_data[0]["price_idx"]
last_bar = test_data[-1]["price_idx"]
n_bars = last_bar - first_bar
years = n_bars / (365.25 * 6)
# Sharpe
if len(pnls) > 1 and years > 0:
n_days = max(n_bars // 6, 1)
daily_pnl = np.zeros(n_days)
for t in trades:
day = min((t.get("entry_idx", first_bar) - first_bar) // 6, n_days - 1)
daily_pnl[day] += t["pnl_net"]
daily_ret = daily_pnl / capital
sharpe = float(np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(252)) if np.std(daily_ret) > 0 else 0
else:
sharpe = 0
# Max DD
eq = np.array(equity_curve)
peak = np.maximum.accumulate(eq)
dd = (peak - eq) / peak
max_dd = dd.max() * 100
months = years * 12
return {
"ticker": asset["ticker"],
"trades": len(trades), "wins": len(wins), "losses": len(losses),
"wr": len(wins) / len(trades) * 100,
"total_pnl": total_pnl, "total_ret": total_ret,
"sharpe": sharpe, "max_dd": max_dd,
"monthly_pnl": total_pnl / months if months > 0 else 0,
"months": months,
"avg_pnl": np.mean(pnls),
"avg_win": np.mean([t["pnl_net"] for t in wins]) if wins else 0,
"avg_loss": np.mean([t["pnl_net"] for t in losses]) if losses else 0,
"capital": capital,
}
def main():
results = []
for asset in ASSETS:
print(f"\n--- {asset['symbol']} ({asset['ticker']}) ---")
print(f" Params: K={asset['K']} shift={asset['shift']} "
f"stop_mult={asset['stop_mult']} stop_scale={asset['stop_scale']} "
f"cooldown={asset['cooldown_bars']} lr={asset['lr']}")
print(f" Fetching 4H data...")
prices, dates = signals.fetch_prices_ccxt(asset["symbol"], "4h", "max")
if prices is None:
print(f" No data")
continue
print(f" Got {len(prices)} bars")
r = run_backtest(asset, prices)
if r:
results.append(r)
print(f"\n{'='*60}")
print(f" {r['ticker']} — PROD PARAMS BACKTEST")
print(f"{'='*60}")
print(f" Period: ~{r['months']:.1f} months | Capital: ${r['capital']:.0f}")
print(f" Trades: {r['trades']} (W:{r['wins']} L:{r['losses']} WR:{r['wr']:.1f}%)")
print(f" Total PnL: ${r['total_pnl']:+,.2f} ({r['total_ret']:+.1f}%)")
print(f" Sharpe: {r['sharpe']:.2f}")
print(f" Max DD: {r['max_dd']:.1f}%")
print(f" Monthly: ${r['monthly_pnl']:+,.2f}/mo")
print(f" Avg win: ${r['avg_win']:+,.2f} | Avg loss: ${r['avg_loss']:+,.2f}")
print(f"{'='*60}")
if results:
total_pnl = sum(r["total_pnl"] for r in results)
total_cap = sum(r["capital"] for r in results)
print(f"\n\n{'='*60}")
mode_str = "LONG ONLY" if LONG_ONLY else "LONG+SHORT"
print(f" PORTFOLIO — PROD PARAMS ({mode_str}) | ${INITIAL_CAPITAL:.0f} capital")
print(f"{'='*60}")
print(f" {'Asset':<12s} {'Sharpe':>8s} {'Return':>10s} {'PnL':>10s} {'Trades':>7s} {'WR':>6s} {'MaxDD':>7s}")
print(f" {'-'*60}")
for r in sorted(results, key=lambda x: x["sharpe"], reverse=True):
print(f" {r['ticker']:<12s} {r['sharpe']:>8.2f} {r['total_ret']:>+9.1f}% "
f"${r['total_pnl']:>+9.2f} {r['trades']:>7d} {r['wr']:>5.1f}% {r['max_dd']:>6.1f}%")
print(f" {'TOTAL':<12s} {'':>8s} {total_pnl/total_cap*100:>+9.1f}% "
f"${total_pnl:>+9.2f}")
if __name__ == "__main__":
main()
+628
View File
@@ -0,0 +1,628 @@
"""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
+446
View File
@@ -0,0 +1,446 @@
"""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