Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
9ec99c1
1
Parent(s): 784525a
feat: implement Hybrid Institutional Architecture (Bulk Market Pre-Fetcher, Dynamic Shards, Breakout Squeeze Radar)
Browse files- backend/engine/bulk_fetcher.py +254 -0
- backend/engine/signal_engine.py +159 -4
- backend/exchanges/binance.py +7 -0
- backend/exchanges/bybit.py +18 -0
- backend/main.py +53 -15
- backend/routers/ai.py +16 -1
- frontend/src/components/signals/AIAnalysisPanel.tsx +10 -0
- frontend/src/components/signals/AIExecutiveSummaryCard.tsx +18 -1
- frontend/src/components/signals/SignalCard.tsx +20 -2
- frontend/src/types/index.ts +57 -0
- tests/test_calculations.py +113 -0
backend/engine/bulk_fetcher.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bulk Market Pre-Fetcher (Tier 1 Architecture)
|
| 3 |
+
==============================================
|
| 4 |
+
Provides high-performance, single-call pre-fetching of market-wide data
|
| 5 |
+
across Binance USDⓈ-M and Bybit Linear Perpetuals.
|
| 6 |
+
|
| 7 |
+
Benefits:
|
| 8 |
+
- Slashes individual REST API calls by 70–80% across all monitored pairs.
|
| 9 |
+
- Eliminates per-symbol rate-limit bottlenecks on /premiumIndex and /tickers.
|
| 10 |
+
- Supplies instantaneous in-memory mark price, index price, funding rates,
|
| 11 |
+
and 24h price extremes.
|
| 12 |
+
- Thread/coroutine safe with async locking and automatic TTL cache (15s).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import asyncio
|
| 16 |
+
import logging
|
| 17 |
+
import time
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import httpx
|
| 21 |
+
|
| 22 |
+
from config import BINANCE_FUTURES_BASE_URL, BYBIT_BASE_URL, PROXY_URL
|
| 23 |
+
from engine.doh_resolver import enable_doh_bypass
|
| 24 |
+
from engine.symbol_resolver import get_symbol_variations
|
| 25 |
+
|
| 26 |
+
enable_doh_bypass()
|
| 27 |
+
|
| 28 |
+
logger = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BulkMarketFetcher:
|
| 32 |
+
"""Singleton pre-fetcher for bulk exchange market snapshots."""
|
| 33 |
+
|
| 34 |
+
_instance: "BulkMarketFetcher | None" = None
|
| 35 |
+
|
| 36 |
+
def __new__(cls) -> "BulkMarketFetcher":
|
| 37 |
+
if cls._instance is None:
|
| 38 |
+
cls._instance = super().__new__(cls)
|
| 39 |
+
cls._instance._init_client()
|
| 40 |
+
return cls._instance
|
| 41 |
+
|
| 42 |
+
def _init_client(self) -> None:
|
| 43 |
+
client_kwargs = {
|
| 44 |
+
"timeout": httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=10.0),
|
| 45 |
+
"limits": httpx.Limits(max_connections=80, max_keepalive_connections=30, keepalive_expiry=30.0),
|
| 46 |
+
"headers": {
|
| 47 |
+
"Accept": "application/json",
|
| 48 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
|
| 49 |
+
},
|
| 50 |
+
"verify": False,
|
| 51 |
+
}
|
| 52 |
+
if PROXY_URL:
|
| 53 |
+
client_kwargs["proxy"] = PROXY_URL
|
| 54 |
+
|
| 55 |
+
self._client = httpx.AsyncClient(**client_kwargs)
|
| 56 |
+
self._binance_premium: dict[str, dict[str, Any]] = {}
|
| 57 |
+
self._binance_24h: dict[str, dict[str, Any]] = {}
|
| 58 |
+
self._bybit_tickers: dict[str, dict[str, Any]] = {}
|
| 59 |
+
self._last_refresh_time: float = 0.0
|
| 60 |
+
self._ttl_seconds: float = 15.0
|
| 61 |
+
self._lock = asyncio.Lock()
|
| 62 |
+
|
| 63 |
+
async def refresh_if_stale(self, force: bool = False) -> None:
|
| 64 |
+
"""Refresh bulk data if cache TTL expired or force is True."""
|
| 65 |
+
now = time.time()
|
| 66 |
+
if not force and (now - self._last_refresh_time < self._ttl_seconds):
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
async with self._lock:
|
| 70 |
+
# Double-check inside lock
|
| 71 |
+
now = time.time()
|
| 72 |
+
if not force and (now - self._last_refresh_time < self._ttl_seconds):
|
| 73 |
+
return
|
| 74 |
+
|
| 75 |
+
tasks = [
|
| 76 |
+
self._fetch_binance_premium(),
|
| 77 |
+
self._fetch_binance_24h(),
|
| 78 |
+
self._fetch_bybit_linear_tickers(),
|
| 79 |
+
]
|
| 80 |
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
| 81 |
+
for idx, res in enumerate(results):
|
| 82 |
+
if isinstance(res, Exception):
|
| 83 |
+
logger.debug("Bulk fetch task %d failed: %s", idx, res)
|
| 84 |
+
|
| 85 |
+
self._last_refresh_time = time.time()
|
| 86 |
+
|
| 87 |
+
async def _fetch_binance_premium(self) -> None:
|
| 88 |
+
"""Binance /fapi/v1/premiumIndex without symbol returns all USD-M perpetuals (weight=1)."""
|
| 89 |
+
try:
|
| 90 |
+
url = f"{BINANCE_FUTURES_BASE_URL}/fapi/v1/premiumIndex"
|
| 91 |
+
r = await self._client.get(url, timeout=5.0)
|
| 92 |
+
if r.status_code == 200:
|
| 93 |
+
data = r.json()
|
| 94 |
+
new_map = {}
|
| 95 |
+
for item in data:
|
| 96 |
+
sym = item.get("symbol")
|
| 97 |
+
if sym:
|
| 98 |
+
new_map[sym.upper()] = item
|
| 99 |
+
if new_map:
|
| 100 |
+
self._binance_premium = new_map
|
| 101 |
+
except Exception as exc:
|
| 102 |
+
logger.debug("[BulkFetcher] Binance premiumIndex error: %s", exc)
|
| 103 |
+
|
| 104 |
+
async def _fetch_binance_24h(self) -> None:
|
| 105 |
+
"""Binance /fapi/v1/ticker/24hr without symbol returns 24h ticker for all pairs (weight=40)."""
|
| 106 |
+
try:
|
| 107 |
+
url = f"{BINANCE_FUTURES_BASE_URL}/fapi/v1/ticker/24hr"
|
| 108 |
+
r = await self._client.get(url, timeout=6.0)
|
| 109 |
+
if r.status_code == 200:
|
| 110 |
+
data = r.json()
|
| 111 |
+
new_map = {}
|
| 112 |
+
for item in data:
|
| 113 |
+
sym = item.get("symbol")
|
| 114 |
+
if sym:
|
| 115 |
+
new_map[sym.upper()] = item
|
| 116 |
+
if new_map:
|
| 117 |
+
self._binance_24h = new_map
|
| 118 |
+
except Exception as exc:
|
| 119 |
+
logger.debug("[BulkFetcher] Binance ticker/24hr error: %s", exc)
|
| 120 |
+
|
| 121 |
+
async def _fetch_bybit_linear_tickers(self) -> None:
|
| 122 |
+
"""Bybit /v5/market/tickers?category=linear returns all linear perp tickers in 1 call."""
|
| 123 |
+
try:
|
| 124 |
+
url = f"{BYBIT_BASE_URL}/v5/market/tickers"
|
| 125 |
+
r = await self._client.get(url, params={"category": "linear"}, timeout=6.0)
|
| 126 |
+
if r.status_code == 200:
|
| 127 |
+
data = r.json()
|
| 128 |
+
items = data.get("result", {}).get("list", [])
|
| 129 |
+
new_map = {}
|
| 130 |
+
for item in items:
|
| 131 |
+
sym = item.get("symbol")
|
| 132 |
+
if sym:
|
| 133 |
+
new_map[sym.upper()] = item
|
| 134 |
+
if new_map:
|
| 135 |
+
self._bybit_tickers = new_map
|
| 136 |
+
except Exception as exc:
|
| 137 |
+
logger.debug("[BulkFetcher] Bybit linear tickers error: %s", exc)
|
| 138 |
+
|
| 139 |
+
def _resolve_key(self, symbol: str, cache_dict: dict[str, Any]) -> str | None:
|
| 140 |
+
"""Resolve exact or candidate variation key in dictionary."""
|
| 141 |
+
sym = symbol.upper().strip()
|
| 142 |
+
if sym in cache_dict:
|
| 143 |
+
return sym
|
| 144 |
+
for var in get_symbol_variations(symbol):
|
| 145 |
+
v_up = var.upper()
|
| 146 |
+
if v_up in cache_dict:
|
| 147 |
+
return v_up
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
# ─────────────────────────────────────────────────────────────────────────
|
| 151 |
+
# Public In-Memory Accessors
|
| 152 |
+
# ─────────────────────────────────────────────────────────────────────────
|
| 153 |
+
|
| 154 |
+
def get_binance_mark_price(self, symbol: str) -> dict[str, Any] | None:
|
| 155 |
+
k = self._resolve_key(symbol, self._binance_premium)
|
| 156 |
+
if not k:
|
| 157 |
+
return None
|
| 158 |
+
item = self._binance_premium[k]
|
| 159 |
+
try:
|
| 160 |
+
mark = float(item["markPrice"])
|
| 161 |
+
index = float(item["indexPrice"])
|
| 162 |
+
basis_pct = ((mark - index) / index * 100) if index else 0.0
|
| 163 |
+
return {
|
| 164 |
+
"mark_price": mark,
|
| 165 |
+
"index_price": index,
|
| 166 |
+
"basis_pct": round(basis_pct, 6),
|
| 167 |
+
}
|
| 168 |
+
except (KeyError, ValueError, TypeError):
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
def get_binance_funding_rate(self, symbol: str) -> dict[str, Any] | None:
|
| 172 |
+
k = self._resolve_key(symbol, self._binance_premium)
|
| 173 |
+
if not k:
|
| 174 |
+
return None
|
| 175 |
+
item = self._binance_premium[k]
|
| 176 |
+
try:
|
| 177 |
+
return {
|
| 178 |
+
"funding_rate": float(item["lastFundingRate"]),
|
| 179 |
+
"next_funding_time": item.get("nextFundingTime"),
|
| 180 |
+
}
|
| 181 |
+
except (KeyError, ValueError, TypeError):
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
def get_binance_24h(self, symbol: str) -> dict[str, Any] | None:
|
| 185 |
+
k = self._resolve_key(symbol, self._binance_24h)
|
| 186 |
+
if not k:
|
| 187 |
+
return None
|
| 188 |
+
item = self._binance_24h[k]
|
| 189 |
+
try:
|
| 190 |
+
return {
|
| 191 |
+
"high_24h": float(item["highPrice"]),
|
| 192 |
+
"low_24h": float(item["lowPrice"]),
|
| 193 |
+
"volume_24h": float(item["volume"]),
|
| 194 |
+
"quote_volume_24h": float(item["quoteVolume"]),
|
| 195 |
+
"price_change_pct": float(item.get("priceChangePercent", 0.0)),
|
| 196 |
+
}
|
| 197 |
+
except (KeyError, ValueError, TypeError):
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
def get_bybit_mark_price(self, symbol: str) -> dict[str, Any] | None:
|
| 201 |
+
k = self._resolve_key(symbol, self._bybit_tickers)
|
| 202 |
+
if not k:
|
| 203 |
+
return None
|
| 204 |
+
item = self._bybit_tickers[k]
|
| 205 |
+
try:
|
| 206 |
+
mark = float(item.get("markPrice", 0))
|
| 207 |
+
index = float(item.get("indexPrice", 0))
|
| 208 |
+
basis_pct = ((mark - index) / index * 100) if index else 0.0
|
| 209 |
+
return {
|
| 210 |
+
"mark_price": mark,
|
| 211 |
+
"index_price": index,
|
| 212 |
+
"basis_pct": round(basis_pct, 6),
|
| 213 |
+
}
|
| 214 |
+
except (KeyError, ValueError, TypeError):
|
| 215 |
+
return None
|
| 216 |
+
|
| 217 |
+
def get_bybit_funding_rate(self, symbol: str) -> dict[str, Any] | None:
|
| 218 |
+
k = self._resolve_key(symbol, self._bybit_tickers)
|
| 219 |
+
if not k:
|
| 220 |
+
return None
|
| 221 |
+
item = self._bybit_tickers[k]
|
| 222 |
+
try:
|
| 223 |
+
fr_raw = item.get("fundingRate")
|
| 224 |
+
if fr_raw is None or fr_raw == "":
|
| 225 |
+
return None
|
| 226 |
+
return {
|
| 227 |
+
"funding_rate": float(fr_raw),
|
| 228 |
+
"next_funding_time": item.get("nextFundingTime"),
|
| 229 |
+
}
|
| 230 |
+
except (KeyError, ValueError, TypeError):
|
| 231 |
+
return None
|
| 232 |
+
|
| 233 |
+
def get_bybit_24h_and_oi(self, symbol: str) -> dict[str, Any] | None:
|
| 234 |
+
k = self._resolve_key(symbol, self._bybit_tickers)
|
| 235 |
+
if not k:
|
| 236 |
+
return None
|
| 237 |
+
item = self._bybit_tickers[k]
|
| 238 |
+
try:
|
| 239 |
+
return {
|
| 240 |
+
"high_24h": float(item.get("highPrice24h", 0)) if item.get("highPrice24h") else None,
|
| 241 |
+
"low_24h": float(item.get("lowPrice24h", 0)) if item.get("lowPrice24h") else None,
|
| 242 |
+
"turnover_24h": float(item.get("turnover24h", 0)) if item.get("turnover24h") else None,
|
| 243 |
+
"open_interest": float(item.get("openInterest", 0)) if item.get("openInterest") else 0.0,
|
| 244 |
+
"open_interest_value": float(item.get("openInterestValue", 0)) if item.get("openInterestValue") else None,
|
| 245 |
+
}
|
| 246 |
+
except (KeyError, ValueError, TypeError):
|
| 247 |
+
return None
|
| 248 |
+
|
| 249 |
+
async def close(self) -> None:
|
| 250 |
+
await self._client.aclose()
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# Global shared instance
|
| 254 |
+
bulk_fetcher = BulkMarketFetcher()
|
backend/engine/signal_engine.py
CHANGED
|
@@ -19,6 +19,7 @@ from engine.mtf_analyzer import MTFAnalyzer
|
|
| 19 |
from engine.fake_detector import FakeDetector
|
| 20 |
from engine.confluence_scorer import ConfluenceScorer
|
| 21 |
from engine.predictive_engine import PredictiveEngine
|
|
|
|
| 22 |
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
|
@@ -840,10 +841,11 @@ def _compute_funding_settlement(exchange_data: dict) -> dict[str, Any]:
|
|
| 840 |
}
|
| 841 |
|
| 842 |
|
| 843 |
-
def _compute_price_extremes_24h(merged_ohlcv: dict, mark_price: float) -> dict[str, Any]:
|
| 844 |
"""
|
| 845 |
Computes rolling 24-hour extremes (High, Low, Range, and % distance).
|
| 846 |
-
Uses the last 24 candles of 1h (or 1d candle if 1h insufficient)
|
|
|
|
| 847 |
Guarantees High >= Mark Price >= Low to prevent inverted range calculations.
|
| 848 |
"""
|
| 849 |
candles_1h = merged_ohlcv.get("1h", []) if merged_ohlcv else []
|
|
@@ -867,6 +869,18 @@ def _compute_price_extremes_24h(merged_ohlcv: dict, mark_price: float) -> dict[s
|
|
| 867 |
if c1d.get("low") and float(c1d["low"]) > 0:
|
| 868 |
lows.append(float(c1d["low"]))
|
| 869 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 870 |
if not highs or not lows or mark_price <= 0:
|
| 871 |
return {
|
| 872 |
"high_24h": mark_price,
|
|
@@ -1020,7 +1034,7 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str
|
|
| 1020 |
|
| 1021 |
return {
|
| 1022 |
"taker_buy_vol_usd": round(taker_buy_vol, 2),
|
| 1023 |
-
"taker_sell_vol_usd": round(taker_sell_vol, 2),
|
| 1024 |
"total_vol_usd": round(total_vol, 2),
|
| 1025 |
"taker_buy_pct": round(buy_pct, 1),
|
| 1026 |
"taker_ratio": round(taker_ratio, 2),
|
|
@@ -1034,6 +1048,132 @@ def _compute_whale_order_flow(trades: list[dict], mark_price: float) -> dict[str
|
|
| 1034 |
}
|
| 1035 |
|
| 1036 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1037 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 1038 |
# Main engine
|
| 1039 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -1262,8 +1402,22 @@ class SignalEngine:
|
|
| 1262 |
# ── 7.5 Institutional Microstructure, Lead-Lag & Order Flow ───────
|
| 1263 |
lead_lag_data = _compute_lead_lag(exchange_data, mark_price)
|
| 1264 |
settlement_data = _compute_funding_settlement(exchange_data)
|
| 1265 |
-
extremes_data = _compute_price_extremes_24h(merged_ohlcv, mark_price)
|
| 1266 |
whale_flow_data = _compute_whale_order_flow(trades, mark_price)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1267 |
|
| 1268 |
# ── 8. Assemble final output ───────────────────────────────────────
|
| 1269 |
now = datetime.now(timezone.utc).isoformat()
|
|
@@ -1282,6 +1436,7 @@ class SignalEngine:
|
|
| 1282 |
"trade_levels": plan["trade_levels"],
|
| 1283 |
"anticipation": predictive_data["anticipation"],
|
| 1284 |
"predictive": predictive_data,
|
|
|
|
| 1285 |
"lead_lag": lead_lag_data,
|
| 1286 |
"funding_settlement": settlement_data,
|
| 1287 |
"price_extremes": extremes_data,
|
|
|
|
| 19 |
from engine.fake_detector import FakeDetector
|
| 20 |
from engine.confluence_scorer import ConfluenceScorer
|
| 21 |
from engine.predictive_engine import PredictiveEngine
|
| 22 |
+
from engine.bulk_fetcher import bulk_fetcher
|
| 23 |
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
|
|
|
| 841 |
}
|
| 842 |
|
| 843 |
|
| 844 |
+
def _compute_price_extremes_24h(merged_ohlcv: dict, mark_price: float, symbol: str = "") -> dict[str, Any]:
|
| 845 |
"""
|
| 846 |
Computes rolling 24-hour extremes (High, Low, Range, and % distance).
|
| 847 |
+
Uses the last 24 candles of 1h (or 1d candle if 1h insufficient),
|
| 848 |
+
with graceful fallback to bulk 24h ticker data.
|
| 849 |
Guarantees High >= Mark Price >= Low to prevent inverted range calculations.
|
| 850 |
"""
|
| 851 |
candles_1h = merged_ohlcv.get("1h", []) if merged_ohlcv else []
|
|
|
|
| 869 |
if c1d.get("low") and float(c1d["low"]) > 0:
|
| 870 |
lows.append(float(c1d["low"]))
|
| 871 |
|
| 872 |
+
# Fallback to pre-fetched bulk 24h ticker extremes
|
| 873 |
+
if (not highs or not lows) and symbol:
|
| 874 |
+
b_24 = bulk_fetcher.get_binance_24h(symbol)
|
| 875 |
+
if b_24 and b_24.get("high_24h") and b_24.get("low_24h"):
|
| 876 |
+
highs.append(float(b_24["high_24h"]))
|
| 877 |
+
lows.append(float(b_24["low_24h"]))
|
| 878 |
+
else:
|
| 879 |
+
by_24 = bulk_fetcher.get_bybit_24h_and_oi(symbol)
|
| 880 |
+
if by_24 and by_24.get("high_24h") and by_24.get("low_24h"):
|
| 881 |
+
highs.append(float(by_24["high_24h"]))
|
| 882 |
+
lows.append(float(by_24["low_24h"]))
|
| 883 |
+
|
| 884 |
if not highs or not lows or mark_price <= 0:
|
| 885 |
return {
|
| 886 |
"high_24h": mark_price,
|
|
|
|
| 1034 |
|
| 1035 |
return {
|
| 1036 |
"taker_buy_vol_usd": round(taker_buy_vol, 2),
|
| 1037 |
+
"taker_sell_vol_usd": round(taker_sell_usd := taker_sell_vol, 2),
|
| 1038 |
"total_vol_usd": round(total_vol, 2),
|
| 1039 |
"taker_buy_pct": round(buy_pct, 1),
|
| 1040 |
"taker_ratio": round(taker_ratio, 2),
|
|
|
|
| 1048 |
}
|
| 1049 |
|
| 1050 |
|
| 1051 |
+
def _compute_breakout_radar(
|
| 1052 |
+
direction: str,
|
| 1053 |
+
conviction: int,
|
| 1054 |
+
predictive_data: dict | None,
|
| 1055 |
+
oi_signal: dict | None,
|
| 1056 |
+
whale_flow: dict | None,
|
| 1057 |
+
extremes_data: dict | None = None,
|
| 1058 |
+
) -> dict[str, Any]:
|
| 1059 |
+
"""
|
| 1060 |
+
Tier 3: Squeeze & Breakout Accumulation Radar.
|
| 1061 |
+
Detects pairs (especially NEUTRAL or consolidation phases) undergoing
|
| 1062 |
+
extreme volatility compression accompanied by silent Open Interest expansion,
|
| 1063 |
+
whale block order flow, or resting liquidity walls.
|
| 1064 |
+
"""
|
| 1065 |
+
pred = predictive_data or {}
|
| 1066 |
+
squeeze = pred.get("volatility_squeeze", {})
|
| 1067 |
+
is_squeeze = bool(squeeze.get("is_squeeze", False))
|
| 1068 |
+
comp_ratio = float(squeeze.get("compression_ratio", 1.0) or 1.0)
|
| 1069 |
+
squeeze_intensity = str(squeeze.get("squeeze_intensity", "NORMAL"))
|
| 1070 |
+
|
| 1071 |
+
whale = whale_flow or {}
|
| 1072 |
+
taker_ratio = float(whale.get("taker_ratio", 1.0) or 1.0)
|
| 1073 |
+
whale_buy_vol = float(whale.get("whale_buy_vol_usd", 0.0) or 0.0)
|
| 1074 |
+
whale_sell_vol = float(whale.get("whale_sell_vol_usd", 0.0) or 0.0)
|
| 1075 |
+
net_whale_usd = whale_buy_vol - whale_sell_vol
|
| 1076 |
+
|
| 1077 |
+
oi_val = (oi_signal or {}).get("oi_change_pct")
|
| 1078 |
+
oi_change_pct = float(oi_val) if oi_val is not None else 0.0
|
| 1079 |
+
|
| 1080 |
+
ob_skew = pred.get("orderbook_skew", {})
|
| 1081 |
+
skew_ratio = float(ob_skew.get("skew_ratio", 0.0) or 0.0)
|
| 1082 |
+
|
| 1083 |
+
# Accumulation & catalyst signals
|
| 1084 |
+
accumulation_signals = []
|
| 1085 |
+
bull_bias_pts = 0
|
| 1086 |
+
bear_bias_pts = 0
|
| 1087 |
+
|
| 1088 |
+
if abs(oi_change_pct) >= 1.5:
|
| 1089 |
+
if oi_change_pct > 0:
|
| 1090 |
+
accumulation_signals.append(f"Ekspansi OI +{oi_change_pct:.1f}%")
|
| 1091 |
+
else:
|
| 1092 |
+
accumulation_signals.append(f"Unwinding OI {oi_change_pct:.1f}%")
|
| 1093 |
+
|
| 1094 |
+
if whale_buy_vol > 0 or whale_sell_vol > 0:
|
| 1095 |
+
if net_whale_usd > 15000 or (whale_buy_vol > whale_sell_vol * 1.4 and whale_buy_vol > 10000):
|
| 1096 |
+
bull_bias_pts += 2
|
| 1097 |
+
accumulation_signals.append(f"Akumulasi Paus +${whale_buy_vol:,.0f}")
|
| 1098 |
+
elif net_whale_usd < -15000 or (whale_sell_vol > whale_buy_vol * 1.4 and whale_sell_vol > 10000):
|
| 1099 |
+
bear_bias_pts += 2
|
| 1100 |
+
accumulation_signals.append(f"Distribusi Paus -${whale_sell_vol:,.0f}")
|
| 1101 |
+
|
| 1102 |
+
if taker_ratio >= 1.25:
|
| 1103 |
+
bull_bias_pts += 1
|
| 1104 |
+
accumulation_signals.append(f"Taker Buy {taker_ratio:.2f}x")
|
| 1105 |
+
elif taker_ratio <= 0.75:
|
| 1106 |
+
bear_bias_pts += 1
|
| 1107 |
+
accumulation_signals.append(f"Taker Sell {taker_ratio:.2f}x")
|
| 1108 |
+
|
| 1109 |
+
if skew_ratio >= 0.20:
|
| 1110 |
+
bull_bias_pts += 1
|
| 1111 |
+
accumulation_signals.append("Bids Wall Dominan")
|
| 1112 |
+
elif skew_ratio <= -0.20:
|
| 1113 |
+
bear_bias_pts += 1
|
| 1114 |
+
accumulation_signals.append("Asks Wall Dominan")
|
| 1115 |
+
|
| 1116 |
+
primary_magnet = pred.get("liquidation_magnets", {}).get("primary_magnet")
|
| 1117 |
+
if primary_magnet == "UPPER":
|
| 1118 |
+
bull_bias_pts += 1
|
| 1119 |
+
elif primary_magnet == "LOWER":
|
| 1120 |
+
bear_bias_pts += 1
|
| 1121 |
+
|
| 1122 |
+
# Stage classification
|
| 1123 |
+
is_compressed = is_squeeze or (comp_ratio <= 0.65)
|
| 1124 |
+
|
| 1125 |
+
if is_compressed:
|
| 1126 |
+
if len(accumulation_signals) >= 2 or abs(net_whale_usd) >= 25000 or abs(oi_change_pct) >= 2.5:
|
| 1127 |
+
squeeze_stage = "READY_TO_BURST"
|
| 1128 |
+
elif len(accumulation_signals) >= 1 or comp_ratio <= 0.50:
|
| 1129 |
+
squeeze_stage = "ACCUMULATING"
|
| 1130 |
+
else:
|
| 1131 |
+
squeeze_stage = "COILING"
|
| 1132 |
+
is_breakout_primed = True
|
| 1133 |
+
elif comp_ratio <= 0.80 and len(accumulation_signals) >= 2:
|
| 1134 |
+
squeeze_stage = "ACCUMULATING"
|
| 1135 |
+
is_breakout_primed = True
|
| 1136 |
+
else:
|
| 1137 |
+
squeeze_stage = "NORMAL"
|
| 1138 |
+
is_breakout_primed = False
|
| 1139 |
+
|
| 1140 |
+
# Projected Direction
|
| 1141 |
+
if bull_bias_pts > bear_bias_pts:
|
| 1142 |
+
projected_dir = "BREAKOUT_UP"
|
| 1143 |
+
dir_label = "BULLISH BIAS"
|
| 1144 |
+
elif bear_bias_pts > bull_bias_pts:
|
| 1145 |
+
projected_dir = "BREAKOUT_DOWN"
|
| 1146 |
+
dir_label = "BEARISH BIAS"
|
| 1147 |
+
else:
|
| 1148 |
+
projected_dir = "COILING_NEUTRAL"
|
| 1149 |
+
dir_label = "EXPANSION PENDING"
|
| 1150 |
+
|
| 1151 |
+
# Radar badge and summary
|
| 1152 |
+
if is_breakout_primed:
|
| 1153 |
+
if squeeze_stage == "READY_TO_BURST":
|
| 1154 |
+
radar_label = f"🚨 READY TO BURST [{dir_label}]"
|
| 1155 |
+
elif squeeze_stage == "ACCUMULATING":
|
| 1156 |
+
radar_label = f"⚡ ACCUMULATION [{dir_label}]"
|
| 1157 |
+
else:
|
| 1158 |
+
radar_label = f"🌀 COILING SQUEEZE"
|
| 1159 |
+
|
| 1160 |
+
catalyst_str = ", ".join(accumulation_signals) if accumulation_signals else "Kompresi ATR ketat"
|
| 1161 |
+
catalyst_summary = f"Kompresi ATR {comp_ratio:.2f}x ({squeeze_intensity}). Katalis: {catalyst_str}. Siaga ledakan volatilitas dlm 1-4 jam."
|
| 1162 |
+
else:
|
| 1163 |
+
radar_label = "NORMAL VOLATILITY"
|
| 1164 |
+
catalyst_summary = f"Rentang volatilitas normal (Rasio ATR {comp_ratio:.2f}x)."
|
| 1165 |
+
|
| 1166 |
+
return {
|
| 1167 |
+
"is_breakout_primed": is_breakout_primed,
|
| 1168 |
+
"radar_label": radar_label,
|
| 1169 |
+
"squeeze_stage": squeeze_stage,
|
| 1170 |
+
"projected_direction": projected_dir,
|
| 1171 |
+
"compression_ratio": round(comp_ratio, 3),
|
| 1172 |
+
"catalyst_summary": catalyst_summary,
|
| 1173 |
+
"catalysts": accumulation_signals,
|
| 1174 |
+
}
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 1178 |
# Main engine
|
| 1179 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 1402 |
# ── 7.5 Institutional Microstructure, Lead-Lag & Order Flow ───────
|
| 1403 |
lead_lag_data = _compute_lead_lag(exchange_data, mark_price)
|
| 1404 |
settlement_data = _compute_funding_settlement(exchange_data)
|
| 1405 |
+
extremes_data = _compute_price_extremes_24h(merged_ohlcv, mark_price, symbol=symbol)
|
| 1406 |
whale_flow_data = _compute_whale_order_flow(trades, mark_price)
|
| 1407 |
+
breakout_radar_data = _compute_breakout_radar(
|
| 1408 |
+
direction=confluence["direction"],
|
| 1409 |
+
conviction=confluence["conviction"],
|
| 1410 |
+
predictive_data=predictive_data,
|
| 1411 |
+
oi_signal=oi_signal,
|
| 1412 |
+
whale_flow=whale_flow_data,
|
| 1413 |
+
extremes_data=extremes_data,
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
if confluence["direction"] == "NEUTRAL" and breakout_radar_data.get("is_breakout_primed"):
|
| 1417 |
+
if plan.get("action") == "WAIT":
|
| 1418 |
+
plan["action"] = "WATCH BREAKOUT"
|
| 1419 |
+
if plan.get("quick_verdict"):
|
| 1420 |
+
plan["quick_verdict"] = f"{breakout_radar_data['radar_label']}: {breakout_radar_data['catalyst_summary']}"
|
| 1421 |
|
| 1422 |
# ── 8. Assemble final output ───────────────────────────────────────
|
| 1423 |
now = datetime.now(timezone.utc).isoformat()
|
|
|
|
| 1436 |
"trade_levels": plan["trade_levels"],
|
| 1437 |
"anticipation": predictive_data["anticipation"],
|
| 1438 |
"predictive": predictive_data,
|
| 1439 |
+
"breakout_radar": breakout_radar_data,
|
| 1440 |
"lead_lag": lead_lag_data,
|
| 1441 |
"funding_settlement": settlement_data,
|
| 1442 |
"price_extremes": extremes_data,
|
backend/exchanges/binance.py
CHANGED
|
@@ -15,6 +15,7 @@ from config import BINANCE_FUTURES_BASE_URL, PROXY_URL
|
|
| 15 |
from exchanges.base import BaseExchange
|
| 16 |
from engine.doh_resolver import enable_doh_bypass
|
| 17 |
from engine.symbol_resolver import get_symbol_variations
|
|
|
|
| 18 |
|
| 19 |
enable_doh_bypass()
|
| 20 |
|
|
@@ -158,6 +159,9 @@ class BinanceClient(BaseExchange):
|
|
| 158 |
return False
|
| 159 |
|
| 160 |
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
| 161 |
sym = self.resolve_symbol(symbol) or symbol
|
| 162 |
data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym})
|
| 163 |
mark = float(data["markPrice"])
|
|
@@ -170,6 +174,9 @@ class BinanceClient(BaseExchange):
|
|
| 170 |
}
|
| 171 |
|
| 172 |
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
| 173 |
sym = self.resolve_symbol(symbol) or symbol
|
| 174 |
data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym})
|
| 175 |
return {
|
|
|
|
| 15 |
from exchanges.base import BaseExchange
|
| 16 |
from engine.doh_resolver import enable_doh_bypass
|
| 17 |
from engine.symbol_resolver import get_symbol_variations
|
| 18 |
+
from engine.bulk_fetcher import bulk_fetcher
|
| 19 |
|
| 20 |
enable_doh_bypass()
|
| 21 |
|
|
|
|
| 159 |
return False
|
| 160 |
|
| 161 |
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
|
| 162 |
+
bulk_data = bulk_fetcher.get_binance_mark_price(symbol)
|
| 163 |
+
if bulk_data:
|
| 164 |
+
return bulk_data
|
| 165 |
sym = self.resolve_symbol(symbol) or symbol
|
| 166 |
data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym})
|
| 167 |
mark = float(data["markPrice"])
|
|
|
|
| 174 |
}
|
| 175 |
|
| 176 |
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
|
| 177 |
+
bulk_data = bulk_fetcher.get_binance_funding_rate(symbol)
|
| 178 |
+
if bulk_data:
|
| 179 |
+
return bulk_data
|
| 180 |
sym = self.resolve_symbol(symbol) or symbol
|
| 181 |
data = await self._get("/fapi/v1/premiumIndex", {"symbol": sym})
|
| 182 |
return {
|
backend/exchanges/bybit.py
CHANGED
|
@@ -14,6 +14,7 @@ import httpx
|
|
| 14 |
from config import BYBIT_BASE_URL, PROXY_URL
|
| 15 |
from exchanges.base import BaseExchange
|
| 16 |
from engine.symbol_resolver import get_symbol_variations
|
|
|
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
@@ -155,6 +156,9 @@ class BybitClient(BaseExchange):
|
|
| 155 |
return False
|
| 156 |
|
| 157 |
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
| 158 |
sym = self.resolve_symbol(symbol) or symbol
|
| 159 |
result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym})
|
| 160 |
items = result.get("list", [])
|
|
@@ -171,6 +175,9 @@ class BybitClient(BaseExchange):
|
|
| 171 |
}
|
| 172 |
|
| 173 |
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
|
|
|
|
|
|
|
|
|
|
| 174 |
sym = self.resolve_symbol(symbol) or symbol
|
| 175 |
result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym})
|
| 176 |
items = result.get("list", [])
|
|
@@ -214,6 +221,17 @@ class BybitClient(BaseExchange):
|
|
| 214 |
}
|
| 215 |
except Exception as exc:
|
| 216 |
logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None}
|
| 218 |
|
| 219 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
|
|
|
| 14 |
from config import BYBIT_BASE_URL, PROXY_URL
|
| 15 |
from exchanges.base import BaseExchange
|
| 16 |
from engine.symbol_resolver import get_symbol_variations
|
| 17 |
+
from engine.bulk_fetcher import bulk_fetcher
|
| 18 |
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
|
|
|
| 156 |
return False
|
| 157 |
|
| 158 |
async def get_mark_price(self, symbol: str) -> dict[str, Any]:
|
| 159 |
+
bulk_data = bulk_fetcher.get_bybit_mark_price(symbol)
|
| 160 |
+
if bulk_data:
|
| 161 |
+
return bulk_data
|
| 162 |
sym = self.resolve_symbol(symbol) or symbol
|
| 163 |
result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym})
|
| 164 |
items = result.get("list", [])
|
|
|
|
| 175 |
}
|
| 176 |
|
| 177 |
async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
|
| 178 |
+
bulk_data = bulk_fetcher.get_bybit_funding_rate(symbol)
|
| 179 |
+
if bulk_data:
|
| 180 |
+
return bulk_data
|
| 181 |
sym = self.resolve_symbol(symbol) or symbol
|
| 182 |
result = await self._get("/v5/market/tickers", {"category": "linear", "symbol": sym})
|
| 183 |
items = result.get("list", [])
|
|
|
|
| 221 |
}
|
| 222 |
except Exception as exc:
|
| 223 |
logger.debug("[Bybit] OI fetch note for %s: %s", sym, exc)
|
| 224 |
+
|
| 225 |
+
# Fallback to bulk ticker OI if available
|
| 226 |
+
bulk_oi = bulk_fetcher.get_bybit_24h_and_oi(symbol)
|
| 227 |
+
if bulk_oi and bulk_oi.get("open_interest"):
|
| 228 |
+
return {
|
| 229 |
+
"open_interest": bulk_oi["open_interest"],
|
| 230 |
+
"prev_open_interest": None,
|
| 231 |
+
"oi_change_pct": 0.0,
|
| 232 |
+
"open_interest_value": bulk_oi.get("open_interest_value"),
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
return {"open_interest": 0.0, "prev_open_interest": None, "oi_change_pct": 0.0, "open_interest_value": None}
|
| 236 |
|
| 237 |
async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
|
backend/main.py
CHANGED
|
@@ -13,6 +13,7 @@ Background loop:
|
|
| 13 |
"""
|
| 14 |
|
| 15 |
import os
|
|
|
|
| 16 |
import asyncio
|
| 17 |
import logging
|
| 18 |
from contextlib import asynccontextmanager
|
|
@@ -43,6 +44,7 @@ from exchanges.okx import OKXClient
|
|
| 43 |
from exchanges.hyperliquid import HyperliquidClient
|
| 44 |
from engine.data_collector import DataCollector
|
| 45 |
from engine.signal_engine import SignalEngine
|
|
|
|
| 46 |
from routers import pairs as pairs_router
|
| 47 |
from routers import signals as signals_router
|
| 48 |
from routers import ws as ws_router
|
|
@@ -211,26 +213,54 @@ async def _process_pair(
|
|
| 211 |
|
| 212 |
|
| 213 |
async def _signal_loop(collector: DataCollector) -> None:
|
| 214 |
-
"""
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
loop_count = 0
|
| 217 |
|
| 218 |
-
async def _guarded_process(p: dict) -> None:
|
| 219 |
-
async with semaphore:
|
| 220 |
-
try:
|
| 221 |
-
await _process_pair(p, collector)
|
| 222 |
-
except Exception as exc:
|
| 223 |
-
logger.error("[%s] Unexpected error in _guarded_process: %s", p.get("symbol"), exc)
|
| 224 |
-
|
| 225 |
while True:
|
|
|
|
| 226 |
try:
|
| 227 |
pairs = await async_get_active_pairs()
|
| 228 |
if not pairs:
|
| 229 |
logger.info("No active pairs — sleeping %ds", UPDATE_INTERVAL)
|
| 230 |
else:
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
loop_count += 1
|
| 236 |
# Run DB retention pruning once every 60 iterations (~1 hour) to keep Neon free tier healthy
|
|
@@ -246,16 +276,22 @@ async def _signal_loop(collector: DataCollector) -> None:
|
|
| 246 |
except Exception as loop_err:
|
| 247 |
logger.error("Error in signal loop iteration: %s", loop_err, exc_info=True)
|
| 248 |
|
| 249 |
-
|
|
|
|
|
|
|
| 250 |
|
| 251 |
|
| 252 |
async def process_active_pairs_batch(collector: DataCollector, limit: int = 30) -> int:
|
| 253 |
-
"""Process active pairs in parallel
|
| 254 |
try:
|
| 255 |
pairs = await async_get_active_pairs()
|
| 256 |
if not pairs:
|
| 257 |
return 0
|
| 258 |
target_pairs = pairs[:limit] if limit else pairs
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
semaphore = asyncio.Semaphore(6)
|
| 260 |
|
| 261 |
async def _guarded(p: dict) -> None:
|
|
@@ -323,7 +359,8 @@ async def lifespan(app: FastAPI):
|
|
| 323 |
pass
|
| 324 |
|
| 325 |
if not is_serverless:
|
| 326 |
-
# Warm up symbol caches in non-blocking background tasks on persistent boot
|
|
|
|
| 327 |
asyncio.create_task(binance._load_symbols())
|
| 328 |
asyncio.create_task(bybit._load_symbols())
|
| 329 |
asyncio.create_task(okx._load_symbols())
|
|
@@ -347,6 +384,7 @@ async def lifespan(app: FastAPI):
|
|
| 347 |
except asyncio.CancelledError:
|
| 348 |
pass
|
| 349 |
|
|
|
|
| 350 |
await binance.close()
|
| 351 |
await bybit.close()
|
| 352 |
await okx.close()
|
|
|
|
| 13 |
"""
|
| 14 |
|
| 15 |
import os
|
| 16 |
+
import time
|
| 17 |
import asyncio
|
| 18 |
import logging
|
| 19 |
from contextlib import asynccontextmanager
|
|
|
|
| 44 |
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
|
|
|
|
| 213 |
|
| 214 |
|
| 215 |
async def _signal_loop(collector: DataCollector) -> None:
|
| 216 |
+
"""
|
| 217 |
+
Tier 2: Dynamic Auto-Partitioned Shard Worker Loop.
|
| 218 |
+
Automatically slices active pairs into balanced shards (e.g. 15 pairs per shard),
|
| 219 |
+
pre-fetches bulk market data across Binance & Bybit, executes shard concurrent workers,
|
| 220 |
+
and applies staggered micro-intervals between shards for smooth throughput and zero rate-limiting.
|
| 221 |
+
"""
|
| 222 |
+
SHARD_SIZE = 15
|
| 223 |
+
CONCURRENCY_PER_SHARD = 5
|
| 224 |
loop_count = 0
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
while True:
|
| 227 |
+
cycle_start = time.time()
|
| 228 |
try:
|
| 229 |
pairs = await async_get_active_pairs()
|
| 230 |
if not pairs:
|
| 231 |
logger.info("No active pairs — sleeping %ds", UPDATE_INTERVAL)
|
| 232 |
else:
|
| 233 |
+
total_pairs = len(pairs)
|
| 234 |
+
shards = [pairs[i:i + SHARD_SIZE] for i in range(0, total_pairs, SHARD_SIZE)]
|
| 235 |
+
num_shards = len(shards)
|
| 236 |
+
logger.info(
|
| 237 |
+
"Processing %d active pair(s) across %d auto-partitioned shard(s) (shard_size=%d, concurrency=%d)...",
|
| 238 |
+
total_pairs, num_shards, SHARD_SIZE, CONCURRENCY_PER_SHARD
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
# Pre-fetch bulk market snapshots across exchanges in one swift call
|
| 242 |
+
try:
|
| 243 |
+
await bulk_fetcher.refresh_if_stale(force=True)
|
| 244 |
+
except Exception as b_err:
|
| 245 |
+
logger.debug("Bulk fetch pre-loop note: %s", b_err)
|
| 246 |
+
|
| 247 |
+
semaphore = asyncio.Semaphore(CONCURRENCY_PER_SHARD)
|
| 248 |
+
|
| 249 |
+
async def _guarded_process(p: dict) -> None:
|
| 250 |
+
async with semaphore:
|
| 251 |
+
try:
|
| 252 |
+
await _process_pair(p, collector)
|
| 253 |
+
except Exception as exc:
|
| 254 |
+
logger.error("[%s] Unexpected error in _guarded_process: %s", p.get("symbol"), exc)
|
| 255 |
+
|
| 256 |
+
for idx, shard in enumerate(shards):
|
| 257 |
+
tasks = [_guarded_process(p) for p in shard]
|
| 258 |
+
await asyncio.gather(*tasks, return_exceptions=True)
|
| 259 |
+
|
| 260 |
+
# Stagger micro-interval between shards if multiple exist to distribute network and DB I/O
|
| 261 |
+
if idx < num_shards - 1:
|
| 262 |
+
stagger = max(1.5, min(4.0, (UPDATE_INTERVAL * 0.4) / max(1, num_shards)))
|
| 263 |
+
await asyncio.sleep(stagger)
|
| 264 |
|
| 265 |
loop_count += 1
|
| 266 |
# Run DB retention pruning once every 60 iterations (~1 hour) to keep Neon free tier healthy
|
|
|
|
| 276 |
except Exception as loop_err:
|
| 277 |
logger.error("Error in signal loop iteration: %s", loop_err, exc_info=True)
|
| 278 |
|
| 279 |
+
elapsed = time.time() - cycle_start
|
| 280 |
+
sleep_time = max(3.0, UPDATE_INTERVAL - elapsed)
|
| 281 |
+
await asyncio.sleep(sleep_time)
|
| 282 |
|
| 283 |
|
| 284 |
async def process_active_pairs_batch(collector: DataCollector, limit: int = 30) -> int:
|
| 285 |
+
"""Process active pairs in parallel shards. Pre-fetches bulk cache first. Returns count of processed pairs."""
|
| 286 |
try:
|
| 287 |
pairs = await async_get_active_pairs()
|
| 288 |
if not pairs:
|
| 289 |
return 0
|
| 290 |
target_pairs = pairs[:limit] if limit else pairs
|
| 291 |
+
try:
|
| 292 |
+
await bulk_fetcher.refresh_if_stale(force=True)
|
| 293 |
+
except Exception:
|
| 294 |
+
pass
|
| 295 |
semaphore = asyncio.Semaphore(6)
|
| 296 |
|
| 297 |
async def _guarded(p: dict) -> None:
|
|
|
|
| 359 |
pass
|
| 360 |
|
| 361 |
if not is_serverless:
|
| 362 |
+
# Warm up symbol caches and bulk market pre-fetcher in non-blocking background tasks on persistent boot
|
| 363 |
+
asyncio.create_task(bulk_fetcher.refresh_if_stale(force=True))
|
| 364 |
asyncio.create_task(binance._load_symbols())
|
| 365 |
asyncio.create_task(bybit._load_symbols())
|
| 366 |
asyncio.create_task(okx._load_symbols())
|
|
|
|
| 384 |
except asyncio.CancelledError:
|
| 385 |
pass
|
| 386 |
|
| 387 |
+
await bulk_fetcher.close()
|
| 388 |
await binance.close()
|
| 389 |
await bybit.close()
|
| 390 |
await okx.close()
|
backend/routers/ai.py
CHANGED
|
@@ -215,6 +215,17 @@ def _build_ai_prompt(
|
|
| 215 |
"flow_verdict": "Order Flow Agregat Seimbang",
|
| 216 |
}
|
| 217 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
# 1. Total Aggregated Open Interest across all venues
|
| 219 |
total_oi_usd = 0.0
|
| 220 |
venue_oi_str_list = []
|
|
@@ -435,6 +446,8 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 435 |
6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK
|
| 436 |
• Struktur MTF: 1D: {struct_map.get('1d', 'unknown').upper()} | 4H: {struct_map.get('4h', 'unknown').upper()} | 1H: {struct_map.get('1h', 'unknown').upper()} | 15M: {struct_map.get('15m', 'unknown').upper()} (Active TF: {active_tf.upper()})
|
| 437 |
• Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
|
|
|
|
|
|
|
| 438 |
• Kedalaman Orderbook (Top 20 Depth): ${bid_depth:,.0f} Bids vs ${ask_depth:,.0f} Asks (Rasio: {depth_ratio:.2f}x) -> {resting_pressure}
|
| 439 |
|
| 440 |
7. MAGNET LIKUIDASI WHALE & TARGET PREDIKTIF
|
|
@@ -458,7 +471,8 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 458 |
3. HUKUM CVD & LEVERAGE TRAP: Jika Futures CVD naik tapi Spot CVD turun/negatif, ini adalah LEVERAGE TRAP (Retail beli futures, Spot buang barang). DILARANG menyarankan Long mengejar pucuk!
|
| 459 |
4. ATURAN INVALIDASI KRITIS: Syarat pembatalan setup WAJIB berbasis penutupan candle (misal: "Batal jika candle 1H ditutup di bawah $X"), BUKAN sekadar sengatan jarum wick touch.
|
| 460 |
5. SINTESIS LEAD-LAG & EXTREMES 24 JAM: Sebutkan bursa mana yang memimpin pergerakan harga dan perhatikan posisi harga terhadap 24H High/Low sebagai zona take profit/invalidation alami.
|
| 461 |
-
6.
|
|
|
|
| 462 |
|
| 463 |
=== 📝 FORMAT OUTPUT WAJIB (Bahasa Indonesia) ===
|
| 464 |
### 🏛️ 1. EXECUTIVE VERDICT & KONSENSUS BURSA
|
|
@@ -523,6 +537,7 @@ Analisa data empiris komprehensif {symbol} berikut secara objektif, tajam, presi
|
|
| 523 |
"taker_buy_pct": whale_flow.get("taker_buy_pct"),
|
| 524 |
"whale_buy_count": whale_flow.get("whale_buy_count"),
|
| 525 |
"whale_sell_count": whale_flow.get("whale_sell_count"),
|
|
|
|
| 526 |
}
|
| 527 |
|
| 528 |
return prompt, data_summary
|
|
|
|
| 215 |
"flow_verdict": "Order Flow Agregat Seimbang",
|
| 216 |
}
|
| 217 |
|
| 218 |
+
breakout = signals_data.get("breakout_radar") or {}
|
| 219 |
+
if not breakout:
|
| 220 |
+
breakout = {
|
| 221 |
+
"is_breakout_primed": False,
|
| 222 |
+
"radar_label": "NORMAL VOLATILITY",
|
| 223 |
+
"squeeze_stage": "NORMAL",
|
| 224 |
+
"projected_direction": "COILING_NEUTRAL",
|
| 225 |
+
"compression_ratio": 1.0,
|
| 226 |
+
"catalyst_summary": "Volatilitas normal",
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
# 1. Total Aggregated Open Interest across all venues
|
| 230 |
total_oi_usd = 0.0
|
| 231 |
venue_oi_str_list = []
|
|
|
|
| 446 |
6. STRUKTUR MULTI-TIMEFRAME (MTF), VOLATILITAS & ORDERBOOK
|
| 447 |
• Struktur MTF: 1D: {struct_map.get('1d', 'unknown').upper()} | 4H: {struct_map.get('4h', 'unknown').upper()} | 1H: {struct_map.get('1h', 'unknown').upper()} | 15M: {struct_map.get('15m', 'unknown').upper()} (Active TF: {active_tf.upper()})
|
| 448 |
• Volatility Squeeze: {squeeze_intensity} (Compression Ratio: {compression_ratio:.2f})
|
| 449 |
+
• Radar Squeeze & Breakout: {breakout.get('radar_label')} | Stage: {breakout.get('squeeze_stage')} | Proyeksi Arah: {breakout.get('projected_direction')}
|
| 450 |
+
• Katalis Breakout: {breakout.get('catalyst_summary')}
|
| 451 |
• Kedalaman Orderbook (Top 20 Depth): ${bid_depth:,.0f} Bids vs ${ask_depth:,.0f} Asks (Rasio: {depth_ratio:.2f}x) -> {resting_pressure}
|
| 452 |
|
| 453 |
7. MAGNET LIKUIDASI WHALE & TARGET PREDIKTIF
|
|
|
|
| 471 |
3. HUKUM CVD & LEVERAGE TRAP: Jika Futures CVD naik tapi Spot CVD turun/negatif, ini adalah LEVERAGE TRAP (Retail beli futures, Spot buang barang). DILARANG menyarankan Long mengejar pucuk!
|
| 472 |
4. ATURAN INVALIDASI KRITIS: Syarat pembatalan setup WAJIB berbasis penutupan candle (misal: "Batal jika candle 1H ditutup di bawah $X"), BUKAN sekadar sengatan jarum wick touch.
|
| 473 |
5. SINTESIS LEAD-LAG & EXTREMES 24 JAM: Sebutkan bursa mana yang memimpin pergerakan harga dan perhatikan posisi harga terhadap 24H High/Low sebagai zona take profit/invalidation alami.
|
| 474 |
+
6. PAIR NETRAL DENGAN SQUEEZE RADAR: Jika sinyal saat ini NETRAL namun Squeeze Radar mendeteksi 'READY TO BURST' atau 'ACCUMULATION', jangan diabaikan! Jelaskan bahwa energi sedang terkompresi kuat dan siapkan skenario pemicu breakout (breakout trigger levels).
|
| 475 |
+
7. Gaya Penulisan: Padat, poin per poin tajam, bernada Quantitative Research Desk Telegram. Panjang 350-500 kata.
|
| 476 |
|
| 477 |
=== 📝 FORMAT OUTPUT WAJIB (Bahasa Indonesia) ===
|
| 478 |
### 🏛️ 1. EXECUTIVE VERDICT & KONSENSUS BURSA
|
|
|
|
| 537 |
"taker_buy_pct": whale_flow.get("taker_buy_pct"),
|
| 538 |
"whale_buy_count": whale_flow.get("whale_buy_count"),
|
| 539 |
"whale_sell_count": whale_flow.get("whale_sell_count"),
|
| 540 |
+
"breakout_radar": breakout,
|
| 541 |
}
|
| 542 |
|
| 543 |
return prompt, data_summary
|
frontend/src/components/signals/AIAnalysisPanel.tsx
CHANGED
|
@@ -429,6 +429,16 @@ export function AIAnalysisPanel({ symbol }: AIAnalysisPanelProps) {
|
|
| 429 |
</span>
|
| 430 |
</div>
|
| 431 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 432 |
</div>
|
| 433 |
)}
|
| 434 |
|
|
|
|
| 429 |
</span>
|
| 430 |
</div>
|
| 431 |
)}
|
| 432 |
+
{result.data_snapshot.breakout_radar?.is_breakout_primed && (
|
| 433 |
+
<div className="col-span-2 sm:col-span-3 p-1.5 rounded bg-purple-500/15 border border-purple-500/30 flex items-center justify-between">
|
| 434 |
+
<span className="text-yellow-400 font-bold text-[9px] flex items-center gap-1 shrink-0">
|
| 435 |
+
<Zap size={10} /> SQUEEZE RADAR:
|
| 436 |
+
</span>
|
| 437 |
+
<span className="text-purple-200 text-[10px] font-semibold truncate ml-2">
|
| 438 |
+
{result.data_snapshot.breakout_radar.radar_label} — {result.data_snapshot.breakout_radar.catalyst_summary}
|
| 439 |
+
</span>
|
| 440 |
+
</div>
|
| 441 |
+
)}
|
| 442 |
</div>
|
| 443 |
)}
|
| 444 |
|
frontend/src/components/signals/AIExecutiveSummaryCard.tsx
CHANGED
|
@@ -33,6 +33,7 @@ export interface AIExecutiveSummary {
|
|
| 33 |
confluenceConsensus?: string;
|
| 34 |
leadLag?: string;
|
| 35 |
fundingSettlement?: string;
|
|
|
|
| 36 |
}
|
| 37 |
|
| 38 |
interface AIExecutiveSummaryCardProps {
|
|
@@ -183,6 +184,15 @@ export function parseAIExecutiveSummary(
|
|
| 183 |
fundingSettlement = fallbackSnapshot.funding_countdown;
|
| 184 |
}
|
| 185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
if (bias || entryZone || stopLoss || verdictSummary) {
|
| 187 |
return {
|
| 188 |
bias: bias || 'ANALYZED',
|
|
@@ -200,6 +210,7 @@ export function parseAIExecutiveSummary(
|
|
| 200 |
confluenceConsensus,
|
| 201 |
leadLag,
|
| 202 |
fundingSettlement,
|
|
|
|
| 203 |
};
|
| 204 |
}
|
| 205 |
|
|
@@ -493,8 +504,14 @@ export function AIExecutiveSummaryCard({
|
|
| 493 |
)}
|
| 494 |
|
| 495 |
{/* ── 5. Market Context Badges (Microstructure Catalyst) ───────────── */}
|
| 496 |
-
{(summary.liquidationMagnet || summary.flowStatus || summary.confluenceConsensus || summary.leadLag || summary.fundingSettlement) && (
|
| 497 |
<div className="flex flex-wrap items-center gap-1.5 pt-1 text-[10px] font-mono text-text-muted">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
{summary.liquidationMagnet && (
|
| 499 |
<div className="px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1">
|
| 500 |
<span className="text-purple-400">🧲 Magnet:</span>
|
|
|
|
| 33 |
confluenceConsensus?: string;
|
| 34 |
leadLag?: string;
|
| 35 |
fundingSettlement?: string;
|
| 36 |
+
breakoutRadar?: string;
|
| 37 |
}
|
| 38 |
|
| 39 |
interface AIExecutiveSummaryCardProps {
|
|
|
|
| 184 |
fundingSettlement = fallbackSnapshot.funding_countdown;
|
| 185 |
}
|
| 186 |
|
| 187 |
+
let breakoutRadar = extractFromText(text, [
|
| 188 |
+
/Radar Squeeze & Breakout[:\s*]+([^\n\r]+)/i,
|
| 189 |
+
/Energi Volatilitas & Profil 24 Jam[:\s*]+([^\n\r]+)/i,
|
| 190 |
+
/Squeeze Radar[:\s*]+([^\n\r]+)/i,
|
| 191 |
+
]);
|
| 192 |
+
if (!breakoutRadar && fallbackSnapshot?.breakout_radar?.is_breakout_primed) {
|
| 193 |
+
breakoutRadar = `${fallbackSnapshot.breakout_radar.radar_label} (${fallbackSnapshot.breakout_radar.squeeze_stage})`;
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
if (bias || entryZone || stopLoss || verdictSummary) {
|
| 197 |
return {
|
| 198 |
bias: bias || 'ANALYZED',
|
|
|
|
| 210 |
confluenceConsensus,
|
| 211 |
leadLag,
|
| 212 |
fundingSettlement,
|
| 213 |
+
breakoutRadar,
|
| 214 |
};
|
| 215 |
}
|
| 216 |
|
|
|
|
| 504 |
)}
|
| 505 |
|
| 506 |
{/* ── 5. Market Context Badges (Microstructure Catalyst) ───────────── */}
|
| 507 |
+
{(summary.liquidationMagnet || summary.flowStatus || summary.confluenceConsensus || summary.leadLag || summary.fundingSettlement || summary.breakoutRadar) && (
|
| 508 |
<div className="flex flex-wrap items-center gap-1.5 pt-1 text-[10px] font-mono text-text-muted">
|
| 509 |
+
{summary.breakoutRadar && (
|
| 510 |
+
<div className="px-2 py-0.5 rounded-md bg-purple-500/20 border border-purple-500/40 text-purple-300 flex items-center gap-1 animate-pulse">
|
| 511 |
+
<span className="text-yellow-400">🚨 Squeeze:</span>
|
| 512 |
+
<span className="font-semibold text-purple-200">{summary.breakoutRadar}</span>
|
| 513 |
+
</div>
|
| 514 |
+
)}
|
| 515 |
{summary.liquidationMagnet && (
|
| 516 |
<div className="px-2 py-0.5 rounded-md bg-bg-card border border-border flex items-center gap-1">
|
| 517 |
<span className="text-purple-400">🧲 Magnet:</span>
|
frontend/src/components/signals/SignalCard.tsx
CHANGED
|
@@ -166,7 +166,23 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
|
|
| 166 |
<span>Spot</span>
|
| 167 |
</span>
|
| 168 |
)}
|
| 169 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
<span
|
| 171 |
className="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse"
|
| 172 |
title="Volatility Squeeze (Breakout Imminent)"
|
|
@@ -174,7 +190,7 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
|
|
| 174 |
<Zap size={10} />
|
| 175 |
<span>Squeeze</span>
|
| 176 |
</span>
|
| 177 |
-
)}
|
| 178 |
<Badge variant="blue" size="sm">
|
| 179 |
{signal.active_timeframe}
|
| 180 |
</Badge>
|
|
@@ -198,6 +214,8 @@ Forward Anticipation: ${signal.anticipation || levels?.anticipation || ''}`;
|
|
| 198 |
? 'bg-signal-long/20 text-signal-long border border-signal-long/30'
|
| 199 |
: signal.direction === 'SHORT'
|
| 200 |
? 'bg-signal-short/20 text-signal-short border border-signal-short/30'
|
|
|
|
|
|
|
| 201 |
: 'bg-bg-elevated text-text-muted border border-border'
|
| 202 |
}`}
|
| 203 |
>
|
|
|
|
| 166 |
<span>Spot</span>
|
| 167 |
</span>
|
| 168 |
)}
|
| 169 |
+
{signal.breakout_radar?.is_breakout_primed ? (
|
| 170 |
+
<span
|
| 171 |
+
className={`px-1.5 py-0.5 rounded text-[10px] font-mono font-bold border flex items-center gap-1 ${
|
| 172 |
+
signal.breakout_radar.squeeze_stage === 'READY_TO_BURST'
|
| 173 |
+
? 'bg-purple-500/25 text-purple-300 border-purple-500/50 animate-pulse'
|
| 174 |
+
: 'bg-amber-500/20 text-amber-300 border-amber-500/40'
|
| 175 |
+
}`}
|
| 176 |
+
title={signal.breakout_radar.catalyst_summary}
|
| 177 |
+
>
|
| 178 |
+
<Zap size={10} className="text-yellow-400" />
|
| 179 |
+
<span>
|
| 180 |
+
{signal.breakout_radar.squeeze_stage === 'READY_TO_BURST'
|
| 181 |
+
? 'BURST PRIMED'
|
| 182 |
+
: 'COILING'}
|
| 183 |
+
</span>
|
| 184 |
+
</span>
|
| 185 |
+
) : isSqueeze ? (
|
| 186 |
<span
|
| 187 |
className="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-amber-500/20 text-amber-400 border border-amber-500/30 flex items-center gap-1 animate-pulse"
|
| 188 |
title="Volatility Squeeze (Breakout Imminent)"
|
|
|
|
| 190 |
<Zap size={10} />
|
| 191 |
<span>Squeeze</span>
|
| 192 |
</span>
|
| 193 |
+
) : null}
|
| 194 |
<Badge variant="blue" size="sm">
|
| 195 |
{signal.active_timeframe}
|
| 196 |
</Badge>
|
|
|
|
| 214 |
? 'bg-signal-long/20 text-signal-long border border-signal-long/30'
|
| 215 |
: signal.direction === 'SHORT'
|
| 216 |
? 'bg-signal-short/20 text-signal-short border border-signal-short/30'
|
| 217 |
+
: signal.breakout_radar?.is_breakout_primed
|
| 218 |
+
? 'bg-purple-500/25 text-purple-300 border border-purple-500/40 animate-pulse'
|
| 219 |
: 'bg-bg-elevated text-text-muted border border-border'
|
| 220 |
}`}
|
| 221 |
>
|
frontend/src/types/index.ts
CHANGED
|
@@ -127,6 +127,57 @@ export interface TradeLevels {
|
|
| 127 |
safety_label?: string;
|
| 128 |
}
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
export interface Signal {
|
| 131 |
symbol: string;
|
| 132 |
direction: Direction;
|
|
@@ -143,6 +194,11 @@ export interface Signal {
|
|
| 143 |
anticipation?: string;
|
| 144 |
predictive?: PredictiveData;
|
| 145 |
trade_levels?: TradeLevels | null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
active_timeframe: string;
|
| 147 |
market_condition: string;
|
| 148 |
signals: SignalDetails;
|
|
@@ -225,6 +281,7 @@ export interface AIAnalysisResponse {
|
|
| 225 |
taker_buy_pct?: number;
|
| 226 |
whale_buy_count?: number;
|
| 227 |
whale_sell_count?: number;
|
|
|
|
| 228 |
};
|
| 229 |
created_at: string;
|
| 230 |
}
|
|
|
|
| 127 |
safety_label?: string;
|
| 128 |
}
|
| 129 |
|
| 130 |
+
export interface BreakoutRadar {
|
| 131 |
+
is_breakout_primed: boolean;
|
| 132 |
+
radar_label: string;
|
| 133 |
+
squeeze_stage: 'NORMAL' | 'COILING' | 'ACCUMULATING' | 'READY_TO_BURST' | string;
|
| 134 |
+
projected_direction: 'BREAKOUT_UP' | 'BREAKOUT_DOWN' | 'COILING_NEUTRAL' | string;
|
| 135 |
+
compression_ratio: number;
|
| 136 |
+
catalyst_summary: string;
|
| 137 |
+
catalysts?: string[];
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
export interface LeadLagData {
|
| 141 |
+
max_spread_bps: number;
|
| 142 |
+
max_spread_usd: number;
|
| 143 |
+
leading_venue: string;
|
| 144 |
+
lagging_venue: string;
|
| 145 |
+
lead_lag_summary: string;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
export interface FundingSettlementData {
|
| 149 |
+
countdown_str: string;
|
| 150 |
+
is_settlement_imminent: boolean;
|
| 151 |
+
risk_label: string;
|
| 152 |
+
venues?: Record<string, { countdown_seconds: number; countdown_str: string; cycle: string }>;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
export interface PriceExtremesData {
|
| 156 |
+
high_24h: number;
|
| 157 |
+
low_24h: number;
|
| 158 |
+
range_usd: number;
|
| 159 |
+
range_pct: number;
|
| 160 |
+
dist_to_high_pct: number;
|
| 161 |
+
dist_to_low_pct: number;
|
| 162 |
+
range_position_pct: number;
|
| 163 |
+
zone_label: string;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
export interface WhaleFlowData {
|
| 167 |
+
taker_buy_vol_usd: number;
|
| 168 |
+
taker_sell_vol_usd: number;
|
| 169 |
+
total_vol_usd: number;
|
| 170 |
+
taker_buy_pct: number;
|
| 171 |
+
taker_ratio: number;
|
| 172 |
+
whale_buy_count: number;
|
| 173 |
+
whale_sell_count: number;
|
| 174 |
+
whale_buy_vol_usd: number;
|
| 175 |
+
whale_sell_vol_usd: number;
|
| 176 |
+
largest_trade_usd: number;
|
| 177 |
+
largest_trade_side: string;
|
| 178 |
+
flow_verdict: string;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
export interface Signal {
|
| 182 |
symbol: string;
|
| 183 |
direction: Direction;
|
|
|
|
| 194 |
anticipation?: string;
|
| 195 |
predictive?: PredictiveData;
|
| 196 |
trade_levels?: TradeLevels | null;
|
| 197 |
+
breakout_radar?: BreakoutRadar;
|
| 198 |
+
lead_lag?: LeadLagData;
|
| 199 |
+
funding_settlement?: FundingSettlementData;
|
| 200 |
+
price_extremes?: PriceExtremesData;
|
| 201 |
+
whale_flow?: WhaleFlowData;
|
| 202 |
active_timeframe: string;
|
| 203 |
market_condition: string;
|
| 204 |
signals: SignalDetails;
|
|
|
|
| 281 |
taker_buy_pct?: number;
|
| 282 |
whale_buy_count?: number;
|
| 283 |
whale_sell_count?: number;
|
| 284 |
+
breakout_radar?: BreakoutRadar;
|
| 285 |
};
|
| 286 |
created_at: string;
|
| 287 |
}
|
tests/test_calculations.py
CHANGED
|
@@ -313,6 +313,119 @@ def test_extended_quant_telemetry():
|
|
| 313 |
assert "ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD" in prompt_txt
|
| 314 |
assert data_summary["high_24h"] == 110.0
|
| 315 |
assert data_summary["whale_buy_count"] == 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
print(" PASSED!")
|
| 317 |
|
| 318 |
if __name__ == "__main__":
|
|
|
|
| 313 |
assert "ORDER FLOW INSTITUSIONAL, WHALE BLOCK TRADES & CVD" in prompt_txt
|
| 314 |
assert data_summary["high_24h"] == 110.0
|
| 315 |
assert data_summary["whale_buy_count"] == 2
|
| 316 |
+
assert "breakout_radar" in data_summary
|
| 317 |
+
print(" PASSED!")
|
| 318 |
+
|
| 319 |
+
def test_breakout_radar_and_bulk_fetcher():
|
| 320 |
+
print("[10] Testing Squeeze & Breakout Accumulation Radar (Tier 3) & Bulk Fetcher (Tier 1)...")
|
| 321 |
+
from engine.signal_engine import _compute_breakout_radar
|
| 322 |
+
from engine.bulk_fetcher import BulkMarketFetcher
|
| 323 |
+
|
| 324 |
+
# 1. Bulk Fetcher in-memory mock parsing
|
| 325 |
+
fetcher = BulkMarketFetcher()
|
| 326 |
+
fetcher._binance_premium = {
|
| 327 |
+
"BTCUSDT": {
|
| 328 |
+
"symbol": "BTCUSDT",
|
| 329 |
+
"markPrice": "67000.50",
|
| 330 |
+
"indexPrice": "67000.00",
|
| 331 |
+
"lastFundingRate": "0.0001",
|
| 332 |
+
"nextFundingTime": 1729872000000,
|
| 333 |
+
}
|
| 334 |
+
}
|
| 335 |
+
fetcher._binance_24h = {
|
| 336 |
+
"BTCUSDT": {
|
| 337 |
+
"symbol": "BTCUSDT",
|
| 338 |
+
"highPrice": "68500.00",
|
| 339 |
+
"lowPrice": "65200.00",
|
| 340 |
+
"volume": "15000.0",
|
| 341 |
+
"quoteVolume": "1000000000.0",
|
| 342 |
+
"priceChangePercent": "2.5",
|
| 343 |
+
}
|
| 344 |
+
}
|
| 345 |
+
fetcher._bybit_tickers = {
|
| 346 |
+
"BTCUSDT": {
|
| 347 |
+
"symbol": "BTCUSDT",
|
| 348 |
+
"markPrice": "67002.00",
|
| 349 |
+
"indexPrice": "67000.00",
|
| 350 |
+
"fundingRate": "0.00012",
|
| 351 |
+
"highPrice24h": "68520.00",
|
| 352 |
+
"lowPrice24h": "65180.00",
|
| 353 |
+
"openInterest": "45000.0",
|
| 354 |
+
"openInterestValue": "3015000000.0",
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
# Test Binance lookups
|
| 359 |
+
b_mp = fetcher.get_binance_mark_price("BTCUSDT")
|
| 360 |
+
assert b_mp is not None
|
| 361 |
+
assert b_mp["mark_price"] == 67000.50
|
| 362 |
+
b_fr = fetcher.get_binance_funding_rate("BTCUSDT")
|
| 363 |
+
assert b_fr is not None
|
| 364 |
+
assert b_fr["funding_rate"] == 0.0001
|
| 365 |
+
b_24 = fetcher.get_binance_24h("BTCUSDT")
|
| 366 |
+
assert b_24 is not None
|
| 367 |
+
assert b_24["high_24h"] == 68500.00
|
| 368 |
+
|
| 369 |
+
# Test Bybit lookups
|
| 370 |
+
by_mp = fetcher.get_bybit_mark_price("BTCUSDT")
|
| 371 |
+
assert by_mp is not None
|
| 372 |
+
assert by_mp["mark_price"] == 67002.00
|
| 373 |
+
by_oi = fetcher.get_bybit_24h_and_oi("BTCUSDT")
|
| 374 |
+
assert by_oi is not None
|
| 375 |
+
assert by_oi["open_interest"] == 45000.0
|
| 376 |
+
|
| 377 |
+
# 2. Breakout Radar: Primed Bullish Squeeze
|
| 378 |
+
pred_squeeze = {
|
| 379 |
+
"volatility_squeeze": {
|
| 380 |
+
"is_squeeze": True,
|
| 381 |
+
"compression_ratio": 0.48,
|
| 382 |
+
"squeeze_intensity": "EXTREME SQUEEZE",
|
| 383 |
+
},
|
| 384 |
+
"orderbook_skew": {
|
| 385 |
+
"skew_ratio": 0.35,
|
| 386 |
+
"resting_pressure": "STRONG BUY WALL",
|
| 387 |
+
},
|
| 388 |
+
"liquidation_magnets": {
|
| 389 |
+
"primary_magnet": "UPPER",
|
| 390 |
+
},
|
| 391 |
+
}
|
| 392 |
+
oi_signal = {"oi_change_pct": 3.2}
|
| 393 |
+
whale_flow = {
|
| 394 |
+
"taker_ratio": 1.45,
|
| 395 |
+
"whale_buy_vol_usd": 85000.0,
|
| 396 |
+
"whale_sell_vol_usd": 15000.0,
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
radar_bull = _compute_breakout_radar(
|
| 400 |
+
direction="NEUTRAL",
|
| 401 |
+
conviction=0,
|
| 402 |
+
predictive_data=pred_squeeze,
|
| 403 |
+
oi_signal=oi_signal,
|
| 404 |
+
whale_flow=whale_flow,
|
| 405 |
+
)
|
| 406 |
+
assert radar_bull["is_breakout_primed"] is True
|
| 407 |
+
assert radar_bull["squeeze_stage"] == "READY_TO_BURST"
|
| 408 |
+
assert radar_bull["projected_direction"] == "BREAKOUT_UP"
|
| 409 |
+
assert "BULLISH BIAS" in radar_bull["radar_label"]
|
| 410 |
+
assert radar_bull["compression_ratio"] == 0.48
|
| 411 |
+
|
| 412 |
+
# 3. Breakout Radar: Normal uncompressed market
|
| 413 |
+
pred_normal = {
|
| 414 |
+
"volatility_squeeze": {
|
| 415 |
+
"is_squeeze": False,
|
| 416 |
+
"compression_ratio": 1.15,
|
| 417 |
+
"squeeze_intensity": "NORMAL",
|
| 418 |
+
},
|
| 419 |
+
}
|
| 420 |
+
radar_normal = _compute_breakout_radar(
|
| 421 |
+
direction="LONG",
|
| 422 |
+
conviction=7,
|
| 423 |
+
predictive_data=pred_normal,
|
| 424 |
+
oi_signal={"oi_change_pct": 0.1},
|
| 425 |
+
whale_flow={"taker_ratio": 1.0, "whale_buy_vol_usd": 0.0, "whale_sell_vol_usd": 0.0},
|
| 426 |
+
)
|
| 427 |
+
assert radar_normal["is_breakout_primed"] is False
|
| 428 |
+
assert radar_normal["squeeze_stage"] == "NORMAL"
|
| 429 |
print(" PASSED!")
|
| 430 |
|
| 431 |
if __name__ == "__main__":
|