172 lines
6.1 KiB
Python
Executable File
172 lines
6.1 KiB
Python
Executable File
"""SQLite persistence for portfolios, trades and equity history."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sqlite3
|
|
import threading
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from .portfolio import Fill, Portfolio
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS strategy_state (
|
|
strategy_id TEXT PRIMARY KEY,
|
|
portfolio TEXT NOT NULL,
|
|
starting_capital REAL NOT NULL,
|
|
last_candle TEXT,
|
|
started_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE IF NOT EXISTS trades (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
strategy_id TEXT NOT NULL,
|
|
time TEXT NOT NULL,
|
|
mode TEXT NOT NULL,
|
|
pair TEXT NOT NULL,
|
|
side TEXT NOT NULL,
|
|
volume REAL NOT NULL,
|
|
price REAL NOT NULL,
|
|
fee REAL NOT NULL,
|
|
realized_pnl REAL,
|
|
txid TEXT
|
|
);
|
|
CREATE INDEX IF NOT EXISTS ix_trades_strategy ON trades(strategy_id, time);
|
|
CREATE TABLE IF NOT EXISTS equity (
|
|
strategy_id TEXT NOT NULL,
|
|
time TEXT NOT NULL,
|
|
equity REAL NOT NULL
|
|
);
|
|
CREATE INDEX IF NOT EXISTS ix_equity_strategy ON equity(strategy_id, time);
|
|
CREATE TABLE IF NOT EXISTS account (
|
|
time TEXT PRIMARY KEY,
|
|
total_usd REAL NOT NULL,
|
|
holdings TEXT NOT NULL
|
|
);
|
|
"""
|
|
|
|
|
|
def _iso(dt: datetime) -> str:
|
|
return dt.astimezone(timezone.utc).isoformat()
|
|
|
|
|
|
class Store:
|
|
def __init__(self, path: Path):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._conn = sqlite3.connect(path, check_same_thread=False)
|
|
self._conn.row_factory = sqlite3.Row
|
|
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
self._conn.executescript(SCHEMA)
|
|
# Engine (event loop) and web handlers (thread pool) share one connection.
|
|
self._lock = threading.Lock()
|
|
|
|
def _exec(self, sql: str, params: tuple = ()) -> list[sqlite3.Row]:
|
|
with self._lock, self._conn:
|
|
return self._conn.execute(sql, params).fetchall()
|
|
|
|
# ---- strategy state ------------------------------------------------
|
|
|
|
def load_state(self, strategy_id: str) -> tuple[Portfolio, float, datetime | None] | None:
|
|
rows = self._exec(
|
|
"SELECT portfolio, starting_capital, last_candle FROM strategy_state"
|
|
" WHERE strategy_id = ?",
|
|
(strategy_id,),
|
|
)
|
|
if not rows:
|
|
return None
|
|
row = rows[0]
|
|
last = datetime.fromisoformat(row["last_candle"]) if row["last_candle"] else None
|
|
return Portfolio.from_dict(json.loads(row["portfolio"])), row["starting_capital"], last
|
|
|
|
def save_state(
|
|
self,
|
|
strategy_id: str,
|
|
portfolio: Portfolio,
|
|
starting_capital: float,
|
|
last_candle: datetime | None,
|
|
) -> None:
|
|
self._exec(
|
|
"INSERT INTO strategy_state (strategy_id, portfolio, starting_capital, last_candle,"
|
|
" started_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(strategy_id) DO UPDATE SET"
|
|
" portfolio = excluded.portfolio, last_candle = excluded.last_candle",
|
|
(
|
|
strategy_id,
|
|
json.dumps(portfolio.to_dict()),
|
|
starting_capital,
|
|
_iso(last_candle) if last_candle else None,
|
|
_iso(datetime.now(timezone.utc)),
|
|
),
|
|
)
|
|
|
|
def started_at(self, strategy_id: str) -> datetime | None:
|
|
rows = self._exec(
|
|
"SELECT started_at FROM strategy_state WHERE strategy_id = ?", (strategy_id,)
|
|
)
|
|
return datetime.fromisoformat(rows[0]["started_at"]) if rows else None
|
|
|
|
# ---- trades --------------------------------------------------------
|
|
|
|
def record_trade(self, strategy_id: str, mode: str, fill: Fill, pnl: float | None) -> None:
|
|
self._exec(
|
|
"INSERT INTO trades (strategy_id, time, mode, pair, side, volume, price, fee,"
|
|
" realized_pnl, txid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
(
|
|
strategy_id,
|
|
_iso(fill.time),
|
|
mode,
|
|
fill.pair,
|
|
fill.side,
|
|
fill.volume,
|
|
fill.price,
|
|
fill.fee,
|
|
pnl,
|
|
fill.txid,
|
|
),
|
|
)
|
|
|
|
def trades(self, strategy_id: str, limit: int | None = None) -> list[dict]:
|
|
sql = "SELECT * FROM trades WHERE strategy_id = ? ORDER BY time DESC, id DESC"
|
|
params: tuple = (strategy_id,)
|
|
if limit:
|
|
sql += " LIMIT ?"
|
|
params += (limit,)
|
|
return [dict(r) for r in self._exec(sql, params)]
|
|
|
|
# ---- equity --------------------------------------------------------
|
|
|
|
def record_equity(self, strategy_id: str, time: datetime, equity: float) -> None:
|
|
self._exec(
|
|
"INSERT INTO equity (strategy_id, time, equity) VALUES (?, ?, ?)",
|
|
(strategy_id, _iso(time), equity),
|
|
)
|
|
|
|
def equity_series(self, strategy_id: str) -> list[tuple[datetime, float]]:
|
|
rows = self._exec(
|
|
"SELECT time, equity FROM equity WHERE strategy_id = ? ORDER BY time",
|
|
(strategy_id,),
|
|
)
|
|
return [(datetime.fromisoformat(r["time"]), r["equity"]) for r in rows]
|
|
|
|
# ---- whole account -------------------------------------------------
|
|
|
|
def record_account(self, time: datetime, total_usd: float, holdings: list[dict]) -> None:
|
|
self._exec(
|
|
"INSERT OR REPLACE INTO account (time, total_usd, holdings) VALUES (?, ?, ?)",
|
|
(_iso(time), total_usd, json.dumps(holdings)),
|
|
)
|
|
|
|
def account_series(self) -> list[tuple[datetime, float]]:
|
|
rows = self._exec("SELECT time, total_usd FROM account ORDER BY time")
|
|
return [(datetime.fromisoformat(r["time"]), r["total_usd"]) for r in rows]
|
|
|
|
def latest_account(self) -> dict | None:
|
|
rows = self._exec("SELECT * FROM account ORDER BY time DESC LIMIT 1")
|
|
if not rows:
|
|
return None
|
|
row = rows[0]
|
|
return {
|
|
"time": datetime.fromisoformat(row["time"]),
|
|
"total_usd": row["total_usd"],
|
|
"holdings": json.loads(row["holdings"]),
|
|
}
|