File size: 20,336 Bytes
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51717a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65ccdcd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
"""
TDD suite for Causal Historical Replay Backtester:
- Strict zero-lookahead causal windowing (mutating future candles/funding never alters prior bar decisions)
- Pessimistic intra-bar SL-first tie-breaking when SL and TP both fall inside one candle
- Taker fees, entry/exit slippage, and 8-hour funding cashflow accounting
- Quantitative metrics (win rate, profit factor, expectancy, Sharpe, Sortino, max drawdown, equity curve)
"""

import copy
import os
import sys

import pytest

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))


def _make_candles(n: int = 80, start_ts: int = 1_700_000_000_000, step_ms: int = 3_600_000, base_price: float = 100.0):
    candles = []
    px = base_price
    for i in range(n):
        o = px
        c = px + 0.35
        h = max(o, c) + 0.25
        l = min(o, c) - 0.20
        candles.append({
            "timestamp": start_ts + i * step_ms,
            "open": round(o, 4),
            "high": round(h, 4),
            "low": round(l, 4),
            "close": round(c, 4),
            "volume": 1000.0,
        })
        px = c
    return candles


def test_backtester_causal_zero_lookahead():
    """Altering future candles/funding after bar K must produce bit-identical decisions up to bar K."""
    from engine.backtester import CausalBacktester

    base_candles = _make_candles(70)
    base_funding = [
        {"timestamp": base_candles[i]["timestamp"], "funding_rate": 0.0001}
        for i in range(0, 70, 8)
    ]

    recorded_windows_a: list[tuple[int, int, float]] = []
    recorded_windows_b: list[tuple[int, int, float]] = []

    def spy_signal_fn(raw_data: dict, recorder: list) -> dict:
        ohlcv_1h = raw_data["binance"]["ohlcv"]["1h"]
        fr = raw_data["binance"]["funding_rate_data"]["funding_rate"]
        recorder.append((len(ohlcv_1h), ohlcv_1h[-1]["timestamp"], fr))
        return {"direction": "NEUTRAL", "conviction": 0, "trade_levels": None}

    bt = CausalBacktester(warmup_bars=30)
    bt.run(
        symbol="BTCUSDT",
        candles_1h=base_candles,
        funding_history=base_funding,
        signal_fn=lambda raw: spy_signal_fn(raw, recorded_windows_a),
    )

    # Corrupt all data from bar 50 onward (massive crash & extreme funding in the future)
    mutated_candles = copy.deepcopy(base_candles)
    for k in range(50, len(mutated_candles)):
        mutated_candles[k]["open"] *= 0.2
        mutated_candles[k]["high"] *= 0.2
        mutated_candles[k]["low"] *= 0.1
        mutated_candles[k]["close"] *= 0.15

    mutated_funding = copy.deepcopy(base_funding)
    for item in mutated_funding:
        if item["timestamp"] >= mutated_candles[50]["timestamp"]:
            item["funding_rate"] = 0.05

    bt.run(
        symbol="BTCUSDT",
        candles_1h=mutated_candles,
        funding_history=mutated_funding,
        signal_fn=lambda raw: spy_signal_fn(raw, recorded_windows_b),
    )

    # First 20 evaluation steps cover bars 30..49 -> strictly identical!
    prefix_len = 50 - 30
    assert recorded_windows_a[:prefix_len] == recorded_windows_b[:prefix_len]
    # Also verify no window ever received a timestamp strictly after its latest close
    assert all(w_len == 30 + idx + 1 for idx, (w_len, _, _) in enumerate(recorded_windows_a))


