""" PostgreSQL (Neon) connection manager and helper utilities. All database operations run synchronously in a thread pool via asyncio.to_thread() called from async FastAPI routes / background tasks. """ import json import logging import math import os import asyncio import threading from contextlib import contextmanager from datetime import datetime, timedelta, timezone from typing import Any, Generator import psycopg from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from config import DATABASE_URL from database.memory_store import InMemoryDatabaseStore, compute_accuracy_summary_from_rows, memory_store from database.models import ( ALL_TABLES, CREATE_TRADE_JOURNAL_TABLE, CREATE_DAMIAN_MEMORY_TABLE, CREATE_JOURNAL_INDEX, CREATE_SIGNAL_PREDICTIONS_TABLE, CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX, CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX, CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX, CREATE_HL_WHALE_WALLETS_TABLE, CREATE_HL_WHALE_WALLETS_RELIABILITY_INDEX, CREATE_MICROSTRUCTURE_TAPE_TABLE, CREATE_MICRO_TAPE_SYM_TS_INDEX, CREATE_MICRO_TAPE_UNEVAL_INDEX, ) logger = logging.getLogger(__name__) _pool: ConnectionPool | None = None _pool_lock = threading.Lock() _mem = memory_store _predictions_table_lock = threading.Lock() _LEGACY_ALTER_COLUMNS_SQL = """ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE; ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_bitget BOOLEAN DEFAULT FALSE; ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE; ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0; ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL'; ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0; ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS failure_tag TEXT; ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS exit_price DOUBLE PRECISION; ALTER TABLE trade_journal ADD COLUMN IF NOT EXISTS holding_duration_seconds INTEGER; ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE; ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT; """ def _sanitize_json_payload(obj: Any) -> Any: """Replace non-finite floats (NaN/Inf) with None so PostgreSQL JSONB never fails on NaN.""" if isinstance(obj, float): return obj if math.isfinite(obj) else None if isinstance(obj, dict): return {k: _sanitize_json_payload(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [_sanitize_json_payload(v) for v in obj] return obj def _safe_json_dumps(obj: Any) -> str: return json.dumps(_sanitize_json_payload(obj), allow_nan=False) def get_pool() -> ConnectionPool: global _pool if not DATABASE_URL: raise RuntimeError("DATABASE_URL is not configured.") if _pool is None: with _pool_lock: if _pool is None: max_pool = max(1, int(os.getenv("DB_POOL_MAX_SIZE", "4") or "4")) _pool = ConnectionPool( conninfo=DATABASE_URL, min_size=1, max_size=max_pool, timeout=15.0, kwargs={"row_factory": dict_row, "prepare_threshold": None}, ) return _pool @contextmanager def get_connection() -> Generator[psycopg.Connection, None, None]: """Yield a connection from the pool; commit or roll back on exit.""" if not DATABASE_URL: raise RuntimeError("DATABASE_URL is not configured.") pool = get_pool() with pool.connection() as conn: try: yield conn conn.commit() except Exception: conn.rollback() raise def _format_row(row: dict | None) -> dict | None: if not row: return None d = dict(row) for k, v in d.items(): if hasattr(v, "isoformat"): d[k] = v.isoformat() if "signal_data" in d and isinstance(d["signal_data"], str): try: d["signal_data"] = json.loads(d["signal_data"]) except Exception: pass if "snapshot_data" in d and isinstance(d["snapshot_data"], str): try: d["snapshot_data"] = json.loads(d["snapshot_data"]) except Exception: pass if isinstance(d.get("signal_data"), dict): if "streak" not in d["signal_data"] or d["signal_data"].get("streak") is None: d["signal_data"]["streak"] = int(d.get("streak_count") or 0) if "streak_direction" not in d["signal_data"] or not d["signal_data"].get("streak_direction"): d["signal_data"]["streak_direction"] = str(d.get("streak_direction") or "NEUTRAL") for bool_col in ("on_binance", "on_bybit", "on_okx", "on_bitget", "on_hyperliquid", "is_active"): if bool_col in d and d[bool_col] is not None: d[bool_col] = bool(d[bool_col]) if "streak_count" in d and d["streak_count"] is not None: d["streak_count"] = int(d["streak_count"]) if "last_conviction" in d and d["last_conviction"] is not None: d["last_conviction"] = int(d["last_conviction"]) if "streak_direction" in d and d["streak_direction"] is not None: d["streak_direction"] = str(d["streak_direction"]) return d def init_db() -> None: """Create all tables in Neon PostgreSQL if they do not exist yet, and run schema migrations. Protected by PostgreSQL advisory lock and schema existence check to prevent concurrent DDL deadlocks. """ if not DATABASE_URL: logger.info("DATABASE_URL not set; skipping database initialization (running in stateless mode).") return try: with get_connection() as conn: with conn.cursor() as cur: # 1. Quick check: if 'pairs' table already exists, ensure trade_journal & damian_memory exist cur.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pairs';") if cur.fetchone(): # Ensure trade_journal and damian_memory tables exist cur.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'trade_journal';") if not cur.fetchone(): cur.execute(CREATE_TRADE_JOURNAL_TABLE) cur.execute(CREATE_DAMIAN_MEMORY_TABLE) cur.execute(CREATE_JOURNAL_INDEX) conn.commit() logger.info("Created trade_journal and damian_memory tables.") cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE) conn.commit() # Run legacy ALTER ADD COLUMN statements BEFORE creating new column indexes (e.g. is_shadow) try: cur.execute(_LEGACY_ALTER_COLUMNS_SQL) conn.commit() except Exception as e: conn.rollback() logger.warning("Postgres schema add column to existing tables note: %s", e) cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX) cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX) cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX) cur.execute(CREATE_HL_WHALE_WALLETS_TABLE) cur.execute(CREATE_HL_WHALE_WALLETS_RELIABILITY_INDEX) cur.execute(CREATE_MICROSTRUCTURE_TAPE_TABLE) cur.execute(CREATE_MICRO_TAPE_SYM_TS_INDEX) cur.execute(CREATE_MICRO_TAPE_UNEVAL_INDEX) cur.execute("CREATE INDEX IF NOT EXISTS idx_signals_symbol_created ON signals (symbol, created_at DESC);") cur.execute("CREATE INDEX IF NOT EXISTS idx_pairs_active ON pairs (is_active);") conn.commit() global _predictions_table_ensured _predictions_table_ensured = True return # 2. Schema does not exist: acquire advisory lock so only 1 worker creates tables cur.execute("SELECT pg_try_advisory_lock(72817001) AS got_lock;") lock_row = cur.fetchone() or {} got_lock = bool(lock_row.get("got_lock", False)) if isinstance(lock_row, dict) else bool(lock_row[0]) if not got_lock: logger.info("Another worker is currently initializing the database. Skipping.") return try: cur.execute("SET LOCAL lock_timeout = '5s';") for ddl in ALL_TABLES: cur.execute(ddl) conn.commit() try: cur.execute(_LEGACY_ALTER_COLUMNS_SQL) conn.commit() except Exception as e: conn.rollback() logger.warning("Postgres schema add column note: %s", e) try: cur.execute(""" DO $$ BEGIN IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_name = 'pairs' AND column_name = 'is_active' AND data_type = 'integer' ) THEN ALTER TABLE pairs ALTER COLUMN on_binance DROP DEFAULT; ALTER TABLE pairs ALTER COLUMN on_bybit DROP DEFAULT; ALTER TABLE pairs ALTER COLUMN is_active DROP DEFAULT; ALTER TABLE pairs ALTER COLUMN on_binance TYPE BOOLEAN USING (on_binance != 0); ALTER TABLE pairs ALTER COLUMN on_bybit TYPE BOOLEAN USING (on_bybit != 0); ALTER TABLE pairs ALTER COLUMN is_active TYPE BOOLEAN USING (is_active != 0); ALTER TABLE pairs ALTER COLUMN on_binance SET DEFAULT FALSE; ALTER TABLE pairs ALTER COLUMN on_bybit SET DEFAULT FALSE; ALTER TABLE pairs ALTER COLUMN is_active SET DEFAULT TRUE; END IF; END $$; """) conn.commit() except Exception as e: conn.rollback() logger.warning("Postgres schema migration note: %s", e) logger.info("Neon PostgreSQL database initialized successfully.") finally: try: conn.rollback() cur.execute("SELECT pg_advisory_unlock(72817001);") conn.commit() except Exception: pass except Exception as exc: # Non-fatal: never crash serverless cold starts due to DDL race condition logger.warning("init_db non-fatal notice (schema already created or lock skipped): %s", exc) # --------------------------------------------------------------------------- # Pairs helpers # --------------------------------------------------------------------------- def db_get_all_pairs() -> list[dict]: if not DATABASE_URL: return _mem.get_all_pairs() with get_connection() as conn: with conn.cursor() as cur: cur.execute("SELECT * FROM pairs ORDER BY created_at DESC") rows = cur.fetchall() return [_format_row(r) for r in rows] def db_get_pair(symbol: str) -> dict | None: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.get_pair(sym) with get_connection() as conn: with conn.cursor() as cur: cur.execute("SELECT * FROM pairs WHERE symbol = %s", (sym,)) row = cur.fetchone() return _format_row(row) def db_insert_pair( 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: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.insert_pair(sym, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """INSERT INTO pairs (symbol, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid, is_active) VALUES (%s, %s, %s, %s, %s, %s, %s, TRUE) ON CONFLICT (symbol) DO UPDATE SET display_name = EXCLUDED.display_name, on_binance = EXCLUDED.on_binance, on_bybit = EXCLUDED.on_bybit, on_okx = EXCLUDED.on_okx, on_bitget = EXCLUDED.on_bitget, on_hyperliquid = EXCLUDED.on_hyperliquid, is_active = TRUE RETURNING *""", (sym, display_name, bool(on_binance), bool(on_bybit), bool(on_okx), bool(on_bitget), bool(on_hyperliquid)), ) row = cur.fetchone() return _format_row(row) def db_update_pair_exchanges( symbol: str, on_binance: bool, on_bybit: bool, on_okx: bool = False, on_bitget: bool = False, on_hyperliquid: bool = False, ) -> dict | None: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.update_pair_exchanges(sym, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """UPDATE pairs SET on_binance = %s, on_bybit = %s, on_okx = %s, on_bitget = %s, on_hyperliquid = %s WHERE symbol = %s RETURNING *""", (bool(on_binance), bool(on_bybit), bool(on_okx), bool(on_bitget), bool(on_hyperliquid), sym), ) row = cur.fetchone() return _format_row(row) def db_update_pair_streak( symbol: str, streak_count: int, streak_direction: str, last_conviction: int, ) -> dict | None: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.update_pair_streak(sym, streak_count, streak_direction, last_conviction) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """UPDATE pairs SET streak_count = %s, streak_direction = %s, last_conviction = %s WHERE symbol = %s RETURNING *""", (int(streak_count), str(streak_direction), int(last_conviction), sym), ) row = cur.fetchone() return _format_row(row) def db_delete_pair(symbol: str) -> bool: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.delete_pair(sym) with get_connection() as conn: with conn.cursor() as cur: cur.execute("DELETE FROM pairs WHERE symbol = %s", (sym,)) return cur.rowcount > 0 def db_delete_pair_by_identifier(identifier: str) -> bool: ident = identifier.strip() if not DATABASE_URL: return _mem.delete_pair_by_identifier(ident) with get_connection() as conn: with conn.cursor() as cur: if ident.isdigit(): cur.execute("DELETE FROM pairs WHERE id = %s", (int(ident),)) else: cur.execute("DELETE FROM pairs WHERE symbol = %s", (ident.upper(),)) return cur.rowcount > 0 def db_toggle_pair(symbol: str) -> dict | None: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.toggle_pair(sym) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """UPDATE pairs SET is_active = NOT is_active WHERE symbol = %s RETURNING *""", (sym,), ) row = cur.fetchone() return _format_row(row) def db_toggle_pair_by_identifier(identifier: str) -> dict | None: ident = identifier.strip() if not DATABASE_URL: return _mem.toggle_pair_by_identifier(ident) with get_connection() as conn: with conn.cursor() as cur: if ident.isdigit(): cur.execute( """UPDATE pairs SET is_active = NOT is_active WHERE id = %s RETURNING *""", (int(ident),), ) else: cur.execute( """UPDATE pairs SET is_active = NOT is_active WHERE symbol = %s RETURNING *""", (ident.upper(),), ) row = cur.fetchone() return _format_row(row) def db_get_active_pairs() -> list[dict]: if not DATABASE_URL: return _mem.get_active_pairs() with get_connection() as conn: with conn.cursor() as cur: cur.execute("SELECT * FROM pairs WHERE is_active = TRUE ORDER BY symbol") rows = cur.fetchall() return [_format_row(r) for r in rows] def db_get_stale_active_pairs(limit: int | None = None) -> list[dict]: """ Get active pairs sorted by least-recently-computed signal first (starvation-free round-robin). Pairs with no signal or oldest created_at are returned first to ensure all pairs refresh equally. """ if not DATABASE_URL: return _mem.get_stale_active_pairs(limit=limit) with get_connection() as conn: with conn.cursor() as cur: query = """ SELECT p.* FROM pairs p LEFT JOIN ( SELECT symbol, MAX(created_at) as last_signal_time FROM signals GROUP BY symbol ) s ON s.symbol = p.symbol WHERE p.is_active = TRUE ORDER BY s.last_signal_time ASC NULLS FIRST, p.symbol ASC """ if limit: query += " LIMIT %s" cur.execute(query, (limit,)) else: cur.execute(query) rows = cur.fetchall() return [_format_row(r) for r in rows] # --------------------------------------------------------------------------- # Signal helpers # --------------------------------------------------------------------------- def db_save_signal(symbol: str, timeframe: str, direction: str, conviction: int, signal_data: dict) -> None: sym = symbol.upper().strip() 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) if not DATABASE_URL: _mem.save_signal(sym, timeframe, direction, conviction, clean_signal_data) return with get_connection() as conn: with conn.cursor() as cur: cur.execute( """INSERT INTO signals (symbol, timeframe, direction, conviction, signal_data) VALUES (%s, %s, %s, %s, %s)""", (sym, timeframe, direction, conviction, _safe_json_dumps(clean_signal_data)), ) def db_get_latest_signals() -> list[dict]: """Latest signal per pair using Postgres DISTINCT ON (symbol).""" if not DATABASE_URL: return _mem.get_latest_signals() with get_connection() as conn: with conn.cursor() as cur: cur.execute( """SELECT DISTINCT ON (s.symbol) s.*, p.streak_count, p.streak_direction, p.last_conviction FROM signals s LEFT JOIN pairs p ON p.symbol = s.symbol ORDER BY s.symbol, s.id DESC""" ) rows = cur.fetchall() return [_format_row(r) for r in rows] def db_get_signal_history(symbol: str, limit: int = 50) -> list[dict]: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.get_signal_history(sym, limit=limit) with get_connection() as conn: with conn.cursor() as cur: cur.execute( "SELECT * FROM signals WHERE symbol = %s ORDER BY created_at DESC LIMIT %s", (sym, limit), ) rows = cur.fetchall() return [_format_row(r) for r in rows] def db_get_latest_signal(symbol: str) -> dict | None: sym = symbol.upper().strip() if not DATABASE_URL: return _mem.get_latest_signal(sym) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """SELECT s.*, p.streak_count, p.streak_direction, p.last_conviction FROM signals s LEFT JOIN pairs p ON p.symbol = s.symbol WHERE s.symbol = %s ORDER BY s.id DESC LIMIT 1""", (sym,), ) row = cur.fetchone() return _format_row(row) # --------------------------------------------------------------------------- # Market snapshot helpers # --------------------------------------------------------------------------- def db_save_snapshot( 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().strip() ex = exchange.lower().strip() if not DATABASE_URL: _mem.save_snapshot( sym, ex, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct, ) return with get_connection() as conn: with conn.cursor() as cur: cur.execute( """INSERT INTO market_snapshots (symbol, exchange, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""", (sym, ex, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct), ) def db_save_snapshots_batch(snapshots: list[tuple]) -> None: """Save multiple exchange market snapshots in a single high-efficiency DB roundtrip.""" if not snapshots: return norm_snapshots = [ (str(s[0]).upper().strip(), str(s[1]).lower().strip(), *s[2:]) for s in snapshots ] if not DATABASE_URL: _mem.save_snapshots_batch(norm_snapshots) return with get_connection() as conn: with conn.cursor() as cur: cur.executemany( """INSERT INTO market_snapshots (symbol, exchange, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""", norm_snapshots, ) def db_get_latest_snapshot(symbol: str) -> list[dict]: """Return latest snapshot per exchange using Postgres DISTINCT ON (exchange).""" sym = symbol.upper().strip() if not DATABASE_URL: return _mem.get_latest_snapshot(sym) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """SELECT DISTINCT ON (exchange) * FROM market_snapshots WHERE symbol = %s ORDER BY exchange, id DESC""", (sym,), ) rows = cur.fetchall() return [_format_row(r) for r in rows] # --------------------------------------------------------------------------- # Async wrappers (run blocking DB calls in thread pool) # --------------------------------------------------------------------------- async def async_get_all_pairs() -> list[dict]: return await asyncio.to_thread(db_get_all_pairs) async def async_get_pair(symbol: str) -> dict | None: return await asyncio.to_thread(db_get_pair, symbol) async def async_insert_pair( 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: return await asyncio.to_thread( db_insert_pair, symbol, display_name, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid ) async def async_update_pair_exchanges( symbol: str, on_binance: bool, on_bybit: bool, on_okx: bool = False, on_bitget: bool = False, on_hyperliquid: bool = False, ) -> dict | None: return await asyncio.to_thread( db_update_pair_exchanges, symbol, on_binance, on_bybit, on_okx, on_bitget, on_hyperliquid ) async def async_update_pair_streak( symbol: str, streak_count: int, streak_direction: str, last_conviction: int, ) -> dict | None: return await asyncio.to_thread( db_update_pair_streak, symbol, streak_count, streak_direction, last_conviction ) async def async_delete_pair(symbol: str) -> bool: return await asyncio.to_thread(db_delete_pair, symbol) async def async_delete_pair_by_identifier(identifier: str) -> bool: return await asyncio.to_thread(db_delete_pair_by_identifier, identifier) async def async_toggle_pair(symbol: str) -> dict | None: return await asyncio.to_thread(db_toggle_pair, symbol) async def async_toggle_pair_by_identifier(identifier: str) -> dict | None: return await asyncio.to_thread(db_toggle_pair_by_identifier, identifier) async def async_get_active_pairs() -> list[dict]: return await asyncio.to_thread(db_get_active_pairs) async def async_get_stale_active_pairs(limit: int | None = None) -> list[dict]: return await asyncio.to_thread(db_get_stale_active_pairs, limit) async def async_save_signal(symbol, timeframe, direction, conviction, signal_data) -> None: return await asyncio.to_thread(db_save_signal, symbol, timeframe, direction, conviction, signal_data) async def async_get_latest_signals() -> list[dict]: return await asyncio.to_thread(db_get_latest_signals) async def async_get_signal_history(symbol: str, limit: int = 50) -> list[dict]: return await asyncio.to_thread(db_get_signal_history, symbol, limit) async def async_get_latest_signal(symbol: str) -> dict | None: return await asyncio.to_thread(db_get_latest_signal, symbol) async def async_save_snapshot(symbol, exchange, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct) -> None: return await asyncio.to_thread( db_save_snapshot, symbol, exchange, funding_rate, open_interest, long_ratio, short_ratio, mark_price, index_price, basis_pct, ) async def async_save_snapshots_batch(snapshots: list[tuple]) -> None: return await asyncio.to_thread(db_save_snapshots_batch, snapshots) async def async_get_latest_snapshot(symbol: str) -> list[dict]: return await asyncio.to_thread(db_get_latest_snapshot, symbol) # --------------------------------------------------------------------------- # Retention Pruning # --------------------------------------------------------------------------- def db_prune_old_records( retention_hours_snapshots: int = 2, retention_days_signals: int = 2, retention_days_predictions: int = 30, retention_days_tape: int = 14, ) -> dict[str, int]: """ Prune old market_snapshots, signals, evaluated signal_predictions, and microstructure_tape to prevent database bloat on Neon free tier. Default: snapshots older than 2h, signals older than 2 days, evaluated predictions older than 30 days, tape older than 14 days. """ pruned = {"snapshots": 0, "signals": 0, "predictions": 0, "microstructure_tape": 0} if not DATABASE_URL: return _mem.prune_old_records( retention_hours_snapshots=retention_hours_snapshots, retention_days_signals=retention_days_signals, retention_days_predictions=retention_days_predictions, retention_days_tape=retention_days_tape, ) try: with get_connection() as conn: with conn.cursor() as cur: cur.execute( "DELETE FROM market_snapshots WHERE snapshot_at < NOW() - (%s * INTERVAL '1 hour')", (retention_hours_snapshots,), ) pruned["snapshots"] = cur.rowcount cur.execute( "DELETE FROM signals WHERE created_at < NOW() - (%s * INTERVAL '1 day')", (retention_days_signals,), ) pruned["signals"] = cur.rowcount cur.execute( "DELETE FROM signal_predictions WHERE outcome != 'PENDING' AND created_at < NOW() - (%s * INTERVAL '1 day')", (retention_days_predictions,), ) pruned["predictions"] = cur.rowcount cur.execute( "DELETE FROM microstructure_tape WHERE recorded_at < NOW() - (%s * INTERVAL '1 day')", (retention_days_tape,), ) pruned["microstructure_tape"] = cur.rowcount # Prune stale non-SMART_WHALE wallets inactive > 14 days and cap table at top 250 wallets cur.execute( """ DELETE FROM hl_whale_wallets WHERE COALESCE(tier, 'UNPROVEN') != 'SMART_WHALE' AND updated_at < NOW() - (%s * INTERVAL '1 day'); """, (retention_days_tape,), ) pruned_wallets = cur.rowcount cur.execute( """ DELETE FROM hl_whale_wallets WHERE address IN ( SELECT address FROM hl_whale_wallets ORDER BY (CASE WHEN tier = 'SMART_WHALE' THEN 1 ELSE 0 END) DESC, reliability_score DESC, account_value_usd DESC, updated_at DESC OFFSET 250 ); """ ) pruned["hl_whale_wallets"] = pruned_wallets + cur.rowcount if pruned["snapshots"] > 0 or pruned["signals"] > 0 or pruned["predictions"] > 0 or pruned["microstructure_tape"] > 0: logger.info( "[DB Retention] Pruned %d snapshots, %d signals, %d predictions, and %d tape records.", pruned["snapshots"], pruned["signals"], pruned["predictions"], pruned["microstructure_tape"], ) except Exception as exc: logger.warning("[DB Retention] Pruning failed: %s", exc) return pruned async def async_prune_old_records( retention_hours_snapshots: int = 2, retention_days_signals: int = 2, retention_days_predictions: int = 30, retention_days_tape: int = 14, ) -> dict[str, int]: return await asyncio.to_thread( db_prune_old_records, retention_hours_snapshots, retention_days_signals, retention_days_predictions, retention_days_tape, ) # --------------------------------------------------------------------------- # Trade Journal & Damian Memory # --------------------------------------------------------------------------- def db_create_journal_entry(data: dict) -> dict: """Insert a new trade record into trade_journal.""" if not DATABASE_URL: return _mem.create_journal_entry(data) snapshot_json = _safe_json_dumps(data.get("snapshot_data") or {}) sym = str(data.get("symbol") or "").upper().strip() bias = str(data.get("bias") or "ANALYZED") status = str(data.get("status") or "PENDING").upper().strip() query = """ INSERT INTO trade_journal ( symbol, bias, entry_zone, stop_loss, take_profit, risk_reward, leverage, invalidation, summary_tldr, full_analysis, model_used, status, outcome_note, failure_tag, exit_price, holding_duration_seconds, snapshot_data ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING *; """ with get_connection() as conn: with conn.cursor() as cur: cur.execute( query, ( sym, bias, data.get("entry_zone"), data.get("stop_loss"), data.get("take_profit"), data.get("risk_reward"), data.get("leverage"), data.get("invalidation"), data.get("summary_tldr"), data.get("full_analysis"), data.get("model_used"), status, data.get("outcome_note"), data.get("failure_tag"), data.get("exit_price"), data.get("holding_duration_seconds"), snapshot_json, ), ) row = cur.fetchone() return _format_row(row) or {} def db_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]: """Fetch trade journal entries with optional status filter.""" if not DATABASE_URL: return _mem.get_journal_entries(status=status, limit=limit, offset=offset) with get_connection() as conn: with conn.cursor() as cur: if status and status.upper() != "ALL": cur.execute( "SELECT * FROM trade_journal WHERE status = %s ORDER BY created_at DESC LIMIT %s OFFSET %s;", (status.upper(), limit, offset), ) else: cur.execute( "SELECT * FROM trade_journal ORDER BY created_at DESC LIMIT %s OFFSET %s;", (limit, offset), ) rows = cur.fetchall() return [_format_row(r) for r in rows if r] def db_update_journal_status( 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 | None: """Update trade outcome status (HIT_TP, HIT_SL, CANCELLED, PENDING) with rich post-mortem metadata.""" if not DATABASE_URL: return _mem.update_journal_status( journal_id=journal_id, status=status, note=note, failure_tag=failure_tag, exit_price=exit_price, holding_duration_seconds=holding_duration_seconds, ) st = status.upper().strip() with get_connection() as conn: with conn.cursor() as cur: if st == "PENDING": cur.execute( """ UPDATE trade_journal SET status = 'PENDING', outcome_note = NULL, outcome_at = NULL, failure_tag = NULL, exit_price = NULL, holding_duration_seconds = NULL, audited = FALSE WHERE id = %s RETURNING *; """, (journal_id,), ) elif st == "HIT_SL": cur.execute( """ UPDATE trade_journal SET status = %s, outcome_note = %s, outcome_at = NOW(), failure_tag = COALESCE(%s, failure_tag), exit_price = COALESCE(%s, exit_price), holding_duration_seconds = COALESCE(%s, holding_duration_seconds) WHERE id = %s RETURNING *; """, (st, note, failure_tag, exit_price, holding_duration_seconds, journal_id), ) else: cur.execute( """ UPDATE trade_journal SET status = %s, outcome_note = %s, outcome_at = NOW(), failure_tag = NULL, audited = FALSE, exit_price = COALESCE(%s, exit_price), holding_duration_seconds = COALESCE(%s, holding_duration_seconds) WHERE id = %s RETURNING *; """, (st, note, exit_price, holding_duration_seconds, journal_id), ) row = cur.fetchone() return _format_row(row) def db_delete_journal_entry(journal_id: int) -> bool: """Delete a trade journal entry.""" if not DATABASE_URL: return _mem.delete_journal_entry(journal_id) with get_connection() as conn: with conn.cursor() as cur: cur.execute("DELETE FROM trade_journal WHERE id = %s;", (journal_id,)) return cur.rowcount > 0 def db_get_journal_stats() -> dict: """Calculate Win Rate, total counts, and unaudited SL count.""" if not DATABASE_URL: return _mem.get_journal_stats() with get_connection() as conn: with conn.cursor() as cur: cur.execute(""" SELECT COUNT(*) as total, COUNT(*) FILTER (WHERE status = 'HIT_TP') as hit_tp, COUNT(*) FILTER (WHERE status = 'HIT_SL') as hit_sl, COUNT(*) FILTER (WHERE status = 'PENDING') as pending, COUNT(*) FILTER (WHERE status = 'CANCELLED') as cancelled, COUNT(*) FILTER (WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE) as unaudited_sl FROM trade_journal; """) row = cur.fetchone() or {} total = int(row.get("total") or 0) hit_tp = int(row.get("hit_tp") or 0) hit_sl = int(row.get("hit_sl") or 0) pending = int(row.get("pending") or 0) cancelled = int(row.get("cancelled") or 0) unaudited_sl = int(row.get("unaudited_sl") or 0) completed = hit_tp + hit_sl win_rate = round((hit_tp / completed * 100), 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 db_get_unaudited_failed_trades(limit: int = 10) -> list[dict]: """Retrieve up to 10 unaudited HIT_SL trades for Damian audit synthesis.""" if not DATABASE_URL: return _mem.get_unaudited_failed_trades(limit=limit) with get_connection() as conn: with conn.cursor() as cur: cur.execute( """ SELECT * FROM trade_journal WHERE status = 'HIT_SL' AND COALESCE(audited, FALSE) = FALSE ORDER BY created_at ASC LIMIT %s; """, (limit,), ) rows = cur.fetchall() return [_format_row(r) for r in rows if r] def db_mark_trades_as_audited(trade_ids: list[int]) -> None: """Mark failed trades as audited.""" if not trade_ids: return if not DATABASE_URL: _mem.mark_trades_as_audited(trade_ids) return with get_connection() as conn: with conn.cursor() as cur: cur.execute( "UPDATE trade_journal SET audited = TRUE WHERE id = ANY(%s);", (trade_ids,), ) def db_save_damian_memory(audit_summary: str, model_used: str, failed_count: int = 10) -> dict: """Save synthesized lessons and golden rules into damian_memory.""" if not DATABASE_URL: return _mem.save_damian_memory(audit_summary=audit_summary, model_used=model_used, failed_count=failed_count) with get_connection() as conn: with conn.cursor() as cur: cur.execute("SELECT pg_advisory_xact_lock(72817002);") cur.execute("SELECT COALESCE(MAX(batch_index), 0) + 1 AS next_batch FROM damian_memory;") batch_row = cur.fetchone() or {} next_batch = int(batch_row.get("next_batch", 1)) if isinstance(batch_row, dict) else int(batch_row[0]) cur.execute( """ INSERT INTO damian_memory (batch_index, failed_count, model_used, audit_summary, is_active) VALUES (%s, %s, %s, %s, TRUE) RETURNING *; """, (next_batch, failed_count, model_used, audit_summary), ) row = cur.fetchone() return _format_row(row) or {} def db_get_active_damian_memory(limit: int = 3) -> list[dict]: """Retrieve active Damian memory audit summaries.""" if not DATABASE_URL: return _mem.get_active_damian_memory(limit=limit) with get_connection() as conn: with conn.cursor() as cur: cur.execute( "SELECT * FROM damian_memory WHERE is_active = TRUE ORDER BY created_at DESC LIMIT %s;", (limit,), ) rows = cur.fetchall() return [_format_row(r) for r in rows if r] async def async_create_journal_entry(data: dict) -> dict: return await asyncio.to_thread(db_create_journal_entry, data) async def async_get_journal_entries(status: str | None = None, limit: int = 50, offset: int = 0) -> list[dict]: return await asyncio.to_thread(db_get_journal_entries, status, limit, offset) async def async_update_journal_status( 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 | None: return await asyncio.to_thread( db_update_journal_status, journal_id, status, note, failure_tag, exit_price, holding_duration_seconds, ) async def async_delete_journal_entry(journal_id: int) -> bool: return await asyncio.to_thread(db_delete_journal_entry, journal_id) async def async_get_journal_stats() -> dict: return await asyncio.to_thread(db_get_journal_stats) async def async_get_unaudited_failed_trades(limit: int = 10) -> list[dict]: return await asyncio.to_thread(db_get_unaudited_failed_trades, limit) async def async_mark_trades_as_audited(trade_ids: list[int]) -> None: return await asyncio.to_thread(db_mark_trades_as_audited, trade_ids) async def async_save_damian_memory(audit_summary: str, model_used: str, failed_count: int = 10) -> dict: return await asyncio.to_thread(db_save_damian_memory, audit_summary, model_used, failed_count) async def async_get_active_damian_memory(limit: int = 3) -> list[dict]: return await asyncio.to_thread(db_get_active_damian_memory, limit) # --------------------------------------------------------------------------- # Signal Predictions (Forward Accuracy Tracker) # --------------------------------------------------------------------------- _predictions_table_ensured = False def _ensure_predictions_table(cur: Any, conn: Any) -> None: global _predictions_table_ensured if _predictions_table_ensured: return with _predictions_table_lock: if _predictions_table_ensured: return # Fast non-locking catalog check: if signal_predictions.is_shadow already exists, skip DDL completely cur.execute( """ SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'signal_predictions' AND column_name = 'is_shadow' LIMIT 1; """ ) if cur.fetchone(): _predictions_table_ensured = True return cur.execute(CREATE_SIGNAL_PREDICTIONS_TABLE) cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS is_shadow BOOLEAN DEFAULT FALSE;") cur.execute("ALTER TABLE signal_predictions ADD COLUMN IF NOT EXISTS veto_reason TEXT;") cur.execute(CREATE_SIGNAL_PREDICTIONS_PENDING_INDEX) cur.execute(CREATE_SIGNAL_PREDICTIONS_EVAL_INDEX) cur.execute(CREATE_SIGNAL_PREDICTIONS_SHADOW_INDEX) conn.commit() _predictions_table_ensured = True def db_insert_signal_prediction(data: dict) -> dict: """Insert a new forward signal prediction row.""" if not DATABASE_URL: return _mem.insert_signal_prediction(data) default_expires = data.get("expires_at") if default_expires is None: default_expires = datetime.now(timezone.utc) + timedelta(hours=24) with get_connection() as conn: with conn.cursor() as cur: _ensure_predictions_table(cur, conn) cur.execute( """ INSERT INTO signal_predictions ( symbol, horizon, direction, conviction, regime, sniper_grade, entry_price, stop_loss, tp1, tp2, factor_scores, outcome, expires_at, is_shadow, veto_reason ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, 'PENDING', %s, %s, %s) RETURNING *; """, ( str(data.get("symbol", "")).upper().strip(), str(data.get("horizon", "intraday")), str(data.get("direction", "NEUTRAL")), int(data.get("conviction", 0)), str(data.get("regime", "ranging")), str(data.get("sniper_grade", "WAIT")), float(data.get("entry_price", 0.0)), float(data.get("stop_loss", 0.0)), float(data.get("tp1", 0.0)), float(data.get("tp2", 0.0)), _safe_json_dumps(data.get("factor_scores") or {}), default_expires, bool(data.get("is_shadow", False)), data.get("veto_reason"), ), ) row = cur.fetchone() return _format_row(row) or {} def db_get_pending_predictions(limit: int = 200) -> list[dict]: """Fetch pending predictions ordered by expires_at ASC.""" if not DATABASE_URL: return _mem.get_pending_predictions(limit=limit) with get_connection() as conn: with conn.cursor() as cur: _ensure_predictions_table(cur, conn) cur.execute( """ SELECT * FROM signal_predictions WHERE outcome = 'PENDING' ORDER BY expires_at ASC, id ASC LIMIT %s; """, (limit,), ) rows = cur.fetchall() return [_format_row(r) for r in rows if r] def db_update_signal_prediction_outcome( pred_id: int, outcome: str, outcome_price: float, r_multiple: float, ) -> dict | None: """Update outcome, outcome_price, r_multiple, and evaluated_at for a prediction.""" if not DATABASE_URL: return _mem.update_signal_prediction_outcome(pred_id, outcome, outcome_price, r_multiple) with get_connection() as conn: with conn.cursor() as cur: _ensure_predictions_table(cur, conn) cur.execute( """ UPDATE signal_predictions SET outcome = %s, outcome_price = %s, r_multiple = %s, evaluated_at = CURRENT_TIMESTAMP WHERE id = %s RETURNING *; """, (outcome, float(outcome_price), float(r_multiple), int(pred_id)), ) row = cur.fetchone() return _format_row(row) if row else None def db_get_recent_prediction( symbol: str, horizon: str, direction: str, cooldown_hours: int, is_shadow: bool = False, veto_reason: str | None = None, ) -> dict | None: """Return an active PENDING prediction or a same-direction prediction within cooldown_hours.""" if not DATABASE_URL: return _mem.get_recent_prediction( symbol, horizon, direction, cooldown_hours, is_shadow=is_shadow, veto_reason=veto_reason, ) sym = symbol.upper() with get_connection() as conn: with conn.cursor() as cur: _ensure_predictions_table(cur, conn) if not is_shadow: cur.execute( """ SELECT * FROM signal_predictions WHERE symbol = %s AND horizon = %s AND COALESCE(is_shadow, FALSE) = FALSE AND ( outcome = 'PENDING' OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour')) ) ORDER BY id DESC LIMIT 1; """, (sym, horizon, direction, int(cooldown_hours)), ) else: cur.execute( """ SELECT * FROM signal_predictions WHERE symbol = %s AND horizon = %s AND is_shadow = TRUE AND veto_reason IS NOT DISTINCT FROM %s AND ( outcome = 'PENDING' OR (direction = %s AND created_at >= NOW() - (%s * INTERVAL '1 hour')) ) ORDER BY id DESC LIMIT 1; """, (sym, horizon, veto_reason, direction, int(cooldown_hours)), ) row = cur.fetchone() return _format_row(row) if row else None def db_get_accuracy_summary(days: int = 30, symbol: str | None = None) -> dict: """Compute rolling forward accuracy summary across evaluated predictions.""" if not DATABASE_URL: return _mem.get_accuracy_summary(days=days, symbol=symbol) with get_connection() as conn: with conn.cursor() as cur: _ensure_predictions_table(cur, conn) if symbol: cur.execute( """ SELECT * FROM signal_predictions WHERE symbol = %s AND created_at >= NOW() - (%s * INTERVAL '1 day') ORDER BY created_at DESC; """, (symbol.upper(), int(days)), ) else: cur.execute( """ SELECT * FROM signal_predictions WHERE created_at >= NOW() - (%s * INTERVAL '1 day') ORDER BY created_at DESC; """, (int(days),), ) rows = [_format_row(r) for r in cur.fetchall() if r] return compute_accuracy_summary_from_rows(rows, days=days) async def async_insert_signal_prediction(data: dict) -> dict: return await asyncio.to_thread(db_insert_signal_prediction, data) async def async_get_pending_predictions(limit: int = 200) -> list[dict]: return await asyncio.to_thread(db_get_pending_predictions, limit) async def async_update_signal_prediction_outcome( pred_id: int, outcome: str, outcome_price: float, r_multiple: float, ) -> dict | None: return await asyncio.to_thread( db_update_signal_prediction_outcome, pred_id, outcome, outcome_price, r_multiple, ) async def async_get_recent_prediction( symbol: str, horizon: str, direction: str, cooldown_hours: int, is_shadow: bool = False, veto_reason: str | None = None, ) -> dict | None: return await asyncio.to_thread( db_get_recent_prediction, symbol, horizon, direction, cooldown_hours, is_shadow, veto_reason, ) async def async_get_accuracy_summary(days: int = 30, symbol: str | None = None) -> dict: return await asyncio.to_thread(db_get_accuracy_summary, days, symbol) # --------------------------------------------------------------------------- # Hyperliquid Whale Wallets # --------------------------------------------------------------------------- def db_upsert_hl_wallet(wallet: dict) -> dict: if not DATABASE_URL: return _mem.upsert_hl_wallet(wallet) addr = str(wallet.get("address", "")).lower() if not addr: return {} sql = """ INSERT INTO hl_whale_wallets ( address, label, account_value_usd, total_notional_usd, cumulative_pnl_usd, win_count, loss_count, reliability_score, tier, positions_json, recent_events_json, updated_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW()) ON CONFLICT (address) DO UPDATE SET label = COALESCE(EXCLUDED.label, hl_whale_wallets.label), account_value_usd = EXCLUDED.account_value_usd, total_notional_usd = EXCLUDED.total_notional_usd, cumulative_pnl_usd = EXCLUDED.cumulative_pnl_usd, win_count = EXCLUDED.win_count, loss_count = EXCLUDED.loss_count, reliability_score = EXCLUDED.reliability_score, tier = EXCLUDED.tier, positions_json = EXCLUDED.positions_json, recent_events_json = EXCLUDED.recent_events_json, updated_at = NOW() RETURNING *; """ try: with get_connection() as conn: with conn.cursor() as cur: cur.execute( sql, ( addr, wallet.get("label"), float(wallet.get("account_value_usd", 0.0) or 0.0), float(wallet.get("total_notional_usd", 0.0) or 0.0), float(wallet.get("cumulative_pnl_usd", 0.0) or 0.0), int(wallet.get("win_count", 0) or 0), int(wallet.get("loss_count", 0) or 0), float(wallet.get("reliability_score", 1.0) or 1.0), wallet.get("tier", "UNPROVEN"), _safe_json_dumps(wallet.get("positions_json", {})), _safe_json_dumps(wallet.get("recent_events_json", [])), ), ) row = cur.fetchone() return _format_row(row) or wallet except Exception as exc: logger.warning("[DB] db_upsert_hl_wallet error: %s", exc) return _mem.upsert_hl_wallet(wallet) def db_get_hl_wallets(limit: int = 100) -> list[dict]: if not DATABASE_URL: return _mem.get_hl_wallets(limit) sql = """ SELECT * FROM hl_whale_wallets ORDER BY reliability_score DESC, account_value_usd DESC LIMIT %s; """ try: with get_connection() as conn: with conn.cursor() as cur: cur.execute(sql, (limit,)) rows = cur.fetchall() return [_format_row(r) for r in rows if r] except Exception as exc: logger.warning("[DB] db_get_hl_wallets error: %s", exc) return _mem.get_hl_wallets(limit) def db_get_hl_wallet(address: str) -> dict | None: if not DATABASE_URL: return _mem.get_hl_wallet(address) sql = "SELECT * FROM hl_whale_wallets WHERE LOWER(address) = LOWER(%s);" try: with get_connection() as conn: with conn.cursor() as cur: cur.execute(sql, (address,)) row = cur.fetchone() return _format_row(row) except Exception as exc: logger.warning("[DB] db_get_hl_wallet error: %s", exc) return _mem.get_hl_wallet(address) # --------------------------------------------------------------------------- # Microstructure Tape # --------------------------------------------------------------------------- def db_insert_microstructure_tape(tape_row: dict) -> dict: if not DATABASE_URL: return _mem.insert_microstructure_tape(tape_row) sql = """ INSERT INTO microstructure_tape ( symbol, timestamp_ms, mark_price, adv_24h_usd, horizon_scores, factor_scores, whale_sub_metrics, raw_replay_slice, ret_15m_pct, ret_1h_pct, ret_4h_pct, recorded_at ) VALUES ( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW() ) RETURNING *; """ try: with get_connection() as conn: with conn.cursor() as cur: cur.execute( sql, ( str(tape_row.get("symbol", "")).upper(), int(tape_row.get("timestamp_ms") or int(datetime.now(timezone.utc).timestamp() * 1000)), float(tape_row.get("mark_price", 0.0) or 0.0), float(tape_row.get("adv_24h_usd", 0.0) or 0.0), _safe_json_dumps(tape_row.get("horizon_scores", {})), _safe_json_dumps(tape_row.get("factor_scores", {})), _safe_json_dumps(tape_row.get("whale_sub_metrics", {})), _safe_json_dumps(tape_row.get("raw_replay_slice", {})), tape_row.get("ret_15m_pct"), tape_row.get("ret_1h_pct"), tape_row.get("ret_4h_pct"), ), ) row = cur.fetchone() return _format_row(row) or tape_row except Exception as exc: logger.warning("[DB] db_insert_microstructure_tape error: %s", exc) return _mem.insert_microstructure_tape(tape_row) def db_get_microstructure_tape(symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict]: if not DATABASE_URL: return _mem.get_microstructure_tape(symbol, limit, days) try: with get_connection() as conn: with conn.cursor() as cur: if symbol: sql = """ SELECT * FROM microstructure_tape WHERE symbol = %s AND recorded_at >= NOW() - (%s * INTERVAL '1 day') ORDER BY timestamp_ms DESC LIMIT %s; """ cur.execute(sql, (symbol.upper(), days, limit)) else: sql = """ SELECT * FROM microstructure_tape WHERE recorded_at >= NOW() - (%s * INTERVAL '1 day') ORDER BY timestamp_ms DESC LIMIT %s; """ cur.execute(sql, (days, limit)) rows = cur.fetchall() return [_format_row(r) for r in rows if r] except Exception as exc: logger.warning("[DB] db_get_microstructure_tape error: %s", exc) return _mem.get_microstructure_tape(symbol, limit, days) def db_get_unevaluated_microstructure_tape(limit: int = 200) -> list[dict]: if not DATABASE_URL: return _mem.get_unevaluated_microstructure_tape(limit) sql = """ SELECT * FROM microstructure_tape WHERE ret_4h_pct IS NULL OR evaluated_at IS NULL ORDER BY timestamp_ms ASC LIMIT %s; """ try: with get_connection() as conn: with conn.cursor() as cur: cur.execute(sql, (limit,)) rows = cur.fetchall() return [_format_row(r) for r in rows if r] except Exception as exc: logger.warning("[DB] db_get_unevaluated_microstructure_tape error: %s", exc) return _mem.get_unevaluated_microstructure_tape(limit) def db_update_microstructure_tape_returns( tape_id: int, ret_15m: float | None, ret_1h: float | None, ret_4h: float | None, ) -> bool: if not DATABASE_URL: return _mem.update_microstructure_tape_returns(tape_id, ret_15m, ret_1h, ret_4h) sql = """ UPDATE microstructure_tape SET ret_15m_pct = COALESCE(%s, ret_15m_pct), ret_1h_pct = COALESCE(%s, ret_1h_pct), ret_4h_pct = COALESCE(%s, ret_4h_pct), evaluated_at = NOW() WHERE id = %s; """ try: with get_connection() as conn: with conn.cursor() as cur: cur.execute(sql, (ret_15m, ret_1h, ret_4h, tape_id)) return cur.rowcount > 0 except Exception as exc: logger.warning("[DB] db_update_microstructure_tape_returns error: %s", exc) return _mem.update_microstructure_tape_returns(tape_id, ret_15m, ret_1h, ret_4h) async def async_upsert_hl_wallet(wallet: dict) -> dict: return await asyncio.to_thread(db_upsert_hl_wallet, wallet) async def async_get_hl_wallets(limit: int = 100) -> list[dict]: return await asyncio.to_thread(db_get_hl_wallets, limit) async def async_get_hl_wallet(address: str) -> dict | None: return await asyncio.to_thread(db_get_hl_wallet, address) async def async_insert_microstructure_tape(tape_row: dict) -> dict: return await asyncio.to_thread(db_insert_microstructure_tape, tape_row) async def async_get_microstructure_tape(symbol: str | None = None, limit: int = 500, days: int = 14) -> list[dict]: return await asyncio.to_thread(db_get_microstructure_tape, symbol, limit, days) async def async_get_unevaluated_microstructure_tape(limit: int = 200) -> list[dict]: return await asyncio.to_thread(db_get_unevaluated_microstructure_tape, limit) async def async_update_microstructure_tape_returns( tape_id: int, ret_15m: float | None, ret_1h: float | None, ret_4h: float | None, ) -> bool: return await asyncio.to_thread(db_update_microstructure_tape_returns, tape_id, ret_15m, ret_1h, ret_4h)