feat: добавить логирование ордеров, баланса биржи и тайминга циклов
- orders: actual fill price, fee, slippage_pct (exchange vs signal price) - balance_snapshots: exchange balance vs DB equity divergence tracking - cycle_log: started_at/finished_at/duration для мониторинга latency - exp17: расширить тест на 7 активов Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,8 @@ import numpy as np
|
||||
from ..config import Config, AssetConfig
|
||||
from ..state import (
|
||||
add_equity_snapshot, close_position, get_open_position, get_trade_history,
|
||||
log_cb_event, log_signal, open_position, update_asset, update_position,
|
||||
log_balance_snapshot, log_cb_event, log_cycle, log_order, log_signal,
|
||||
open_position, update_asset, update_position,
|
||||
)
|
||||
from . import model as model_mod
|
||||
from . import risk, signals
|
||||
@@ -36,9 +37,13 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
|
||||
Returns list of log messages.
|
||||
"""
|
||||
from datetime import datetime as dt
|
||||
import time as _time
|
||||
cycle_start = dt.utcnow().isoformat()
|
||||
cycle_t0 = _time.monotonic()
|
||||
|
||||
logs = []
|
||||
today = str(date.today())
|
||||
|
||||
if cfg.mode == "live" and len(cfg.assets) > 1:
|
||||
log.warning(f"Live mode with {len(cfg.assets)} assets — "
|
||||
f"exchange balance is shared, not per-asset")
|
||||
@@ -131,6 +136,22 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]:
|
||||
_retrain(conn, ticker, prices, cfg)
|
||||
logs.append(f"{ticker}: retrained ({retrain_reason})")
|
||||
|
||||
# Log cycle timing
|
||||
cycle_end = dt.utcnow().isoformat()
|
||||
duration = _time.monotonic() - cycle_t0
|
||||
n_signals = sum(1 for m in logs if "SIGNAL" in m)
|
||||
n_closes = sum(1 for m in logs if "CLOSED" in m)
|
||||
log_cycle(conn, cycle_start, cycle_end, round(duration, 2),
|
||||
len(cfg.assets), n_signals, n_closes)
|
||||
|
||||
# Balance snapshot: exchange vs DB equity
|
||||
from ..state import get_all_assets
|
||||
all_assets = get_all_assets(conn)
|
||||
db_total = sum(a["equity"] for a in all_assets)
|
||||
from ..notify import _get_exchange_balance
|
||||
exchange_bal = _get_exchange_balance(cfg)
|
||||
log_balance_snapshot(conn, today, exchange_bal, db_total)
|
||||
|
||||
return logs
|
||||
|
||||
|
||||
@@ -272,8 +293,10 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg):
|
||||
else:
|
||||
fee_str = ""
|
||||
msg += f" [LIVE SELL OK{fee_str}]"
|
||||
log_order(conn, pos["id"], "sell", asset_cfg.symbol, exit_price, order)
|
||||
else:
|
||||
msg += " [LIVE SELL FAILED]"
|
||||
log_order(conn, pos["id"], "sell", asset_cfg.symbol, exit_price, None, failed=True)
|
||||
log.error(f"{asset_cfg.ticker}: live sell failed on close")
|
||||
|
||||
return msg
|
||||
@@ -426,6 +449,7 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
else:
|
||||
fee_str = ""
|
||||
msg += f" [LIVE BUY OK{fee_str}]"
|
||||
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, order)
|
||||
|
||||
# Place safety stop on exchange (hard protection against flash crash)
|
||||
if cfg.risk.safety_stop_pct > 0:
|
||||
@@ -438,6 +462,7 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg):
|
||||
msg += f" [SAFETY STOP ${safety_price:,.2f}]"
|
||||
else:
|
||||
# Rollback paper position — no phantom positions
|
||||
log_order(conn, pos_id, "buy", asset_cfg.symbol, entry_price, None, failed=True)
|
||||
close_position(conn, pos_id,
|
||||
exit_price=entry_price, exit_date=str(dates[-1]),
|
||||
exit_reason="live_buy_failed", pnl_net=0, pnl_pct=0)
|
||||
|
||||
@@ -91,10 +91,49 @@ def init_db(conn: sqlite3.Connection) -> None:
|
||||
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, -- price at signal time
|
||||
filled_price REAL, -- actual average fill
|
||||
slippage_pct REAL, -- (filled - requested) / requested * 100
|
||||
fee REAL,
|
||||
fee_currency TEXT,
|
||||
cost REAL, -- total cost in quote currency
|
||||
status TEXT, -- filled | failed | dry_run
|
||||
created_at TEXT DEFAULT (datetime('now')),
|
||||
FOREIGN KEY (pos_id) REFERENCES positions(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS balance_snapshots (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
date TEXT NOT NULL,
|
||||
exchange_balance REAL,
|
||||
db_equity REAL,
|
||||
divergence_pct REAL,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS cycle_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
started_at TEXT NOT NULL,
|
||||
finished_at TEXT NOT NULL,
|
||||
duration_sec REAL,
|
||||
assets_processed INTEGER,
|
||||
signals_generated INTEGER DEFAULT 0,
|
||||
trades_closed INTEGER DEFAULT 0,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_positions_ticker ON positions(ticker);
|
||||
CREATE INDEX IF NOT EXISTS idx_positions_status ON positions(status);
|
||||
CREATE INDEX IF NOT EXISTS idx_signals_ticker ON signals(ticker);
|
||||
CREATE INDEX IF NOT EXISTS idx_equity_ticker ON equity_snapshots(ticker);
|
||||
CREATE INDEX IF NOT EXISTS idx_orders_pos ON orders(pos_id);
|
||||
""")
|
||||
# Migrations
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(assets)").fetchall()}
|
||||
@@ -234,6 +273,78 @@ def get_equity_history(conn: sqlite3.Connection, ticker: str | None = None) -> l
|
||||
|
||||
# -- CB events --
|
||||
|
||||
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 (fill price, fee, slippage)."""
|
||||
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()
|
||||
|
||||
|
||||
def log_balance_snapshot(conn: sqlite3.Connection, date: str,
|
||||
exchange_balance: float | None,
|
||||
db_equity: float) -> None:
|
||||
"""Log exchange balance vs DB equity for divergence tracking."""
|
||||
if exchange_balance is None:
|
||||
return
|
||||
divergence = ((exchange_balance - db_equity) / db_equity * 100
|
||||
if db_equity > 0 else 0)
|
||||
conn.execute(
|
||||
"INSERT INTO balance_snapshots (date, exchange_balance, db_equity, divergence_pct) "
|
||||
"VALUES (?,?,?,?)",
|
||||
(date, exchange_balance, db_equity, round(divergence, 2)),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def log_cycle(conn: sqlite3.Connection, started_at: str, finished_at: str,
|
||||
duration_sec: float, assets_processed: int,
|
||||
signals_generated: int = 0, trades_closed: int = 0) -> None:
|
||||
"""Log cycle timing and summary."""
|
||||
conn.execute(
|
||||
"INSERT INTO cycle_log (started_at, finished_at, duration_sec, "
|
||||
"assets_processed, signals_generated, trades_closed) VALUES (?,?,?,?,?,?)",
|
||||
(started_at, finished_at, duration_sec,
|
||||
assets_processed, signals_generated, trades_closed),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def log_cb_event(conn: sqlite3.Connection, ticker: str, action: str,
|
||||
reason: str = "", details: str = "") -> None:
|
||||
conn.execute(
|
||||
|
||||
Reference in New Issue
Block a user