- День live-торговли с 08.03.2026 - Всего сделок / WR (cumulative) - Обратный отсчёт: 50 trades (статзначимость), 90д (Sharpe), 180д (полный цикл) - Счётчик до 100 trades Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
394 lines
16 KiB
Python
394 lines
16 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 _get_exchange_balance(cfg) -> float | None:
|
|
"""Fetch total portfolio balance from exchange (mark-to-market)."""
|
|
try:
|
|
from .core.spot import SpotExecutor
|
|
spot = SpotExecutor(cfg.exchange, leverage=cfg.risk.leverage)
|
|
spot._ensure_markets()
|
|
b = spot.exchange.fetch_balance()
|
|
total = 0.0
|
|
# Build coin list from configured assets + stablecoins
|
|
coins = {"USDC", "USDT"}
|
|
for a in cfg.assets:
|
|
coins.add(a.symbol.split("/")[0])
|
|
for coin in sorted(coins):
|
|
amt = float(b.get(coin, {}).get("total", 0) or 0)
|
|
if amt < 0.0001:
|
|
continue
|
|
if coin in ("USDC", "USDT"):
|
|
total += amt
|
|
else:
|
|
price = spot.get_price(f"{coin}/USDC")
|
|
total += amt * price if price else 0
|
|
return total
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def _get_current_price(cfg, ticker):
|
|
"""Fetch current price for ticker via exchange."""
|
|
try:
|
|
# Find symbol from config
|
|
for a in cfg.assets:
|
|
if a.ticker == ticker:
|
|
from .core.signals import fetch_prices_ccxt
|
|
prices, _ = fetch_prices_ccxt(a.symbol, "4h", "1d", cfg.exchange)
|
|
if prices is not None and len(prices) > 0:
|
|
return float(prices[-1])
|
|
return None
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
def format_status_report(cfg, conn) -> str:
|
|
"""Format full status report for Telegram."""
|
|
from .state import get_asset, get_open_position
|
|
|
|
# Only show assets from current config
|
|
active_tickers = {a.ticker for a in cfg.assets}
|
|
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)
|
|
|
|
# Get real balance from exchange (mark-to-market)
|
|
exchange_balance = _get_exchange_balance(cfg)
|
|
if exchange_balance is None:
|
|
# Fallback to DB equity
|
|
exchange_balance = sum(a["equity"] for a in assets)
|
|
|
|
total_pnl = exchange_balance - total_initial
|
|
total_pct = (exchange_balance / total_initial - 1) * 100 if total_initial > 0 else 0
|
|
|
|
# Collect open positions with current prices
|
|
open_positions = []
|
|
for a in assets:
|
|
pos = get_open_position(conn, a["ticker"])
|
|
if pos:
|
|
cur_price = _get_current_price(cfg, a["ticker"])
|
|
open_positions.append((a, pos, cur_price))
|
|
|
|
S = "\u00a0" # non-breaking space for Telegram
|
|
lines = ["\U0001f4ca <b>RemizovTrader</b>", ""]
|
|
|
|
# --- Portfolio ---
|
|
lines.append("\U0001f4b0 <b>Портфель</b>")
|
|
lines.append(f"{S*3}Баланс: <b>${exchange_balance:,.2f}</b> ({total_pct:+.1f}%)")
|
|
lines.append(f"{S*3}PnL: ${total_pnl:+,.2f}")
|
|
lines.append("")
|
|
|
|
if open_positions:
|
|
lines.append(f"\U0001f4c8 <b>Позиции</b> ({len(open_positions)}/{cfg.risk.max_open_positions})")
|
|
for a, pos, cur_price in open_positions:
|
|
d = "\U0001f7e2 LONG" if pos["direction"] == 1 else "\U0001f534 SHORT"
|
|
ac = next((x for x in cfg.assets if x.ticker == a["ticker"]), None)
|
|
_tf = (ac.timeframe if ac and ac.timeframe else cfg.timeframe)
|
|
lev = cfg.leverage_for(ac) if ac else cfg.risk.leverage
|
|
entry = pos["entry_price"]
|
|
stop = pos["stop_price"]
|
|
size = pos["pos_value"]
|
|
pos_size = pos["pos_size"]
|
|
risk_pct = abs(entry - stop) / entry * 100
|
|
|
|
pnl_str = ""
|
|
if cur_price:
|
|
upnl = pos_size * (cur_price - entry) * pos["direction"]
|
|
upnl_pct = (cur_price / entry - 1) * 100 * pos["direction"]
|
|
pnl_icon = "\U0001f7e2" if upnl >= 0 else "\U0001f534"
|
|
pnl_str = f"\n{S*6}{pnl_icon} PnL: ${upnl:+,.2f} ({upnl_pct:+.1f}%) @ ${cur_price:,.2f}"
|
|
|
|
lines.append("")
|
|
lines.append(f"{S*3}<b>{a['ticker']}</b> {_tf} {lev}x")
|
|
lines.append(f"{S*6}{d} @ ${entry:,.2f}")
|
|
lines.append(f"{S*6}Стоп: ${stop:,.2f} ({risk_pct:.1f}%) | ${size:,.2f}{pnl_str}")
|
|
else:
|
|
lines.append("\U0001f4c8 <b>Позиции:</b> нет")
|
|
lines.append("")
|
|
|
|
# --- Stats per asset ---
|
|
lines.append("\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 ""
|
|
ac = next((x for x in cfg.assets if x.ticker == a["ticker"]), None)
|
|
if ac:
|
|
_tf = ac.timeframe or cfg.timeframe
|
|
lev = cfg.leverage_for(ac)
|
|
ws = ac.window_size or cfg.model.window_size
|
|
w_pct = f"{ac.weight*100:.0f}%" if ac.weight > 0 else ""
|
|
extra = f" | {_tf} ws={ws} {lev}x {w_pct}"
|
|
else:
|
|
extra = ""
|
|
lines.append(f"{S*3}{a['ticker']}: {trades} сд. WR {wr:.0f}%{extra}{cb}")
|
|
lines.append("")
|
|
|
|
# --- Settings ---
|
|
lines.append("\u2699\ufe0f <b>Настройки</b>")
|
|
tfs = sorted(set(a.timeframe or cfg.timeframe for a in cfg.assets))
|
|
lines.append(f"{S*3}{cfg.mode} | TF: {'/'.join(tfs)} | "
|
|
f"риск {cfg.risk.per_trade*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_asset, get_open_position
|
|
|
|
active_tickers = {a.ticker for a in cfg.assets}
|
|
assets = [get_asset(conn, t) for t in active_tickers]
|
|
assets = [a for a in assets if a is not None]
|
|
open_count = sum(1 for a in assets if get_open_position(conn, a["ticker"]))
|
|
total_trades = sum(a["trades_count"] for a in assets)
|
|
|
|
exchange_balance = _get_exchange_balance(cfg)
|
|
if exchange_balance is None:
|
|
exchange_balance = sum(a["equity"] for a in assets)
|
|
|
|
lines = [
|
|
f"Сервер: <code>{platform.node()}</code>",
|
|
f"Режим: {cfg.mode} | TF: {'/'.join(sorted(set(a.timeframe or cfg.timeframe for a in cfg.assets)))}",
|
|
f"Активов: {len(cfg.assets)} | Позиций: {open_count}/{cfg.risk.max_open_positions}",
|
|
f"Капитал: ${exchange_balance:,.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("&", "&").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 (mark-to-market)
|
|
exchange_balance = _get_exchange_balance(cfg)
|
|
if exchange_balance is None:
|
|
# Fallback: last known exchange balance from snapshots
|
|
snap = conn.execute(
|
|
"SELECT exchange_balance FROM balance_snapshots "
|
|
"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)
|
|
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', 'phantom_cleanup', 'portfolio_rebalance') "
|
|
"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")
|
|
|
|
# --- Validation milestones ---
|
|
from datetime import date
|
|
LIVE_START = date(2026, 3, 8)
|
|
today = now.date()
|
|
live_days = (today - LIVE_START).days
|
|
|
|
# Total real trades (excluding failures/resets)
|
|
total_real = conn.execute(
|
|
"SELECT COUNT(*) as cnt, SUM(CASE WHEN pnl_net > 0 THEN 1 ELSE 0 END) as wins "
|
|
"FROM positions WHERE status='closed' "
|
|
"AND exit_reason NOT IN ('live_buy_failed', 'manual_reset', 'phantom_cleanup', 'portfolio_rebalance')"
|
|
).fetchone()
|
|
total_trades = total_real["cnt"] if total_real else 0
|
|
total_wins = total_real["wins"] if total_real else 0
|
|
live_wr = total_wins / total_trades * 100 if total_trades > 0 else 0
|
|
|
|
lines.append("")
|
|
lines.append(f"\U0001f3af <b>Валидация</b> (день {live_days})")
|
|
lines.append(f"{S*3}Всего сделок: {total_trades} | WR: {live_wr:.0f}%")
|
|
|
|
# Milestones
|
|
milestones = [
|
|
(50, "статзначимость (50 trades)"),
|
|
(90, "Sharpe из live (3 мес)"),
|
|
(180, "полный цикл рынка (6 мес)"),
|
|
]
|
|
for target_days, label in milestones:
|
|
remaining = target_days - live_days
|
|
if remaining > 0:
|
|
target_date = LIVE_START + timedelta(days=target_days)
|
|
lines.append(f"{S*3}\u23f3 {label}: {remaining}д ({target_date.strftime('%d.%m')})")
|
|
else:
|
|
lines.append(f"{S*3}\u2705 {label}: ГОТОВО")
|
|
|
|
# Trade milestone
|
|
trades_remaining = max(0, 100 - total_trades)
|
|
if trades_remaining > 0:
|
|
lines.append(f"{S*3}\u23f3 100 trades: ещё {trades_remaining}")
|
|
else:
|
|
lines.append(f"{S*3}\u2705 100 trades: ГОТОВО")
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
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)
|