def test_backtester_sl_first_tiebreak_and_costs():
    """When SL and TP both trigger inside the same bar, SL must resolve first; fees, slippage, and 8h funding reduce net PnL."""
    from engine.backtester import CausalBacktester

    candles = _make_candles(45, step_ms=3_600_000, base_price=100.0)
    # Bar 30 triggers LONG signal; entry occurs at bar 31 open (~110.5)
    entry_open = candles[31]["open"]
    # Bar 31 sweeps BOTH below SL and above TP2 in the same candle -> pessimistic SL-first MUST record a loss
    candles[31]["low"] = entry_open - 5.0
    candles[31]["high"] = entry_open + 12.0
    candles[31]["close"] = entry_open + 8.0

    signals_emitted = {"count": 0}

    def single_entry_signal(raw_data: dict) -> dict:
        ohlcv_1h = raw_data["binance"]["ohlcv"]["1h"]
        if len(ohlcv_1h) == 31 and signals_emitted["count"] == 0:
            signals_emitted["count"] += 1
            px = ohlcv_1h[-1]["close"]
            return {
                "direction": "LONG",
                "conviction": 6,
                "trade_levels": {
                    "entry_price": px,
                    "stop_loss": px - 2.0,
                    "take_profit_1": px + 3.0,
                    "take_profit_2": px + 6.0,
                },
            }
        return {"direction": "NEUTRAL", "conviction": 0, "trade_levels": None}

    bt = CausalBacktester(
        initial_capital_usd=1000.0,
        position_size_pct=1.0,
        leverage=1.0,
        taker_fee_bps=10.0,   # 0.10% per leg
        slippage_bps=5.0,     # 0.05% per leg
        warmup_bars=30,
    )
    report = bt.run(symbol="BTCUSDT", candles_1h=candles, signal_fn=single_entry_signal)

    assert report["total_trades"] == 1
    t0 = report["trades"][0]
    assert t0["exit_reason"] == "STOP_LOSS"
    assert t0["net_pnl_usd"] < 0
    assert report["total_fees_usd"] > 0
    assert report["win_rate_pct"] == 0.0
    assert report["max_drawdown_pct"] > 0.0

    # Test 2: Winning trade held across an 8h funding interval pays positive funding + fees
    win_candles = _make_candles(48, start_ts=3_600_000, step_ms=3_600_000, base_price=100.0)
    # Bar 31..40 drift steadily without hitting SL, crossing 8h timestamp (e.g. bar 32 ts = 33 * 3_600_000; ensure exact 8h multiple!)
    base_ts = 1_700_006_400_000  # divisible cleanly? compute aligned multiple of 28_800_000
    aligned_start = 1_700_006_400_000 - (1_700_006_400_000 % 28_800_000)
    win_candles = _make_candles(45, start_ts=aligned_start, step_ms=3_600_000, base_price=100.0)
    # Bar 31 enter at bar 32 open (bar 32 is index 32 -> timestamp = aligned_start + 32 * 3_600_000 = multiple of 8h!)
    # Hold through bar 32 (8h funding settlement) and hit TP1+TP2 cleanly on bar 33
    win_entry = win_candles[32]["open"]
    for idx in range(32, 36):
        win_candles[idx]["low"] = win_entry - 0.2
        win_candles[idx]["high"] = win_entry + 0.5
        win_candles[idx]["close"] = win_entry + 0.3
    # At bar 34 (timestamp % 28_800_000 != 0, held across bar 32 settlement) surge past TP2 without hitting SL
    win_candles[34]["high"] = win_entry + 10.0
    win_candles[34]["close"] = win_entry + 9.0

    win_emitted = {"done": False}

    def win_signal(raw_data: dict) -> dict:
        bars = raw_data["binance"]["ohlcv"]["1h"]
        if len(bars) == 32 and not win_emitted["done"]:
            win_emitted["done"] = True
            px = bars[-1]["close"]
            return {
                "direction": "LONG",
                "conviction": 6,
                "trade_levels": {
                    "entry_price": px,
                    "stop_loss": px - 3.0,
                    "take_profit_1": px + 3.0,
                    "take_profit_2": px + 6.0,
                },
            }
        return {"direction": "NEUTRAL", "conviction": 0, "trade_levels": None}

    funding_series = [
        {"timestamp": c["timestamp"], "funding_rate": 0.001}
        for c in win_candles
    ]
    win_report = bt.run(
        symbol="BTCUSDT",
        candles_1h=win_candles,
        funding_history=funding_series,
        signal_fn=win_signal,
    )
    assert win_report["total_trades"] == 1
    wt = win_report["trades"][0]
    assert "TAKE_PROFIT" in wt["exit_reason"]
    assert wt["funding_usd"] > 0.0, "Positive funding on LONG position across 8h settlement must incur positive funding cost"
    assert wt["net_pnl_usd"] < wt["gross_pnl_usd"]
    assert win_report["win_rate_pct"] == 100.0
    assert win_report["expectancy_usd"] > 0.0


