"""The trading rules: pinned to recorded behaviour so a future edit can't silently change them.""" import json from dataclasses import replace from pathlib import Path import pytest from app import strategy from app.strategy import DEFAULT, Bars, signal from tests.helpers import wave SERIES = {"a": dict(phase=0.0), "b": dict(phase=1.3, drift=0.03), "c": dict(phase=2.6, amp=22.0)} def replay(candles, params=DEFAULT): b, out = Bars(), [] for i, c in enumerate(candles): b.add(c.high, c.low, c.close, c.volume) r = signal(b, params) if r: out.append([i, r[0], r[1]]) b.in_position = r[0] == "buy" if r[0] == "sell": b.trail = None return out def test_signals_match_the_recorded_reference(): golden = json.loads((Path(__file__).parent / "golden_signals.json").read_text()) for key, kw in SERIES.items(): assert replay(wave(700, **kw)) == golden[key], f"series {key} changed behaviour" def test_no_signal_before_the_indicators_have_warmed_up(): assert replay(wave(DEFAULT.slow + 1)) == [] def test_buys_and_sells_alternate_and_use_known_reasons(): sigs = replay(wave(700)) assert [s[1] for s in sigs] == ["buy", "sell"] * (len(sigs) // 2) assert {s[2] for s in sigs} <= {"trend_up_volume", "trend_reversal", "atr_stop"} def test_a_tighter_stop_exits_sooner_or_equal(): base = replay(wave(700)) tight = replay(wave(700), replace(DEFAULT, atr_mult=0.5)) first_exit = lambda sigs: next(i for i, a, _ in sigs if a == "sell") # noqa: E731 assert first_exit(tight) <= first_exit(base) def test_removing_the_volume_filter_never_reduces_entries_on_the_first_trade(): # Without the filter the first buy can only come earlier or at the same candle. base = replay(wave(700)) loose = replay(wave(700), replace(DEFAULT, vol_mult=0.0)) assert loose[0][0] <= base[0][0] def test_matches_the_plain_ema_and_atr_helpers(): vals = [c.close for c in wave(200)] kf = 2 / 22 e = None for x in vals: e = x if e is None else x * kf + e * (1 - kf) assert e == pytest.approx(strategy.ema(vals, 21)[-1], rel=1e-12) def test_diagnose_agrees_with_signal_on_every_candle(): """The health panel must never say 'ready' when the bot would not buy, or the reverse.""" b, ready_seen = Bars(), 0 for i, c in enumerate(wave(700)): b.add(c.high, c.low, c.close, c.volume) d = strategy.diagnose(b) sig = signal(b) if d["warming"]: assert sig is None continue assert d["ready"] == (sig == ("buy", "trend_up_volume")), f"candle {i}" assert d["ready"] == (not d["missing"]) ready_seen += d["ready"] assert ready_seen > 0 def test_diagnose_reports_warmup_and_holding(): b = Bars() for c in wave(30): b.add(c.high, c.low, c.close, c.volume) d = strategy.diagnose(b) assert d["warming"] and d["have"] == 30 and d["need"] == DEFAULT.slow + 2 for c in wave(700): b.add(c.high, c.low, c.close, c.volume) b.in_position = True assert strategy.diagnose(b)["ready"] is False # already holding: nothing to buy def test_volume_check_shows_raw_numbers_and_flags_missing_volume(): b = Bars() for c in wave(300): b.add(c.high, c.low, c.close, c.volume) vol = next(x for x in strategy.diagnose(b)["checks"] if x["key"] == "volume")["detail"] assert "newest candle" in vol and "average" in vol z = Bars() for c in wave(300): z.add(c.high, c.low, c.close, 0.0) d = strategy.diagnose(z) assert d["no_volume"] and "no volume" in next(x for x in d["checks"] if x["key"] == "volume")["detail"] assert d["ready"] is False