Spaces:
Sleeping
Sleeping
Naufal Arhab
feat(engine): upgrade signal accuracy, L/S ratio split, chop gate, and trade stream buffer
13f15a5 Download tests/test_accuracy_upgrades.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 24.4 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/tests/test_accuracy_upgrades.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/tests/test_accuracy_upgrades.py
-
curl -L -o test_accuracy_upgrades.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/tests/test_accuracy_upgrades.py
24.4 kB
| """ | |
| Regression tests for accuracy upgrades (Paket 1 & Paket 2). | |
| Written TDD-first before implementation fixes. | |
| """ | |
| import os | |
| import sys | |
| from unittest.mock import patch | |
| import pytest | |
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend"))) | |
| def anyio_backend(): | |
| return "asyncio" | |
| async def test_ls_ratio_separates_retail_from_whale_positions(): | |
| """ | |
| Bybit account-ratio and OKX/Bitget retail fallback must tag retail_long_ratio / source='retail'. | |
| _compute_ls_ratio must never apply contrarian 'Crowded Retail Longs' to pure whale top-trader ratios. | |
| """ | |
| from exchanges.bybit import BybitClient | |
| from exchanges.okx import OKXClient | |
| from exchanges.bitget import BitgetClient | |
| from engine.signal_engine import _compute_ls_ratio | |
| byb = BybitClient() | |
| okx = OKXClient() | |
| bg = BitgetClient() | |
| try: | |
| async def _mock_byb_get(path: str, params: dict | None = None): | |
| return {"list": [{"buyRatio": "0.72", "sellRatio": "0.28"}]} | |
| byb._get = _mock_byb_get # type: ignore[method-assign] | |
| byb_ls = await byb.get_long_short_ratio("BTCUSDT") | |
| assert byb_ls["source"] == "retail" | |
| assert byb_ls["retail_long_ratio"] == pytest.approx(0.72) | |
| assert byb_ls["top_position_long_ratio"] is None | |
| async def _mock_okx_retail_only(path: str, params: dict | None = None): | |
| if "long-short-account-ratio" in path: | |
| return [["1700000000000", "2.0"]] # 2 / 3 = 0.6667 | |
| raise RuntimeError("top position endpoint down") | |
| okx._get = _mock_okx_retail_only # type: ignore[method-assign] | |
| okx_ls = await okx.get_long_short_ratio("BTCUSDT") | |
| assert okx_ls["source"] == "retail" | |
| assert okx_ls["retail_long_ratio"] == pytest.approx(0.6667, abs=1e-4) | |
| assert okx_ls["top_position_long_ratio"] is None | |
| async def _mock_bg_retail_only(path: str, params: dict | None = None): | |
| if "account-long-short" in path: | |
| return [{"longRatio": "0.68", "shortRatio": "0.32"}] | |
| return [] | |
| bg._get = _mock_bg_retail_only # type: ignore[method-assign] | |
| bg_ls = await bg.get_long_short_ratio("BTCUSDT") | |
| assert bg_ls["source"] == "retail" | |
| assert bg_ls["retail_long_ratio"] == pytest.approx(0.68) | |
| assert bg_ls["top_position_long_ratio"] is None | |
| finally: | |
| await byb.close() | |
| await okx.close() | |
| await bg.close() | |
| # Pure whale top-trader longs (0.72) with NO retail_long_ratio must NOT trigger contrarian -1 short! | |
| okx_whale_only = { | |
| "open_interest_data": {"open_interest_value": 5_000_000.0}, | |
| "ls_ratio_data": { | |
| "long_ratio": 0.72, | |
| "short_ratio": 0.28, | |
| "top_position_long_ratio": 0.72, | |
| "retail_long_ratio": None, | |
| "source": "top_trader", | |
| }, | |
| } | |
| res_whale_only = _compute_ls_ratio(None, None, okx_data=okx_whale_only, bitget_data=None) | |
| assert res_whale_only["score"] == 0, f"Must not contrarian-short pure whale positions: {res_whale_only}" | |
| assert res_whale_only["retail"] is None | |
| # Mixed venues: OKX whale=0.68, Bybit retail=0.66 (delta=+0.02 < 0.07) -> contrarian checks RETAIL (0.66 >= 0.62 -> -1) | |
| byb_retail = { | |
| "open_interest_data": {"open_interest_value": 5_000_000.0}, | |
| "ls_ratio_data": { | |
| "long_ratio": 0.66, | |
| "short_ratio": 0.34, | |
| "retail_long_ratio": 0.66, | |
| "top_position_long_ratio": None, | |
| "source": "retail", | |
| }, | |
| } | |
| res_mixed = _compute_ls_ratio(None, byb_retail, okx_data=okx_whale_only, bitget_data=None) | |
| assert res_mixed["score"] == -1 | |
| assert "Crowded Retail Longs" in res_mixed["label"] | |
| def test_non_collinear_confirmation_blocks_pure_orderflow_cluster(): | |
| """ | |
| Live mode (horizon_thresholds=None) must NOT trigger LONG/SHORT from purely collinear | |
| micro-orderflow/orderbook factors (cvd + spot_futures_cvd + orderbook_skew) when all | |
| structural/derivatives factors (market_structure, oi_divergence, funding, ls_ratio, basis, hl) are 0. | |
| """ | |
| from engine.signal_engine import SignalEngine | |
| now_ms = 1_700_000_000_000 | |
| mock_mtf_neutral = { | |
| "active_timeframe": "15m", | |
| "structure_per_tf": {"15m": "ranging", "1h": "ranging"}, | |
| "score": 0, | |
| "label": "Ranging", | |
| "market_condition": "ranging", | |
| "regime": "ranging", | |
| "intraday_structure": 0, | |
| "swing_structure": 0, | |
| "intraday_atr_stretch": 0.0, | |
| "swing_atr_stretch": 0.0, | |
| } | |
| raw = { | |
| "symbol": "BTCUSDT", | |
| "has_spot": True, | |
| "binance": { | |
| "mark_price_data": {"mark_price": 50000.0, "index_price": 50000.0, "basis_pct": 0.0}, | |
| "funding_rate_data": {"funding_rate": 0.0, "funding_rate_pct": 0.0}, | |
| "open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 0.0, "oi_horizon": "15m"}, | |
| "trades": [], | |
| "ohlcv": { | |
| "15m": [ | |
| {"timestamp": now_ms + i * 900_000, "open": 50000.0, "high": 50050.0, "low": 49950.0, "close": 50000.0, "volume": 10.0} | |
| for i in range(5) | |
| ] | |
| }, | |
| "orderbook": {"bids": [[49990.0, 100.0]], "asks": [[50010.0, 10.0]]}, | |
| }, | |
| "bybit": None, | |
| "okx": None, | |
| "bitget": None, | |
| "hyperliquid": None, | |
| } | |
| mock_ob_bull = { | |
| "score": 1, | |
| "resting_pressure": "BUY_WALL", | |
| "tight_bid_depth_usd": 500_000.0, | |
| "tight_ask_depth_usd": 50_000.0, | |
| } | |
| with patch("engine.signal_engine.mtf_analyzer.analyze", return_value=mock_mtf_neutral), \ | |
| patch("engine.signal_engine._compute_cvd", return_value={"score": 1, "rising": True, "label": "Bull CVD"}), \ | |
| patch("engine.signal_engine._compute_spot_futures_cvd", return_value={"score": 1, "label": "Spot Lead"}), \ | |
| patch("engine.signal_engine._compute_oi_divergence", return_value={"score": 0, "intraday_score": 0, "swing_score": 0, "label": "Neutral OI"}), \ | |
| patch("engine.signal_engine._compute_whale_order_flow", return_value={"whale_composite_score": 0, "flow_verdict": "Neutral"}), \ | |
| patch("engine.signal_engine._compute_orderbook_skew", return_value=mock_ob_bull): | |
| res_collinear = SignalEngine().compute(raw, horizon_thresholds=None) | |
| assert res_collinear["direction"] == "NEUTRAL" | |
| assert res_collinear["conviction"] <= 2 | |
| assert res_collinear["horizons"]["intraday"]["unconfirmed_single_factor"] is True | |
| assert res_collinear["horizons"]["primary"]["unconfirmed_single_factor"] is True | |
| async def test_outcome_evaluator_horizon_isolation_and_multi_exchange_fallback(): | |
| """ | |
| 1. Top-level ANTI_CHASING_EXTREME (from intraday) must NOT mark an unvetoed live SHORT swing | |
| horizon as vetoed/skipped in async_log_prediction_if_new. | |
| 2. An explicitly non-vetoed NEUTRAL intraday horizon must NOT inherit another horizon's top-level veto. | |
| 3. async_evaluate_pending_predictions falls back to okx/bitget when binance & bybit return empty. | |
| """ | |
| from database.memory_store import memory_store | |
| from engine.outcome_evaluator import _to_epoch_ms, async_evaluate_pending_predictions, async_log_prediction_if_new | |
| memory_store.reset() | |
| # Case 1: intraday vetoed by ANTI_CHASING_EXTREME (no _shadow_trade_levels), top-level echoes it, | |
| # while swing is live SHORT with veto_reason=None and valid trade_levels. | |
| sig = { | |
| "symbol": "ETHUSDT", | |
| "direction": "NEUTRAL", | |
| "conviction": 3, | |
| "veto_reason": "ANTI_CHASING_EXTREME", | |
| "vetoed_from": "LONG", | |
| "sniper_grade": "WAIT", | |
| "horizons": { | |
| "intraday": { | |
| "direction": "NEUTRAL", | |
| "veto_reason": None, # suppose unvetoed NEUTRAL on intraday while swing blocked, or vice versa | |
| "conviction": 2, | |
| "regime": "ranging", | |
| "trade_levels": None, | |
| }, | |
| "swing": { | |
| "direction": "SHORT", | |
| "veto_reason": None, | |
| "conviction": 4, | |
| "regime": "trending", | |
| "trade_levels": {"entry_price": 3000.0, "stop_loss": 3150.0, "take_profit_1": 2800.0, "take_profit_2": 2600.0}, | |
| "factor_scores": {"market_structure": -2, "oi_divergence": -1, "funding_rate": -1}, | |
| }, | |
| }, | |
| } | |
| with patch("database.db.DATABASE_URL", ""): | |
| logged = await async_log_prediction_if_new(sig) | |
| assert len(logged) == 1 | |
| assert logged[0]["horizon"] == "swing" | |
| assert logged[0]["is_shadow"] is False | |
| assert logged[0]["veto_reason"] is None | |
| assert logged[0]["direction"] == "SHORT" | |
| # Case 2: Evaluate via OKX fallback client when Binance & Bybit fail/empty | |
| class _EmptyExch: | |
| async def get_ohlcv(self, symbol: str, tf: str, limit: int = 100): | |
| return [] | |
| class _OkxFallback: | |
| async def get_ohlcv(self, symbol: str, tf: str, limit: int = 100): | |
| return [ | |
| {"timestamp": _to_epoch_ms(logged[0]["created_at"]) + 3_600_000, "high": 2980.0, "low": 2550.0, "close": 2600.0} | |
| ] | |
| with patch("database.db.DATABASE_URL", ""): | |
| eval_res = await async_evaluate_pending_predictions( | |
| _EmptyExch(), | |
| _EmptyExch(), | |
| okx_client=_OkxFallback(), | |
| ) | |
| assert eval_res["resolved"] == 1 | |
| def test_ai_prompt_separates_basis_spread_from_cross_exchange_divergence(): | |
| """_build_ai_prompt must display Basis Spread from signals['basis']['value'], not cross_exchange divergence_pct.""" | |
| from routers.ai import _build_ai_prompt | |
| sig = { | |
| "symbol": "SOLUSDT", | |
| "direction": "LONG", | |
| "conviction": 5, | |
| "signal_data": { | |
| "signals": { | |
| "basis": {"score": 1, "value": 0.125, "label": "Deep Discount"}, | |
| "cross_exchange": {"divergence_pct": 0.042, "label": "Tight Spread"}, | |
| }, | |
| "exchange_data": { | |
| "binance": {"mark_price": 150.0, "index_price": 149.8, "oi": 1e7, "funding_rate": 0.0001}, | |
| }, | |
| }, | |
| } | |
| prompt, _ = _build_ai_prompt("SOLUSDT", sig, [{"exchange": "binance", "mark_price": 150.0, "index_price": 149.8}]) | |
| assert "Basis Spread: +0.125%" in prompt | |
| assert "+0.042%" in prompt | |
| def test_breakout_radar_ignores_false_magnet_proximity_bias(): | |
| """Closer upper liquidation magnet alone must NOT produce BREAKOUT_UP directional bias in neutral squeeze.""" | |
| from engine.signal_engine import _compute_breakout_radar | |
| pred = { | |
| "volatility_squeeze": {"is_squeeze": True, "compression_ratio": 0.45, "squeeze_intensity": "EXTREME SQUEEZE"}, | |
| "orderbook_skew": {"skew_ratio": 0.0, "resting_pressure": "BALANCED"}, | |
| "liquidation_magnets": {"primary_magnet": "UPPER"}, | |
| } | |
| res = _compute_breakout_radar( | |
| direction="NEUTRAL", | |
| conviction=0, | |
| predictive_data=pred, | |
| oi_signal={"oi_change_pct": 0.0}, | |
| whale_flow={"taker_ratio": 1.0, "whale_buy_vol_usd": 0.0, "whale_sell_vol_usd": 0.0}, | |
| ) | |
| assert res["is_breakout_primed"] is True | |
| assert res["projected_direction"] == "COILING_NEUTRAL" | |
| def test_mtf_efficiency_ratio_detects_chop_as_ranging(): | |
| """Sideways overlapping chop with normal ATR ratio (~1.0) must classify as 'ranging', not 'trending'.""" | |
| from engine.mtf_analyzer import MTFAnalyzer | |
| # Generate 40 alternating zigzag candles with constant true range (ATR ratio ~ 1.0) | |
| chop_1h = [] | |
| px = 100.0 | |
| for i in range(40): | |
| nxt = 101.0 if i % 2 == 0 else 100.0 | |
| chop_1h.append({ | |
| "timestamp": i * 3_600_000, | |
| "open": px, | |
| "high": max(px, nxt) + 0.5, | |
| "low": min(px, nxt) - 0.5, | |
| "close": nxt, | |
| "volume": 500.0, | |
| }) | |
| px = nxt | |
| trend_1h = [] | |
| for i in range(40): | |
| base = 100.0 + i * 0.8 | |
| trend_1h.append({ | |
| "timestamp": i * 3_600_000, | |
| "open": base, | |
| "high": base + 0.9, | |
| "low": base - 0.1, | |
| "close": base + 0.75, | |
| "volume": 500.0, | |
| }) | |
| analyzer = MTFAnalyzer() | |
| res_chop = analyzer.analyze({"1h": chop_1h, "15m": chop_1h, "4h": chop_1h}) | |
| assert res_chop["market_condition"] == "ranging" | |
| assert res_chop["efficiency_ratio"] < 0.25 | |
| res_trend = analyzer.analyze({"1h": trend_1h, "15m": trend_1h, "4h": trend_1h}) | |
| assert res_trend["market_condition"] == "trending" | |
| assert res_trend["efficiency_ratio"] > 0.7 | |
| def test_oi_divergence_requires_exhaustion_confirmation_on_full_candles(): | |
| """ | |
| With >= 3 full OHLC bars: | |
| - Strong marubozu green breakout + OI down must NOT blindly score -1 (Short Covering Rally). | |
| - Upper-wick rejection candle + OI down DOES score -1 (Short Covering Exhaustion). | |
| - Strong red capitulation dump + OI down must NOT blindly score +1 (Falling Knife). | |
| """ | |
| from engine.signal_engine import _compute_oi_divergence | |
| base_bars = [ | |
| {"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.0}, | |
| {"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.2}, | |
| ] | |
| # 1. Strong marubozu breakout closing near high on OI unwind -> wait confirmation (0) | |
| marubozu_up = base_bars + [{"open": 100.2, "high": 102.0, "low": 100.1, "close": 101.95}] | |
| res_breakout = _compute_oi_divergence( | |
| {"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": -0.8, "oi_horizon": "15m"}, "ohlcv": {"15m": marubozu_up}}, | |
| None, | |
| ) | |
| assert res_breakout["score"] == 0 | |
| # 2. Upper-wick shooting-star rejection on OI unwind -> exhaustion (-1) | |
| rejection_up = base_bars + [{"open": 100.2, "high": 103.0, "low": 100.1, "close": 101.1}] | |
| res_reject = _compute_oi_divergence( | |
| {"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": -0.8, "oi_horizon": "15m"}, "ohlcv": {"15m": rejection_up}}, | |
| None, | |
| ) | |
| assert res_reject["score"] == -1 | |
| # 3. Clean red capitulation close near low on OI unwind -> falling knife guard (0) | |
| dump_down = [ | |
| {"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.0}, | |
| {"open": 100.0, "high": 100.2, "low": 99.5, "close": 99.8}, | |
| {"open": 99.8, "high": 99.9, "low": 98.0, "close": 98.05}, | |
| ] | |
| res_dump = _compute_oi_divergence( | |
| {"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": -0.8, "oi_horizon": "15m"}, "ohlcv": {"15m": dump_down}}, | |
| None, | |
| ) | |
| assert res_dump["score"] == 0 | |
| def test_swing_uses_macro_kline_cvd_and_btc_macro_beta_guard(): | |
| """ | |
| 1. Swing horizon factors use 4h/1h taker flow (not 15m micro bursts). | |
| 2. Altcoin LONG setups receive -1 macro headwind adjustment when btc_context signals active BTC_DUMP. | |
| """ | |
| from engine.signal_engine import SignalEngine | |
| now_ms = 1_700_000_000_000 | |
| # 15m bullish micro taker buys, while 4h taker flow is heavily bearish (seller dominated) | |
| bars_15m = [ | |
| {"timestamp": now_ms + i * 900_000, "open": 100.0, "high": 101.0, "low": 99.5, "close": 100.6, "volume": 500.0, "taker_buy_volume": 420.0} | |
| for i in range(20) | |
| ] | |
| bars_4h = [ | |
| {"timestamp": now_ms + i * 14_400_000, "open": 105.0 - i * 0.2, "high": 105.5 - i * 0.2, "low": 103.5 - i * 0.2, "close": 104.0 - i * 0.2, "volume": 5000.0, "taker_buy_volume": 1200.0} | |
| for i in range(20) | |
| ] | |
| bars_1h = list(bars_4h) | |
| raw = { | |
| "symbol": "SOLUSDT", | |
| "has_spot": True, | |
| "binance": { | |
| "mark_price_data": {"mark_price": 101.0, "index_price": 101.0, "basis_pct": 0.0}, | |
| "funding_rate_data": {"funding_rate": 0.0}, | |
| "open_interest_data": {"open_interest": 1e6, "oi_change_pct": 0.1, "oi_horizon": "15m"}, | |
| "trades": [], | |
| "ohlcv": {"15m": bars_15m, "1h": bars_1h, "4h": bars_4h, "1d": bars_4h}, | |
| "orderbook": {"bids": [[100.9, 500.0]], "asks": [[101.1, 500.0]]}, | |
| }, | |
| "bybit": None, "okx": None, "bitget": None, "hyperliquid": None, | |
| } | |
| eng = SignalEngine() | |
| res_no_btc = eng.compute(raw) | |
| assert res_no_btc["horizons"]["intraday"]["factor_scores"]["cvd"] == 1 | |
| assert res_no_btc["horizons"]["swing"]["factor_scores"]["cvd"] == -1 | |
| # BTC Soft Beta-Guard: mock strong bullish altcoin raw, then pass btc_dump market_context | |
| bull_bars = [ | |
| {"timestamp": now_ms + i * 3_600_000, "open": 100.0 + i * 0.5, "high": 101.0 + i * 0.5, "low": 99.6 + i * 0.5, "close": 100.8 + i * 0.5, "volume": 1000.0, "taker_buy_volume": 750.0} | |
| for i in range(30) | |
| ] | |
| bull_raw = { | |
| "symbol": "SOLUSDT", | |
| "has_spot": True, | |
| "binance": { | |
| "mark_price_data": {"mark_price": 115.0, "index_price": 115.0, "basis_pct": -0.05}, | |
| "funding_rate_data": {"funding_rate": -0.0001}, | |
| "open_interest_data": {"open_interest": 1e7, "oi_change_pct": 1.2, "oi_horizon": "15m"}, | |
| "ls_ratio_data": {"long_ratio": 0.34, "short_ratio": 0.66, "retail_long_ratio": 0.34}, | |
| "trades": [], | |
| "ohlcv": {"15m": bull_bars, "1h": bull_bars, "4h": bull_bars, "1d": bull_bars}, | |
| "orderbook": {"bids": [[114.9, 1000.0]], "asks": [[115.1, 500.0]]}, | |
| }, | |
| "bybit": None, "okx": None, "bitget": None, "hyperliquid": None, | |
| } | |
| res_clean = eng.compute(bull_raw) | |
| res_btc_dump = eng.compute( | |
| bull_raw, | |
| market_context={"btc_direction": "SHORT", "btc_conviction": 5, "btc_regime": "trending", "btc_1h_change_pct": -2.0}, | |
| ) | |
| assert res_btc_dump["horizons"]["intraday"]["score"] < res_clean["horizons"]["intraday"]["score"] | |
| assert res_btc_dump["confluence"].get("btc_macro_guard") == "BTC_DUMP_HEADWIND" | |
| def test_ws_trade_ring_buffer_parses_and_expires(): | |
| """TradeStreamBuffer ingests Binance/Bybit WebSocket trade messages, deduplicates, and expires old trades.""" | |
| from engine.ws_trade_stream import TradeStreamBuffer | |
| buf = TradeStreamBuffer(max_age_sec=60, max_trades_per_key=100) | |
| now_ms = 1_700_000_000_000 | |
| buf.ingest_binance_message({ | |
| "stream": "btcusdt@aggTrade", | |
| "data": {"e": "aggTrade", "s": "BTCUSDT", "p": "65000.5", "q": "1.25", "m": False, "T": now_ms}, | |
| }, now_ts=now_ms / 1000.0) | |
| buf.ingest_binance_message({ | |
| "stream": "btcusdt@aggTrade", | |
| "data": {"e": "aggTrade", "s": "BTCUSDT", "p": "64900.0", "q": "0.50", "m": True, "T": now_ms - 120_000}, | |
| }, now_ts=now_ms / 1000.0) | |
| buf.ingest_bybit_message({ | |
| "topic": "publicTrade.BTCUSDT", | |
| "data": [{"s": "BTCUSDT", "p": "65001.0", "v": "0.75", "S": "Sell", "T": now_ms + 500}], | |
| }, now_ts=(now_ms + 500) / 1000.0) | |
| bnb_trades = buf.get_recent_trades("binance", "BTCUSDT", now_ts=now_ms / 1000.0) | |
| assert len(bnb_trades) == 1 | |
| assert bnb_trades[0]["price"] == pytest.approx(65000.5) | |
| assert bnb_trades[0]["qty"] == pytest.approx(1.25) | |
| assert bnb_trades[0]["is_buyer_maker"] is False | |
| byb_trades = buf.get_recent_trades("bybit", "BTCUSDT", now_ts=(now_ms + 500) / 1000.0) | |
| assert len(byb_trades) == 1 | |
| assert byb_trades[0]["is_buyer_maker"] is True | |
| def test_chop_gate_and_htf_countertrend_guard(): | |
| """ | |
| 1. Low directional efficiency chop (ER < 0.25) raises effective entry threshold (+2) | |
| on intraday/primary so weak chop whipsaws stay NEUTRAL (chop_filtered=True). | |
| 2. Intraday fighting strong opposing swing_structure (+/-2) without spot/whale reversal | |
| receives -1 / +1 HTF Counter-Trend penalty (htf_countertrend_guarded=True). | |
| """ | |
| from engine.signal_engine import SignalEngine | |
| now_ms = 1_700_000_000_000 | |
| base_raw = { | |
| "symbol": "ETHUSDT", | |
| "has_spot": True, | |
| "binance": { | |
| "mark_price_data": {"mark_price": 2500.0, "index_price": 2500.0, "basis_pct": 0.0}, | |
| "funding_rate_data": {"funding_rate": 0.0}, | |
| "open_interest_data": {"open_interest": 1e6, "oi_change_pct": 0.0, "oi_horizon": "15m"}, | |
| "trades": [], | |
| "ohlcv": { | |
| "15m": [{"timestamp": now_ms + i * 900_000, "open": 2500.0, "high": 2510.0, "low": 2490.0, "close": 2500.0, "volume": 100.0} for i in range(5)], | |
| "1h": [{"timestamp": now_ms + i * 3_600_000, "open": 2500.0, "high": 2515.0, "low": 2485.0, "close": 2500.0, "volume": 200.0} for i in range(5)], | |
| }, | |
| "orderbook": {"bids": [[2499.0, 100.0]], "asks": [[2501.0, 100.0]]}, | |
| }, | |
| "bybit": None, "okx": None, "bitget": None, "hyperliquid": None, | |
| } | |
| # Case 1: Choppy low-ER (0.15) with score=+3 (1+1+1) in live mode (needs >=5 in chop) | |
| mock_mtf_chop = { | |
| "active_timeframe": "1h", "regime": "ranging", "market_condition": "ranging", | |
| "atr_ratio": 1.0, "efficiency_ratio": 0.15, "swing_efficiency_ratio": 0.45, | |
| "score": 1, "intraday_structure": 1, "swing_structure": 1, | |
| "label": "Choppy", "structure_per_tf": {"15m": "bullish", "1h": "ranging", "4h": "bullish", "1d": "ranging"}, | |
| "intraday_atr_stretch": 0.2, "swing_atr_stretch": 0.2, | |
| } | |
| with patch("engine.signal_engine.mtf_analyzer.analyze", return_value=mock_mtf_chop), \ | |
| patch("engine.signal_engine._compute_cvd", return_value={"score": 1, "rising": True, "label": "Bull"}), \ | |
| patch("engine.signal_engine._compute_oi_divergence", return_value={"score": 1, "intraday_score": 1, "swing_score": 1, "label": "OI Bull"}), \ | |
| patch("engine.signal_engine._compute_basis", return_value={"score": 1, "value": -0.25, "label": "Disc"}): | |
| res_chop = SignalEngine().compute(base_raw) | |
| assert res_chop["horizons"]["intraday"]["direction"] == "NEUTRAL" | |
| assert res_chop["horizons"]["intraday"].get("chop_filtered") is True | |
| # Case 2: Unconfirmed counter-trend LONG against strong bearish swing_structure (-2) with ER >= 0.35 | |
| mock_mtf_counter = { | |
| "active_timeframe": "1h", "regime": "trending", "market_condition": "trending", | |
| "atr_ratio": 1.0, "efficiency_ratio": 0.45, "swing_efficiency_ratio": 0.65, | |
| "score": 0, "intraday_structure": 1, "swing_structure": -2, | |
| "label": "Split", "structure_per_tf": {"15m": "bullish", "1h": "bullish", "4h": "bearish", "1d": "bearish"}, | |
| "intraday_atr_stretch": 0.2, "swing_atr_stretch": -0.5, | |
| } | |
| with patch("engine.signal_engine.mtf_analyzer.analyze", return_value=mock_mtf_counter), \ | |
| patch("engine.signal_engine._compute_cvd", return_value={"score": 1, "rising": True, "label": "Bull"}), \ | |
| patch("engine.signal_engine._compute_oi_divergence", return_value={"score": 1, "intraday_score": 1, "swing_score": -1, "label": "OI Bull"}), \ | |
| patch("engine.signal_engine._compute_spot_futures_cvd", return_value={"score": 0, "label": "Neutral"}), \ | |
| patch("engine.signal_engine._compute_whale_order_flow", return_value={"whale_composite_score": 0, "flow_verdict": "Neutral"}): | |
| res_counter = SignalEngine().compute(base_raw) | |
| assert res_counter["horizons"]["intraday"].get("htf_countertrend_guarded") is True | |
| assert res_counter["horizons"]["intraday"]["direction"] == "NEUTRAL" | |
| def test_trade_plan_horizon_specific_atr_cushion(): | |
| """Intraday 1.75 ATR / 0.35 buffer cushions wick noise without inflating Swing 1.5 ATR geometry.""" | |
| from engine.signal_engine import _compute_trade_plan | |
| candles = [{"open": 100.0, "high": 100.5, "low": 98.5, "close": 100.0} for _ in range(20)] # ATR = 2.0, swing low = 98.5 (-1.5%) | |
| swing_p = _compute_trade_plan("LONG", 100.0, candles, 1, 5, sl_min_pct=0.015, sl_max_pct=0.08, sl_fallback_max_pct=0.06) | |
| intra_p = _compute_trade_plan("LONG", 100.0, candles, 1, 5, sl_min_pct=0.008, sl_max_pct=0.04, sl_fallback_max_pct=0.035, sl_atr_mult=1.75, sl_struct_buffer_atr=0.35) | |
| sw_sl = swing_p["trade_levels"]["stop_loss"] # 98.5 - 0.2*2.0 = 98.1 (within [92.0, 98.5]) | |
| in_sl = intra_p["trade_levels"]["stop_loss"] # 98.5 - 0.35*2.0 = 97.8 (within [96.0, 99.2]) | |
| assert in_sl < sw_sl | |
| in_risk = 100.0 - in_sl | |
| assert intra_p["trade_levels"]["take_profit_1"] >= 100.0 + in_risk - 1e-6 | |
| assert intra_p["trade_levels"]["take_profit_2"] >= 100.0 + 2.0 * in_risk - 1e-6 | |