def test_backtester_runs_with_real_signal_engine_and_reports_all_metrics():
    """Default SignalEngine integration runs cleanly end-to-end and outputs Sharpe, Sortino, PF, DD, Expectancy."""
    from engine.backtester import CausalBacktester

    # Create a 75-bar trending + choppy series to exercise real SignalEngine
    candles = _make_candles(75, base_price=200.0)
    for i in range(45, 75):
        candles[i]["close"] -= (i - 44) * 0.9
        candles[i]["low"] = min(candles[i]["open"], candles[i]["close"]) - 0.4
        candles[i]["high"] = max(candles[i]["open"], candles[i]["close"]) + 0.3

    bt = CausalBacktester(warmup_bars=30)
    res = bt.run(symbol="ETHUSDT", candles_1h=candles)

    expected_keys = {
        "symbol",
        "bars_evaluated",
        "total_trades",
        "win_rate_pct",
        "profit_factor",
        "expectancy_usd",
        "expectancy_r",
        "sharpe_ratio",
        "sortino_ratio",
        "max_drawdown_pct",
        "net_pnl_usd",
        "net_return_pct",
        "total_fees_usd",
        "total_funding_usd",
        "equity_curve",
        "trades",
    }
    assert expected_keys.issubset(res.keys())
    assert res["symbol"] == "ETHUSDT"
    assert res["bars_evaluated"] == 44  # indices 30..73 (needs bar i+1 to fill)
    assert len(res["equity_curve"]) >= 44


def test_backtester_cli_fixture_mode(tmp_path, capsys):
    """CLI run_backtest.py executes offline --fixture JSON replay cleanly and prints valid JSON metrics."""
    import json
    from scripts.run_backtest import main as backtest_main

    fixture_file = tmp_path / "btc_fixture.json"
    fixture_file.write_text(
        json.dumps({
            "symbol": "BTCUSDT",
            "candles_1h": _make_candles(60, base_price=50000.0),
            "funding_history": [{"timestamp": 1_700_000_000_000, "funding_rate": 0.0001}],
        }),
        encoding="utf-8",
    )
    exit_code = backtest_main(["--fixture", str(fixture_file), "--warmup", "30", "--json"])
    assert exit_code == 0
    out = json.loads(capsys.readouterr().out)
    assert out["symbol"] == "BTCUSDT"
    assert out["bars_evaluated"] == 29
    assert "sharpe_ratio" in out and "max_drawdown_pct" in out


def test_backtester_dual_horizon_breakeven_after_tp1_and_sniper_calibration():
    """Verify breakeven_after_tp1=True moves SL to entry_fill + 6 bps after TP1 and OHLCV_FUNDING_ONLY threshold calibration works."""
    from engine.backtester import CausalBacktester
    candles = _make_candles(35, base_price=100.0)
    # Signal fires on index 30 (warmup=30), fills on index 31 open=100.0
    candles[31] = {**candles[31], "open": 100.0, "high": 106.0, "low": 99.5, "close": 104.0, "volume": 100.0}
    # Index 32 retraces to 100.0 (hits breakeven SL at ~100.06, above original SL=95.0)
    candles[32] = {**candles[32], "open": 104.0, "high": 104.2, "low": 99.8, "close": 100.1, "volume": 100.0}

    def _mock_signal(raw):
        bar_ts = raw["binance"]["ohlcv"]["1h"][-1]["timestamp"]
        if bar_ts == candles[30]["timestamp"]:
            tl = {"entry": 100.0, "stop_loss": 95.0, "tp1": 105.0, "tp2": 115.0}
            return {
                "direction": "LONG",
                "conviction": 4,
                "sniper_grade": "SNIPER_A_PLUS",
                "trade_levels": tl,
                "horizons": {
                    "intraday": {"direction": "LONG", "conviction": 4, "trade_levels": tl},
                    "swing": {"direction": "LONG", "conviction": 4, "trade_levels": tl},
                    "primary": {"direction": "LONG", "conviction": 4, "trade_levels": tl},
                },
            }
        return {"direction": "NEUTRAL", "conviction": 0, "sniper_grade": "WAIT", "trade_levels": None, "horizons": {}}

    bt = CausalBacktester(warmup_bars=30)
    res_be = bt.run(
        symbol="BTCUSDT",
        candles_1h=candles,
        signal_fn=_mock_signal,
        horizon="intraday",
        sniper_only=True,
        breakeven_after_tp1=True,
    )
    assert res_be["total_trades"] == 1
    assert res_be["trades"][0]["exit_reason"] == "STOP_LOSS_BREAKEVEN"
    assert res_be["trades"][0]["net_pnl_usd"] > 0  # TP1 leg + breakeven runner > 0

    # Real SignalEngine with OHLCV_FUNDING_ONLY automatic threshold calibration (2)
    trend_1h = [
        {"timestamp": 1_700_000_000_000 + i * 3_600_000, "open": 100.0 + i * 0.4, "high": 100.8 + i * 0.4, "low": 99.7 + i * 0.4, "close": 100.5 + i * 0.4, "volume": 500.0}
        for i in range(60)
    ]
    bt_real = CausalBacktester(warmup_bars=30)
    res_sniper = bt_real.run(
        symbol="ETHUSDT",
        candles_1h=trend_1h,
        horizon="intraday",
        sniper_only=True,
        breakeven_after_tp1=True,
    )
    assert res_sniper["telemetry_fidelity"] == "OHLCV_FUNDING_ONLY"
    assert res_sniper["horizon"] == "intraday"
    assert res_sniper["sniper_only"] is True
    assert res_sniper["breakeven_after_tp1"] is True
    assert res_sniper["total_trades"] >= 1


