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:
anor
2026-03-10 03:01:53 +10:00
co-authored by Claude Opus 4.6
parent 536e32261a
commit 7167dedcaa
3 changed files with 178 additions and 8 deletions
+40 -6
View File
@@ -27,11 +27,22 @@ CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
COMMISSION = 0.001
INTEREST_RATE_DAILY = 0.0002
STOP_SCALE = 0.5 # exp16e winner
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.5},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.5},
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
@@ -153,7 +164,9 @@ def run_sim(asset_data, events, variant="baseline"):
if stopped:
pnl_gross = pos.pos_size * (pos.stop_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
pnl_net = pnl_gross - commission_cost
hold_hours = bars_since * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({"ticker": ticker, "pnl_net": pnl_net,
@@ -194,21 +207,39 @@ def run_sim(asset_data, events, variant="baseline"):
# Use model_prices for prediction input
w = model_prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy() # always Close for confirmation
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
# Shape confirmation: always use Close prices with Close normalization
confirm = prices[price_idx - K:price_idx].copy()
w_close = prices[price_idx - ws - K:price_idx - K]
mu_close, std_close = float(w_close.mean()), float(w_close.std())
if std_close < 1e-10:
continue
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
pred_new, confirm, mu_close, std_close, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
# Correlation filter
skip_corr = False
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
skip_corr = True
if skip_corr:
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
@@ -252,7 +283,10 @@ def run_sim(asset_data, events, variant="baseline"):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
pnl_net = pnl_gross - pos.pos_value * COMMISSION * 2
bars_held = ad["test_data"][-1]["price_idx"] - pos.entry_bar
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - pos.pos_value * COMMISSION * 2 - trade_interest
free_usdc += pos.margin_locked + pnl_net
per_asset[ticker] = per_asset.get(ticker, 0) + pnl_net
trades.append({"ticker": ticker, "pnl_net": pnl_net,
+27 -2
View File
@@ -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)
+111
View File
@@ -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(