""" L2 Orderbook Microstructure: True Iceberg Refill & Wall Pulling / Spoofing Detector. Analyzes high-resolution L2 depth snapshots and streaming feeds to detect: 1. True Limit Order Iceberg Refills: Repeated absorption where taker volume severely exceeds visible liquidity without price breaking. 2. Confirmed Spoofing / Wall Pulling: Large visible walls (> $50k) that vanish (> 70% reduction) as price approaches without taker execution. """ from __future__ import annotations from collections import deque import logging import math import time from typing import Any logger = logging.getLogger(__name__) class PriceBucket: """Tracks resting depth, refill events, and executed taker volume for a 5-bps price bucket.""" def __init__(self, bucket_price: float, now_ts: float | None = None) -> None: now = float(now_ts) if now_ts is not None else time.time() self.bucket_price = bucket_price self.initial_visible_usd = 0.0 self.peak_visible_usd = 0.0 self.current_visible_usd = 0.0 self.refill_count = 0 self.executed_taker_buy_usd = 0.0 self.executed_taker_sell_usd = 0.0 self._trade_events: deque[tuple[float, float, bool]] = deque() self.first_seen_ts = now self.last_updated_ts = now def _prune_trades(self, now: float) -> None: cutoff = now - 180.0 while self._trade_events and self._trade_events[0][0] < cutoff: _, old_usd, old_sell = self._trade_events.popleft() if old_sell: self.executed_taker_sell_usd = max(0.0, self.executed_taker_sell_usd - old_usd) else: self.executed_taker_buy_usd = max(0.0, self.executed_taker_buy_usd - old_usd) def update_depth(self, visible_usd: float, dist_pct: float, now_ts: float | None = None) -> None: now = float(now_ts) if now_ts is not None else time.time() self._prune_trades(now) self.last_updated_ts = now # Record initial visible when price enters proximity (within 0.50%) if self.initial_visible_usd <= 0.0 and abs(dist_pct) <= 0.50: self.initial_visible_usd = visible_usd # Record peak visible while price is 0.15% - 1.50% away (potential spoof wall) if 0.15 <= abs(dist_pct) <= 1.50: if visible_usd > self.peak_visible_usd: self.peak_visible_usd = visible_usd # Detect refill: visible increased after being depleted if self.current_visible_usd > 0 and visible_usd > self.current_visible_usd * 1.30: self.refill_count += 1 self.current_visible_usd = visible_usd def add_taker_trade(self, usd_val: float, is_sell: bool, now_ts: float | None = None) -> None: now = float(now_ts) if now_ts is not None else time.time() self._prune_trades(now) self.last_updated_ts = now self._trade_events.append((now, usd_val, is_sell)) if is_sell: self.executed_taker_sell_usd += usd_val else: self.executed_taker_buy_usd += usd_val class SymbolL2State: """Maintains price buckets and sliding window state for a symbol.""" def __init__(self, symbol: str, now_ts: float | None = None) -> None: now = float(now_ts) if now_ts is not None else time.time() self.symbol = symbol self.bid_buckets: dict[int, PriceBucket] = {} # bucket_key -> PriceBucket self.ask_buckets: dict[int, PriceBucket] = {} self.updates_count = 0 self.last_update_ts = now self._seen_trade_keys: set[tuple[Any, ...]] = set() self._seen_trade_queue: deque[tuple[Any, ...]] = deque() def _get_bucket_key(self, price: float, ref_price: float = 0.0) -> int: if price <= 0: return -999999999 # 5 bps (0.05%) logarithmic step invariant to mark price movement return int(math.floor(math.log(max(price, 1e-9)) / 0.0005)) def _get_bucket_price(self, bucket_key: int, ref_price: float = 0.0) -> float: if bucket_key == -999999999: return 0.0 return math.exp((bucket_key + 0.5) * 0.0005) def update_book( self, bids: list[Any], asks: list[Any], mark_price: float, now_ts: float | None = None, ) -> None: if mark_price <= 0: return now = float(now_ts) if now_ts is not None else time.time() self.updates_count += 1 self.last_update_ts = now # Aggregate raw levels into 5-bps buckets BEFORE updating bucket state bid_agg: dict[int, tuple[float, float]] = {} # k -> (total_usd, min_abs_dist_signed) min_seen_bid_px: float | None = None for b in bids[:25]: try: p = float(b[0]) q = float(b[1]) usd = p * q if usd <= 0 or p <= 0: continue if min_seen_bid_px is None or p < min_seen_bid_px: min_seen_bid_px = p k = self._get_bucket_key(p, mark_price) if k == -999999999: continue dist = (p - mark_price) / mark_price * 100.0 if k in bid_agg: prev_usd, prev_dist = bid_agg[k] best_dist = dist if abs(dist) < abs(prev_dist) else prev_dist bid_agg[k] = (prev_usd + usd, best_dist) else: bid_agg[k] = (usd, dist) except (ValueError, TypeError, IndexError): continue for k, (usd, dist) in bid_agg.items(): if k not in self.bid_buckets: self.bid_buckets[k] = PriceBucket(self._get_bucket_price(k, mark_price), now_ts=now) self.bid_buckets[k].update_depth(usd, dist, now_ts=now) # Zero-out current_visible_usd only for buckets strictly inside the top-25 bid price span if min_seen_bid_px is not None: for k, b_obj in self.bid_buckets.items(): if k not in bid_agg: if min_seen_bid_px <= b_obj.bucket_price <= mark_price: b_obj.current_visible_usd = 0.0 # Aggregate ask levels into 5-bps buckets BEFORE updating bucket state ask_agg: dict[int, tuple[float, float]] = {} max_seen_ask_px: float | None = None for a in asks[:25]: try: p = float(a[0]) q = float(a[1]) usd = p * q if usd <= 0 or p <= 0: continue if max_seen_ask_px is None or p > max_seen_ask_px: max_seen_ask_px = p k = self._get_bucket_key(p, mark_price) if k == -999999999: continue dist = (p - mark_price) / mark_price * 100.0 if k in ask_agg: prev_usd, prev_dist = ask_agg[k] best_dist = dist if abs(dist) < abs(prev_dist) else prev_dist ask_agg[k] = (prev_usd + usd, best_dist) else: ask_agg[k] = (usd, dist) except (ValueError, TypeError, IndexError): continue for k, (usd, dist) in ask_agg.items(): if k not in self.ask_buckets: self.ask_buckets[k] = PriceBucket(self._get_bucket_price(k, mark_price), now_ts=now) self.ask_buckets[k].update_depth(usd, dist, now_ts=now) # Zero-out current_visible_usd only for buckets strictly inside the top-25 ask price span if max_seen_ask_px is not None: for k, a_obj in self.ask_buckets.items(): if k not in ask_agg: if mark_price <= a_obj.bucket_price <= max_seen_ask_px: a_obj.current_visible_usd = 0.0 # Prune old buckets older than 180s self.bid_buckets = {k: v for k, v in self.bid_buckets.items() if (now - v.last_updated_ts) <= 180.0} self.ask_buckets = {k: v for k, v in self.ask_buckets.items() if (now - v.last_updated_ts) <= 180.0} def record_taker_trade( self, price: float, qty: float, is_sell: bool, mark_price: float, trade_time_ms: int | None = None, venue: str | None = None, trade_id: Any = None, now_ts: float | None = None, ) -> None: ref_px = mark_price or price if ref_px <= 0 or price <= 0 or qty <= 0: return now = float(now_ts) if now_ts is not None else time.time() if trade_time_ms and trade_time_ms > 0: # Skip stale trades outside the 180s rolling microstructure window if trade_time_ms < (now - 180.0) * 1000.0: return v_key = str(venue or "") dedup_key: tuple[Any, ...] = ( (v_key, int(trade_time_ms), str(trade_id)) if trade_id is not None else (v_key, int(trade_time_ms), round(price, 8), round(qty, 8), bool(is_sell)) ) if dedup_key in self._seen_trade_keys: return self._seen_trade_keys.add(dedup_key) self._seen_trade_queue.append(dedup_key) while len(self._seen_trade_queue) > 8000: evicted = self._seen_trade_queue.popleft() self._seen_trade_keys.discard(evicted) usd = price * qty k = self._get_bucket_key(price, ref_px) if k == -999999999: return if is_sell: bucket = self.bid_buckets.get(k) if not bucket: bucket = PriceBucket(self._get_bucket_price(k, ref_px), now_ts=now) self.bid_buckets[k] = bucket bucket.add_taker_trade(usd, is_sell=True, now_ts=now) else: bucket = self.ask_buckets.get(k) if not bucket: bucket = PriceBucket(self._get_bucket_price(k, ref_px), now_ts=now) self.ask_buckets[k] = bucket bucket.add_taker_trade(usd, is_sell=False, now_ts=now) class L2OrderbookTracker: """ Tracks orderbook microstructure across symbols to discover true limit iceberg fills and detect spoof walls pulled before trade execution. """ def __init__(self) -> None: self._states: dict[str, SymbolL2State] = {} def _get_state(self, symbol: str) -> SymbolL2State: sym = symbol.upper() if sym not in self._states: # Keep max 40 symbols if len(self._states) >= 40: oldest_sym = min(self._states.keys(), key=lambda s: self._states[s].last_update_ts) del self._states[oldest_sym] self._states[sym] = SymbolL2State(sym) return self._states[sym] def update_book( self, symbol: str, bids: list[Any], asks: list[Any], mark_price: float = 0.0, now_ts: float | None = None, ) -> None: if not symbol: return st = self._get_state(symbol) st.update_book(bids, asks, mark_price, now_ts=now_ts) def record_trade( self, symbol: str, price: float, qty: float, is_sell: bool, mark_price: float = 0.0, trade_time_ms: int | None = None, venue: str | None = None, trade_id: Any = None, now_ts: float | None = None, ) -> None: if not symbol: return st = self._get_state(symbol) st.record_taker_trade( price, qty, is_sell, mark_price, trade_time_ms=trade_time_ms, venue=venue, trade_id=trade_id, now_ts=now_ts, ) def evaluate_iceberg_and_spoof( self, symbol: str, mark_price: float, adv_floor_usd: float = 5000.0, ) -> dict[str, Any]: """ Evaluate true L2 iceberg refills and wall pulling/spoofing. """ sym = symbol.upper() default_res: dict[str, Any] = { "l2_iceberg_score": 0, "iceberg_type": None, "iceberg_price": 0.0, "absorbed_usd": 0.0, "visible_usd": 0.0, "iceberg_note": None, "spoof_pulled": False, "spoof_side": None, "spoof_price": 0.0, "pulled_wall_usd": 0.0, "spoof_note": None, "updates_count": 0, } if sym not in self._states or mark_price <= 0: return default_res st = self._states[sym] default_res["updates_count"] = st.updates_count # ── 1. Bullish L2 Iceberg Refill (Bids absorbed by aggressive sellers) ─ iceberg_thresh = max(25_000.0, adv_floor_usd * 1.5) best_bull_sc = 0 best_bull_data: dict[str, Any] = {} for b in st.bid_buckets.values(): px = b.bucket_price if not (mark_price * 0.995 <= px <= mark_price * 1.002): continue absorbed = b.executed_taker_sell_usd visible = b.initial_visible_usd if b.initial_visible_usd > 0 else max(b.peak_visible_usd, b.current_visible_usd) if visible < 500.0 or absorbed < iceberg_thresh: continue ratio = absorbed / visible price_held = mark_price >= px * 0.9985 refilled = b.refill_count >= 1 or b.current_visible_usd >= 0.40 * visible if price_held and refilled: if ratio >= 2.5: sc = 2 elif ratio >= 1.8: sc = 1 else: sc = 0 if sc > best_bull_sc: best_bull_sc = sc best_bull_data = { "l2_iceberg_score": sc, "iceberg_type": "BULLISH_L2_ICEBERG_REFILL", "iceberg_price": round(px, 4 if px < 10 else 2), "absorbed_usd": round(absorbed, 2), "visible_usd": round(visible, 2), "iceberg_note": f"Bullish L2 Iceberg Refill @ ${px:,.2f}: Diserap ${absorbed:,.0f} ({ratio:.1f}x visible ${visible:,.0f})", } # ── 2. Bearish L2 Iceberg Refill (Asks absorbed by aggressive buyers) ── best_bear_sc = 0 best_bear_data: dict[str, Any] = {} for a in st.ask_buckets.values(): px = a.bucket_price if not (mark_price * 0.998 <= px <= mark_price * 1.005): continue absorbed = a.executed_taker_buy_usd visible = a.initial_visible_usd if a.initial_visible_usd > 0 else max(a.peak_visible_usd, a.current_visible_usd) if visible < 500.0 or absorbed < iceberg_thresh: continue ratio = absorbed / visible price_capped = mark_price <= px * 1.0015 refilled = a.refill_count >= 1 or a.current_visible_usd >= 0.40 * visible if price_capped and refilled: if ratio >= 2.5: sc = -2 elif ratio >= 1.8: sc = -1 else: sc = 0 if sc < best_bear_sc: best_bear_sc = sc best_bear_data = { "l2_iceberg_score": sc, "iceberg_type": "BEARISH_L2_ICEBERG_REFILL", "iceberg_price": round(px, 4 if px < 10 else 2), "absorbed_usd": round(absorbed, 2), "visible_usd": round(visible, 2), "iceberg_note": f"Bearish L2 Iceberg Refill @ ${px:,.2f}: Diserap ${absorbed:,.0f} ({ratio:.1f}x visible ${visible:,.0f})", } if best_bull_sc > 0: default_res.update(best_bull_data) elif best_bear_sc < 0: default_res.update(best_bear_data) # ── 3. Confirmed Wall Pulling / Spoofing ─────────────────────────────── spoof_wall_min = max(50_000.0, adv_floor_usd * 2.5) # Check Bids pulled for b in st.bid_buckets.values(): px = b.bucket_price if px > mark_price * 1.001: continue dist_pct = abs((px - mark_price) / mark_price * 100.0) peak = b.peak_visible_usd curr = b.current_visible_usd if peak >= spoof_wall_min and dist_pct <= 0.15: vanished = peak - curr if curr <= 0.30 * peak and vanished >= spoof_wall_min * 0.70: # Check how much taker sell actually filled at this price filled = b.executed_taker_sell_usd if filled < 0.15 * vanished: default_res["spoof_pulled"] = True default_res["spoof_side"] = "BID" default_res["spoof_price"] = round(px, 4 if px < 10 else 2) default_res["pulled_wall_usd"] = round(vanished, 2) default_res["spoof_note"] = ( f"Confirmed BID Wall Pulling/Spoof: Wall ${peak:,.0f} ditarik 70%+ " f"saat harga mendekat ({dist_pct:.2f}%); hanya ${filled:,.0f} yang terisi." ) break # Check Asks pulled if not default_res["spoof_pulled"]: for a in st.ask_buckets.values(): px = a.bucket_price if px < mark_price * 0.999: continue dist_pct = abs((px - mark_price) / mark_price * 100.0) peak = a.peak_visible_usd curr = a.current_visible_usd if peak >= spoof_wall_min and dist_pct <= 0.15: vanished = peak - curr if curr <= 0.30 * peak and vanished >= spoof_wall_min * 0.70: filled = a.executed_taker_buy_usd if filled < 0.15 * vanished: default_res["spoof_pulled"] = True default_res["spoof_side"] = "ASK" default_res["spoof_price"] = round(px, 4 if px < 10 else 2) default_res["pulled_wall_usd"] = round(vanished, 2) default_res["spoof_note"] = ( f"Confirmed ASK Wall Pulling/Spoof: Wall ${peak:,.0f} ditarik 70%+ " f"saat harga mendekat ({dist_pct:.2f}%); hanya ${filled:,.0f} yang terisi." ) break return default_res # Global singleton instance _GLOBAL_L2_TRACKER: L2OrderbookTracker | None = None def get_l2_tracker() -> L2OrderbookTracker: global _GLOBAL_L2_TRACKER if _GLOBAL_L2_TRACKER is None: _GLOBAL_L2_TRACKER = L2OrderbookTracker() return _GLOBAL_L2_TRACKER