""" SignalEngine – orchestrates all signal computations for one symbol. Flow: raw_data (from DataCollector) → individual factor computations → FakeDetector → MTFAnalyzer → ConfluenceScorer → final signal dict """ import logging import math import time from datetime import datetime, timezone from typing import Any from engine.mtf_analyzer import MTFAnalyzer, _atr, _valid_ohlc_candles from engine.fake_detector import FakeDetector from engine.confluence_scorer import ConfluenceScorer from engine.predictive_engine import PredictiveEngine, _compute_orderbook_skew from engine.bulk_fetcher import bulk_fetcher from engine.l2_microstructure import L2OrderbookTracker, get_l2_tracker from engine.hl_whale_tracker import HyperliquidWhaleTracker, get_hl_whale_tracker logger = logging.getLogger(__name__) mtf_analyzer = MTFAnalyzer() fake_detector = FakeDetector() confluence_scorer = ConfluenceScorer() predictive_engine = PredictiveEngine() # ───────────────────────────────────────────────────────────────────────────── # Quantitative Normalization & Weighting Helpers # ───────────────────────────────────────────────────────────────────────────── def _extract_venue_oi_weight(exch: dict | None, is_hl: bool = False) -> float: """ Extract USD notional Open Interest weight for a venue to compute Open-Interest-Weighted cross-exchange consensus metrics. """ if not exch or not isinstance(exch, dict): return 0.0 if is_hl: try: raw_oi = float(exch.get("open_interest") or 0.0) mark_px = float(exch.get("mark_price") or 0.0) if raw_oi > 0: return raw_oi * mark_px if mark_px > 0 else raw_oi except (ValueError, TypeError): pass return 0.0 oi_data = exch.get("open_interest_data") or {} mp_data = exch.get("mark_price_data") or {} try: mark_px = float(mp_data.get("mark_price") or 0.0) except (ValueError, TypeError): mark_px = 0.0 try: oi_val = oi_data.get("open_interest_value") if oi_val is not None and float(oi_val) > 0: return float(oi_val) except (ValueError, TypeError): pass try: raw_oi = oi_data.get("open_interest") if raw_oi is not None and float(raw_oi) > 0: return float(raw_oi) * mark_px if mark_px > 0 else float(raw_oi) except (ValueError, TypeError): pass return 0.0 def _oi_weighted_average(values: list[float], weights: list[float]) -> float: """ Compute Open-Interest-Weighted Average across venues. Falls back to arithmetic mean when OI weights are unavailable. """ if not values: return 0.0 if len(values) == 1 or len(values) != len(weights): return sum(values) / len(values) pos_weights = [w for w in weights if w > 0] if len(pos_weights) == len(values): total_w = sum(weights) if total_w > 0: return sum(v * w for v, w in zip(values, weights)) / total_w if len(pos_weights) >= 2: # Assign conservative fallback weight (25% of mean positive OI) to venues missing OI snapshot fallback_w = 0.25 * (sum(pos_weights) / len(pos_weights)) adj_weights = [w if w > 0 else fallback_w for w in weights] total_w = sum(adj_weights) if total_w > 0: return sum(v * w for v, w in zip(values, adj_weights)) / total_w return sum(values) / len(values) def _get_multiplier_scale(venue_px: float | None, ref_px: float | None) -> float: """ Detect and normalize power-of-10 contract multiplier discrepancies across exchanges (e.g. 1000PEPEUSDT @ $0.01 on Binance/Bybit vs PEPE-USDT-SWAP @ $0.00001 on OKX/Bitget). Returns the price scaling factor 10^k (or 1.0 if prices are already on the same scale). """ if not venue_px or not ref_px or venue_px <= 0 or ref_px <= 0: return 1.0 try: log_ratio = math.log10(float(ref_px) / float(venue_px)) k = round(log_ratio) if 2 <= abs(k) <= 9 and abs(log_ratio - k) < 0.15: return float(10.0 ** k) except (ValueError, TypeError, ZeroDivisionError): pass return 1.0 def _normalize_orderbook_scale(ob: dict | None, scale: float) -> dict | None: """ Scale orderbook prices by `scale` and quantities by `1 / scale` so USD notional (price * qty) is strictly invariant while price levels align with canonical mark_price. """ if not ob or not isinstance(ob, dict) or scale == 1.0 or scale <= 0: return ob inv_scale = 1.0 / scale norm_bids = [] for item in ob.get("bids", []): try: norm_bids.append([float(item[0]) * scale, float(item[1]) * inv_scale]) except (ValueError, TypeError, IndexError): continue norm_asks = [] for item in ob.get("asks", []): try: norm_asks.append([float(item[0]) * scale, float(item[1]) * inv_scale]) except (ValueError, TypeError, IndexError): continue return {"bids": norm_bids, "asks": norm_asks} def _normalize_trades_scale(trades: list[dict], scale: float) -> list[dict]: """ Scale trade prices by `scale` and quantities by `1 / scale` so base-coin CVD and USD block trade volumes remain commensurate across 1000x vs 1x contracts. """ if not trades or scale == 1.0 or scale <= 0: return trades inv_scale = 1.0 / scale normalized = [] for t in trades: try: nt = dict(t) if "price" in nt and nt["price"] is not None: nt["price"] = float(nt["price"]) * scale if "qty" in nt and nt["qty"] is not None: nt["qty"] = float(nt["qty"]) * inv_scale normalized.append(nt) except (ValueError, TypeError): continue return normalized def _normalize_candles_scale(candles: list[dict], scale: float) -> list[dict]: """ Scale OHLCV prices by `scale` and base volumes / taker_buy_volume by `1 / scale` so cross-exchange candle fallback keeps 1000x vs 1x price and USD notional aligned. """ if not candles or scale == 1.0 or scale <= 0: return candles inv_scale = 1.0 / scale normalized: list[dict] = [] for c in candles: if not isinstance(c, dict): continue nc = dict(c) for px_k in ("open", "high", "low", "close"): if nc.get(px_k) is not None: try: nc[px_k] = float(nc[px_k]) * scale except (ValueError, TypeError): pass for vol_k in ("volume", "taker_buy_volume"): if nc.get(vol_k) is not None: try: nc[vol_k] = float(nc[vol_k]) * inv_scale except (ValueError, TypeError): pass normalized.append(nc) return normalized def _normalize_liquidations_scale(liquidations: list[dict], scale: float) -> list[dict]: """ Scale liquidation prices by `scale` and quantities by `1 / scale` so USD notional (price * qty) is strictly invariant across 1000x vs 1x contracts. """ if not liquidations or scale == 1.0 or scale <= 0: return liquidations inv_scale = 1.0 / scale normalized = [] for liq in liquidations: try: n_liq = dict(liq) if "price" in n_liq and n_liq["price"] is not None: n_liq["price"] = float(n_liq["price"]) * scale if "qty" in n_liq and n_liq["qty"] is not None: n_liq["qty"] = float(n_liq["qty"]) * inv_scale normalized.append(n_liq) except (ValueError, TypeError): continue return normalized def _split_trades_by_midpoint(trades: list[dict]) -> tuple[list[dict], list[dict]]: """Split chronologically sorted trades into past/recent halves using timestamp midpoint.""" if len(trades) < 2: return [], trades times = [float(t.get("time", 0) or 0) for t in trades] if times[-1] > times[0] > 0: mid_t = (times[0] + times[-1]) / 2.0 first = [t for t in trades if float(t.get("time", 0) or 0) <= mid_t] second = [t for t in trades if float(t.get("time", 0) or 0) > mid_t] if first and second: return first, second mid = len(trades) // 2 return trades[:mid], trades[mid:] def _is_half_rising(sorted_trades: list[dict], total_cvd: float) -> bool: """Return True when cumulative CVD is rising in the second half of the window.""" first, second = _split_trades_by_midpoint(sorted_trades) if not first or not second: return total_cvd > 0 h2_buy = sum(float(t.get("qty") or 0.0) for t in second if not t.get("is_buyer_maker", False)) h2_sell = sum(float(t.get("qty") or 0.0) for t in second if t.get("is_buyer_maker", False)) h2_cvd = h2_buy - h2_sell return h2_cvd > 0 def _align_multi_venue_trades(trades: list[dict]) -> tuple[dict[str, list[dict]], str]: """ Partition trades by venue and time-align dense multi-venue feeds: - Mode 'single': < 2 distinct venue keys or < 2 dense timestamped venues (len >= 5, time > 0). - Mode 'overlap': >= 2 dense venues share an overlap window >= 5,000ms with >= 5 trades each. - Mode 'per_venue': multi-venue without sufficient shared overlap window. """ if not trades: return {}, "single" venue_trades: dict[str, list[dict]] = {} for t in trades: v = t.get("venue") if v: venue_trades.setdefault(str(v), []).append(t) if len(venue_trades) < 2: return {}, "single" # Dense timestamped venues: len >= 5 with time > 0 dense_venues: dict[str, list[dict]] = {} venue_min_t: dict[str, float] = {} venue_max_t: dict[str, float] = {} for v, trs in venue_trades.items(): valid_t = [float(t.get("time") or 0) for t in trs if float(t.get("time") or 0) > 0] if len(valid_t) >= 5: dense_venues[v] = sorted(trs, key=lambda t: float(t.get("time") or 0)) venue_min_t[v] = min(valid_t) venue_max_t[v] = max(valid_t) if len(dense_venues) < 2: return {}, "single" overlap_start = max(venue_min_t.values()) global_max_t = max(venue_max_t.values()) if (global_max_t - overlap_start) >= 5_000: aligned: dict[str, list[dict]] = {} for v, trs in dense_venues.items(): in_window = [t for t in trs if overlap_start <= float(t.get("time") or 0) <= global_max_t] if in_window: aligned[v] = in_window qualifying = [v for v, trs in aligned.items() if len(trs) >= 5] if len(qualifying) >= 2: return {v: aligned[v] for v in qualifying}, "overlap" # Fallback to per-venue slices return {v: sorted(trs, key=lambda t: float(t.get("time") or 0)) for v, trs in venue_trades.items()}, "per_venue" # ───────────────────────────────────────────────────────────────────────────── # Individual signal computers # ───────────────────────────────────────────────────────────────────────────── def _compute_funding_rate( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, hl_data: dict | None = None, bitget_data: dict | None = None, ) -> dict[str, Any]: """ Contrarian funding-rate signal with OI-Weighted Multi-Exchange Triangulation (Binance + Bybit + OKX + Bitget + Hyperliquid DEX). """ rates: list[float] = [] weights: list[float] = [] venues: list[str] = [] if binance_data and binance_data.get("funding_rate_data"): fr = binance_data["funding_rate_data"].get("funding_rate") if fr is not None: rates.append(float(fr)) weights.append(_extract_venue_oi_weight(binance_data)) venues.append("Binance") if bybit_data and bybit_data.get("funding_rate_data"): fr = bybit_data["funding_rate_data"].get("funding_rate") if fr is not None: rates.append(float(fr)) weights.append(_extract_venue_oi_weight(bybit_data)) venues.append("Bybit") if okx_data and okx_data.get("funding_rate_data"): fr = okx_data["funding_rate_data"].get("funding_rate") if fr is not None: rates.append(float(fr)) weights.append(_extract_venue_oi_weight(okx_data)) venues.append("OKX") if bitget_data and bitget_data.get("funding_rate_data"): fr = bitget_data["funding_rate_data"].get("funding_rate") if fr is not None: rates.append(float(fr)) weights.append(_extract_venue_oi_weight(bitget_data)) venues.append("Bitget") if hl_data and hl_data.get("funding_rate") is not None: rates.append(float(hl_data["funding_rate"])) weights.append(_extract_venue_oi_weight(hl_data, is_hl=True)) venues.append("Hyperliquid") if not rates: return {"value": None, "score": 0, "label": "No Data"} avg_fr = _oi_weighted_average(rates, weights) fr_pct = avg_fr * 100 # percentage per 8h venues_str = "+".join(venues) if fr_pct > 0.05: score, label = -2, f"Extreme Long Funding ({venues_str}) → Strong Short Bias" elif fr_pct > 0.02: score, label = -1, f"Elevated Long Funding ({venues_str}) → Short Bias" elif fr_pct < -0.05: score, label = 2, f"Extreme Short Funding ({venues_str}) → Strong Long Bias" elif fr_pct < -0.015: score, label = 1, f"Discount/Bearish Funding ({venues_str}) → Long Bias" else: score, label = 0, f"Neutral / Baseline Funding ({venues_str})" return { "value": round(avg_fr, 6), "value_pct": round(fr_pct, 6), "score": score, "label": label, "venues_count": len(rates), } def _score_spot_futures_pair( spot_trades: list[dict], futures_trades: list[dict], ref_mark_px: float | None = None, ) -> dict[str, Any]: """ Evaluate scale-normalized, time-aligned Spot vs Futures trades for a single venue pair. Returns: spot_cvd, fut_cvd, spot_ratio, fut_ratio, spot_rising, fut_rising, spot_usd, fut_usd """ def _sample_trade_px(trade_list: list[dict]) -> float | None: for tr in trade_list: try: p = float(tr.get("price") or 0.0) if p > 0: return p except (TypeError, ValueError): continue return None spot_px = _sample_trade_px(spot_trades) fut_px = _sample_trade_px(futures_trades) target_px = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else fut_px s_trades = list(spot_trades) f_trades = list(futures_trades) if s_trades and target_px: spot_scale = _get_multiplier_scale(spot_px, target_px) s_trades = _normalize_trades_scale(s_trades, spot_scale) if f_trades and target_px: fut_scale = _get_multiplier_scale(fut_px, target_px) f_trades = _normalize_trades_scale(f_trades, fut_scale) # Sort trades chronologically and intersect overlapping Spot/Futures time window when populated sorted_spot = sorted(s_trades, key=lambda t: float(t.get("time") or 0)) sorted_fut = sorted(f_trades, key=lambda t: float(t.get("time") or 0)) spot_times = [float(t.get("time") or 0) for t in sorted_spot if float(t.get("time") or 0) > 0] fut_times = [float(t.get("time") or 0) for t in sorted_fut if float(t.get("time") or 0) > 0] if spot_times and fut_times: overlap_start = max(spot_times[0], fut_times[0]) overlap_end = min(spot_times[-1], fut_times[-1]) if overlap_start < overlap_end: aligned_spot = [t for t in sorted_spot if overlap_start <= float(t.get("time") or 0) <= overlap_end] aligned_fut = [t for t in sorted_fut if overlap_start <= float(t.get("time") or 0) <= overlap_end] if len(aligned_spot) >= 5 and len(aligned_fut) >= 5: sorted_spot = aligned_spot sorted_fut = aligned_fut spot_buy = sum(float(t.get("qty") or 0.0) for t in sorted_spot if not t.get("is_buyer_maker", False)) spot_sell = sum(float(t.get("qty") or 0.0) for t in sorted_spot if t.get("is_buyer_maker", False)) spot_total = spot_buy + spot_sell spot_cvd = spot_buy - spot_sell spot_ratio = (spot_cvd / spot_total) if spot_total > 0 else 0.0 fut_buy = sum(float(t.get("qty") or 0.0) for t in sorted_fut if not t.get("is_buyer_maker", False)) fut_sell = sum(float(t.get("qty") or 0.0) for t in sorted_fut if t.get("is_buyer_maker", False)) fut_total = fut_buy + fut_sell futures_cvd = fut_buy - fut_sell fut_ratio = (futures_cvd / fut_total) if fut_total > 0 else 0.0 spot_rising = _is_half_rising(sorted_spot, spot_cvd) fut_rising = _is_half_rising(sorted_fut, futures_cvd) spot_usd = sum( float(t.get("qty") or 0.0) * (float(t.get("price") or 0.0) or target_px or 1.0) for t in sorted_spot ) fut_usd = sum( float(t.get("qty") or 0.0) * (float(t.get("price") or 0.0) or target_px or 1.0) for t in sorted_fut ) return { "spot_cvd": spot_cvd, "futures_cvd": futures_cvd, "spot_ratio": spot_ratio, "futures_ratio": fut_ratio, "spot_rising": spot_rising, "futures_rising": fut_rising, "spot_usd": spot_usd, "fut_usd": fut_usd, } def _compute_spot_futures_cvd( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, bitget_data: dict | None = None, ref_mark_px: float | None = None, ) -> dict[str, Any]: """ Spot vs Futures CVD Divergence across up to 4 exchanges (Binance, Bybit, OKX, Bitget). Pairs same-venue (spot_trades, trades), applies multiplier scale normalization & time alignment, aggregates USD-notional weighted ratios/momentum, and falls back to cross-venue pairing when no same-venue pairs exist. """ venues_input = [ ("binance", binance_data), ("bybit", bybit_data), ("okx", okx_data), ("bitget", bitget_data), ] # Resolve a canonical price reference up front so both same-venue and cross-venue paths # normalize multiplier contracts (e.g. 1000PEPE vs PEPE) consistently before summing CVDs. canon_ref = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else None if not canon_ref: for _, v_data in venues_input: if v_data and v_data.get("mark_price_data") and (v_data["mark_price_data"].get("mark_price") or 0) > 0: canon_ref = float(v_data["mark_price_data"]["mark_price"]) break if not canon_ref: for _, v_data in venues_input: for tr in ((v_data or {}).get("trades") or []) + ((v_data or {}).get("spot_trades") or []): try: p = float(tr.get("price") or 0.0) if p > 0: canon_ref = p break except (TypeError, ValueError): continue if canon_ref: break # 1. Identify same-venue pairs (where both spot_trades and trades exist) same_venue_pairs: list[tuple[str, dict]] = [] for v_name, v_data in venues_input: if v_data and v_data.get("spot_trades") and v_data.get("trades"): pair_res = _score_spot_futures_pair( v_data["spot_trades"], v_data["trades"], ref_mark_px=canon_ref, ) same_venue_pairs.append((v_name, pair_res)) if same_venue_pairs: spot_venues = [v_name for v_name, _ in same_venue_pairs] venues_count = len(spot_venues) total_spot_usd = sum(p["spot_usd"] for _, p in same_venue_pairs) total_fut_usd = sum(p["fut_usd"] for _, p in same_venue_pairs) if total_spot_usd > 0: spot_ratio = sum(p["spot_ratio"] * p["spot_usd"] for _, p in same_venue_pairs) / total_spot_usd spot_rising = (sum((1.0 if p["spot_rising"] else 0.0) * p["spot_usd"] for _, p in same_venue_pairs) / total_spot_usd) > 0.5 else: spot_ratio = sum(p["spot_ratio"] for _, p in same_venue_pairs) / venues_count spot_rising = any(p["spot_rising"] for _, p in same_venue_pairs) if total_fut_usd > 0: fut_ratio = sum(p["futures_ratio"] * p["fut_usd"] for _, p in same_venue_pairs) / total_fut_usd fut_rising = (sum((1.0 if p["futures_rising"] else 0.0) * p["fut_usd"] for _, p in same_venue_pairs) / total_fut_usd) > 0.5 else: fut_ratio = sum(p["futures_ratio"] for _, p in same_venue_pairs) / venues_count fut_rising = any(p["futures_rising"] for _, p in same_venue_pairs) spot_cvd = sum(p["spot_cvd"] for _, p in same_venue_pairs) futures_cvd = sum(p["futures_cvd"] for _, p in same_venue_pairs) else: # Cross-venue fallback: normalize each venue to common price scale before combining all_spot_trades: list[dict] = [] all_fut_trades: list[dict] = [] spot_venues = [] fallback_ref = ref_mark_px if (ref_mark_px and ref_mark_px > 0) else None if not fallback_ref: for _, v_data in venues_input: if v_data and v_data.get("mark_price_data") and (v_data["mark_price_data"].get("mark_price") or 0) > 0: fallback_ref = float(v_data["mark_price_data"]["mark_price"]) break if not fallback_ref: for _, v_data in venues_input: for tr in ((v_data or {}).get("trades") or []) + ((v_data or {}).get("spot_trades") or []): if (tr.get("price") or 0) > 0: fallback_ref = float(tr["price"]) break if fallback_ref: break def _first_px(trs: list[dict]) -> float | None: for tr in trs: try: p = float(tr.get("price") or 0.0) if p > 0: return p except (TypeError, ValueError): continue return None for v_name, v_data in venues_input: if v_data and v_data.get("spot_trades"): s_list = v_data["spot_trades"] if fallback_ref: s_scale = _get_multiplier_scale(_first_px(s_list), fallback_ref) s_list = _normalize_trades_scale(s_list, s_scale) all_spot_trades.extend(s_list) spot_venues.append(v_name) if v_data and v_data.get("trades"): f_list = v_data["trades"] if fallback_ref: f_scale = _get_multiplier_scale(_first_px(f_list), fallback_ref) f_list = _normalize_trades_scale(f_list, f_scale) all_fut_trades.extend(f_list) if not all_fut_trades and not all_spot_trades: return { "value": "No Data", "score": 0, "label": "Trade Data Unavailable", "spot_cvd": None, "futures_cvd": None, "venues_count": 0, "spot_venues": [], } if not all_spot_trades: fut_buy = sum(float(t.get("qty") or 0.0) for t in all_fut_trades if not t.get("is_buyer_maker", False)) fut_sell = sum(float(t.get("qty") or 0.0) for t in all_fut_trades if t.get("is_buyer_maker", False)) futures_cvd = fut_buy - fut_sell return { "value": f"Perp: {futures_cvd:+.1f} (No Spot)", "score": 0, "label": "Perpetual Only (Spot Market Not Listed)", "spot_cvd": None, "futures_cvd": round(futures_cvd, 2), "venues_count": 0, "spot_venues": [], } # Both spot and futures exist across venues fb_pair = _score_spot_futures_pair(all_spot_trades, all_fut_trades, ref_mark_px=ref_mark_px) spot_cvd = fb_pair["spot_cvd"] futures_cvd = fb_pair["futures_cvd"] spot_ratio = fb_pair["spot_ratio"] fut_ratio = fb_pair["futures_ratio"] spot_rising = fb_pair["spot_rising"] fut_rising = fb_pair["futures_rising"] venues_count = len(spot_venues) DEADBAND = 0.02 spot_bull = spot_ratio >= DEADBAND and spot_rising spot_bear = spot_ratio <= -DEADBAND and not spot_rising fut_bull = fut_ratio >= DEADBAND and fut_rising fut_bear = fut_ratio <= -DEADBAND and not fut_rising val_str = f"Spot: {spot_cvd:+.1f} | Fut: {futures_cvd:+.1f}" if spot_bull and fut_bull: score = 2 label = "Organic Spot+Futures Inflow (Institutional Accumulation)" elif fut_bull and (spot_ratio <= -DEADBAND or not spot_rising): score = -2 label = "⚠️ Leverage Trap! Futures Buying without Spot Support" elif spot_bear and fut_bear: score = -2 label = "Organic Institutional Selling (Spot+Futures Outflow)" elif spot_bull and (fut_ratio <= -DEADBAND or not fut_rising): score = 2 label = "🚀 Spot Absorption / Short Squeeze Fuel (Whales Buying Spot)" elif spot_ratio >= DEADBAND: score = 1 label = "Mild Spot Inflow (Spot Buying Lead)" elif spot_ratio <= -DEADBAND: score = -1 label = "Mild Spot Outflow (Spot Selling Lead)" else: score = 0 label = "Balanced Spot vs Futures Flow" return { "value": val_str, "spot_cvd": round(spot_cvd, 2), "futures_cvd": round(futures_cvd, 2), "spot_delta_ratio": round(spot_ratio, 4), "futures_delta_ratio": round(fut_ratio, 4), "score": score, "label": label, "venues_count": venues_count, "spot_venues": spot_venues, } def _compute_hyperliquid_signal( hl_data: dict | None, cex_funding_rate: float | None = None, cex_basis_pct: float | None = None, ) -> dict[str, Any]: """ Hyperliquid On-Chain DEX Alpha Signal (Institutional Alpha Edge #2). When CEX consensus is supplied, scores only the incremental DEX-vs-CEX spread in [-1, +1] so funding/basis aren't double-counted with CEX signals. """ if not hl_data: return { "value": "N/A", "score": 0, "label": "Not Listed on Hyperliquid DEX", "funding_rate": None, "open_interest": None, } fr = float(hl_data.get("funding_rate") or 0.0) basis_pct = float(hl_data.get("basis_pct") or 0.0) oi = float(hl_data.get("open_interest") or 0.0) mark_px = float(hl_data.get("mark_price") or 0.0) oi_usd = oi * mark_px if mark_px else oi score = 0 reasons = [] fr_pct = fr * 100.0 if cex_funding_rate is not None or cex_basis_pct is not None: fr_spread_pct = (fr - (cex_funding_rate if cex_funding_rate is not None else fr)) * 100.0 basis_spread = basis_pct - (cex_basis_pct if cex_basis_pct is not None else basis_pct) if fr_spread_pct < -0.02: score = 1 reasons.append(f"DEX FR Discount vs CEX ({fr_spread_pct:+.3f}%)") elif fr_spread_pct > 0.02: score = -1 reasons.append(f"DEX FR Crowding vs CEX ({fr_spread_pct:+.3f}%)") elif basis_spread < -0.15: score = 1 reasons.append(f"DEX Basis Discount vs CEX ({basis_spread:+.3f}%)") elif basis_spread > 0.15: score = -1 reasons.append(f"DEX Basis Premium vs CEX ({basis_spread:+.3f}%)") if score > 0: label = f"Hyperliquid DEX Bullish Spread: {', '.join(reasons)}" elif score < 0: label = f"Hyperliquid DEX Bearish Spread: {', '.join(reasons)}" else: label = "Hyperliquid Aligned with CEX Consensus" else: # Standalone DEX scoring when CEX consensus is absent if fr_pct < -0.01: score += 1 reasons.append(f"DEX Shorts Paying Longs ({fr_pct:+.3f}%)") elif fr_pct > 0.02: score -= 1 reasons.append(f"DEX Overleveraged Longs ({fr_pct:+.3f}%)") if basis_pct < -0.10: score += 1 reasons.append("DEX Mark Discount to Oracle") elif basis_pct > 0.10: score -= 1 reasons.append("DEX Mark Premium to Oracle") score = max(-2, min(2, score)) if score > 0: label = f"Hyperliquid Bullish Inflow: {', '.join(reasons)}" elif score < 0: label = f"Hyperliquid Bearish / Hedging: {', '.join(reasons)}" else: label = "Hyperliquid DEX Equilibrium" val_str = f"FR: {fr_pct:+.4f}% | Basis: {basis_pct:+.3f}%" return { "value": val_str, "funding_rate": fr, "basis_pct": basis_pct, "open_interest": oi, "oi_usd": round(oi_usd, 2), "score": score, "label": label, } def _candle_shows_exhaustion(candles: list[dict], side: str) -> bool: """ Confirm exhaustion/absorption on >= 3 full OHLC bars before fading an OI unwind move. Returns True for short (< 3 bar) or close-only unit mocks for backward compatibility. """ full_bars = [ c for c in (candles or []) if isinstance(c, dict) and c.get("open") is not None and c.get("high") is not None and c.get("low") is not None and c.get("close") is not None ] if len(full_bars) < 3: return True last = full_bars[-1] prev = full_bars[-2] o = float(last["open"]) h = float(last["high"]) l_val = float(last["low"]) c = float(last["close"]) prev_c = float(prev["close"]) rng = h - l_val if rng <= 0.0: return True close_pos = (c - l_val) / rng if side == "top": upper_wick = h - max(o, c) return (close_pos <= 0.60) or (upper_wick >= 0.25 * rng) or (c < prev_c) or (c < o) if side == "bottom": lower_wick = min(o, c) - l_val return (close_pos >= 0.40) or (lower_wick >= 0.25 * rng) or (c > prev_c) or (c > o) return True def _compute_oi_divergence( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, bitget_data: dict | None = None, hl_data: dict | None = None, ) -> dict[str, Any]: """ Open Interest + Price divergence signal (OI-Weighted across Binance, Bybit, OKX, Bitget, and Hyperliquid). Computes both 15m/1h Intraday divergence and 4h Swing divergence with ATR-normalized thresholds and separation of 15m historical series from rolling snapshots. 1. Price↑ + OI↑ (>+0.25%) → Real Long Inflow (+1 / +2) 2. Price↑ + OI↓ (<-0.25%) → Short Covering Exhaustion / Weak Rally (-1) 3. Price↓ + OI↑ (>+0.25%) → Real Short Inflow (-1 / -2) 4. Price↓ + OI↓ (<-0.25%) → Long Liquidation / Squeeze Exhaustion Done (+1) 5. Flat / Small changes → Neutral (0) """ venue_items: list[tuple[dict | None, bool]] = [ (binance_data, False), (bybit_data, False), (okx_data, False), (bitget_data, False), (hl_data, True), ] # Compute 15m ATR on longest valid sequence (>= 15 bars) longest_15m: list[dict] = [] for exch, _ in venue_items: if not exch or not isinstance(exch, dict): continue candles = (exch.get("ohlcv") or {}).get("15m") or [] valid = _valid_ohlc_candles(candles) if len(valid) > len(longest_15m): longest_15m = valid if len(longest_15m) >= 15: atr_15m = _atr(longest_15m, period=14) c15_close = float(longest_15m[-1].get("close") or 0.0) if c15_close > 0 and atr_15m > 0: atr_15m_pct = (atr_15m / c15_close) * 100.0 price_threshold = min(0.60, max(0.10, 0.30 * atr_15m_pct)) else: price_threshold = 0.15 else: price_threshold = 0.15 # Compute 4h ATR on longest valid sequence (>= 15 bars) longest_4h: list[dict] = [] for exch, _ in venue_items: if not exch or not isinstance(exch, dict): continue candles = (exch.get("ohlcv") or {}).get("4h") or [] valid = _valid_ohlc_candles(candles) if len(valid) > len(longest_4h): longest_4h = valid if len(longest_4h) >= 15: atr_4h = _atr(longest_4h, period=14) c4h_close = float(longest_4h[-1].get("close") or 0.0) if c4h_close > 0 and atr_4h > 0: atr_4h_pct = (atr_4h / c4h_close) * 100.0 swing_price_threshold = min(1.50, max(0.30, 0.30 * atr_4h_pct)) else: swing_price_threshold = 0.40 else: swing_price_threshold = 0.40 price_changes: list[float] = [] price_weights: list[float] = [] price_4h_changes: list[float] = [] price_4h_weights: list[float] = [] hist_15m_oi_changes: list[float] = [] hist_15m_oi_weights: list[float] = [] rolling_oi_changes: list[tuple[float, float, float | None]] = [] oi_1h_changes: list[float] = [] oi_1h_weights: list[float] = [] oi_4h_changes: list[float] = [] oi_4h_weights: list[float] = [] for exch, is_hl in venue_items: if not exch or not isinstance(exch, dict): continue w = _extract_venue_oi_weight(exch, is_hl=is_hl) ohlcv = exch.get("ohlcv", {}) or {} # 15m candle price change % candles = ohlcv.get("15m", []) if len(candles) >= 2 and (candles[-2].get("close") or 0) > 0 and candles[-1].get("close") is not None: prev_c = float(candles[-2]["close"]) curr_c = float(candles[-1]["close"]) pc = (curr_c - prev_c) / prev_c * 100 price_changes.append(pc) price_weights.append(w) # 4h candle price change % (or 4-bar 1h fallback) c4h = ohlcv.get("4h", []) c1h = ohlcv.get("1h", []) if len(c4h) >= 2 and (c4h[-2].get("close") or 0) > 0 and c4h[-1].get("close") is not None: prev4 = float(c4h[-2]["close"]) curr4 = float(c4h[-1]["close"]) pc4 = (curr4 - prev4) / prev4 * 100 price_4h_changes.append(pc4) price_4h_weights.append(w) elif len(c1h) >= 5 and (c1h[-5].get("close") or 0) > 0 and c1h[-1].get("close") is not None: prev4 = float(c1h[-5]["close"]) curr4 = float(c1h[-1]["close"]) pc4 = (curr4 - prev4) / prev4 * 100 price_4h_changes.append(pc4) price_4h_weights.append(w) # OI change % (15m, 1h, 4h) oi_data = exch.get("open_interest_data") if not oi_data and ("oi_change_pct" in exch or "open_interest" in exch): oi_data = exch if oi_data and isinstance(oi_data, dict): raw_oi_change = oi_data.get("oi_change_pct") if raw_oi_change is not None: val = float(raw_oi_change) oi_horizon = oi_data.get("oi_horizon") or exch.get("oi_horizon") oi_window_sec = oi_data.get("oi_window_sec") or exch.get("oi_window_sec") if oi_horizon == "rolling": rolling_oi_changes.append((val, w, oi_window_sec)) else: hist_15m_oi_changes.append(val) hist_15m_oi_weights.append(w) if oi_data.get("oi_change_1h_pct") is not None: oi_1h_changes.append(float(oi_data["oi_change_1h_pct"])) oi_1h_weights.append(w) if oi_data.get("oi_change_4h_pct") is not None: oi_4h_changes.append(float(oi_data["oi_change_4h_pct"])) oi_4h_weights.append(w) if not price_changes and not price_4h_changes: return { "value": "No Data", "score": 0, "intraday_score": 0, "swing_score": 0, "label": "No Price Data", "price_threshold_pct": round(price_threshold, 4), "oi_horizon_used": "none", } avg_price_change = _oi_weighted_average(price_changes, price_weights) if price_changes else 0.0 if hist_15m_oi_changes: avg_oi_change = _oi_weighted_average(hist_15m_oi_changes, hist_15m_oi_weights) oi_horizon_used = "15m" elif rolling_oi_changes: scaled_changes: list[float] = [] rolling_weights: list[float] = [] for raw_pct, rw, win in rolling_oi_changes: win_sec = float(win) if win is not None else 300.0 scale = min(2.0, 900.0 / max(win_sec, 60.0)) scaled_changes.append(raw_pct * scale) rolling_weights.append(rw) avg_oi_change = _oi_weighted_average(scaled_changes, rolling_weights) oi_horizon_used = "rolling" else: avg_oi_change = 0.0 oi_horizon_used = "none" avg_oi_1h_change = _oi_weighted_average(oi_1h_changes, oi_1h_weights) if oi_1h_changes else avg_oi_change avg_oi_4h_change = _oi_weighted_average(oi_4h_changes, oi_4h_weights) if oi_4h_changes else avg_oi_1h_change avg_price_4h_change = _oi_weighted_average(price_4h_changes, price_4h_weights) if price_4h_changes else avg_price_change # Robust threshold to filter sub-tick micro-noise on 15m timeframe: # Dimensionless ATR-normalized threshold clamped to [0.10, 0.60] (fallback 0.15) # and 0.25% net Open Interest expansion/unwinding OI_THRESHOLD = 0.25 significant_price_up = avg_price_change > price_threshold significant_price_down = avg_price_change < -price_threshold significant_oi_up = avg_oi_change > OI_THRESHOLD significant_oi_down = avg_oi_change < -OI_THRESHOLD if significant_price_up and significant_oi_up: score = 1 direction_val = f"Up+Up (+{avg_price_change:.2f}% P, +{avg_oi_change:.2f}% OI)" label = "Aggressive Long Inflow (Price↑ + OI↑)" elif significant_price_up and significant_oi_down: if _candle_shows_exhaustion(longest_15m, "top"): score = -1 direction_val = f"Up+Down (+{avg_price_change:.2f}% P, {avg_oi_change:.2f}% OI)" label = "Short Covering Exhaustion (Price↑ + OI↓)" else: score = 0 direction_val = f"Up+Down (+{avg_price_change:.2f}% P, {avg_oi_change:.2f}% OI)" label = "Short Covering Rally (Wait Rejection)" elif significant_price_down and significant_oi_up: score = -1 direction_val = f"Down+Up ({avg_price_change:.2f}% P, +{avg_oi_change:.2f}% OI)" label = "Aggressive Short Inflow (Price↓ + OI↑)" elif significant_price_down and significant_oi_down: if _candle_shows_exhaustion(longest_15m, "bottom"): score = 1 direction_val = f"Down+Down ({avg_price_change:.2f}% P, {avg_oi_change:.2f}% OI)" label = "Long Squeeze Exhaustion Done (Price↓ + OI↓)" else: score = 0 direction_val = f"Down+Down ({avg_price_change:.2f}% P, {avg_oi_change:.2f}% OI)" label = "Deleveraging Selloff (Falling Knife Guard)" elif avg_price_change > 0: score = 0 direction_val = f"Mild Up (+{avg_price_change:.2f}% P, {avg_oi_change:+.2f}% OI)" label = "Mild Upward Drift (Neutral OI)" elif avg_price_change < 0: score = 0 direction_val = f"Mild Down ({avg_price_change:.2f}% P, {avg_oi_change:+.2f}% OI)" label = "Mild Downward Drift (Neutral OI)" else: score = 0 direction_val = "Flat (Neutral)" label = "Balanced Market Flow" # Swing 4h OI score uses 4h OI expansion (>0.50%) + 4h price displacement (>swing_price_threshold) when 4h OI history exists swing_score = score if oi_4h_changes: p4_up = avg_price_4h_change > swing_price_threshold p4_dn = avg_price_4h_change < -swing_price_threshold oi4_up = avg_oi_4h_change > 0.50 oi4_dn = avg_oi_4h_change < -0.50 if p4_up and oi4_up: swing_score = 1 elif p4_up and oi4_dn: swing_score = -1 if _candle_shows_exhaustion(longest_4h, "top") else 0 elif p4_dn and oi4_up: swing_score = -1 elif p4_dn and oi4_dn: swing_score = 1 if _candle_shows_exhaustion(longest_4h, "bottom") else 0 else: swing_score = 0 return { "value": direction_val, "price_change_pct": round(avg_price_change, 4), "price_change_4h_pct": round(avg_price_4h_change, 4), "oi_change_pct": round(avg_oi_change, 4), "oi_change_1h_pct": round(avg_oi_1h_change, 4), "oi_change_4h_pct": round(avg_oi_4h_change, 4), "score": score, "intraday_score": score, "swing_score": swing_score, "label": label, "price_threshold_pct": round(price_threshold, 4), "oi_horizon_used": oi_horizon_used, } def _compute_cvd(trades: list[dict]) -> dict[str, Any]: """ Cumulative Volume Delta = sum(aggressive_buy_vol) - sum(aggressive_sell_vol). Uses Volume-Normalized Delta Ratio (cvd / total_vol) with a 3% deadband filter to eliminate micro-noise on balanced order flow. Supports multi-venue time alignment (overlap / per_venue) with single-venue backward compatibility. """ if not trades: return {"value": 0, "delta_ratio": 0.0, "score": 0, "rising": False, "label": "No Trade Data"} slices, mode = _align_multi_venue_trades(trades) if mode == "overlap": total_buy_usd = 0.0 total_sell_usd = 0.0 total_buy_qty = 0.0 total_sell_qty = 0.0 weighted_rising_sum = 0.0 total_venue_usd = 0.0 for v, v_trades in slices.items(): v_buy_usd = 0.0 v_sell_usd = 0.0 v_buy_qty = 0.0 v_sell_qty = 0.0 for t in v_trades: qty = float(t.get("qty") or 0.0) px = float(t.get("price") or 0.0) usd = qty * px if px > 0 else qty if t.get("is_buyer_maker", False): v_sell_usd += usd v_sell_qty += qty else: v_buy_usd += usd v_buy_qty += qty v_tot_usd = v_buy_usd + v_sell_usd v_cvd_qty = v_buy_qty - v_sell_qty v_rising = _is_half_rising(v_trades, v_cvd_qty) total_buy_usd += v_buy_usd total_sell_usd += v_sell_usd total_buy_qty += v_buy_qty total_sell_qty += v_sell_qty if v_tot_usd > 0: weighted_rising_sum += (1.0 if v_rising else 0.0) * v_tot_usd total_venue_usd += v_tot_usd cvd = total_buy_qty - total_sell_qty cvd_usd = total_buy_usd - total_sell_usd total_vol_usd = total_buy_usd + total_sell_usd delta_ratio = (cvd_usd / total_vol_usd) if total_vol_usd > 0 else 0.0 cvd_rising = (weighted_rising_sum / total_venue_usd > 0.5) if total_venue_usd > 0 else False elif mode == "per_venue": venue_stats: list[tuple[float, bool, float, float]] = [] # (delta_ratio_v, is_rising_v, vol_v, cvd_qty_v) total_buy_qty = 0.0 total_sell_qty = 0.0 for v, v_trades in slices.items(): v_buy_usd = 0.0 v_sell_usd = 0.0 v_buy_qty = 0.0 v_sell_qty = 0.0 for t in v_trades: qty = float(t.get("qty") or 0.0) px = float(t.get("price") or 0.0) usd = qty * px if px > 0 else qty if t.get("is_buyer_maker", False): v_sell_usd += usd v_sell_qty += qty else: v_buy_usd += usd v_buy_qty += qty v_tot_usd = v_buy_usd + v_sell_usd v_cvd_qty = v_buy_qty - v_sell_qty v_delta_ratio = (v_buy_usd - v_sell_usd) / v_tot_usd if v_tot_usd > 0 else 0.0 v_rising = _is_half_rising(v_trades, v_cvd_qty) venue_stats.append((v_delta_ratio, v_rising, v_tot_usd, v_cvd_qty)) total_buy_qty += v_buy_qty total_sell_qty += v_sell_qty vols = [st[2] for st in venue_stats if st[2] > 0] sorted_vols = sorted(vols) median_vol = sorted_vols[len(sorted_vols) // 2] if sorted_vols else 1.0 tot_w = 0.0 weighted_delta_sum = 0.0 weighted_rising_sum = 0.0 for dr_v, ris_v, vol_v, _ in venue_stats: w_v = min(vol_v, median_vol * 2.0) tot_w += w_v weighted_delta_sum += dr_v * w_v weighted_rising_sum += (1.0 if ris_v else 0.0) * w_v delta_ratio = (weighted_delta_sum / tot_w) if tot_w > 0 else 0.0 cvd_rising = (weighted_rising_sum / tot_w > 0.5) if tot_w > 0 else False cvd = total_buy_qty - total_sell_qty else: # Single-venue fallback (bit-identical to existing logic) sorted_trades = sorted(trades, key=lambda t: float(t.get("time") or 0)) buy_vol = 0.0 sell_vol = 0.0 for t in sorted_trades: qty = float(t.get("qty") or 0.0) if t.get("is_buyer_maker", False): sell_vol += qty else: buy_vol += qty total_vol = buy_vol + sell_vol cvd = buy_vol - sell_vol delta_ratio = (cvd / total_vol) if total_vol > 0 else 0.0 cvd_rising = _is_half_rising(sorted_trades, cvd) CVD_DEADBAND = 0.03 # 3% net volume imbalance required for directional conviction if abs(delta_ratio) < CVD_DEADBAND: score, label = 0, "Neutral CVD (Balanced / Noise Filtered)" elif delta_ratio >= CVD_DEADBAND and cvd_rising: score, label = 1, "Positive CVD Rising → Strong Long Pressure" elif delta_ratio >= CVD_DEADBAND and not cvd_rising: score, label = 0, "Positive CVD Fading" elif delta_ratio <= -CVD_DEADBAND and not cvd_rising: score, label = -1, "Negative CVD Falling → Strong Short Pressure" else: score, label = 0, "Negative CVD Recovering" return { "value": round(cvd, 2), "delta_ratio": round(delta_ratio, 4), "rising": cvd_rising, "score": score, "label": label, } def _compute_cross_exchange( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, bitget_data: dict | None = None, hl_data: dict | None = None, ) -> dict[str, Any]: """ Triangulate price changes across derivative venues (Binance + Bybit + OKX + Bitget). Large divergence (>0.3%) → exchange dislocation or manipulation risk. Aligned exchanges confirm price consistency. """ def _pct_change_5m(exch: dict) -> float | None: candles = (exch.get("ohlcv") or {}).get("5m", []) if len(candles) < 2: return None prev = candles[-2].get("close") curr = candles[-1].get("close") if prev is None or curr is None or float(prev) <= 0: return None return (float(curr) - float(prev)) / float(prev) * 100 rates = {} if binance_data: p = _pct_change_5m(binance_data) if p is not None: rates["binance"] = p if bybit_data: p = _pct_change_5m(bybit_data) if p is not None: rates["bybit"] = p if okx_data: p = _pct_change_5m(okx_data) if p is not None: rates["okx"] = p if bitget_data: p = _pct_change_5m(bitget_data) if p is not None: rates["bitget"] = p if hl_data: p = _pct_change_5m(hl_data) if p is not None: rates["hyperliquid"] = p if len(rates) < 2: return { "binance_5m_pct": round(rates.get("binance", 0.0), 4) if "binance" in rates else None, "bybit_5m_pct": round(rates.get("bybit", 0.0), 4) if "bybit" in rates else None, "okx_5m_pct": round(rates.get("okx", 0.0), 4) if "okx" in rates else None, "bitget_5m_pct": round(rates.get("bitget", 0.0), 4) if "bitget" in rates else None, "hyperliquid_5m_pct": round(rates.get("hyperliquid", 0.0), 4) if "hyperliquid" in rates else None, "divergence_pct": 0.0, "score": 0, "dislocation_risk": False, "label": "Single Exchange (No Divergence)", } # Max spread among all available venues vals = list(rates.values()) max_div = max(vals) - min(vals) venue_str = "+".join(k.capitalize() for k in rates.keys()) dislocation_risk = max_div > 0.30 score = 0 # Non-directional risk monitor; dislocation never implies Short bias if dislocation_risk: label = f"High Triangulation Divergence {max_div:.3f}% ({venue_str}) → Dislocation Risk" elif max_div > 0.15: label = f"Moderate Spread {max_div:.3f}% ({venue_str})" else: label = f"Triangulation Confirmed across {venue_str} (div {max_div:.3f}%)" hl_basis = float(hl_data.get("basis_pct")) if (hl_data and hl_data.get("basis_pct") is not None) else None return { "binance_5m_pct": round(rates["binance"], 4) if "binance" in rates else None, "bybit_5m_pct": round(rates["bybit"], 4) if "bybit" in rates else None, "okx_5m_pct": round(rates.get("okx", 0.0), 4) if "okx" in rates else None, "bitget_5m_pct": round(rates.get("bitget", 0.0), 4) if "bitget" in rates else None, "hyperliquid_5m_pct": round(rates.get("hyperliquid", 0.0), 4) if "hyperliquid" in rates else None, "hyperliquid_basis_pct": round(hl_basis, 4) if hl_basis is not None else None, "divergence_pct": round(max_div, 4), "score": score, "dislocation_risk": dislocation_risk, "label": label, } def _compute_ls_ratio( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, bitget_data: dict | None = None, ) -> dict[str, Any]: """ Smart Money Whale Position vs Retail Crowd L/S Ratio (OI-Weighted across Binance, Bybit, OKX, and Bitget). Separates Top-Trader Position Size (Smart Money) from Global Account Ratio (Retail Crowd). """ long_ratios: list[float] = [] weights: list[float] = [] whale_pos_ratios: list[float] = [] whale_pos_weights: list[float] = [] top_acc_ratios: list[float] = [] top_acc_weights: list[float] = [] retail_ratios: list[float] = [] retail_weights: list[float] = [] legacy_crowd_ratios: list[float] = [] legacy_crowd_weights: list[float] = [] for exch in [binance_data, bybit_data, okx_data, bitget_data]: if exch and exch.get("ls_ratio_data"): ls_d = exch["ls_ratio_data"] w = _extract_venue_oi_weight(exch) lr = ls_d.get("long_ratio") wp = ls_d.get("top_position_long_ratio") ta = ls_d.get("top_account_long_ratio") rr = ls_d.get("retail_long_ratio") src = str(ls_d.get("source") or "").lower() if lr is not None: long_ratios.append(float(lr)) weights.append(w) if wp is not None: whale_pos_ratios.append(float(wp)) whale_pos_weights.append(w) if ta is not None: top_acc_ratios.append(float(ta)) top_acc_weights.append(w) if rr is not None: retail_ratios.append(float(rr)) retail_weights.append(w) elif wp is None and src not in ("top_trader", "smart_money") and lr is not None: # Backward compat: legacy single-field mocks without top_position_long_ratio represent crowd L/S legacy_crowd_ratios.append(float(lr)) legacy_crowd_weights.append(w) if not long_ratios: return { "top_trader": None, "retail": None, "whale_position_long_ratio": None, "top_account_long_ratio": None, "mega_whale_divergence": 0.0, "smart_money_delta": 0.0, "whale_sentiment": "NEUTRAL", "score": 0, "label": "No Data", } avg_long = _oi_weighted_average(long_ratios, weights) avg_whale_pos = _oi_weighted_average(whale_pos_ratios, whale_pos_weights) if whale_pos_ratios else None avg_top_acc = _oi_weighted_average(top_acc_ratios, top_acc_weights) if top_acc_ratios else None mega_whale_divergence = ( round(avg_whale_pos - avg_top_acc, 4) if (avg_whale_pos is not None and avg_top_acc is not None) else 0.0 ) avg_retail = ( _oi_weighted_average(retail_ratios, retail_weights) if retail_ratios else (_oi_weighted_average(legacy_crowd_ratios, legacy_crowd_weights) if legacy_crowd_ratios else None) ) smart_money_delta = (avg_whale_pos - avg_retail) if (avg_whale_pos is not None and avg_retail is not None) else 0.0 def _contrarian_crowd_signal() -> tuple[int, str]: if avg_retail is None: return 0, f"Smart Money Only {avg_long:.1%} (No Retail Feed)" if avg_retail >= 0.62: return -1, f"Crowded Retail Longs {avg_retail:.1%} → Contrarian Short" if avg_retail <= 0.38: return 1, f"Crowded Retail Shorts {avg_retail:.1%} → Contrarian Long" return 0, f"Balanced L/S {avg_retail:.1%}" whale_sentiment = "NEUTRAL" # Smart Money Whale Position vs Retail Crowd Divergence if avg_whale_pos is not None and avg_retail is not None and abs(smart_money_delta) >= 0.07: if smart_money_delta >= 0.12 and avg_whale_pos >= 0.56: score = 2 whale_sentiment = "STRONG_WHALE_LONG" label = f"Whale Position Accumulation ({avg_whale_pos:.1%} Whale Long vs {avg_retail:.1%} Retail) → Strong Smart Money Long" elif smart_money_delta <= -0.12 and avg_whale_pos <= 0.44: score = -2 whale_sentiment = "STRONG_WHALE_SHORT" label = f"Whale Position Distribution ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail Long) → Strong Smart Money Short" elif smart_money_delta >= 0.07 and avg_whale_pos >= 0.52: score = 1 whale_sentiment = "WHALE_LONG_TILT" label = f"Smart Money Whale Long Tilt ({avg_whale_pos:.1%} Whale Pos vs {avg_retail:.1%} Retail)" elif smart_money_delta <= -0.07 and avg_whale_pos <= 0.48: score = -1 whale_sentiment = "WHALE_SHORT_TILT" label = f"Smart Money Whale Short Tilt ({1.0 - avg_whale_pos:.1%} Whale Short vs {avg_retail:.1%} Retail)" else: score, label = _contrarian_crowd_signal() else: score, label = _contrarian_crowd_signal() return { "top_trader": round(avg_long, 4), "retail": round(avg_retail, 4) if retail_ratios else None, "whale_position_long_ratio": round(avg_whale_pos, 4) if avg_whale_pos is not None else None, "top_account_long_ratio": round(avg_top_acc, 4) if avg_top_acc is not None else None, "mega_whale_divergence": mega_whale_divergence, "smart_money_delta": round(smart_money_delta, 4), "whale_sentiment": whale_sentiment, "score": score, "label": label, } def _compute_basis( binance_data: dict | None, bybit_data: dict | None, okx_data: dict | None = None, bitget_data: dict | None = None, hl_data: dict | None = None, ) -> dict[str, Any]: """ OI-Weighted Basis = (mark_price - index_price) / index_price * 100 - Normal / Stable (<0.20%): Market in fair equilibrium (score: 0 neutral) - High Perp Premium (>+0.20%): Longs overpaying → Bearish reversion bias (-1) - High Perp Discount (<-0.20%): Perp discounted to spot → Bullish reversion bias (+1) """ bases: list[float] = [] weights: list[float] = [] for exch in [binance_data, bybit_data, okx_data, bitget_data]: if exch and exch.get("mark_price_data"): bp = exch["mark_price_data"].get("basis_pct") if bp is not None: bases.append(float(bp)) weights.append(_extract_venue_oi_weight(exch)) if hl_data and hl_data.get("basis_pct") is not None: bases.append(float(hl_data["basis_pct"])) weights.append(_extract_venue_oi_weight(hl_data, is_hl=True)) if not bases: return {"value": None, "score": 0, "label": "No Data"} avg_basis = _oi_weighted_average(bases, weights) if avg_basis > 0.20: score, label = -1, f"Perp Premium +{avg_basis:.3f}% → Overheated Pullback Bias" elif avg_basis < -0.20: score, label = 1, f"Perp Discount {avg_basis:.3f}% → Oversold Bounce Bias" else: score, label = 0, f"Equilibrium Basis {avg_basis:.3f}%" return {"value": round(avg_basis, 6), "score": score, "label": label} def _compute_trade_plan( direction: str, mark_price: float | None, ohlcv_1h: list[dict], spot_futures_score: int, conviction: int, predictive_data: dict | None = None, is_fake: bool = False, sl_min_pct: float = 0.01, sl_max_pct: float = 0.05, sl_fallback_max_pct: float = 0.04, sl_atr_mult: float = 1.5, sl_struct_buffer_atr: float = 0.2, ) -> dict[str, Any]: """ Actionable trade setup & instant 1-second verdict for lazy traders: - Pre-calculated Entry Zone, Stop Loss, and Take Profit (TP1 & TP2) - Forward-Looking Predictive Targets (Liquidation Magnet Hunt Pools) - Volatility Squeeze & Energy Coiling Forecaster - 1-sentence verdict summarizing the market in plain Indonesian - Instant Action status (STRONG BUY, BUY ON PULLBACK, SELL ON RALLY, WAIT, etc.) """ if not mark_price or mark_price <= 0: return { "trade_levels": None, "quick_verdict": "Menunggu data harga untuk menghitung level entry...", "action": "WAIT", } from engine.mtf_analyzer import _atr atr = _atr(ohlcv_1h, 14) if ohlcv_1h else mark_price * 0.012 if atr <= 0: atr = mark_price * 0.012 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}" pred = predictive_data or {} pred_target = pred.get("predicted_target") target_type = pred.get("target_type") target_dist_pct = pred.get("target_dist_pct") anticipation = pred.get("anticipation") squeeze_intensity = pred.get("volatility_squeeze", {}).get("squeeze_intensity", "NORMAL") ob_pressure = pred.get("orderbook_skew", {}).get("resting_pressure", "BALANCED") long_struct_min = 1.0 - sl_max_pct long_struct_max = 1.0 - sl_min_pct long_fb_min = 1.0 - sl_fallback_max_pct short_struct_min = 1.0 + sl_min_pct short_struct_max = 1.0 + sl_max_pct short_fb_max = 1.0 + sl_fallback_max_pct if direction == "LONG": entry_low = max(mark_price * 0.90, mark_price - (0.35 * atr)) entry_high = mark_price + (0.05 * atr) # Structure-Based Invalidation Stop Loss: anchor to recent swing low if within [sl_min_pct, sl_max_pct] recent_lows = [c["low"] for c in ohlcv_1h[-20:] if (c.get("low") or 0) > 0] if ohlcv_1h else [] if recent_lows: struct_low = min(recent_lows) - (sl_struct_buffer_atr * atr) if mark_price * long_struct_min <= struct_low <= mark_price * long_struct_max: sl = struct_low else: raw_sl = mark_price - (sl_atr_mult * atr) sl = max(mark_price * long_fb_min, min(mark_price * long_struct_max, raw_sl)) else: raw_sl = mark_price - (sl_atr_mult * atr) sl = max(mark_price * long_fb_min, min(mark_price * long_struct_max, raw_sl)) risk = abs(mark_price - sl) tp1 = max(mark_price + (1.5 * atr), mark_price + risk) tp2 = max(mark_price + (3.0 * atr), mark_price + (2.0 * risk)) if is_fake: verdict = "⚠️ Waspada Manipulasi Pasar! Terdeteksi wick sweep atau anomali volume, tunda entry sampai struktur stabil." action = "WAIT / MANIPULATION ALERT" elif spot_futures_score >= 1: verdict = "Whale borong Spot riil + Trend HTF Bullish. Setup akumulasi organik (High Conviction)." action = "STRONG BUY" if conviction >= 5 else "BUY ON PULLBACK" elif spot_futures_score <= -1: verdict = "Waspada Leverage Trap! Futures naik tapi Spot buang barang. Jangan kejar pucuk." action = "WAIT / TRAP ALERT" else: verdict = "Bias Bullish terkonfirmasi. Entry bertahap di zona pullback." action = "BUY ON PULLBACK" reward2 = abs(tp2 - mark_price) rr_ratio = round(reward2 / risk, 1) if risk > 0 else 2.0 trade_levels = { "entry_zone": f"{_fmt(entry_low)} - {_fmt(entry_high)}", "entry_price": round(mark_price, 8), "stop_loss": round(sl, 8), "stop_loss_str": _fmt(sl), "take_profit_1": round(tp1, 8), "take_profit_1_str": _fmt(tp1), "take_profit_2": round(tp2, 8), "take_profit_2_str": _fmt(tp2), "risk_reward": f"1 : {rr_ratio:.1f} (TP2)", "action": action, "predicted_target": pred_target, "target_type": target_type, "target_dist_pct": target_dist_pct, "squeeze_intensity": squeeze_intensity, "orderbook_pressure": ob_pressure, "anticipation": anticipation, } elif direction == "SHORT": entry_low = max(mark_price * 0.90, mark_price - (0.05 * atr)) entry_high = mark_price + (0.35 * atr) # Structure-Based Invalidation Stop Loss: anchor to recent swing high if within [sl_min_pct, sl_max_pct] recent_highs = [c["high"] for c in ohlcv_1h[-20:] if (c.get("high") or 0) > 0] if ohlcv_1h else [] if recent_highs: struct_high = max(recent_highs) + (sl_struct_buffer_atr * atr) if mark_price * short_struct_min <= struct_high <= mark_price * short_struct_max: sl = struct_high else: raw_sl = mark_price + (sl_atr_mult * atr) sl = min(mark_price * short_fb_max, max(mark_price * short_struct_min, raw_sl)) else: raw_sl = mark_price + (sl_atr_mult * atr) sl = min(mark_price * short_fb_max, max(mark_price * short_struct_min, raw_sl)) risk = abs(sl - mark_price) tp1 = max(mark_price * 0.05, min(mark_price - (1.5 * atr), mark_price - risk)) tp2 = max(mark_price * 0.01, min(mark_price - (3.0 * atr), mark_price - (2.0 * risk))) if is_fake: verdict = "⚠️ Waspada Manipulasi Pasar! Terdeteksi sapuan likuidasi, jangan panic short di dasar lembah." action = "WAIT / MANIPULATION ALERT" elif spot_futures_score <= -1: verdict = "Spot & Futures kompak keluar barang. Tekanan jual institusi riil (High Conviction Short)." action = "STRONG SHORT" if conviction >= 5 else "SELL ON RALLY" elif spot_futures_score >= 1: verdict = "Waspada Short Squeeze! Spot whales mulai serap barang di bawah." action = "CAUTION / SQUEEZE RISK" else: verdict = "Bias Bearish terkonfirmasi. Cari entry sell di pantulan resistensi." action = "SELL ON RALLY" reward2 = abs(mark_price - tp2) rr_ratio = round(reward2 / risk, 1) if risk > 0 else 2.0 trade_levels = { "entry_zone": f"{_fmt(entry_low)} - {_fmt(entry_high)}", "entry_price": round(mark_price, 8), "stop_loss": round(sl, 8), "stop_loss_str": _fmt(sl), "take_profit_1": round(tp1, 8), "take_profit_1_str": _fmt(tp1), "take_profit_2": round(tp2, 8), "take_profit_2_str": _fmt(tp2), "risk_reward": f"1 : {rr_ratio:.1f} (TP2)", "action": action, "predicted_target": pred_target, "target_type": target_type, "target_dist_pct": target_dist_pct, "squeeze_intensity": squeeze_intensity, "orderbook_pressure": ob_pressure, "anticipation": anticipation, } else: # NEUTRAL trade_levels = None if is_fake: action = "WAIT / MANIPULATION ALERT" verdict = "Terdeteksi sinyal manipulasi harga / wick sweep. Disarankan 'Wait-and-See' untuk menghindari jebakan likuiditas." else: action = "DO NOT TRADE / WAIT" verdict = "Struktur pasar sideways/chop atau sinyal bursa belum konvergen. Disarankan 'Wait-and-See' menunggu momentum jelas." return { "trade_levels": trade_levels, "quick_verdict": verdict, "action": action, } def _compute_lead_lag(exchange_data: dict, mark_price: float) -> dict[str, Any]: """ Lead-Lag Price Disparity across Binance, Bybit, OKX, Bitget, and Hyperliquid. Automatically normalizes power-of-10 contract denomination differences (e.g. 1000PEPE vs PEPE) and identifies which exchange is leading price discovery and the cross-venue spread in basis points. """ raw_prices: dict[str, float] = {} for exch_name, data in exchange_data.items(): if not data: continue px = data.get("mark_price") if px and isinstance(px, (int, float)) and px > 0: raw_prices[exch_name] = float(px) if not raw_prices and mark_price > 0: raw_prices["benchmark"] = mark_price ref_px = mark_price if (mark_price and mark_price > 0) else next(iter(raw_prices.values()), 0.0) venue_prices: dict[str, float] = {} for exch_name, px in raw_prices.items(): scale = _get_multiplier_scale(px, ref_px) venue_prices[exch_name] = round(px * scale, 10) if len(venue_prices) < 2: return { "venue_prices": venue_prices, "max_spread_usd": 0.0, "max_spread_bps": 0.0, "max_spread_pct": 0.0, "leading_exchange": None, "lagging_exchange": None, "lead_lag_summary": "Single venue / data tidak cukup untuk perbandingan lead-lag", "spread_table": [], } highest_exch = max(venue_prices, key=venue_prices.get) lowest_exch = min(venue_prices, key=venue_prices.get) highest_px = venue_prices[highest_exch] lowest_px = venue_prices[lowest_exch] spread_usd = highest_px - lowest_px spread_pct = (spread_usd / lowest_px * 100.0) if lowest_px > 0 else 0.0 spread_bps = spread_pct * 100.0 # 1% = 100 bps avg_px = sum(venue_prices.values()) / len(venue_prices) spread_table = [] for exch, px in venue_prices.items(): diff_bps = ((px - avg_px) / avg_px * 10000.0) if avg_px > 0 else 0.0 spread_table.append({ "exchange": exch, "price": px, "diff_from_avg_bps": round(diff_bps, 2), "is_lead_bullish": exch == highest_exch, "is_lead_bearish": exch == lowest_exch, }) if spread_bps >= 15.0: summary = f"Disparitas Tinggi: {highest_exch.upper()} memimpin di atas ({spread_bps:+.1f} bps vs {lowest_exch.upper()}). Potensi momentum agresif / arbitrase lag!" elif spread_bps >= 5.0: summary = f"Disparitas Moderat: {highest_exch.upper()} premium {spread_bps:+.1f} bps di atas {lowest_exch.upper()}." else: summary = f"Sangat Ketat: Spread antar bursa hanya {spread_bps:.1f} bps (konsensus harga seragam & likuiditas stabil)." return { "venue_prices": venue_prices, "max_spread_usd": round(spread_usd, 8), "max_spread_bps": round(spread_bps, 2), "max_spread_pct": round(spread_pct, 4), "leading_exchange": highest_exch, "lagging_exchange": lowest_exch, "lead_lag_summary": summary, "spread_table": spread_table, } def _compute_funding_settlement(exchange_data: dict) -> dict[str, Any]: """ Funding Settlement Countdown and dynamic fee risk estimation. Calculates time remaining to next settlement across CEXes (8h) and Hyperliquid (1h). Prioritizes CEX 8H settlement for the primary market risk indicator. """ now_ts = time.time() now_ms = now_ts * 1000.0 next_settlements = {} cex_diff_seconds = None cex_venue = None hl_diff_seconds = None for exch_name, data in exchange_data.items(): if not data: continue nft = data.get("next_funding_time") if exch_name == "hyperliquid" or not nft: if exch_name == "hyperliquid": next_hour_s = (int(now_ts // 3600) + 1) * 3600 diff_s = next_hour_s - now_ts m = int(diff_s // 60) hl_diff_seconds = diff_s next_settlements[exch_name] = { "countdown_seconds": int(diff_s), "countdown_str": f"{m}m", "cycle": "1H", } continue if nft: try: if isinstance(nft, (int, float)): nft_ms = float(nft) elif isinstance(nft, str): if nft.isdigit(): nft_ms = float(nft) else: from datetime import datetime as dt_cls dt = dt_cls.fromisoformat(nft.replace("Z", "+00:00")) nft_ms = dt.timestamp() * 1000.0 else: nft_ms = 0.0 if 0 < nft_ms < 10_000_000_000: nft_ms *= 1000.0 diff_s = (nft_ms - now_ms) / 1000.0 if diff_s > 0: h = int(diff_s // 3600) m = int((diff_s % 3600) // 60) cd_str = f"{h}h {m}m" if h > 0 else f"{m}m" next_settlements[exch_name] = { "countdown_seconds": int(diff_s), "countdown_str": cd_str, "cycle": "8H", } if cex_diff_seconds is None or diff_s < cex_diff_seconds: cex_diff_seconds = diff_s cex_venue = exch_name except Exception: pass if cex_diff_seconds is not None and cex_diff_seconds > 0: h = int(cex_diff_seconds // 3600) m = int((cex_diff_seconds % 3600) // 60) overall_countdown = f"{h}h {m}m" if h > 0 else f"{m}m" is_imminent = cex_diff_seconds <= 2700 # within 45 minutes of major 8H settlement venue_label = cex_venue.upper() if cex_venue else "CEX" if is_imminent: risk_label = f"⚠️ SETTLEMENT CEX 8H DALAM {overall_countdown} ({venue_label}): Waspada rebalancing funding & volatilitas likuidasi!" else: risk_label = f"Settlement CEX 8H berikutnya dalam {overall_countdown} ({venue_label}). Risiko volatilitas sesaat rendah." if hl_diff_seconds is not None: risk_label += f" | Hyperliquid (1H): {int(hl_diff_seconds // 60)}m" elif hl_diff_seconds is not None and hl_diff_seconds > 0: overall_countdown = f"{int(hl_diff_seconds // 60)}m" is_imminent = False risk_label = f"Hyperliquid DEX 1H Settlement dalam {overall_countdown} (funding kontinu per jam)." else: overall_countdown = "N/A" is_imminent = False risk_label = "Jadwal settlement standar (siklus 8 jam CEX / 1 jam Hyperliquid)." return { "countdown_str": overall_countdown, "is_settlement_imminent": is_imminent, "risk_label": risk_label, "venues": next_settlements, } def _compute_price_extremes_24h( merged_ohlcv: dict, mark_price: float, symbol: str = "", exchange_data: dict | None = None, ) -> dict[str, Any]: """ Computes rolling 24-hour extremes (High, Low, Range, and % distance). Uses the last 24 candles of 1h (or 1d candle if 1h insufficient), with graceful fallback to bulk 24h ticker data and OKX/Bitget tickers. Guarantees High >= Mark Price >= Low to prevent inverted range calculations. """ candles_1h = merged_ohlcv.get("1h", []) if merged_ohlcv else [] highs = [] lows = [] if candles_1h and len(candles_1h) >= 1: recent_bars = candles_1h[-24:] for b in recent_bars: h = b.get("high") l = b.get("low") if h is not None and float(h) > 0: highs.append(float(h)) if l is not None and float(l) > 0: lows.append(float(l)) # If 1h history is partial (< 20 bars), augment with 1d candle, bulk 24h ticker, and OKX/Bitget if len(highs) < 20 or len(lows) < 20: if merged_ohlcv and merged_ohlcv.get("1d"): for c1d in merged_ohlcv["1d"][-2:]: if c1d.get("high") and float(c1d["high"]) > 0: highs.append(float(c1d["high"])) if c1d.get("low") and float(c1d["low"]) > 0: lows.append(float(c1d["low"])) if symbol: for ticker_24 in ( bulk_fetcher.get_binance_24h(symbol), bulk_fetcher.get_bybit_24h_and_oi(symbol), ): if ticker_24 and ticker_24.get("high_24h") and ticker_24.get("low_24h"): h24 = float(ticker_24["high_24h"]) l24 = float(ticker_24["low_24h"]) if h24 > 0 and l24 > 0: ref_venue = float(ticker_24.get("last_price") or ((h24 + l24) / 2.0)) scale = _get_multiplier_scale(ref_venue, mark_price) highs.append(h24 * scale) lows.append(l24 * scale) if exchange_data: for exch_k in ("okx", "bitget"): ex_d = exchange_data.get(exch_k) or {} mp_d = ex_d.get("mark_price_data") if isinstance(ex_d.get("mark_price_data"), dict) else ex_d h24 = float(mp_d.get("high_24h", 0.0) or ex_d.get("high_24h", 0.0) or 0.0) l24 = float(mp_d.get("low_24h", 0.0) or ex_d.get("low_24h", 0.0) or 0.0) if h24 > 0 and l24 > 0: mp_ex = float(mp_d.get("mark_price", 0.0) or ((h24 + l24) / 2.0)) scale = _get_multiplier_scale(mp_ex, mark_price) highs.append(h24 * scale) lows.append(l24 * scale) # Always incorporate OKX and Bitget 24h extremes if present in exchange_data to guarantee 5-exchange coverage if exchange_data: for exch_k in ("okx", "bitget"): ex_d = exchange_data.get(exch_k) or {} mp_d = ex_d.get("mark_price_data") if isinstance(ex_d.get("mark_price_data"), dict) else ex_d h24 = float(mp_d.get("high_24h", 0.0) or ex_d.get("high_24h", 0.0) or 0.0) l24 = float(mp_d.get("low_24h", 0.0) or ex_d.get("low_24h", 0.0) or 0.0) if h24 > 0 and l24 > 0: mp_ex = float(mp_d.get("mark_price", 0.0) or ((h24 + l24) / 2.0)) scale = _get_multiplier_scale(mp_ex, mark_price) highs.append(h24 * scale) lows.append(l24 * scale) if not highs or not lows or mark_price <= 0: return { "high_24h": mark_price, "low_24h": mark_price, "range_usd": 0.0, "range_pct": 0.0, "dist_to_high_pct": 0.0, "dist_to_low_pct": 0.0, "range_position_pct": 50.0, "zone_label": "Equilibrium", } raw_high = max(highs) raw_low = min(lows) # Current mark price anchors extremes so High is never below mark price and Low is never above it high_24h = max(raw_high, mark_price) low_24h = min(raw_low, mark_price) range_usd = high_24h - low_24h range_pct = (range_usd / low_24h * 100.0) if low_24h > 0 else 0.0 dist_to_high_pct = max(0.0, ((high_24h - mark_price) / mark_price * 100.0)) if mark_price > 0 else 0.0 dist_to_low_pct = max(0.0, ((mark_price - low_24h) / mark_price * 100.0)) if mark_price > 0 else 0.0 if range_usd > 0: pos_pct = max(0.0, min(100.0, (mark_price - low_24h) / range_usd * 100.0)) else: pos_pct = 50.0 if pos_pct >= 80.0: zone = f"DEKAT 24H RESISTANCE/HIGH ({pos_pct:.1f}% rentang) — Waspada rejection atau fakeout wick hunt" elif pos_pct <= 20.0: zone = f"DEKAT 24H SUPPORT/LOW ({pos_pct:.1f}% rentang) — Area diskon / potensi sweep likuidasi buyer" elif 40.0 <= pos_pct <= 60.0: zone = f"MID-RANGE EQUILIBRIUM ({pos_pct:.1f}% rentang) — Menunggu dorongan momentum" elif pos_pct > 60.0: zone = f"UPPER RANGE EXPANSION ({pos_pct:.1f}% rentang) — Bullish momentum" else: zone = f"LOWER RANGE EXPANSION ({pos_pct:.1f}% rentang) — Bearish pressure" return { "high_24h": round(high_24h, 8), "low_24h": round(low_24h, 8), "range_usd": round(range_usd, 8), "range_pct": round(range_pct, 2), "dist_to_high_pct": round(dist_to_high_pct, 2), "dist_to_low_pct": round(dist_to_low_pct, 2), "range_position_pct": round(pos_pct, 1), "zone_label": zone, } def _compute_adv_24h_usd( symbol: str | dict | None = "", binance_data: dict | None = None, bybit_data: dict | None = None, okx_data: dict | None = None, bitget_data: dict | None = None, hl_data: dict | None = None, merged_ohlcv: dict | None = None, mark_price: float = 0.0, **kwargs: Any, ) -> tuple[float, dict[str, float]]: """ Computes 24h USD notional turnover (ADV) across all 5 venues without extra REST roundtrips. Returns: (total_adv_usd, venue_adv_usd_dict) """ # Handle positional or alternative kwarg invocations if isinstance(symbol, dict): hl_data = bitget_data bitget_data = okx_data okx_data = bybit_data bybit_data = binance_data binance_data = symbol symbol = "" if not binance_data and "binance" in kwargs: binance_data = kwargs["binance"] if not bybit_data and "bybit" in kwargs: bybit_data = kwargs["bybit"] if not okx_data and "okx" in kwargs: okx_data = kwargs["okx"] if not bitget_data and "bitget" in kwargs: bitget_data = kwargs["bitget"] if not hl_data and ("hyperliquid" in kwargs or "hl" in kwargs): hl_data = kwargs.get("hyperliquid") or kwargs.get("hl") venue_map: dict[str, float] = {} # 1. Binance b_24 = bulk_fetcher.get_binance_24h(symbol) if (symbol and isinstance(symbol, str)) else {} b_vol = float((b_24 or {}).get("quote_volume_24h", 0.0) or 0.0) if b_vol > 0: venue_map["binance"] = b_vol elif binance_data: c1d = (binance_data.get("ohlcv") or {}).get("1d", []) if c1d and c1d[-1].get("quote_volume"): venue_map["binance"] = float(c1d[-1]["quote_volume"]) elif (binance_data.get("ohlcv") or {}).get("1h"): c1h = binance_data["ohlcv"]["1h"][-24:] v_sum = sum(float(c.get("quote_volume") or (float(c.get("volume", 0.0) or 0.0) * float(c.get("close", 0.0) or mark_price))) for c in c1h) if v_sum > 0: venue_map["binance"] = v_sum # 2. Bybit y_24 = bulk_fetcher.get_bybit_24h_and_oi(symbol) if (symbol and isinstance(symbol, str)) else {} y_vol = float((y_24 or {}).get("turnover_24h", 0.0) or 0.0) if y_vol > 0: venue_map["bybit"] = y_vol elif bybit_data: c1d = (bybit_data.get("ohlcv") or {}).get("1d", []) if c1d and (c1d[-1].get("quote_volume") or (c1d[-1].get("volume") and c1d[-1].get("close"))): qv = c1d[-1].get("quote_volume") or (float(c1d[-1]["volume"]) * float(c1d[-1]["close"])) venue_map["bybit"] = float(qv) elif (bybit_data.get("ohlcv") or {}).get("1h"): c1h = bybit_data["ohlcv"]["1h"][-24:] v_sum = sum(float(c.get("quote_volume") or (float(c.get("volume", 0.0) or 0.0) * float(c.get("close", 0.0) or mark_price))) for c in c1h) if v_sum > 0: venue_map["bybit"] = v_sum # 3. OKX if okx_data: mp_d = okx_data.get("mark_price_data") or {} o_vol = float(mp_d.get("quote_volume_24h", 0.0) or 0.0) if o_vol > 0: venue_map["okx"] = o_vol # 4. Bitget if bitget_data: mp_d = bitget_data.get("mark_price_data") or {} bg_vol = float(mp_d.get("quote_volume_24h", 0.0) or 0.0) if bg_vol > 0: venue_map["bitget"] = bg_vol # 5. Hyperliquid if hl_data: hl_vol = float(hl_data.get("day_notional_volume", 0.0) or 0.0) if hl_vol > 0: venue_map["hyperliquid"] = hl_vol total_adv = sum(venue_map.values()) # Fallback to merged_ohlcv 24 1h bars if ticker volumes are absent if total_adv <= 0 and merged_ohlcv and merged_ohlcv.get("1h"): c1h = merged_ohlcv["1h"][-24:] fallback_sum = sum( float(c.get("quote_volume") or (float(c.get("volume", 0.0) or 0.0) * float(c.get("close", 0.0) or mark_price))) for c in c1h ) if fallback_sum > 0: total_adv = fallback_sum venue_map["merged"] = fallback_sum return round(total_adv, 2), {k: round(v, 2) for k, v in venue_map.items()} def _compute_liquidation_cascade( liquidations: list[dict] | None, oi_signal: dict[str, Any] | None, whale_flow: dict[str, Any] | None, spot_futures_signal: dict[str, Any] | None, merged_ohlcv: dict[str, list[dict]] | None = None, adv_floor_usd: float = 5000.0, ) -> dict[str, Any]: """ Derivatives Deleveraging & Forced Liquidation Cascade Analysis (Factor: liquidation_cascade [-2, +2]). Identifies capitulation reversals when forced liquidation flushes are absorbed by smart money. """ long_liq_usd = 0.0 short_liq_usd = 0.0 long_liq_count = 0 short_liq_count = 0 if liquidations: for liq in liquidations: try: p = float(liq.get("price") or 0.0) q = float(liq.get("qty") or 0.0) usd_v = p * q is_long = bool(liq.get("is_long_liq", True)) if usd_v > 0: if is_long: long_liq_usd += usd_v long_liq_count += 1 else: short_liq_usd += usd_v short_liq_count += 1 except (ValueError, TypeError): continue # Deleveraging proxy fallback if liquidation stream is empty (e.g. historical replay or REST without liq feed) oi_val = (oi_signal or {}).get("oi_change_pct") oi_chg = float(oi_val) if oi_val is not None else 0.0 wf = whale_flow or {} t_sell_usd = float(wf.get("taker_sell_vol_usd", 0.0) or 0.0) t_buy_usd = float(wf.get("taker_buy_vol_usd", 0.0) or 0.0) if (long_liq_usd == 0 and short_liq_usd == 0) and oi_chg <= -0.35: synth_floor = max(25_000.0, adv_floor_usd * 2.0) if t_sell_usd >= synth_floor and t_sell_usd > t_buy_usd * 1.2: long_liq_usd = max(t_sell_usd * 0.5, adv_floor_usd * 2.0) long_liq_count = 1 elif t_buy_usd >= synth_floor and t_buy_usd > t_sell_usd * 1.2: short_liq_usd = max(t_buy_usd * 0.5, adv_floor_usd * 2.0) short_liq_count = 1 cascade_thresh = max(15_000.0, adv_floor_usd * 1.5) score = 0 cascade_state = "NONE" label = "No Liquidation Cascade" candles_15m = (merged_ohlcv.get("15m") or []) if merged_ohlcv else [] sf_sc = int((spot_futures_signal or {}).get("score", 0) or 0) abs_sc = int(wf.get("absorption_score", 0) or 0) abs_type = str(wf.get("absorption_type", "")).upper() is_iceberg_absorbing = bool(wf.get("is_iceberg_absorbing", False)) # Bullish iceberg absorbs sells (limit bid): absorption_score > 0, explicit BULLISH type, or generic is_iceberg_absorbing without BEARISH type is_bull_iceberg = abs_sc > 0 or ("BULLISH" in abs_type) or (is_iceberg_absorbing and "BEARISH" not in abs_type) # Bearish iceberg absorbs buys (limit ask): absorption_score < 0, explicit BEARISH type, or generic is_iceberg_absorbing without BULLISH type is_bear_iceberg = abs_sc < 0 or ("BEARISH" in abs_type) or (is_iceberg_absorbing and "BULLISH" not in abs_type) wh_comp = int(wf.get("whale_composite_score", 0) or 0) # 1. Long Liquidation Capitulation (Contrarian Bullish +1 / +2) if long_liq_usd >= cascade_thresh and long_liq_usd > short_liq_usd * 2.0: has_bottom_exhaustion = _candle_shows_exhaustion(candles_15m, "bottom") if candles_15m else False is_absorbed = has_bottom_exhaustion or sf_sc >= 1 or is_bull_iceberg or wh_comp >= 1 if is_absorbed: is_extreme = long_liq_usd >= cascade_thresh * 3.0 and (sf_sc >= 1 or is_bull_iceberg) score = 2 if is_extreme else 1 cascade_state = "LONG_CAPITULATION_ABSORBED" label = f"Long Liquidation Capitulation Absorbed (${long_liq_usd:,.0f}) → Bullish Reversal" else: score = 0 cascade_state = "ACTIVE_LONG_FLUSH_WAIT" label = f"Active Long Liquidation Cascade (${long_liq_usd:,.0f} - Wait Bottom Absorption)" # 2. Short Liquidation Squeeze Exhaustion (Contrarian Bearish -1 / -2) elif short_liq_usd >= cascade_thresh and short_liq_usd > long_liq_usd * 2.0: has_top_exhaustion = _candle_shows_exhaustion(candles_15m, "top") if candles_15m else False is_absorbed = has_top_exhaustion or sf_sc <= -1 or is_bear_iceberg or wh_comp <= -1 if is_absorbed: is_extreme = short_liq_usd >= cascade_thresh * 3.0 and (sf_sc <= -1 or is_bear_iceberg) score = -2 if is_extreme else -1 cascade_state = "SHORT_SQUEEZE_EXHAUSTED" label = f"Short Squeeze Exhaustion Flushed (${short_liq_usd:,.0f}) → Bearish Reversal" else: score = 0 cascade_state = "ACTIVE_SHORT_SQUEEZE_WAIT" label = f"Active Short Liquidation Squeeze (${short_liq_usd:,.0f} - Wait Top Exhaustion)" return { "score": score, "label": label, "long_liq_usd": round(long_liq_usd, 2), "short_liq_usd": round(short_liq_usd, 2), "long_liq_count": long_liq_count, "short_liq_count": short_liq_count, "cascade_state": cascade_state, } def _compute_whale_order_flow( trades: list[dict], mark_price: float, merged_ohlcv: dict | None = None, oi_signal: dict | None = None, ls_signal: dict | None = None, adv_24h_usd: float = 0.0, venue_adv_usd: dict[str, float] | None = None, liquidations: list[dict] | None = None, exchange_candles: dict[str, dict[str, list[dict]]] | None = None, l2_microstructure: dict[str, Any] | None = None, hl_whale_summary: dict[str, Any] | None = None, ) -> dict[str, Any]: """ Multi-Layer Institutional Order Flow & True Whale Movement Intelligence: 1. Absolute ADV Whale Thresholds (scaled to 24h turnover) + Quantile Block Trade Detection 2. Reconstructed Market Sweep Clustering (coalesces split resting fills sharing exact tick timestamp) 3. Multi-Exchange Whale TWAP & Average Trade Size via Klines `taker_buy_volume` & `trade_count` 4. Hyperliquid On-Chain Single-Wallet Whale Accumulation Tracker (`taker_wallet` grouping) 5. True L2 Iceberg Refill & Passive Limit Absorption Detector (High Taker Sell + Price Hold + OI Expansion) 6. Forced Liquidation De-Contamination (excludes liquidations from organic aggressive whale volume) """ # Dynamic ADV Whale Floors if adv_24h_usd > 0: adv_floor_usd = max(5000.0, min(250_000.0, adv_24h_usd * 0.00005)) twap_min_usd = max(25_000.0, min(500_000.0, adv_24h_usd * 0.0002)) else: adv_floor_usd = 5000.0 twap_min_usd = 25_000.0 twap_buy_usd = 0.0 twap_sell_usd = 0.0 twap_bias = "NEUTRAL" twap_score = 0 absorption_type: str | None = None absorption_note: str | None = None absorption_score = 0 total_trade_count = 0 tc_vol_usd = 0.0 oi_val = (oi_signal or {}).get("oi_change_pct") oi_chg = float(oi_val) if oi_val is not None else 0.0 oi_1h_val = (oi_signal or {}).get("oi_change_1h_pct") oi_1h_chg = float(oi_1h_val) if oi_1h_val is not None else oi_chg # Only elevate 1H OI over 15m when aligned in sign (or 15m is flat 0.0); never let stale 1H mask active 15m unwinding if oi_chg != 0.0 and (oi_chg * oi_1h_chg) < 0: eff_oi_chg = oi_chg else: eff_oi_chg = oi_1h_chg if abs(oi_1h_chg) > abs(oi_chg) else oi_chg # Multi-exchange candle aggregation for Layer 3 TWAP & Average Trade Size if exchange_candles and mark_price > 0: for v_name, v_ohlcv in exchange_candles.items(): if not v_ohlcv: continue v_bars = (v_ohlcv.get("15m") or v_ohlcv.get("1h") or [])[-4:] for b in v_bars: if not isinstance(b, dict): continue v_tot = float(b.get("volume", 0.0) or 0.0) if v_tot <= 0: continue px_b = float(b.get("close") or mark_price) tb_raw = b.get("taker_buy_volume") if tb_raw is not None: v_buy = min(v_tot, max(0.0, float(tb_raw))) v_sell = max(0.0, v_tot - v_buy) twap_buy_usd += v_buy * px_b twap_sell_usd += v_sell * px_b tc = b.get("trade_count") if tc is not None: try: tc_int = int(tc) if tc_int > 0: total_trade_count += tc_int tc_vol_usd += v_tot * px_b except (ValueError, TypeError): pass elif merged_ohlcv and mark_price > 0: ref_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-4:] tb_bars = [b for b in ref_bars if b.get("taker_buy_volume") is not None and float(b.get("volume", 0.0) or 0.0) > 0] if tb_bars: for b in tb_bars: v_tot = float(b.get("volume", 0.0) or 0.0) v_buy = min(v_tot, max(0.0, float(b.get("taker_buy_volume", 0.0) or 0.0))) v_sell = max(0.0, v_tot - v_buy) px_b = float(b.get("close") or mark_price) twap_buy_usd += v_buy * px_b twap_sell_usd += v_sell * px_b tc = b.get("trade_count") if tc is not None: try: tc_int = int(tc) if tc_int > 0: total_trade_count += tc_int tc_vol_usd += v_tot * px_b except (ValueError, TypeError): pass twap_tot_usd = twap_buy_usd + twap_sell_usd twap_delta_usd = twap_buy_usd - twap_sell_usd twap_delta_ratio = (twap_delta_usd / twap_tot_usd) if twap_tot_usd > 0 else 0.0 avg_trade_size_usd = (tc_vol_usd / total_trade_count) if total_trade_count > 0 else 0.0 # Require institutional notional size (>= twap_min_usd) to classify TWAP accumulation if twap_tot_usd >= twap_min_usd: if twap_delta_ratio >= 0.06 and eff_oi_chg >= 0.20: twap_bias = "WHALE_TWAP_LONG_BUILDUP" twap_score = 2 if (twap_delta_ratio >= 0.12 and eff_oi_chg >= 0.50) else 1 elif twap_delta_ratio <= -0.06 and eff_oi_chg >= 0.20: twap_bias = "WHALE_TWAP_SHORT_BUILDUP" twap_score = -2 if (twap_delta_ratio <= -0.12 and eff_oi_chg >= 0.50) else -1 elif twap_delta_ratio >= 0.08: twap_bias = "TWAP_BUY_ACCUMULATION" twap_score = 1 elif twap_delta_ratio <= -0.08: twap_bias = "TWAP_SELL_DISTRIBUTION" twap_score = -1 # Iceberg Limit Absorption on latest completed/active 15m or 1h bar if merged_ohlcv: ref_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or []) if ref_bars: last_b = ref_bars[-1] b_high = float(last_b.get("high", 0.0) or 0.0) b_low = float(last_b.get("low", 0.0) or 0.0) b_close = float(last_b.get("close", 0.0) or 0.0) b_rng = b_high - b_low min_meaningful_rng = b_close * 0.001 if b_close > 0 else 0.0 close_pos = ((b_close - b_low) / b_rng) if (b_rng > 0 and b_rng >= min_meaningful_rng) else 0.5 if b_rng >= min_meaningful_rng and twap_tot_usd >= twap_min_usd and eff_oi_chg >= 0.25: if twap_delta_ratio <= -0.05 and close_pos >= 0.60: absorption_type = "BULLISH_ICEBERG_ABSORPTION" absorption_note = f"Limit Bid Iceberg menyerap jualan agresif + OI naik {eff_oi_chg:+.2f}%" absorption_score = 1 elif twap_delta_ratio >= 0.05 and close_pos <= 0.40: absorption_type = "BEARISH_ICEBERG_ABSORPTION" absorption_note = f"Limit Ask Iceberg menahan beli agresif + OI naik {eff_oi_chg:+.2f}%" absorption_score = -1 # Override/prioritize with true L2 orderbook iceberg detection when confirmed if l2_microstructure and isinstance(l2_microstructure, dict): l2_sc = int(l2_microstructure.get("l2_iceberg_score", 0) or 0) if l2_sc != 0: absorption_score = l2_sc absorption_type = "BULLISH_L2_ICEBERG_REFILL" if l2_sc > 0 else "BEARISH_L2_ICEBERG_REFILL" absorption_note = l2_microstructure.get("iceberg_note") or f"L2 Iceberg Refill (${l2_microstructure.get('iceberg_price', 0):,.2f})" sm_delta = float((ls_signal or {}).get("smart_money_delta", 0.0) or 0.0) whale_pos_lr = (ls_signal or {}).get("whale_position_long_ratio") retail_acc_lr = (ls_signal or {}).get("retail") # Hyperliquid tracked smart whale open-position bias (from clearinghouseState poller) hl_pos_score = 0 if hl_whale_summary and isinstance(hl_whale_summary, dict): hl_holders = int(hl_whale_summary.get("total_tracked_holders", 0) or 0) hl_smart_bias = str(hl_whale_summary.get("smart_bias") or "NEUTRAL").upper() hl_s_long = float(hl_whale_summary.get("smart_long_usd", 0.0) or 0.0) hl_s_short = float(hl_whale_summary.get("smart_short_usd", 0.0) or 0.0) if hl_holders >= 1 and max(hl_s_long, hl_s_short) >= 250_000.0: if hl_smart_bias == "SMART_WHALES_NET_LONG": hl_pos_score = 1 elif hl_smart_bias == "SMART_WHALES_NET_SHORT": hl_pos_score = -1 # Ingest forced liquidations for de-contamination (track timestamps to align with active trade window) long_liq_usd = 0.0 short_liq_usd = 0.0 long_liq_count = 0 short_liq_count = 0 feed_liq_events: list[tuple[int, bool, float]] = [] if liquidations: for liq in liquidations: try: lp = float(liq.get("price") or 0.0) lq = float(liq.get("qty") or 0.0) l_usd = lp * lq is_long = bool(liq.get("is_long_liq", True)) l_ts = int(liq.get("time") or 0) if l_usd > 0: feed_liq_events.append((l_ts, is_long, l_usd)) if is_long: long_liq_usd += l_usd long_liq_count += 1 else: short_liq_usd += l_usd short_liq_count += 1 except (ValueError, TypeError): continue taker_buy_vol = 0.0 taker_sell_vol = 0.0 parsed_trades = [] sweep_buckets: dict[tuple[str, int, bool], float] = {} unbucketed_sweeps: list[tuple[float, bool]] = [] wallet_flows: dict[str, list[float]] = {} venue_parsed: dict[str, list[tuple[float, bool]]] = {} min_trade_ts = 0 max_trade_ts = 0 if trades and mark_price > 0: for t in trades: try: px = float(t.get("price", 0.0)) qty = float(t.get("qty", 0.0)) if px <= 0 or qty <= 0: continue usd_val = px * qty is_sell_taker = bool(t.get("is_buyer_maker", False)) or (str(t.get("side", "")).lower() in ("sell", "s", "a")) # If trade is tagged as liquidation, record in liq pool and skip standard taker flow if t.get("is_liquidation"): if is_sell_taker: long_liq_usd += usd_val long_liq_count += 1 else: short_liq_usd += usd_val short_liq_count += 1 continue parsed_trades.append((usd_val, is_sell_taker)) v_name = str(t.get("venue") or "default") venue_parsed.setdefault(v_name, []).append((usd_val, is_sell_taker)) if is_sell_taker: taker_sell_vol += usd_val else: taker_buy_vol += usd_val t_ms = int(t.get("time", 0) or 0) venue = str(t.get("venue", "default")) if t_ms > 0: if min_trade_ts == 0 or t_ms < min_trade_ts: min_trade_ts = t_ms if t_ms > max_trade_ts: max_trade_ts = t_ms b_key = (venue, t_ms, is_sell_taker) sweep_buckets[b_key] = sweep_buckets.get(b_key, 0.0) + usd_val else: unbucketed_sweeps.append((usd_val, is_sell_taker)) w_addr = t.get("taker_wallet") if w_addr and isinstance(w_addr, str): wf = wallet_flows.setdefault(w_addr, [0.0, 0.0]) if is_sell_taker: wf[1] += usd_val else: wf[0] += usd_val except Exception: continue # Neutralize absorbed aggressive TWAP flow when opposite Limit Iceberg absorption confirms eff_twap_score = 0 if (absorption_score * twap_score < 0) else twap_score if not parsed_trades: fallback_buy_pct = ( round(twap_buy_usd / (twap_buy_usd + twap_sell_usd) * 100.0, 1) if (twap_buy_usd + twap_sell_usd) > 0 else 50.0 ) fallback_ratio = ( round(twap_buy_usd / twap_sell_usd, 2) if twap_sell_usd > 0 else (99.0 if twap_buy_usd > 0 else 1.0) ) comp_score = max(-2, min(2, eff_twap_score + absorption_score + hl_pos_score)) if absorption_type in ("BULLISH_ICEBERG_ABSORPTION", "BULLISH_L2_ICEBERG_REFILL") and comp_score >= 0: verdict = f"🛡️ Iceberg Absorption Paus (Bullish): {absorption_note}" elif absorption_type in ("BEARISH_ICEBERG_ABSORPTION", "BEARISH_L2_ICEBERG_REFILL") and comp_score <= 0: verdict = f"🛡️ Iceberg Absorption Paus (Bearish): {absorption_note}" elif twap_bias == "WHALE_TWAP_LONG_BUILDUP": verdict = f"Akumulasi TWAP Paus (Klines): Net Taker Buy +${twap_delta_usd:,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%." elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP": verdict = f"Distribusi TWAP Paus (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f} disertai ekspansi OI {eff_oi_chg:+.2f}%." elif twap_bias == "TWAP_BUY_ACCUMULATION": verdict = f"Akumulasi TWAP Beli (Klines): Net Taker Buy +${twap_delta_usd:,.0f}." elif twap_bias == "TWAP_SELL_DISTRIBUTION": verdict = f"Distribusi TWAP Jual (Klines): Net Taker Sell -${abs(twap_delta_usd):,.0f}." else: verdict = ( "Order Flow Agregat Seimbang (Belum Ada Data Trades)" if not trades else "Order Flow Agregat Seimbang" ) return { "taker_buy_vol_usd": round(twap_buy_usd, 2), "taker_sell_vol_usd": round(twap_sell_usd, 2), "total_vol_usd": round(twap_buy_usd + twap_sell_usd, 2), "taker_buy_pct": fallback_buy_pct, "taker_ratio": fallback_ratio, "whale_buy_count": 0, "whale_sell_count": 0, "whale_buy_vol_usd": 0.0, "whale_sell_vol_usd": 0.0, "largest_trade_usd": 0.0, "largest_trade_side": "NONE", "dynamic_threshold_usd": round(adv_floor_usd, 2), "net_whale_threshold_usd": round(adv_floor_usd, 2), "adv_24h_usd": round(adv_24h_usd, 2), "adv_floor_usd": round(adv_floor_usd, 2), "avg_trade_size_usd": round(avg_trade_size_usd, 2), "long_liq_usd": round(long_liq_usd, 2), "short_liq_usd": round(short_liq_usd, 2), "long_liq_count": long_liq_count, "short_liq_count": short_liq_count, "sweep_buy_count": 0, "sweep_sell_count": 0, "sweep_buy_vol_usd": 0.0, "sweep_sell_vol_usd": 0.0, "largest_sweep_usd": 0.0, "twap_bias": twap_bias, "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1), "twap_net_delta_usd": round(twap_delta_usd, 2), "twap_delta_ratio": round(twap_delta_ratio, 4), "twap_tot_usd": round(twap_tot_usd, 2), "whale_block_score": 0, "twap_score": eff_twap_score, "absorption_score": absorption_score, "onchain_score": hl_pos_score, "hl_smart_whale_score": hl_pos_score, "absorption_type": absorption_type, "absorption_note": absorption_note, "is_iceberg_absorbing": absorption_score != 0, "onchain_whale_wallets": 0, "onchain_buy_vol_usd": 0.0, "onchain_sell_vol_usd": 0.0, "top_whale_wallet_usd": 0.0, "top_whale_wallet_side": "NONE", "whale_position_long_ratio": whale_pos_lr, "retail_account_long_ratio": retail_acc_lr, "smart_money_delta": sm_delta, "whale_composite_score": comp_score, "whale_venues_bull": 0, "whale_venues_bear": 0, "cross_venue_whale_aligned": False, "flow_verdict": verdict, } total_vol = taker_buy_vol + taker_sell_vol buy_pct = (taker_buy_vol / total_vol * 100.0) if total_vol > 0 else 50.0 if taker_sell_vol > 0: taker_ratio = taker_buy_vol / taker_sell_vol elif taker_buy_vol > 0: taker_ratio = 99.0 else: taker_ratio = 1.0 # Dynamic Whale Threshold scaled to ADV absolute floor + per-pair trade distribution + notional volume: sorted_vals = sorted(v for v, _ in parsed_trades) n_trades = len(sorted_vals) if n_trades >= 20: p_idx = min(n_trades - 1, int(0.95 * (n_trades - 1))) dist_anchor = sorted_vals[p_idx] else: dist_anchor = sorted_vals[n_trades // 2] threshold = max(adv_floor_usd, dist_anchor, total_vol * 0.015) net_whale_threshold = max(adv_floor_usd, total_vol * 0.025) whale_buys = [v for v, is_sell in parsed_trades if (not is_sell) and v >= threshold] whale_sells = [v for v, is_sell in parsed_trades if is_sell and v >= threshold] whale_buy_vol = sum(whale_buys) whale_sell_vol = sum(whale_sells) # Reconstructed sweep orders (coalesces split fills at identical tick timestamp) all_sweeps = [(val, is_sell) for (_, _, is_sell), val in sweep_buckets.items()] + unbucketed_sweeps sweep_buys = [v for v, is_sell in all_sweeps if (not is_sell) and v >= threshold] sweep_sells = [v for v, is_sell in all_sweeps if is_sell and v >= threshold] sweep_buy_vol = sum(sweep_buys) sweep_sell_vol = sum(sweep_sells) largest_sweep_usd = max((v for v, _ in all_sweeps), default=0.0) # Hyperliquid On-Chain Single-Wallet Whale Accumulation onchain_whale_wallets = 0 onchain_buy_vol_usd = 0.0 onchain_sell_vol_usd = 0.0 top_whale_wallet_usd = 0.0 top_whale_wallet_side = "NONE" for w_buy_u, w_sell_u in wallet_flows.values(): net_w = w_buy_u - w_sell_u if abs(net_w) >= max(10_000.0, threshold): onchain_whale_wallets += 1 if net_w > 0: onchain_buy_vol_usd += net_w else: onchain_sell_vol_usd += abs(net_w) if abs(net_w) > top_whale_wallet_usd: top_whale_wallet_usd = abs(net_w) top_whale_wallet_side = "BUY" if net_w > 0 else "SELL" onchain_score = 0 if onchain_buy_vol_usd > onchain_sell_vol_usd * 1.4 and onchain_buy_vol_usd >= threshold: onchain_score = 1 elif onchain_sell_vol_usd > onchain_buy_vol_usd * 1.4 and onchain_sell_vol_usd >= threshold: onchain_score = -1 # Incorporate Hyperliquid tracked Smart Whale open-position bias (single Hyperliquid venue vote) if onchain_score == 0 and hl_pos_score != 0: onchain_score = hl_pos_score # Per-venue independent evaluation when >= 2 venues present active_trade_venues = [v for v, trs in venue_parsed.items() if v != "default" and trs] if not active_trade_venues and "default" in venue_parsed: active_trade_venues = ["default"] non_hl_bull = 0 non_hl_bear = 0 hl_block_bull = False hl_block_bear = False if len(active_trade_venues) >= 2: for v in active_trade_venues: v_trs = venue_parsed[v] v_vals = sorted(val for val, _ in v_trs) v_n = len(v_vals) v_vol = sum(v_vals) if v_n >= 20: v_p_idx = min(v_n - 1, int(0.95 * (v_n - 1))) v_anchor = v_vals[v_p_idx] else: v_anchor = v_vals[v_n // 2] if v_n > 0 else 0.0 v_adv = (venue_adv_usd or {}).get(v, 0.0) v_adv_floor = max(5000.0, min(150_000.0, v_adv * 0.00005)) if v_adv > 0 else max(5000.0, adv_floor_usd * 0.35) min_venue_thresh = max(v_adv_floor, v_anchor, v_vol * 0.015) v_buys = [val for val, is_sell in v_trs if (not is_sell) and val >= min_venue_thresh] v_sells = [val for val, is_sell in v_trs if is_sell and val >= min_venue_thresh] v_sw_buys = [val for (ven, _, is_sell), val in sweep_buckets.items() if ven == v and (not is_sell) and val >= min_venue_thresh] v_sw_sells = [val for (ven, _, is_sell), val in sweep_buckets.items() if ven == v and is_sell and val >= min_venue_thresh] v_eff_buy = max(sum(v_buys), sum(v_sw_buys)) v_eff_sell = max(sum(v_sells), sum(v_sw_sells)) if v_eff_buy >= min_venue_thresh and v_eff_buy > v_eff_sell * 1.2: if v == "hyperliquid": hl_block_bull = True else: non_hl_bull += 1 if v_eff_sell >= min_venue_thresh and v_eff_sell > v_eff_buy * 1.2: if v == "hyperliquid": hl_block_bear = True else: non_hl_bear += 1 else: eff_w_buy = max(whale_buy_vol, sweep_buy_vol) eff_w_sell = max(whale_sell_vol, sweep_sell_vol) is_only_hl = active_trade_venues == ["hyperliquid"] if eff_w_buy >= threshold and eff_w_buy > eff_w_sell * 1.4: if is_only_hl: hl_block_bull = True else: non_hl_bull = 1 elif eff_w_sell >= threshold and eff_w_sell > eff_w_buy * 1.4: if is_only_hl: hl_block_bear = True else: non_hl_bear = 1 # Treat Hyperliquid (DEX block trades + on-chain wallet flow) as a single venue vote to prevent self-confirmation whale_venues_bull = non_hl_bull + (1 if (hl_block_bull or onchain_score > 0) else 0) whale_venues_bear = non_hl_bear + (1 if (hl_block_bear or onchain_score < 0) else 0) cross_venue_whale_aligned = (whale_venues_bull >= 2 or whale_venues_bear >= 2) # Also check live tape Iceberg Absorption if not already triggered by klines if absorption_score == 0 and merged_ohlcv and total_vol >= 25_000.0 and eff_oi_chg >= 0.25: ref_b = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or []) if ref_b: lb = ref_b[-1] l_high = float(lb.get("high", 0.0) or 0.0) l_low = float(lb.get("low", 0.0) or 0.0) l_close = float(lb.get("close", 0.0) or 0.0) rng = l_high - l_low min_rng = l_close * 0.001 if l_close > 0 else 0.0 c_pos = ((l_close - l_low) / rng) if (rng > 0 and rng >= min_rng) else 0.5 if rng >= min_rng and buy_pct <= 40.0 and c_pos >= 0.60: absorption_type = "BULLISH_ICEBERG_ABSORPTION" absorption_note = f"Jualan agresif ({100.0 - buy_pct:.0f}% Taker Sell) diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%" absorption_score = 1 elif buy_pct >= 60.0 and c_pos <= 0.40: absorption_type = "BEARISH_ICEBERG_ABSORPTION" absorption_note = f"Beli agresif ({buy_pct:.0f}% Taker Buy) ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%" absorption_score = -1 # Decontaminate forced liquidations from aggressive whale order flow using time-window alignment # (prevents stale 15m liquidation events from erasing fresh organic whale flow in a 5m trade window) window_long_liq_usd = 0.0 window_short_liq_usd = 0.0 for l_ts, is_long, l_usd in feed_liq_events: if min_trade_ts > 0 and l_ts > 0: if not ((min_trade_ts - 5_000) <= l_ts <= (max_trade_ts + 5_000)): continue if is_long: window_long_liq_usd += l_usd else: window_short_liq_usd += l_usd clean_whale_buy = max(0.0, whale_buy_vol - window_short_liq_usd) clean_whale_sell = max(0.0, whale_sell_vol - window_long_liq_usd) clean_sweep_buy = max(0.0, sweep_buy_vol - window_short_liq_usd) clean_sweep_sell = max(0.0, sweep_sell_vol - window_long_liq_usd) # Composite Whale Score [-2, +2] eff_whale_buy = max(clean_whale_buy, clean_sweep_buy) eff_whale_sell = max(clean_whale_sell, clean_sweep_sell) block_score = 0 if eff_whale_buy > eff_whale_sell * 1.4 and eff_whale_buy >= threshold: block_score = 2 if eff_whale_buy >= threshold * 3.0 and len(sweep_buys) >= 2 else 1 elif eff_whale_sell > eff_whale_buy * 1.4 and eff_whale_sell >= threshold: block_score = -2 if eff_whale_sell >= threshold * 3.0 and len(sweep_sells) >= 2 else -1 # Neutralize absorbed aggressive block/TWAP flow when passive Iceberg absorption confirms eff_block_score = 0 if (absorption_score * block_score < 0) else block_score eff_twap_score_main = 0 if (absorption_score * twap_score < 0) else twap_score whale_composite_score = max( -2, min(2, eff_block_score + eff_twap_score_main + absorption_score + onchain_score), ) # Single-venue block-only cap: # When >= 2 trade venues active and unconfirmed by cross-venue / TWAP / iceberg / onchain if ( len(active_trade_venues) >= 2 and not cross_venue_whale_aligned and eff_twap_score_main == 0 and absorption_score == 0 and onchain_score == 0 ): whale_composite_score = max(-1, min(1, whale_composite_score)) largest_val, largest_is_sell = max(parsed_trades, key=lambda x: x[0]) largest_side = "SELL" if largest_is_sell else "BUY" if absorption_type in ("BULLISH_ICEBERG_ABSORPTION", "BULLISH_L2_ICEBERG_REFILL") and whale_composite_score >= 0: verdict = f"🛡️ Iceberg Absorption Paus (Bullish): {absorption_note or f'Jualan agresif diserap Limit Buy Wall + OI naik {eff_oi_chg:+.2f}%!'}" elif absorption_type in ("BEARISH_ICEBERG_ABSORPTION", "BEARISH_L2_ICEBERG_REFILL") and whale_composite_score <= 0: verdict = f"🛡️ Iceberg Absorption Paus (Bearish): {absorption_note or f'Beli agresif ditahan Limit Sell Wall + OI naik {eff_oi_chg:+.2f}%!'}" elif clean_whale_buy >= threshold and clean_whale_sell <= 0.0 and clean_sweep_sell <= 0.0: verdict = f"Paus Agresif Sisi Beli: {len(whale_buys)} block buy (${clean_whale_buy:,.0f}) tanpa block sell tandingan!" elif clean_whale_sell >= threshold and clean_whale_buy <= 0.0 and clean_sweep_buy <= 0.0: verdict = f"Paus Agresif Sisi Jual: {len(whale_sells)} block sell (${clean_whale_sell:,.0f}) tanpa block buy tandingan!" elif eff_whale_buy > eff_whale_sell * 1.5 and eff_whale_buy >= threshold: verdict = f"Dominasi Block/Sweep Buy: Whale buy ${eff_whale_buy:,.0f} ({max(len(whale_buys), len(sweep_buys))} orders) vs sell ${eff_whale_sell:,.0f}." elif eff_whale_sell > eff_whale_buy * 1.5 and eff_whale_sell >= threshold: verdict = f"Dominasi Block/Sweep Sell: Whale sell ${eff_whale_sell:,.0f} ({max(len(whale_sells), len(sweep_sells))} orders) vs buy ${eff_whale_buy:,.0f}." elif twap_bias == "WHALE_TWAP_LONG_BUILDUP": verdict = f"Akumulasi TWAP Paus: Net Taker Buy +${twap_delta_usd:,.0f} + OI naik {eff_oi_chg:+.2f}%." elif twap_bias == "WHALE_TWAP_SHORT_BUILDUP": verdict = f"Distribusi TWAP Paus: Net Taker Sell -${abs(twap_delta_usd):,.0f} + OI naik {eff_oi_chg:+.2f}%." elif twap_bias == "TWAP_BUY_ACCUMULATION": verdict = f"Akumulasi TWAP Beli: Net Taker Buy +${twap_delta_usd:,.0f} ({50.0 + twap_delta_ratio * 50.0:.1f}% Taker Buy)." elif twap_bias == "TWAP_SELL_DISTRIBUTION": verdict = f"Distribusi TWAP Jual: Net Taker Sell -${abs(twap_delta_usd):,.0f} ({50.0 - twap_delta_ratio * 50.0:.1f}% Taker Sell)." elif buy_pct >= 58.0: verdict = f"Taker Buy Dominan: {buy_pct:.1f}% volume taker agresif beli (Rasio {taker_ratio:.2f}x)." elif buy_pct <= 42.0: verdict = f"Taker Sell Dominan: {100.0 - buy_pct:.1f}% volume taker agresif jual (Rasio {taker_ratio:.2f}x)." else: verdict = f"Order Flow Seimbang: Taker buy {buy_pct:.1f}% vs sell {100.0 - buy_pct:.1f}%." return { "taker_buy_vol_usd": round(taker_buy_vol, 2), "taker_sell_vol_usd": round(taker_sell_vol, 2), "total_vol_usd": round(total_vol, 2), "taker_buy_pct": round(buy_pct, 1), "taker_ratio": round(taker_ratio, 2), "whale_buy_count": len(whale_buys), "whale_sell_count": len(whale_sells), "whale_buy_vol_usd": round(clean_whale_buy, 2), "whale_sell_vol_usd": round(clean_whale_sell, 2), "largest_trade_usd": round(largest_val, 2), "largest_trade_side": largest_side, "dynamic_threshold_usd": round(threshold, 2), "net_whale_threshold_usd": round(net_whale_threshold, 2), "adv_24h_usd": round(adv_24h_usd, 2), "adv_floor_usd": round(adv_floor_usd, 2), "avg_trade_size_usd": round(avg_trade_size_usd, 2), "long_liq_usd": round(long_liq_usd, 2), "short_liq_usd": round(short_liq_usd, 2), "long_liq_count": long_liq_count, "short_liq_count": short_liq_count, "sweep_buy_count": len(sweep_buys), "sweep_sell_count": len(sweep_sells), "sweep_buy_vol_usd": round(clean_sweep_buy, 2), "sweep_sell_vol_usd": round(clean_sweep_sell, 2), "largest_sweep_usd": round(largest_sweep_usd, 2), "twap_bias": twap_bias, "twap_buy_pct": round(50.0 + twap_delta_ratio * 50.0, 1), "twap_net_delta_usd": round(twap_delta_usd, 2), "twap_delta_ratio": round(twap_delta_ratio, 4), "twap_tot_usd": round(twap_tot_usd, 2), "whale_block_score": eff_block_score, "twap_score": eff_twap_score_main, "absorption_score": absorption_score, "onchain_score": onchain_score, "hl_smart_whale_score": hl_pos_score, "absorption_type": absorption_type, "absorption_note": absorption_note, "is_iceberg_absorbing": absorption_score != 0, "onchain_whale_wallets": onchain_whale_wallets, "onchain_buy_vol_usd": round(onchain_buy_vol_usd, 2), "onchain_sell_vol_usd": round(onchain_sell_vol_usd, 2), "top_whale_wallet_usd": round(top_whale_wallet_usd, 2), "top_whale_wallet_side": top_whale_wallet_side, "whale_position_long_ratio": whale_pos_lr, "retail_account_long_ratio": retail_acc_lr, "smart_money_delta": sm_delta, "whale_composite_score": whale_composite_score, "whale_venues_bull": whale_venues_bull, "whale_venues_bear": whale_venues_bear, "cross_venue_whale_aligned": cross_venue_whale_aligned, "flow_verdict": verdict, } def _compute_liquidity_guard( orderbook: dict | None, mark_price: float, skew_data: dict | None = None, ) -> dict[str, Any]: """ Spread & tight (±1.5%) depth guardrail on top-of-book liquidity. - Graceful NO_BOOK_DATA pass when orderbook is absent/empty (e.g. OHLCV backtests). - Hard ILLIQUID_OR_WIDE_SPREAD veto when book is one-sided, crossed (best_bid >= best_ask), spread > 50 bps, or tight ±1.5% depth < $25,000. - WIDE_SPREAD_CAUTION when 25 bps < spread <= 50 bps. """ if not orderbook or not isinstance(orderbook, dict): return { "passed": True, "status": "NO_BOOK_DATA", "spread_bps": None, "depth_usd": 0.0, } bids = orderbook.get("bids") or [] asks = orderbook.get("asks") or [] if len(bids) == 0 and len(asks) == 0: return { "passed": True, "status": "NO_BOOK_DATA", "spread_bps": None, "depth_usd": 0.0, } try: best_bid = float(bids[0][0]) if bids else 0.0 except (ValueError, TypeError, IndexError): best_bid = 0.0 try: best_ask = float(asks[0][0]) if asks else 0.0 except (ValueError, TypeError, IndexError): best_ask = 0.0 if best_bid <= 0 or best_ask <= 0 or best_bid >= best_ask: return { "passed": False, "status": "ILLIQUID_OR_WIDE_SPREAD", "spread_bps": None, "depth_usd": 0.0, } mid_px = (best_bid + best_ask) / 2.0 spread_bps = ((best_ask - best_bid) / mid_px) * 10_000.0 ref_px = mark_price if (mark_price and mark_price > 0) else mid_px if skew_data is None: skew_data = _compute_orderbook_skew(orderbook, ref_px) if "tight_bid_depth_usd" in skew_data or "tight_ask_depth_usd" in skew_data: tight_depth_usd = float(skew_data.get("tight_bid_depth_usd", 0.0) or 0.0) + float( skew_data.get("tight_ask_depth_usd", 0.0) or 0.0 ) else: recomputed = _compute_orderbook_skew(orderbook, ref_px) tight_depth_usd = float(recomputed.get("tight_bid_depth_usd", 0.0) or 0.0) + float( recomputed.get("tight_ask_depth_usd", 0.0) or 0.0 ) if spread_bps > 50.0 or tight_depth_usd < 25_000.0: return { "passed": False, "status": "ILLIQUID_OR_WIDE_SPREAD", "spread_bps": round(spread_bps, 2), "depth_usd": round(tight_depth_usd, 2), } if spread_bps > 25.0: return { "passed": True, "status": "WIDE_SPREAD_CAUTION", "spread_bps": round(spread_bps, 2), "depth_usd": round(tight_depth_usd, 2), } return { "passed": True, "status": "LIQUID", "spread_bps": round(spread_bps, 2), "depth_usd": round(tight_depth_usd, 2), } def _compute_anti_chasing_guard(direction: str, stretch_atr: float) -> dict[str, Any]: """ Evaluates whether a directional signal is chasing an already over-extended vertical move relative to EMA(9) in ATR(14) units: - |stretch| > 2.8 in signal direction -> blocked = True ("ANTI_CHASING_EXTREME") - 2.2 < |stretch| <= 2.8 in signal direction -> penalty = -1 (+1 for SHORT) ("ANTI_CHASING_PENALTY") - Otherwise -> "CLEAN" """ s = float(stretch_atr or 0.0) if direction == "LONG" and s > 0: if s > 2.8: return {"blocked": True, "penalty": 0, "status": "ANTI_CHASING_EXTREME", "stretch_atr": round(s, 3)} if s > 2.2: return {"blocked": False, "penalty": -1, "status": "ANTI_CHASING_PENALTY", "stretch_atr": round(s, 3)} elif direction == "SHORT" and s < 0: if abs(s) > 2.8: return {"blocked": True, "penalty": 0, "status": "ANTI_CHASING_EXTREME", "stretch_atr": round(s, 3)} if abs(s) > 2.2: return {"blocked": False, "penalty": 1, "status": "ANTI_CHASING_PENALTY", "stretch_atr": round(s, 3)} return {"blocked": False, "penalty": 0, "status": "CLEAN", "stretch_atr": round(s, 3)} def _compute_breakout_radar( direction: str, conviction: int, predictive_data: dict | None, oi_signal: dict | None, whale_flow: dict | None, extremes_data: dict | None = None, ) -> dict[str, Any]: """ Tier 3: Squeeze & Breakout Accumulation Radar. Detects pairs (especially NEUTRAL or consolidation phases) undergoing extreme volatility compression accompanied by silent Open Interest expansion, whale block order flow, or resting liquidity walls. """ pred = predictive_data or {} squeeze = pred.get("volatility_squeeze", {}) is_squeeze = bool(squeeze.get("is_squeeze", False)) raw_comp = squeeze.get("compression_ratio") comp_ratio = float(raw_comp) if raw_comp is not None else 1.0 squeeze_intensity = str(squeeze.get("squeeze_intensity", "NORMAL")) # Guard against flatline / dead candle artifact where ATR is 0 if comp_ratio <= 0.05: comp_ratio = 1.0 is_squeeze = False squeeze_intensity = "NORMAL" whale = whale_flow or {} taker_ratio = float(whale.get("taker_ratio", 1.0) or 1.0) whale_buy_vol = float(whale.get("whale_buy_vol_usd", 0.0) or 0.0) whale_sell_vol = float(whale.get("whale_sell_vol_usd", 0.0) or 0.0) net_whale_usd = whale_buy_vol - whale_sell_vol oi_val = (oi_signal or {}).get("oi_change_pct") oi_change_pct = float(oi_val) if oi_val is not None else 0.0 ob_skew = pred.get("orderbook_skew", {}) skew_ratio = float(ob_skew.get("skew_ratio", 0.0) or 0.0) # Accumulation & catalyst signals accumulation_signals = [] bull_bias_pts = 0 bear_bias_pts = 0 if abs(oi_change_pct) >= 1.5: if oi_change_pct > 0: accumulation_signals.append(f"Ekspansi OI +{oi_change_pct:.1f}%") else: accumulation_signals.append(f"Unwinding OI {oi_change_pct:.1f}%") whale_dyn_thresh = float(whale.get("dynamic_threshold_usd", 25000.0) or 25000.0) whale_net_thresh = float(whale.get("net_whale_threshold_usd", 15000.0) or 15000.0) whale_vol_floor = min(10000.0, whale_dyn_thresh) if whale_buy_vol > 0 or whale_sell_vol > 0: if net_whale_usd > whale_net_thresh or (whale_buy_vol > whale_sell_vol * 1.4 and whale_buy_vol > whale_vol_floor): bull_bias_pts += 2 accumulation_signals.append(f"Akumulasi Paus +${whale_buy_vol:,.0f}") elif net_whale_usd < -whale_net_thresh or (whale_sell_vol > whale_buy_vol * 1.4 and whale_sell_vol > whale_vol_floor): bear_bias_pts += 2 accumulation_signals.append(f"Distribusi Paus -${whale_sell_vol:,.0f}") if taker_ratio >= 1.25: bull_bias_pts += 1 accumulation_signals.append(f"Taker Buy {taker_ratio:.2f}x") elif taker_ratio <= 0.75: bear_bias_pts += 1 accumulation_signals.append(f"Taker Sell {taker_ratio:.2f}x") if skew_ratio >= 0.20: bull_bias_pts += 1 accumulation_signals.append("Bids Wall Dominan") elif skew_ratio <= -0.20: bear_bias_pts += 1 accumulation_signals.append("Asks Wall Dominan") if direction == "LONG" and conviction >= 3: bull_bias_pts += 1 elif direction == "SHORT" and conviction >= 3: bear_bias_pts += 1 # Stage classification (aligned with < 0.55 canonical squeeze threshold) is_compressed = is_squeeze or (comp_ratio < 0.55) if is_compressed: if len(accumulation_signals) >= 2 or abs(net_whale_usd) >= whale_dyn_thresh or abs(oi_change_pct) >= 2.5: squeeze_stage = "READY_TO_BURST" elif len(accumulation_signals) >= 1 or comp_ratio <= 0.50: squeeze_stage = "ACCUMULATING" else: squeeze_stage = "COILING" is_breakout_primed = True elif comp_ratio <= 0.80 and len(accumulation_signals) >= 2: squeeze_stage = "ACCUMULATING" is_breakout_primed = True else: squeeze_stage = "NORMAL" is_breakout_primed = False # Projected Direction if bull_bias_pts > bear_bias_pts: projected_dir = "BREAKOUT_UP" dir_label = "BULLISH BIAS" elif bear_bias_pts > bull_bias_pts: projected_dir = "BREAKOUT_DOWN" dir_label = "BEARISH BIAS" else: projected_dir = "COILING_NEUTRAL" dir_label = "EXPANSION PENDING" # Radar badge and summary if is_breakout_primed: if squeeze_stage == "READY_TO_BURST": radar_label = f"🚨 READY TO BURST [{dir_label}]" elif squeeze_stage == "ACCUMULATING": radar_label = f"⚡ ACCUMULATION [{dir_label}]" else: radar_label = f"🌀 COILING SQUEEZE" catalyst_str = ", ".join(accumulation_signals) if accumulation_signals else "Kompresi ATR ketat" catalyst_summary = f"Kompresi ATR {comp_ratio:.2f}x ({squeeze_intensity}). Katalis: {catalyst_str}. Siaga ledakan volatilitas dlm 1-4 jam." else: radar_label = "NORMAL VOLATILITY" catalyst_summary = f"Rentang volatilitas normal (Rasio ATR {comp_ratio:.2f}x)." return { "is_breakout_primed": is_breakout_primed, "radar_label": radar_label, "squeeze_stage": squeeze_stage, "projected_direction": projected_dir, "compression_ratio": round(comp_ratio, 3), "catalyst_summary": catalyst_summary, "catalysts": accumulation_signals, } # ───────────────────────────────────────────────────────────────────────────── # Main engine # ───────────────────────────────────────────────────────────────────────────── def _compute_kline_cvd_from_bars( bars: list[dict], base_signal: dict[str, Any] | None = None, allow_candle_proxy: bool = False, ) -> dict[str, Any] | None: """Derive directional taker CVD from OHLCV taker_buy_volume (or candle proxy in OHLCV-only replay).""" if not bars: return None base = dict(base_signal or {"value": 0.0, "score": 0, "rising": False, "label": "No Trade Data"}) tb_bars = [ b for b in bars if isinstance(b, dict) and b.get("taker_buy_volume") is not None and float(b.get("volume", 0.0) or 0.0) > 0 ] if tb_bars: net_delta = 0.0 tot_vol = 0.0 for b in tb_bars: v_tot = float(b.get("volume", 0.0) or 0.0) v_buy = max(0.0, min(v_tot, float(b.get("taker_buy_volume") or 0.0))) net_delta += (2.0 * v_buy) - v_tot tot_vol += v_tot if tot_vol > 0: ratio = net_delta / tot_vol buy_pct = 50.0 + ratio * 50.0 if ratio > 0.06: return {**base, "score": 1, "rising": True, "value": round(net_delta, 2), "label": f"Klines Taker CVD Bullish ({buy_pct:.1f}% Buy)"} if ratio < -0.06: return {**base, "score": -1, "rising": False, "value": round(net_delta, 2), "label": f"Klines Taker CVD Bearish ({buy_pct:.1f}% Buy)"} return {**base, "score": 0, "rising": net_delta >= 0, "value": round(net_delta, 2), "label": f"Klines Taker CVD Balanced ({buy_pct:.1f}% Buy)"} elif allow_candle_proxy: net_delta = 0.0 tot_vol = 0.0 for b in bars: if not isinstance(b, dict): continue o, h, l_val, c, v = b.get("open"), b.get("high"), b.get("low"), b.get("close"), b.get("volume") if None in (o, h, l_val, c): continue try: o_f, h_f, l_f, c_f = float(o), float(h), float(l_val), float(c) v_f = float(v) if v is not None else 0.0 except (TypeError, ValueError): continue rng = max(h_f - l_f, 1e-9) net_delta += ((c_f - o_f) / rng) * v_f tot_vol += v_f if tot_vol > 0: ratio = net_delta / tot_vol if ratio > 0.15: return {**base, "score": 1, "rising": True, "label": "OHLCV Candle Volume Delta Bullish"} if ratio < -0.15: return {**base, "score": -1, "rising": False, "label": "OHLCV Candle Volume Delta Bearish"} return {**base, "score": 0, "rising": net_delta >= 0, "label": "OHLCV Candle Volume Delta Neutral"} return None class SignalEngine: """ Computes all signals for a single symbol from raw collected data. """ def __init__( self, l2_tracker: L2OrderbookTracker | None = None, hl_tracker: HyperliquidWhaleTracker | None = None, ) -> None: self._l2_tracker = l2_tracker self._hl_tracker = hl_tracker def compute( self, raw: dict[str, Any], horizon_thresholds: dict[str, int] | None = None, market_context: dict[str, Any] | None = None, now_ts: float | None = None, ) -> dict[str, Any]: """ Parameters ---------- raw: output from DataCollector.collect() Returns ------- Full signal dict ready for DB storage and WS broadcast. """ symbol = raw["symbol"] binance = raw.get("binance") bybit = raw.get("bybit") okx = raw.get("okx") bitget = raw.get("bitget") hyperliquid = raw.get("hyperliquid") has_spot = bool(raw.get("has_spot", False)) if any(ex and ex.get("spot_trades") for ex in (binance, bybit, okx, bitget)): has_spot = True # ── 1. Individual signals ────────────────────────────────────────── funding_signal = _compute_funding_rate(binance, bybit, okx, hyperliquid, bitget) oi_signal = _compute_oi_divergence(binance, bybit, okx, bitget, hyperliquid) # Institutional Alpha #2: Hyperliquid On-Chain DEX Whale Flow (deduplicated against CEX consensus) cex_fr_sig = _compute_funding_rate(binance, bybit, okx, None, bitget) cex_basis_sig = _compute_basis(binance, bybit, okx, bitget, None) hl_signal = _compute_hyperliquid_signal( hyperliquid, cex_funding_rate=cex_fr_sig.get("value"), cex_basis_pct=cex_basis_sig.get("value"), ) # Determine canonical reference mark price early to normalize 1000x multiplier discrepancies binance_mark = ( binance["mark_price_data"]["mark_price"] if binance and binance.get("mark_price_data") else None ) bybit_mark = ( bybit["mark_price_data"]["mark_price"] if bybit and bybit.get("mark_price_data") else None ) bitget_mark = ( bitget["mark_price_data"]["mark_price"] if bitget and bitget.get("mark_price_data") else None ) okx_mark = ( okx["mark_price_data"]["mark_price"] if okx and okx.get("mark_price_data") else None ) hl_mark_px = hyperliquid.get("mark_price") if hyperliquid else None ref_mark_px = binance_mark or bybit_mark or bitget_mark or okx_mark or hl_mark_px or 0.0 # Institutional Alpha #1: Spot vs Futures CVD (Organic vs Leverage Trap) spot_futures_signal = _compute_spot_futures_cvd( binance, bybit, okx_data=okx, bitget_data=bitget, ref_mark_px=ref_mark_px ) if not has_spot: spot_futures_signal["label"] = "⚠️ PERP ONLY (Tidak Ada di Spot - Pasar Sintetis)" spot_futures_signal["score"] = 0 # CVD & Whale Order Flow: combine Binance, Bybit, OKX, Bitget, and Hyperliquid (normalized to canonical contract scale). trades = [] liquidations = [] for v_name, v_data, v_mark in [ ("binance", binance, binance_mark), ("bybit", bybit, bybit_mark), ("okx", okx, okx_mark), ("bitget", bitget, bitget_mark), ("hyperliquid", hyperliquid, hl_mark_px), ]: if v_data: sample_px = v_mark if not sample_px: if v_data.get("trades"): sample_px = v_data["trades"][0].get("price") elif v_data.get("liquidations"): sample_px = v_data["liquidations"][0].get("price") t_scale = _get_multiplier_scale(sample_px, ref_mark_px) if v_data.get("trades"): for nt in _normalize_trades_scale(v_data["trades"], t_scale): trades.append({**nt, "venue": v_name}) if v_data.get("liquidations"): for nl in _normalize_liquidations_scale(v_data["liquidations"], t_scale): liquidations.append({**nl, "venue": v_name}) cvd_signal = _compute_cvd(trades) # Institutional Alpha #3: Triangulation Consensus across Binance + Bybit + OKX + Bitget + Hyperliquid cross_signal = _compute_cross_exchange(binance, bybit, okx, bitget, hyperliquid) ls_signal = _compute_ls_ratio(binance, bybit, okx, bitget) basis_signal = _compute_basis(binance, bybit, okx, bitget, hyperliquid) # ── 2. MTF analysis ──────────────────────────────────────────────── # Merge OHLCV from exchanges (prefer Binance, then Bybit, then OKX, then Bitget) # and normalize each timeframe's price & volume scale against ref_mark_px. merged_ohlcv: dict[str, list] = {} ohlcv_sources = [ (binance, binance_mark), (bybit, bybit_mark), (okx, okx_mark), (bitget, bitget_mark), ] for tf in ["1m", "5m", "15m", "1h", "4h", "1d"]: candles = None src_px = None for ex_data, ex_mark in ohlcv_sources: cand = ex_data.get("ohlcv", {}).get(tf) if ex_data else None if cand: candles = cand src_px = ex_mark if not src_px: try: src_px = float(cand[-1].get("close") or 0.0) or None except (TypeError, ValueError, AttributeError): src_px = None break if candles: c_scale = _get_multiplier_scale(src_px, ref_mark_px) merged_ohlcv[tf] = _normalize_candles_scale(candles, c_scale) # Backfill taker_buy_volume on 15m and 1h when primary candle feed lacks it for tf in ("15m", "1h"): target_candles = merged_ohlcv.get(tf) if target_candles and not any(c.get("taker_buy_volume") is not None for c in target_candles): for aux_data, aux_mark in ohlcv_sources: aux_cand = aux_data.get("ohlcv", {}).get(tf) if aux_data else None if aux_cand and any(c.get("taker_buy_volume") is not None for c in aux_cand): aux_scale = _get_multiplier_scale(aux_mark, ref_mark_px) norm_aux = _normalize_candles_scale(aux_cand, aux_scale) aux_by_ts = { int(c.get("timestamp") or c.get("time") or 0): c for c in norm_aux if (c.get("timestamp") or c.get("time")) } for b in target_candles: ts = int(b.get("timestamp") or b.get("time") or 0) aux_c = aux_by_ts.get(ts) if aux_c and aux_c.get("taker_buy_volume") is not None: aux_tb = float(aux_c["taker_buy_volume"]) aux_v = float(aux_c.get("volume", 0.0) or 0.0) b_v = float(b.get("volume", 0.0) or 0.0) if aux_v > 0 and b_v > 0: b["taker_buy_volume"] = min(b_v, max(0.0, (aux_tb / aux_v) * b_v)) else: b["taker_buy_volume"] = min(b_v, max(0.0, aux_tb)) if b_v > 0 else max(0.0, aux_tb) if any(c.get("taker_buy_volume") is not None for c in target_candles): break mtf_result = mtf_analyzer.analyze(merged_ohlcv) if not trades: ref_cvd_bars = (merged_ohlcv.get("15m") or merged_ohlcv.get("1h") or [])[-10:] kline_cvd = _compute_kline_cvd_from_bars( ref_cvd_bars, base_signal=cvd_signal, allow_candle_proxy=bool(horizon_thresholds is not None), ) if kline_cvd is not None: cvd_signal = kline_cvd # Independent macro CVD for swing horizon (4h[-8:] -> 1h[-12:]) so micro 15m/tick tape does not distort swing swing_cvd_bars = (merged_ohlcv.get("4h") or merged_ohlcv.get("1h") or [])[-8:] swing_kline_cvd = _compute_kline_cvd_from_bars( swing_cvd_bars, base_signal=cvd_signal, allow_candle_proxy=bool(horizon_thresholds is not None), ) swing_cvd_signal = swing_kline_cvd if swing_kline_cvd is not None else cvd_signal active_tf = mtf_result["active_timeframe"] active_struct = mtf_result["structure_per_tf"].get(active_tf, "unknown") ms_signal = { "tf": active_tf, "structure": active_struct, "structure_per_tf": mtf_result["structure_per_tf"], "score": mtf_result["score"], "label": mtf_result["label"], "market_condition": mtf_result["market_condition"], "value": f"{active_struct} ({active_tf.upper()})", } # ── 3. Fake detector ─────────────────────────────────────────────── ohlcv_1m = merged_ohlcv.get("1m", []) ohlcv_5m = merged_ohlcv.get("5m", []) # CVD delta trend matches price direction? price_up = False if merged_ohlcv.get("5m") and len(merged_ohlcv["5m"]) >= 2: price_up = merged_ohlcv["5m"][-1]["close"] > merged_ohlcv["5m"][-2]["close"] # Check if CVD momentum aligns with price momentum (live trade feed OR directional Klines taker CVD fallback) has_cvd_data = ( (bool(trades) or int(cvd_signal.get("score", 0) or 0) != 0) and cvd_signal.get("label") not in ("No Trade Data", "No Data") ) if has_cvd_data: cvd_rising = cvd_signal.get("rising", True) cvd_matches_price = (price_up == cvd_rising) else: cvd_matches_price = True # Do not falsely flag absorption if no trade feed # Consolidate orderbook depth across all available exchanges (Cross-Exchange Global Liquidity Pool) # Normalizes 1000x contract scale per venue before merging bids/asks so depth skew is never distorted ob_venue_pairs = [ (binance.get("orderbook") if binance else None, binance_mark), (bybit.get("orderbook") if bybit else None, bybit_mark), (okx.get("orderbook") if okx else None, okx_mark), (bitget.get("orderbook") if bitget else None, bitget_mark), (hyperliquid.get("orderbook") if hyperliquid else None, hl_mark_px), ] valid_obs = [] for raw_ob, v_px in ob_venue_pairs: if raw_ob and isinstance(raw_ob, dict) and (len(raw_ob.get("bids", [])) > 0 or len(raw_ob.get("asks", [])) > 0): probe_px = v_px if not probe_px: try: if raw_ob.get("bids"): probe_px = float(raw_ob["bids"][0][0]) elif raw_ob.get("asks"): probe_px = float(raw_ob["asks"][0][0]) except (ValueError, TypeError, IndexError): probe_px = None ob_scale = _get_multiplier_scale(probe_px, ref_mark_px) valid_obs.append(_normalize_orderbook_scale(raw_ob, ob_scale)) if valid_obs: merged_bids = [] merged_asks = [] for ob in valid_obs: merged_bids.extend(ob.get("bids", [])) merged_asks.extend(ob.get("asks", [])) # Sort consolidated orderbook: bids descending (highest price first), asks ascending (lowest price first) try: merged_bids.sort(key=lambda x: float(x[0]), reverse=True) merged_asks.sort(key=lambda x: float(x[0]), reverse=False) except Exception: pass orderbook = { "bids": merged_bids, "asks": merged_asks, "venues_count": len(valid_obs), } else: orderbook = None bybit_mark_aligned = ( bybit_mark * _get_multiplier_scale(bybit_mark, binance_mark) if (bybit_mark and binance_mark) else bybit_mark ) # Build multi-exchange scaled marks for cross-exchange divergence monitoring scaled_venue_marks: dict[str, float] = {} for ex_name, ex_mark in [ ("binance", binance_mark), ("bybit", bybit_mark), ("okx", okx_mark), ("bitget", bitget_mark), ("hyperliquid", hl_mark_px), ]: if ex_mark and ex_mark > 0: s_scale = _get_multiplier_scale(ex_mark, ref_mark_px) scaled_venue_marks[ex_name] = ex_mark * s_scale # ── 3.5 Pre-calculate Canonical Mark Price & Real-Time Microstructure ─ mark_price = ( binance_mark or bybit_mark or bitget_mark or ((okx.get("mark_price_data") or {}).get("mark_price") if okx else None) or (hyperliquid.get("mark_price") if hyperliquid else None) or 0.0 ) if mark_price <= 0 and merged_ohlcv: for tf in ["15m", "1h", "5m"]: bars = merged_ohlcv.get(tf) or [] for bar in reversed(bars): raw_px = bar.get("close") if isinstance(bar, dict) else None if raw_px is None: continue try: candidate_px = float(raw_px) except (TypeError, ValueError): continue if candidate_px > 0: mark_price = candidate_px break if mark_price > 0: break exchange_candles = { "binance": binance.get("ohlcv") if binance else None, "bybit": bybit.get("ohlcv") if bybit else None, "okx": okx.get("ohlcv") if okx else None, "bitget": bitget.get("ohlcv") if bitget else None, "hyperliquid": hyperliquid.get("ohlcv") if hyperliquid else None, } adv_24h_usd, venue_adv_usd = _compute_adv_24h_usd( binance=binance, bybit=bybit, okx=okx, bitget=bitget, hyperliquid=hyperliquid, merged_ohlcv=merged_ohlcv, symbol=symbol, mark_price=mark_price, ) adv_floor_usd = max(5000.0, min(250_000.0, adv_24h_usd * 0.00005)) if adv_24h_usd > 0 else 5000.0 # Update and evaluate L2 orderbook tracker (isolated instance when injected, e.g. backtester) l2_tracker = self._l2_tracker if self._l2_tracker is not None else get_l2_tracker() eff_now_ts = now_ts if now_ts is not None else raw.get("replay_now_ts") if orderbook and mark_price > 0: l2_tracker.update_book( symbol, orderbook.get("bids", []), orderbook.get("asks", []), mark_price=mark_price, now_ts=eff_now_ts, ) for t in trades: is_sell = bool(t.get("is_buyer_maker", False)) or (str(t.get("side", "")).lower() == "sell") t_ms_raw = t.get("time") t_ms = int(t_ms_raw) if t_ms_raw is not None else None l2_tracker.record_trade( symbol, float(t.get("price") or 0.0), float(t.get("qty") or 0.0), is_sell, mark_price=mark_price, trade_time_ms=t_ms, venue=t.get("venue"), trade_id=t.get("trade_id"), now_ts=eff_now_ts, ) l2_microstructure = l2_tracker.evaluate_iceberg_and_spoof(symbol, mark_price, adv_floor_usd=adv_floor_usd) # Update and query Hyperliquid on-chain whale tracker (both aggressive taker_wallet and passive maker_wallet) hl_tracker = self._hl_tracker if self._hl_tracker is not None else get_hl_whale_tracker() if hyperliquid and hyperliquid.get("trades"): for ht in hyperliquid["trades"]: ht_px = float(ht.get("price") or 0.0) ht_qty = float(ht.get("qty") or 0.0) ht_is_sell = bool(ht.get("is_buyer_maker", False)) or (str(ht.get("side", "")).upper() in ("SELL", "S", "A")) if ht.get("taker_wallet"): hl_tracker.register_trade( taker_wallet=ht.get("taker_wallet"), coin=symbol, price=ht_px, qty=ht_qty, side="SELL" if ht_is_sell else "BUY", ) if ht.get("maker_wallet"): hl_tracker.register_trade( taker_wallet=ht.get("maker_wallet"), coin=symbol, price=ht_px, qty=ht_qty, side="BUY" if ht_is_sell else "SELL", ) hl_whale_summary = hl_tracker.get_coin_whale_summary(symbol, mark_price=mark_price) fake_result = fake_detector.detect( ohlcv_1m=ohlcv_1m, ohlcv_5m=ohlcv_5m, binance_mark=binance_mark, bybit_mark=bybit_mark_aligned, cvd_matches_price=cvd_matches_price, orderbook=orderbook, venue_prices=scaled_venue_marks, cvd_rising=(bool(cvd_signal.get("rising", False)) if has_cvd_data else None), l2_microstructure=l2_microstructure, ) if not has_spot: fake_result["warnings"].insert( 0, "⚠️ PERP ONLY: Aset tidak ada di pasar Spot (harga sintetis, waspada wick sweep / manipulasi MM).", ) fake_result["is_perp_only"] = True # Compute Orderbook Resting Skew & Whale Block Order Flow for Confluence Scoring ob_skew = _compute_orderbook_skew(orderbook, mark_price) whale_flow_data = _compute_whale_order_flow( trades, mark_price, merged_ohlcv=merged_ohlcv, oi_signal=oi_signal, ls_signal=ls_signal, adv_24h_usd=adv_24h_usd, venue_adv_usd=venue_adv_usd, liquidations=liquidations, exchange_candles=exchange_candles, l2_microstructure=l2_microstructure, hl_whale_summary=hl_whale_summary, ) liq_cascade_data = _compute_liquidation_cascade( liquidations=liquidations, oi_signal=oi_signal, whale_flow=whale_flow_data, spot_futures_signal=spot_futures_signal, merged_ohlcv=merged_ohlcv, adv_floor_usd=adv_floor_usd, ) raw_whale_comp = whale_flow_data.get("whale_composite_score") whale_score = int(raw_whale_comp or 0) w_buy = whale_flow_data.get("whale_buy_vol_usd", 0.0) w_sell = whale_flow_data.get("whale_sell_vol_usd", 0.0) t_buy_pct = whale_flow_data.get("taker_buy_pct", 50.0) dyn_whale_thresh = float(whale_flow_data.get("dynamic_threshold_usd", 25000.0) or 25000.0) if raw_whale_comp is None: if w_buy > w_sell * 1.4 and w_buy >= dyn_whale_thresh: whale_score = 1 elif w_sell > w_buy * 1.4 and w_sell >= dyn_whale_thresh: whale_score = -1 whale_factor = { "score": whale_score, "label": whale_flow_data.get("flow_verdict", "Order Flow Agregat Seimbang"), "taker_buy_pct": t_buy_pct, "taker_ratio": whale_flow_data.get("taker_ratio", 1.0), "whale_buy_vol_usd": w_buy, "whale_sell_vol_usd": w_sell, "sweep_buy_vol_usd": whale_flow_data.get("sweep_buy_vol_usd", 0.0), "sweep_sell_vol_usd": whale_flow_data.get("sweep_sell_vol_usd", 0.0), "sweep_buy_count": whale_flow_data.get("sweep_buy_count", 0), "sweep_sell_count": whale_flow_data.get("sweep_sell_count", 0), "twap_bias": whale_flow_data.get("twap_bias", "NEUTRAL"), "twap_buy_pct": whale_flow_data.get("twap_buy_pct", 50.0), "twap_delta_ratio": whale_flow_data.get("twap_delta_ratio", 0.0), "twap_net_delta_usd": whale_flow_data.get("twap_net_delta_usd", 0.0), "twap_tot_usd": whale_flow_data.get("twap_tot_usd", 0.0), "whale_block_score": whale_flow_data.get("whale_block_score", 0), "twap_score": whale_flow_data.get("twap_score", 0), "absorption_score": whale_flow_data.get("absorption_score", 0), "onchain_score": whale_flow_data.get("onchain_score", 0), "absorption_type": whale_flow_data.get("absorption_type"), "absorption_note": whale_flow_data.get("absorption_note"), "whale_position_long_ratio": whale_flow_data.get("whale_position_long_ratio"), "retail_account_long_ratio": whale_flow_data.get("retail_account_long_ratio"), "smart_money_delta": whale_flow_data.get("smart_money_delta"), "onchain_whale_wallets": whale_flow_data.get("onchain_whale_wallets", 0), "onchain_buy_vol_usd": whale_flow_data.get("onchain_buy_vol_usd", 0.0), "onchain_sell_vol_usd": whale_flow_data.get("onchain_sell_vol_usd", 0.0), } ob_factor = { "score": ob_skew.get("score", 0), "label": ob_skew.get("resting_pressure", "BALANCED RESTING DEPTH"), "skew_ratio": ob_skew.get("skew_ratio", 0.0), "bid_depth_usd": ob_skew.get("bid_depth_usd", 0.0), "ask_depth_usd": ob_skew.get("ask_depth_usd", 0.0), "spoof_guarded": False, } # Anti-spoof guard: resting book opposes active taker CVD or spot_futures without whale alignment ob_sc = int(ob_factor.get("score", 0) or 0) cvd_sc = int(cvd_signal.get("score", 0) or 0) sf_sc = int(spot_futures_signal.get("score", 0) or 0) wh_sc = int(whale_score or 0) if ( ob_sc != 0 and ((has_cvd_data and ob_sc * cvd_sc < 0) or (sf_sc != 0 and ob_sc * sf_sc < 0)) and (wh_sc * ob_sc <= 0) ): ob_factor["score"] = 0 ob_factor["label"] = f"{ob_factor['label']} (Spoof-Guarded vs Taker Flow)" ob_factor["spoof_guarded"] = True if l2_microstructure.get("spoof_pulled"): ob_factor["score"] = 0 ob_factor["label"] = f"{ob_factor['label']} (Confirmed L2 Wall Pulling / Spoof)" ob_factor["spoof_guarded"] = True # ── 4. Confluence (Dual-Horizon + Primary Legacy) ────────────────── factors = { "funding_rate": funding_signal, "oi_divergence": oi_signal, "cvd": cvd_signal, "spot_futures_cvd": spot_futures_signal, "hyperliquid": hl_signal, "cross_exchange": cross_signal, "ls_ratio": ls_signal, "basis": basis_signal, "market_structure": ms_signal, "orderbook_skew": ob_factor, "whale_order_flow": whale_factor, "fake_detector": fake_result, "liquidation_cascade": liq_cascade_data, } from engine.confluence_scorer import score_to_direction regime_name = mtf_result.get("regime", mtf_result.get("market_condition", "trending")) h_thresh_map = horizon_thresholds or {} def _apply_contextual_contrarian_gating(h_factors: dict[str, Any]) -> dict[str, Any]: """Neutralize mild (-1/+1) contrarian funding/basis drag when strong MTF structure AND institutional flow confirm a fresh trend.""" ms_sc = int(h_factors.get("market_structure", {}).get("score", 0) or 0) sf_sc = int(h_factors.get("spot_futures_cvd", {}).get("score", 0) or 0) wh_sc = int(h_factors.get("whale_order_flow", {}).get("score", 0) or 0) fr_sc = int(h_factors.get("funding_rate", {}).get("score", 0) or 0) bs_sc = int(h_factors.get("basis", {}).get("score", 0) or 0) out = dict(h_factors) if (ms_sc >= 2 and (sf_sc >= 1 or wh_sc >= 1)) or (ms_sc >= 1 and sf_sc >= 1 and wh_sc >= 1): if fr_sc == -1: out["funding_rate"] = {**h_factors["funding_rate"], "score": 0} if bs_sc == -1: out["basis"] = {**h_factors["basis"], "score": 0} elif (ms_sc <= -2 and (sf_sc <= -1 or wh_sc <= -1)) or (ms_sc <= -1 and sf_sc <= -1 and wh_sc <= -1): if fr_sc == 1: out["funding_rate"] = {**h_factors["funding_rate"], "score": 0} if bs_sc == 1: out["basis"] = {**h_factors["basis"], "score": 0} return out factors_primary = _apply_contextual_contrarian_gating(dict(factors)) factors_intraday = _apply_contextual_contrarian_gating({ **factors, "oi_divergence": {**oi_signal, "score": oi_signal.get("intraday_score", oi_signal["score"])}, "market_structure": {**ms_signal, "score": mtf_result.get("intraday_structure", ms_signal["score"])}, }) factors_swing = _apply_contextual_contrarian_gating({ **factors, "cvd": swing_cvd_signal, "oi_divergence": {**oi_signal, "score": oi_signal.get("swing_score", oi_signal["score"])}, "market_structure": {**ms_signal, "score": mtf_result.get("swing_structure", ms_signal["score"])}, }) primary_conf = confluence_scorer.compute( factors_primary, horizon="primary", regime=regime_name, threshold_override=h_thresh_map.get("primary"), ) intraday_conf = confluence_scorer.compute( factors_intraday, horizon="intraday", regime=regime_name, threshold_override=h_thresh_map.get("intraday"), ) swing_conf = confluence_scorer.compute( factors_swing, horizon="swing", regime=regime_name, threshold_override=h_thresh_map.get("swing"), ) # BTC Soft Beta-Guard: penalize altcoin LONG setups by -1 when BTC is actively dumping if symbol.upper() != "BTCUSDT" and isinstance(market_context, dict): btc_dir = str(market_context.get("btc_direction") or "NEUTRAL").upper() btc_conv = int(market_context.get("btc_conviction") or 0) btc_1h_chg = float(market_context.get("btc_1h_change_pct") or 0.0) btc_reg = str(market_context.get("btc_regime") or "trending").lower() btc_dump_headwind = ( btc_dir == "SHORT" and (btc_1h_chg <= -1.2 or (btc_conv >= 4 and btc_reg != "ranging")) ) if btc_dump_headwind: for h_conf in (primary_conf, intraday_conf, swing_conf): if h_conf["score"] > 0: adj_s = h_conf["score"] - 1 h_conf["score"] = adj_s h_conf["conviction"] = abs(adj_s) h_conf["direction"] = score_to_direction(adj_s, threshold=h_conf["effective_threshold"]) h_conf["btc_macro_guard"] = "BTC_DUMP_HEADWIND" # Precompute WHALE_SWEEP_ENTRY eligibility so manipulation vetoes never get masked by soft quality guards sf_score = spot_futures_signal.get("score", 0) sweep_dir = fake_result.get("sweep_direction") has_non_sweep = fake_result.get("has_non_sweep_manipulation", True) dislocation_risk = bool(cross_signal.get("dislocation_risk", False)) absorption_type = whale_flow_data.get("absorption_type") orig_is_fake = bool(fake_result.get("is_fake", False)) def _horizon_sweep_confirmed(h_dir: str) -> bool: if not ( has_spot is True and orig_is_fake is True and sweep_dir in ("LOWER_SWEEP", "UPPER_SWEEP") and (not has_non_sweep) and (not dislocation_risk) ): return False if h_dir == "LONG" and sweep_dir == "LOWER_SWEEP": return ( sf_score >= 1 or absorption_type == "BULLISH_ICEBERG_ABSORPTION" or whale_score >= 1 ) if h_dir == "SHORT" and sweep_dir == "UPPER_SWEEP": return ( sf_score <= -1 or absorption_type == "BEARISH_ICEBERG_ABSORPTION" or whale_score <= -1 ) return False # HTF Counter-Trend Alignment Guard & Low-Efficiency Chop Filter (for intraday / non-HTF primary) sw_struct = int(mtf_result.get("swing_structure", 0) or 0) eff_ratio = float(mtf_result.get("efficiency_ratio", 1.0) or 1.0) sf_sc_raw = int(spot_futures_signal.get("score", 0) or 0) wh_sc_raw = int(whale_factor.get("score", 0) or 0) primary_is_htf = mtf_result.get("active_timeframe") in ("4h", "1d") for h_conf, is_htf_horizon in ( (intraday_conf, False), (primary_conf, primary_is_htf), ): if is_htf_horizon: continue h_dir_pre = h_conf.get("direction") if h_dir_pre in ("LONG", "SHORT"): if orig_is_fake and not _horizon_sweep_confirmed(h_dir_pre): # Preserve direction so FAKE_DETECTOR veto takes canonical precedence & logs shadow counterfactual continue d_sign = 1 if h_dir_pre == "LONG" else -1 # Penalize unconfirmed counter-trend setups fighting strong 4h/1d swing structure if sw_struct * d_sign <= -2 and sf_sc_raw * d_sign <= 0 and wh_sc_raw * d_sign <= 0: adj_ct = d_sign * max(0, abs(int(h_conf["score"])) - 2) h_conf["score"] = adj_ct h_conf["conviction"] = abs(adj_ct) h_conf["direction"] = score_to_direction(adj_ct, threshold=h_conf["effective_threshold"]) h_conf["htf_countertrend_guarded"] = True # Low directional efficiency sideways chop requires stronger multi-factor confirmation (+2 threshold) if eff_ratio < 0.25 and h_conf.get("direction") in ("LONG", "SHORT"): chop_req = int(h_conf["effective_threshold"]) + 2 if abs(int(h_conf["score"])) < chop_req: h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(int(h_conf["conviction"]), 2) h_conf["chop_filtered"] = True # Evaluate Anti-Chasing EMA(9) ATR Stretch across all horizons before selecting plans intra_stretch = float(mtf_result.get("intraday_atr_stretch", 0.0) or 0.0) swing_stretch = float(mtf_result.get("swing_atr_stretch", 0.0) or 0.0) primary_stretch = swing_stretch if mtf_result["active_timeframe"] in ("4h", "1d") else intra_stretch def _apply_anti_chasing(h_conf: dict[str, Any], stretch_val: float) -> tuple[str, dict[str, Any]]: raw_dir = h_conf["direction"] ac = _compute_anti_chasing_guard(raw_dir, stretch_val) if ac["penalty"] != 0 and raw_dir in ("LONG", "SHORT"): adj = max(-10, min(10, h_conf["score"] + ac["penalty"])) h_conf["score"] = adj h_conf["conviction"] = abs(adj) h_conf["direction"] = score_to_direction(adj, threshold=h_conf["effective_threshold"]) elif ac["blocked"] and raw_dir in ("LONG", "SHORT"): h_conf["vetoed_from"] = raw_dir h_conf["veto_reason"] = "ANTI_CHASING_EXTREME" h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(h_conf["conviction"], 3) return raw_dir, ac intra_raw_dir, intra_ac = _apply_anti_chasing(intraday_conf, intra_stretch) swing_raw_dir, swing_ac = _apply_anti_chasing(swing_conf, swing_stretch) primary_raw_dir, primary_ac = _apply_anti_chasing(primary_conf, primary_stretch) # Live multi-factor & non-collinear confirmation check (>= 2 aligned factors + >= 1 structural/derivatives factor) _ORDERFLOW_CLUSTER_KEYS = {"cvd", "spot_futures_cvd", "whale_order_flow", "orderbook_skew"} if not horizon_thresholds: for h_conf, h_facs in [ (primary_conf, factors_primary), (intraday_conf, factors_intraday), (swing_conf, factors_swing), ]: h_dir = h_conf.get("direction") if h_dir in ("LONG", "SHORT"): dir_sign = 1 if h_dir == "LONG" else -1 aligned_keys = [ k for k, f_data in h_facs.items() if k not in ("fake_detector", "cross_exchange") and (int((f_data.get("score", 0) if isinstance(f_data, dict) else f_data) or 0) * dir_sign > 0) ] aligned_count = len(aligned_keys) structural_aligned = sum(1 for k in aligned_keys if k not in _ORDERFLOW_CLUSTER_KEYS) if aligned_count < 2 or structural_aligned < 1: h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(h_conf["conviction"], 2) h_conf["unconfirmed_single_factor"] = True else: h_conf["unconfirmed_single_factor"] = False else: h_conf["unconfirmed_single_factor"] = False intra_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(intraday_conf["direction"])) swing_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(swing_conf["direction"])) primary_is_fake = bool(orig_is_fake and not _horizon_sweep_confirmed(primary_conf["direction"])) # Select primary active horizon for top-level backward-compatible Signal fields: # Intraday leads unless fake-vetoed while swing confirms WHALE_SWEEP_ENTRY; # else Swing unless Intraday was blocked by ANTI_CHASING_EXTREME in the same direction. intra_chased_dir = intra_raw_dir if (intra_ac["blocked"] and intra_raw_dir in ("LONG", "SHORT")) else None if intraday_conf["direction"] in ("LONG", "SHORT") and (not intra_is_fake or swing_is_fake or swing_conf["direction"] == "NEUTRAL"): confluence = dict(intraday_conf) active_horizon_key = "intraday" elif swing_conf["direction"] in ("LONG", "SHORT") and not swing_is_fake and ( intra_chased_dir is None or swing_conf["direction"] != intra_chased_dir ): confluence = dict(swing_conf) active_horizon_key = "swing" elif swing_conf["direction"] in ("LONG", "SHORT") and swing_conf["direction"] != intra_chased_dir and intraday_conf["direction"] == "NEUTRAL": confluence = dict(swing_conf) active_horizon_key = "swing" else: confluence = dict(intraday_conf) active_horizon_key = "intraday" # ── 5. Exchange summary ──────────────────────────────────────────── def _exch_summary(exch: dict | None) -> dict | None: if not exch: return None mp = exch.get("mark_price_data") or {} fr = exch.get("funding_rate_data") or {} oi = exch.get("open_interest_data") or {} ls = exch.get("ls_ratio_data") or {} mark_p = mp.get("mark_price") or 0.0 # Prefer USD notional value for Open Interest; fallback to coins * mark_price (using unscaled price) oi_val = oi.get("open_interest_value") if oi_val is not None and float(oi_val) > 0: oi_notional = float(oi_val) else: raw_oi = oi.get("open_interest") if raw_oi is not None and mark_p > 0: oi_notional = float(raw_oi) * mark_p else: oi_notional = raw_oi px_scale = _get_multiplier_scale(mark_p, ref_mark_px) scaled_mark = (float(mark_p) * px_scale) if mark_p else mp.get("mark_price") raw_index = mp.get("index_price") scaled_index = (float(raw_index) * px_scale) if raw_index else raw_index return { "funding_rate": fr.get("funding_rate"), "next_funding_time": fr.get("next_funding_time"), "oi": round(oi_notional, 2) if oi_notional is not None else None, "mark_price": scaled_mark, "index_price": scaled_index, "basis_pct": mp.get("basis_pct"), "long_ratio": ls.get("long_ratio"), "short_ratio": ls.get("short_ratio"), } exchange_data = {} if binance: exchange_data["binance"] = _exch_summary(binance) if bybit: exchange_data["bybit"] = _exch_summary(bybit) if okx: exchange_data["okx"] = _exch_summary(okx) if bitget: exchange_data["bitget"] = _exch_summary(bitget) if hyperliquid: hl_mark = hyperliquid.get("mark_price") or 0.0 hl_oi_raw = hyperliquid.get("open_interest") or 0.0 hl_oi_usd = hl_oi_raw * hl_mark if hl_mark > 0 else hl_oi_raw hl_scale = _get_multiplier_scale(hl_mark, ref_mark_px) hl_oracle = hyperliquid.get("oracle_price") exchange_data["hyperliquid"] = { "funding_rate": hyperliquid.get("funding_rate"), "next_funding_time": int(((time.time() // 3600) + 1) * 3600 * 1000), "oi": round(hl_oi_usd, 2) if hl_oi_usd else None, "mark_price": (float(hl_mark) * hl_scale) if hl_mark else hyperliquid.get("mark_price"), "index_price": (float(hl_oracle) * hl_scale) if hl_oracle else hl_oracle, "basis_pct": hyperliquid.get("basis_pct"), } # ── 6. Predictive Forward-Looking Engine ────────────────────────── predictive_data = predictive_engine.analyze( mark_price=mark_price, ohlcv=merged_ohlcv, orderbook=orderbook, direction=confluence["direction"], conviction=confluence["conviction"], funding_rate=funding_signal.get("value"), hl_liq_clusters=hl_whale_summary.get("liquidation_clusters"), ) orig_predictive_data = dict(predictive_data) # Primary-venue orderbook liquidity guard (tight ±1.5% depth & top-of-book spread) primary_venue_ob = valid_obs[0] if valid_obs else None liquidity_guard = _compute_liquidity_guard(primary_venue_ob, mark_price, skew_data=ob_skew) # ── 7. Horizon Trade Plans & Instant Verdict ─────────────────────── intraday_candles = merged_ohlcv.get("1h") or merged_ohlcv.get("15m") or [] swing_candles = merged_ohlcv.get("4h") or merged_ohlcv.get("1h") or [] is_fake_flag = fake_result.get("is_fake", False) swing_chased_dir = swing_raw_dir if (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT")) else None # Candidate direction before global circuit breakers (including any chased direction) candidate_dir = ( confluence["direction"] if confluence["direction"] in ("LONG", "SHORT") else (intra_chased_dir or swing_chased_dir or primary_conf.get("direction", "NEUTRAL")) ) # Primary-horizon sweep override evaluation (precomputed above for horizon selection) candidate_sweep_ok = _horizon_sweep_confirmed(candidate_dir) is_fake_flag = bool(orig_is_fake and not candidate_sweep_ok) if candidate_sweep_ok: fake_result["is_fake"] = False fake_result["sweep_override"] = "WHALE_SWEEP_ENTRY" fake_result["label"] = "Whale Liquidity Sweep Confirmed (Institutional Absorption)" intraday_plan = _compute_trade_plan( direction=intraday_conf["direction"], mark_price=mark_price, ohlcv_1h=intraday_candles, spot_futures_score=sf_score, conviction=intraday_conf["conviction"], predictive_data=predictive_data, is_fake=intra_is_fake, sl_min_pct=0.008, sl_max_pct=0.04, sl_fallback_max_pct=0.035, sl_atr_mult=1.75, sl_struct_buffer_atr=0.35, ) if intra_ac["blocked"] and intra_raw_dir in ("LONG", "SHORT"): intraday_plan["action"] = "WAIT / OVEREXTENDED" intraday_plan["quick_verdict"] = ( "⚠️ Veto Anti-Chasing: Harga sudah melampaui >2.8 ATR dari EMA(9). Hindari FOMO kejar pucuk/lembah, tunggu pullback!" ) swing_plan = _compute_trade_plan( direction=swing_conf["direction"], mark_price=mark_price, ohlcv_1h=swing_candles, spot_futures_score=sf_score, conviction=swing_conf["conviction"], predictive_data=predictive_data, is_fake=swing_is_fake, sl_min_pct=0.015, sl_max_pct=0.08, sl_fallback_max_pct=0.06, ) if swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT"): swing_plan["action"] = "WAIT / OVEREXTENDED" swing_plan["quick_verdict"] = ( "⚠️ Veto Anti-Chasing: Harga sudah melampaui >2.8 ATR dari EMA(9). Hindari FOMO kejar pucuk/lembah, tunggu pullback!" ) primary_plan = _compute_trade_plan( direction=primary_conf["direction"], mark_price=mark_price, ohlcv_1h=merged_ohlcv.get("1h", []), spot_futures_score=sf_score, conviction=primary_conf["conviction"], predictive_data=predictive_data, is_fake=primary_is_fake, sl_atr_mult=1.5 if primary_is_htf else 1.75, sl_struct_buffer_atr=0.2 if primary_is_htf else 0.35, ) if primary_ac["blocked"] and primary_raw_dir in ("LONG", "SHORT"): primary_plan["action"] = "WAIT / OVEREXTENDED" primary_plan["quick_verdict"] = ( "⚠️ Veto Anti-Chasing: Harga sudah melampaui >2.8 ATR dari EMA(9). Hindari FOMO kejar pucuk/lembah, tunggu pullback!" ) plan = dict(intraday_plan if active_horizon_key == "intraday" else swing_plan) # ── 7.1 Institutional Hierarchical Quality Gate / Circuit Breakers ─── if cross_signal.get("dislocation_risk") and isinstance(fake_result.get("warnings"), list): fake_result["warnings"].append( f"⚠️ Cross-Exchange Dislocation Risk: {cross_signal.get('label', '')}" ) avg_fr_val = funding_signal.get("value_pct") if avg_fr_val is None and funding_signal.get("value") is not None: avg_fr_val = float(funding_signal["value"]) * 100.0 avg_fr_val = avg_fr_val or 0.0 crowded_long_veto = candidate_dir == "LONG" and avg_fr_val > 0.05 crowded_short_veto = candidate_dir == "SHORT" and avg_fr_val < -0.05 crowded_funding_veto = crowded_long_veto or crowded_short_veto fake_veto = bool(is_fake_flag and candidate_dir in ("LONG", "SHORT")) illiquid_veto = bool((not liquidity_guard["passed"]) and candidate_dir in ("LONG", "SHORT")) anti_chasing_top_veto = bool( (intra_chased_dir is not None and (swing_conf["direction"] == "NEUTRAL" or swing_conf["direction"] == intra_chased_dir)) or (swing_ac["blocked"] and swing_raw_dir in ("LONG", "SHORT") and intraday_conf["direction"] == "NEUTRAL") ) # Deterministic Veto Enum Precedence: # 1. FAKE_DETECTOR > 2. CROWDED_FUNDING > 3. ILLIQUID_OR_WIDE_SPREAD > 4. ANTI_CHASING_EXTREME > null canonical_veto: str | None = None if fake_veto: canonical_veto = "FAKE_DETECTOR" elif crowded_funding_veto: canonical_veto = "CROWDED_FUNDING" elif illiquid_veto: canonical_veto = "ILLIQUID_OR_WIDE_SPREAD" elif anti_chasing_top_veto: canonical_veto = "ANTI_CHASING_EXTREME" # Global circuit breakers (FakeDetector, Crowded Funding, Liquidity Guard) invalidate ALL horizons if fake_veto or crowded_funding_veto or illiquid_veto: for h_conf, h_plan in [ (intraday_conf, intraday_plan), (swing_conf, swing_plan), (primary_conf, primary_plan), ]: if h_conf["direction"] in ("LONG", "SHORT"): h_conf["vetoed_from"] = h_conf["direction"] h_conf["veto_reason"] = canonical_veto h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(h_conf["conviction"], 3) h_plan["trade_levels"] = None else: # Close cross-horizon bypasses when horizons point in opposite directions for h_conf, h_plan, h_is_fake in ( (intraday_conf, intraday_plan, intra_is_fake), (swing_conf, swing_plan, swing_is_fake), (primary_conf, primary_plan, primary_is_fake), ): h_dir = h_conf.get("direction") if h_is_fake and h_dir in ("LONG", "SHORT"): h_conf["vetoed_from"] = h_dir h_conf["veto_reason"] = "FAKE_DETECTOR" h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(h_conf["conviction"], 3) h_plan["trade_levels"] = None h_plan["action"] = "WAIT / MANIPULATION ALERT" h_plan["quick_verdict"] = ( "⚠️ Veto Manipulasi Aktif: Terdeteksi wick sweep / anomali pasar. Entry dibatalkan hingga struktur stabil." ) elif (h_dir == "LONG" and avg_fr_val > 0.05) or (h_dir == "SHORT" and avg_fr_val < -0.05): h_conf["vetoed_from"] = h_dir h_conf["veto_reason"] = "CROWDED_FUNDING" h_conf["direction"] = "NEUTRAL" h_conf["conviction"] = min(h_conf["conviction"], 3) h_plan["trade_levels"] = None if h_dir == "LONG": h_plan["action"] = "WAIT / CROWDED LONG RISK" h_plan["quick_verdict"] = ( "⚠️ Veto Sirkuit Kritis: Funding rate ekstrem positif (>0.05%). " "Pasar overleveraged Long rentan long-squeeze flush!" ) else: h_plan["action"] = "WAIT / SQUEEZE RISK" h_plan["quick_verdict"] = ( "⚠️ Veto Sirkuit Kritis: Funding rate diskon ekstrem (<-0.05%). " "Shorts membayar bunga sangat tinggi, rawan short-squeeze!" ) if canonical_veto is not None: orig_dir = confluence["direction"] if confluence["direction"] in ("LONG", "SHORT") else (candidate_dir if candidate_dir in ("LONG", "SHORT") else "LONG") confluence["vetoed_from"] = orig_dir confluence["veto_reason"] = canonical_veto confluence["direction"] = "NEUTRAL" confluence["conviction"] = min(confluence["conviction"], 3) plan["trade_levels"] = None if canonical_veto == "FAKE_DETECTOR": fake_note = "⚠️ Veto Manipulasi Aktif: Terdeteksi wick sweep / anomali pasar. Entry dibatalkan hingga struktur stabil." plan["action"] = "WAIT / MANIPULATION ALERT" plan["quick_verdict"] = fake_note elif canonical_veto == "CROWDED_FUNDING": if crowded_long_veto: crowd_note = "⚠️ Veto Sirkuit Kritis: Funding rate ekstrem positif (>0.05%). Pasar overleveraged Long rentan long-squeeze flush!" plan["action"] = "WAIT / CROWDED LONG RISK" else: crowd_note = "⚠️ Veto Sirkuit Kritis: Funding rate diskon ekstrem (<-0.05%). Shorts membayar bunga sangat tinggi, rawan short-squeeze!" plan["action"] = "WAIT / SQUEEZE RISK" plan["quick_verdict"] = crowd_note elif canonical_veto == "ILLIQUID_OR_WIDE_SPREAD": liq_note = "⚠️ Veto Likuiditas: Spread orderbook terlalu lebar (>50 bps) atau kedalaman ±1.5% tipis (<$25k). Tunda eksekusi!" plan["action"] = "WAIT / ILLIQUID BOOK" plan["quick_verdict"] = liq_note elif canonical_veto == "ANTI_CHASING_EXTREME": chase_note = "⚠️ Veto Anti-Chasing: Harga sudah melampaui >2.8 ATR dari EMA(9). Hindari FOMO kejar pucuk/lembah, tunggu pullback!" plan["action"] = "WAIT / OVEREXTENDED" plan["quick_verdict"] = chase_note if fake_veto or crowded_funding_veto or illiquid_veto: for h_plan in (intraday_plan, swing_plan, primary_plan): h_plan["action"] = plan["action"] h_plan["quick_verdict"] = plan["quick_verdict"] # Refresh forward anticipation to NEUTRAL so top-level anticipation never contradicts a vetoed signal neutral_pred = predictive_engine.analyze( mark_price=mark_price, ohlcv=merged_ohlcv, orderbook=orderbook, direction="NEUTRAL", conviction=confluence["conviction"], funding_rate=funding_signal.get("value"), hl_liq_clusters=hl_whale_summary.get("liquidation_clusters"), ) predictive_data["predicted_target"] = neutral_pred["predicted_target"] predictive_data["target_type"] = neutral_pred["target_type"] predictive_data["target_dist_pct"] = neutral_pred["target_dist_pct"] predictive_data["anticipation"] = neutral_pred["anticipation"] # Keep verdict clean without clumsy bracket tags (badges already displayed in UI) for p_item in (plan, intraday_plan, swing_plan, primary_plan): if not has_spot and p_item.get("quick_verdict") and not str(p_item["quick_verdict"]).startswith("Perp-Only:"): p_item["quick_verdict"] = f"Perp-Only: {p_item['quick_verdict']}" if p_item.get("trade_levels"): p_item["trade_levels"]["is_perp_only"] = not has_spot p_item["trade_levels"]["safety_label"] = "AMAN (Ada Spot)" if has_spot else "RAWAN (Perp Only)" # Compute Sniper Grade squeeze_active = ( mtf_result.get("market_condition") == "squeeze" or bool(predictive_data.get("volatility_squeeze", {}).get("is_squeeze", False)) ) intra_dir = intraday_conf["direction"] sw_dir = swing_conf["direction"] if canonical_veto is not None or (intra_dir == "NEUTRAL" and sw_dir == "NEUTRAL"): sniper_grade = "WAIT" elif intra_dir in ("LONG", "SHORT") and sw_dir == intra_dir: sf_aligned = (intra_dir == "LONG" and sf_score > 0) or (intra_dir == "SHORT" and sf_score < 0) whale_aligned = (intra_dir == "LONG" and whale_score > 0) or (intra_dir == "SHORT" and whale_score < 0) cvd_sc = int(cvd_signal.get("score", 0) or 0) ohlcv_cvd_aligned = bool(horizon_thresholds) and ( eff_ratio >= 0.25 and abs(int(intraday_conf.get("score") or 0)) >= 3 and ((intra_dir == "LONG" and cvd_sc > 0) or (intra_dir == "SHORT" and cvd_sc < 0)) ) if squeeze_active or sf_aligned or whale_aligned or ohlcv_cvd_aligned: sniper_grade = "SNIPER_A_PLUS" else: sniper_grade = "INTRADAY_ONLY" elif intra_dir in ("LONG", "SHORT") and sw_dir == "NEUTRAL": sniper_grade = "INTRADAY_ONLY" elif intra_dir in ("LONG", "SHORT") and sw_dir in ("LONG", "SHORT") and sw_dir != intra_dir: sniper_grade = "SNIPER_COUNTER" elif sw_dir in ("LONG", "SHORT") and intra_dir == "NEUTRAL": sniper_grade = "SWING_SETUP" else: sniper_grade = "WAIT" def _extract_scores(f_map: dict[str, Any]) -> dict[str, int]: return { k: int(v.get("score", 0) or 0) if isinstance(v, dict) else int(v or 0) for k, v in f_map.items() if k != "fake_detector" } # Transient shadow trade levels for counterfactual outcome tracking shadow_trade_levels: dict[str, Any] = {} intra_vetoed_from = intraday_conf.get("vetoed_from") if intra_vetoed_from in ("LONG", "SHORT") and intraday_conf.get("veto_reason"): shadow_intra_plan = _compute_trade_plan( direction=intra_vetoed_from, mark_price=mark_price, ohlcv_1h=intraday_candles, spot_futures_score=sf_score, conviction=max(3, int(intraday_conf.get("conviction") or 3)), predictive_data=orig_predictive_data, is_fake=False, sl_min_pct=0.008, sl_max_pct=0.04, sl_fallback_max_pct=0.035, sl_atr_mult=1.75, sl_struct_buffer_atr=0.35, ) if shadow_intra_plan.get("trade_levels"): shadow_trade_levels["intraday"] = shadow_intra_plan["trade_levels"] swing_vetoed_from = swing_conf.get("vetoed_from") if swing_vetoed_from in ("LONG", "SHORT") and swing_conf.get("veto_reason"): shadow_swing_plan = _compute_trade_plan( direction=swing_vetoed_from, mark_price=mark_price, ohlcv_1h=swing_candles, spot_futures_score=sf_score, conviction=max(3, int(swing_conf.get("conviction") or 3)), predictive_data=orig_predictive_data, is_fake=False, sl_min_pct=0.015, sl_max_pct=0.08, sl_fallback_max_pct=0.06, ) if shadow_swing_plan.get("trade_levels"): shadow_trade_levels["swing"] = shadow_swing_plan["trade_levels"] horizons_payload = { "intraday": { "timeframe": "15m-4h", "direction": intraday_conf["direction"], "score": intraday_conf["score"], "conviction": intraday_conf["conviction"], "regime": regime_name, "veto_reason": intraday_conf.get("veto_reason"), "vetoed_from": intraday_conf.get("vetoed_from"), "unconfirmed_single_factor": intraday_conf.get("unconfirmed_single_factor", False), "chop_filtered": intraday_conf.get("chop_filtered", False), "htf_countertrend_guarded": intraday_conf.get("htf_countertrend_guarded", False), "factor_scores": _extract_scores(factors_intraday), "stretch_atr": intra_ac["stretch_atr"], "anti_chasing_status": intra_ac["status"], "trade_levels": intraday_plan["trade_levels"], "action": intraday_plan["action"], "quick_verdict": intraday_plan["quick_verdict"], }, "swing": { "timeframe": "4h-1d", "direction": swing_conf["direction"], "score": swing_conf["score"], "conviction": swing_conf["conviction"], "regime": regime_name, "veto_reason": swing_conf.get("veto_reason"), "vetoed_from": swing_conf.get("vetoed_from"), "unconfirmed_single_factor": swing_conf.get("unconfirmed_single_factor", False), "factor_scores": _extract_scores(factors_swing), "stretch_atr": swing_ac["stretch_atr"], "anti_chasing_status": swing_ac["status"], "trade_levels": swing_plan["trade_levels"], "action": swing_plan["action"], "quick_verdict": swing_plan["quick_verdict"], }, "primary": { "timeframe": mtf_result["active_timeframe"], "direction": primary_conf["direction"], "score": primary_conf["score"], "conviction": primary_conf["conviction"], "regime": regime_name, "veto_reason": primary_conf.get("veto_reason"), "vetoed_from": primary_conf.get("vetoed_from"), "unconfirmed_single_factor": primary_conf.get("unconfirmed_single_factor", False), "chop_filtered": primary_conf.get("chop_filtered", False), "htf_countertrend_guarded": primary_conf.get("htf_countertrend_guarded", False), "factor_scores": _extract_scores(factors_primary), "stretch_atr": primary_ac["stretch_atr"], "anti_chasing_status": primary_ac["status"], "trade_levels": primary_plan["trade_levels"], "action": primary_plan["action"], "quick_verdict": primary_plan["quick_verdict"], }, } # ── 7.5 Institutional Microstructure, Lead-Lag & Order Flow ─────── lead_lag_data = _compute_lead_lag(exchange_data, mark_price) settlement_data = _compute_funding_settlement(exchange_data) extremes_data = _compute_price_extremes_24h(merged_ohlcv, mark_price, symbol=symbol, exchange_data=exchange_data) breakout_radar_data = _compute_breakout_radar( direction=confluence["direction"], conviction=confluence["conviction"], predictive_data=predictive_data, oi_signal=oi_signal, whale_flow=whale_flow_data, extremes_data=extremes_data, ) if ( confluence["direction"] == "NEUTRAL" and canonical_veto is None and not is_fake_flag and liquidity_guard.get("passed", True) and breakout_radar_data.get("is_breakout_primed") ): if plan.get("action") in ("WAIT", "DO NOT TRADE / WAIT"): plan["action"] = "WATCH BREAKOUT" if plan.get("quick_verdict"): plan["quick_verdict"] = f"{breakout_radar_data['radar_label']}: {breakout_radar_data['catalyst_summary']}" # ── 8. Assemble final output ─────────────────────────────────────── now = datetime.now(timezone.utc).isoformat() return { "symbol": symbol, "direction": confluence["direction"], "conviction": confluence["conviction"], "score": confluence["score"], "sniper_grade": sniper_grade, "veto_reason": canonical_veto, "unconfirmed_single_factor": confluence.get("unconfirmed_single_factor", False), "liquidity_guard": liquidity_guard, "horizons": horizons_payload, "confluence": confluence, "has_spot": has_spot, "spot_status": "SPOT_BACKED" if has_spot else "PERP_ONLY", "safety_status": "SAFE" if has_spot else "UNSAFE", "safety_label": "AMAN (Ada Spot)" if has_spot else "RAWAN (Perp Only)", "action": plan["action"], "quick_verdict": plan["quick_verdict"], "trade_levels": plan["trade_levels"], "_shadow_trade_levels": shadow_trade_levels, "anticipation": predictive_data["anticipation"], "predictive": predictive_data, "breakout_radar": breakout_radar_data, "lead_lag": lead_lag_data, "funding_settlement": settlement_data, "price_extremes": extremes_data, "whale_flow": whale_flow_data, "adv_24h_usd": adv_24h_usd, "liquidation_cascade": liq_cascade_data, "hl_whale_summary": hl_whale_summary, "l2_microstructure": l2_microstructure, "active_timeframe": mtf_result["active_timeframe"], "market_condition": mtf_result["market_condition"], "signals": { "funding_rate": funding_signal, "oi_divergence": oi_signal, "cvd": cvd_signal, "spot_futures_cvd": spot_futures_signal, "hyperliquid": hl_signal, "cross_exchange": cross_signal, "ls_ratio": ls_signal, "basis": basis_signal, "market_structure": ms_signal, "orderbook_skew": ob_factor, "whale_order_flow": whale_factor, "fake_detector": fake_result, "liquidation_cascade": liq_cascade_data, }, "exchange_data": exchange_data, "updated_at": now, }