Perps-Terminal / tests /test_audit_regression_fixes.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
21.4 kB
"""
Regression tests for logic, math, API-contract, security, and state fixes
identified during the full codebase audit.
"""
import json
import os
import sys
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock, 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"
def test_cross_exchange_absent_venues_return_none_and_oi_swing_default():
from engine.signal_engine import _compute_cross_exchange, _compute_oi_divergence
res_single = _compute_cross_exchange(
binance_data=None,
bybit_data=None,
okx_data={"ohlcv": {"5m": [{"close": 100.0}, {"close": 101.0}]}},
)
assert res_single["binance_5m_pct"] is None
assert res_single["bybit_5m_pct"] is None
assert res_single["okx_5m_pct"] == pytest.approx(1.0)
res_pair = _compute_cross_exchange(
binance_data=None,
bybit_data=None,
okx_data={"ohlcv": {"5m": [{"close": 100.0}, {"close": 101.0}]}},
bitget_data={"ohlcv": {"5m": [{"close": 100.0}, {"close": 101.0}]}},
)
assert res_pair["binance_5m_pct"] is None
assert res_pair["bybit_5m_pct"] is None
# Mild 4h OI change must still assign explicit swing_score=0
oi_res = _compute_oi_divergence(
binance_data={
"open_interest_data": {"open_interest_value": 1_000_000.0, "oi_change_pct": 0.1, "oi_change_4h_pct": 0.2},
"ohlcv": {"15m": [{"close": 100.0}, {"close": 100.05}], "4h": [{"close": 100.0}, {"close": 100.1}]},
},
bybit_data=None,
)
assert oi_res["swing_score"] == 0
def test_whale_order_flow_no_mixed_sweep_contradiction():
from engine.signal_engine import _compute_whale_order_flow
# Alternating massive buy + sell trades on distinct timestamps -> sweeps on BOTH sides
trades = []
base_ts = 1_700_000_000_000
for i in range(12):
# 2x small buys + 2x small sells for baseline median
trades.append({"price": 100.0, "qty": 1.0, "is_buyer_maker": False, "time": base_ts + i * 1000, "venue": "binance"})
trades.append({"price": 100.0, "qty": 1.0, "is_buyer_maker": True, "time": base_ts + i * 1000 + 100, "venue": "binance"})
# Large institutional buy sweep & equal large institutional sell sweep
trades.append({"price": 100.0, "qty": 500.0, "is_buyer_maker": False, "time": base_ts + 20_000, "venue": "binance"})
trades.append({"price": 100.0, "qty": 500.0, "is_buyer_maker": True, "time": base_ts + 21_000, "venue": "binance"})
wf = _compute_whale_order_flow(trades, mark_price=100.0)
assert "tanpa block sell tandingan" not in wf["flow_verdict"]
assert "tanpa block buy tandingan" not in wf["flow_verdict"]
def test_predictive_fallback_to_1h_and_mtf_atr_lookback_and_causal_htf():
from engine.backtester import CausalBacktester
from engine.mtf_analyzer import _atr_ratio
from engine.predictive_engine import PredictiveEngine
# 1. PredictiveEngine falls back to 1h when 15m has < 15 valid bars
bars_1h = []
for i in range(30):
rng = 12.0 if i < 15 else 1.0
bars_1h.append({
"timestamp": 1700000000000 + i * 3600_000,
"open": 100.0,
"high": 100.0 + rng,
"low": 100.0 - rng,
"close": 100.5,
"volume": 100.0,
})
bars_15m_short = bars_1h[-5:]
pred = PredictiveEngine().analyze(
mark_price=100.5,
ohlcv={"15m": bars_15m_short, "1h": bars_1h, "4h": [], "1d": []},
orderbook=None,
direction="LONG",
conviction=5,
)
assert pred["volatility_squeeze"]["is_squeeze"] is True
assert pred["volatility_squeeze"]["squeeze_intensity"] == "EXTREME SQUEEZE"
# 2. _atr_ratio respects lookback > period + 1
candles = []
for i in range(60):
# First 30 bars huge volatility, last 25 bars tiny volatility
rng = 20.0 if i < 30 else 0.5
candles.append({"open": 100.0, "high": 100.0 + rng, "low": 100.0 - rng, "close": 100.0})
ratio_short = _atr_ratio(candles, period=14, lookback=25)
ratio_long = _atr_ratio(candles, period=14, lookback=60)
assert ratio_short == pytest.approx(1.0, abs=1e-3)
assert ratio_long < 0.2
# 3. CausalBacktester builds in-progress 4h/1d bar strictly from causal 1h prefix
bt = CausalBacktester()
t0 = 1700006400000 # aligned cleanly to 4h
bars_1h_bt = [
{
"timestamp": t0 + i * 3600_000,
"open": 100.0 + i,
"high": 101.0 + i,
"low": 99.0 + i,
"close": 100.5 + i,
"volume": 10.0,
}
for i in range(8)
]
bars_4h_future = [
{"timestamp": t0, "open": 100.0, "high": 999.0, "low": 50.0, "close": 888.0, "volume": 1000.0},
{"timestamp": t0 + 4 * 3600_000, "open": 104.0, "high": 777.0, "low": 60.0, "close": 777.0, "volume": 1000.0},
]
t_now = bars_1h_bt[1]["timestamp"] # 2nd hour inside first 4h bar
raw = bt._build_causal_raw(
symbol="BTCUSDT",
bars_1h_prefix=bars_1h_bt[:2],
t_now=t_now,
candles_by_tf={"4h": bars_4h_future, "1d": []},
tf_timestamps={"4h": [b["timestamp"] for b in bars_4h_future], "1d": []},
funding_sorted=[],
funding_ts=[],
)
causal_4h = raw["binance"]["ohlcv"]["4h"]
assert len(causal_4h) == 1
assert causal_4h[0]["close"] == pytest.approx(101.5)
assert causal_4h[0]["high"] < 200.0
def test_outcome_evaluator_multiplier_scale_and_symbol_variations_and_merge():
from engine.outcome_evaluator import evaluate_prediction_against_candles
from engine.symbol_resolver import get_symbol_variations
from engine.ws_trade_stream import merge_trade_feeds
vars_list = get_symbol_variations("PEPEUSDT")
assert "1000PEPEUSDT" in vars_list
assert "100000PEPEUSDT" in vars_list
assert "1MPEPEUSDT" in vars_list
assert "PEPEUSDT" in get_symbol_variations("1MPEPEUSDT")
# Prediction stored in 1000x price ($12.0 -> TP1 $13.0) while candle feed uses 1x ($0.012 -> $0.0135)
t_created = int(datetime.now(timezone.utc).timestamp() * 1000)
pred = {
"symbol": "PEPEUSDT",
"horizon": "intraday",
"direction": "LONG",
"entry_price": 12.0,
"stop_loss": 11.4,
"tp1": 13.0,
"tp2": 14.0,
"created_at": datetime.fromtimestamp(t_created / 1000, tz=timezone.utc).isoformat(),
"expires_at": datetime.fromtimestamp((t_created + 14400_000) / 1000, tz=timezone.utc).isoformat(),
}
candles = [
{"timestamp": t_created + 900_000, "open": 0.012, "high": 0.0145, "low": 0.0119, "close": 0.0142},
]
eval_res = evaluate_prediction_against_candles(pred, candles, t_created + 1_800_000)
assert eval_res is not None
outcome, _, r_mult = eval_res
assert outcome == "TP2"
assert r_mult > 0
# Trade feed deduplication by trade_id across WS and REST
ws_trades = [
{"price": 100.0, "qty": 2.0, "is_buyer_maker": False, "time": 1700000002000, "venue": "binance", "trade_id": "t-2"},
]
rest_trades = [
{"price": 100.0, "qty": 2.0, "is_buyer_maker": False, "time": 1700000002000, "venue": "binance", "trade_id": "t-2"},
{"price": 100.0, "qty": 1.0, "is_buyer_maker": True, "time": 1700000001000, "venue": "binance", "trade_id": "t-1"},
]
merged = merge_trade_feeds(ws_trades, rest_trades)
assert len(merged) == 2
assert [m["trade_id"] for m in merged] == ["t-1", "t-2"]
@pytest.mark.anyio
async def test_exchange_contracts_okx_bitget_hyperliquid():
from exchanges.bitget import BitgetClient
from exchanges.hyperliquid import HyperliquidClient
from exchanges.okx import OKXClient
# OKX: USDT > USDC priority, live filter, fundingTime & interval scaling, ctVal*ctMult & inverse
okx = OKXClient()
try:
async def _mock_okx_get(path: str, params=None):
if path == "/api/v5/public/instruments" and not (params or {}).get("instId"):
return [
{"instId": "ETH-USDC-SWAP", "state": "live"},
{"instId": "ETH-USDT-SWAP", "state": "live"},
{"instId": "DEAD-USDT-SWAP", "state": "suspend"},
]
if path == "/api/v5/public/funding-rate":
return [{
"fundingRate": "0.0001",
"fundingTime": "1700014400000", # upcoming (+4h)
"prevFundingTime": "1700000000000",
"nextFundingTime": "1700028800000",
}]
if path == "/api/v5/public/instruments" and (params or {}).get("instId") == "BTC-USD-SWAP":
return [{"instId": "BTC-USD-SWAP", "ctVal": "100", "ctMult": "2", "ctType": "inverse"}]
if path == "/api/v5/market/trades":
return [{"px": "50000", "sz": "10", "side": "buy", "ts": "1700000000000"}]
return []
okx._get = _mock_okx_get # type: ignore[method-assign]
await okx._load_symbols()
assert okx.resolve_inst_id("ETH") == "ETH-USDT-SWAP"
assert "DEADUSDT" not in okx._known_symbols
fr = await okx.get_funding_rate("ETHUSDT")
assert fr["next_funding_time"] == 1700014400000
assert fr["funding_rate"] == pytest.approx(0.0002) # 4h -> 8h equivalent
inv_trades = await okx.get_recent_trades("BTCUSD")
# 10 contracts * 100 * 2 USD / $50,000 = 0.04 BTC
assert inv_trades[0]["qty"] == pytest.approx(0.04)
finally:
await okx.close()
# Bitget: nextUpdate + fundingRateInterval + longPositionRatio/longAccountRatio + unavailable
bg = BitgetClient()
try:
async def _mock_bg_get(path: str, params=None):
if path == "/api/v2/mix/market/current-fund-rate":
return [{"fundingRate": "0.00015", "nextUpdate": "1700014400000", "fundingRateInterval": "4"}]
if path == "/api/v2/mix/market/position-long-short":
return [{"longPositionRatio": "0.62"}]
if path == "/api/v2/mix/market/account-long-short":
return [{"longAccountRatio": "0.48"}]
return []
bg._get = _mock_bg_get # type: ignore[method-assign]
bg_fr = await bg.get_funding_rate("BTCUSDT")
assert bg_fr["next_funding_time"] == 1700014400000
assert bg_fr["funding_rate"] == pytest.approx(0.0003)
bg_ls = await bg.get_long_short_ratio("BTCUSDT", period="15m")
assert bg_ls["top_position_long_ratio"] == pytest.approx(0.62)
assert bg_ls["retail_long_ratio"] == pytest.approx(0.48)
assert bg_ls["source"] == "smart_money"
bg._get = AsyncMock(return_value=[]) # type: ignore[method-assign]
empty_ls = await bg.get_long_short_ratio("BTCUSDT")
assert empty_ls == {"long_ratio": None, "short_ratio": None, "source": "unavailable"}
finally:
await bg.close()
# Hyperliquid: inherits BaseExchange, skips isDelisted, returns {} orderbook, kas->KAS & 1000PEPE->kPEPE
from exchanges.base import BaseExchange
hl = HyperliquidClient()
try:
assert isinstance(hl, BaseExchange)
class _MockResp:
def __init__(self, data):
self.status_code = 200
self._data = data
def raise_for_status(self):
return None
def json(self):
return self._data
seen_ohlcv_coins = []
async def _mock_post(url, json=None, **kwargs):
t = (json or {}).get("type")
if t == "metaAndAssetCtxs":
return _MockResp([
{"universe": [{"name": "OLD", "isDelisted": True}, {"name": "KAS"}]},
[{"funding": "0.0001", "openInterest": "100", "markPx": "1.0", "oraclePx": "1.0", "dayNtlVlm": "10"},
{"funding": "0.00001", "openInterest": "400", "markPx": "0.15", "oraclePx": "0.15", "dayNtlVlm": "50000"}],
])
if t == "candleSnapshot":
seen_ohlcv_coins.append(json["req"]["coin"])
return _MockResp([])
return _MockResp({})
hl._client.post = _mock_post # type: ignore[method-assign]
await hl._refresh_meta()
assert "OLD" not in hl._cached_universe
assert "KAS" in hl._cached_universe
ob = await hl.get_orderbook("UNKNOWNCOIN")
assert ob == {"bids": [], "asks": []}
# Empty universe fallback casing test
hl._cached_universe.clear()
hl._coin_lookup.clear()
hl._cache_time = 0.0
hl._client.post = AsyncMock(return_value=_MockResp([])) # type: ignore[method-assign]
# Force candleSnapshot directly by testing uncached symbol conversion when meta fails
calls = []
async def _mock_fail_meta_ok_candle(url, json=None, **kwargs):
t = (json or {}).get("type")
if t == "metaAndAssetCtxs":
raise RuntimeError("meta unreachable")
calls.append(json["req"]["coin"])
return _MockResp([])
hl._client.post = _mock_fail_meta_ok_candle # type: ignore[method-assign]
await hl.get_ohlcv("kasusdt", "15m", 10)
await hl.get_ohlcv("1000PEPEUSDT", "15m", 10)
assert calls == ["KAS", "kPEPE"]
finally:
await hl.close()
@pytest.mark.anyio
async def test_executor_validation_uta_balance_and_partial_cancelled_reconcile():
from engine.execution.bybit_executor import BybitExecutor
executor = BybitExecutor(api_key="k", api_secret="s", mode="demo")
try:
# 1. UTA wallet balance reads totalAvailableBalance when availableToWithdraw is ""
executor._request = AsyncMock(return_value={ # type: ignore[method-assign]
"retCode": 0,
"result": {
"list": [{
"totalEquity": "2500.0",
"totalAvailableBalance": "1234.5",
"coin": [{"coin": "USDT", "availableToWithdraw": "", "walletBalance": "2500.0", "equity": "2500.0"}],
}]
},
})
bal = await executor.get_wallet_balance()
assert bal["available_balance"] == pytest.approx(1234.5)
# 2. Invalid side / order_type raises ValueError BEFORE set_leverage
lev_mock = AsyncMock(return_value=True)
executor.set_leverage = lev_mock # type: ignore[method-assign]
executor.get_instrument_info = AsyncMock(return_value={ # type: ignore[method-assign]
"symbol": "BTCUSDT", "base_coin": "BTC", "quote_coin": "USDT",
"qty_step": 0.001, "min_order_qty": 0.001, "max_order_qty": 100.0,
"tick_size": 0.1, "min_price": 0.1, "max_price": 1000000.0,
})
with pytest.raises(ValueError, match="Side tidak valid"):
await executor.execute_trade_setup("BTCUSDT", "Biy", "Market", 100.0, 5, 95.0, 105.0, mark_price=100.0)
assert not lev_mock.called
# 3. Cancelled with cumExecQty > 0 still reconciles partial position and merges below min_qty into TP1
placed = []
async def _mock_partial_req(method, path, params=None, json_body=None):
if path == "/v5/order/realtime":
return {"retCode": 0, "result": {"list": [{"orderId": "e1", "orderStatus": "Cancelled", "cumExecQty": "0.001"}]}}
if path == "/v5/order/create":
placed.append(dict(json_body or {}))
return {"retCode": 0, "result": {"orderId": "tp-partial-1"}}
raise AssertionError(path)
executor._request = _mock_partial_req # type: ignore[method-assign]
rec = await executor.reconcile_limit_tp2_once(
symbol="BTCUSDT",
entry_order_id="e1",
opposite_side="Sell",
tp2_qty=0.005,
tp2_price=70000.0,
percent=50.0,
qty_step=0.001,
tick_size=0.1,
tp1_qty=0.005,
tp1_price=65000.0,
tp1_percent=50.0,
)
assert rec["status"] == "PLACED"
assert len(placed) == 1
assert placed[0]["qty"] == "0.001"
assert placed[0]["price"] == "65000.0"
finally:
await executor.close()
def test_memory_store_journal_cleanup_accuracy_skip_and_retention():
from database.memory_store import InMemoryDatabaseStore
store = InMemoryDatabaseStore()
entry = store.create_journal_entry({"symbol": "ETHUSDT", "bias": "SHORT"})
sl_row = store.update_journal_status(entry["id"], "HIT_SL", note="wick", failure_tag="WICK_HUNT")
assert sl_row["failure_tag"] == "WICK_HUNT"
# Correcting HIT_SL -> HIT_TP clears stale failure_tag & audited
tp_row = store.update_journal_status(entry["id"], "HIT_TP", note="actually won")
assert tp_row["failure_tag"] is None
assert tp_row["audited"] is False
# Resetting to PENDING clears outcome_note even if note param passed
pend_row = store.update_journal_status(entry["id"], "PENDING", note="resetting")
assert pend_row["outcome_note"] is None
# Bad created_at in prediction is skipped in accuracy summary, valid datetime is counted
p_good = store.insert_signal_prediction({
"symbol": "BTCUSDT", "horizon": "intraday", "direction": "LONG",
"conviction": 7, "entry_price": 100.0, "stop_loss": 95.0, "tp1": 110.0, "tp2": 115.0,
"created_at": datetime.now(timezone.utc),
})
store.update_signal_prediction_outcome(p_good["id"], "TP1_OPEN", 110.0, 2.0)
store._predictions[999] = {
"id": 999, "symbol": "BTCUSDT", "horizon": "intraday", "direction": "LONG",
"outcome": "SL", "r_multiple": -1.0, "created_at": "INVALID-DATE",
}
summary = store.get_accuracy_summary(days=30, symbol="BTCUSDT")
assert summary["total_evaluated"] == 1
assert summary["win_rate_pct"] == 100.0
@pytest.mark.anyio
async def test_ai_auth_cache_isolation_and_ws_sensitive_broadcast(monkeypatch):
from fastapi.testclient import TestClient
import main as main_module
from routers import ai as ai_router
from routers import ws as ws_router
import security
ai_router._AI_CACHE.clear()
monkeypatch.setattr(security, "PERPS_API_TOKEN", "secret-token-xyz")
monkeypatch.setenv("OPENAI_API_KEY", "sk-server-env-secret")
client = TestClient(main_module.app)
try:
# 1. Unauthenticated request without BYOK key gets 401 before touching env key or cache
r_unauth = client.post("/api/ai/analyze", json={"symbol": "BTCUSDT", "provider": "openai"})
assert r_unauth.status_code == 401
# 2. Separate BYOK keys do not share cache entries
call_keys = []
async def _fake_exec(**kwargs):
call_keys.append(kwargs["clean_api_key"])
return f"BIAS: LONG ({kwargs['clean_api_key']})", "gpt-4o-mini"
with patch("routers.ai.async_get_latest_signal", AsyncMock(return_value={"symbol": "BTCUSDT", "direction": "LONG", "conviction": 7, "created_at": datetime.now(timezone.utc).isoformat()})), \
patch("routers.ai.async_get_latest_snapshot", AsyncMock(return_value=[])), \
patch("routers.signals.get_market_regime", AsyncMock(return_value={"regime": "BULLISH"})), \
patch("routers.ai.execute_llm_completion", side_effect=_fake_exec):
r1 = client.post("/api/ai/analyze", json={"symbol": "BTCUSDT", "provider": "openai", "api_key": "user-key-A"})
r2 = client.post("/api/ai/analyze", json={"symbol": "BTCUSDT", "provider": "openai", "api_key": "user-key-B"})
assert r1.status_code == 200 and r2.status_code == 200
assert r2.json()["is_cached"] is False
assert call_keys == ["user-key-A", "user-key-B"]
# 3. Setup keyword word boundary ("slippage" must NOT trigger setup mode)
p_slip, _ = ai_router._build_ai_prompt(
"BTCUSDT", {"symbol": "BTCUSDT", "direction": "LONG", "conviction": 6, "signal_data": {"factors": {}, "exchange_data": {}}},
[], custom_question="bagaimana slippage orderbook saat ini?"
)
assert "DILARANG KERAS MENGELUARKAN TEMPLATE SETUP LENGKAP 4 BAB" in p_slip
# 4. WebSocket broadcast gates sensitive journal_updated to authenticated sockets only
pub_ws = MagicMock()
pub_ws.send_text = AsyncMock()
auth_ws = MagicMock()
auth_ws.send_text = AsyncMock()
orig_conns = set(ws_router._connections)
orig_auth = set(ws_router._auth_connections)
try:
ws_router._connections = {pub_ws, auth_ws}
ws_router._auth_connections = {auth_ws}
await ws_router.broadcast({"type": "journal_updated", "data": {"id": 1}})
assert not pub_ws.send_text.called
assert auth_ws.send_text.called
pub_ws.send_text.reset_mock()
auth_ws.send_text.reset_mock()
await ws_router.broadcast({"type": "signal_update", "data": {"symbol": "BTCUSDT"}})
assert pub_ws.send_text.called
assert auth_ws.send_text.called
finally:
ws_router._connections = orig_conns
ws_router._auth_connections = orig_auth
finally:
ai_router._AI_CACHE.clear()