diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 2378220..28c62ad 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -184,21 +184,26 @@ def daemon(): """Run as daemon — auto-cycle on schedule + web dashboard.""" from apscheduler.schedulers.background import BackgroundScheduler - import platform - from .core.executor import run_cycle - from .notify import format_cycle_report, send_status, send_telegram + from .notify import (format_cycle_report, format_startup_details, + format_status_report, send_status, send_telegram) from .web.app import create_app cfg = load_config() + conn = get_db() + init_db(conn) - # Notify: bot started + # Notify: bot started with full details if cfg.telegram.enabled: - info = (f"Сервер: {platform.node()}\n" - f"Таймфрейм: {cfg.timeframe}, Активов: {len(cfg.assets)}\n" - f"Режим: {cfg.mode}") + info = format_startup_details(cfg, conn) send_status(cfg.telegram, "start", info) + # Start Telegram command listener (non-blocking) + if cfg.telegram.enabled: + _start_telegram_listener(cfg, get_db) + + conn.close() + def scheduled_cycle(): conn = get_db() init_db(conn) @@ -242,6 +247,44 @@ def daemon(): send_status(cfg.telegram, "stop") +def _start_telegram_listener(cfg, get_db_fn): + """Poll Telegram for /status command in a background thread.""" + import threading + import time + + import httpx + + from .notify import format_status_report, send_telegram + + def poll_loop(): + offset = 0 + url = f"https://api.telegram.org/bot{cfg.telegram.bot_token}/getUpdates" + while True: + try: + resp = httpx.get(url, params={"offset": offset, "timeout": 30}, timeout=35) + if resp.status_code != 200: + time.sleep(5) + continue + updates = resp.json().get("result", []) + for upd in updates: + offset = upd["update_id"] + 1 + msg = upd.get("message", {}) + text = msg.get("text", "") + chat_id = str(msg.get("chat", {}).get("id", "")) + if chat_id != cfg.telegram.chat_id: + continue + if text.strip() == "/status": + conn = get_db_fn() + report = format_status_report(cfg, conn) + conn.close() + send_telegram(cfg.telegram, report) + except Exception: + time.sleep(10) + + t = threading.Thread(target=poll_loop, daemon=True) + t.start() + + @main.command() @click.argument("key") @click.argument("value") diff --git a/src/remizov_trader/notify.py b/src/remizov_trader/notify.py index 2a00aa8..6a00fb3 100644 --- a/src/remizov_trader/notify.py +++ b/src/remizov_trader/notify.py @@ -48,6 +48,77 @@ def send_status(cfg: TelegramConfig, event: str, details: str = "") -> bool: return send_telegram(cfg, msg) +def format_status_report(cfg, conn) -> str: + """Format full status report for Telegram.""" + from .state import get_all_assets, get_open_position + + lines = ["\U0001f4ca RemizovTrader — СТАТУС", ""] + + assets = get_all_assets(conn) + total_equity = 0.0 + total_initial = 0.0 + open_positions = [] + + for a in assets: + total_equity += a["equity"] + total_initial += cfg.initial_capital + pos = get_open_position(conn, a["ticker"]) + if pos: + d = "LONG" if pos["direction"] == 1 else "SHORT" + open_positions.append(f" {a['ticker']}: {d} @ ${pos['entry_price']:,.2f}") + + total_pnl = total_equity - total_initial + total_pct = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0 + + lines.append(f"Капитал: ${total_equity:,.2f} ({total_pct:+.1f}%)") + lines.append(f"PnL: ${total_pnl:+,.2f}") + lines.append("") + + if open_positions: + lines.append(f"Открытые позиции ({len(open_positions)}/{cfg.risk.max_open_positions}):") + lines.extend(open_positions) + else: + lines.append(f"Открытые позиции: 0/{cfg.risk.max_open_positions}") + + lines.append("") + lines.append("Активы:") + for a in assets: + wr = a["wins"] / a["trades_count"] * 100 if a["trades_count"] > 0 else 0 + cb = " [CB]" if a["cb_active"] else "" + lines.append(f" {a['ticker']}: ${a['equity']:,.2f} | " + f"{a['trades_count']} сделок, WR {wr:.0f}%{cb}") + + lines.append("") + lines.append(f"Режим: {cfg.mode} | TF: {cfg.timeframe}") + lines.append(f"Риск: {cfg.risk.per_trade*100:.0f}% | " + f"Макс. позиция: {cfg.risk.max_position_pct*100:.0f}%") + + return "\n".join(lines) + + +def format_startup_details(cfg, conn) -> str: + """Format startup message with key parameters.""" + import platform + from .state import get_all_assets, get_open_position + + assets = get_all_assets(conn) + open_count = sum(1 for a in assets if get_open_position(conn, a["ticker"])) + total_equity = sum(a["equity"] for a in assets) + total_trades = sum(a["trades_count"] for a in assets) + + lines = [ + f"Сервер: {platform.node()}", + f"Режим: {cfg.mode} | TF: {cfg.timeframe}", + f"Активов: {len(cfg.assets)} | Позиций: {open_count}/{cfg.risk.max_open_positions}", + f"Капитал: ${total_equity:,.2f} | Сделок: {total_trades}", + "", + f"Риск/сделка: {cfg.risk.per_trade*100:.0f}%", + f"Макс. позиция: {cfg.risk.max_position_pct*100:.0f}% от equity", + f"CB: ATR>{cfg.circuit_breaker.atr_ratio_on}x | DD>{cfg.circuit_breaker.max_drawdown*100:.0f}%", + ] + return "\n".join(lines) + + def format_cycle_report(logs: list[str]) -> str: """Format cycle logs into a Telegram message.""" if not logs: