Spaces:
Sleeping
Sleeping
Naufal Arhab
perf(whale,db): add HL maker_wallet discovery, 2-tier scout DB gate & dirty-check, bounded RAM, and non-locking accuracy query
7088133 Download backend/database/memory_store.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 39.6 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/database/memory_store.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/database/memory_store.py
-
curl -L -o memory_store.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/database/memory_store.py
39.6 kB
| """ | |
| Thread-safe in-memory fallback store when DATABASE_URL is not configured. | |
| Ensures stateless local runs, previews, and tests never crash with | |
| RuntimeError("DATABASE_URL is not configured.") across pairs, signals, | |
| snapshots, trade journal, and Damian memory APIs. | |
| """ | |
| import copy | |
| import threading | |
| from datetime import datetime, timezone | |
| from typing import Any | |
| def _utc_now_iso() -> str: | |
| return datetime.now(timezone.utc).isoformat() | |
| class InMemoryDatabaseStore: | |
| """Thread-safe bounded in-memory mirror of the PostgreSQL schema.""" | |
| def __init__(self) -> None: | |
| self._lock = threading.RLock() | |
| self._pair_seq = 0 | |
| self._signal_seq = 0 | |
| self._snapshot_seq = 0 | |
| self._journal_seq = 0 | |
| self._memory_seq = 0 | |
| self._prediction_seq = 0 | |
| self._pairs: dict[str, dict[str, Any]] = {} | |
| self._signals: dict[str, list[dict[str, Any]]] = {} | |
| self._snapshots: dict[str, dict[str, dict[str, Any]]] = {} | |
| self._journal: dict[int, dict[str, Any]] = {} | |
| self._memories: list[dict[str, Any]] = [] | |
| self._predictions: dict[int, dict[str, Any]] = {} | |
| self._hl_wallets: dict[str, dict[str, Any]] = {} | |
| self._microstructure_tape: list[dict[str, Any]] = [] | |
| self._tape_seq = 0 | |
| self._seed_defaults() | |
| def _seed_defaults(self) -> None: | |
| now = _utc_now_iso() | |
| for sym, disp in (("BTCUSDT", "BTC/USDT"), ("ETHUSDT", "ETH/USDT"), ("SOLUSDT", "SOL/USDT")): | |
| self._pair_seq += 1 | |
| self._pairs[sym] = { | |
| "id": self._pair_seq, | |
| "symbol": sym, | |
| "display_name": disp, | |
| "on_binance": True, | |
| "on_bybit": True, | |
| "on_okx": True, | |
| "on_bitget": True, | |
| "on_hyperliquid": True, | |
| "streak_count": 0, | |
| "streak_direction": "NEUTRAL", | |
| "last_conviction": 0, | |
| "is_active": True, | |
| "created_at": now, | |
| } | |
| def reset(self) -> None: | |
| with self._lock: | |
| self._pair_seq = 0 | |
| self._signal_seq = 0 | |
| self._snapshot_seq = 0 | |
| self._journal_seq = 0 | |
| self._memory_seq = 0 | |
| self._prediction_seq = 0 | |
| self._pairs.clear() | |
| self._signals.clear() | |
| self._snapshots.clear() | |
| self._journal.clear() | |
| self._memories.clear() | |
| self._predictions.clear() | |
| self._hl_wallets.clear() | |
| self._microstructure_tape.clear() | |
| self._tape_seq = 0 | |
| self._seed_defaults() | |
| # ── Pairs ──────────────────────────────────────────────────────────────── | |
| def get_all_pairs(self) -> list[dict[str, Any]]: | |
| with self._lock: | |
| rows = list(self._pairs.values()) | |
| rows.sort(key=lambda p: (p.get("created_at") or "", int(p.get("id") or 0)), reverse=True) | |
| return [copy.deepcopy(r) for r in rows] | |
| def get_pair(self, symbol: str) -> dict[str, Any] | None: | |
| with self._lock: | |
| row = self._pairs.get(symbol.upper()) | |
| return copy.deepcopy(row) if row else None | |
| def insert_pair( | |
| self, | |
| symbol: str, | |
| display_name: str, | |
| on_binance: bool = False, | |
| on_bybit: bool = False, | |
| on_okx: bool = False, | |
| on_bitget: bool = False, | |
| on_hyperliquid: bool = False, | |
| ) -> dict[str, Any]: | |
| sym = symbol.upper() | |
| with self._lock: | |
| existing = self._pairs.get(sym) | |
| if existing: | |
| existing.update({ | |
| "display_name": display_name, | |
| "on_binance": bool(on_binance), | |
| "on_bybit": bool(on_bybit), | |
| "on_okx": bool(on_okx), | |
| "on_bitget": bool(on_bitget), | |
| "on_hyperliquid": bool(on_hyperliquid), | |
| "is_active": True, | |
| }) | |
| return copy.deepcopy(existing) | |
| self._pair_seq += 1 | |
| row = { | |
| "id": self._pair_seq, | |
| "symbol": sym, | |
| "display_name": display_name, | |
| "on_binance": bool(on_binance), | |
| "on_bybit": bool(on_bybit), | |
| "on_okx": bool(on_okx), | |
| "on_bitget": bool(on_bitget), | |
| "on_hyperliquid": bool(on_hyperliquid), | |
| "streak_count": 0, | |
| "streak_direction": "NEUTRAL", | |
| "last_conviction": 0, | |
| "is_active": True, | |
| "created_at": _utc_now_iso(), | |
| } | |
| self._pairs[sym] = row | |
| return copy.deepcopy(row) | |
| def update_pair_exchanges( | |
| self, | |
| symbol: str, | |
| on_binance: bool, | |
| on_bybit: bool, | |
| on_okx: bool = False, | |
| on_bitget: bool = False, | |
| on_hyperliquid: bool = False, | |
| ) -> dict[str, Any] | None: | |
| sym = symbol.upper() | |
| with self._lock: | |
| row = self._pairs.get(sym) | |
| if not row: | |
| return None | |
| row.update({ | |
| "on_binance": bool(on_binance), | |
| "on_bybit": bool(on_bybit), | |
| "on_okx": bool(on_okx), | |
| "on_bitget": bool(on_bitget), | |
| "on_hyperliquid": bool(on_hyperliquid), | |
| }) | |
| return copy.deepcopy(row) | |
| def update_pair_streak( | |
| self, | |
| symbol: str, | |
| streak_count: int, | |
| streak_direction: str, | |
| last_conviction: int, | |
| ) -> dict[str, Any] | None: | |
| sym = symbol.upper() | |
| with self._lock: | |
| row = self._pairs.get(sym) | |
| if not row: | |
| return None | |
| row.update({ | |
| "streak_count": int(streak_count), | |
| "streak_direction": str(streak_direction), | |
| "last_conviction": int(last_conviction), | |
| }) | |
| return copy.deepcopy(row) | |
| def delete_pair(self, symbol: str) -> bool: | |
| sym = symbol.upper() | |
| with self._lock: | |
| return self._pairs.pop(sym, None) is not None | |
| def delete_pair_by_identifier(self, identifier: str) -> bool: | |
| with self._lock: | |
| if identifier.isdigit(): | |
| target_id = int(identifier) | |
| for sym, row in list(self._pairs.items()): | |
| if row.get("id") == target_id: | |
| del self._pairs[sym] | |
| return True | |
| return False | |
| return self._pairs.pop(identifier.upper(), None) is not None | |
| def toggle_pair(self, symbol: str) -> dict[str, Any] | None: | |
| sym = symbol.upper() | |
| with self._lock: | |
| row = self._pairs.get(sym) | |
| if not row: | |
| return None | |
| row["is_active"] = not bool(row.get("is_active", True)) | |
| return copy.deepcopy(row) | |
| def toggle_pair_by_identifier(self, identifier: str) -> dict[str, Any] | None: | |
| with self._lock: | |
| if identifier.isdigit(): | |
| target_id = int(identifier) | |
| for row in self._pairs.values(): | |
| if row.get("id") == target_id: | |
| row["is_active"] = not bool(row.get("is_active", True)) | |
| return copy.deepcopy(row) | |
| return None | |
| return self.toggle_pair(identifier) | |
| def get_active_pairs(self) -> list[dict[str, Any]]: | |
| with self._lock: | |
| active = [copy.deepcopy(r) for r in self._pairs.values() if r.get("is_active")] | |
| active.sort(key=lambda r: r["symbol"]) | |
| return active | |
| def get_stale_active_pairs(self, limit: int | None = None) -> list[dict[str, Any]]: | |
| with self._lock: | |
| active = [r for r in self._pairs.values() if r.get("is_active")] | |
| def _sort_key(pair: dict[str, Any]) -> tuple[str, str]: | |
| hist = self._signals.get(pair["symbol"], []) | |
| last_ts = hist[0].get("created_at", "") if hist else "" | |
| return (last_ts, pair["symbol"]) | |
| active.sort(key=_sort_key) | |
| if limit is not None and limit > 0: | |
| active = active[:limit] | |
| return [copy.deepcopy(r) for r in active] | |
| # ── Signals & Snapshots ────────────────────────────────────────────────── | |
| def _enrich_signal_row(self, sig: dict[str, Any]) -> dict[str, Any]: | |
| out = copy.deepcopy(sig) | |
| pair = self._pairs.get(out["symbol"], {}) | |
| streak = int(pair.get("streak_count") or 0) | |
| streak_dir = str(pair.get("streak_direction") or "NEUTRAL") | |
| last_conv = int(pair.get("last_conviction") or 0) | |
| out["streak_count"] = streak | |
| out["streak_direction"] = streak_dir | |
| out["last_conviction"] = last_conv | |
| if isinstance(out.get("signal_data"), dict): | |
| if "streak" not in out["signal_data"] or out["signal_data"].get("streak") is None: | |
| out["signal_data"]["streak"] = streak | |
| if "streak_direction" not in out["signal_data"] or not out["signal_data"].get("streak_direction"): | |
| out["signal_data"]["streak_direction"] = streak_dir | |
| return out | |
| def save_signal( | |
| self, | |
| symbol: str, | |
| timeframe: str, | |
| direction: str, | |
| conviction: int, | |
| signal_data: dict[str, Any], | |
| ) -> None: | |
| clean_signal_data = signal_data | |
| if isinstance(signal_data, dict) and "_shadow_trade_levels" in signal_data: | |
| clean_signal_data = dict(signal_data) | |
| clean_signal_data.pop("_shadow_trade_levels", None) | |
| sym = symbol.upper() | |
| with self._lock: | |
| self._signal_seq += 1 | |
| entry = { | |
| "id": self._signal_seq, | |
| "symbol": sym, | |
| "timeframe": timeframe, | |
| "direction": direction, | |
| "conviction": int(conviction), | |
| "signal_data": copy.deepcopy(clean_signal_data), | |
| "created_at": _utc_now_iso(), | |
| } | |
| bucket = self._signals.setdefault(sym, []) | |
| bucket.insert(0, entry) | |
| if len(bucket) > 100: | |
| del bucket[100:] | |
| def get_latest_signals(self) -> list[dict[str, Any]]: | |
| with self._lock: | |
| latest = [ | |
| self._enrich_signal_row(bucket[0]) | |
| for sym, bucket in sorted(self._signals.items()) | |
| if bucket | |
| ] | |
| return latest | |
| def get_signal_history(self, symbol: str, limit: int = 50) -> list[dict[str, Any]]: | |
| sym = symbol.upper() | |
| with self._lock: | |
| bucket = self._signals.get(sym, [])[:limit] | |
| return [self._enrich_signal_row(r) for r in bucket] | |
| def get_latest_signal(self, symbol: str) -> dict[str, Any] | None: | |
| sym = symbol.upper() | |
| with self._lock: | |
| bucket = self._signals.get(sym) | |
| if not bucket: | |
| return None | |
| return self._enrich_signal_row(bucket[0]) | |
| def save_snapshot( | |
| self, | |
| symbol: str, | |
| exchange: str, | |
| funding_rate: float | None, | |
| open_interest: float | None, | |
| long_ratio: float | None, | |
| short_ratio: float | None, | |
| mark_price: float | None, | |
| index_price: float | None, | |
| basis_pct: float | None, | |
| ) -> None: | |
| sym = symbol.upper() | |
| ex = exchange.lower() | |
| with self._lock: | |
| self._snapshot_seq += 1 | |
| self._snapshots.setdefault(sym, {})[ex] = { | |
| "id": self._snapshot_seq, | |
| "symbol": sym, | |
| "exchange": ex, | |
| "funding_rate": funding_rate, | |
| "open_interest": open_interest, | |
| "long_ratio": long_ratio, | |
| "short_ratio": short_ratio, | |
| "mark_price": mark_price, | |
| "index_price": index_price, | |
| "basis_pct": basis_pct, | |
| "snapshot_at": _utc_now_iso(), | |
| } | |
| def save_snapshots_batch(self, snapshots: list[tuple]) -> None: | |
| for snap in snapshots: | |
| self.save_snapshot(*snap) | |
| def get_latest_snapshot(self, symbol: str) -> list[dict[str, Any]]: | |
| sym = symbol.upper() | |
| with self._lock: | |
| ex_map = self._snapshots.get(sym, {}) | |
| return [copy.deepcopy(ex_map[ex]) for ex in sorted(ex_map.keys())] | |
| # ── Trade Journal & Damian Memory ──────────────────────────────────────── | |
| def create_journal_entry(self, data: dict[str, Any]) -> dict[str, Any]: | |
| with self._lock: | |
| self._journal_seq += 1 | |
| entry = { | |
| "id": self._journal_seq, | |
| "symbol": str(data.get("symbol") or "").upper(), | |
| "bias": data.get("bias", ""), | |
| "entry_zone": data.get("entry_zone"), | |
| "stop_loss": data.get("stop_loss"), | |
| "take_profit": data.get("take_profit"), | |
| "risk_reward": data.get("risk_reward"), | |
| "leverage": data.get("leverage"), | |
| "invalidation": data.get("invalidation"), | |
| "summary_tldr": data.get("summary_tldr"), | |
| "full_analysis": data.get("full_analysis"), | |
| "model_used": data.get("model_used"), | |
| "status": str(data.get("status") or "PENDING").upper(), | |
| "outcome_note": data.get("outcome_note"), | |
| "outcome_at": None, | |
| "failure_tag": data.get("failure_tag"), | |
| "exit_price": data.get("exit_price"), | |
| "holding_duration_seconds": data.get("holding_duration_seconds"), | |
| "snapshot_data": copy.deepcopy(data.get("snapshot_data") or {}), | |
| "audited": False, | |
| "created_at": _utc_now_iso(), | |
| } | |
| self._journal[entry["id"]] = entry | |
| return copy.deepcopy(entry) | |
| def get_journal_entries( | |
| self, status: str | None = None, limit: int = 50, offset: int = 0 | |
| ) -> list[dict[str, Any]]: | |
| with self._lock: | |
| rows = list(self._journal.values()) | |
| if status and status.upper() != "ALL": | |
| target = status.upper() | |
| rows = [r for r in rows if r.get("status") == target] | |
| rows.sort(key=lambda r: (r.get("created_at") or "", r["id"]), reverse=True) | |
| sliced = rows[offset : offset + limit] | |
| return [copy.deepcopy(r) for r in sliced] | |
| def update_journal_status( | |
| self, | |
| journal_id: int, | |
| status: str, | |
| note: str | None = None, | |
| failure_tag: str | None = None, | |
| exit_price: float | None = None, | |
| holding_duration_seconds: int | None = None, | |
| ) -> dict[str, Any] | None: | |
| st = status.upper().strip() | |
| with self._lock: | |
| entry = self._journal.get(journal_id) | |
| if not entry: | |
| return None | |
| entry["status"] = st | |
| if st == "PENDING": | |
| entry["outcome_note"] = None | |
| entry["outcome_at"] = None | |
| entry["failure_tag"] = None | |
| entry["exit_price"] = None | |
| entry["holding_duration_seconds"] = None | |
| entry["audited"] = False | |
| return copy.deepcopy(entry) | |
| entry["outcome_note"] = note | |
| entry["outcome_at"] = _utc_now_iso() | |
| if st == "HIT_SL": | |
| if failure_tag is not None: | |
| entry["failure_tag"] = failure_tag | |
| else: | |
| entry["failure_tag"] = None | |
| entry["audited"] = False | |
| if exit_price is not None: | |
| entry["exit_price"] = exit_price | |
| if holding_duration_seconds is not None: | |
| entry["holding_duration_seconds"] = holding_duration_seconds | |
| return copy.deepcopy(entry) | |
| def delete_journal_entry(self, journal_id: int) -> bool: | |
| with self._lock: | |
| return self._journal.pop(journal_id, None) is not None | |
| def get_journal_stats(self) -> dict[str, Any]: | |
| with self._lock: | |
| entries = list(self._journal.values()) | |
| total = len(entries) | |
| hit_tp = sum(1 for e in entries if e.get("status") == "HIT_TP") | |
| hit_sl = sum(1 for e in entries if e.get("status") == "HIT_SL") | |
| pending = sum(1 for e in entries if e.get("status") == "PENDING") | |
| cancelled = sum(1 for e in entries if e.get("status") == "CANCELLED") | |
| unaudited_sl = sum(1 for e in entries if e.get("status") == "HIT_SL" and not e.get("audited")) | |
| completed = hit_tp + hit_sl | |
| win_rate = round((hit_tp / completed) * 100.0, 1) if completed > 0 else 0.0 | |
| return { | |
| "total": total, | |
| "hit_tp": hit_tp, | |
| "hit_sl": hit_sl, | |
| "pending": pending, | |
| "cancelled": cancelled, | |
| "completed": completed, | |
| "win_rate_pct": win_rate, | |
| "unaudited_sl_count": unaudited_sl, | |
| } | |
| def get_unaudited_failed_trades(self, limit: int = 10) -> list[dict[str, Any]]: | |
| with self._lock: | |
| failed = [ | |
| r for r in self._journal.values() | |
| if r.get("status") == "HIT_SL" and not r.get("audited") | |
| ] | |
| failed.sort(key=lambda r: (r.get("created_at") or "", r["id"])) | |
| return [copy.deepcopy(r) for r in failed[:limit]] | |
| def mark_trades_as_audited(self, trade_ids: list[int]) -> None: | |
| if not trade_ids: | |
| return | |
| with self._lock: | |
| for tid in trade_ids: | |
| if tid in self._journal: | |
| self._journal[tid]["audited"] = True | |
| def save_damian_memory(self, audit_summary: str, model_used: str, failed_count: int = 10) -> dict[str, Any]: | |
| with self._lock: | |
| self._memory_seq += 1 | |
| next_batch = max((int(m.get("batch_index") or 0) for m in self._memories), default=0) + 1 | |
| mem = { | |
| "id": self._memory_seq, | |
| "batch_index": next_batch, | |
| "failed_count": int(failed_count), | |
| "model_used": model_used, | |
| "audit_summary": audit_summary, | |
| "is_active": True, | |
| "created_at": _utc_now_iso(), | |
| } | |
| self._memories.insert(0, mem) | |
| return copy.deepcopy(mem) | |
| def get_active_damian_memory(self, limit: int = 3) -> list[dict[str, Any]]: | |
| with self._lock: | |
| active = [m for m in self._memories if m.get("is_active", True)] | |
| return [copy.deepcopy(m) for m in active[:limit]] | |
| def _parse_utc_dt(val: Any) -> datetime | None: | |
| if val is None: | |
| return None | |
| if isinstance(val, datetime): | |
| return val.replace(tzinfo=timezone.utc) if val.tzinfo is None else val.astimezone(timezone.utc) | |
| if isinstance(val, str): | |
| raw = val.strip() | |
| if not raw: | |
| return None | |
| try: | |
| dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) | |
| return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc) | |
| except ValueError: | |
| return None | |
| return None | |
| def _to_iso(cls, val: Any, fallback: str) -> str: | |
| dt = cls._parse_utc_dt(val) | |
| if dt is not None: | |
| return dt.isoformat() | |
| if isinstance(val, str) and val.strip(): | |
| return val.strip() | |
| return fallback | |
| # ── Signal Predictions (Forward Accuracy Tracker) ──────────────────────── | |
| def insert_signal_prediction(self, data: dict[str, Any]) -> dict[str, Any]: | |
| with self._lock: | |
| self._prediction_seq += 1 | |
| now_iso = _utc_now_iso() | |
| row = { | |
| "id": self._prediction_seq, | |
| "symbol": str(data.get("symbol", "")).upper().strip(), | |
| "horizon": str(data.get("horizon", "intraday")), | |
| "direction": str(data.get("direction", "NEUTRAL")), | |
| "conviction": int(data.get("conviction", 0)), | |
| "regime": str(data.get("regime", "ranging")), | |
| "sniper_grade": str(data.get("sniper_grade", "WAIT")), | |
| "entry_price": float(data.get("entry_price", 0.0)), | |
| "stop_loss": float(data.get("stop_loss", 0.0)), | |
| "tp1": float(data.get("tp1", 0.0)), | |
| "tp2": float(data.get("tp2", 0.0)), | |
| "factor_scores": copy.deepcopy(data.get("factor_scores") or {}), | |
| "outcome": str(data.get("outcome") or "PENDING"), | |
| "outcome_price": data.get("outcome_price"), | |
| "r_multiple": data.get("r_multiple"), | |
| "created_at": self._to_iso(data.get("created_at"), now_iso), | |
| "expires_at": self._to_iso(data.get("expires_at"), now_iso), | |
| "evaluated_at": self._to_iso(data.get("evaluated_at"), "") if data.get("evaluated_at") else None, | |
| "is_shadow": bool(data.get("is_shadow", False)), | |
| "veto_reason": data.get("veto_reason"), | |
| } | |
| self._predictions[row["id"]] = row | |
| return copy.deepcopy(row) | |
| def get_pending_predictions(self, limit: int = 200) -> list[dict[str, Any]]: | |
| epoch_min = datetime.min.replace(tzinfo=timezone.utc) | |
| with self._lock: | |
| pending = [r for r in self._predictions.values() if r.get("outcome") == "PENDING"] | |
| pending.sort(key=lambda r: (self._parse_utc_dt(r.get("expires_at")) or epoch_min, r["id"])) | |
| return [copy.deepcopy(r) for r in pending[:limit]] | |
| def update_signal_prediction_outcome( | |
| self, | |
| pred_id: int, | |
| outcome: str, | |
| outcome_price: float, | |
| r_multiple: float, | |
| ) -> dict[str, Any] | None: | |
| with self._lock: | |
| row = self._predictions.get(int(pred_id)) | |
| if not row: | |
| return None | |
| row["outcome"] = outcome | |
| row["outcome_price"] = float(outcome_price) | |
| row["r_multiple"] = float(r_multiple) | |
| row["evaluated_at"] = _utc_now_iso() | |
| return copy.deepcopy(row) | |
| def get_recent_prediction( | |
| self, | |
| symbol: str, | |
| horizon: str, | |
| direction: str, | |
| cooldown_hours: int, | |
| is_shadow: bool = False, | |
| veto_reason: str | None = None, | |
| ) -> dict[str, Any] | None: | |
| sym = symbol.upper().strip() | |
| now_dt = datetime.now(timezone.utc) | |
| with self._lock: | |
| candidates = [ | |
| r for r in self._predictions.values() | |
| if r.get("symbol") == sym and r.get("horizon") == horizon | |
| ] | |
| if not is_shadow: | |
| candidates = [r for r in candidates if not r.get("is_shadow")] | |
| else: | |
| candidates = [ | |
| r for r in candidates | |
| if r.get("is_shadow") and r.get("veto_reason") == veto_reason | |
| ] | |
| candidates.sort(key=lambda r: r["id"], reverse=True) | |
| for r in candidates: | |
| if r.get("outcome") == "PENDING": | |
| return copy.deepcopy(r) | |
| if r.get("direction") == direction: | |
| c_dt = self._parse_utc_dt(r.get("created_at")) | |
| if c_dt is not None and (now_dt - c_dt).total_seconds() < cooldown_hours * 3600: | |
| return copy.deepcopy(r) | |
| return None | |
| def get_accuracy_summary(self, days: int = 30, symbol: str | None = None) -> dict[str, Any]: | |
| sym_filter = symbol.upper().strip() if symbol else None | |
| now_dt = datetime.now(timezone.utc) | |
| cutoff_sec = max(1, int(days)) * 86400 | |
| with self._lock: | |
| rows = [] | |
| for r in self._predictions.values(): | |
| if sym_filter and r.get("symbol") != sym_filter: | |
| continue | |
| c_dt = self._parse_utc_dt(r.get("created_at")) | |
| if c_dt is None or (now_dt - c_dt).total_seconds() > cutoff_sec: | |
| continue | |
| rows.append(copy.deepcopy(r)) | |
| return compute_accuracy_summary_from_rows(rows, days=days) | |
| # ── Hyperliquid Whale Wallets ───────────────────────────────────────────── | |
| def upsert_hl_wallet(self, wallet: dict[str, Any]) -> dict[str, Any]: | |
| with self._lock: | |
| addr = str(wallet.get("address", "")).lower() | |
| if not addr: | |
| return {} | |
| existing = self._hl_wallets.get(addr, {}) | |
| merged = { | |
| "address": addr, | |
| "label": wallet.get("label") or existing.get("label"), | |
| "account_value_usd": float(wallet.get("account_value_usd", existing.get("account_value_usd", 0.0)) or 0.0), | |
| "total_notional_usd": float(wallet.get("total_notional_usd", existing.get("total_notional_usd", 0.0)) or 0.0), | |
| "cumulative_pnl_usd": float(wallet.get("cumulative_pnl_usd", existing.get("cumulative_pnl_usd", 0.0)) or 0.0), | |
| "win_count": int(wallet.get("win_count", existing.get("win_count", 0)) or 0), | |
| "loss_count": int(wallet.get("loss_count", existing.get("loss_count", 0)) or 0), | |
| "reliability_score": float(wallet.get("reliability_score", existing.get("reliability_score", 1.0)) or 1.0), | |
| "tier": wallet.get("tier", existing.get("tier", "UNPROVEN")), | |
| "positions_json": copy.deepcopy(wallet.get("positions_json", existing.get("positions_json", {}))), | |
| "recent_events_json": copy.deepcopy(wallet.get("recent_events_json", existing.get("recent_events_json", []))), | |
| "updated_at": _utc_now_iso(), | |
| } | |
| self._hl_wallets[addr] = merged | |
| return copy.deepcopy(merged) | |
| def get_hl_wallets(self, limit: int = 100) -> list[dict[str, Any]]: | |
| with self._lock: | |
| rows = list(self._hl_wallets.values()) | |
| rows.sort(key=lambda w: (float(w.get("reliability_score", 1.0) or 1.0), float(w.get("account_value_usd", 0.0) or 0.0)), reverse=True) | |
| return [copy.deepcopy(r) for r in rows[:limit]] | |
| def get_hl_wallet(self, address: str) -> dict[str, Any] | None: | |
| with self._lock: | |
| row = self._hl_wallets.get(str(address).lower()) | |
| return copy.deepcopy(row) if row else None | |
| # ── Microstructure Tape ─────────────────────────────────────────────────── | |
| def insert_microstructure_tape(self, tape_row: dict[str, Any]) -> dict[str, Any]: | |
| with self._lock: | |
| self._tape_seq += 1 | |
| now = _utc_now_iso() | |
| row = { | |
| "id": self._tape_seq, | |
| "symbol": str(tape_row.get("symbol", "")).upper(), | |
| "recorded_at": tape_row.get("recorded_at") or now, | |
| "timestamp_ms": int(tape_row.get("timestamp_ms") or int(datetime.now(timezone.utc).timestamp() * 1000)), | |
| "mark_price": float(tape_row.get("mark_price", 0.0) or 0.0), | |
| "adv_24h_usd": float(tape_row.get("adv_24h_usd", 0.0) or 0.0), | |
| "horizon_scores": copy.deepcopy(tape_row.get("horizon_scores", {})), | |
| "factor_scores": copy.deepcopy(tape_row.get("factor_scores", {})), | |
| "whale_sub_metrics": copy.deepcopy(tape_row.get("whale_sub_metrics", {})), | |
| "raw_replay_slice": copy.deepcopy(tape_row.get("raw_replay_slice", {})), | |
| "ret_15m_pct": tape_row.get("ret_15m_pct"), | |
| "ret_1h_pct": tape_row.get("ret_1h_pct"), | |
| "ret_4h_pct": tape_row.get("ret_4h_pct"), | |
| "evaluated_at": tape_row.get("evaluated_at"), | |
| } | |
| self._microstructure_tape.append(row) | |
| return copy.deepcopy(row) | |
| def get_microstructure_tape(self, symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict[str, Any]]: | |
| now_dt = datetime.now(timezone.utc) | |
| cutoff_sec = max(1, int(days)) * 86400 | |
| sym_filter = symbol.upper() if symbol else None | |
| with self._lock: | |
| matched = [] | |
| for r in reversed(self._microstructure_tape): | |
| if sym_filter and r.get("symbol") != sym_filter: | |
| continue | |
| c_dt = self._parse_utc_dt(r.get("recorded_at")) | |
| if c_dt is not None and (now_dt - c_dt).total_seconds() > cutoff_sec: | |
| continue | |
| matched.append(copy.deepcopy(r)) | |
| if len(matched) >= limit: | |
| break | |
| return matched | |
| def get_unevaluated_microstructure_tape(self, limit: int = 200) -> list[dict[str, Any]]: | |
| with self._lock: | |
| res = [ | |
| copy.deepcopy(r) | |
| for r in self._microstructure_tape | |
| if r.get("ret_4h_pct") is None or r.get("evaluated_at") is None | |
| ] | |
| return res[:limit] | |
| def update_microstructure_tape_returns( | |
| self, | |
| tape_id: int, | |
| ret_15m: float | None, | |
| ret_1h: float | None, | |
| ret_4h: float | None, | |
| ) -> bool: | |
| with self._lock: | |
| for r in self._microstructure_tape: | |
| if r.get("id") == tape_id: | |
| if ret_15m is not None: | |
| r["ret_15m_pct"] = ret_15m | |
| if ret_1h is not None: | |
| r["ret_1h_pct"] = ret_1h | |
| if ret_4h is not None: | |
| r["ret_4h_pct"] = ret_4h | |
| r["evaluated_at"] = _utc_now_iso() | |
| return True | |
| return False | |
| def prune_old_records( | |
| self, | |
| retention_hours_snapshots: int = 2, | |
| retention_days_signals: int = 2, | |
| retention_days_predictions: int = 30, | |
| retention_days_tape: int = 14, | |
| ) -> dict[str, int]: | |
| now_dt = datetime.now(timezone.utc) | |
| snap_sec = max(1, int(retention_hours_snapshots)) * 3600 | |
| sig_sec = max(1, int(retention_days_signals)) * 86400 | |
| pred_sec = max(1, int(retention_days_predictions)) * 86400 | |
| tape_sec = max(1, int(retention_days_tape)) * 86400 | |
| pruned = {"snapshots": 0, "signals": 0, "predictions": 0, "microstructure_tape": 0} | |
| with self._lock: | |
| for sym in list(self._snapshots.keys()): | |
| ex_map = self._snapshots[sym] | |
| for ex in list(ex_map.keys()): | |
| dt = self._parse_utc_dt(ex_map[ex].get("snapshot_at")) | |
| if dt is not None and (now_dt - dt).total_seconds() > snap_sec: | |
| del ex_map[ex] | |
| pruned["snapshots"] += 1 | |
| if not ex_map: | |
| del self._snapshots[sym] | |
| for sym in list(self._signals.keys()): | |
| orig = self._signals[sym] | |
| kept = [] | |
| for s in orig: | |
| dt = self._parse_utc_dt(s.get("created_at")) | |
| if dt is not None and (now_dt - dt).total_seconds() > sig_sec: | |
| pruned["signals"] += 1 | |
| else: | |
| kept.append(s) | |
| self._signals[sym] = kept | |
| for pid in list(self._predictions.keys()): | |
| pred = self._predictions[pid] | |
| if pred.get("outcome") != "PENDING": | |
| dt = self._parse_utc_dt(pred.get("created_at")) | |
| if dt is not None and (now_dt - dt).total_seconds() > pred_sec: | |
| del self._predictions[pid] | |
| pruned["predictions"] += 1 | |
| kept_tape = [] | |
| for r in self._microstructure_tape: | |
| dt = self._parse_utc_dt(r.get("recorded_at")) | |
| if dt is not None and (now_dt - dt).total_seconds() > tape_sec: | |
| pruned["microstructure_tape"] += 1 | |
| else: | |
| kept_tape.append(r) | |
| self._microstructure_tape = kept_tape | |
| pruned_wallets = 0 | |
| for addr in list(self._hl_wallets.keys()): | |
| w = self._hl_wallets[addr] | |
| if w.get("tier") != "SMART_WHALE": | |
| dt = self._parse_utc_dt(w.get("updated_at")) | |
| if dt is not None and (now_dt - dt).total_seconds() > tape_sec: | |
| del self._hl_wallets[addr] | |
| pruned_wallets += 1 | |
| if len(self._hl_wallets) > 250: | |
| ordered = sorted( | |
| self._hl_wallets.values(), | |
| key=lambda x: ( | |
| 1 if x.get("tier") == "SMART_WHALE" else 0, | |
| float(x.get("reliability_score", 0.0) or 0.0), | |
| float(x.get("account_value_usd", 0.0) or 0.0), | |
| ), | |
| reverse=True, | |
| ) | |
| keep_addrs = {str(x.get("address", "")).lower() for x in ordered[:250]} | |
| for addr in list(self._hl_wallets.keys()): | |
| if addr not in keep_addrs: | |
| del self._hl_wallets[addr] | |
| pruned_wallets += 1 | |
| pruned["hl_whale_wallets"] = pruned_wallets | |
| return pruned | |
| def compute_accuracy_summary_from_rows(rows: list[dict[str, Any]], days: int = 30) -> dict[str, Any]: | |
| """Compute unified accuracy summary from signal_predictions rows (shared by DB and memory_store).""" | |
| # Exclude all is_shadow=True rows from primary metrics | |
| live_rows = [r for r in rows if not r.get("is_shadow")] | |
| shadow_rows = [r for r in rows if bool(r.get("is_shadow"))] | |
| pending_count = sum(1 for r in live_rows if r.get("outcome") == "PENDING") | |
| eval_rows = [r for r in live_rows if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None] | |
| total_evaluated = len(eval_rows) | |
| expired_count = sum(1 for r in eval_rows if r.get("outcome") == "EXPIRED") | |
| def _stats(subset: list[dict[str, Any]]) -> dict[str, Any]: | |
| n = len(subset) | |
| if n == 0: | |
| return {"total": 0, "win_rate_pct": 0.0, "avg_r": 0.0} | |
| wins = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) > 0.0) | |
| avg_r = sum(float(r.get("r_multiple") or 0.0) for r in subset) / n | |
| return { | |
| "total": n, | |
| "win_rate_pct": round((wins / n) * 100.0, 1), | |
| "avg_r": round(avg_r, 3), | |
| } | |
| overall = _stats(eval_rows) | |
| non_expired = [r for r in eval_rows if r.get("outcome") != "EXPIRED"] | |
| tp_hits = sum(1 for r in non_expired if r.get("outcome") in ("TP1_OPEN", "TP1_BREAKEVEN", "TP2")) | |
| tp_hit_rate_pct = round((tp_hits / len(non_expired)) * 100.0, 1) if non_expired else 0.0 | |
| intraday_rows = [r for r in eval_rows if r.get("horizon") == "intraday"] | |
| swing_rows = [r for r in eval_rows if r.get("horizon") == "swing"] | |
| sniper_rows = [r for r in eval_rows if r.get("sniper_grade") == "SNIPER_A_PLUS"] | |
| non_sniper_rows = [r for r in eval_rows if r.get("sniper_grade") != "SNIPER_A_PLUS"] | |
| factor_buckets: dict[str, dict[str, list[float]]] = {} | |
| for r in eval_rows: | |
| dir_sign = 1 if r.get("direction") == "LONG" else (-1 if r.get("direction") == "SHORT" else 0) | |
| if dir_sign == 0: | |
| continue | |
| r_mult = float(r.get("r_multiple") or 0.0) | |
| f_scores = r.get("factor_scores") or {} | |
| if isinstance(f_scores, str): | |
| import json | |
| try: | |
| f_scores = json.loads(f_scores) | |
| except Exception: | |
| f_scores = {} | |
| if not isinstance(f_scores, dict): | |
| continue | |
| for f_name, raw_val in f_scores.items(): | |
| raw_score = raw_val.get("score", 0) if isinstance(raw_val, dict) else raw_val | |
| try: | |
| score = int(float(raw_score)) if raw_score is not None else 0 | |
| except (TypeError, ValueError): | |
| score = 0 | |
| if score == 0: | |
| continue | |
| b = factor_buckets.setdefault(f_name, {"aligned": [], "opposing": []}) | |
| if score * dir_sign > 0: | |
| b["aligned"].append(r_mult) | |
| elif score * dir_sign < 0: | |
| b["opposing"].append(r_mult) | |
| by_factor: dict[str, dict[str, Any]] = {} | |
| for f_name, b in factor_buckets.items(): | |
| al = b["aligned"] | |
| op = b["opposing"] | |
| al_n = len(al) | |
| op_n = len(op) | |
| al_wr = round((sum(1 for x in al if x > 0.0) / al_n) * 100.0, 1) if al_n > 0 else 0.0 | |
| al_avg = round(sum(al) / al_n, 3) if al_n > 0 else 0.0 | |
| op_wr = round((sum(1 for x in op if x > 0.0) / op_n) * 100.0, 1) if op_n > 0 else 0.0 | |
| op_avg = round(sum(op) / op_n, 3) if op_n > 0 else 0.0 | |
| by_factor[f_name] = { | |
| "aligned_trades": al_n, | |
| "aligned_win_rate_pct": al_wr, | |
| "aligned_avg_r": al_avg, | |
| "opposing_trades": op_n, | |
| "opposing_win_rate_pct": op_wr, | |
| "opposing_avg_r": op_avg, | |
| } | |
| # Isolated veto_effectiveness grouped by veto_reason | |
| shadow_eval_rows = [ | |
| r for r in shadow_rows | |
| if r.get("outcome") and r.get("outcome") != "PENDING" and r.get("r_multiple") is not None | |
| ] | |
| veto_groups: dict[str, list[dict[str, Any]]] = {} | |
| for r in shadow_eval_rows: | |
| vr = str(r.get("veto_reason") or "UNKNOWN") | |
| veto_groups.setdefault(vr, []).append(r) | |
| veto_effectiveness: dict[str, dict[str, Any]] = {} | |
| for vr, subset in sorted(veto_groups.items()): | |
| n = len(subset) | |
| wins = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) > 0.0) | |
| losses = sum(1 for r in subset if float(r.get("r_multiple") or 0.0) < 0.0) | |
| avg_r = sum(float(r.get("r_multiple") or 0.0) for r in subset) / n if n > 0 else 0.0 | |
| veto_effectiveness[vr] = { | |
| "total": n, | |
| "would_have_won_pct": round((wins / n) * 100.0, 1) if n > 0 else 0.0, | |
| "avg_shadow_r": round(avg_r, 3), | |
| "saved_loss_rate_pct": round((losses / n) * 100.0, 1) if n > 0 else 0.0, | |
| } | |
| return { | |
| "window_days": int(days), | |
| "total_evaluated": total_evaluated, | |
| "pending_count": pending_count, | |
| "expired_count": expired_count, | |
| "win_rate_pct": overall["win_rate_pct"], | |
| "tp_hit_rate_pct": tp_hit_rate_pct, | |
| "avg_r_multiple": overall["avg_r"], | |
| "by_horizon": { | |
| "intraday": _stats(intraday_rows), | |
| "swing": _stats(swing_rows), | |
| }, | |
| "sniper_a_plus": _stats(sniper_rows), | |
| "non_sniper": _stats(non_sniper_rows), | |
| "by_factor": by_factor, | |
| "veto_effectiveness": veto_effectiveness, | |
| } | |
| memory_store = InMemoryDatabaseStore() | |