File size: 11,456 Bytes
f74bb64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
FVG-Delta Forex Signal Engine v6.0 β€” Persistence Layer
======================================================

GOAL
----
Survive container restarts on Hugging Face. The Space has a Storage Bucket
(Xet-backed) mounted read-write at ``/data`` (8.7 GB). We persist:

  * Trade History           -> SQLite  (``fvg_engine.db``)   β€” queryable/filterable
  * Live engine state       -> JSON    (``state.json``)      β€” whole snapshot
  * Alerts feed             -> JSON    (``alerts.json``)
  * Engine stats            -> JSON    (``stats.json``)

DESIGN RULES (as requested)
---------------------------
* **Create-if-missing, read-if-exists.** ``init()`` opens (and creates) the DB
  and returns the data dir. ``load_*`` returns ``None``/empty when a file is
  absent (first ever run) β€” the engine then just starts fresh.
* **Atomic writes.** JSON is written to a temp file then ``os.replace``d, so a
  crash mid-write can never corrupt the live snapshot.
* **SQLite for history** because the Trade-History dashboard filters by time
  (15m … All time) and aggregates metrics β€” that is ``WHERE ts BETWEEN`` /
  ``GROUP BY``, fast and corruption-safe (WAL mode, one writer + many readers).
* **Graceful degrade.** If ``/data`` is not writable (e.g. free tier with no
  mount), we fall back to the current working directory and set
  ``persistent=False`` so the dashboard can warn β€” the engine still runs.

WHY BOTH SQLite *and* JSON?
---------------------------
Trade History is an append-mostly, growing, *queryable* record β†’ SQLite.
Live state is one volatile blob fully rewritten each save and fully reloaded on
boot β†’ a single atomic JSON file (a relational schema would buy nothing and the
atomic replace cannot corrupt). Each fits its job.

