Perps-Terminal / backend /engine /predictive_engine.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
16.2 kB
"""
Predictive & Forward-Looking Anticipation Engine
================================================
Anticipates future price movement and liquidity hunts rather than just
reflecting lagging historical indicators:
1. Liquidation Magnet Pools (Predicted Smart Money Sweep Targets)
- Identifies resting 25x-50x liquidation clusters above swing highs & below swing lows
- Determines the primary 'Magnetic Pull' direction
2. Order Book Depth Skew (Resting Intentions)
- Evaluates resting limit order pressure (Bids vs Asks within ±1.5% of mark price)
- Predicts near-term order flow resistance / support
3. Volatility Squeeze & Breakout Forecaster
- Measures ATR compression ratio to forecast imminent explosive expansion (1-4 hour horizon)
4. Forward Outlook Synthesis
- Combines the predictive factors into an actionable forward-looking verdict
"""
import logging
from typing import Any
logger = logging.getLogger(__name__)
def _compute_liquidation_magnets(
mark_price: float,
ohlcv_1h: list[dict],
ohlcv_4h: list[dict] | None = None,
hl_liq_clusters: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Computes estimated liquidation clusters and magnetic draw levels.
Short liquidations cluster above recent swing highs.
Long liquidations cluster below recent swing lows.
When Hyperliquid on-chain liquidation clusters are present, anchors directly
to real whale liquidation price concentrations.
"""
if not mark_price or mark_price <= 0:
return {
"upper_magnet": 0.0,
"lower_magnet": 0.0,
"upper_magnet_str": "N/A",
"lower_magnet_str": "N/A",
"dist_upper_pct": 0.0,
"dist_lower_pct": 0.0,
"primary_magnet": "NONE",
"method": "swing_liquidity_proxy",
"upper_magnet_notional_usd": 0.0,
"lower_magnet_notional_usd": 0.0,
}
def _fmt(p: float) -> str:
if p is None or p <= 0:
return "$0.00"
if p >= 1000:
return f"${p:,.2f}"
if p >= 1:
return f"${p:,.4f}"
if p >= 0.01:
return f"${p:.4f}"
if p >= 0.0001:
return f"${p:.6f}"
if p >= 0.000001:
return f"${p:.8f}"
s = f"{p:.10f}".rstrip("0")
return f"${s}"
candles = (ohlcv_1h[-36:] if ohlcv_1h else []) or (ohlcv_4h[-12:] if ohlcv_4h else [])
if not candles:
# Fallback to standard 2.5% distance
upper = mark_price * 1.025
lower = mark_price * 0.975
return {
"upper_magnet": round(upper, 8),
"lower_magnet": round(lower, 8),
"upper_magnet_str": _fmt(upper),
"lower_magnet_str": _fmt(lower),
"dist_upper_pct": 2.5,
"dist_lower_pct": -2.5,
"primary_magnet": "UPPER",
"method": "swing_liquidity_proxy",
"upper_magnet_notional_usd": 0.0,
"lower_magnet_notional_usd": 0.0,
}
recent_highs = [c["high"] for c in candles if (c.get("high") or 0) > 0]
recent_lows = [c["low"] for c in candles if (c.get("low") or 0) > 0]
if not recent_highs or not recent_lows:
upper = mark_price * 1.025
lower = mark_price * 0.975
return {
"upper_magnet": round(upper, 8),
"lower_magnet": round(lower, 8),
"upper_magnet_str": _fmt(upper),
"lower_magnet_str": _fmt(lower),
"dist_upper_pct": 2.5,
"dist_lower_pct": -2.5,
"primary_magnet": "UPPER",
"method": "swing_liquidity_proxy",
"upper_magnet_notional_usd": 0.0,
"lower_magnet_notional_usd": 0.0,
}
max_high = max(recent_highs)
min_low = min(recent_lows)
# 25x-50x leverage liquidation clusters sit beyond key swing points, clamped to realistic target horizons (max +8% / -8%)
raw_upper = max(mark_price * 1.008, max_high * 1.012)
raw_lower = min(mark_price * 0.992, min_low * 0.988)
upper_magnet = min(raw_upper, mark_price * 1.08)
lower_magnet = max(raw_lower, mark_price * 0.92)
upper_notional = 0.0
lower_notional = 0.0
is_onchain_map = False
# Check Hyperliquid real on-chain liquidation clusters
if hl_liq_clusters and isinstance(hl_liq_clusters, dict):
short_c = hl_liq_clusters.get("short_liq_clusters") or []
valid_short = [
c for c in short_c
if 0.4 <= float(c.get("distance_pct", 0.0)) <= 8.0
and float(c.get("notional_usd", 0.0)) >= 50_000.0
]
if valid_short:
best_short = max(valid_short, key=lambda x: float(x.get("notional_usd", 0.0)))
upper_magnet = float(best_short["price"])
upper_notional = float(best_short["notional_usd"])
is_onchain_map = True
long_c = hl_liq_clusters.get("long_liq_clusters") or []
valid_long = [
c for c in long_c
if -8.0 <= float(c.get("distance_pct", 0.0)) <= -0.4
and float(c.get("notional_usd", 0.0)) >= 50_000.0
]
if valid_long:
best_long = max(valid_long, key=lambda x: float(x.get("notional_usd", 0.0)))
lower_magnet = float(best_long["price"])
lower_notional = float(best_long["notional_usd"])
is_onchain_map = True
dist_upper_pct = ((upper_magnet - mark_price) / mark_price) * 100
dist_lower_pct = ((lower_magnet - mark_price) / mark_price) * 100
primary_magnet = "UPPER" if abs(dist_upper_pct) <= abs(dist_lower_pct) else "LOWER"
return {
"upper_magnet": round(upper_magnet, 8),
"lower_magnet": round(lower_magnet, 8),
"upper_magnet_str": _fmt(upper_magnet),
"lower_magnet_str": _fmt(lower_magnet),
"dist_upper_pct": round(dist_upper_pct, 2),
"dist_lower_pct": round(dist_lower_pct, 2),
"primary_magnet": primary_magnet,
"method": "hyperliquid_onchain_liq_map" if is_onchain_map else "swing_liquidity_proxy",
"upper_magnet_notional_usd": round(upper_notional, 2),
"lower_magnet_notional_usd": round(lower_notional, 2),
}
def _compute_orderbook_skew(orderbook: dict | None, mark_price: float) -> dict[str, Any]:
"""
Evaluates resting limit order depth skew within ±1.5% of mark price across consolidated exchanges.
"""
if not orderbook or not mark_price or mark_price <= 0:
return {
"bid_depth_usd": 0.0,
"ask_depth_usd": 0.0,
"tight_bid_depth_usd": 0.0,
"tight_ask_depth_usd": 0.0,
"skew_ratio": 0.0,
"resting_pressure": "BALANCED",
"score": 0,
"venues_count": 0,
}
venues_count = int(orderbook.get("venues_count", 1) or 1)
bids = orderbook.get("bids", [])
asks = orderbook.get("asks", [])
# Filter depth within ±1.5% of mark price with per-item resilience
bid_vol_usd = 0.0
for item in bids:
try:
p = float(item[0])
q = float(item[1])
if mark_price * 0.985 <= p <= mark_price * 1.005:
bid_vol_usd += p * q
except (ValueError, TypeError, IndexError):
continue
ask_vol_usd = 0.0
for item in asks:
try:
p = float(item[0])
q = float(item[1])
if mark_price * 0.995 <= p <= mark_price * 1.015:
ask_vol_usd += p * q
except (ValueError, TypeError, IndexError):
continue
tight_bid_vol_usd = bid_vol_usd
tight_ask_vol_usd = ask_vol_usd
total = bid_vol_usd + ask_vol_usd
# Fallback: if tight ±1.5% window produced zero depth (e.g. wide spread or volatile pair), relax to ±5.0%
if total <= 0 and (bids or asks):
for item in bids:
try:
p = float(item[0])
q = float(item[1])
if mark_price * 0.95 <= p <= mark_price * 1.02:
bid_vol_usd += p * q
except (ValueError, TypeError, IndexError):
continue
for item in asks:
try:
p = float(item[0])
q = float(item[1])
if mark_price * 0.98 <= p <= mark_price * 1.05:
ask_vol_usd += p * q
except (ValueError, TypeError, IndexError):
continue
total = bid_vol_usd + ask_vol_usd
if total <= 0:
return {
"bid_depth_usd": 0.0,
"ask_depth_usd": 0.0,
"tight_bid_depth_usd": 0.0,
"tight_ask_depth_usd": 0.0,
"skew_ratio": 0.0,
"resting_pressure": "BALANCED",
"score": 0,
"venues_count": venues_count,
}
# Skew from -1.0 (100% asks) to +1.0 (100% bids)
skew = (bid_vol_usd - ask_vol_usd) / total
if skew >= 0.25:
resting_pressure = "STRONG BUY WALL (Bids Dominating + Cushion)"
score = 1
elif skew <= -0.25:
resting_pressure = "STRONG SELL WALL (Asks Dominating + Resistance)"
score = -1
else:
resting_pressure = "BALANCED RESTING DEPTH"
score = 0
return {
"bid_depth_usd": round(bid_vol_usd, 2),
"ask_depth_usd": round(ask_vol_usd, 2),
"tight_bid_depth_usd": round(tight_bid_vol_usd, 2),
"tight_ask_depth_usd": round(tight_ask_vol_usd, 2),
"skew_ratio": round(skew, 3),
"resting_pressure": resting_pressure,
"score": score,
"venues_count": venues_count,
}
def _compute_volatility_squeeze(
ohlcv_15m: list[dict],
ohlcv_1d: list[dict] | None = None,
) -> dict[str, Any]:
"""
Measures volatility coiling (energy build-up) to forecast an impending explosive breakout.
Uses rolling ATR chunks across the trailing lookback window to detect compression vs baseline.
"""
from engine.mtf_analyzer import _atr, _valid_ohlc_candles
valid_bars = _valid_ohlc_candles(ohlcv_15m)[-100:]
if len(valid_bars) < 15:
return {
"is_squeeze": False,
"compression_ratio": 1.0,
"squeeze_intensity": "NORMAL",
"squeeze_score": 0,
"label": "Kondisi Volatilitas Rata-Rata",
}
current_atr = _atr(valid_bars, 14)
# Compute rolling baseline ATR across recent lookback candles
step = max(1, (len(valid_bars) - 15) // 10)
rolling_atrs = []
for i in range(0, len(valid_bars) - 15, step):
chunk = valid_bars[i:i + 15]
a = _atr(chunk, 14)
if a > 0:
rolling_atrs.append(a)
if not rolling_atrs:
baseline_atr = current_atr
else:
baseline_atr = sum(rolling_atrs) / len(rolling_atrs)
if baseline_atr <= 0 or current_atr <= 0:
return {
"is_squeeze": False,
"compression_ratio": 1.0,
"squeeze_intensity": "NORMAL",
"squeeze_score": 0,
"label": "Kondisi Volatilitas Rata-Rata",
}
ratio = current_atr / baseline_atr
if ratio < 0.55:
is_squeeze = True
intensity = "EXTREME SQUEEZE"
label = "🔥 Energi Terkompresi Ekstrem (Potensi Ledakan Breakout Kuat dlm 1-4 Jam)"
score = 2
elif ratio < 0.75:
is_squeeze = False
intensity = "MODERATE_COMPRESSION"
label = "⚡ Volatilitas Mengkerut (Mempersiapkan Ekspansi Trend)"
score = 1
elif ratio > 1.8:
is_squeeze = False
intensity = "HIGH EXPANSION"
label = "🌊 Volatilitas Meledak / Momentum Aktif"
score = 0
else:
is_squeeze = False
intensity = "NORMAL"
label = "Kondisi Volatilitas Rata-Rata"
score = 0
return {
"is_squeeze": is_squeeze,
"compression_ratio": round(ratio, 3),
"squeeze_intensity": intensity,
"squeeze_score": score,
"label": label,
}
class PredictiveEngine:
"""
Combines Liquidation Magnets, Order Book Depth Skew, and Volatility Squeeze
to anticipate future price trajectories before they unfold.
"""
def analyze(
self,
mark_price: float,
ohlcv: dict[str, list[dict]],
orderbook: dict | None,
direction: str,
conviction: int,
funding_rate: float | None = None,
hl_liq_clusters: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Synthesizes predictive forward-looking signals.
"""
magnets = _compute_liquidation_magnets(
mark_price=mark_price,
ohlcv_1h=ohlcv.get("1h", []),
ohlcv_4h=ohlcv.get("4h", []),
hl_liq_clusters=hl_liq_clusters,
)
ob_skew = _compute_orderbook_skew(orderbook, mark_price)
c_15m = ohlcv.get("15m") or []
c_1h = ohlcv.get("1h") or []
squeeze_bars = c_15m if len(c_15m) >= 15 else (c_1h if len(c_1h) >= 15 else (c_15m or c_1h))
squeeze = _compute_volatility_squeeze(
ohlcv_15m=squeeze_bars,
ohlcv_1d=ohlcv.get("1d", []),
)
# ── Determine Magnetic Draw & Forward Bias ─────────────────────────
# In crypto perps, smart money drives price towards the easiest liquidity cluster
if direction == "LONG":
target_magnet = magnets["upper_magnet_str"]
target_dist = magnets["dist_upper_pct"]
target_type = "Short Liquidation Hunt Pool"
if squeeze["is_squeeze"]:
anticipation = (
f"Antisipasi Breakout: Terjadi kompresi energi ekstrem. Proyeksi ekspansi bullish menuju "
f"kolam likuidasi Short di {target_magnet} (+{target_dist}%)."
)
else:
anticipation = (
f"Proyeksi Alur: Harga tertarik secara magnetis menyapu likuidasi Short di {target_magnet} (+{target_dist}%) "
f"dengan bantalan order beli di bawah."
)
elif direction == "SHORT":
target_magnet = magnets["lower_magnet_str"]
target_dist = abs(magnets["dist_lower_pct"])
target_type = "Long Liquidation Hunt Pool"
if squeeze["is_squeeze"]:
anticipation = (
f"Antisipasi Breakdown: Energi terkompresi siap meledak ke bawah. Proyeksi dump mengincar "
f"likuidasi Long retail di {target_magnet} (-{target_dist}%)."
)
else:
anticipation = (
f"Proyeksi Alur: Tekanan jual mendorong harga menyapu stop loss/likuidasi Long di {target_magnet} (-{target_dist}%)."
)
else: # NEUTRAL
target_magnet = (
magnets["upper_magnet_str"]
if ob_skew["skew_ratio"] >= 0
else magnets["lower_magnet_str"]
)
target_dist = (
magnets["dist_upper_pct"]
if ob_skew["skew_ratio"] >= 0
else abs(magnets["dist_lower_pct"])
)
target_type = "Range Boundary Liquidity"
if squeeze["is_squeeze"]:
anticipation = (
f"Antisipasi Squeeze: Pasar sedang 'coiling' kencang. Tunggu arah breakout menyapu antara "
f"{magnets['lower_magnet_str']} atau {magnets['upper_magnet_str']}."
)
else:
anticipation = (
f"Antisipasi Konsolidasi: Harga masih terjebak di antara dua magnet likuidasi "
f"({magnets['lower_magnet_str']} - {magnets['upper_magnet_str']}). Jangan terburu-buru entry."
)
return {
"liquidation_magnets": magnets,
"orderbook_skew": ob_skew,
"volatility_squeeze": squeeze,
"predicted_target": target_magnet,
"target_type": target_type,
"target_dist_pct": target_dist,
"anticipation": anticipation,
"method": magnets.get("method", "swing_liquidity_proxy"),
}