File size: 16,238 Bytes
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
712f4ea
 
 
 
 
48f60d7
 
712f4ea
 
 
 
 
 
 
 
 
 
48f60d7
 
 
712f4ea
 
6019628
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
6019628
712f4ea
 
 
6019628
 
 
 
712f4ea
 
 
48f60d7
 
 
712f4ea
 
80df99b
 
712f4ea
 
 
 
 
6019628
 
712f4ea
 
 
 
 
48f60d7
 
 
712f4ea
 
 
 
 
6019628
 
 
 
 
 
712f4ea
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
44d1f89
 
712f4ea
 
 
 
 
 
 
44d1f89
48f60d7
 
 
712f4ea
 
 
 
 
42ab2f3
712f4ea
c757254
712f4ea
 
 
740fcec
 
712f4ea
 
 
42ab2f3
712f4ea
 
42ab2f3
712f4ea
 
 
c224e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
740fcec
 
712f4ea
baefaf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
740fcec
 
712f4ea
 
 
42ab2f3
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
712f4ea
 
 
42ab2f3
712f4ea
 
 
 
 
 
 
 
 
48f60d7
712f4ea
48f60d7
 
 
 
712f4ea
 
 
 
 
 
 
 
48f60d7
712f4ea
48f60d7
 
712f4ea
48f60d7
 
712f4ea
 
 
 
 
 
 
 
 
72bd8f0
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
712f4ea
 
 
 
 
 
 
 
48f60d7
712f4ea
 
 
48f60d7
 
 
712f4ea
48f60d7
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
712f4ea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""
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"),
        }