The trades table keeps a few indexed columns for fast filtering plus a ``data``
JSON column holding the COMPLETE row, so we never lose a field and the dashboard
can show full per-trade detail without a brittle wide schema.
"""
from __future__ import annotations

import json
import logging
import os
import sqlite3
import threading
import time
from typing import Dict, List, Optional

log = logging.getLogger("fvg.persistence")

_LOCK = threading.RLock()
_DB: Optional[sqlite3.Connection] = None
_DATA_DIR = ""
_PERSISTENT = False

DB_NAME = "fvg_engine.db"
STATE_FILE = "state.json"
ALERTS_FILE = "alerts.json"
STATS_FILE = "stats.json"


# --------------------------------------------------------------------------- #
# Init / paths
# --------------------------------------------------------------------------- #
def _pick_data_dir() -> "tuple[str, bool]":
    """Choose the data directory. Prefer FVG_DATA_DIR, then /data (HF mount),
    then ./ (cwd). Returns (path, is_persistent_mount)."""
    candidates = []
    env_dir = os.getenv("FVG_DATA_DIR", "").strip()
    if env_dir:
        candidates.append((env_dir, True))
    candidates.append(("/data", True))
    candidates.append((os.path.abspath("."), False))
    for path, persistent in candidates:
        try:
            os.makedirs(path, exist_ok=True)
            probe = os.path.join(path, ".fvg_write_test")
            with open(probe, "w") as f:
                f.write("ok")
            os.remove(probe)
            return path, persistent
        except Exception:
            continue
    # last resort β€” cwd without write test
    return os.path.abspath("."), False


def init(data_dir: Optional[str] = None) -> str:
    """Open (creating if needed) the SQLite DB and return the data dir path.
    Idempotent β€” safe to call once at startup."""
    global _DB, _DATA_DIR, _PERSISTENT
    with _LOCK:
        if _DB is not None:
            return _DATA_DIR
        if data_dir:
            _DATA_DIR, _PERSISTENT = data_dir, True
            os.makedirs(_DATA_DIR, exist_ok=True)
        else:
            _DATA_DIR, _PERSISTENT = _pick_data_dir()
        db_path = os.path.join(_DATA_DIR, DB_NAME)
        _DB = sqlite3.connect(db_path, check_same_thread=False)
        _DB.row_factory = sqlite3.Row
        try:
            _DB.execute("PRAGMA journal_mode=WAL;")
            _DB.execute("PRAGMA synchronous=NORMAL;")
        except Exception:
            pass
        _DB.execute(
            """
            CREATE TABLE IF NOT EXISTS trades (
                id         INTEGER PRIMARY KEY AUTOINCREMENT,
                symbol     TEXT,
                opened_ts  INTEGER,
                closed_ts  INTEGER,
                direction  TEXT,
                outcome    TEXT,
                category   TEXT,
                data       TEXT,
                UNIQUE(symbol, opened_ts)
            )
            """
        )
        _DB.execute("CREATE INDEX IF NOT EXISTS ix_trades_closed ON trades(closed_ts)")
        _DB.execute("CREATE INDEX IF NOT EXISTS ix_trades_symbol ON trades(symbol)")
        _DB.commit()
        log.info("persistence: data_dir=%s persistent=%s db=%s",
                 _DATA_DIR, _PERSISTENT, db_path)
        return _DATA_DIR


def storage_info() -> Dict:
    """Diagnostics for the dashboard: where we persist + whether it survives."""
    info = {"data_dir": _DATA_DIR, "persistent": _PERSISTENT,
            "db": os.path.join(_DATA_DIR, DB_NAME) if _DATA_DIR else ""}
    try:
        if _DATA_DIR:
            st = os.statvfs(_DATA_DIR)
            info["free_gb"] = round(st.f_bavail * st.f_frsize / 1e9, 2)
            info["total_gb"] = round(st.f_blocks * st.f_frsize / 1e9, 2)
    except Exception:
        pass
    return info


# --------------------------------------------------------------------------- #
# JSON snapshots (atomic) β€” live state / alerts / stats
# --------------------------------------------------------------------------- #
def _atomic_write_json(filename: str, payload) -> bool:
    if not _DATA_DIR:
        init()
    path = os.path.join(_DATA_DIR, filename)
    tmp = path + ".tmp"
    try:
        with _LOCK:
            with open(tmp, "w") as f:
                json.dump(payload, f, separators=(",", ":"))
                f.flush()
                os.fsync(f.fileno())
            os.replace(tmp, path)
        return True
    except Exception as e:
        log.warning("persistence: write %s failed: %s", filename, e)
        try:
            if os.path.exists(tmp):
                os.remove(tmp)
        except Exception:
            pass
        return False


def _read_json(filename: str):
    if not _DATA_DIR:
        init()
    path = os.path.join(_DATA_DIR, filename)
    if not os.path.exists(path):
        return None
    try:
        with open(path) as f:
            return json.load(f)
    except Exception as e:
        log.warning("persistence: read %s failed: %s", filename, e)
        return None


def save_state(payload: Dict) -> bool:
    """Persist the live engine snapshot (pairs in stage 1-4 + their locked
    structure). Caller builds a plain-dict payload."""
    payload = dict(payload or {})
    payload["_saved_ts"] = int(time.time())
    return _atomic_write_json(STATE_FILE, payload)


def load_state() -> Optional[Dict]:
    """Return the last live snapshot, or None on first ever run."""
    return _read_json(STATE_FILE)


def save_alerts(alerts: List[Dict]) -> bool:
    return _atomic_write_json(ALERTS_FILE, list(alerts or []))


def load_alerts() -> List[Dict]:
    data = _read_json(ALERTS_FILE)
    return data if isinstance(data, list) else []


def save_stats(stats: Dict) -> bool:
    return _atomic_write_json(STATS_FILE, dict(stats or {}))


def load_stats() -> Optional[Dict]:
    return _read_json(STATS_FILE)


# --------------------------------------------------------------------------- #
# Trade history (SQLite)
# --------------------------------------------------------------------------- #
def record_trade(row: Dict) -> bool:
    """Upsert one trade row keyed by (symbol, opened_ts). Stores indexed columns
    for filtering plus the complete row as JSON in ``data``."""
    if _DB is None:
        init()
    symbol = row.get("symbol")
    opened_ts = row.get("opened_ts")
    if not symbol or not opened_ts:
        return False
    try:
        with _LOCK:
            _DB.execute(
                """
                INSERT INTO trades (symbol, opened_ts, closed_ts, direction,
                                    outcome, category, data)
                VALUES (?,?,?,?,?,?,?)
                ON CONFLICT(symbol, opened_ts) DO UPDATE SET
                    closed_ts=excluded.closed_ts,
                    direction=excluded.direction,
                    outcome=excluded.outcome,
                    category=excluded.category,
                    data=excluded.data
                """,
                (symbol, int(opened_ts),
                 int(row.get("closed_ts") or 0) or None,
                 row.get("direction"), row.get("outcome"),
                 row.get("category"), json.dumps(row, separators=(",", ":"))),
            )
            _DB.commit()
        return True
    except Exception as e:
        log.warning("persistence: record_trade failed (%s): %s", symbol, e)
        return False


def _row_to_dict(r: sqlite3.Row) -> Dict:
    try:
        d = json.loads(r["data"]) if r["data"] else {}
    except Exception:
        d = {}
    # ensure indexed columns win (in case the blob is stale)
    d.setdefault("symbol", r["symbol"])
    d.setdefault("opened_ts", r["opened_ts"])
    if r["closed_ts"]:
        d.setdefault("closed_ts", r["closed_ts"])
    if r["outcome"]:
        d.setdefault("outcome", r["outcome"])
    return d


def load_recent_trades(limit: int = 3000) -> List[Dict]:
    """Newest-first list to repopulate the in-memory history deque on startup."""
    if _DB is None:
        init()
    try:
        with _LOCK:
            cur = _DB.execute(
                "SELECT * FROM trades ORDER BY COALESCE(closed_ts, opened_ts) DESC LIMIT ?",
                (int(limit),))
            return [_row_to_dict(r) for r in cur.fetchall()]
    except Exception as e:
        log.warning("persistence: load_recent_trades failed: %s", e)
        return []


def query_trades(since_ts: Optional[int] = None, until_ts: Optional[int] = None,
                 closed_only: bool = True, limit: int = 100000) -> List[Dict]:
    """Filtered query for the Trade-History dashboard. Filters on closed_ts
    (the moment the trade resolved) so the time windows match 'completed trades'.
    """
    if _DB is None:
        init()
    where, params = [], []
    if closed_only:
        where.append("closed_ts IS NOT NULL")
    if since_ts is not None:
        where.append("COALESCE(closed_ts, opened_ts) >= ?")
        params.append(int(since_ts))
    if until_ts is not None:
        where.append("COALESCE(closed_ts, opened_ts) < ?")
        params.append(int(until_ts))
    sql = "SELECT * FROM trades"
    if where:
        sql += " WHERE " + " AND ".join(where)
    sql += " ORDER BY COALESCE(closed_ts, opened_ts) DESC LIMIT ?"
    params.append(int(limit))
    try:
        with _LOCK:
            cur = _DB.execute(sql, tuple(params))
            return [_row_to_dict(r) for r in cur.fetchall()]
    except Exception as e:
        log.warning("persistence: query_trades failed: %s", e)
        return []


def count_trades() -> int:
    if _DB is None:
        init()
    try:
        with _LOCK:
            cur = _DB.execute("SELECT COUNT(*) AS n FROM trades")
            return int(cur.fetchone()["n"])
    except Exception:
        return 0