feat: ежедневный утренний отчёт в Telegram (00:00 UTC / 10:00 AEST)

- 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 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-10 13:32:25 +10:00
co-authored by Claude Opus 4.6
parent 166e22ae92
commit e4b1587375
2 changed files with 126 additions and 1 deletions
+14 -1
View File
@@ -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.")
+112
View File
@@ -215,6 +215,118 @@ def _escape_html(text: str) -> str:
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
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 <b>Утренний отчёт RemizovTrader</b>", ""]
# --- Balance ---
lines.append(f"\U0001f4b0 <b>Баланс: ${exchange_balance:,.2f}</b> ({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 <b>Открытые позиции ({len(open_positions)})</b>")
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"<b>${upnl:+,.2f}</b> ({upnl_pct:+.1f}%)")
lines.append(f"{S*3}Unrealized: <b>${total_unrealized:+,.2f}</b>")
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 <b>Сделки за 24ч ({len(rows)})</b>")
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"<b>${pnl:+,.2f}</b>")
wr = wins / len(rows) * 100 if rows else 0
lines.append(f"{S*3}Realized: <b>${realized:+,.2f}</b> | 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} <b>Net PnL: ${net:+,.2f}</b> (realized ${realized:+,.2f} + unrealized ${total_unrealized:+,.2f})")
lines.append("")
# --- Per-asset summary ---
lines.append("\U0001f4ca <b>Активы</b>")
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: