- AssetConfig: +window_size, +weight, +leverage fields - Config: +model_for(), +leverage_for() helpers - executor: weight-based position sizing (equity × weight × leverage) - cli init: per-asset window_size for model training - notify: show ws/lev/weight% in Telegram stats - config.yaml: Sharpe-optimal params (exp15 grid search) BTC ws=32 24.1%, ETH ws=64 15.8%, ADA ws=64 13.7%, DOT ws=32 13.7%, DOGE ws=48 12.7%, SOL ws=128 10.8%, XRP ws=64 9.2% Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
241 lines
8.9 KiB
Python
241 lines
8.9 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))
|
|
|
|
lines = ["\U0001f4ca <b>RemizovTrader</b>"]
|
|
lines.append("")
|
|
|
|
# --- Portfolio ---
|
|
lines.append(f"\U0001f4b0 <b>Портфель</b>")
|
|
lines.append(f" Баланс: <b>${exchange_balance:,.2f}</b> ({total_pct:+.1f}%)")
|
|
lines.append(f" 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"
|
|
# Find per-asset timeframe
|
|
_tf = cfg.timeframe
|
|
for ac in cfg.assets:
|
|
if ac.ticker == a["ticker"]:
|
|
_tf = ac.timeframe or cfg.timeframe
|
|
break
|
|
entry = pos["entry_price"]
|
|
stop = pos["stop_price"]
|
|
size = pos["pos_value"]
|
|
pos_size = pos["pos_size"]
|
|
risk_pct = abs(entry - stop) / entry * 100
|
|
|
|
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 {pnl_icon} PnL: ${upnl:+,.2f} ({upnl_pct:+.1f}%) @ ${cur_price:,.2f}"
|
|
else:
|
|
pnl_str = ""
|
|
|
|
lines.append(f" {a['ticker']} ({_tf}): {d}")
|
|
lines.append(f" Вход: ${entry:,.2f} | Стоп: ${stop:,.2f} ({risk_pct:.1f}%)")
|
|
lines.append(f" Размер: ${size:,.2f}{pnl_str}")
|
|
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 ""
|
|
# Show per-asset weight/ws if configured
|
|
ac = next((x for x in cfg.assets if x.ticker == a["ticker"]), None)
|
|
extra = ""
|
|
if ac and ac.weight > 0:
|
|
lev = cfg.leverage_for(ac)
|
|
ws = ac.window_size or cfg.model.window_size
|
|
extra = f" | ws={ws} {lev}x {ac.weight*100:.0f}%"
|
|
lines.append(f" {a['ticker']}: {trades} сделок, WR {wr:.0f}%{extra}{cb}")
|
|
lines.append("")
|
|
|
|
# --- Settings ---
|
|
lines.append(f"\u2699\ufe0f <b>Настройки</b>")
|
|
tfs = sorted(set(a.timeframe or cfg.timeframe for a in cfg.assets))
|
|
tf_str = "/".join(tfs)
|
|
lines.append(f" {cfg.mode} | TF: {tf_str} | "
|
|
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_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_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)
|