Files
remizov-trader/src/remizov_trader/notify.py
T
anorandClaude Opus 4.6 7cd49f2af6 fix: экранировать HTML в Telegram уведомлениях цикла
Символы < > в сообщениях (например corr=-1.000 < 0.50)
ломали HTML-парсинг Telegram API.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 12:16:22 +10:00

159 lines
5.7 KiB
Python

"""Telegram notifications — send trade alerts."""
from __future__ import annotations
import logging
import httpx
from .config import TelegramConfig
log = logging.getLogger(__name__)
def send_telegram(cfg: TelegramConfig, message: str) -> bool:
"""Send message via Telegram bot API. Returns True on success."""
if not cfg.enabled or not cfg.bot_token or not cfg.chat_id:
return False
url = f"https://api.telegram.org/bot{cfg.bot_token}/sendMessage"
try:
resp = httpx.post(url, json={
"chat_id": cfg.chat_id,
"text": message,
"parse_mode": "HTML",
}, timeout=10)
if resp.status_code != 200:
log.warning("Telegram API error: %s", resp.text)
return False
return True
except httpx.HTTPError as e:
log.warning("Telegram send failed: %s", e)
return False
def send_status(cfg: TelegramConfig, event: str, details: str = "") -> bool:
"""Send bot status notification (start, stop, restart, error)."""
labels = {
"start": ("\u2705", "ЗАПУЩЕН"),
"restart": ("\U0001f504", "ПЕРЕЗАПУЩЕН"),
"stop": ("\u26d4", "ОСТАНОВЛЕН"),
"error": ("\u26a0\ufe0f", "ОШИБКА"),
"crash": ("\U0001f4a5", "СБОЙ"),
}
icon, label = labels.get(event, ("\u2139\ufe0f", event.upper()))
msg = f"{icon} <b>RemizovTrader — {label}</b>"
if details:
msg += f"\n{details}"
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
assets = get_all_assets(conn)
total_equity = sum(a["equity"] for a in assets)
total_initial = cfg.initial_capital * len(assets) if assets else cfg.initial_capital
total_pnl = total_equity - total_initial
total_pct = (total_equity / total_initial - 1) * 100 if total_initial > 0 else 0
lines = ["\U0001f4ca <b>RemizovTrader</b>"]
lines.append("")
# --- Portfolio ---
lines.append(f"\U0001f4b0 <b>Портфель</b>")
lines.append(f" Капитал: <b>${total_equity:,.2f}</b> ({total_pct:+.1f}%)")
lines.append(f" PnL: ${total_pnl:+,.2f}")
lines.append("")
# --- Open positions ---
open_positions = []
for a in assets:
pos = get_open_position(conn, a["ticker"])
if pos:
open_positions.append((a, pos))
if open_positions:
lines.append(f"\U0001f4c8 <b>Позиции</b> ({len(open_positions)}/{cfg.risk.max_open_positions})")
for a, pos in open_positions:
d = "\U0001f7e2 LONG" if pos["direction"] == 1 else "\U0001f534 SHORT"
entry = pos["entry_price"]
stop = pos["stop_price"]
size = pos["pos_value"]
risk_pct = abs(entry - stop) / entry * 100
lines.append(f" {a['ticker']}: {d}")
lines.append(f" Вход: ${entry:,.2f} | Стоп: ${stop:,.2f} ({risk_pct:.1f}%)")
lines.append(f" Размер: ${size:,.2f}")
else:
lines.append(f"\U0001f4c8 <b>Позиции:</b> нет")
lines.append("")
# --- Stats per asset ---
lines.append(f"\U0001f4ca <b>Статистика</b>")
for a in assets:
trades = a["trades_count"]
wr = a["wins"] / trades * 100 if trades > 0 else 0
cb = " \u26a0\ufe0f CB" if a["cb_active"] else ""
lines.append(f" {a['ticker']}: {trades} сделок, WR {wr:.0f}%{cb}")
lines.append("")
# --- Settings ---
lines.append(f"\u2699\ufe0f <b>Настройки</b>")
lines.append(f" {cfg.mode} | {cfg.timeframe} | "
f"риск {cfg.risk.per_trade*100:.0f}% | "
f"макс {cfg.risk.max_position_pct*100:.0f}%")
if cfg.risk.leverage > 1:
lines.append(f" Плечо: {cfg.risk.leverage}x")
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"Сервер: <code>{platform.node()}</code>",
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"Плечо: {cfg.risk.leverage}x",
f"CB: ATR>{cfg.circuit_breaker.atr_ratio_on}x | DD>{cfg.circuit_breaker.max_drawdown*100:.0f}%",
]
return "\n".join(lines)
def _escape_html(text: str) -> str:
"""Escape HTML special characters for Telegram."""
return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def format_cycle_report(logs: list[str]) -> str:
"""Format cycle logs into a Telegram message."""
if not logs:
return "<b>RemizovTrader</b>\nЦикл завершён — без активности."
lines = ["<b>RemizovTrader</b>"]
for msg in logs:
safe = _escape_html(msg)
if "SIGNAL" in msg or "CLOSED" in msg:
lines.append(f" {safe}")
elif "CB ON" in msg:
lines.append(f" {safe}")
elif "retrained" in msg:
lines.append(f" {safe}")
else:
lines.append(f" <i>{safe}</i>")
return "\n".join(lines)