Naufal Arhab commited on
Commit
72bd8f0
·
1 Parent(s): 53df866

fix(audit): comprehensive system audit refinements and resilience guards

Browse files
backend/engine/fake_detector.py CHANGED
@@ -95,11 +95,11 @@ def _orderbook_imbalance_detected(orderbook: dict | None, cvd_matches_price: boo
95
 
96
  imbalance = (bid_vol - ask_vol) / total_vol
97
 
98
- # Bid wall spoofing: huge bids (>85% of book) while aggressive orders are selling
99
- if imbalance > ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
100
  return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof"
101
- # Ask wall spoofing: huge asks (>85% of book) while aggressive orders are buying
102
- if imbalance < -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
103
  return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof"
104
 
105
  return False, ""
 
95
 
96
  imbalance = (bid_vol - ask_vol) / total_vol
97
 
98
+ # Bid wall spoofing: huge bids (>=85% of book) while aggressive orders are selling
99
+ if imbalance >= ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
100
  return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof"
101
+ # Ask wall spoofing: huge asks (>=85% of book) while aggressive orders are buying
102
+ if imbalance <= -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price:
103
  return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof"
104
 
105
  return False, ""
backend/engine/predictive_engine.py CHANGED
@@ -222,7 +222,7 @@ def _compute_volatility_squeeze(
222
  else:
223
  baseline_atr = sum(rolling_atrs) / len(rolling_atrs)
224
 
225
- if baseline_atr <= 0:
226
  return {
227
  "is_squeeze": False,
228
  "compression_ratio": 1.0,
 
222
  else:
223
  baseline_atr = sum(rolling_atrs) / len(rolling_atrs)
224
 
225
+ if baseline_atr <= 0 or current_atr <= 0:
226
  return {
227
  "is_squeeze": False,
228
  "compression_ratio": 1.0,
backend/main.py CHANGED
@@ -45,7 +45,6 @@ from exchanges.hyperliquid import HyperliquidClient
45
  from engine.data_collector import DataCollector
46
  from engine.signal_engine import SignalEngine
47
  from engine.bulk_fetcher import bulk_fetcher
48
- from routers import pairs as pairs_router
49
  from routers import signals as signals_router
50
  from routers import ws as ws_router
51
  from routers import market as market_router
 
45
  from engine.data_collector import DataCollector
46
  from engine.signal_engine import SignalEngine
47
  from engine.bulk_fetcher import bulk_fetcher
 
48
  from routers import signals as signals_router
49
  from routers import ws as ws_router
50
  from routers import market as market_router
backend/routers/ai.py CHANGED
@@ -301,7 +301,7 @@ def _build_ai_prompt(
301
  resting_pressure = ob_skew.get("resting_pressure", "BALANCED")
302
  bid_depth = ob_skew.get("bid_depth_usd", 0.0)
303
  ask_depth = ob_skew.get("ask_depth_usd", 0.0)
304
- depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else 1.0
305
 
306
  # Liquidation Magnets & Predictive Targets
307
  magnets = pred.get("liquidation_magnets") or {}
@@ -598,8 +598,21 @@ async def analyze_pair(body: AIAnalyzeRequest, request: Request):
598
  if collector:
599
  try:
600
  from engine.signal_engine import SignalEngine
 
 
 
 
 
 
 
601
  eng = SignalEngine()
602
- raw = await collector.collect(symbol)
 
 
 
 
 
 
603
  signal = eng.compute(raw)
604
  except Exception as exc:
605
  logger.warning("[%s] On-demand signal collect failed: %s", symbol, exc)
 
301
  resting_pressure = ob_skew.get("resting_pressure", "BALANCED")
302
  bid_depth = ob_skew.get("bid_depth_usd", 0.0)
303
  ask_depth = ob_skew.get("ask_depth_usd", 0.0)
304
+ depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else (99.0 if bid_depth > 0 else 1.0)
305
 
306
  # Liquidation Magnets & Predictive Targets
307
  magnets = pred.get("liquidation_magnets") or {}
 
598
  if collector:
599
  try:
600
  from engine.signal_engine import SignalEngine
601
+ from database.db import async_get_pair
602
+ pair_meta = await async_get_pair(symbol)
603
+ on_binance = bool(pair_meta.get("on_binance", True)) if pair_meta else True
604
+ on_bybit = bool(pair_meta.get("on_bybit", True)) if pair_meta else True
605
+ on_okx = bool(pair_meta.get("on_okx", False)) if pair_meta else True
606
+ on_hl = bool(pair_meta.get("on_hyperliquid", False)) if pair_meta else True
607
+
608
  eng = SignalEngine()
609
+ raw = await collector.collect(
610
+ symbol,
611
+ on_binance=on_binance,
612
+ on_bybit=on_bybit,
613
+ on_okx=on_okx,
614
+ on_hyperliquid=on_hl,
615
+ )
616
  signal = eng.compute(raw)
617
  except Exception as exc:
618
  logger.warning("[%s] On-demand signal collect failed: %s", symbol, exc)
backend/routers/journal.py CHANGED
@@ -257,7 +257,21 @@ Format Output Wajib:
257
  choices = res_json.get("choices", [])
258
  if choices:
259
  msg = choices[0].get("message") or {}
260
- audit_summary = (msg.get("content") or msg.get("reasoning_content") or "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  else:
262
  logger.error("Audit LLM request failed: %d - %s", resp.status_code, resp.text[:200])
263
  raise HTTPException(
 
257
  choices = res_json.get("choices", [])
258
  if choices:
259
  msg = choices[0].get("message") or {}
260
+ raw_content = msg.get("content") or msg.get("reasoning_content") or choices[0].get("text") or ""
261
+ if isinstance(raw_content, list):
262
+ chunks = []
263
+ for part in raw_content:
264
+ if isinstance(part, dict):
265
+ chunks.append(part.get("text", "") or part.get("content", ""))
266
+ elif isinstance(part, str):
267
+ chunks.append(part)
268
+ else:
269
+ chunks.append(str(part))
270
+ audit_summary = "".join(chunks).strip()
271
+ elif isinstance(raw_content, dict):
272
+ audit_summary = str(raw_content.get("text", "") or raw_content.get("content", "")).strip()
273
+ else:
274
+ audit_summary = str(raw_content).strip() if raw_content is not None else ""
275
  else:
276
  logger.error("Audit LLM request failed: %d - %s", resp.status_code, resp.text[:200])
277
  raise HTTPException(
backend/routers/pairs.py CHANGED
@@ -1,5 +1,7 @@
1
  """
2
- /api/pairs endpoints
 
 
3
  """
4
 
5
  from fastapi import APIRouter, HTTPException, Depends
 
1
  """
2
+ /api/pairs reference definitions.
3
+ Note: In this application, active /api/pairs routes are mounted directly on FastAPI app in `backend/main.py`
4
+ to access `app.state` exchange clients (Binance, Bybit, OKX, Hyperliquid) and the DataCollector.
5
  """
6
 
7
  from fastapi import APIRouter, HTTPException, Depends
backend/routers/signals.py CHANGED
@@ -126,9 +126,9 @@ async def get_market_regime():
126
  short_pct = round((n_short / total) * 100, 1)
127
  neutral_pct = round((n_neut / total) * 100, 1)
128
 
129
- avg_conv = round(sum(s.get("conviction", 0) for s in active_signals) / total, 2)
130
- avg_long_conv = round(sum(s.get("conviction", 0) for s in longs) / n_long, 2) if n_long else 0.0
131
- avg_short_conv = round(sum(s.get("conviction", 0) for s in shorts) / n_short, 2) if n_short else 0.0
132
 
133
  if n_long >= n_short * 1.3 and long_pct >= 35:
134
  regime = "STRONG BULLISH" if long_pct >= 50 else "BULLISH"
@@ -244,6 +244,8 @@ async def refresh_signal(symbol: str, request: Request):
244
  sym,
245
  on_binance=on_binance,
246
  on_bybit=on_bybit,
 
 
247
  )
248
  signal = _signal_engine.compute(raw)
249
 
 
126
  short_pct = round((n_short / total) * 100, 1)
127
  neutral_pct = round((n_neut / total) * 100, 1)
128
 
129
+ avg_conv = round(sum(int(s.get("conviction") or 0) for s in active_signals) / total, 2)
130
+ avg_long_conv = round(sum(int(s.get("conviction") or 0) for s in longs) / n_long, 2) if n_long else 0.0
131
+ avg_short_conv = round(sum(int(s.get("conviction") or 0) for s in shorts) / n_short, 2) if n_short else 0.0
132
 
133
  if n_long >= n_short * 1.3 and long_pct >= 35:
134
  regime = "STRONG BULLISH" if long_pct >= 50 else "BULLISH"
 
244
  sym,
245
  on_binance=on_binance,
246
  on_bybit=on_bybit,
247
+ on_okx=on_okx,
248
+ on_hyperliquid=on_hyperliquid,
249
  )
250
  signal = _signal_engine.compute(raw)
251
 
backend/routers/ws.py CHANGED
@@ -21,17 +21,22 @@ _connections: set[WebSocket] = set()
21
 
22
 
23
  async def broadcast(data: Any) -> None:
24
- """Send a JSON payload to every connected WebSocket client."""
25
  if not _connections:
26
  return
27
  message = json.dumps(data, default=str)
 
28
  dead: set[WebSocket] = set()
29
- for ws in list(_connections):
 
30
  try:
31
- await ws.send_text(message)
32
  except Exception:
33
  dead.add(ws)
34
- _connections.difference_update(dead)
 
 
 
35
 
36
 
37
  @router.websocket("/ws/signals")
 
21
 
22
 
23
  async def broadcast(data: Any) -> None:
24
+ """Send a JSON payload to every connected WebSocket client concurrently with timeout guard."""
25
  if not _connections:
26
  return
27
  message = json.dumps(data, default=str)
28
+ clients = list(_connections)
29
  dead: set[WebSocket] = set()
30
+
31
+ async def _send(ws: WebSocket) -> None:
32
  try:
33
+ await asyncio.wait_for(ws.send_text(message), timeout=2.0)
34
  except Exception:
35
  dead.add(ws)
36
+
37
+ await asyncio.gather(*[_send(ws) for ws in clients], return_exceptions=True)
38
+ if dead:
39
+ _connections.difference_update(dead)
40
 
41
 
42
  @router.websocket("/ws/signals")
tests/test_calculations.py CHANGED
@@ -462,6 +462,46 @@ def test_breakout_radar_and_bulk_fetcher():
462
 
463
  print(" PASSED!")
464
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  if __name__ == "__main__":
466
  print("=" * 60)
467
  print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")
 
462
 
463
  print(" PASSED!")
464
 
465
+
466
+ def test_market_regime_none_conviction_handling():
467
+ print("[11] Testing market regime handling with None conviction and empty cases...")
468
+ # Simulates active signals containing None or missing convictions
469
+ active_signals = [
470
+ {"symbol": "BTCUSDT", "direction": "LONG", "conviction": 5},
471
+ {"symbol": "ETHUSDT", "direction": "LONG", "conviction": None},
472
+ {"symbol": "SOLUSDT", "direction": "SHORT", "conviction": 4},
473
+ {"symbol": "DOGEUSDT", "direction": "NEUTRAL", "conviction": None},
474
+ ]
475
+ longs = [s for s in active_signals if s.get("direction") == "LONG"]
476
+ shorts = [s for s in active_signals if s.get("direction") == "SHORT"]
477
+ total = len(active_signals)
478
+
479
+ avg_conv = round(sum(int(s.get("conviction") or 0) for s in active_signals) / total, 2)
480
+ avg_long_conv = round(sum(int(s.get("conviction") or 0) for s in longs) / len(longs), 2)
481
+ avg_short_conv = round(sum(int(s.get("conviction") or 0) for s in shorts) / len(shorts), 2)
482
+
483
+ assert avg_conv == 2.25
484
+ assert avg_long_conv == 2.5
485
+ assert avg_short_conv == 4.0
486
+ print(" PASSED!")
487
+
488
+
489
+ def test_orderbook_skew_depth_ratio_and_zero_asks():
490
+ print("[12] Testing depth ratio resilience with zero asks / zero bids...")
491
+ # Bid depth > 0, ask depth = 0
492
+ bid_depth = 50000.0
493
+ ask_depth = 0.0
494
+ depth_ratio = (bid_depth / ask_depth) if ask_depth > 0 else (99.0 if bid_depth > 0 else 1.0)
495
+ assert depth_ratio == 99.0
496
+
497
+ # Bid depth = 0, ask depth = 0
498
+ bid_depth_zero = 0.0
499
+ ask_depth_zero = 0.0
500
+ depth_ratio_zero = (bid_depth_zero / ask_depth_zero) if ask_depth_zero > 0 else (99.0 if bid_depth_zero > 0 else 1.0)
501
+ assert depth_ratio_zero == 1.0
502
+ print(" PASSED!")
503
+
504
+
505
  if __name__ == "__main__":
506
  print("=" * 60)
507
  print("STARTING TEST SUITE: ENGINE CALCULATION AUDIT")