Perps-Terminal / tests /test_deep_audit_fixes.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
17.6 kB
"""
Regression test suite for genuine logic, calculation, auth, DB, and connector bugs
identified and fixed during the full-codebase deep audit.
"""
from __future__ import annotations
import asyncio
import os
import sys
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
def test_is_half_rising_and_spot_futures_cvd_slope():
from engine.signal_engine import _is_half_rising, _compute_spot_futures_cvd
# Decelerating buying: cumulative CVD is still rising (+1000 -> +1400)
decel_buys = [
{"time": 1000, "qty": 1100.0, "price": 100.0, "is_buyer_maker": False},
{"time": 1100, "qty": 100.0, "price": 100.0, "is_buyer_maker": True},
{"time": 2000, "qty": 500.0, "price": 100.0, "is_buyer_maker": False},
{"time": 2100, "qty": 100.0, "price": 100.0, "is_buyer_maker": True},
]
assert _is_half_rising(decel_buys, 1400.0) is True
# Decelerating selling: cumulative CVD is still falling (-1000 -> -1200)
decel_sells = [
{"time": 1000, "qty": 1100.0, "price": 100.0, "is_buyer_maker": True},
{"time": 1100, "qty": 100.0, "price": 100.0, "is_buyer_maker": False},
{"time": 2000, "qty": 300.0, "price": 100.0, "is_buyer_maker": True},
{"time": 2100, "qty": 100.0, "price": 100.0, "is_buyer_maker": False},
]
assert _is_half_rising(decel_sells, -1200.0) is False
# Strong organic Spot+Futures buying with decelerating Spot pace must NOT trigger Leverage Trap (-2)
fut_buys = [
{"time": 1000 + i * 200, "qty": 100.0 + i * 20, "price": 100.0, "is_buyer_maker": False}
for i in range(6)
]
spot_decel = [
{"time": 1000, "qty": 500.0, "price": 100.0, "is_buyer_maker": False},
{"time": 1200, "qty": 500.0, "price": 100.0, "is_buyer_maker": False},
{"time": 1400, "qty": 400.0, "price": 100.0, "is_buyer_maker": False},
{"time": 1600, "qty": 200.0, "price": 100.0, "is_buyer_maker": False},
{"time": 1800, "qty": 200.0, "price": 100.0, "is_buyer_maker": False},
{"time": 2000, "qty": 100.0, "price": 100.0, "is_buyer_maker": False},
]
sf = _compute_spot_futures_cvd({"spot_trades": spot_decel, "trades": fut_buys}, None, ref_mark_px=100.0)
assert sf["score"] == 2
assert "Leverage Trap" not in sf["label"]
def test_whale_order_flow_no_twap_dilution_and_trade_count_denominator():
from engine.signal_engine import _compute_whale_order_flow
# Binance has taker_buy_volume + trade_count; Bybit has huge volume without taker_buy_volume or trade_count
ex_candles = {
"binance": {
"15m": [
{"close": 100.0, "volume": 100.0, "taker_buy_volume": 80.0, "trade_count": 10},
]
},
"bybit": {
"15m": [
{"close": 100.0, "volume": 10_000.0, "taker_buy_volume": None},
]
},
}
wf = _compute_whale_order_flow(
trades=[],
mark_price=100.0,
exchange_candles=ex_candles,
)
# Only Binance's 80 buy / 20 sell -> (8000 - 2000) / 10000 = +0.60, not diluted by Bybit's 10,000*100
assert wf["twap_delta_ratio"] == pytest.approx(0.6, abs=1e-4)
assert wf["twap_tot_usd"] == pytest.approx(10_000.0, abs=1e-2)
# avg_trade_size_usd uses Binance's $10,000 / 10 = $1,000, not $1,010,000 / 10
assert wf["avg_trade_size_usd"] == pytest.approx(1_000.0, abs=1e-2)
def test_liquidation_cascade_synthetic_dominance_short_squeeze():
from engine.signal_engine import _compute_liquidation_cascade
# Both taker sell and taker buy > $500k synth_floor, but taker buy dominates 5x (short squeeze)
res = _compute_liquidation_cascade(
liquidations=[],
oi_signal={"oi_change_pct": -1.2},
whale_flow={"taker_sell_vol_usd": 1_000_000.0, "taker_buy_vol_usd": 5_000_000.0},
spot_futures_signal={"score": -1},
adv_floor_usd=250_000.0,
)
assert res["short_liq_usd"] > 0.0
assert res["long_liq_usd"] == 0.0
assert res["score"] < 0
def test_predictive_engine_preserves_onchain_method():
from engine.predictive_engine import PredictiveEngine
ohlcv = {
"15m": [{"high": 101.0, "low": 99.0, "close": 100.0, "volume": 10.0} for _ in range(25)],
"1h": [{"high": 102.0, "low": 98.0, "close": 100.0, "volume": 50.0} for _ in range(25)],
}
res = PredictiveEngine().analyze(
mark_price=100.0,
ohlcv=ohlcv,
orderbook={"bids": [[99.9, 100.0]], "asks": [[100.1, 100.0]]},
direction="LONG",
conviction=4,
hl_liq_clusters={
"short_liq_clusters": [{"price": 105.0, "notional_usd": 500_000.0, "distance_pct": 5.0}],
"long_liq_clusters": [{"price": 95.0, "notional_usd": 400_000.0, "distance_pct": -5.0}],
},
)
assert res["method"] == "hyperliquid_onchain_liq_map"
def test_l2_microstructure_bucket_aggregation_truncation_and_trade_dedup():
from engine.l2_microstructure import L2OrderbookTracker
tracker = L2OrderbookTracker()
mark_px = 100_000.0
# Two levels inside the SAME 5-bps bucket: second is >1.3x larger than first
bids = [[99_960.0, 0.1], [99_970.0, 0.5]]
asks = [[100_040.0, 0.2]]
tracker.update_book("BTCUSDT", bids, asks, mark_price=mark_px, now_ts=1000.0)
st = tracker._get_state("BTCUSDT")
assert len(st.bid_buckets) == 1
bucket = next(iter(st.bid_buckets.values()))
assert bucket.refill_count == 0
assert bucket.current_visible_usd == pytest.approx(99_960.0 * 0.1 + 99_970.0 * 0.5, rel=1e-4)
# Top-25 truncation test: deeper wall at 99,000 must NOT be zeroed when bids[:25] only reaches 99,800
wall_tracker = L2OrderbookTracker()
wall_tracker.update_book("ETHUSDT", [[2686.5, 100_000.0 / 2686.5]], [], mark_price=2700.0, now_ts=1000.0)
# Next update has closer orders at 2698..2699 pushing 2686.5 outside top-25 window
closer_bids = [[2698.0 + i * 0.05, 1.0] for i in range(25)]
wall_tracker.update_book("ETHUSDT", closer_bids, [], mark_price=2698.5, now_ts=1005.0)
res_trunc = wall_tracker.evaluate_iceberg_and_spoof("ETHUSDT", mark_price=2698.5, adv_floor_usd=5000.0)
assert res_trunc["spoof_pulled"] is False
# Trade dedup across replayed SignalEngine cycles
dedup_tracker = L2OrderbookTracker()
dedup_tracker.update_book("SOLUSDT", [[100.0, 100.0]], [[100.2, 100.0]], mark_price=100.1, now_ts=1000.0)
for _ in range(5):
dedup_tracker.record_trade(
"SOLUSDT",
price=100.0,
qty=50.0,
is_sell=True,
mark_price=100.1,
trade_time_ms=999_000,
venue="binance",
trade_id="t1",
now_ts=1000.0,
)
st_sol = dedup_tracker._get_state("SOLUSDT")
sol_bucket = next(iter(st_sol.bid_buckets.values()))
assert sol_bucket.executed_taker_sell_usd == pytest.approx(5000.0, rel=1e-6)
def test_hl_whale_tracker_partial_reduce_pnl_and_k_prefix():
from engine.hl_whale_tracker import HyperliquidWhaleTracker
async def _run():
tracker = HyperliquidWhaleTracker()
addr = "0xabc1234567890abcdef1234567890abcdef12345"
tracker.register_trade(taker_wallet=addr, coin="BTC", price=90000.0, qty=2.0, side="BUY")
client = MagicMock()
# Snapshot 1: Long 10 BTC @ entry 90,000 (mark 90,000)
client.get_clearinghouse_state = AsyncMock(return_value={
"marginSummary": {"accountValue": "1000000.0"},
"assetPositions": [{
"position": {
"coin": "BTC",
"szi": "10.0",
"entryPx": "90000.0",
"positionValue": "900000.0",
"unrealizedPnl": "0.0",
"returnOnEquity": "0.0",
"liquidationPx": "80000.0",
"leverage": {"value": 2.0},
}
}],
})
await tracker.poll_wallet(addr, client=client)
# Snapshot 2: Reduced to 5 BTC while entryPx stays 90,000 and mark rises to 95,000 (posVal = 475,000)
client.get_clearinghouse_state = AsyncMock(return_value={
"marginSummary": {"accountValue": "1050000.0"},
"assetPositions": [
{
"position": {
"coin": "BTC",
"szi": "5.0",
"entryPx": "90000.0",
"positionValue": "475000.0",
"unrealizedPnl": "25000.0",
"returnOnEquity": "0.10",
"liquidationPx": "80000.0",
"leverage": {"value": 2.0},
}
},
{
"position": {
"coin": "kPEPE",
"szi": "10000.0",
"entryPx": "0.01",
"positionValue": "120.0",
"unrealizedPnl": "20.0",
"returnOnEquity": "0.20",
"liquidationPx": "0.005",
"leverage": {"value": 3.0},
}
},
],
})
w = await tracker.poll_wallet(addr, client=client)
assert w["win_count"] == 1
assert w["loss_count"] == 0
assert w["cumulative_pnl_usd"] == pytest.approx(25_000.0, rel=1e-4)
pepe_summary = tracker.get_coin_whale_summary("1000PEPEUSDT", mark_price=0.012)
assert pepe_summary["top_whales_long_count"] == 1
assert pepe_summary["raw_long_usd"] == pytest.approx(120.0, rel=1e-4)
asyncio.run(_run())
def test_factor_calibrator_replay_side_and_negative_expectancy_ranking():
from engine.factor_calibrator import record_microstructure_tape_slice, calibrate_whale_thresholds
with patch("engine.factor_calibrator.db_insert_microstructure_tape", side_effect=lambda d: d):
row = record_microstructure_tape_slice(
symbol="BTCUSDT",
signal_dict={
"symbol": "BTCUSDT",
"price_extremes": {"mark_price": 90000.0},
"whale_flow": {"twap_net_delta_usd": 30_000.0, "twap_delta_ratio": 0.5},
"liquidation_cascade": {},
"l2_microstructure": {},
"horizons": {},
"signals": {},
},
exchange_data={
"binance": {
"trades": [
{"price": 90000.0, "qty": 1.0, "is_buyer_maker": True},
{"price": 90000.0, "qty": 0.5, "is_buyer_maker": False},
]
}
},
now_ms=1_700_000_000_000,
force=True,
)
assert row["whale_sub_metrics"]["twap_tot_usd"] == pytest.approx(60_000.0, rel=1e-4)
sides = [t["s"] for t in row["raw_replay_slice"]["top_trades"]]
assert sides == ["S", "B"]
# Negative returns: higher hit rate / less negative mean return must win
bad_rows = [
{
"ret_1h_pct": -0.2 if i < 6 else 0.1,
"whale_sub_metrics": {
"whale_buy_vol_usd": 60_000.0 if i < 10 else 0.0,
"whale_sell_vol_usd": 35_000.0,
"twap_delta_ratio": 0.0,
"twap_tot_usd": 0.0,
},
}
for i in range(12)
]
opt = calibrate_whale_thresholds(bad_rows)
assert opt["status"] == "OPTIMIZED"
def test_ws_trade_stream_bybit_liq_and_okx_contract_scaling():
from engine.ws_trade_stream import TradeStreamBuffer
buf = TradeStreamBuffer()
now_ts = 1_700_000_000.0
ts_ms = int(now_ts * 1000)
# Bybit allLiquidation: S="Buy" means LONG position liquidated
added = buf.ingest_bybit_message({
"topic": "allLiquidation.BTCUSDT",
"data": [
{"s": "BTCUSDT", "S": "Buy", "p": "90000", "v": "1.5", "T": ts_ms},
{"s": "BTCUSDT", "S": "Sell", "p": "90500", "v": "0.5", "T": ts_ms},
],
}, now_ts=now_ts)
assert added == 2
liqs = buf.get_recent_liquidations("bybit", "BTCUSDT", now_ts=now_ts)
assert liqs[0]["is_long_liq"] is True
assert liqs[1]["is_long_liq"] is False
# OKX contract scaling: BTC-USDT-SWAP ctVal=0.01 -> 100 contracts == 1.0 BTC
buf.set_okx_contract_spec("BTC-USDT-SWAP", 0.01, is_inverse=False)
okx_added = buf.ingest_okx_message({
"arg": {"channel": "trades", "instId": "BTC-USDT-SWAP"},
"data": [{"instId": "BTC-USDT-SWAP", "px": "90000", "sz": "100", "side": "buy", "ts": str(ts_ms), "tradeId": "1"}],
}, now_ts=now_ts)
assert okx_added == 1
okx_trades = buf.get_recent_trades("okx", "BTCUSDT", now_ts=now_ts)
assert okx_trades[0]["qty"] == pytest.approx(1.0, rel=1e-6)
def test_okx_liquidations_uses_inst_family_and_filters_inst_id():
from exchanges.okx import OKXClient
async def _run():
client = OKXClient()
client._contract_spec_cache["BTC-USDT-SWAP"] = (0.01, False)
called_params = []
async def mock_get(path, params=None):
called_params.append((path, dict(params or {})))
return [
{"instId": "BTC-USDT-SWAP", "details": [{"bkPx": "90000", "sz": "50", "side": "sell", "ts": "1700000000000"}]},
{"instId": "BTC-USDT-241227", "details": [{"bkPx": "91000", "sz": "100", "side": "sell", "ts": "1700000000000"}]},
]
client._get = mock_get
liqs = await client.get_liquidations("BTCUSDT")
await client.close()
assert len(called_params) == 1
assert "instFamily" in called_params[0][1]
assert "instId" not in called_params[0][1]
assert len(liqs) == 1
assert liqs[0]["qty"] == pytest.approx(0.5, rel=1e-6)
asyncio.run(_run())
def test_bulk_fetcher_funding_normalization_and_loop_tracking():
from engine.bulk_fetcher import BulkMarketFetcher
from exchanges.binance import BinanceClient
fetcher = BulkMarketFetcher()
fetcher._binance_premium = {
"BTCUSDT": {"symbol": "BTCUSDT", "lastFundingRate": "0.0001", "nextFundingTime": 1700000000000},
"FASTUSDT": {"symbol": "FASTUSDT", "lastFundingRate": "0.0001", "nextFundingTime": 1700000000000},
}
fetcher._binance_funding_intervals = {"BTCUSDT": 8.0, "FASTUSDT": 4.0}
fr_fast = fetcher.get_binance_funding_rate("FASTUSDT")
assert fr_fast is not None
assert fr_fast["funding_rate"] == pytest.approx(0.0002, rel=1e-6)
assert fr_fast["normalized_8h"] is True
# Ensure BinanceClient.get_funding_rate does NOT double-scale when normalized_8h is True
async def _run():
b_client = BinanceClient()
b_client._funding_intervals = {"FASTUSDT": 4.0}
b_client._last_funding_info_time = 9e12
with patch("exchanges.binance.bulk_fetcher.get_binance_funding_rate", return_value=fr_fast):
res = await b_client.get_funding_rate("FASTUSDT")
await b_client.close()
assert res["funding_rate"] == pytest.approx(0.0002, rel=1e-6)
# Verify _ensure_client captures running loop when initially None
f2 = BulkMarketFetcher()
f2._client_loop = None
f2._ensure_client()
assert f2._client_loop is asyncio.get_running_loop()
asyncio.run(_run())
def test_ws_and_ai_auth_use_get_configured_api_token(monkeypatch):
import config
import security
from routers.ws import _is_ws_authenticated
monkeypatch.setattr(security, "PERPS_API_TOKEN", None)
monkeypatch.setattr(config, "PERPS_API_TOKEN", "prod-secret-token")
fake_ws_no_auth = MagicMock()
fake_ws_no_auth.headers = {}
fake_ws_no_auth.query_params = {}
assert _is_ws_authenticated(fake_ws_no_auth) is False
fake_ws_valid = MagicMock()
fake_ws_valid.headers = {"authorization": "Bearer prod-secret-token"}
fake_ws_valid.query_params = {}
assert _is_ws_authenticated(fake_ws_valid) is True
def test_data_collector_get_ohlcv_merged_fallback():
from engine.data_collector import DataCollector
async def _run():
b = MagicMock()
b.get_ohlcv = AsyncMock(side_effect=RuntimeError("451 blocked"))
y = MagicMock()
y.get_ohlcv = AsyncMock(return_value=[{"timestamp": 1700000000000, "close": 90000.0}])
dc = DataCollector(binance=b, bybit=y, okx=MagicMock(), hyperliquid=MagicMock(), bitget=MagicMock())
out = await dc.get_ohlcv_merged("BTCUSDT")
assert "15m" in out and len(out["15m"]) == 1
asyncio.run(_run())
def test_run_backtest_calibrate_no_json_and_isolated_trackers(capsys):
from engine.backtester import CausalBacktester
from engine.l2_microstructure import get_l2_tracker
from scripts.run_backtest import main as backtest_main
# _GLOBAL_L2_TRACKER must remain untouched by CausalBacktester
global_l2 = get_l2_tracker()
before_keys = set(global_l2._states.keys())
bt = CausalBacktester(warmup_bars=5)
assert bt._engine._l2_tracker is not global_l2
after_keys = set(global_l2._states.keys())
assert before_keys == after_keys
# --calibrate without --json and without --fixture must NOT fetch Binance or raise KeyError
with patch("scripts.run_backtest.db_get_microstructure_tape", return_value=[]):
rc = backtest_main(["--symbol", "BTCUSDT", "--calibrate"])
assert rc == 0
out = capsys.readouterr().out
assert "Factor Calibration Report" in out