- cli.py: RotatingFileHandler (data/scalp-bot.log, 5MB, 3 backup) - executor: log.info/warning/error на каждое действие (cycle, entry, exit, slippage, equity, candidates, holiday/weekend skip) - state: логирование open/close_position, equity changes, peak equity - Все log.* дублируют logs.append — и в journald, и в CLI output Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
257 lines
8.7 KiB
Python
257 lines
8.7 KiB
Python
"""SQLite state management — positions, sessions, equity, orders."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import sqlite3
|
|
from datetime import date
|
|
from pathlib import Path
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
DB_PATH = Path(__file__).parent / "data" / "scalp.db"
|
|
|
|
|
|
def get_db(path: Path | None = None) -> sqlite3.Connection:
|
|
"""Get database connection with row factory."""
|
|
path = path or DB_PATH
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
conn = sqlite3.connect(str(path))
|
|
conn.row_factory = sqlite3.Row
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA foreign_keys=ON")
|
|
return conn
|
|
|
|
|
|
def init_db(conn: sqlite3.Connection) -> None:
|
|
"""Create tables if they don't exist."""
|
|
conn.executescript("""
|
|
CREATE TABLE IF NOT EXISTS state (
|
|
key TEXT PRIMARY KEY,
|
|
value REAL NOT NULL
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
date TEXT NOT NULL,
|
|
symbol TEXT NOT NULL,
|
|
or_high REAL NOT NULL,
|
|
or_low REAL NOT NULL,
|
|
created_at TEXT DEFAULT (datetime('now')),
|
|
PRIMARY KEY (date, symbol)
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS positions (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
date TEXT NOT NULL,
|
|
symbol TEXT NOT NULL DEFAULT '',
|
|
direction TEXT NOT NULL, -- long | short
|
|
entry_price REAL NOT NULL,
|
|
exit_price REAL,
|
|
stop_price REAL NOT NULL,
|
|
tp_price REAL NOT NULL,
|
|
pos_size REAL NOT NULL, -- qty in base currency
|
|
pos_value REAL NOT NULL, -- notional in USDT
|
|
pnl_net REAL,
|
|
status TEXT DEFAULT 'open', -- open | closed
|
|
exit_reason TEXT, -- sl | tp | eod | manual
|
|
sl_order_id TEXT,
|
|
tp_order_id TEXT,
|
|
entry_time TEXT,
|
|
exit_time TEXT,
|
|
created_at TEXT DEFAULT (datetime('now'))
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS orders (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
pos_id INTEGER NOT NULL,
|
|
exchange_order_id TEXT,
|
|
side TEXT NOT NULL, -- buy | sell
|
|
symbol TEXT NOT NULL,
|
|
qty REAL,
|
|
requested_price REAL,
|
|
filled_price REAL,
|
|
slippage_pct REAL,
|
|
fee REAL,
|
|
fee_currency TEXT,
|
|
cost REAL,
|
|
status TEXT, -- filled | failed | dry_run
|
|
created_at TEXT DEFAULT (datetime('now')),
|
|
FOREIGN KEY (pos_id) REFERENCES positions(id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_positions_status ON positions(status);
|
|
CREATE INDEX IF NOT EXISTS idx_positions_date ON positions(date);
|
|
CREATE INDEX IF NOT EXISTS idx_orders_pos ON orders(pos_id);
|
|
""")
|
|
# Seed state defaults
|
|
for key, default in [("equity", 0), ("peak_equity", 0),
|
|
("trades_count", 0), ("wins", 0), ("total_pnl", 0)]:
|
|
conn.execute(
|
|
"INSERT OR IGNORE INTO state (key, value) VALUES (?, ?)",
|
|
(key, default),
|
|
)
|
|
conn.commit()
|
|
|
|
|
|
# -- State KV --
|
|
|
|
def get_state_val(conn: sqlite3.Connection, key: str) -> float:
|
|
row = conn.execute("SELECT value FROM state WHERE key=?", (key,)).fetchone()
|
|
return row["value"] if row else 0.0
|
|
|
|
|
|
def set_state_val(conn: sqlite3.Connection, key: str, value: float) -> None:
|
|
conn.execute(
|
|
"INSERT INTO state (key, value) VALUES (?, ?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value=?",
|
|
(key, value, value),
|
|
)
|
|
conn.commit()
|
|
|
|
|
|
def get_equity(conn: sqlite3.Connection) -> float:
|
|
return get_state_val(conn, "equity")
|
|
|
|
|
|
def update_equity(conn: sqlite3.Connection, equity: float) -> None:
|
|
old = get_state_val(conn, "equity")
|
|
set_state_val(conn, "equity", equity)
|
|
peak = get_state_val(conn, "peak_equity")
|
|
if equity > peak:
|
|
set_state_val(conn, "peak_equity", equity)
|
|
log.info("New peak equity: $%.2f (prev=$%.2f)", equity, peak)
|
|
log.debug("Equity: $%.2f → $%.2f (Δ=$%.2f)", old, equity, equity - old)
|
|
|
|
|
|
# -- Sessions --
|
|
|
|
def save_session(conn: sqlite3.Connection, dt: date, or_high: float,
|
|
or_low: float, symbol: str = "") -> None:
|
|
conn.execute(
|
|
"INSERT INTO sessions (date, symbol, or_high, or_low) VALUES (?, ?, ?, ?) "
|
|
"ON CONFLICT(date, symbol) DO UPDATE SET or_high=?, or_low=?",
|
|
(str(dt), symbol, or_high, or_low, or_high, or_low),
|
|
)
|
|
conn.commit()
|
|
|
|
|
|
def get_session(conn: sqlite3.Connection, dt: date,
|
|
symbol: str = "") -> dict | None:
|
|
row = conn.execute(
|
|
"SELECT * FROM sessions WHERE date=? AND symbol=?", (str(dt), symbol)
|
|
).fetchone()
|
|
return dict(row) if row else None
|
|
|
|
|
|
# -- Positions --
|
|
|
|
def open_position(conn: sqlite3.Connection, **kwargs) -> int:
|
|
cols = ", ".join(kwargs.keys())
|
|
placeholders = ", ".join("?" for _ in kwargs)
|
|
cur = conn.execute(
|
|
f"INSERT INTO positions ({cols}) VALUES ({placeholders})",
|
|
list(kwargs.values()),
|
|
)
|
|
conn.commit()
|
|
log.info("DB open_position id=%d %s %s @ %.2f",
|
|
cur.lastrowid, kwargs.get("symbol", ""),
|
|
kwargs.get("direction", ""), kwargs.get("entry_price", 0))
|
|
return cur.lastrowid
|
|
|
|
|
|
def close_position(conn: sqlite3.Connection, pos_id: int, **kwargs) -> None:
|
|
kwargs["status"] = "closed"
|
|
sets = ", ".join(f"{k}=?" for k in kwargs)
|
|
vals = list(kwargs.values()) + [pos_id]
|
|
conn.execute(f"UPDATE positions SET {sets} WHERE id=?", vals)
|
|
conn.commit()
|
|
log.info("DB close_position id=%d reason=%s pnl=%.4f",
|
|
pos_id, kwargs.get("exit_reason", ""), kwargs.get("pnl_net", 0))
|
|
|
|
|
|
def get_open_positions(conn: sqlite3.Connection,
|
|
symbol: str | None = None) -> list[dict]:
|
|
if symbol:
|
|
rows = conn.execute(
|
|
"SELECT * FROM positions WHERE status='open' AND symbol=? ORDER BY id",
|
|
(symbol,),
|
|
).fetchall()
|
|
else:
|
|
rows = conn.execute(
|
|
"SELECT * FROM positions WHERE status='open' ORDER BY id"
|
|
).fetchall()
|
|
return [dict(r) for r in rows]
|
|
|
|
|
|
def get_today_trade_count(conn: sqlite3.Connection, dt: date) -> int:
|
|
row = conn.execute(
|
|
"SELECT COUNT(*) as cnt FROM positions WHERE date=?", (str(dt),)
|
|
).fetchone()
|
|
return row["cnt"] if row else 0
|
|
|
|
|
|
def get_today_trade_keys(conn: sqlite3.Connection, dt: date,
|
|
symbol: str) -> set[str]:
|
|
"""Get trade keys for today's positions (for crash recovery)."""
|
|
rows = conn.execute(
|
|
"SELECT direction, entry_price, stop_price FROM positions "
|
|
"WHERE date=? AND symbol=?", (str(dt), symbol)
|
|
).fetchall()
|
|
return {f"{r['direction']}_{r['entry_price']:.2f}_{r['stop_price']:.2f}"
|
|
for r in rows}
|
|
|
|
|
|
def get_trade_history(conn: sqlite3.Connection, limit: int = 50) -> list[dict]:
|
|
rows = conn.execute(
|
|
"SELECT * FROM positions WHERE status='closed' ORDER BY id DESC LIMIT ?",
|
|
(limit,),
|
|
).fetchall()
|
|
return [dict(r) for r in rows]
|
|
|
|
|
|
# -- Orders --
|
|
|
|
def log_order(conn: sqlite3.Connection, pos_id: int, side: str, symbol: str,
|
|
requested_price: float, order: dict | None,
|
|
failed: bool = False) -> None:
|
|
"""Log exchange order execution details."""
|
|
if order is None or failed:
|
|
conn.execute(
|
|
"INSERT INTO orders (pos_id, side, symbol, requested_price, status) "
|
|
"VALUES (?,?,?,?,?)",
|
|
(pos_id, side, symbol, requested_price, "failed"),
|
|
)
|
|
conn.commit()
|
|
return
|
|
|
|
if order.get("dry_run"):
|
|
conn.execute(
|
|
"INSERT INTO orders (pos_id, side, symbol, requested_price, "
|
|
"filled_price, qty, cost, status) VALUES (?,?,?,?,?,?,?,?)",
|
|
(pos_id, side, symbol, requested_price,
|
|
order.get("price"), order.get("amount"), order.get("cost"), "dry_run"),
|
|
)
|
|
conn.commit()
|
|
return
|
|
|
|
filled_price = float(order.get("average") or order.get("price") or requested_price)
|
|
qty = float(order.get("filled") or order.get("amount") or 0)
|
|
cost = float(order.get("cost") or 0)
|
|
fee_info = order.get("fee") or {}
|
|
fee_cost = float(fee_info.get("cost") or 0)
|
|
fee_cur = fee_info.get("currency", "")
|
|
exchange_id = order.get("id", "")
|
|
|
|
slippage = ((filled_price - requested_price) / requested_price * 100
|
|
if requested_price > 0 else 0)
|
|
|
|
conn.execute(
|
|
"INSERT INTO orders (pos_id, exchange_order_id, side, symbol, qty, "
|
|
"requested_price, filled_price, slippage_pct, fee, fee_currency, cost, status) "
|
|
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
|
|
(pos_id, exchange_id, side, symbol, qty,
|
|
requested_price, filled_price, round(slippage, 4),
|
|
fee_cost, fee_cur, cost, "filled"),
|
|
)
|
|
conn.commit()
|