feat: автоматическое обнаружение депозитов/выводов

- Таблица deposits в БД для хранения истории пополнений
- detect_deposit(): сравнивает баланс с предыдущим снимком + realized PnL,
  порог $10 для фильтрации шума от unrealized изменений
- get_total_deposited(): config.total + сумма депозитов из БД
- Все отчёты (Telegram, web, CLI) теперь считают % от реального депо
- При обнаружении депозита — запись в лог и Telegram

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-10 19:30:10 +10:00
co-authored by Claude Opus 4.6
parent 295dbc043d
commit 0fc318dec2
5 changed files with 91 additions and 7 deletions
+3 -1
View File
@@ -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)
+24 -2
View File
@@ -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
+7 -3
View File
@@ -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 <b>Утренний отчёт RemizovTrader</b>", ""]
@@ -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 = []
+54
View File
@@ -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:
+3 -1
View File
@@ -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