File size: 9,608 Bytes
c6262df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
"""
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()]