From e4b1587375136e8db99ad94783540dcbf086be4a Mon Sep 17 00:00:00 2001 From: anor Date: Tue, 10 Mar 2026 13:32:25 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=B5=D0=B6=D0=B5=D0=B4=D0=BD=D0=B5?= =?UTF-8?q?=D0=B2=D0=BD=D1=8B=D0=B9=20=D1=83=D1=82=D1=80=D0=B5=D0=BD=D0=BD?= =?UTF-8?q?=D0=B8=D0=B9=20=D0=BE=D1=82=D1=87=D1=91=D1=82=20=D0=B2=20Telegr?= =?UTF-8?q?am=20(00:00=20UTC=20/=2010:00=20AEST)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - format_morning_report: баланс, открытые позиции с unrealized PnL, закрытые сделки за 24ч, net PnL, статистика по активам, циклы - scheduler job в cli.py daemon - Фильтрует live_buy_failed и manual_reset из отчёта Co-Authored-By: Claude Opus 4.6 --- src/remizov_trader/cli.py | 15 ++++- src/remizov_trader/notify.py | 112 +++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 1 deletion(-) diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 595e14e..87eb25a 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -189,7 +189,8 @@ def daemon(): from apscheduler.schedulers.background import BackgroundScheduler from .core.executor import run_cycle - from .notify import (format_cycle_report, format_startup_details, + from .notify import (format_cycle_report, format_morning_report, + format_startup_details, format_status_report, send_status, send_telegram) from .web.app import create_app @@ -241,6 +242,18 @@ def daemon(): scheduler.add_job(scheduled_cycle, "cron", hour=cron_hours, minute=5) click.echo(f"Scheduled: every {min_hours}h at :05 UTC (hours: {cron_hours})") + # Morning report at 00:00 UTC (10:00 AEST) + if cfg.telegram.enabled: + def morning_report(): + c = get_db() + init_db(c) + report = format_morning_report(cfg, c) + c.close() + send_telegram(cfg.telegram, report) + + scheduler.add_job(morning_report, "cron", hour=0, minute=0) + click.echo("Morning report scheduled: daily at 00:00 UTC (10:00 AEST)") + scheduler.start() click.echo("Daemon started. Web dashboard + scheduler running.") diff --git a/src/remizov_trader/notify.py b/src/remizov_trader/notify.py index 546439c..7eb000b 100644 --- a/src/remizov_trader/notify.py +++ b/src/remizov_trader/notify.py @@ -215,6 +215,118 @@ def _escape_html(text: str) -> str: return text.replace("&", "&").replace("<", "<").replace(">", ">") +def format_morning_report(cfg, conn) -> str: + """Format daily morning trading summary for Telegram.""" + from datetime import datetime, timedelta, timezone + from .state import get_all_assets, get_open_position + + S = "\u00a0" + now = datetime.now(timezone.utc) + since = (now - timedelta(hours=24)).isoformat() + + # Active assets from config + active_tickers = {a.ticker for a in cfg.assets} + assets = [a for a in get_all_assets(conn) if a["ticker"] in active_tickers] + + # Exchange balance + exchange_balance = _get_exchange_balance(cfg) + if exchange_balance is None: + exchange_balance = sum(a["equity"] for a in assets) + total_initial = cfg.total_capital if cfg.total_capital > 0 else cfg.initial_capital * len(assets) + total_pct = (exchange_balance / total_initial - 1) * 100 if total_initial > 0 else 0 + + lines = ["\u2600\ufe0f Утренний отчёт RemizovTrader", ""] + + # --- Balance --- + lines.append(f"\U0001f4b0 Баланс: ${exchange_balance:,.2f} ({total_pct:+.1f}%)") + lines.append("") + + # --- Open positions with unrealized PnL --- + open_positions = [] + total_unrealized = 0.0 + for a in assets: + pos = get_open_position(conn, a["ticker"]) + if pos: + cur_price = _get_current_price(cfg, a["ticker"]) + upnl = 0.0 + if cur_price: + upnl = pos["pos_size"] * (cur_price - pos["entry_price"]) * pos["direction"] + open_positions.append((a, pos, cur_price, upnl)) + total_unrealized += upnl + + if open_positions: + lines.append(f"\U0001f4c8 Открытые позиции ({len(open_positions)})") + for a, pos, cur_price, upnl in open_positions: + d = "L" if pos["direction"] == 1 else "S" + price_str = f"${cur_price:,.2f}" if cur_price else "?" + upnl_pct = ((cur_price / pos["entry_price"] - 1) * 100 * pos["direction"]) if cur_price else 0 + icon = "\U0001f7e2" if upnl >= 0 else "\U0001f534" + lines.append(f"{S*3}{icon} {a['ticker']} {d} ${pos['entry_price']:,.2f}\u2192{price_str} " + f"${upnl:+,.2f} ({upnl_pct:+.1f}%)") + lines.append(f"{S*3}Unrealized: ${total_unrealized:+,.2f}") + else: + lines.append("\U0001f4c8 Нет открытых позиций") + lines.append("") + + # --- Closed trades last 24h --- + rows = conn.execute( + "SELECT ticker, direction, entry_price, exit_price, exit_reason, pnl_net, pnl_pct " + "FROM positions WHERE status='closed' AND exit_date >= ? " + "AND exit_reason NOT IN ('live_buy_failed', 'manual_reset') " + "ORDER BY id DESC", (since[:10],) + ).fetchall() + + realized = 0.0 + wins = 0 + if rows: + lines.append(f"\U0001f4dd Сделки за 24ч ({len(rows)})") + for r in rows: + d = "L" if r["direction"] == 1 else "S" + pnl = r["pnl_net"] or 0 + realized += pnl + if pnl > 0: + wins += 1 + icon = "\U0001f7e2" if pnl >= 0 else "\U0001f534" + lines.append(f"{S*3}{icon} {r['ticker']} {d} ${r['entry_price']:,.2f}\u2192" + f"${r['exit_price']:,.2f} ({r['exit_reason']}) " + f"${pnl:+,.2f}") + wr = wins / len(rows) * 100 if rows else 0 + lines.append(f"{S*3}Realized: ${realized:+,.2f} | WR: {wr:.0f}%") + else: + lines.append("\U0001f4dd Нет закрытых сделок за 24ч") + lines.append("") + + # --- Net PnL --- + net = realized + total_unrealized + net_icon = "\U0001f7e2" if net >= 0 else "\U0001f534" + lines.append(f"{net_icon} Net PnL: ${net:+,.2f} (realized ${realized:+,.2f} + unrealized ${total_unrealized:+,.2f})") + lines.append("") + + # --- Per-asset summary --- + lines.append("\U0001f4ca Активы") + for a in sorted(assets, key=lambda x: x["ticker"]): + tc = a["trades_count"] + wr = a["wins"] / tc * 100 if tc > 0 else 0 + pnl = a["total_pnl"] or 0 + status = "" + pos = get_open_position(conn, a["ticker"]) + if pos: + status = " \U0001f7e2" if pos["direction"] == 1 else " \U0001f534" + lines.append(f"{S*3}{a['ticker']}{status}: {tc}сд WR{wr:.0f}% PnL${pnl:+,.2f}") + + # --- Cycles --- + cycle_rows = conn.execute( + "SELECT COUNT(*) as cnt, AVG(duration_sec) as avg_dur " + "FROM cycle_log WHERE started_at >= ?", (since,) + ).fetchone() + if cycle_rows and cycle_rows["cnt"] > 0: + lines.append("") + lines.append(f"\u2699\ufe0f Циклов: {cycle_rows['cnt']} | " + f"Avg: {cycle_rows['avg_dur']:.1f}s") + + return "\n".join(lines) + + def format_cycle_report(logs: list[str]) -> str: """Format cycle logs into a Telegram message.""" if not logs: