Spaces:
Sleeping
Sleeping
Naufal Arhab
fix(audit): refine bybit split-tp breakeven, 1000x chart scaling, and frontend surfacing
075133b Download tests/test_audit_fixes.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 103 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/tests/test_audit_fixes.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/tests/test_audit_fixes.py
-
curl -L -o test_audit_fixes.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/tests/test_audit_fixes.py
103 kB
"""
Regression tests covering bugs and miscalculations resolved in the deep audit:
1. outcome_evaluator calling ExchangeClient.get_ohlcv (instead of nonexistent fetch_ohlcv)
2. BinanceClient / BybitClient multi-horizon OI calculation & None on short/missing history
3. Whale order flow guards for contracting 15m OI and flat/doji candles
4. SignalEngine Klines Taker CVD fallback skipping partial None bars & clamping
5. Preserving explicit whale_composite_score == 0 and triggering WATCH BREAKOUT on unvetoed primed NEUTRAL
6. Decimal step rounding in BybitExecutor and taker_buy_volume clamping in market candle delta
"""
from datetime import datetime, timedelta, timezone
import os
import sys
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi import BackgroundTasks
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
from database.memory_store import InMemoryDatabaseStore, compute_accuracy_summary_from_rows
from engine.execution.bybit_executor import BybitExecutor
from engine.outcome_evaluator import (
_to_epoch_ms,
async_evaluate_pending_predictions,
evaluate_prediction_against_candles,
)
from engine.signal_engine import (
SignalEngine,
_compute_cross_exchange,
_compute_cvd,
_compute_oi_divergence,
_compute_spot_futures_cvd,
_compute_whale_order_flow,
)
from exchanges.base import BaseExchange
from exchanges.binance import TF_MAP as BINANCE_TF_MAP, BinanceClient
from exchanges.bitget import TIMEFRAME_MAP as BITGET_TF_MAP, BitgetClient
from exchanges.bybit import TF_MAP as BYBIT_TF_MAP, BybitClient
from exchanges.okx import TF_MAP as OKX_TF_MAP
from routers import ai as ai_router
from routers import signals as signals_router
from routers.market import _calculate_candle_delta
@pytest.fixture
def anyio_backend():
return "asyncio"
def _make_candles(n: int = 35, price: float = 100.0, volume: float = 1000.0) -> list[dict]:
return [
{
"timestamp": i * 900_000,
"open": price,
"high": price * 1.005,
"low": price * 0.995,
"close": price,
"volume": volume,
}
for i in range(n)
]
@pytest.mark.anyio
async def test_outcome_evaluator_uses_get_ohlcv_and_bybit_fallback():
"""async_evaluate_pending_predictions must call get_ohlcv() cleanly and resolve outcomes."""
class BinanceOnlyGetOhlcv:
def __init__(self):
self.calls = 0
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100):
self.calls += 1
return [] # Simulate empty Binance so Bybit fallback runs
class BybitOnlyGetOhlcv:
def __init__(self):
self.calls = 0
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100):
self.calls += 1
return [
{"timestamp": 60_000, "open": 100.0, "high": 102.0, "low": 99.5, "close": 101.0},
{"timestamp": 120_000, "open": 101.0, "high": 112.0, "low": 100.5, "close": 111.0},
]
binance_stub = BinanceOnlyGetOhlcv()
bybit_stub = BybitOnlyGetOhlcv()
pending_rows = [
{
"id": 42,
"symbol": "BTCUSDT",
"horizon": "intraday",
"direction": "LONG",
"entry_price": 100.0,
"stop_loss": 95.0,
"tp1": 105.0,
"tp2": 110.0,
"created_at": 1_000,
"expires_at": 500_000,
}
]
recorded_updates = []
async def _fake_update(pred_id, **kwargs):
recorded_updates.append({"id": pred_id, **kwargs})
return True
with patch("engine.outcome_evaluator.async_get_pending_predictions", AsyncMock(return_value=pending_rows)), \
patch("engine.outcome_evaluator.async_update_signal_prediction_outcome", side_effect=_fake_update):
res = await async_evaluate_pending_predictions(binance_stub, bybit_stub)
assert binance_stub.calls == 1
assert bybit_stub.calls == 1
assert res["checked"] == 1
assert res["resolved"] == 1
assert len(recorded_updates) == 1
assert recorded_updates[0]["id"] == 42
assert recorded_updates[0]["outcome"] == "TP2"
def test_base_exchange_compute_oi_horizons():
"""Shared OI horizon helper must never mislabel short history as 1H or 4H."""
assert BaseExchange._compute_oi_horizons([]) == (None, None, None)
assert BaseExchange._compute_oi_horizons([1000.0]) == (None, None, None)
# 3 bars -> 15m only; 1h and 4h remain None
c15, c1h, c4h = BaseExchange._compute_oi_horizons([1000.0, 1020.0, 1071.0])
assert c15 == pytest.approx(5.0)
assert c1h is None
assert c4h is None
# 5 bars -> 15m and 1h computed; 4h remains None
series_5 = [1000.0, 1010.0, 1020.0, 1030.0, 1050.0]
c15_5, c1h_5, c4h_5 = BaseExchange._compute_oi_horizons(series_5)
assert c15_5 == pytest.approx(((1050.0 - 1030.0) / 1030.0) * 100.0, abs=1e-4)
assert c1h_5 == pytest.approx(5.0)
assert c4h_5 is None
# 17 bars -> full 15m, 1h (-5), 4h (-17 / [0])
series_17 = [1000.0] + [1010.0] * 11 + [1020.0, 1030.0, 1040.0, 1050.0, 1100.0]
assert len(series_17) == 17
c15_17, c1h_17, c4h_17 = BaseExchange._compute_oi_horizons(series_17)
assert c15_17 == pytest.approx(((1100.0 - 1050.0) / 1050.0) * 100.0, abs=1e-4)
assert c1h_17 == pytest.approx(((1100.0 - 1020.0) / 1020.0) * 100.0, abs=1e-4)
assert c4h_17 == pytest.approx(10.0)
@pytest.mark.anyio
async def test_binance_bybit_oi_return_none_on_short_or_fallback_and_preserve_divergence():
"""Short/failed OI history returns None instead of fake 0.0 that dilutes multi-exchange divergence."""
bnb = BinanceClient()
byb = BybitClient()
bnb._known_symbols = {"BTCUSDT"}
byb._known_symbols = {"BTCUSDT"}
try:
# 1) Binance fallback path returns None deltas (not 0.0)
with patch.object(
bnb,
"_get",
AsyncMock(side_effect=[[{"sumOpenInterest": "5000", "sumOpenInterestValue": "500000"}]]),
):
short_bnb = await bnb.get_open_interest("BTCUSDT")
assert short_bnb["open_interest"] == 5000.0
assert short_bnb["oi_change_pct"] is None
assert short_bnb["oi_change_1h_pct"] is None
assert short_bnb["oi_change_4h_pct"] is None
# 2) Bybit 3-item history (newest-first) computes 15m accurately and leaves 1h/4h None
with patch("exchanges.bybit.bulk_fetcher.get_bybit_24h_and_oi", return_value=None), \
patch.object(
byb,
"_get",
AsyncMock(return_value={
"list": [
{"openInterest": "1050"},
{"openInterest": "1000"},
{"openInterest": "950"},
]
}),
):
short_byb = await byb.get_open_interest("BTCUSDT")
assert short_byb["open_interest"] == 1050.0
assert short_byb["oi_change_pct"] == pytest.approx(5.0)
assert short_byb["oi_change_1h_pct"] is None
assert short_byb["oi_change_4h_pct"] is None
# 3) Unavailable OKX/Bitget OI deltas (None) must NOT dilute valid Binance +4.0% OI growth
two_bars = [{"open": 100.0, "close": 100.0}, {"open": 100.0, "close": 102.0}]
div = _compute_oi_divergence(
{"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 4.0, "oi_change_1h_pct": 6.0}, "ohlcv": {"15m": two_bars}},
{"open_interest_data": short_bnb, "ohlcv": {"15m": two_bars}},
None,
None,
)
assert div["oi_change_pct"] == pytest.approx(4.0)
assert div["oi_change_1h_pct"] == pytest.approx(6.0)
finally:
await bnb.close()
await byb.close()
def test_whale_flow_guards_contracting_oi_and_flat_candle():
"""Active 15m OI unwinding and flat doji candles must never trigger false Iceberg Absorption."""
flat_bar = [{"timestamp": 0, "open": 100.0, "high": 100.02, "low": 100.0, "close": 100.02, "volume": 1000.0, "taker_buy_volume": 200.0}]
healthy_bar = [{"timestamp": 0, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.9, "volume": 1000.0, "taker_buy_volume": 200.0}]
sell_trades = [{"price": 100.0, "qty": 400.0, "is_buyer_maker": True} for _ in range(3)]
# Positive control: healthy candle + aligned positive OI expansion + sell pressure DOES trigger Iceberg Absorption
pos_res = _compute_whale_order_flow(
trades=sell_trades,
mark_price=100.0,
merged_ohlcv={"15m": healthy_bar},
oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5},
)
assert pos_res["absorption_type"] == "BULLISH_ICEBERG_ABSORPTION"
assert pos_res["whale_composite_score"] > 0
# Heavy sell delta on flat/doji candle even with strong OI expansion -> close_pos clamped to 0.5, no Iceberg
flat_tape_res = _compute_whale_order_flow(
trades=sell_trades,
mark_price=100.0,
merged_ohlcv={"15m": flat_bar},
oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5},
)
assert flat_tape_res["absorption_type"] is None
flat_klines_res = _compute_whale_order_flow(
trades=[],
mark_price=100.0,
merged_ohlcv={"15m": flat_bar},
oi_signal={"oi_change_pct": 1.2, "oi_change_1h_pct": 1.5},
)
assert flat_klines_res["absorption_type"] is None
# Active 15m OI unwinding (-0.6%) must override stale positive 1h OI (+0.8%) -> no Iceberg position building
unwinding_res = _compute_whale_order_flow(
trades=sell_trades,
mark_price=100.0,
merged_ohlcv={"15m": healthy_bar},
oi_signal={"oi_change_pct": -0.6, "oi_change_1h_pct": 0.8},
)
assert unwinding_res["absorption_type"] is None
def test_signal_engine_taker_cvd_partial_none_and_score_zero_and_watch_breakout():
"""
1. Klines Taker CVD fallback skips bars missing taker_buy_volume instead of counting them as 100% sell.
2. Explicit whale_composite_score == 0 is preserved rather than overridden by raw whale volume ratio.
3. Unvetoed breakout-primed NEUTRAL signal upgrades 'DO NOT TRADE / WAIT' -> 'WATCH BREAKOUT'.
"""
engine = SignalEngine()
# Mix 5 valid bullish taker_buy_volume bars with 5 None bars (large volume)
mixed_15m = [
{"timestamp": i * 900_000, "open": 100.0, "high": 101.0, "low": 99.5, "close": 100.8, "volume": 1000.0, "taker_buy_volume": 800.0}
for i in range(5)
] + [
{"timestamp": (5 + i) * 900_000, "open": 100.0, "high": 101.0, "low": 99.5, "close": 100.8, "volume": 5000.0, "taker_buy_volume": None}
for i in range(5)
]
full_15m = _make_candles(25, price=100.0, volume=1000.0) + mixed_15m
flat_tf = _make_candles(35, price=100.0, volume=1000.0)
raw = {
"symbol": "MIXUSDT",
"binance": {
"mark_price_data": {"mark_price": 100.0, "index_price": 100.0, "basis_pct": 0.0},
"funding_rate_data": {"funding_rate": 0.0001},
"open_interest_data": {"open_interest": 10_000_000.0, "oi_change_pct": 0.1},
"trades": [], # Trigger Klines Taker CVD fallback
"spot_trades": [],
"ohlcv": {"1m": flat_tf, "5m": flat_tf, "15m": full_15m, "1h": flat_tf, "4h": flat_tf, "1d": flat_tf},
"orderbook": {"bids": [[99.9, 5000]], "asks": [[100.1, 5000]]},
},
"bybit": None,
"okx": None,
"bitget": None,
"hyperliquid": None,
}
res = engine.compute(raw)
assert res["confluence"]["breakdown"]["cvd"]["score"] == 1
# Preserve whale_composite_score == 0 + activate WATCH BREAKOUT when unvetoed NEUTRAL is primed
cancelled_whale = {
"score": 0,
"whale_composite_score": 0,
"whale_buy_vol_usd": 300_000.0,
"whale_sell_vol_usd": 100_000.0,
"whale_net_vol_usd": 200_000.0,
"whale_count": 6,
"taker_buy_pct": 52.0,
"dynamic_threshold_usd": 25_000.0,
"absorption_type": "NONE",
"absorption_score": 0,
"twap_detected": False,
"twap_direction": "NONE",
"twap_score": 0,
"block_score": 0,
"smart_money_aligned": False,
"label": "Neutral",
}
primed_radar = {
"is_breakout_primed": True,
"score": 45,
"bias": "NEUTRAL",
"radar_label": "COILED SPRING BREAKOUT",
"catalyst_summary": "BB Squeeze + OI expansion",
"catalysts": ["BB Squeeze"],
}
with patch("engine.signal_engine._compute_whale_order_flow", return_value=cancelled_whale), \
patch("engine.signal_engine._compute_breakout_radar", return_value=primed_radar):
res_breakout = engine.compute(raw)
assert res_breakout["confluence"]["breakdown"]["whale_order_flow"]["score"] == 0
assert res_breakout["direction"] == "NEUTRAL"
assert res_breakout["action"] == "WATCH BREAKOUT"
# When safety veto IS active (e.g. wide/illiquid book), WATCH BREAKOUT must NOT overwrite safety warning
raw_illiquid = {
**raw,
"binance": {
**raw["binance"],
"orderbook": {"bids": [[95.0, 100]], "asks": [[105.0, 100]]},
},
}
with patch("engine.signal_engine._compute_whale_order_flow", return_value=cancelled_whale), \
patch("engine.signal_engine._compute_breakout_radar", return_value=primed_radar):
res_vetoed = engine.compute(raw_illiquid)
assert res_vetoed["direction"] == "NEUTRAL"
assert res_vetoed["action"] != "WATCH BREAKOUT"
def test_bybit_decimal_round_step_and_market_delta_clamp():
"""Decimal rounding prevents IEEE 754 floor drops; market candle delta clamps oversized taker_buy_volume."""
assert BybitExecutor._round_step(0.03, 0.01) == 0.03
assert BybitExecutor._round_step(0.29, 0.01) == 0.29
assert BybitExecutor._round_tick(1.005, 0.01) == 1.01
clamped_delta = _calculate_candle_delta({
"open": 100.0,
"high": 102.0,
"low": 99.0,
"close": 101.0,
"volume": 100.0,
"taker_buy_volume": 125.0,
})
assert clamped_delta == 100.0
def test_memory_store_pending_reset_and_naive_timestamps_and_null_scores():
"""
1. Resetting journal entry to PENDING clears failure_tag, exit_price, holding_duration_seconds, audited.
2. Naive / 'Z' ISO created_at strings work in get_recent_prediction and get_accuracy_summary.
3. compute_accuracy_summary_from_rows tolerates None factor scores without crashing.
"""
store = InMemoryDatabaseStore()
entry = store.create_journal_entry({"symbol": "BTCUSDT", "bias": "STRONG LONG"})
eid = entry["id"]
sl_updated = store.update_journal_status(
journal_id=eid,
status="HIT_SL",
note="Wick hunt",
failure_tag="WICK_HUNT",
exit_price=95000.0,
holding_duration_seconds=1800,
)
assert sl_updated is not None
assert sl_updated["failure_tag"] == "WICK_HUNT"
store._journal[eid]["audited"] = True
reset_entry = store.update_journal_status(journal_id=eid, status="PENDING", note="Reopen")
assert reset_entry is not None
assert reset_entry["status"] == "PENDING"
assert reset_entry["outcome_at"] is None
assert reset_entry["failure_tag"] is None
assert reset_entry["exit_price"] is None
assert reset_entry["holding_duration_seconds"] is None
assert reset_entry["audited"] is False
# Naive UTC timestamp (without tzinfo) for evaluated prediction
naive_recent = datetime.now(timezone.utc).replace(tzinfo=None).isoformat()
pred = store.insert_signal_prediction({
"symbol": "ETHUSDT",
"horizon": "intraday",
"direction": "LONG",
"conviction": 7,
"regime": "trending",
"sniper_grade": "SNIPER_A_PLUS",
"entry_price": 2000.0,
"stop_loss": 1950.0,
"tp1": 2100.0,
"tp2": 2200.0,
"factor_scores": {"whale_order_flow": {"score": None}, "cvd": None, "ls_ratio": "1"},
"created_at": naive_recent,
})
store.update_signal_prediction_outcome(pred["id"], outcome="TP1_OPEN", outcome_price=2100.0, r_multiple=2.0)
recent_hit = store.get_recent_prediction("ETHUSDT", "intraday", "LONG", cooldown_hours=4)
assert recent_hit is not None
assert recent_hit["id"] == pred["id"]
acc = store.get_accuracy_summary(days=30, symbol="ETHUSDT")
assert acc["total_evaluated"] == 1
assert "ls_ratio" in acc["by_factor"]
direct_acc = compute_accuracy_summary_from_rows([
{
"direction": "SHORT",
"horizon": "swing",
"sniper_grade": "STANDARD",
"outcome": "SL",
"r_multiple": -1.0,
"factor_scores": {"whale_order_flow": {"score": None}, "funding_rate": {"score": -2}},
}
])
assert direct_acc["total_evaluated"] == 1
assert direct_acc["by_factor"]["funding_rate"]["aligned_trades"] == 1
assert "whale_order_flow" not in direct_acc["by_factor"]
@pytest.mark.anyio
async def test_exchange_timeframes_and_bitget_oi_null_mark_and_trade_sort():
"""Verify 3m/30m/2h mappings, Bitget None OI USD guard when mark_price is None, and ascending trade sort."""
for tf in ("3m", "30m", "2h"):
assert tf in BYBIT_TF_MAP
assert tf in OKX_TF_MAP
assert tf in BITGET_TF_MAP
bg = BitgetClient()
try:
# 1) Empty OI payload includes oi_change_pct: None
with patch.object(bg, "_get", AsyncMock(return_value={})):
empty_oi = await bg.get_open_interest("BTCUSDT")
assert empty_oi == {"open_interest": None, "open_interest_value": None, "oi_change_pct": None}
# 2) Valid size but missing mark_price yields open_interest_value: None (never size * 1.0)
with patch.object(bg, "_get", AsyncMock(return_value={"openInterestList": [{"size": "250.5"}]})), \
patch.object(bg, "get_mark_price", AsyncMock(return_value={"mark_price": None})):
no_mp_oi = await bg.get_open_interest("BTCUSDT")
assert no_mp_oi["open_interest"] == 250.5
assert no_mp_oi["open_interest_value"] is None
# 3) Recent trades handle mixed-case side and sort ascending by time
raw_fills = [
{"price": "101", "size": "2", "side": "Sell", "ts": "2000"},
{"price": "100", "size": "1", "side": "BUY", "ts": "1000"},
]
with patch.object(bg, "_get", AsyncMock(return_value=raw_fills)):
trades = await bg.get_recent_trades("BTCUSDT")
assert [t["time"] for t in trades] == [1000, 2000]
assert trades[0]["is_buyer_maker"] is False
assert trades[1]["is_buyer_maker"] is True
finally:
await bg.close()
@pytest.mark.anyio
async def test_signals_router_naive_timestamp_and_ai_prompt_null_fields_and_key_isolation():
"""
1. signals.get_all_signals handles naive and 'Z' ISO updated_at timestamps without triggering false stale refreshes.
2. ai._build_ai_prompt tolerates None values inside nested dicts and avoids double '$$'.
3. ai.analyze_pair does not leak OPENAI_API_KEY to groq/openrouter providers when API key is missing.
"""
fresh_z = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
fresh_naive = (datetime.now(timezone.utc) - timedelta(seconds=10)).replace(tzinfo=None).isoformat()
sample_signals = [
{"signal_data": {"symbol": "BTCUSDT", "updated_at": fresh_z}},
{"signal_data": {"symbol": "ETHUSDT", "updated_at": fresh_naive}},
]
fake_req = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(collector=object())))
bg_tasks = BackgroundTasks()
orig_trigger = signals_router._last_batch_trigger_time
signals_router._last_batch_trigger_time = 0.0
try:
with patch("routers.signals.async_get_latest_signals", AsyncMock(return_value=sample_signals)):
out = await signals_router.get_all_signals(fake_req, bg_tasks)
assert len(out) == 2
assert len(bg_tasks.tasks) == 0
finally:
signals_router._last_batch_trigger_time = orig_trigger
signal_with_nones = {
"symbol": "SOLUSDT",
"direction": "NEUTRAL",
"conviction": 0,
"exchange_data": {
"binance": {"mark_price": 150.0, "index_price": 150.0, "oi": 10000.0},
"hyperliquid": {"mark_price": 150.2, "basis_pct": None, "funding_rate": 0.0001, "oi": 5000.0},
},
"lead_lag": {"max_spread_bps": None, "max_spread_usd": 0.2},
"price_extremes": {
"high_24h": None,
"low_24h": None,
"range_usd": None,
"range_pct": None,
"dist_to_high_pct": None,
"dist_to_low_pct": None,
"range_position_pct": None,
"zone_label": None,
},
"predictive": {
"volatility_squeeze": {"squeeze_intensity": None, "compression_ratio": None},
"orderbook_skew": {"bid_depth_usd": None, "ask_depth_usd": None},
"liquidation_magnets": {"dist_upper_pct": None, "dist_lower_pct": None},
"target_dist_pct": None,
},
"signals": {
"cross_exchange": {"divergence_pct": None},
"whale_order_flow": {"score": None, "label": None},
"market_structure": {"tf": None, "structure_per_tf": {"1d": None}},
},
}
prompt_text, summary = ai_router._build_ai_prompt("SOLUSDT", signal_with_nones, [])
assert "$$" not in prompt_text
assert summary["compression_ratio"] == 1.0
assert summary["depth_ratio"] == 1.0
# Groq provider without explicit api_key must raise 400 rather than stealing OPENAI_API_KEY
req_obj = SimpleNamespace(headers={}, app=SimpleNamespace(state=SimpleNamespace(collector=None)))
with patch.dict(os.environ, {"OPENAI_API_KEY": "sk-should-not-leak", "GROQ_API_KEY": ""}, clear=False):
with pytest.raises(ai_router.HTTPException) as exc_info:
await ai_router.analyze_pair(
ai_router.AIAnalyzeRequest(symbol="BTC/USDT", provider="groq"),
req_obj,
)
assert exc_info.value.status_code == 400
@pytest.mark.anyio
async def test_bybit_get_signature_matches_exact_query_string():
"""GET query string on HTTP wire must match exact sorted query signed in X-BAPI-SIGN."""
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
fake_resp = MagicMock()
fake_resp.status_code = 200
fake_resp.json.return_value = {"retCode": 0, "result": {"list": []}}
executor._client.get = AsyncMock(return_value=fake_resp)
try:
# Deliberately pass unsorted insertion-order dict
await executor._request(
"GET",
"/v5/order/realtime",
params={"symbol": "BTCUSDT", "category": "linear", "orderId": "ord-1"},
)
args, kwargs = executor._client.get.await_args
assert args[0] == "/v5/order/realtime?category=linear&orderId=ord-1&symbol=BTCUSDT"
assert "params" not in kwargs
sent_headers = kwargs["headers"]
expected_sig = executor._generate_signature(
sent_headers["X-BAPI-TIMESTAMP"],
"category=linear&orderId=ord-1&symbol=BTCUSDT",
)
assert sent_headers["X-BAPI-SIGN"] == expected_sig
finally:
await executor.close()
@pytest.mark.anyio
async def test_bybit_decimal_split_tp2_no_scientific_notation_and_limit_fallback_price():
"""
1. _format_num never produces scientific notation (e.g. '1e-05') in Bybit V5 string fields.
2. Decimal subtraction preserves TP2 qty (0.3 - 0.2 == 0.1, avoiding IEEE 754 floor-to-zero).
3. Limit orders always include 'price' using mark_price fallback when entry_price is omitted.
4. Symbols like 'MEME/USDT' normalize cleanly to 'MEMEUSDT'.
"""
assert BybitExecutor._format_num(1e-5, 1e-5) == "0.00001"
assert BybitExecutor._format_num(1e-6) == "0.000001"
assert BybitExecutor._format_num(100.0, 0.5) == "100.0"
assert BybitExecutor._format_num(100.0, 1.0) == "100"
assert BybitExecutor._format_num(110.0) == "110.0"
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
captured_payload: dict = {}
async def _fake_request(method, path, params=None, json_body=None):
if method == "POST" and path == "/v5/order/create":
captured_payload.update(json_body or {})
return {"retCode": 0, "result": {"orderId": "limit_order_1"}}
try:
with patch.object(
executor,
"get_instrument_info",
AsyncMock(return_value={
"symbol": "MEMEUSDT",
"base_coin": "MEME",
"quote_coin": "USDT",
"qty_step": 0.1,
"min_order_qty": 0.1,
"max_order_qty": 1_000_000.0,
"tick_size": 0.000001,
"min_price": 0.000001,
"max_price": 100.0,
}),
), patch.object(executor, "set_leverage", AsyncMock(return_value=True)), \
patch.object(executor, "_request", side_effect=_fake_request):
res = await executor.execute_trade_setup(
symbol="MEME/USDT",
side="Buy",
order_type="Limit",
margin_usd=0.000001,
leverage=3,
stop_loss=0.000008,
take_profit_1=0.000012,
take_profit_2=0.000015,
tp1_percent=67.0,
entry_price=None,
mark_price=0.00001,
)
assert res["symbol"] == "MEMEUSDT"
assert res["total_qty"] == pytest.approx(0.3)
assert captured_payload["symbol"] == "MEMEUSDT"
assert captured_payload["price"] == "0.000010"
assert captured_payload["stopLoss"] == "0.000008"
# Split TP Limit entries must NOT send tpSize/tpslMode or full-qty takeProfit to /v5/order/create
assert "tpSize" not in captured_payload
assert "tpslMode" not in captured_payload
assert "takeProfit" not in captured_payload
assert captured_payload["qty"] == "0.3"
assert "e-" not in captured_payload["price"].lower()
assert len(res["tp_orders"]) == 2
assert res["tp_orders"][0]["qty"] == pytest.approx(0.2)
assert res["tp_orders"][1]["qty"] == pytest.approx(0.1)
finally:
await executor.close()
def test_outcome_evaluator_naive_datetime_utc_and_none_shadow_fallback():
"""Naive datetimes/ISO strings normalize as UTC and None primary keys fall back cleanly."""
aware = datetime(2026, 3, 15, 12, 30, 0, tzinfo=timezone.utc)
naive = datetime(2026, 3, 15, 12, 30, 0)
assert _to_epoch_ms(naive) == _to_epoch_ms(aware)
assert _to_epoch_ms("2026-03-15T12:30:00") == _to_epoch_ms("2026-03-15T12:30:00Z")
pred = {
"direction": "LONG",
"entry_price": None,
"entry": 100.0,
"stop_loss": 95.0,
"tp1": None,
"take_profit_1": 105.0,
"tp2": None,
"take_profit_2": 110.0,
"created_at": 1_000,
"expires_at": 500_000,
}
candles = [{"timestamp": 60_000, "high": 112.0, "low": 99.0, "close": 111.0}]
res = evaluate_prediction_against_candles(pred, candles, now_ts=100_000)
assert res is not None
assert res[0] == "TP2"
assert res[1] == pytest.approx(110.0)
def test_signal_engine_handles_none_trade_time_qty_and_candle_close():
"""Signal helpers tolerate None values in trade timestamps/qty and candle closes without TypeError."""
spot = [{"time": None, "qty": None, "is_buyer_maker": False}] + [
{"time": 1_000 + i * 100, "qty": 50.0, "is_buyer_maker": False} for i in range(6)
]
fut = [{"time": None, "qty": None, "is_buyer_maker": True}] + [
{"time": 1_000 + i * 100, "qty": 40.0, "is_buyer_maker": True} for i in range(6)
]
sf = _compute_spot_futures_cvd({"spot_trades": spot, "trades": fut}, None)
assert isinstance(sf, dict)
assert sf["spot_cvd"] > 0
assert sf["futures_cvd"] < 0
cvd = _compute_cvd(spot)
assert isinstance(cvd, dict)
assert cvd["value"] > 0
none_candles = [{"close": None}, {"close": None}]
oi_res = _compute_oi_divergence(
{"open_interest_data": {"open_interest": 1000.0, "oi_change_pct": 1.0}, "ohlcv": {"15m": none_candles}},
None,
None,
None,
)
assert isinstance(oi_res, dict)
cx_res = _compute_cross_exchange(
{"ohlcv": {"5m": none_candles}},
{"ohlcv": {"5m": none_candles}},
)
assert isinstance(cx_res, dict)
assert cx_res["divergence_pct"] == 0.0
@pytest.mark.anyio
async def test_exchange_hardening_bitget_orderbook_sort_binance_tf_and_bybit_empty_strings():
"""Verify Bitget orderbook sorting, Binance 3m/30m/2h intervals, and Bybit empty-string ticker guards."""
assert {"3m", "30m", "2h"}.issubset(BINANCE_TF_MAP.keys())
bg = BitgetClient()
byb = BybitClient()
try:
unsorted_book = {
"bids": [["99.0", "5"], ["101.0", "10"], ["100.0", "7"]],
"asks": [["104.0", "3"], ["102.0", "8"], ["103.0", "4"]],
}
with patch.object(bg, "_get", AsyncMock(return_value=unsorted_book)):
ob = await bg.get_orderbook("BTCUSDT", depth=2)
assert ob["bids"] == [[101.0, 10.0], [100.0, 7.0]]
assert ob["asks"] == [[102.0, 8.0], [103.0, 4.0]]
empty_ticker = {"list": [{"markPrice": "", "indexPrice": None, "fundingRate": ""}]}
with patch("exchanges.bybit.bulk_fetcher.get_bybit_mark_price", return_value=None), \
patch("exchanges.bybit.bulk_fetcher.get_bybit_funding_rate", return_value=None), \
patch.object(byb, "_get", AsyncMock(return_value=empty_ticker)):
mp = await byb.get_mark_price("BTCUSDT")
fr = await byb.get_funding_rate("BTCUSDT")
assert mp["mark_price"] == 0.0
assert mp["index_price"] == 0.0
assert fr["funding_rate"] == 0.0
finally:
await bg.close()
await byb.close()
def test_symbol_resolver_preserves_k_tickers_and_strips_valid_multipliers():
"""Tickers starting with K (KAVA, KAS, KSM, KNC) must never lose their leading K."""
from engine.symbol_resolver import get_symbol_variations, strip_multiplier_prefix
assert strip_multiplier_prefix("KAVAUSDT") == "KAVAUSDT"
assert strip_multiplier_prefix("KASUSDT") == "KASUSDT"
assert strip_multiplier_prefix("KSMUSDT") == "KSMUSDT"
assert strip_multiplier_prefix("KNCUSDT") == "KNCUSDT"
assert strip_multiplier_prefix("1INCHUSDT") == "1INCHUSDT"
assert strip_multiplier_prefix("1000PEPEUSDT") == "PEPEUSDT"
assert strip_multiplier_prefix("kPEPE") == "PEPE"
assert strip_multiplier_prefix("KPEPEUSDT") == "PEPEUSDT"
kava_vars = get_symbol_variations("KAVAUSDT")
assert "KAVAUSDT" in kava_vars
assert "AVAUSDT" not in kava_vars
assert "AVA" not in kava_vars
pepe_vars = get_symbol_variations("kPEPE")
assert "PEPEUSDT" in pepe_vars
assert "kPEPE" in pepe_vars
@pytest.mark.anyio
async def test_ai_ssrf_and_key_exfiltration_blocked_and_non_usdt_preserved(monkeypatch):
"""Custom base_url must not receive server env keys, must reject non-custom providers and private IPs, and preserve BTCUSDC."""
from fastapi import HTTPException
from fastapi.testclient import TestClient
import main as main_module
monkeypatch.setenv("VIKEY_API_KEY", "vk-server-secret-token")
assert ai_router.resolve_ai_api_key("vikey", None, None, "https://attacker.example") is None
assert ai_router.resolve_ai_api_key("custom", None, None, None) is None
assert ai_router.resolve_ai_api_key("vikey", None, None, None) == "vk-server-secret-token"
for bad_url in (
"http://127.0.0.1:8080",
"http://localhost:8000",
"http://169.254.169.254/latest/meta-data",
"ftp://example.com/v1",
"https://user:pass@example.com/v1",
):
with pytest.raises(HTTPException) as exc_info:
ai_router._validate_ai_base_url(bad_url)
assert exc_info.value.status_code == 400
with pytest.raises(HTTPException) as non_custom_exc:
await ai_router.execute_llm_completion(
provider="vikey",
clean_api_key="vk-test-key",
model_name=None,
prompt="hello",
base_url="https://attacker.example",
)
assert non_custom_exc.value.status_code == 400
ai_router._AI_CACHE.clear()
captured_symbols: list[str] = []
async def _fake_completion(**kwargs):
captured_symbols.append(kwargs.get("context_label", ""))
return (f"BIAS: LONG — mock {kwargs.get('base_url')}", "custom-model")
client = TestClient(main_module.app)
with patch("routers.ai.async_get_latest_signal", AsyncMock(return_value={"symbol": "BTCUSDC", "direction": "LONG", "conviction": 7})), \
patch("routers.ai.async_get_latest_snapshot", AsyncMock(return_value=[])), \
patch("routers.signals.get_market_regime", AsyncMock(return_value={"regime": "BULLISH"})), \
patch("database.db.async_get_active_damian_memory", AsyncMock(return_value=[])), \
patch("routers.ai.execute_llm_completion", side_effect=_fake_completion):
r1 = client.post(
"/api/ai/analyze",
json={"symbol": "BTC/USDC", "provider": "custom", "api_key": "ck-1", "base_url": "https://one.example.com"},
)
assert r1.status_code == 200
assert r1.json()["symbol"] == "BTCUSDC"
assert captured_symbols[-1] == "BTCUSDC"
r2 = client.post(
"/api/ai/analyze",
json={"symbol": "BTC/USDC", "provider": "custom", "api_key": "ck-1", "base_url": "https://two.example.com"},
)
assert r2.status_code == 200
assert r2.json()["is_cached"] is False
ai_router._AI_CACHE.clear()
def test_mtf_analyzer_skips_none_closes_in_atr_stretch():
"""_calc_atr_stretch must tolerate None close entries without raising TypeError."""
from engine.mtf_analyzer import _calc_atr_stretch
candles = [{"high": 102.0 + i * 0.2, "low": 99.0 + i * 0.2, "close": 100.0 + i * 0.2} for i in range(18)]
candles.append({"high": 105.0, "low": 102.0, "close": None})
candles.append({"high": 106.0, "low": 103.0, "close": 104.5})
stretch = _calc_atr_stretch(candles)
assert isinstance(stretch, float)
def test_ws_safe_json_and_chart_okx_fallback():
"""WebSocket serialization replaces NaN/Inf cleanly and ws_chart falls back to OKX/Bitget mark prices."""
import json
from fastapi import FastAPI
from fastapi.testclient import TestClient
from routers import ws as ws_router
encoded = ws_router._safe_json_dumps({"price": float("nan"), "inf": float("inf"), "ok": 42.5})
assert "NaN" not in encoded and "Infinity" not in encoded
decoded = json.loads(encoded)
assert decoded["price"] is None and decoded["inf"] is None and decoded["ok"] == 42.5
ws_app = FastAPI()
ws_app.include_router(ws_router.router)
ws_app.state.binance = SimpleNamespace(get_mark_price=AsyncMock(return_value=None))
ws_app.state.bybit = SimpleNamespace(get_mark_price=AsyncMock(return_value=None))
ws_app.state.okx = SimpleNamespace(get_mark_price=AsyncMock(return_value={"mark_price": 55.25}))
ws_app.state.bitget = SimpleNamespace(get_mark_price=AsyncMock(return_value=None))
with patch("routers.ws.bulk_fetcher.get_binance_mark_price", return_value=None), \
patch("routers.ws.bulk_fetcher.get_bybit_mark_price", return_value=None):
client = TestClient(ws_app)
with client.websocket_connect("/ws/chart/OKB-USDT") as ws:
init_msg = json.loads(ws.receive_text())
tick_msg = json.loads(ws.receive_text())
assert init_msg["type"] == "chart_init"
assert tick_msg["type"] == "chart_tick"
assert tick_msg["symbol"] == "OKBUSDT"
assert tick_msg["price"] == pytest.approx(55.25)
assert tick_msg["exchanges"]["okx"] == pytest.approx(55.25)
def test_signals_cron_auth_enforced_and_db_json_sanitized(monkeypatch):
"""GET /api/signals/cron must enforce token auth and DB JSON dumps must sanitize NaN values."""
import json
from fastapi.testclient import TestClient
from database import db
import main as main_module
import security
monkeypatch.setattr(security, "PERPS_API_TOKEN", "top-secret-token")
monkeypatch.setattr(security, "CRON_SECRET", None)
client = TestClient(main_module.app)
unauth = client.get("/api/signals/cron")
assert unauth.status_code == 401
auth_ok = client.get("/api/signals/cron", headers={"Authorization": "Bearer top-secret-token"})
assert auth_ok.status_code == 200
sanitized_str = db._safe_json_dumps({"conviction": 8, "delta": float("nan"), "nested": [float("inf")]})
parsed = json.loads(sanitized_str)
assert parsed == {"conviction": 8, "delta": None, "nested": [None]}
assert hasattr(db, "_predictions_table_lock")
@pytest.mark.anyio
async def test_serve_spa_blocks_directory_traversal():
"""serve_spa must reject path traversal attempts outside STATIC_DIR with HTTP 404."""
from fastapi import HTTPException
import main as main_module
assert hasattr(main_module, "serve_spa")
with pytest.raises(HTTPException) as exc_info:
await main_module.serve_spa("../../backend/.env")
assert exc_info.value.status_code == 404
@pytest.mark.anyio
async def test_spot_symbol_cleaning_and_okx_non_usdt_probe(monkeypatch):
"""Spot market checks must preserve K-initial tickers (KAVA/KAS/KSM) and support non-USDT OKX pairs."""
from engine import data_collector
assert data_collector._clean_spot_symbol("KAVAUSDT") == "KAVAUSDT"
assert data_collector._clean_spot_symbol("KASUSDT") == "KASUSDT"
assert data_collector._clean_spot_symbol("KSMUSDT") == "KSMUSDT"
assert data_collector._clean_spot_symbol("1000PEPEUSDT") == "PEPEUSDT"
assert data_collector._clean_spot_symbol("kPEPE/USDT") == "PEPEUSDT"
requested_urls: list[str] = []
class _FakeResp:
def __init__(self, status_code: int, payload: dict):
self.status_code = status_code
self._payload = payload
def json(self) -> dict:
return self._payload
class _FakeClient:
async def get(self, url: str):
requested_urls.append(url)
if "instId=PEPE-USDC" in url:
return _FakeResp(200, {"data": [{"instId": "PEPE-USDC"}]})
return _FakeResp(404, {"data": [], "result": {"list": []}})
monkeypatch.setattr(data_collector, "_SPOT_VERIFICATION_CACHE", {})
monkeypatch.setattr(data_collector, "_get_spot_http_client", lambda: _FakeClient())
await data_collector.check_spot_market_exists("KAVAUSDT")
assert not any("AVAUSDT" in url and "KAVAUSDT" not in url for url in requested_urls)
requested_urls.clear()
has_spot = await data_collector.check_spot_market_exists("1000PEPEUSDC")
assert has_spot is True
assert any("instId=PEPE-USDC" in url for url in requested_urls)
@pytest.mark.anyio
async def test_binance_get_spot_trades_preserves_k_tickers_and_non_usdt(monkeypatch):
"""BinanceClient.get_spot_trades must never strip leading 'K' from KAVAUSDT while handling 1000PEPEUSDC."""
from exchanges.binance import BinanceClient
queried_symbols: list[str] = []
class _FakeResp:
def __init__(self, status_code: int, payload):
self.status_code = status_code
self._payload = payload
def json(self):
return self._payload
class _FakeClient:
async def get(self, url: str, params=None):
sym = (params or {}).get("symbol", "")
queried_symbols.append(sym)
if sym == "PEPEUSDC":
return _FakeResp(200, [{"price": "0.00001", "qty": "100", "isBuyerMaker": False, "time": 1}])
return _FakeResp(400, [])
async def aclose(self):
return None
client = BinanceClient()
monkeypatch.setattr(client, "_client", _FakeClient())
await client.get_spot_trades("KAVAUSDT")
assert queried_symbols == ["KAVAUSDT"]
queried_symbols.clear()
trades = await client.get_spot_trades("1000PEPEUSDC")
assert queried_symbols == ["1000PEPEUSDC", "PEPEUSDC"]
assert len(trades) == 1
await client.close()
def test_okx_to_inst_id_non_usdt_and_slashes():
"""OKXClient._to_inst_id cold-cache fallback must format USDC/USD/EUR pairs and strip delimiters."""
from exchanges.okx import OKXClient
client = OKXClient()
assert client._to_inst_id("BTC/USDC") == "BTC-USDC-SWAP"
assert client._to_inst_id("BTC-USDC") == "BTC-USDC-SWAP"
assert client._to_inst_id("ETH/EUR") == "ETH-EUR-SWAP"
assert client._to_inst_id("BTC-USDC-SWAP") == "BTC-USDC-SWAP"
@pytest.mark.anyio
async def test_multi_stream_preserves_zero_funding_and_open_interest(monkeypatch):
"""get_multi_exchange_stream must preserve 0.0 funding_rate and open_interest instead of coalescing to None."""
from types import SimpleNamespace
from routers import market as market_router
class _DummyExchange:
async def get_mark_price(self, _sym: str):
return {"mark_price": 95000.0, "index_price": 95000.0}
async def get_funding_rate(self, _sym: str):
return {"funding_rate": 0.0001}
async def get_open_interest(self, _sym: str):
return {"open_interest": 1234.0}
monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_mark_price", lambda _s: {"mark_price": 95000.0, "index_price": 95000.0})
monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_funding_rate", lambda _s: {"funding_rate": 0.0})
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_mark_price", lambda _s: {"mark_price": 95005.0, "index_price": 95000.0})
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_funding_rate", lambda _s: {"funding_rate": 0.0})
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_24h_and_oi", lambda _s: {"open_interest": 0.0})
fake_req = SimpleNamespace(
app=SimpleNamespace(
state=SimpleNamespace(
binance=_DummyExchange(),
bybit=_DummyExchange(),
okx=None,
bitget=None,
hyperliquid=None,
)
)
)
res = await market_router.get_multi_exchange_stream("BTCUSDT", fake_req)
assert res["exchanges"]["binance"]["funding_rate"] == 0.0
assert res["exchanges"]["bybit"]["funding_rate"] == 0.0
assert res["exchanges"]["bybit"]["open_interest"] == 0.0
def test_signal_engine_ohlcv_fallback_tolerates_none_and_zero_volume():
"""OHLCV delta fallback in SignalEngine.compute must ignore None OHLC bars and not inflate 0.0 volume to 1.0."""
from engine.signal_engine import SignalEngine
candles = [
{"timestamp": i * 900_000, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.0, "volume": 0.0, "taker_buy_volume": None}
for i in range(12)
]
candles[-1] = {
"timestamp": 12 * 900_000,
"open": None,
"high": 102.0,
"low": 99.0,
"close": None,
"volume": None,
"taker_buy_volume": None,
}
raw = {
"symbol": "TESTUSDT",
"binance": {
"mark_price": {"mark_price": 101.0, "index_price": 101.0},
"ohlcv": {"15m": candles},
},
"bybit": None,
"okx": None,
"hyperliquid": None,
"bitget": None,
}
sig = SignalEngine().compute(raw, horizon_thresholds={"cvd_min_notional": 1000})
assert sig["symbol"] == "TESTUSDT"
assert sig["signals"]["cvd"]["score"] == 0
assert "OHLCV Candle Volume Delta" not in str(sig["signals"]["cvd"].get("label", ""))
def test_ai_http_client_disables_redirects():
"""Shared AI HTTP client must set follow_redirects=False so SSRF IP validation cannot be bypassed via 302."""
from routers import ai as ai_router
client = ai_router.get_ai_http_client()
assert client.follow_redirects is False
def test_execution_journal_logs_100pct_tp1_without_runner_and_subcent_prices(monkeypatch):
"""Auto-journal entry must log 100% TP1 when there is no TP2 runner and preserve sub-cent precision."""
from fastapi.testclient import TestClient
import main as main_module
from routers import execution as execution_router
import security
captured_journal: dict = {}
class _FakeExecutor:
api_key = "k"
api_secret = "s"
mode = "demo"
async def execute_trade_setup(self, **_kwargs):
return {
"symbol": "1000PEPEUSDT",
"side": "Buy",
"mode": "demo",
"entry_order_id": "ord-123",
"total_qty": 1000.0,
"tp1_qty": 1000.0,
"tp2_qty": 0.0,
"tp_orders": [{"tp_level": "TP1", "qty": 1000.0, "order_id": "tp-1"}],
}
async def close(self):
return None
async def _fake_journal_create(entry: dict):
captured_journal.update(entry)
return entry
monkeypatch.setattr(security, "PERPS_API_TOKEN", "exec-secret-token")
monkeypatch.setattr(execution_router, "_get_active_executor", lambda **_kwargs: (_FakeExecutor(), "test"))
monkeypatch.setattr(execution_router, "async_create_journal_entry", _fake_journal_create)
client = TestClient(main_module.app)
resp = client.post(
"/api/execution/bybit/order",
headers={"Authorization": "Bearer exec-secret-token"},
json={
"symbol": "1000PEPE/USDT",
"side": "Buy",
"order_type": "Limit",
"margin_usd": 50.0,
"leverage": 5,
"entry_price": 0.00001234,
"stop_loss": 0.0000112,
"take_profit_1": 0.0000145,
"take_profit_2": None,
"tp1_percent": 50.0,
"log_to_journal": True,
},
)
assert resp.status_code == 200
assert captured_journal["symbol"] == "1000PEPEUSDT"
assert captured_journal["entry_zone"] == "$0.00001234"
assert captured_journal["stop_loss"] == "$0.0000112"
assert captured_journal["take_profit"] == "TP1: $0.0000145 (100%)"
assert captured_journal["snapshot_data"]["tp1_percent"] == 100.0
# ---------------------------------------------------------------------------
# Pass-4 Deep Audit Regression Tests
# ---------------------------------------------------------------------------
def test_predictive_engine_magnets_tolerates_none_ohlc():
"""_compute_liquidation_magnets must ignore None high/low candle fields instead of raising TypeError."""
from engine.predictive_engine import _compute_liquidation_magnets
candles = [
{"high": None, "low": None, "close": 100.0},
{"high": 105.0, "low": 96.0, "close": 100.0},
{"high": 104.0, "low": 97.0, "close": 101.0},
]
res = _compute_liquidation_magnets(mark_price=100.0, ohlcv_1h=candles)
assert res["upper_magnet"] > 105.0
assert res["lower_magnet"] < 96.0
def test_outcome_evaluator_skips_none_ohlc_and_zero_low_bars():
"""evaluate_prediction_against_candles must skip None/0 OHLC bars without crashing or falsely triggering SL."""
t0 = 1_700_000_000_000
pred = {
"direction": "LONG",
"entry_price": 100.0,
"stop_loss": 95.0,
"tp1": 105.0,
"tp2": 110.0,
"created_at": t0,
"expires_at": t0 + 3600_000,
}
candles = [
{"timestamp": t0 + 600_000, "high": None, "low": None, "close": None},
{"timestamp": t0 + 1200_000, "high": 111.0, "low": 99.0, "close": 110.5},
]
res = evaluate_prediction_against_candles(pred, candles, now_ts=t0 + 1800_000)
assert res is not None
outcome, _, r_mult = res
assert outcome == "TP2"
assert r_mult > 0
# Also test EXPIRED path where final bar has close=None -> falls back to prior valid close
pred_exp = {
"direction": "LONG",
"entry_price": 100.0,
"stop_loss": 90.0,
"tp1": 120.0,
"tp2": 130.0,
"created_at": t0,
"expires_at": t0 + 3600_000,
}
candles_exp = [
{"timestamp": t0 + 1200_000, "high": 103.0, "low": 98.0, "close": 102.0},
{"timestamp": t0 + 2400_000, "high": 103.0, "low": 99.0, "close": None},
]
res_exp = evaluate_prediction_against_candles(pred_exp, candles_exp, now_ts=t0 + 7200_000)
assert res_exp is not None
assert res_exp[0] == "EXPIRED"
assert res_exp[1] == 102.0
def test_fake_detector_tolerates_none_candles_and_multielem_orderbook():
"""fake_detector helpers must tolerate None OHLCV fields and >2-element orderbook levels."""
from engine.fake_detector import (
_orderbook_imbalance_detected,
_wash_trade_detected,
_wick_sweep_detected,
)
wick_candles = [
{"open": None, "high": None, "low": None, "close": None},
{"open": 100.0, "high": 105.0, "low": 99.5, "close": 100.2},
{"open": 100.2, "high": 101.0, "low": 99.9, "close": 100.5},
]
has_wick, _ = _wick_sweep_detected(wick_candles)
assert has_wick is True
wash_candles = [
{"open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 10.0}
for _ in range(19)
] + [
{"open": None, "high": None, "low": None, "close": None, "volume": None},
{"open": 100.0, "high": 100.5, "low": 99.5, "close": 100.1, "volume": 100.0},
{"open": 100.0, "high": 100.1, "low": 99.9, "close": 100.0, "volume": 1.0},
]
assert _wash_trade_detected(wash_candles) is True
ob = {
"bids": [[100.0, 1000.0, "0", "5"]],
"asks": [[101.0, 10.0, "0", "1"]],
}
flagged, label = _orderbook_imbalance_detected(ob, cvd_matches_price=False)
assert flagged is True
assert "Bid Wall Imbalance" in label
@pytest.mark.anyio
async def test_bybit_executor_empty_list_response_guards():
"""BybitExecutor must handle empty result.list arrays gracefully instead of raising IndexError."""
executor = BybitExecutor(api_key="test-k", api_secret="test-s", mode="demo")
async def _fake_request(_method: str, path: str, _params: dict | None = None, json_body: dict | None = None):
if "wallet-balance" in path:
return {"result": {"list": []}}
if "instruments-info" in path:
return {
"result": {
"list": [
{
"lotSizeFilter": {"qtyStep": "1", "minOrderQty": "1"},
"priceFilter": {"tickSize": "0.01"},
}
]
}
}
if "position/set-leverage" in path:
return {"retCode": 0, "result": {}}
if "market/tickers" in path:
return {"result": {"list": []}}
return {"result": {}}
executor._request = _fake_request # type: ignore[method-assign]
bal = await executor.get_wallet_balance()
assert bal["available_balance"] == 0.0
assert bal["total_equity"] == 0.0
with pytest.raises(ValueError, match="Tidak dapat menentukan harga acuan"):
await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Buy",
order_type="Market",
margin_usd=50.0,
leverage=5,
stop_loss=90.0,
take_profit_1=110.0,
entry_price=None,
mark_price=None,
)
await executor.close()
@pytest.mark.anyio
async def test_bybit_spot_trades_probes_raw_and_stripped_multiplier_symbol():
"""BybitClient.get_spot_trades must probe raw_sym first then stripped spot symbol on multiplier tokens."""
queried: list[str] = []
client = BybitClient()
async def _fake_get(_path: str, params: dict | None = None):
sym = (params or {}).get("symbol", "")
queried.append(sym)
if sym == "1000PEPEUSDT":
return {"list": []}
return {
"list": [
{"price": "0.000012", "size": "1000", "side": "Buy", "time": "1700000002000"},
{"price": "0.000011", "size": "500", "side": "Sell", "time": "1700000001000"},
]
}
client._get = _fake_get # type: ignore[method-assign]
trades = await client.get_spot_trades("1000PEPEUSDT")
assert queried == ["1000PEPEUSDT", "PEPEUSDT"]
assert len(trades) == 2
assert trades[0]["time"] < trades[1]["time"]
assert trades[0]["is_buyer_maker"] is True
assert trades[1]["is_buyer_maker"] is False
await client.close()
@pytest.mark.anyio
async def test_bitget_hyperliquid_symbol_and_okx_ratio_guards():
"""Verify Bitget symbol normalization, Hyperliquid delimiter/limit handling, and OKX negative ratio guard."""
import time
from exchanges.hyperliquid import HyperliquidClient
from exchanges.okx import OKXClient
bg = BitgetClient()
assert bg._to_bitget_symbol("btc/usdt") == "BTCUSDT"
assert bg._to_bitget_symbol("eth-usdt") == "ETHUSDT"
await bg.close()
hl = HyperliquidClient()
assert hl._format_symbol("kPEPE/USDT") == "kPEPE"
assert hl._format_symbol("BTC-USDC") == "BTC"
assert hl._format_symbol("USD") == "USD"
hl._cached_universe = {"BTC": {}}
hl._coin_lookup = {"BTC": "BTC"}
hl._cache_time = time.time()
fake_resp = MagicMock()
fake_resp.raise_for_status = MagicMock()
fake_resp.json.return_value = [
{"px": "100", "sz": "1", "side": "B", "time": i}
for i in range(10)
]
hl._client.post = AsyncMock(return_value=fake_resp)
trades = await hl.get_recent_trades("BTCUSDT", limit=3)
assert len(trades) == 3
assert [t["time"] for t in trades] == [7, 8, 9]
await hl.close()
okx = OKXClient()
okx._get = AsyncMock(return_value=[[1700000000000, "-1"]]) # type: ignore[method-assign]
ratio_res = await okx.get_long_short_ratio("BTCUSDT")
assert ratio_res is None
await okx.close()
def test_signal_engine_compute_trade_plan_none_ohlcv_and_swing_chased_dir_veto(monkeypatch):
"""_compute_trade_plan tolerates None high/low bars; swing extreme SHORT veto populates vetoed_from='SHORT'."""
from engine import signal_engine as se_mod
from engine.signal_engine import SignalEngine, _compute_trade_plan
long_plan = _compute_trade_plan(
direction="LONG",
mark_price=100.0,
ohlcv_1h=[{"open": 100.0, "high": 101.0, "low": None, "close": 100.0}],
spot_futures_score=0,
conviction=5,
)
short_plan = _compute_trade_plan(
direction="SHORT",
mark_price=100.0,
ohlcv_1h=[{"open": 100.0, "high": None, "low": 99.0, "close": 100.0}],
spot_futures_score=0,
conviction=5,
)
assert long_plan["trade_levels"] is not None
assert short_plan["trade_levels"] is not None
# Stub MTF analyzer + confluence scorer so intraday=NEUTRAL while swing raw SHORT is anti-chasing blocked
monkeypatch.setattr(
se_mod.mtf_analyzer,
"analyze",
lambda *_args, **_kwargs: {
"active_timeframe": "1h",
"market_condition": "CHOPPY",
"regime": "CHOPPY",
"atr_ratio": 1.0,
"score": 0,
"weighted_score": 0,
"structure": "ranging",
"tf": "1h",
"label": "Ranging / Mixed Structure",
"active_structure": "ranging",
"intraday_structure": 0,
"swing_structure": 0,
"structure_per_tf": {},
"intraday_atr_stretch": 0.0,
"swing_atr_stretch": -3.5,
},
)
def _fake_compute(_factors, horizon="primary", regime="CHOPPY", threshold_override=None):
is_swing = horizon == "swing"
return {
"score": -5 if is_swing else 0,
"direction": "SHORT" if is_swing else "NEUTRAL",
"conviction": 5 if is_swing else 0,
"effective_threshold": threshold_override or 4,
"horizon": horizon,
"regime": regime,
"weights_applied": {},
"raw_score": -5 if is_swing else 0,
}
monkeypatch.setattr(se_mod.confluence_scorer, "compute", _fake_compute)
candles = [
{"timestamp": i * 3_600_000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.0, "volume": 1000.0}
for i in range(24)
]
raw = {
"symbol": "SWINGSHORTUSDT",
"binance": {
"mark_price": {"mark_price": 100.0, "index_price": 100.0},
"ohlcv": {"15m": candles, "1h": candles, "4h": candles},
"orderbook": {"bids": [[99.9, 5000.0]], "asks": [[100.1, 5000.0]]},
},
"bybit": None,
"okx": None,
"bitget": None,
"hyperliquid": None,
}
sig = SignalEngine().compute(raw)
assert sig["veto_reason"] == "ANTI_CHASING_EXTREME"
assert sig["confluence"]["vetoed_from"] == "SHORT"
assert sig["direction"] == "NEUTRAL"
def test_ai_prompt_sub_million_oi_not_double_multiplied_and_signal_none():
"""_build_ai_prompt must treat already-normalized USD OI as USD (no <1e6 * price) and tolerate signal=None."""
snapshots = [
{"exchange": "binance", "mark_price": 500.0, "oi": 250000.0, "funding_rate": 0.0001},
{"exchange": "bybit", "mark_price": 500.0, "oi": 250000.0, "funding_rate": 0.0003},
]
prompt, summary = ai_router._build_ai_prompt(
symbol="ALTUSDT",
signal=None,
snapshots=snapshots,
)
assert "$500.0K" in prompt
assert "$250.00M" not in prompt
assert summary["avg_fr_8h_pct"] == 0.02
assert summary["annualized_apr_pct"] == 21.9
assert summary["warnings"] == []
@pytest.mark.anyio
async def test_market_candles_and_funding_history_tolerate_none_timestamp():
"""market endpoints must treat timestamp=None safely as 0 instead of raising TypeError."""
from routers import market as market_router
class _DummyBinance:
async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [
{"timestamp": None, "open": 100.0, "high": 102.0, "low": 99.0, "close": 101.0, "volume": 10.0},
{"timestamp": 1700000000000, "open": 101.0, "high": 103.0, "low": 100.0, "close": 102.0, "volume": 20.0},
]
async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [{"timestamp": None, "open_interest_usd": 500000.0}]
async def get_funding_rate_history(self, _sym: str, limit: int = 30):
return [{"timestamp": None, "funding_rate": 0.0001}]
class _DummyBybit:
async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [{"timestamp": None, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.5, "volume": 5.0}]
async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [{"timestamp": None, "open_interest": 100.0}]
async def get_funding_rate_history(self, _sym: str, limit: int = 30):
return [{"timestamp": None, "funding_rate": 0.0002}]
fake_req = SimpleNamespace(
app=SimpleNamespace(
state=SimpleNamespace(
binance=_DummyBinance(),
bybit=_DummyBybit(),
okx=None,
bitget=None,
hyperliquid=None,
)
)
)
candles_res = await market_router.get_market_candles("BTCUSDT", fake_req, timeframe="15m", limit=10, exchange=None)
assert candles_res["count"] == 2
funding_res = await market_router.get_market_funding_history("BTCUSDT", fake_req, limit=10)
assert funding_res["count"] == 1
@pytest.mark.anyio
async def test_market_multi_stream_resolves_usd_notional_oi_across_all_venues(monkeypatch):
"""
/api/market/{symbol}/multi-stream feeds MultiExchangeLiveBoard fmtOi ($B/$M/$K).
Every exchange's open_interest must resolve to USD notional rather than raw base coin count.
"""
from types import SimpleNamespace
from routers import market as market_router
monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_mark_price", lambda _s: None)
monkeypatch.setattr(market_router.bulk_fetcher, "get_binance_funding_rate", lambda _s: None)
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_mark_price", lambda _s: None)
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_funding_rate", lambda _s: None)
monkeypatch.setattr(market_router.bulk_fetcher, "get_bybit_24h_and_oi", lambda _s: None)
class _Binance:
async def get_mark_price(self, _s):
return {"mark_price": 50000.0, "index_price": 50000.0}
async def get_funding_rate(self, _s):
return {"funding_rate": 0.0001}
async def get_open_interest(self, _s):
return {"open_interest": 2000.0, "open_interest_value": 100_000_000.0}
class _Bybit:
async def get_mark_price(self, _s):
return {"mark_price": 50010.0, "index_price": 50000.0}
async def get_funding_rate(self, _s):
return {"funding_rate": 0.0001}
async def get_open_interest(self, _s):
# Missing open_interest_value -> must fallback to coins * bybit_price
return {"open_interest": 1000.0, "open_interest_value": None}
class _Okx:
async def get_mark_price(self, _s):
return {"mark_price": 50020.0, "index_price": 50000.0}
async def get_funding_rate(self, _s):
return {"funding_rate": 0.0001}
async def get_open_interest(self, _s):
return {"open_interest": 500.0, "open_interest_value": 25_010_000.0}
class _Bitget:
async def get_mark_price(self, _s):
return {"mark_price": 50030.0, "index_price": 50000.0}
async def get_funding_rate(self, _s):
return {"funding_rate": 0.0001}
async def get_open_interest(self, _s):
return {"open_interest": 400.0, "open_interest_value": 20_012_000.0}
class _Hyperliquid:
async def get_market_data(self, _s):
# Hyperliquid reports openInterest in base coins -> must multiply by mark_price
return {"mark_price": 50040.0, "funding_rate": 0.0002, "open_interest": 300.0}
fake_req = SimpleNamespace(
app=SimpleNamespace(
state=SimpleNamespace(
binance=_Binance(),
bybit=_Bybit(),
okx=_Okx(),
bitget=_Bitget(),
hyperliquid=_Hyperliquid(),
)
)
)
res = await market_router.get_multi_exchange_stream("BTCUSDT", fake_req)
ex = res["exchanges"]
assert ex["binance"]["open_interest"] == 100_000_000.0
assert ex["bybit"]["open_interest"] == 50_010_000.0
assert ex["okx"]["open_interest"] == 25_010_000.0
assert ex["bitget"]["open_interest"] == 20_012_000.0
assert ex["hyperliquid"]["open_interest"] == 15_012_000.0
@pytest.mark.anyio
async def test_market_candles_skips_zero_timestamp_in_oi_history():
"""
Invalid timestamp=0 / None entries in OI history must not become the LOCF baseline
for real candles.
"""
from types import SimpleNamespace
from routers import market as market_router
class _Binance:
async def get_ohlcv(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [
{"timestamp": 1700000000000, "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.0, "volume": 10.0},
{"timestamp": 1700000900000, "open": 100.0, "high": 102.0, "low": 100.0, "close": 101.0, "volume": 12.0},
]
async def get_oi_history(self, _sym: str, timeframe: str = "15m", limit: int = 150):
return [
{"timestamp": None, "open_interest_usd": 999_999_999.0},
{"timestamp": 1700000900000, "open_interest_usd": 500_000.0},
]
fake_req = SimpleNamespace(
app=SimpleNamespace(
state=SimpleNamespace(binance=_Binance(), bybit=None, okx=None, bitget=None, hyperliquid=None)
)
)
res = await market_router.get_market_candles("BTCUSDT", fake_req, timeframe="15m", limit=10, exchange=None)
assert res["candles"][0]["open_interest"] == 500_000.0
assert res["candles"][1]["open_interest"] == 500_000.0
@pytest.mark.anyio
async def test_bybit_executor_reduce_only_tp_formats_integer_qty_without_decimal_noise():
"""
reconcile_limit_tp2_once must format reduce-only TP qty and price using instrument
qty_step and tick_size so integer steps emit '100' rather than '100.0' and sub-cent
prices never emit scientific notation.
"""
from engine.execution.bybit_executor import BybitExecutor
executor = BybitExecutor(api_key="test-key", api_secret="test-secret", mode="demo")
posted_payloads: list[dict] = []
async def _fake_get_inst(_sym: str):
return {
"symbol": "PEPEUSDT",
"qty_step": 1.0,
"tick_size": 0.000001,
"min_order_qty": 1.0,
}
async def _fake_request(method: str, path: str, params=None, json_body=None):
if path == "/v5/order/realtime":
return {"result": {"list": [{"orderStatus": "Filled"}]}}
if path == "/v5/order/create" and json_body is not None:
posted_payloads.append(json_body)
return {"result": {"orderId": "tp2-order-1"}}
return {"result": {}}
executor.get_instrument_info = _fake_get_inst # type: ignore[method-assign]
executor._request = _fake_request # type: ignore[method-assign]
res = await executor.reconcile_limit_tp2_once(
symbol="PEPEUSDT",
entry_order_id="entry-1",
opposite_side="Sell",
tp2_qty=100.0,
tp2_price=0.000012,
percent=50.0,
)
await executor.close()
assert res["status"] == "PLACED"
assert len(posted_payloads) == 1
assert posted_payloads[0]["qty"] == "100"
assert posted_payloads[0]["price"] == "0.000012"
def test_price_extremes_24h_normalizes_1000x_bulk_ticker_multiplier(monkeypatch):
"""
When 1h bars are partial (< 20), _compute_price_extremes_24h must normalize
bulk Binance/Bybit 24h high/low prices against mark_price (e.g. 1000PEPEUSDT
vs PEPEUSDT) instead of inflating high_24h by 1000x.
"""
from engine import signal_engine
monkeypatch.setattr(
signal_engine.bulk_fetcher,
"get_binance_24h",
lambda _sym: {"high_24h": 0.014, "low_24h": 0.011, "last_price": 0.0125},
)
monkeypatch.setattr(
signal_engine.bulk_fetcher,
"get_bybit_24h_and_oi",
lambda _sym: {"high_24h": 0.0138, "low_24h": 0.0112, "last_price": 0.0124},
)
merged_ohlcv = {
"1h": [
{"high": 0.0000130, "low": 0.0000118},
{"high": 0.0000132, "low": 0.0000119},
],
"1d": [{"high": 0.0000135, "low": 0.0000115}],
}
ext = signal_engine._compute_price_extremes_24h(merged_ohlcv, mark_price=0.0000125, symbol="PEPEUSDT")
assert ext["high_24h"] == pytest.approx(0.000014, rel=1e-6)
assert ext["low_24h"] == pytest.approx(0.000011, rel=1e-6)
assert ext["range_pct"] < 50.0
def test_failed_trade_dossier_preserves_subcent_exit_price():
"""
_format_failed_trade_dossier must format sub-cent exit prices with sufficient
decimal precision so Damian audit prompts never show '$0.0000'.
"""
from routers.journal import _format_failed_trade_dossier
dossier = _format_failed_trade_dossier(
1,
{
"symbol": "PEPEUSDT",
"bias": "LONG",
"created_at": "2026-05-01T00:00:00Z",
"entry_zone": "$0.00001300",
"stop_loss": "$0.00001240",
"take_profit": "TP1: $0.00001450",
"exit_price": 0.00001234,
"holding_duration_seconds": 1800,
},
)
assert "$0.00001234" in dossier
assert "$0.0000\n" not in dossier
def test_build_ai_prompt_reads_hyperliquid_oi_key():
"""
_build_ai_prompt populates data_snapshot['hyperliquid_oi_usd'] from
exchange_data['hyperliquid']['oi'] (and falls back to 'open_interest').
"""
from routers.ai import _build_ai_prompt
sig = {
"direction": "LONG",
"conviction": 7,
"active_timeframe": "1h",
"exchange_data": {
"binance": {"mark_price": 100.0, "funding_rate": 0.0001, "oi": 50_000_000.0},
"hyperliquid": {"mark_price": 100.05, "funding_rate": 0.00012, "oi": 12_345_678.0},
},
"signals": {},
}
_prompt, summary = _build_ai_prompt("SOLUSDT", sig, snapshots=[])
assert summary["hyperliquid_oi_usd"] == pytest.approx(12_345_678.0)
sig_legacy = {
"direction": "LONG",
"conviction": 7,
"exchange_data": {
"binance": {"mark_price": 100.0, "funding_rate": 0.0001, "oi": 50_000_000.0},
"hyperliquid": {"mark_price": 100.05, "funding_rate": 0.00012, "open_interest": 9_876_543.0},
},
"signals": {},
}
_prompt2, summary2 = _build_ai_prompt("SOLUSDT", sig_legacy, snapshots=[])
assert summary2["hyperliquid_oi_usd"] == pytest.approx(9_876_543.0)
def test_signal_engine_post_veto_refreshes_anticipation_and_closes_cross_horizon_bypass():
"""
1. Circuit-breaker vetoes refresh predictive anticipation to NEUTRAL ('Range Boundary Liquidity').
2. Opposing intraday/swing horizons cannot bypass CROWDED_FUNDING veto independently.
"""
eng = SignalEngine()
candles_1h = [
{
"timestamp": 1_700_000_000_000 + i * 3_600_000,
"open": 100.0 + i * 0.5,
"high": 101.0 + i * 0.5,
"low": 99.5 + i * 0.5,
"close": 100.4 + i * 0.5,
"volume": 1000.0,
"taker_buy_volume": 650.0,
}
for i in range(60)
]
candles_15m = [
{
"timestamp": 1_700_000_000_000 + i * 900_000,
"open": 100.0 + i * 0.1,
"high": 100.4 + i * 0.1,
"low": 99.8 + i * 0.1,
"close": 100.2 + i * 0.1,
"volume": 500.0,
"taker_buy_volume": 320.0,
}
for i in range(60)
]
raw_veto = {
"symbol": "VETOTESTUSDT",
"has_spot": True,
"binance": {
"mark_price_data": {"mark_price": 130.0, "index_price": 130.0, "basis_pct": 0.0},
"funding_rate_data": {"funding_rate": 0.001, "next_funding_time": 9_999_999_999_999},
"open_interest_data": {"open_interest": 1000.0, "open_interest_value": 130_000.0, "oi_change_pct": 1.0, "oi_change_1h_pct": 2.0, "oi_change_4h_pct": 3.0},
"ls_ratio_data": {"long_ratio": 0.30, "short_ratio": 0.70, "retail": 0.30, "whale_position_long_ratio": 0.70, "smart_money_delta": 0.40},
"trades": [{"price": 130.0, "qty": 500.0, "is_buyer_maker": False, "time": 1_700_000_000_000 + i * 1000} for i in range(30)],
"spot_trades": [{"price": 130.0, "qty": 500.0, "is_buyer_maker": False, "time": 1_700_000_000_000 + i * 1000} for i in range(30)],
"ohlcv": {"1m": candles_15m[-30:], "5m": candles_15m[-30:], "15m": candles_15m, "1h": candles_1h, "4h": candles_1h[-35:], "1d": candles_1h[-30:]},
"orderbook": {"bids": [[129.99, 500.0]], "asks": [[130.01, 200.0]]},
},
"bybit": None, "okx": None, "bitget": None, "hyperliquid": None,
}
sig_veto = eng.compute(raw_veto)
assert sig_veto["direction"] == "NEUTRAL"
assert sig_veto["veto_reason"] == "CROWDED_FUNDING"
assert sig_veto["trade_levels"] is None
assert sig_veto["predictive"]["target_type"] == "Range Boundary Liquidity"
assert "Proyeksi Alur:" not in sig_veto["anticipation"]
# Opposing horizons: intraday LONG (+3) vs swing SHORT (-3) under extreme crowded negative funding (-0.10%)
c15_mild = [{"timestamp": i * 900_000, "open": 98 + i * 0.05, "high": 98 + i * 0.05 + 0.2, "low": 98 + i * 0.05 - 0.1, "close": 98 + i * 0.05 + 0.25, "volume": 100.0, "taker_buy_volume": 50.0} for i in range(40)]
c1h_mild = [{"timestamp": i * 3_600_000, "open": 98 + i * 0.05, "high": 98 + i * 0.05 + 0.2, "low": 98 + i * 0.05 - 0.1, "close": 98 + i * 0.05 + 0.05, "volume": 100.0, "taker_buy_volume": 50.0} for i in range(40)]
raw_opp = {
"symbol": "OPPFUNDUSDT",
"has_spot": True,
"binance": {
"mark_price_data": {"mark_price": 100.0, "index_price": 100.0, "basis_pct": 0.0},
"funding_rate_data": {"funding_rate": -0.001, "next_funding_time": 9_999_999_999_999},
"open_interest_data": {"open_interest": 1000.0, "open_interest_value": 100_000.0, "oi_change_pct": 1.0, "oi_change_1h_pct": 1.0, "oi_change_4h_pct": 2.0},
"ls_ratio_data": {"long_ratio": 0.70, "short_ratio": 0.30, "retail": 0.70, "whale_position_long_ratio": 0.40, "smart_money_delta": -0.30},
"trades": [{"price": 100.0, "qty": 50.0, "is_buyer_maker": True, "time": 1000 + i * 1000} for i in range(20)],
"spot_trades": [{"price": 100.0, "qty": 50.0, "is_buyer_maker": True, "time": 1000 + i * 1000} for i in range(20)],
"ohlcv": {
"1m": [{"timestamp": i * 60_000, "open": 100.0, "high": 100.2, "low": 99.8, "close": 100.0, "volume": 100.0} for i in range(30)],
"5m": [{"timestamp": i * 300_000, "open": 100.0, "high": 100.2, "low": 99.8, "close": 100.0, "volume": 100.0} for i in range(30)],
"15m": c15_mild,
"1h": c1h_mild,
"4h": [{"timestamp": i * 14_400_000, "open": 130 - i * 0.5, "high": 130 - i * 0.5 + 0.2, "low": 130 - i * 0.5 - 0.6, "close": 130 - i * 0.5 - 0.4, "volume": 500.0} for i in range(40)],
"1d": [{"timestamp": i * 86_400_000, "open": 150 - i * 0.8, "high": 150 - i * 0.8 + 0.3, "low": 150 - i * 0.8 - 1.0, "close": 150 - i * 0.8 - 0.7, "volume": 1000.0} for i in range(40)],
},
"orderbook": {"bids": [[99.99, 3000.0]], "asks": [[100.01, 500.0]]},
},
"bybit": None, "okx": None, "bitget": None, "hyperliquid": None,
}
sig_opp = eng.compute(raw_opp)
assert sig_opp["horizons"]["intraday"]["direction"] == "LONG"
assert sig_opp["horizons"]["swing"]["direction"] == "NEUTRAL"
assert sig_opp["horizons"]["swing"]["veto_reason"] == "CROWDED_FUNDING"
assert sig_opp["horizons"]["swing"]["trade_levels"] is None
assert sig_opp["sniper_grade"] == "INTRADAY_ONLY"
def test_signal_engine_spot_futures_1000x_scaling_and_klines_cvd_fake_detector():
"""_compute_spot_futures_cvd normalizes 1000x trade quantities and Klines CVD triggers FakeDetector mismatch."""
sf = _compute_spot_futures_cvd(
{
"spot_trades": [{"price": 0.000012, "qty": 1_000_000.0, "is_buyer_maker": False, "time": 1000 + i} for i in range(10)],
"trades": [{"price": 0.012, "qty": 500.0, "is_buyer_maker": True, "time": 1000 + i} for i in range(10)],
},
None,
ref_mark_px=0.012,
)
assert sf["spot_cvd"] == pytest.approx(10_000.0, rel=1e-4)
assert sf["futures_cvd"] == pytest.approx(-5_000.0, rel=1e-4)
# Empty live trades + bearish Klines taker CVD on rising 5m price triggers CVD absorption warning in FakeDetector
c5m = [{"timestamp": i * 300_000, "open": 100.0, "high": 100.5, "low": 99.5, "close": 100.0 + i * 0.1, "volume": 100.0} for i in range(10)]
c15m_bear_cvd = [{"timestamp": i * 900_000, "open": 100.0, "high": 100.5, "low": 99.5, "close": 100.0, "volume": 1000.0, "taker_buy_volume": 200.0} for i in range(20)]
res = SignalEngine().compute({
"symbol": "KLINECVDUSDT",
"has_spot": True,
"binance": {
"mark_price_data": {"mark_price": 101.0, "index_price": 101.0},
"ohlcv": {"1m": c5m, "5m": c5m, "15m": c15m_bear_cvd, "1h": c15m_bear_cvd},
"orderbook": {"bids": [[100.99, 500.0]], "asks": [[101.01, 500.0]]},
},
"bybit": None, "okx": None, "bitget": None, "hyperliquid": None,
})
assert any("CVD delta momentum opposes price move" in w for w in res["signals"]["fake_detector"]["warnings"])
@pytest.mark.anyio
async def test_outcome_evaluator_logs_conviction_3_and_expires_past_lookback():
"""async_log_prediction_if_new logs threshold-3 signals; expired rows past candle lookback resolve EXPIRED."""
from database.memory_store import memory_store
from engine.outcome_evaluator import HORIZON_CONFIG, async_log_prediction_if_new
assert HORIZON_CONFIG["intraday"]["limit"] >= 480
assert HORIZON_CONFIG["swing"]["limit"] >= 240
memory_store.reset()
with patch("database.db.DATABASE_URL", ""):
logged = await async_log_prediction_if_new({
"symbol": "THRESH3USDT",
"veto_reason": None,
"sniper_grade": "INTRADAY_ONLY",
"horizons": {
"intraday": {
"direction": "LONG",
"conviction": 3,
"regime": "trending",
"trade_levels": {"entry_price": 100.0, "stop_loss": 95.0, "take_profit_1": 105.0, "take_profit_2": 110.0},
},
"swing": {"direction": "NEUTRAL", "conviction": 2, "trade_levels": None},
},
})
assert len(logged) == 1
assert logged[0]["conviction"] == 3
now = datetime(2026, 11, 16, 0, 0, tzinfo=timezone.utc)
created = now - timedelta(hours=160)
expires = created + timedelta(hours=12)
recent_candles = [
{"timestamp": int((now - timedelta(minutes=15 * i)).timestamp() * 1000), "open": 100.0, "high": 101.0, "low": 99.0, "close": 100.0}
for i in range(96, 0, -1)
]
res = evaluate_prediction_against_candles(
{
"id": 99,
"direction": "LONG",
"entry_price": 100.0,
"stop_loss": 95.0,
"tp1": 105.0,
"tp2": 110.0,
"created_at": created.isoformat(),
"expires_at": expires.isoformat(),
},
recent_candles,
now_ts=int(now.timestamp() * 1000),
)
assert res == ("EXPIRED", 100.0, 0.0)
def test_backtester_primary_horizon_reads_horizons_primary_and_updates_end_drawdown():
"""CausalBacktester horizon='primary' uses horizons['primary'] with threshold calibration and reconciles END_OF_DATA DD."""
from engine.backtester import CausalBacktester
bt = CausalBacktester(warmup_bars=30)
bars_55 = [
{"timestamp": 1_700_000_000_000 + i * 3_600_000, "open": 100.0 + i * 0.2, "high": 101.0 + i * 0.2, "low": 99.5 + i * 0.2, "close": 100.4 + i * 0.2, "volume": 1000.0}
for i in range(55)
]
calls: list[dict] = []
def _spy(raw):
out = SignalEngine().compute(raw, horizon_thresholds={"primary": 2, "intraday": 2, "swing": 2})
# Force distinct primary vs top-level decision on first bar to verify selector
out["direction"] = "NEUTRAL"
out["trade_levels"] = None
out["horizons"]["primary"] = {
"direction": "LONG",
"score": 4,
"trade_levels": {"stop_loss": 90.0, "take_profit_1": 140.0, "take_profit_2": 160.0},
}
calls.append(out)
return out
rep_p = bt.run("BTCUSDT", bars_55, horizon="primary", signal_fn=_spy)
assert rep_p["total_trades"] >= 1
assert calls
# Verify END_OF_DATA exit slippage/fee updates final equity_curve drawdown_pct and max_drawdown_pct
bars_dd = [{"timestamp": i * 3_600_000, "open": 100.0, "high": 100.2, "low": 99.8, "close": 100.0} for i in range(35)]
idx_n = {"n": 0}
def _fn_end(raw):
idx_n["n"] += 1
if idx_n["n"] == 1:
return {"direction": "LONG", "trade_levels": {"stop_loss": 50.0, "take_profit_1": 150.0, "take_profit_2": 200.0}}
return {"direction": "NEUTRAL", "trade_levels": None}
rep_dd = CausalBacktester(warmup_bars=30, taker_fee_bps=50.0, slippage_bps=100.0).run("BTCUSDT", bars_dd, signal_fn=_fn_end)
assert rep_dd["trades"][-1]["exit_reason"] == "END_OF_DATA"
expected_dd = round((10_000.0 - rep_dd["final_equity_usd"]) / 10_000.0 * 100.0, 4)
assert rep_dd["equity_curve"][-1]["drawdown_pct"] == pytest.approx(expected_dd, abs=1e-3)
assert rep_dd["max_drawdown_pct"] >= round(expected_dd, 2)
def test_market_router_and_ws_normalize_1000x_multiplier():
"""/candles, /multi-stream, and /ws/chart normalize 1000x contract differences cleanly."""
import json
from fastapi.testclient import TestClient
import main as main_module
mc_bin = MagicMock()
mc_bin.get_ohlcv = AsyncMock(return_value=[{"timestamp": 1_730_000_000_000, "open": 0.012, "high": 0.013, "low": 0.011, "close": 0.012, "volume": 1000.0, "taker_buy_volume": 600.0}])
mc_bin.get_oi_history = AsyncMock(return_value=[])
mc_bin.get_mark_price = AsyncMock(return_value={"mark_price": 0.012, "index_price": 0.012})
mc_bin.get_funding_rate = AsyncMock(return_value={"funding_rate": 0.0001})
mc_bin.get_open_interest = AsyncMock(return_value={"open_interest": 100_000.0, "open_interest_value": 1200.0})
mc_okx = MagicMock()
mc_okx.get_ohlcv = AsyncMock(return_value=[{"timestamp": 1_730_000_000_000, "open": 0.000012, "high": 0.000013, "low": 0.000011, "close": 0.000012, "volume": 1_000_000.0}])
mc_okx.get_mark_price = AsyncMock(return_value={"mark_price": 0.000012, "index_price": 0.000012})
mc_okx.get_funding_rate = AsyncMock(return_value={"funding_rate": 0.0001})
mc_okx.get_open_interest = AsyncMock(return_value={"open_interest": 100_000_000.0, "open_interest_value": 1200.0})
orig_state = (
getattr(main_module.app.state, "binance", None),
getattr(main_module.app.state, "bybit", None),
getattr(main_module.app.state, "okx", None),
getattr(main_module.app.state, "bitget", None),
getattr(main_module.app.state, "hyperliquid", None),
)
try:
main_module.app.state.binance = mc_bin
main_module.app.state.bybit = None
main_module.app.state.okx = mc_okx
main_module.app.state.bitget = None
main_module.app.state.hyperliquid = None
client = TestClient(main_module.app)
rc = client.get("/api/market/PEPEUSDT/candles?timeframe=15m").json()
assert rc["candles"][0]["volume"] == pytest.approx(2000.0, rel=1e-4)
rm = client.get("/api/market/PEPEUSDT/multi-stream").json()
assert rm["ref_price"] == pytest.approx(0.012, rel=1e-4)
assert abs(rm["exchanges"]["binance"]["diff_pct"]) < 0.1
assert abs(rm["exchanges"]["okx"]["diff_pct"]) < 0.1
assert rm["exchanges"]["okx"]["open_interest"] == pytest.approx(1200.0, rel=1e-4)
with patch("routers.ws.bulk_fetcher.get_binance_mark_price", return_value=None), \
patch("routers.ws.bulk_fetcher.get_bybit_mark_price", return_value=None):
with client.websocket_connect("/ws/chart/PEPEUSDT?exchange=okx") as ws:
_ = json.loads(ws.receive_text())
tick = json.loads(ws.receive_text())
assert tick["type"] == "chart_tick"
assert tick["price"] == pytest.approx(0.000012, rel=1e-4)
assert tick["exchanges"]["binance"] == pytest.approx(0.000012, rel=1e-4)
finally:
main_module.app.state.binance, main_module.app.state.bybit, main_module.app.state.okx, main_module.app.state.bitget, main_module.app.state.hyperliquid = orig_state
@pytest.mark.anyio
async def test_ai_router_live_oi_priority_streak_preservation_and_gemini_model():
"""AI prompt prefers fresh exchange_data OI over stale snapshots, normalizes underscores, preserves streak, and keeps custom Gemini models."""
from fastapi.testclient import TestClient
import main as main_module
_prompt, summary = ai_router._build_ai_prompt(
"BTCUSDT",
{"direction": "LONG", "conviction": 7, "exchange_data": {"binance": {"mark_price": 100.0, "oi": 50_000_000.0}}, "signals": {}},
snapshots=[{"exchange": "binance", "oi": 1_000_000.0}],
)
assert summary["total_oi_usd"] == pytest.approx(50_000_000.0)
# Custom model without 'gemini' substring must be tried first under provider='gemini'
called_urls: list[str] = []
class _MockResp:
status_code = 200
def json(self):
return {"candidates": [{"content": {"parts": [{"text": "OK gemma"}]}}]}
class _MockClient:
async def post(self, url, **_kwargs):
called_urls.append(url)
return _MockResp()
with patch("routers.ai.get_ai_http_client", return_value=_MockClient()):
txt, used = await ai_router.execute_llm_completion(
provider="gemini",
clean_api_key="test-key",
model_name="gemma-3-27b-it",
prompt="hello",
)
assert txt == "OK gemma"
assert used == "gemma-3-27b-it"
assert "gemma-3-27b-it" in called_urls[0]
# /api/ai/analyze normalizes underscores and preserves streak on refresh
ai_router._AI_CACHE.clear()
saved_signals: list[dict] = []
mock_collector = SimpleNamespace(collect=AsyncMock(return_value={
"symbol": "BTCUSDT",
"has_spot": True,
"binance": {
"mark_price_data": {"mark_price": 100.0, "index_price": 100.0},
"ohlcv": {"15m": [], "1h": [], "4h": [], "1d": []},
"open_interest_data": {"open_interest": 500_000.0, "open_interest_value": 50_000_000.0},
},
"bybit": None, "okx": None, "bitget": None, "hyperliquid": None,
}))
main_module.app.state.collector = mock_collector
async def _fake_save(**kwargs):
saved_signals.append(kwargs["signal_data"])
with patch("routers.ai.async_get_latest_signal", AsyncMock(return_value=None)), \
patch("routers.ai.async_get_latest_snapshot", AsyncMock(return_value=[{"exchange": "binance", "oi": 1_000_000.0}])), \
patch("database.db.async_get_pair", AsyncMock(return_value={"symbol": "BTCUSDT", "streak_count": 4, "streak_direction": "LONG"})), \
patch("database.db.async_save_signal", side_effect=_fake_save), \
patch("routers.signals.get_market_regime", AsyncMock(return_value={"regime": "BULLISH"})), \
patch("database.db.async_get_active_damian_memory", AsyncMock(return_value=[])), \
patch("routers.ai.execute_llm_completion", AsyncMock(return_value=("BIAS: LONG", "gemini-2.5-flash"))):
resp = TestClient(main_module.app).post(
"/api/ai/analyze",
json={"symbol": "BTC_USDT", "provider": "gemini", "api_key": "k-123", "force_refresh": True},
)
assert resp.status_code == 200
assert resp.json()["symbol"] == "BTCUSDT"
assert saved_signals and saved_signals[0]["streak"] == 4
ai_router._AI_CACHE.clear()
@pytest.mark.anyio
async def test_okx_ls_ratio_period_forwarding():
"""OKX get_long_short_ratio honors requested period mapping while preserving None guard for negative ratios."""
from exchanges.okx import OKXClient
okx = OKXClient()
okx_params: list[dict] = []
async def _mock_okx_get(_path, params=None):
okx_params.append(dict(params or {}))
return [["1700000000000", "-1"]]
okx._get = _mock_okx_get
ls_res = await okx.get_long_short_ratio("BTCUSDT", period="4h")
assert okx_params[0]["period"] == "1H"
assert ls_res is None
okx_params.clear()
await okx.get_long_short_ratio("BTCUSDT", period="1d")
assert okx_params[0]["period"] == "1D"
await okx.close()
@pytest.mark.anyio
async def test_round2_bybit_limit_split_tp_post_fill_and_breakeven_no_tp1_guard(monkeypatch):
"""
Round-2 regression:
1. Limit split-TP must not send tpSize/tpslMode or full-qty takeProfit to /v5/order/create.
2. Single-TP 100% Limit order still attaches native takeProfit.
3. Stateful reconcile_limit_tp2_once places BOTH reduceOnly TP1 & TP2 post-fill and chains real TP1 ID to breakeven.
4. watch_position_tp1_breakeven rejects None tp1_order_id (no false breakeven trigger).
"""
from unittest.mock import AsyncMock, patch
from fastapi.testclient import TestClient
import main as main_module
import security
from engine.execution.bybit_executor import (
BybitExecutor,
watch_limit_entry_and_place_tp2,
watch_position_tp1_breakeven,
)
monkeypatch.delenv("VERCEL", raising=False)
monkeypatch.delenv("NOW_REGION", raising=False)
executor = BybitExecutor(api_key="k", api_secret="s", mode="demo")
order_payloads: list[dict] = []
async def _fake_req(method, path, params=None, json_body=None):
if path == "/v5/market/instruments-info":
return {
"retCode": 0,
"result": {
"list": [{
"baseCoin": "BTC",
"lotSizeFilter": {"qtyStep": "0.001", "minOrderQty": "0.001", "maxOrderQty": "100"},
"priceFilter": {"tickSize": "0.1", "minPrice": "1", "maxPrice": "500000"},
}]
},
}
if path == "/v5/position/set-leverage":
return {"retCode": 0, "result": {}}
if path == "/v5/order/create":
order_payloads.append(dict(json_body or {}))
idx = len(order_payloads)
return {"retCode": 0, "result": {"orderId": f"ord-{idx}"}}
if path == "/v5/order/realtime":
return {"retCode": 0, "result": {"list": [{"orderId": "ord-1", "orderStatus": "Filled", "cumExecQty": "0.005"}]}}
raise AssertionError(f"Unexpected call {method} {path}")
executor._request = _fake_req # type: ignore[method-assign]
# Case A: Split-TP Limit order
res_split = await executor.execute_trade_setup(
symbol="BTCUSDT", side="Buy", order_type="Limit",
margin_usd=100.0, leverage=3, stop_loss=58000.0,
take_profit_1=65000.0, take_profit_2=70000.0,
tp1_percent=60.0, entry_price=60000.0, mark_price=61000.0,
)
assert "tpSize" not in order_payloads[0]
assert "tpslMode" not in order_payloads[0]
assert "takeProfit" not in order_payloads[0]
assert order_payloads[0]["stopLoss"] == "58000.0"
assert [t["status"] for t in res_split["tp_orders"]] == ["WATCHING_FILL", "WATCHING_FILL"]
# Reconcile places both TP1 (0.003) and TP2 (0.002) reduceOnly limit orders
rec = await executor.reconcile_limit_tp2_once(
symbol="BTCUSDT", entry_order_id="ord-1", opposite_side="Sell",
tp2_qty=res_split["tp2_qty"], tp2_price=70000.0, percent=40.0,
tp1_qty=res_split["tp1_qty"], tp1_price=65000.0, tp1_percent=60.0,
)
assert rec["status"] == "PLACED"
assert rec["tp1_order"]["qty"] == pytest.approx(0.003)
assert rec["tp2_order"]["qty"] == pytest.approx(0.002)
assert order_payloads[1]["reduceOnly"] is True and order_payloads[1]["price"] == "65000.0"
assert order_payloads[2]["reduceOnly"] is True and order_payloads[2]["price"] == "70000.0"
# Case B: 100% single TP Limit still binds takeProfit directly
order_payloads.clear()
res_single = await executor.execute_trade_setup(
symbol="BTCUSDT", side="Buy", order_type="Limit",
margin_usd=100.0, leverage=3, stop_loss=58000.0,
take_profit_1=65000.0, take_profit_2=None,
tp1_percent=100.0, entry_price=60000.0,
)
assert order_payloads[0]["takeProfit"] == "65000.0"
assert res_single["tp_orders"][0]["status"] == "BOUND_TO_ENTRY"
await executor.close()
# Case C: watch_position_tp1_breakeven rejects None tp1_order_id
with patch.object(BybitExecutor, "move_sl_to_breakeven", new_callable=AsyncMock) as be_move:
be_none = await watch_position_tp1_breakeven(
"k", "s", "demo", None, "BTCUSDT", "Buy",
total_qty=0.004, tp1_qty=0.002, tp1_order_id=None,
poll_interval=0.01, max_polls=1,
)
assert be_none == {"status": "NO_TP1_ORDER", "breakeven_sl": None}
assert not be_move.called
# Case D: Limit watcher forwards real placed TP1 order_id (not bound-) to breakeven watcher
captured_be_ids: list[str | None] = []
async def _fake_reconcile(self, **_kwargs):
return {
"status": "PLACED",
"order_status": "Filled",
"tp1_order": {"tp_level": "TP1", "order_id": "real-tp1-888", "qty": 0.003, "price": 65000.0},
"tp2_order": {"tp_level": "TP2", "order_id": "real-tp2-999", "qty": 0.002, "price": 70000.0},
}
async def _fake_be_watch(*_args, **kwargs):
captured_be_ids.append(kwargs.get("tp1_order_id"))
return {"status": "BREAKEVEN_ARMED", "breakeven_sl": 60036.0}
with patch.object(BybitExecutor, "reconcile_limit_tp2_once", _fake_reconcile), \
patch("engine.execution.bybit_executor.watch_position_tp1_breakeven", _fake_be_watch):
w_res = await watch_limit_entry_and_place_tp2(
"k", "s", "demo", None, "BTCUSDT", "lim-1", "Sell",
tp2_qty=0.002, tp2_price=70000.0, percent=40.0,
poll_interval=0.01, max_polls=1, auto_breakeven=True,
side="Buy", total_qty=0.005, tp1_qty=0.003, tp1_order_id=None,
tp1_price=65000.0, tp1_percent=60.0,
)
assert captured_be_ids == ["real-tp1-888"]
assert w_res["breakeven_result"]["status"] == "BREAKEVEN_ARMED"
# Case E: Router skips breakeven watcher cleanly when Market TP1 order failed
monkeypatch.setattr(security, "PERPS_API_TOKEN", "round2-exec-token")
market_tp1_failed = {
"success": True, "symbol": "BTCUSDT", "side": "Buy", "order_type": "MARKET",
"margin_usd": 100.0, "leverage": 3, "notional_usd": 300.0,
"total_qty": 0.005, "tp1_qty": 0.003, "tp2_qty": 0.002,
"entry_order_id": "mkt-1", "stop_loss": 58000.0,
"tp_orders": [{"tp_level": "TP2", "percent": 40.0, "status": "PLACED", "order_id": "tp2-ok", "price": 70000.0, "qty": 0.002}],
"mode": "demo", "timestamp": 1.0,
}
with patch("routers.execution.BybitExecutor.execute_trade_setup", AsyncMock(return_value=market_tp1_failed)), \
patch("routers.execution.BybitExecutor.close", AsyncMock()):
resp = TestClient(main_module.app).post(
"/api/execution/bybit/order",
json={
"symbol": "BTCUSDT", "side": "Buy", "order_type": "Market",
"margin_usd": 100.0, "leverage": 3, "stop_loss": 58000.0,
"take_profit_1": 65000.0, "take_profit_2": 70000.0,
"tp1_percent": 60.0, "auto_breakeven": True, "log_to_journal": False,
},
headers={
"Authorization": "Bearer round2-exec-token",
"X-Bybit-Api-Key": "k", "X-Bybit-Api-Secret": "s", "X-Bybit-Mode": "demo",
},
)
assert resp.status_code == 200
assert resp.json()["execution"]["breakeven_status"] == "SKIPPED_NO_TP1_ORDER"
assert resp.json()["execution"]["breakeven_watcher_scheduled"] is False
def test_round2_signal_engine_merged_ohlcv_exchange_data_1000x_and_primary_anti_chasing():
"""
Round-2 regression:
1. merged_ohlcv and exchange_data normalize 1000x/1x venue differences against ref_mark_px while preserving USD OI.
2. ANTI_CHASING_EXTREME vetoes horizons['primary'] consistently with top-level & intraday.
"""
from engine.signal_engine import SignalEngine
def _bars(px: float, n: int = 30) -> list[dict]:
return [
{
"timestamp": 1700000000000 + i * 900000,
"open": px,
"high": px * 1.005,
"low": px * 0.995,
"close": px * (1.001 + i * 0.0005),
"volume": 100_000.0,
"taker_buy_volume": 60_000.0,
}
for i in range(n)
]
# 1. Bitget has 1000x scale (8.0) w/o OHLCV; OKX has 1x scale (0.008) with OHLCV
raw_1000x = {
"symbol": "1000PEPEUSDT",
"has_spot": True,
"bitget": {
"mark_price_data": {"mark_price": 8.0, "index_price": 8.0, "basis_pct": 0.0},
"funding_rate_data": {"funding_rate": 0.0001},
"open_interest_data": {"open_interest": 500_000, "open_interest_value": 4_000_000, "oi_change_pct": 1.0},
"ohlcv": {},
"trades": [],
"orderbook": {"bids": [[7.99, 5000]], "asks": [[8.01, 5000]]},
},
"okx": {
"mark_price_data": {"mark_price": 0.008, "index_price": 0.008, "basis_pct": 0.0},
"funding_rate_data": {"funding_rate": 0.0001},
"open_interest_data": {"open_interest": 1_000_000_000, "open_interest_value": 8_000_000, "oi_change_pct": 1.0},
"ls_ratio_data": {"long_ratio": 0.55, "short_ratio": 0.45},
"ohlcv": {tf: _bars(0.008) for tf in ("1m", "5m", "15m", "1h", "4h", "1d")},
"trades": [],
"orderbook": {"bids": [[0.00799, 100_000]], "asks": [[0.00801, 100_000]]},
},
}
sig_scaled = SignalEngine().compute(raw_1000x)
assert sig_scaled["price_extremes"]["range_pct"] < 10.0
assert sig_scaled["price_extremes"]["low_24h"] > 5.0
assert sig_scaled["exchange_data"]["okx"]["mark_price"] == pytest.approx(8.0)
assert sig_scaled["exchange_data"]["okx"]["oi"] == pytest.approx(8_000_000.0)
# 2. Extreme stretch blocks horizons['primary'] as well as top/intraday
up_bars = []
px = 100.0
for i in range(40):
c = px * (1.002 if i < 38 else 1.25)
up_bars.append({
"timestamp": 1700000000000 + i * 3_600_000,
"open": px,
"high": c * 1.002,
"low": px * 0.998,
"close": c,
"volume": 50_000.0,
"taker_buy_volume": 45_000.0,
})
px = c if i < 38 else px
raw_chase = {
"symbol": "BTCUSDT",
"has_spot": True,
"binance": {
"mark_price_data": {"mark_price": up_bars[-1]["close"], "index_price": up_bars[-1]["close"], "basis_pct": 0.05},
"funding_rate_data": {"funding_rate": -0.0001},
"open_interest_data": {"open_interest": 10_000, "open_interest_value": 1_000_000, "oi_change_pct": 5.0},
"ls_ratio_data": {"long_ratio": 0.4, "short_ratio": 0.6},
"ohlcv": {"1m": up_bars, "5m": up_bars, "15m": up_bars, "1h": up_bars, "4h": _bars(100.0, 20), "1d": _bars(100.0, 20)},
"trades": [{"price": up_bars[-1]["close"], "qty": 100, "is_buyer_maker": False, "time": 1700000000000} for _ in range(5)],
"spot_trades": [{"price": up_bars[-1]["close"], "qty": 100, "is_buyer_maker": False, "time": 1700000000000} for _ in range(5)],
"orderbook": {"bids": [[up_bars[-1]["close"] * 0.999, 5000]], "asks": [[up_bars[-1]["close"] * 1.001, 5000]]},
},
}
sig_chase = SignalEngine().compute(raw_chase)
assert sig_chase["veto_reason"] == "ANTI_CHASING_EXTREME"
# When active_timeframe is 4h/1d (unstretched), primary keeps aligned CLEAN status without self-contradiction
primary_h = sig_chase["horizons"]["primary"]
if sig_chase["active_timeframe"] in ("4h", "1d"):
assert primary_h["anti_chasing_status"] == "CLEAN"
assert primary_h["direction"] in ("LONG", "NEUTRAL")
# When primary active_timeframe itself is stretched (1h/15m or stretched 4h), primary is vetoed consistently
raw_chase_primary = {
**raw_chase,
"binance": {
**raw_chase["binance"],
"ohlcv": {"1m": up_bars, "5m": up_bars, "15m": up_bars, "1h": up_bars},
},
}
sig_chase_p = SignalEngine().compute(raw_chase_primary)
assert sig_chase_p["veto_reason"] == "ANTI_CHASING_EXTREME"
p_blocked = sig_chase_p["horizons"]["primary"]
assert p_blocked["direction"] == "NEUTRAL"
assert p_blocked["veto_reason"] == "ANTI_CHASING_EXTREME"
assert p_blocked["anti_chasing_status"] == "ANTI_CHASING_EXTREME"
assert p_blocked["trade_levels"] is None
@pytest.mark.anyio
async def test_round2_journal_subcent_mark_price_and_serverless_lifespan_cleanup(monkeypatch):
"""
Round-2 regression:
1. _format_failed_trade_dossier uses sub-cent formatting for fallback mark_price.
2. Serverless lifespan shutdown closes exchange & shared HTTP client pools.
"""
from unittest.mock import AsyncMock, MagicMock, patch
from routers.journal import _format_failed_trade_dossier
import main as main_module
import engine.data_collector as dc_module
import routers.ai as ai_module
dossier = _format_failed_trade_dossier(
1,
{"id": 1, "symbol": "PEPEUSDT", "bias": "STRONG LONG", "snapshot_data": {"mark_price": 0.00001234}},
)
assert "$0.00001234" in dossier
assert "- Mark Price: $0.0000 |" not in dossier
monkeypatch.setenv("VERCEL", "1")
mock_spot = MagicMock(is_closed=False, aclose=AsyncMock())
mock_ai = MagicMock(is_closed=False, aclose=AsyncMock())
monkeypatch.setattr(dc_module, "_SPOT_HTTP_CLIENT", mock_spot)
monkeypatch.setattr(ai_module, "_AI_HTTP_CLIENT", mock_ai)
with patch.object(main_module.bulk_fetcher, "close", AsyncMock()) as m_bulk, \
patch("exchanges.binance.BinanceClient.close", AsyncMock()) as m_bin, \
patch("exchanges.bybit.BybitClient.close", AsyncMock()) as m_byb, \
patch("exchanges.okx.OKXClient.close", AsyncMock()) as m_okx, \
patch("exchanges.bitget.BitgetClient.close", AsyncMock()) as m_bit, \
patch("exchanges.hyperliquid.HyperliquidClient.close", AsyncMock()) as m_hl:
async with main_module.lifespan(main_module.app):
pass
assert m_bulk.called and m_bin.called and m_byb.called
assert m_okx.called and m_bit.called and m_hl.called
assert mock_spot.aclose.called and mock_ai.aclose.called
"""
Regression tests covering bugs and miscalculations resolved in the deep audit:
1. outcome_evaluator calling ExchangeClient.get_ohlcv (instead of nonexistent fetch_ohlcv)
2. BinanceClient / BybitClient multi-horizon OI calculation & None on short/missing history
3. Whale order flow guards for contracting 15m OI and flat/doji candles
4. SignalEngine Klines Taker CVD fallback skipping partial None bars & clamping
5. Preserving explicit whale_composite_score == 0 and triggering WATCH BREAKOUT on unvetoed primed NEUTRAL
6. Decimal step rounding in BybitExecutor and taker_buy_volume clamping in market candle delta
"""
from datetime import datetime, timedelta, timezone
import os
import sys
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi import BackgroundTasks
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
from database.memory_store import InMemoryDatabaseStore, compute_accuracy_summary_from_rows
from engine.execution.bybit_executor import BybitExecutor
from engine.outcome_evaluator import (
_to_epoch_ms,
async_evaluate_pending_predictions,
evaluate_prediction_against_candles,
)
from engine.signal_engine import (
SignalEngine,
_compute_cross_exchange,
_compute_cvd,
_compute_oi_divergence,
_compute_spot_futures_cvd,
_compute_whale_order_flow,
)
from exchanges.base import BaseExchange
from exchanges.binance import TF_MAP as BINANCE_TF_MAP, BinanceClient
from exchanges.bitget import TIMEFRAME_MAP as BITGET_TF_MAP, BitgetClient
from exchanges.bybit import TF_MAP as BYBIT_TF_MAP, BybitClient
from exchanges.okx import TF_MAP as OKX_TF_MAP
from routers import ai as ai_router
from routers import signals as signals_router
from routers.market import _calculate_candle_delta
def anyio_backend():
return "asyncio"
def _make_candles(n: int = 35, price: float = 100.0, volume: float = 1000.0) -> list[dict]:
return [
{
"timestamp": i * 900_000,
"open": price,
"high": price * 1.005,
"low": price * 0.995,
"close": price,
"volume": volume,
}
for i in range(n)
]
async def test_outcome_evaluator_uses_get_ohlcv_and_bybit_fallback():
"""async_evaluate_pending_predictions must call get_ohlcv() cleanly and resolve outcomes."""
class BinanceOnlyGetOhlcv:
def __init__(self):
self.calls = 0
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100):
self.calls += 1
return [] # Simulate empty Binance so Bybit fallback runs
class BybitOnlyGetOhlcv:
def __init__(self):
self.calls = 0
async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100):
self.calls += 1
return [
{"timestamp": 60_000, "open": 100.0, "high": 102.0, "low": 99.5, "close": 101.0},
{"timestamp": 120_000, "open": 101.0, "high": 112.0, "low": 100.5, "close": 111.0},
]
binance_stub = BinanceOnlyGetOhlcv()
bybit_stub = BybitOnlyGetOhlcv()
pending_rows = [
{
"id": 42,
"symbol": "BTCUSDT",
"horizon": "intraday",
"direction": "LONG",
"entry_price": 100.0,
"stop_loss": 95.0,
"tp1": 105.0,
"tp2": 110.0,