Coverage for notifications/telegram_alerts.py: 100%
28 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Pure Telegram alert gating + formatting (Phase V2-19).
3Mirrors experience/observation_metrics.py's and performance/triggers.py's
4design: every function here operates on plain dicts already produced
5elsewhere (a performance_triggers row from performance/postgres_triggers.py,
6or a session_summary event from experience/redis_queue.py's
7build_session_summary_event()) — nothing here recomputes a metric, it only
8decides whether to alert and how to render the message. No Postgres/Telegram/
9network dependency lives here; see notifications/postgres_telegram.py for the
10I/O layer and notifications/telegram_client.py for the outbound HTTP call.
11"""
13from __future__ import annotations
15from typing import Any
17SEVERITY_EMOJI = {"info": "ℹ️", "warning": "⚠️", "critical": "\U0001f6a8"}
18_SEVERITY_RANK = {"info": 0, "warning": 1, "critical": 2}
21def should_alert_trigger(trigger: dict[str, Any], min_severity: str = "warning") -> bool:
22 """True if trigger["severity"] clears min_severity (info < warning < critical)."""
23 trigger_rank = _SEVERITY_RANK.get(trigger.get("severity"), 0)
24 threshold_rank = _SEVERITY_RANK.get(min_severity, 1)
25 return trigger_rank >= threshold_rank
28def format_trigger_alert(trigger: dict[str, Any]) -> str:
29 """Render a performance_triggers row as a Telegram message.
31 Renders fields performance/triggers.py already computed (message,
32 recommended_action) — recomputes nothing.
33 """
34 emoji = SEVERITY_EMOJI.get(trigger.get("severity"), "")
35 lines = [
36 f"{emoji} {trigger.get('trigger_type', 'trigger')} ({trigger.get('severity', 'unknown')})",
37 trigger.get("message", ""),
38 f"Scope: {trigger.get('scope', 'portfolio')} | Mode: {trigger.get('mode', 'unknown')}",
39 f"Recommended action: {trigger.get('recommended_action', 'none')}",
40 ]
41 return "\n".join(line for line in lines if line)
44def _num(value, default: float = 0.0) -> float:
45 """V5.4.7 (development/Problems.md #124): an explicit JSONB null (a
46 key PRESENT with value None) previously crashed every f-string format
47 below - `.get(key, default)` only covers a MISSING key - and the
48 worker's frozen watermark then refetched the poison row forever,
49 permanently blocking ALL alerts. Coerce anything non-numeric to the
50 default instead."""
51 if value is None:
52 return default
53 try:
54 return float(value)
55 except (TypeError, ValueError):
56 return default
59def format_session_summary_alert(session_summary_event: dict[str, Any]) -> str:
60 """Render a session_summary experience event as a Telegram digest.
62 Reads the observation_summary sub-dict produced by
63 experience/observation_metrics.py::compute_observation_summary() —
64 recomputes nothing.
65 """
66 summary = session_summary_event.get("observation_summary") or {}
67 win_loss = summary.get("simulated_win_loss") or {}
68 session_return = _num(session_summary_event.get("session_return"))
69 win_rate = _num(win_loss.get("win_rate"))
70 simulated_sharpe = _num(summary.get("simulated_sharpe"))
71 simulated_max_drawdown = _num(summary.get("simulated_max_drawdown"))
73 lines = [
74 f"\U0001f4ca Session summary — {session_summary_event.get('session_date', 'unknown date')}",
75 f"Mode: {session_summary_event.get('mode', 'unknown')}",
76 f"Equity: {_num(session_summary_event.get('session_start_equity')):,.2f} -> "
77 f"{_num(session_summary_event.get('session_end_equity')):,.2f} ({session_return:+.2%})",
78 f"Observations: {_num(summary.get('count_observations')):.0f}",
79 f"Simulated win/loss: {_num(win_loss.get('wins')):.0f}/{_num(win_loss.get('losses')):.0f} "
80 f"(win rate {win_rate:.1%})",
81 f"Simulated Sharpe: {simulated_sharpe:.2f}",
82 f"Simulated max drawdown: {simulated_max_drawdown:.2%}",
83 ]
84 return "\n".join(lines)