FVG-Delta_Forex_Engine / persistence.py
abyXsmart's picture
Upload 19 files
f74bb64 verified
Raw History Blame Contribute Delete
11.5 kB
"""
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