Download store/db.py from abyXsmart/Confluence_Reversal_Engine: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/spaces/abyXsmart/Confluence_Reversal_Engine/resolve/main/store/db.py
- Command line
-
hf download hf://spaces/abyXsmart/Confluence_Reversal_Engine/store/db.py
-
curl -L -o db.py https://huggingface.co/spaces/abyXsmart/Confluence_Reversal_Engine/resolve/main/store/db.py
9.61 kB
| """ | |
| SQLite persistence layer (spec Β§9). | |
| Schema is verbatim from Β§9. Access is synchronous (sqlite3) but every call is | |
| short; background asyncio workers wrap writes in asyncio.to_thread so the event | |
| loop never blocks. WAL mode + check_same_thread=False makes concurrent reads | |
| (dashboard) safe alongside writer tasks. | |
| DB_PATH is configurable (spec Β§12): ./cre.db (ephemeral) or /data/cre.db (HF | |
| persistent storage). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import sqlite3 | |
| import time | |
| from typing import Any | |
| from config import DB_PATH | |
| _SCHEMA = """ | |
| CREATE TABLE IF NOT EXISTS liq_buckets ( | |
| symbol TEXT, minute_ts INTEGER, | |
| long_notional REAL, short_notional REAL, | |
| n_orders INTEGER, complete INTEGER DEFAULT 1, | |
| PRIMARY KEY (symbol, minute_ts) | |
| ); | |
| CREATE TABLE IF NOT EXISTS market_snapshots ( | |
| symbol TEXT, ts INTEGER, | |
| funding_rate REAL, funding_z REAL, | |
| oi_usd REAL, oi_pctile REAL, | |
| mark_price REAL, spot_price REAL, | |
| PRIMARY KEY (symbol, ts) | |
| ); | |
| CREATE TABLE IF NOT EXISTS signals ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| created_ts INTEGER, symbol TEXT, direction TEXT, | |
| tier TEXT, state TEXT, | |
| score_total INTEGER, score_funding INTEGER, score_oi INTEGER, | |
| score_liq INTEGER, score_priceflow INTEGER, | |
| funding_z REAL, oi_pctile REAL, liq_mult REAL, | |
| flush_candle_ts INTEGER, | |
| entry REAL, stop REAL, target1 REAL, target2 REAL, rr1 REAL, | |
| cold_start INTEGER DEFAULT 0, | |
| config_version INTEGER, | |
| resolved_ts INTEGER, outcome TEXT, result_r REAL, mfe_r REAL, mae_r REAL, | |
| UNIQUE (symbol, direction, flush_candle_ts) | |
| ); | |
| CREATE TABLE IF NOT EXISTS alerts_sent ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| signal_id INTEGER, ts INTEGER, kind TEXT, delivered INTEGER | |
| ); | |
| CREATE TABLE IF NOT EXISTS config_versions ( | |
| version INTEGER PRIMARY KEY, ts INTEGER, json TEXT | |
| ); | |
| """ | |
| _conn: sqlite3.Connection | None = None | |
| def conn() -> sqlite3.Connection: | |
| global _conn | |
| if _conn is None: | |
| _conn = sqlite3.connect(DB_PATH, check_same_thread=False) | |
| _conn.row_factory = sqlite3.Row | |
| _conn.execute("PRAGMA journal_mode=WAL;") | |
| _conn.execute("PRAGMA synchronous=NORMAL;") | |
| return _conn | |
| def init() -> None: | |
| """Create tables if missing. Idempotent β safe on every boot.""" | |
| c = conn() | |
| c.executescript(_SCHEMA) | |
| c.commit() | |
| def save_config_version(version: int, snapshot: dict) -> None: | |
| """Persist the active config snapshot (spec Β§7 traceability).""" | |
| c = conn() | |
| c.execute( | |
| "INSERT OR REPLACE INTO config_versions (version, ts, json) VALUES (?,?,?)", | |
| (version, int(time.time()), json.dumps(snapshot)), | |
| ) | |
| c.commit() | |
| # ββ Liquidation buckets (spec Β§2.1) βββββββββββββββββββββββββββββββββββββββββ | |
| def upsert_liq_bucket( | |
| symbol: str, minute_ts: int, long_add: float, short_add: float, | |
| n_add: int, complete: int = 1, | |
| ) -> None: | |
| """Accumulate a per-symbol/per-minute liquidation bucket.""" | |
| c = conn() | |
| c.execute( | |
| """ | |
| INSERT INTO liq_buckets (symbol, minute_ts, long_notional, short_notional, n_orders, complete) | |
| VALUES (?,?,?,?,?,?) | |
| ON CONFLICT(symbol, minute_ts) DO UPDATE SET | |
| long_notional = long_notional + excluded.long_notional, | |
| short_notional = short_notional + excluded.short_notional, | |
| n_orders = n_orders + excluded.n_orders, | |
| complete = MIN(complete, excluded.complete) | |
| """, | |
| (symbol, minute_ts, long_add, short_add, n_add, complete), | |
| ) | |
| c.commit() | |
| def mark_gap(symbol: str, minute_ts: int) -> None: | |
| """Mark a minute bucket incomplete (ws gap) so baselines exclude it (spec Β§8.2).""" | |
| c = conn() | |
| c.execute( | |
| """INSERT INTO liq_buckets (symbol, minute_ts, long_notional, short_notional, n_orders, complete) | |
| VALUES (?,?,0,0,0,0) | |
| ON CONFLICT(symbol, minute_ts) DO UPDATE SET complete=0""", | |
| (symbol, minute_ts), | |
| ) | |
| c.commit() | |
| def liq_baseline_days(symbol: str) -> float: | |
| """Distinct days of complete liquidation data collected for a symbol (cold-start gauge).""" | |
| c = conn() | |
| row = c.execute( | |
| "SELECT COUNT(DISTINCT minute_ts/1440) AS d FROM liq_buckets WHERE symbol=? AND complete=1", | |
| (symbol,), | |
| ).fetchone() | |
| return float(row["d"] or 0) | |
| def recent_liq_buckets(symbol: str, since_minute_ts: int) -> list[dict]: | |
| c = conn() | |
| rows = c.execute( | |
| "SELECT * FROM liq_buckets WHERE symbol=? AND minute_ts>=? AND complete=1 ORDER BY minute_ts", | |
| (symbol, since_minute_ts), | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| # ββ Market snapshots (spec Β§9) ββββββββββββββββββββββββββββββββββββββββββββββ | |
| def save_market_snapshot(s: dict) -> None: | |
| c = conn() | |
| c.execute( | |
| """INSERT OR REPLACE INTO market_snapshots | |
| (symbol, ts, funding_rate, funding_z, oi_usd, oi_pctile, mark_price, spot_price) | |
| VALUES (:symbol,:ts,:funding_rate,:funding_z,:oi_usd,:oi_pctile,:mark_price,:spot_price)""", | |
| s, | |
| ) | |
| c.commit() | |
| def latest_snapshots() -> list[dict]: | |
| """Most recent snapshot per symbol (dashboard tab 1).""" | |
| c = conn() | |
| rows = c.execute( | |
| """SELECT m.* FROM market_snapshots m | |
| JOIN (SELECT symbol, MAX(ts) mts FROM market_snapshots GROUP BY symbol) x | |
| ON m.symbol=x.symbol AND m.ts=x.mts ORDER BY m.symbol""", | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def liq_baseline_notional(symbol: str, lookback_minutes: int = 1440) -> float: | |
| """Median per-minute total liquidation notional over recent complete buckets | |
| (self-collected baseline for L1). 0 if no data yet (cold start).""" | |
| c = conn() | |
| rows = c.execute( | |
| """SELECT (long_notional + short_notional) AS tot FROM liq_buckets | |
| WHERE symbol=? AND complete=1 AND (long_notional+short_notional)>0 | |
| ORDER BY minute_ts DESC LIMIT ?""", | |
| (symbol, lookback_minutes), | |
| ).fetchall() | |
| vals = sorted(r["tot"] for r in rows) | |
| if not vals: | |
| return 0.0 | |
| n = len(vals) | |
| return vals[n // 2] if n % 2 else (vals[n // 2 - 1] + vals[n // 2]) / 2 | |
| def oi_change_pct(symbol: str, window_sec: int = 1800) -> float: | |
| """% change in OI between the latest snapshot and the one ~window_sec earlier | |
| (self-collected, avoids the rubik scale mismatch). 0 if insufficient history.""" | |
| c = conn() | |
| rows = c.execute( | |
| "SELECT ts, oi_usd FROM market_snapshots WHERE symbol=? AND oi_usd>0 ORDER BY ts DESC LIMIT 200", | |
| (symbol,), | |
| ).fetchall() | |
| if len(rows) < 2: | |
| return 0.0 | |
| latest = rows[0] | |
| ref = next((r for r in rows if latest["ts"] - r["ts"] >= window_sec), rows[-1]) | |
| if ref["oi_usd"] <= 0: | |
| return 0.0 | |
| return (latest["oi_usd"] - ref["oi_usd"]) / ref["oi_usd"] * 100.0 | |
| # ββ Signals (spec Β§5, Β§7) ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def insert_signal(s: dict) -> int | None: | |
| """Insert a new signal. Returns row id, or None if a duplicate | |
| (symbol,direction,flush_candle_ts) already exists (UNIQUE guard).""" | |
| c = conn() | |
| try: | |
| cur = c.execute( | |
| """INSERT INTO signals | |
| (created_ts,symbol,direction,tier,state,score_total,score_funding, | |
| score_oi,score_liq,score_priceflow,funding_z,oi_pctile,liq_mult, | |
| flush_candle_ts,entry,stop,target1,target2,rr1,cold_start,config_version, | |
| resolved_ts,outcome,result_r,mfe_r,mae_r) | |
| VALUES | |
| (:created_ts,:symbol,:direction,:tier,:state,:score_total,:score_funding, | |
| :score_oi,:score_liq,:score_priceflow,:funding_z,:oi_pctile,:liq_mult, | |
| :flush_candle_ts,:entry,:stop,:target1,:target2,:rr1,:cold_start,:config_version, | |
| NULL,NULL,NULL,NULL,NULL)""", | |
| s, | |
| ) | |
| c.commit() | |
| return cur.lastrowid | |
| except sqlite3.IntegrityError: | |
| return None | |
| def update_signal_state(signal_id: int, state: str, resolved_ts: int | None = None, | |
| outcome: str | None = None, result_r: float | None = None) -> None: | |
| c = conn() | |
| c.execute( | |
| """UPDATE signals SET state=?, | |
| resolved_ts=COALESCE(?,resolved_ts), outcome=COALESCE(?,outcome), | |
| result_r=COALESCE(?,result_r) WHERE id=?""", | |
| (state, resolved_ts, outcome, result_r, signal_id), | |
| ) | |
| c.commit() | |
| def active_signals() -> list[dict]: | |
| """Non-terminal signals the monitor must track.""" | |
| c = conn() | |
| rows = c.execute( | |
| "SELECT * FROM signals WHERE state NOT IN ('HIT_TARGET2','HIT_STOP','EXPIRED','CANCELLED') ORDER BY created_ts DESC" | |
| ).fetchall() | |
| return [dict(r) for r in rows] | |
| def recent_signals(limit: int = 100) -> list[dict]: | |
| c = conn() | |
| rows = c.execute("SELECT * FROM signals ORDER BY created_ts DESC LIMIT ?", (limit,)).fetchall() | |
| return [dict(r) for r in rows] | |
| def log_alert(signal_id: int, kind: str, delivered: int) -> None: | |
| c = conn() | |
| c.execute( | |
| "INSERT INTO alerts_sent (signal_id, ts, kind, delivered) VALUES (?,?,?,?)", | |
| (signal_id, int(time.time()), kind, delivered), | |
| ) | |
| c.commit() | |
| def query(sql: str, params: tuple = ()) -> list[dict]: | |
| """Generic read helper for analytics/dashboard.""" | |
| c = conn() | |
| return [dict(r) for r in c.execute(sql, params).fetchall()] | |