def test_backtester_cli_compare_ab_mode(tmp_path, capsys):
    """CLI --compare-ab outputs baseline, sniper_dual_horizon, and delta comparison."""
    import json
    from scripts.run_backtest import main as backtest_main

    trend_1h = [
        {"timestamp": 1_700_000_000_000 + i * 3_600_000, "open": 100.0 + i * 0.4, "high": 100.8 + i * 0.4, "low": 99.7 + i * 0.4, "close": 100.5 + i * 0.4, "volume": 500.0}
        for i in range(60)
    ]
    fixture_file = tmp_path / "ab_fixture.json"
    fixture_file.write_text(
        json.dumps({
            "symbol": "SOLUSDT",
            "candles_1h": trend_1h,
            "funding_history": [{"timestamp": 1_700_000_000_000, "funding_rate": -0.0001}],
        }),
        encoding="utf-8",
    )
    exit_code = backtest_main(["--fixture", str(fixture_file), "--warmup", "30", "--compare-ab", "--json"])
    assert exit_code == 0
    out = json.loads(capsys.readouterr().out)
    assert "baseline" in out
    assert "sniper_dual_horizon" in out
    assert "delta" in out
    assert "win_rate_pct_diff" in out["delta"]


def test_backtester_causal_oi_history_zero_lookahead():
    """Provides sorted oi_history and mutates future OI bars after bar K -> verifies zero lookahead up to bar K,
    verifies open_interest_data exposes oi_change_pct, oi_change_1h_pct, oi_change_4h_pct, and verifies oi_history=None
    preserves existing open_interest_data=None behavior."""
    from engine.backtester import CausalBacktester

    base_candles = _make_candles(70, start_ts=1_700_000_000_000, step_ms=3_600_000)
    # 15m OI bars (4 per 1h candle)
    base_oi: list[dict] = []
    for m in range(70 * 4):
        base_oi.append({
            "timestamp": 1_700_000_000_000 + m * 900_000,
            "open_interest": 10_000.0 + m * 10.0,
            "open_interest_value": (10_000.0 + m * 10.0) * 100.0,
        })

    recorded_oi_a: list[dict | None] = []
    recorded_oi_b: list[dict | None] = []
    recorded_oi_none: list[dict | None] = []

    def spy_fn(raw_data: dict, recorder: list) -> dict:
        oi_data = raw_data["binance"].get("open_interest_data")
        recorder.append(copy.deepcopy(oi_data))
        return {"direction": "NEUTRAL", "conviction": 0, "trade_levels": None}

    bt = CausalBacktester(warmup_bars=30)
    bt.run(
        symbol="BTCUSDT",
        candles_1h=base_candles,
        oi_history=base_oi,
        signal_fn=lambda raw: spy_fn(raw, recorded_oi_a),
    )

    # Corrupt all OI data from bar 50 onward
    k_bar = 50
    t_corrupt = base_candles[k_bar]["timestamp"]
    mutated_oi = copy.deepcopy(base_oi)
    for item in mutated_oi:
        if item["timestamp"] >= t_corrupt:
            item["open_interest"] = item["open_interest"] * 10.0
            item["open_interest_value"] = item["open_interest_value"] * 10.0

    bt.run(
        symbol="BTCUSDT",
        candles_1h=base_candles,
        oi_history=mutated_oi,
        signal_fn=lambda raw: spy_fn(raw, recorded_oi_b),
    )

    # First 20 evaluation steps (bars 30..49) strictly identical!
    prefix_len = k_bar - 30
    assert recorded_oi_a[:prefix_len] == recorded_oi_b[:prefix_len]

    # At bar K, corruption causes divergence
    assert recorded_oi_a[prefix_len]["oi_change_pct"] != recorded_oi_b[prefix_len]["oi_change_pct"]

    # Verify open_interest_data fields on populated causal entry
    oi_sample = recorded_oi_a[prefix_len]
    assert oi_sample is not None
    assert "open_interest" in oi_sample
    assert "prev_open_interest" in oi_sample
    assert "oi_change_pct" in oi_sample
    assert "oi_change_1h_pct" in oi_sample
    assert "oi_change_4h_pct" in oi_sample
    assert oi_sample.get("oi_horizon") == "15m"
    assert isinstance(oi_sample["oi_change_pct"], float)
    assert isinstance(oi_sample["oi_change_1h_pct"], float)
    assert isinstance(oi_sample["oi_change_4h_pct"], float)

    # Verify oi_history=None preserves open_interest_data=None behavior
    bt.run(
        symbol="BTCUSDT",
        candles_1h=base_candles,
        oi_history=None,
        signal_fn=lambda raw: spy_fn(raw, recorded_oi_none),
    )
    assert len(recorded_oi_none) > 0
    assert all(x is None for x in recorded_oi_none)


