From 0fc318dec224f3d839dd5144e0da52b62ae6b4d3 Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 10 Mar 2026 19:30:10 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BC=D0=B0?= =?UTF-8?q?=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=BE=D0=B5=20=D0=BE=D0=B1?= =?UTF-8?q?=D0=BD=D0=B0=D1=80=D1=83=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4?= =?UTF-8?q?=D0=B5=D0=BF=D0=BE=D0=B7=D0=B8=D1=82=D0=BE=D0=B2/=D0=B2=D1=8B?= =?UTF-8?q?=D0=B2=D0=BE=D0=B4=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Таблица deposits в БД для хранения истории пополнений - detect_deposit(): сравнивает баланс с предыдущим снимком + realized PnL, порог $10 для фильтрации шума от unrealized изменений - get_total_deposited(): config.total + сумма депозитов из БД - Все отчёты (Telegram, web, CLI) теперь считают % от реального депо - При обнаружении депозита — запись в лог и Telegram Co-Authored-By: Claude Opus 4.6 --- src/remizov_trader/cli.py | 4 ++- src/remizov_trader/core/executor.py | 26 ++++++++++++-- src/remizov_trader/notify.py | 10 ++++-- src/remizov_trader/state.py | 54 +++++++++++++++++++++++++++++ src/remizov_trader/web/app.py | 4 ++- 5 files changed, 91 insertions(+), 7 deletions(-) diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 034d4ce..4c43b3e 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -107,8 +107,10 @@ def status(): click.echo(f" REMIZOV TRADER — {cfg.mode.upper()} MODE") click.echo("=" * 70) + from .state import get_total_deposited total_equity = 0 - total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + config_total = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + total_initial = get_total_deposited(conn, config_total) header = f" {'Asset':<10s} {'Equity':>10s} {'PnL':>10s} {'Trades':>7s} {'WR':>5s} {'Position':>12s} {'CB':>3s}" click.echo(header) diff --git a/src/remizov_trader/core/executor.py b/src/remizov_trader/core/executor.py index ec80d70..38efe3c 100644 --- a/src/remizov_trader/core/executor.py +++ b/src/remizov_trader/core/executor.py @@ -11,8 +11,9 @@ import numpy as np from ..config import Config, AssetConfig from ..state import ( add_equity_snapshot, close_position, get_open_position, get_trade_history, - log_balance_snapshot, log_cb_event, log_cycle, log_order, log_signal, - open_position, update_asset, update_position, + detect_deposit, log_balance_snapshot, log_cb_event, log_cycle, + log_order, log_signal, open_position, record_deposit, + update_asset, update_position, ) from . import model as model_mod from . import risk, signals @@ -150,6 +151,27 @@ def run_cycle(conn: sqlite3.Connection, cfg: Config) -> list[str]: db_total = sum(a["equity"] for a in all_assets) from ..notify import _get_exchange_balance exchange_bal = _get_exchange_balance(cfg) + + # Detect deposits/withdrawals before logging snapshot + if exchange_bal is not None: + realized_pnl = sum( + float(m.split("PnL $")[1].split()[0]) + for m in logs if "PnL $" in m and "CLOSED" in m + ) if any("CLOSED" in m for m in logs) else 0.0 + + prev_snap = conn.execute( + "SELECT exchange_balance FROM balance_snapshots " + "WHERE exchange_balance IS NOT NULL ORDER BY id DESC LIMIT 1" + ).fetchone() + + deposit = detect_deposit(conn, exchange_bal, realized_pnl) + if deposit is not None: + prev_bal = prev_snap["exchange_balance"] if prev_snap else 0 + record_deposit(conn, deposit, prev_bal, exchange_bal) + action = "пополнение" if deposit > 0 else "вывод" + logs.append(f"DEPOSIT: {action} ${abs(deposit):,.2f} " + f"(${prev_bal:,.2f} → ${exchange_bal:,.2f})") + log_balance_snapshot(conn, today, exchange_bal, db_total) return logs diff --git a/src/remizov_trader/notify.py b/src/remizov_trader/notify.py index 3dcb9be..795c184 100644 --- a/src/remizov_trader/notify.py +++ b/src/remizov_trader/notify.py @@ -8,6 +8,7 @@ import logging import httpx from .config import LLMConfig, TelegramConfig +from .state import get_total_deposited log = logging.getLogger(__name__) @@ -99,7 +100,8 @@ def format_status_report(cfg, conn) -> str: assets = [get_asset(conn, t) for t in active_tickers] assets = [a for a in assets if a is not None] - total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + config_total = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + total_initial = get_total_deposited(conn, config_total) # Get real balance from exchange (mark-to-market) exchange_balance = _get_exchange_balance(cfg) @@ -238,7 +240,8 @@ def format_morning_report(cfg, conn) -> str: "WHERE exchange_balance IS NOT NULL ORDER BY id DESC LIMIT 1" ).fetchone() exchange_balance = snap["exchange_balance"] if snap else sum(a["equity"] for a in assets) - total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + config_total = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + total_initial = get_total_deposited(conn, config_total) total_pct = (exchange_balance / total_initial - 1) * 100 if total_initial > 0 else 0 lines = ["\u2600\ufe0f Утренний отчёт RemizovTrader", ""] @@ -396,7 +399,8 @@ def gather_daily_data(cfg, conn) -> dict: ).fetchone() exchange_balance = snap["exchange_balance"] if snap else sum(a["equity"] for a in assets) - total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + config_total = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + total_initial = get_total_deposited(conn, config_total) # Open positions open_positions = [] diff --git a/src/remizov_trader/state.py b/src/remizov_trader/state.py index d419805..a6768b8 100644 --- a/src/remizov_trader/state.py +++ b/src/remizov_trader/state.py @@ -118,6 +118,14 @@ def init_db(conn: sqlite3.Connection) -> None: created_at TEXT DEFAULT (datetime('now')) ); + CREATE TABLE IF NOT EXISTS deposits ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + amount REAL NOT NULL, + balance_before REAL, + balance_after REAL, + created_at TEXT DEFAULT (datetime('now')) + ); + CREATE TABLE IF NOT EXISTS cycle_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, started_at TEXT NOT NULL, @@ -332,6 +340,52 @@ def log_balance_snapshot(conn: sqlite3.Connection, date: str, conn.commit() +def detect_deposit(conn: sqlite3.Connection, exchange_balance: float, + realized_pnl_since: float = 0.0, + threshold: float = 10.0) -> float | None: + """Detect deposit/withdrawal by comparing with previous balance snapshot. + + Returns deposit amount if detected (negative = withdrawal), None otherwise. + Threshold filters out noise from price changes between cycles. + """ + prev = conn.execute( + "SELECT exchange_balance FROM balance_snapshots " + "WHERE exchange_balance IS NOT NULL ORDER BY id DESC LIMIT 1" + ).fetchone() + if prev is None: + return None + + prev_bal = prev["exchange_balance"] + # Expected balance = previous + realized PnL (unrealized changes don't count) + expected = prev_bal + realized_pnl_since + diff = exchange_balance - expected + + if abs(diff) > threshold: + return round(diff, 2) + return None + + +def record_deposit(conn: sqlite3.Connection, amount: float, + balance_before: float, balance_after: float) -> None: + """Record a detected deposit or withdrawal.""" + conn.execute( + "INSERT INTO deposits (amount, balance_before, balance_after) VALUES (?,?,?)", + (amount, balance_before, balance_after), + ) + conn.commit() + + +def get_total_deposited(conn: sqlite3.Connection, + config_total: float = 0.0) -> float: + """Get total deposited capital (config seed + all detected deposits). + + config_total is the initial seed from config.yaml (first deposit). + """ + row = conn.execute("SELECT SUM(amount) as total FROM deposits").fetchone() + extra = row["total"] if row and row["total"] else 0.0 + return config_total + extra + + 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: diff --git a/src/remizov_trader/web/app.py b/src/remizov_trader/web/app.py index 3f078b4..73ffb96 100644 --- a/src/remizov_trader/web/app.py +++ b/src/remizov_trader/web/app.py @@ -41,8 +41,10 @@ def create_app(cfg: Config) -> FastAPI: if pos: positions[a["ticker"]] = dict(pos) + from ..state import get_total_deposited total_equity = sum(a["equity"] for a in assets) - total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(cfg.assets) + config_total = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(cfg.assets) + total_initial = get_total_deposited(conn, config_total) total_pnl = total_equity - total_initial total_ret = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0