Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download backend/engine/fake_detector.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/engine/fake_detector.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/engine/fake_detector.py
-
curl -L -o fake_detector.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/engine/fake_detector.py
11 kB
| """ | |
| Fake Move / Manipulation Detector. | |
| Detects: | |
| 1. Wick sweeps followed by close-back (liquidity grab) | |
| 2. Volume spike with minimal price move (wash trading) | |
| 3. Cross-exchange price divergence (one exchange lead / lag) | |
| """ | |
| import logging | |
| from typing import Any | |
| logger = logging.getLogger(__name__) | |
| # Thresholds | |
| WICK_RANGE_MIN_PCT = 0.001 # candle total range must be >= 0.1% to qualify as a real sweep | |
| WICK_DOMINANCE_RATIO = 0.60 # wick must comprise >60% of candle's high-low range | |
| MIN_VOLUME_SPIKE_MULTIPLIER = 3.0 # volume > 3x avg = spike | |
| MAX_PRICE_MOVE_FOR_WASHTRADING = 0.001 # <0.1% price move during volume spike | |
| CROSS_EXCHANGE_DIVERGENCE_PCT = 0.30 # >0.3% divergence = suspicious | |
| ORDERBOOK_WALL_IMBALANCE_THRESHOLD = 0.70 # >70% book imbalance = wall spoofing / absorption | |
| def _wick_sweep_detected(candles: list[dict]) -> tuple[bool, str]: | |
| """ | |
| Detect genuine wick sweep / liquidity grab in the last completed candles. | |
| Excludes the forming/incomplete candle (candles[-1]) and requires meaningful | |
| high-low range (>=0.1%) and wick dominance (>60% of total range). | |
| """ | |
| if len(candles) < 3: | |
| return False, "" | |
| # Evaluate completed candles only (newest first so latest liquidity sweep wins) | |
| recent = candles[-4:-1] if len(candles) >= 4 else candles[:-1] | |
| for c in reversed(recent): | |
| high = c.get("high") | |
| low = c.get("low") | |
| open_p = c.get("open") | |
| close = float(c.get("close") or 0) | |
| if high is None or low is None or open_p is None or close <= 0: | |
| continue | |
| rng = float(high) - float(low) | |
| if rng <= 0 or (rng / close) < WICK_RANGE_MIN_PCT: | |
| continue | |
| upper_wick = float(high) - max(close, float(open_p)) | |
| lower_wick = min(close, float(open_p)) - float(low) | |
| if (upper_wick / rng) > WICK_DOMINANCE_RATIO: | |
| return True, "upper_wick_sweep (Liquidity Grab at Highs)" | |
| if (lower_wick / rng) > WICK_DOMINANCE_RATIO: | |
| return True, "lower_wick_sweep (Liquidity Grab at Lows)" | |
| return False, "" | |
| def _wash_trade_detected(candles: list[dict]) -> bool: | |
| """Volume spike with tiny price move = possible wash trading.""" | |
| if len(candles) < 20: | |
| return False | |
| volumes = [float(c["volume"]) for c in candles[:-2] if c.get("volume") is not None] | |
| if not volumes: | |
| return False | |
| avg_vol = sum(volumes) / len(volumes) | |
| if avg_vol <= 0: | |
| return False | |
| # Check the last completed candles (candles[-3] and candles[-2]), excluding the incomplete forming candle candles[-1] | |
| candidates = [candles[-3], candles[-2]] if len(candles) >= 21 else [candles[-2]] | |
| for cand in candidates: | |
| cand_vol = float(cand.get("volume") or 0) | |
| cand_open = float(cand.get("open") or 0) | |
| cand_close = float(cand.get("close") or 0) | |
| cand_high = float(cand.get("high") or 0) | |
| cand_low = float(cand.get("low") or 0) | |
| if cand_vol > avg_vol * MIN_VOLUME_SPIKE_MULTIPLIER: | |
| if cand_open > 0: | |
| price_move_pct = abs(cand_close - cand_open) / cand_open | |
| cand_rng_pct = max(0.0, cand_high - cand_low) / cand_open | |
| if price_move_pct < MAX_PRICE_MOVE_FOR_WASHTRADING and cand_rng_pct < 0.015: | |
| return True | |
| return False | |
| def _orderbook_imbalance_detected( | |
| orderbook: dict | None, | |
| cvd_matches_price: bool, | |
| cvd_rising: bool | None = None, | |
| ) -> tuple[bool, str]: | |
| """Detect extreme order book depth imbalance / spoofing walls.""" | |
| if not orderbook: | |
| return False, "" | |
| bids = orderbook.get("bids", []) | |
| asks = orderbook.get("asks", []) | |
| if not bids or not asks: | |
| return False, "" | |
| try: | |
| bid_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (bids or [])[:20] if lvl) | |
| ask_vol = sum(float(lvl[0]) * float(lvl[1]) for lvl in (asks or [])[:20] if lvl) | |
| except (ValueError, TypeError, IndexError): | |
| return False, "" | |
| total_vol = bid_vol + ask_vol | |
| if total_vol <= 0: | |
| return False, "" | |
| imbalance = (bid_vol - ask_vol) / total_vol | |
| if cvd_rising is not None: | |
| # True aggressive-flow check catches spoofs even when price & CVD drop together | |
| if imbalance >= ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_rising: | |
| return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof" | |
| if imbalance <= -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and cvd_rising: | |
| return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof" | |
| else: | |
| # Backward-compatible fallback when caller does not pass cvd_rising | |
| if imbalance >= ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price: | |
| return True, f"Bid Wall Imbalance ({imbalance:.1%}) with Selling Pressure — Possible Wall Spoof" | |
| if imbalance <= -ORDERBOOK_WALL_IMBALANCE_THRESHOLD and not cvd_matches_price: | |
| return True, f"Ask Wall Imbalance ({abs(imbalance):.1%}) with Buying Pressure — Possible Wall Spoof" | |
| return False, "" | |
| def _cross_exchange_divergence( | |
| binance_mark: float | None = None, | |
| bybit_mark: float | None = None, | |
| venue_prices: dict[str, float] | None = None, | |
| ) -> tuple[float, bool]: | |
| """ | |
| Returns (divergence_pct, is_divergent). | |
| Evaluates multi-venue divergence if venue_prices provided, otherwise Binance vs Bybit. | |
| Divergent if max spread / min price > threshold. | |
| """ | |
| if venue_prices: | |
| valid_venues = {k: float(v) for k, v in venue_prices.items() if v is not None and float(v) > 0} | |
| if len(valid_venues) >= 2: | |
| highest_p = max(valid_venues.values()) | |
| lowest_p = min(valid_venues.values()) | |
| div_pct = ((highest_p - lowest_p) / lowest_p * 100.0) if lowest_p > 0 else 0.0 | |
| return round(div_pct, 4), div_pct > CROSS_EXCHANGE_DIVERGENCE_PCT | |
| if binance_mark is None or bybit_mark is None or binance_mark <= 0 or bybit_mark <= 0: | |
| return 0.0, False | |
| avg = (binance_mark + bybit_mark) / 2 | |
| div_pct = abs(binance_mark - bybit_mark) / avg * 100 | |
| return round(div_pct, 4), div_pct > CROSS_EXCHANGE_DIVERGENCE_PCT | |
| class FakeDetector: | |
| """ | |
| Analyses collected data for manipulation signals. | |
| Returns a score penalty (0 or negative) and a list of warnings. | |
| """ | |
| def detect( | |
| self, | |
| ohlcv_1m: list[dict], | |
| ohlcv_5m: list[dict], | |
| binance_mark: float | None, | |
| bybit_mark: float | None, | |
| cvd_matches_price: bool, | |
| orderbook: dict | None = None, | |
| venue_prices: dict[str, float] | None = None, | |
| cvd_rising: bool | None = None, | |
| l2_microstructure: dict[str, Any] | None = None, | |
| ) -> dict[str, Any]: | |
| """ | |
| Parameters | |
| ---------- | |
| ohlcv_1m : 1-min candles (short-term wick detection) | |
| ohlcv_5m : 5-min candles (volume-spike detection) | |
| binance_mark : current Binance mark price | |
| bybit_mark : current Bybit mark price | |
| cvd_matches_price: False if CVD momentum opposes price momentum | |
| orderbook : top 20 order book depth | |
| Returns | |
| ------- | |
| { | |
| "is_fake": bool, | |
| "warnings": [str], | |
| "divergence_pct": float, | |
| "score": int, # 0 or negative penalty (-1 to -3) | |
| "label": str, | |
| } | |
| """ | |
| warnings: list[str] = [] | |
| score_penalty = 0 | |
| # 1. Wick sweep (fallback to 5m when 1m has < 3 bars) | |
| sweep_candles = ohlcv_1m if (ohlcv_1m and len(ohlcv_1m) >= 3) else ohlcv_5m | |
| sweep_detected, sweep_dir = _wick_sweep_detected(sweep_candles) | |
| if sweep_detected: | |
| warnings.append(f"Wick sweep detected ({sweep_dir}) — potential liquidity sweep") | |
| score_penalty -= 1 | |
| # 2. Wash trading | |
| wash_detected = _wash_trade_detected(ohlcv_5m) | |
| if wash_detected: | |
| warnings.append("Volume spike with minimal price move — possible wash trading / absorption") | |
| score_penalty -= 1 | |
| # 3. Cross-exchange divergence | |
| divergence_pct, is_divergent = _cross_exchange_divergence( | |
| binance_mark=binance_mark, | |
| bybit_mark=bybit_mark, | |
| venue_prices=venue_prices, | |
| ) | |
| if is_divergent: | |
| div_msg = ( | |
| f"Cross-exchange price divergence {divergence_pct:.3f}% > " | |
| f"{CROSS_EXCHANGE_DIVERGENCE_PCT}% threshold" | |
| ) | |
| if venue_prices: | |
| valid_v = {k: float(v) for k, v in venue_prices.items() if v is not None and float(v) > 0} | |
| if len(valid_v) >= 2: | |
| h_v = max(valid_v, key=valid_v.get) | |
| l_v = min(valid_v, key=valid_v.get) | |
| div_msg = ( | |
| f"Cross-exchange price divergence {divergence_pct:.3f}% " | |
| f"({h_v.upper()} vs {l_v.upper()}) > {CROSS_EXCHANGE_DIVERGENCE_PCT}% threshold" | |
| ) | |
| warnings.append(div_msg) | |
| score_penalty -= 1 | |
| # 4. CVD vs price mismatch (order flow absorption) | |
| if not cvd_matches_price: | |
| warnings.append("CVD delta momentum opposes price move — aggressive delta absorption") | |
| score_penalty -= 1 | |
| # 5. Orderbook depth spoofing wall | |
| ob_spoof, ob_msg = _orderbook_imbalance_detected(orderbook, cvd_matches_price, cvd_rising=cvd_rising) | |
| if ob_spoof: | |
| warnings.append(ob_msg) | |
| score_penalty -= 1 | |
| # 5b. Confirmed L2 Wall Pulling / Spoofing | |
| if l2_microstructure and isinstance(l2_microstructure, dict) and l2_microstructure.get("spoof_pulled"): | |
| spoof_msg = l2_microstructure.get("spoof_note") or "Confirmed L2 Wall Pulling / Spoofing" | |
| warnings.append(spoof_msg) | |
| ob_spoof = True | |
| is_fake = sweep_detected or (len(warnings) >= 2) | |
| sweep_direction = "NONE" | |
| if "lower_wick_sweep" in sweep_dir: | |
| sweep_direction = "LOWER_SWEEP" | |
| elif "upper_wick_sweep" in sweep_dir: | |
| sweep_direction = "UPPER_SWEEP" | |
| has_non_sweep_manipulation = bool(wash_detected or is_divergent or ob_spoof) | |
| label = ( | |
| "Strong Manipulation Signals" | |
| if is_fake | |
| else ("Minor Warnings" if warnings else "Clean (No Manipulation Detected)") | |
| ) | |
| # Warning is informational label only; does not penalize conviction score per user specification | |
| score_penalty = 0 | |
| return { | |
| "is_fake": is_fake, | |
| "warnings": warnings, | |
| "reason": "; ".join(warnings) if warnings else "", | |
| "divergence_pct": divergence_pct, | |
| "score": score_penalty, | |
| "label": label, | |
| "sweep_direction": sweep_direction, | |
| "has_non_sweep_manipulation": has_non_sweep_manipulation, | |
| } | |