def test_backtester_cli_walk_forward_and_multi_symbols(tmp_path, capsys, monkeypatch):
    """Passes --fixture with --walk-forward --json and asserts output includes in_sample, out_of_sample, and oos_retention_ratio.
    Also tests --symbols multi-symbol execution."""
    import json
    from scripts.run_backtest import main as backtest_main

    fixture_file = tmp_path / "wf_fixture.json"
    fixture_file.write_text(
        json.dumps({
            "symbol": "BTCUSDT",
            "candles_1h": _make_candles(80, base_price=50000.0),
            "funding_history": [{"timestamp": 1_700_000_000_000, "funding_rate": 0.0001}],
            "oi_history": [
                {"timestamp": 1_700_000_000_000 + i * 900_000, "open_interest": 1000.0 + i}
                for i in range(80 * 4)
            ],
        }),
        encoding="utf-8",
    )

    exit_code = backtest_main(["--fixture", str(fixture_file), "--warmup", "30", "--walk-forward", "--json"])
    assert exit_code == 0
    out = json.loads(capsys.readouterr().out)
    assert "in_sample" in out
    assert "out_of_sample" in out
    assert "oos_retention_ratio" in out
    assert isinstance(out["oos_retention_ratio"], (int, float))
    assert out["in_sample"]["bars_evaluated"] > 0
    assert out["out_of_sample"]["bars_evaluated"] > 0

    # Multi-symbol CLI verification with monkeypatched fetch
    async def mock_fetch(sym: str, days: int):
        px = 50000.0 if "BTC" in sym else 3000.0
        c = _make_candles(80, base_price=px)
        f = [{"timestamp": 1_700_000_000_000, "funding_rate": 0.0001}]
        return c, f, [], []

    monkeypatch.setattr("scripts.run_backtest.fetch_historical_dataset", mock_fetch)
    exit_code_multi = backtest_main(["--symbols", "BTCUSDT,ETHUSDT", "--days", "14", "--warmup", "30", "--walk-forward", "--json"])
    assert exit_code_multi == 0
    out_multi = json.loads(capsys.readouterr().out)
    assert "symbols" in out_multi
    assert "BTCUSDT" in out_multi["symbols"]
    assert "ETHUSDT" in out_multi["symbols"]
    assert "in_sample" in out_multi["symbols"]["BTCUSDT"]
    assert "out_of_sample" in out_multi["symbols"]["BTCUSDT"]
    assert "oos_retention_ratio" in out_multi["symbols"]["BTCUSDT"]


def test_backtester_oi_history_deduplicates_timestamps():
    """Duplicate OI timestamps must deduplicate rather than collapsing series[-1] == series[-2] to 0% delta."""
    from engine.backtester import CausalBacktester

    candles = _make_candles(40, base_price=50000.0)
    t_eval = candles[32]["timestamp"]
    oi_history = [
        {"timestamp": t_eval - 900_000, "open_interest": 1000.0},
        {"timestamp": t_eval, "open_interest": 1100.0},
        {"timestamp": t_eval, "open_interest": 1100.0},  # duplicate timestamp
    ]
    captured_oi_pct: list[float | None] = []

    def _inspect_signal(raw):
        oi_data = raw["binance"]["open_interest_data"]
        if oi_data and candles[32]["timestamp"] == raw["binance"]["ohlcv"]["1h"][-1]["timestamp"]:
            captured_oi_pct.append(oi_data.get("oi_change_pct"))
        return {"direction": "NEUTRAL", "conviction": 0, "sniper_grade": "WAIT", "trade_levels": None}

    bt = CausalBacktester(warmup_bars=30)
    bt.run(symbol="BTCUSDT", candles_1h=candles, oi_history=oi_history, signal_fn=_inspect_signal)
    assert captured_oi_pct == [pytest.approx(10.0)]