File size: 14,409 Bytes
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Quantitative rigor tests:
- 1m OHLCV fetch for FakeDetector
- Binance resolved symbol on L/S fallback & OKX 1000-prefix stripping
- Contrarian L/S scoring
- Time-aligned Spot vs Futures CVD & midpoint CVD velocity split
- Hyperliquid DEX-vs-CEX deduplication
- Symmetric non-directional cross-exchange dislocation risk
- Order-flow cluster cap ([-3, +3]) and whale_order_flow deduplication
- Strict NEUTRAL + trade_levels=None veto on Circuit Breakers / FakeDetector
- PredictiveEngine swing_liquidity_proxy transparency label
- Guaranteed >= 1:1 (TP1) and >= 2:1 (TP2) R:R
"""

import os
import sys
from unittest.mock import AsyncMock, patch

import pytest

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


@pytest.fixture
def anyio_backend():
    return "asyncio"


@pytest.mark.anyio
async def test_collect_all_fetches_1m_ohlcv():
    """BaseExchange.collect_all must fetch 1m candles alongside higher timeframes for FakeDetector."""
    from exchanges.base import BaseExchange

    class DummyExchange(BaseExchange):
        name = "dummy"

        def __init__(self):
            super().__init__()
            self.ohlcv_calls: list[tuple[str, int]] = []

        def _make_client(self):
            return None

        async def get_funding_rate(self, symbol: str):
            return {"funding_rate": 0.0001}

        async def get_open_interest(self, symbol: str):
            return {"open_interest": 1000.0, "oi_change_pct": 0.1}

        async def get_long_short_ratio(self, symbol: str):
            return {"long_ratio": 0.5, "short_ratio": 0.5}

        async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100):
            self.ohlcv_calls.append((timeframe, limit))
            return [{"timestamp": 1000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 10.0}]

        async def get_recent_trades(self, symbol: str, limit: int = 200):
            return []

        async def get_orderbook(self, symbol: str, depth: int = 20):
            return {"bids": [], "asks": []}

        async def get_mark_price(self, symbol: str):
            return {"mark_price": 100.5, "index_price": 100.5, "basis_pct": 0.0}

        async def check_symbol_exists(self, symbol: str):
            return True

        async def close(self):
            return None

    client = DummyExchange()
    res = await client.get_full_snapshot("BTCUSDT")
    called_tfs = dict(client.ohlcv_calls)
    assert "1m" in called_tfs, "BaseExchange.get_full_snapshot must request 1m OHLCV for FakeDetector"
    assert "1m" in res["ohlcv"] and len(res["ohlcv"]["1m"]) == 1


@pytest.mark.anyio
async def test_binance_ls_fallback_and_okx_multiplier_prefix():
    """Binance L/S fallback must use resolved symbol (1000PEPEUSDT) and OKX must strip 1000-prefix to PEPE."""
    from engine.symbol_resolver import strip_multiplier_prefix
    from exchanges.binance import BinanceClient
    from exchanges.okx import OKXClient

    assert strip_multiplier_prefix("1000PEPEUSDT") == "PEPEUSDT"
    assert strip_multiplier_prefix("10000BONKUSDT") == "BONKUSDT"
    assert strip_multiplier_prefix("1INCHUSDT") == "1INCHUSDT"

    b_client = BinanceClient()
    b_client._known_symbols.add("1000PEPEUSDT")
    observed_calls: list[tuple[str, str]] = []

    async def fake_binance_get(path: str, params: dict | None = None):
        sym_arg = (params or {}).get("symbol", "")
        observed_calls.append((path, sym_arg))
        if "topLongShortAccountRatio" in path:
            raise RuntimeError("primary unavailable")
        return [{"longAccount": "0.60", "shortAccount": "0.40", "longShortRatio": "1.5"}]

    b_client._get = fake_binance_get  # type: ignore[method-assign]
    ls_b = await b_client.get_long_short_ratio("PEPEUSDT")
    assert ls_b is not None
    assert ("/futures/data/globalLongShortAccountRatio", "1000PEPEUSDT") in observed_calls
    await b_client.close()

    o_client = OKXClient()
    okx_params: list[dict] = []

    async def fake_okx_get(path: str, params: dict | None = None):
        okx_params.append(dict(params or {}))
        return [["1700000000000", "1.25"]]

    o_client._get = fake_okx_get  # type: ignore[method-assign]
    ls_o = await o_client.get_long_short_ratio("1000PEPEUSDT")
    assert ls_o is not None
    assert okx_params and okx_params[0].get("ccy") == "PEPE"
    await o_client.close()


def test_ls_ratio_is_contrarian():
    """Crowded retail longs must score -1 (contrarian SHORT), crowded shorts +1, balanced 0."""
    from engine.signal_engine import _compute_ls_ratio

    crowded_long = _compute_ls_ratio({"ls_ratio_data": {"long_ratio": 0.72, "short_ratio": 0.28}, "open_interest_data": {"open_interest": 1e7}}, None)
    assert crowded_long["score"] == -1

    crowded_short = _compute_ls_ratio({"ls_ratio_data": {"long_ratio": 0.28, "short_ratio": 0.72}, "open_interest_data": {"open_interest": 1e7}}, None)
    assert crowded_short["score"] == 1

    neutral = _compute_ls_ratio({"ls_ratio_data": {"long_ratio": 0.50, "short_ratio": 0.50}, "open_interest_data": {"open_interest": 1e7}}, None)
    assert neutral["score"] == 0


def test_spot_futures_cvd_aligns_overlapping_time_window():
    """Spot vs Futures CVD must intersect timestamps and split halves by midpoint timestamp."""
    from engine.signal_engine import _compute_spot_futures_cvd, _compute_cvd

    # Spot has old heavy selling at t=1000..1500 outside Futures window (t=1800..2000),
    # while during overlap t=1800..2000 BOTH Spot and Futures are organically buying.
    spot_trades = [
        {"time": 1000 + i * 50, "qty": 100.0, "is_buyer_maker": True}
        for i in range(6)
    ] + [
        {"time": 1800 + i * 20, "qty": 20.0, "is_buyer_maker": False}
        for i in range(6)
    ]
    futures_trades = [
        {"time": 1800 + i * 20, "qty": 20.0, "is_buyer_maker": False}
        for i in range(6)
    ]
    res = _compute_spot_futures_cvd({"spot_trades": spot_trades}, {"trades": futures_trades})
    assert res["score"] == 2, f"Expected organic overlap score +2, got {res}"

    # Verify _compute_cvd uses time-midpoint instead of unequal array index length split:
    # 8 small buys in [1000, 1100] and 2 huge sells in [1900, 1950] -> midpoint t=1475 cleanly puts sells in second half
    uneven_trades = [
        {"time": 1000 + i * 10, "qty": 1.0, "is_buyer_maker": False}
        for i in range(8)
    ] + [
        {"time": 1900 + i * 50, "qty": 2.0, "is_buyer_maker": True}
        for i in range(2)
    ]
    cvd = _compute_cvd(uneven_trades)
    assert cvd["rising"] is False


def test_hyperliquid_signal_deduplicated_and_cross_exchange_neutral():
    """Hyperliquid should score only DEX-vs-CEX spread when CEX consensus is supplied; cross_exchange is always 0."""
    from engine.signal_engine import _compute_hyperliquid_signal, _compute_cross_exchange

    hl = {"funding_rate": 0.0005, "basis_pct": 0.08, "mark_price": 100.08, "oracle_price": 100.0, "open_interest": 5e6}
    # When DEX matches CEX consensus closely -> no redundant stacked score
    dedup = _compute_hyperliquid_signal(hl, cex_funding_rate=0.0005, cex_basis_pct=0.08)
    assert dedup["score"] == 0

    # Significant DEX bearish funding crowding relative to CEX -> incremental -1 max
    div = _compute_hyperliquid_signal(
        {"funding_rate": 0.0008, "basis_pct": 0.09, "mark_price": 100.09, "oracle_price": 100.0, "open_interest": 5e6},
        cex_funding_rate=0.0001,
        cex_basis_pct=0.01,
    )
    assert div["score"] == -1

    # Cross-exchange dislocation must stay non-directional (score == 0, dislocation_risk flag True)
    cross = _compute_cross_exchange(
        {"ohlcv": {"5m": [{"close": 100.0}, {"close": 100.0}]}},
        {"ohlcv": {"5m": [{"close": 100.0}, {"close": 100.6}]}},
    )
    assert cross["score"] == 0
    assert cross.get("dislocation_risk") is True


def test_confluence_cluster_cap_and_whale_dedup():
    """Order flow factors (cvd, spot_futures_cvd, whale_order_flow) must clamp at [-3, +3] and avoid taker dup."""
    from engine.confluence_scorer import ConfluenceScorer
    from engine.signal_engine import SignalEngine

    scorer = ConfluenceScorer()
    pos = scorer.compute({
        "cvd": {"score": 1},
        "spot_futures_cvd": {"score": 2},
        "whale_order_flow": {"score": 2},
    })
    assert pos["score"] == 3, f"Order flow cluster exceeded +3 cap: {pos}"

    neg = scorer.compute({
        "cvd": {"score": -1},
        "spot_futures_cvd": {"score": -2},
        "whale_order_flow": {"score": -2},
    })
    assert neg["score"] == -3, f"Order flow cluster exceeded -3 cap: {neg}"

    # SignalEngine with aggressive small taker trades ($500 each, 0 whale blocks) must give whale_order_flow score == 0
    small_buys = [{"time": 1000 + i * 100, "price": 100.0, "qty": 5.0, "is_buyer_maker": False} for i in range(15)]
    small_sells = [{"time": 2500 + i * 100, "price": 100.0, "qty": 2.0, "is_buyer_maker": True} for i in range(5)]
    candles = [
        {"timestamp": i * 3600_000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 100.0}
        for i in range(30)
    ]
    raw = {
        "symbol": "TESTUSDT",
        "binance": {
            "mark_price_data": {"mark_price": 100.5, "index_price": 100.5, "basis_pct": 0.0},
            "funding_rate_data": {"funding_rate": 0.0001},
            "open_interest_data": {"open_interest": 10_000_000.0, "oi_change_pct": 0.5},
            "trades": small_buys + small_sells,
            "spot_trades": small_buys + small_sells,
            "ohlcv": {"1m": candles, "5m": candles, "15m": candles, "1h": candles, "4h": candles, "1d": candles},
            "orderbook": {"bids": [[100.4, 100]], "asks": [[100.6, 100]]},
        },
        "bybit": None,
        "okx": None,
        "bitget": None,
        "hyperliquid": None,
    }
    res = SignalEngine().compute(raw)
    assert res["confluence"]["breakdown"]["whale_order_flow"]["score"] == 0


def test_circuit_breaker_and_fake_detector_force_strict_neutral_and_proxy_label():
    """Crowded funding veto or FakeDetector trigger must force direction='NEUTRAL' and trade_levels=None."""
    from engine.signal_engine import SignalEngine

    candles_up = [
        {"timestamp": i * 3600_000, "open": 100.0 + i * 0.6, "high": 101.2 + i * 0.6, "low": 99.6 + i * 0.6, "close": 101.0 + i * 0.6, "volume": 500.0}
        for i in range(40)
    ]
    candles_1m_clean = [
        {"timestamp": i * 60_000, "open": 124.0, "high": 124.5, "low": 123.8, "close": 124.2, "volume": 200.0}
        for i in range(30)
    ]
    whale_buys = [{"time": 1000 + i * 50, "price": 124.2, "qty": 500.0, "is_buyer_maker": False} for i in range(12)]
    base_raw = {
        "symbol": "CROWDUSDT",
        "binance": {
            "mark_price_data": {"mark_price": 124.2, "index_price": 124.2, "basis_pct": -0.06},  # neg basis -> +1 contrarian
            "funding_rate_data": {"funding_rate": -0.0001},
            "open_interest_data": {"open_interest": 5e7, "oi_change_pct": 1.2},  # +1 OI inflow
            "ls_ratio_data": {"long_ratio": 0.30, "short_ratio": 0.70},  # +1 contrarian LONG
            "trades": whale_buys,
            "spot_trades": whale_buys,
            "ohlcv": {"1m": candles_1m_clean, "5m": candles_up, "15m": candles_up, "1h": candles_up, "4h": candles_up, "1d": candles_up},
            "orderbook": {"bids": [[124.1, 5000]], "asks": [[124.3, 500]]},
        },
        "bybit": None,
        "okx": None,
        "bitget": None,
        "hyperliquid": None,
    }
    engine = SignalEngine()

    # Baseline (unvetoed) should be a clean LONG with trade_levels
    clean_res = engine.compute(base_raw)
    assert clean_res["direction"] == "LONG", f"Expected clean baseline LONG, got {clean_res['confluence']}"
    assert clean_res["trade_levels"] is not None
    assert clean_res["predictive"].get("method") == "swing_liquidity_proxy"

    # Case A: FakeDetector fires -> MUST veto direction to NEUTRAL & null trade_levels
    with patch("engine.signal_engine.FakeDetector.detect", return_value={"is_fake": True, "confidence": 0.9, "warnings": ["Test fake pump"], "is_perp_only": False}):
        fake_res = engine.compute(base_raw)
    assert fake_res["direction"] == "NEUTRAL"
    assert fake_res["conviction"] <= 3
    assert fake_res["trade_levels"] is None
    assert fake_res["confluence"].get("vetoed_from") == "LONG"

    # Case B: Extreme crowded positive funding (+0.08% > 0.05%) on an otherwise >=4 LONG setup -> MUST veto LONG to NEUTRAL
    crowded_raw = {
        **base_raw,
        "binance": {
            **base_raw["binance"],
            "funding_rate_data": {"funding_rate": 0.0008},
        },
    }
    crowd_res = engine.compute(crowded_raw)
    assert crowd_res["direction"] == "NEUTRAL"
    assert crowd_res["conviction"] <= 3
    assert crowd_res["trade_levels"] is None
    assert crowd_res["confluence"].get("vetoed_from") == "LONG"


def test_trade_plan_guarantees_minimum_one_to_one_and_two_to_one_rr():
    """_compute_trade_plan must compute risk first and enforce TP1 >= 1R, TP2 >= 2R for both LONG and SHORT."""
    from engine.signal_engine import _compute_trade_plan

    low_atr_candles = [
        {"timestamp": i * 3600_000, "open": 100.0, "high": 100.3, "low": 99.8, "close": 100.1, "volume": 100.0}
        for i in range(20)
    ]

    long_plan = _compute_trade_plan(
        direction="LONG",
        mark_price=100.0,
        ohlcv_1h=low_atr_candles,
        spot_futures_score=2,
        conviction=6,
        predictive_data={"nearest_support": 96.5, "nearest_resistance": 100.2},
    )
    l_lvl = long_plan["trade_levels"]
    l_risk = l_lvl["entry_price"] - l_lvl["stop_loss"]
    assert l_lvl["take_profit_1"] - l_lvl["entry_price"] >= l_risk - 1e-6
    assert l_lvl["take_profit_2"] - l_lvl["entry_price"] >= (2.0 * l_risk) - 1e-6

    short_plan = _compute_trade_plan(
        direction="SHORT",
        mark_price=100.0,
        ohlcv_1h=low_atr_candles,
        spot_futures_score=-2,
        conviction=6,
        predictive_data={"nearest_support": 99.8, "nearest_resistance": 103.5},
    )
    s_lvl = short_plan["trade_levels"]
    s_risk = s_lvl["stop_loss"] - s_lvl["entry_price"]
    assert s_lvl["entry_price"] - s_lvl["take_profit_1"] >= s_risk - 1e-6
    assert s_lvl["entry_price"] - s_lvl["take_profit_2"] >= (2.0 * s_risk) - 1e-6