Skip to main content

schwab_cli/agent/
telegram_format.rs

1//! Plain-language Telegram messages (no raw JSON).
2
3use chrono::{DateTime, Utc};
4use serde_json::Value;
5
6use crate::agent::llm::{LlmReview, PositionReview};
7use crate::agent::state::AgentState;
8use crate::rules::TelegramNotifyConfig;
9
10/// Fingerprint for deduplicating routine LLM Telegram updates.
11pub fn llm_digest_key(review: &LlmReview) -> String {
12    let pos = review
13        .position_reviews
14        .first()
15        .map(|p| {
16            format!(
17                "{}:{}:{}",
18                short_position_label(&p.position_id),
19                p.recommendation.to_lowercase(),
20                p.urgency.to_lowercase()
21            )
22        })
23        .unwrap_or_else(|| "none".into());
24    format!(
25        "{}|{}|{}",
26        review.phase,
27        review.entry_recommendation.to_lowercase(),
28        pos
29    )
30}
31
32pub fn is_llm_urgent(review: &LlmReview) -> bool {
33    review.entry_recommendation.eq_ignore_ascii_case("proceed")
34        || !review.urgent_close_positions().is_empty()
35        || review
36            .position_reviews
37            .iter()
38            .any(|p| p.urgency.eq_ignore_ascii_case("high"))
39}
40
41/// Whether to send an LLM review to Telegram (urgent immediately; routine on digest cadence).
42pub fn should_send_llm_telegram(
43    review: &LlmReview,
44    config: &TelegramNotifyConfig,
45    state: &AgentState,
46    now: DateTime<Utc>,
47) -> bool {
48    let key = llm_digest_key(review);
49
50    if is_llm_urgent(review) {
51        if !config.llm_notify_urgent {
52            return false;
53        }
54        if state.last_telegram_llm_digest_key.as_deref() == Some(key.as_str()) {
55            if let Some(at) = state.last_telegram_llm_at {
56                if (now - at).num_minutes() < config.llm_urgent_cooldown_minutes as i64 {
57                    return false;
58                }
59            }
60        }
61        return true;
62    }
63
64    if !config.llm_notify_digest || config.llm_digest_interval_minutes == 0 {
65        return false;
66    }
67    if state.last_telegram_llm_digest_key.as_deref() == Some(key.as_str()) {
68        return false;
69    }
70    if let Some(at) = state.last_telegram_llm_at {
71        if (now - at).num_minutes() < config.llm_digest_interval_minutes as i64 {
72            return false;
73        }
74    }
75    true
76}
77
78pub fn record_llm_telegram_sent(state: &mut AgentState, review: &LlmReview, now: DateTime<Utc>) {
79    state.last_telegram_llm_at = Some(now);
80    state.last_telegram_llm_digest_key = Some(llm_digest_key(review));
81}
82
83/// Broker-style status update from an LLM review.
84pub fn format_llm_review_telegram(review: &LlmReview, monitored: &[Value]) -> String {
85    let mut out = String::new();
86
87    let headline = match review.phase.as_str() {
88        "overnight_digest" => "Overnight check-in",
89        "selection" => "Options update",
90        _ => "Position check-in",
91    };
92    out.push_str(headline);
93    out.push_str("\n\n");
94
95    if let Some(snapshot) = monitored.first() {
96        out.push_str(&format_position_snapshot(snapshot));
97        out.push('\n');
98    }
99
100    for pos in &review.position_reviews {
101        out.push_str(&format_position_advice(pos));
102        out.push('\n');
103    }
104
105    out.push_str(&format_entry_advice(review));
106    out.push_str("\n\n");
107    out.push_str(&format_what_to_do(review));
108    out
109}
110
111pub fn format_overnight_telegram(review: &LlmReview) -> String {
112    let mut msg = format_llm_review_telegram(review, &[]);
113    if !review.risk_alerts.is_empty() {
114        msg.push_str("\n\nWatch overnight:");
115        for alert in &review.risk_alerts {
116            msg.push_str("\n• ");
117            msg.push_str(&plain_sentence(alert, 220));
118        }
119    }
120    msg
121}
122
123pub fn format_market_open_telegram(playbook: Option<&Value>, open_position_count: usize) -> String {
124    let Some(pb) = playbook else {
125        return if open_position_count > 0 {
126            format!(
127                "Market is open. Mechanical exits active on {open_position_count} open position(s)."
128            )
129        } else {
130            "Market is open. Scanning for entries.".into()
131        };
132    };
133    let mut out = "Market is open.\n\n".to_string();
134    if let Some(positions) = pb.get("positions").and_then(|v| v.as_array()) {
135        for pos in positions {
136            let id = pos
137                .get("position_id")
138                .and_then(|v| v.as_str())
139                .unwrap_or("position");
140            let rec = pos
141                .get("recommendation")
142                .and_then(|v| v.as_str())
143                .unwrap_or("watch");
144            out.push_str(&format!(
145                "Overnight note for {}: {}.\n",
146                short_position_label(id),
147                plain_rec_label(rec)
148            ));
149        }
150    }
151    if let Some(alerts) = pb.get("risk_alerts").and_then(|v| v.as_array()) {
152        if !alerts.is_empty() {
153            out.push_str("\nHeads up at the open:\n");
154            for alert in alerts.iter().take(3) {
155                if let Some(s) = alert.as_str() {
156                    out.push_str("• ");
157                    out.push_str(&plain_sentence(s, 200));
158                    out.push('\n');
159                }
160            }
161        }
162    }
163    out.trim_end().to_string()
164}
165
166/// Returns `None` when the action should not be pushed to Telegram (internal/skip).
167pub fn format_action_telegram(kind: &str, detail: &Value) -> Option<String> {
168    if let Some(fill) = detail.get("fill_status").and_then(|v| v.as_str()) {
169        return format_order_telegram(kind, fill, detail);
170    }
171    if detail.get("exit").is_some() || kind.contains("EXIT") {
172        let underlying = detail
173            .pointer("/signal/underlying")
174            .and_then(|v| v.as_str())
175            .unwrap_or("position");
176        let reason = detail
177            .pointer("/signal/reason")
178            .and_then(|v| v.as_str())
179            .unwrap_or("rule");
180        let reason_plain = match reason {
181            "profit_target" => "profit target hit",
182            "stop_loss" => "stop loss hit",
183            "dte_close" => "approaching expiration",
184            r if r.starts_with("thesis_") => "thesis deterioration (mechanical exit)",
185            "llm_recommendation" => "advisor recommendation",
186            other => other,
187        };
188        return Some(format!("Position closed: {underlying}\nReason: {reason_plain}"));
189    }
190    None
191}
192
193fn format_order_telegram(kind: &str, fill_status: &str, detail: &Value) -> Option<String> {
194    if fill_status.eq_ignore_ascii_case("SKIPPED") {
195        return None;
196    }
197
198    let signal = detail.get("signal").unwrap_or(detail);
199    let underlying = signal
200        .pointer("/params/underlying")
201        .or_else(|| signal.get("underlying"))
202        .and_then(|v| v.as_str())
203        .unwrap_or("?");
204    let expiry = signal
205        .pointer("/params/expiry")
206        .and_then(|v| v.as_str())
207        .unwrap_or("");
208    let short = signal.pointer("/params/short_strike").and_then(|v| v.as_f64());
209    let long = signal.pointer("/params/long_strike").and_then(|v| v.as_f64());
210    let credit = signal
211        .get("estimated_credit")
212        .or_else(|| signal.pointer("/params/limit_credit"))
213        .and_then(|v| v.as_f64());
214    let contracts = signal
215        .pointer("/params/contracts")
216        .and_then(|v| v.as_f64())
217        .unwrap_or(1.0)
218        .round() as u32;
219
220    let strikes = match (short, long) {
221        (Some(s), Some(l)) => format!("${s:.0}/${l:.0}"),
222        _ => "spread".into(),
223    };
224
225    let status_line = match fill_status {
226        "FILLED" => "Trade filled",
227        "WORKING" | "ACCEPTED" | "PENDING_ACTIVATION" | "QUEUED" => "Limit order working",
228        "REJECTED" | "CANCELED" | "EXPIRED" => "Order not filled",
229        _ if kind.contains("REJECTED") => "Order not filled",
230        _ => "Order update",
231    };
232
233    let mut msg = format!(
234        "{status_line}\n{underlying} put spread {strikes}, exp {expiry}"
235    );
236    if let Some(c) = credit {
237        msg.push_str(&format!("\nCredit ~${c:.2}"));
238    }
239    if contracts > 1 {
240        msg.push_str(&format!("\n{contracts} contracts"));
241    }
242    if fill_status == "REJECTED" || fill_status == "CANCELED" {
243        if let Some(note) = detail.get("note").and_then(|v| v.as_str()) {
244            msg.push_str(&format!("\n{note}"));
245        }
246    }
247    Some(msg)
248}
249
250fn format_position_snapshot(pos: &Value) -> String {
251    let underlying = pos
252        .get("underlying")
253        .and_then(|v| v.as_str())
254        .unwrap_or("?");
255    let expiry = pos.get("expiry").and_then(|v| v.as_str()).unwrap_or("?");
256    let short = pos
257        .pointer("/market_context/short_strike")
258        .and_then(|v| v.as_f64());
259    let long = pos
260        .pointer("/market_context/long_strike")
261        .and_then(|v| v.as_f64());
262    let px = pos
263        .pointer("/market_context/underlying_price")
264        .and_then(|v| v.as_f64());
265    let profit = pos.get("profit_pct").and_then(|v| v.as_f64());
266    let dte = pos
267        .get("dte")
268        .and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)));
269
270    let strikes = match (short, long) {
271        (Some(s), Some(l)) => format!(" (${s:.0}/${l:.0})"),
272        _ => String::new(),
273    };
274    let mut line = format!("{underlying} spread{strikes}, exp {expiry}");
275    if let Some(p) = px {
276        line.push_str(&format!(" — {underlying} ${p:.2}"));
277    }
278    if let Some(pnl) = profit {
279        line.push_str(&format!(" — {pnl:+.0}% on paper"));
280    }
281    if let Some(d) = dte {
282        line.push_str(&format!(" — {d} days left"));
283    }
284    line
285}
286
287fn format_position_advice(pos: &PositionReview) -> String {
288    let label = short_position_label(&pos.position_id);
289    let action = plain_rec_label(&pos.recommendation);
290    let why = plain_sentence(&pos.reasoning, 240);
291    format!("{label}: {action}\n{why}")
292}
293
294fn format_entry_advice(review: &LlmReview) -> String {
295    let rec = review.entry_recommendation.to_lowercase();
296    let headline = match rec.as_str() {
297        "proceed" => "New trade: Yes — ready to open if rules allow",
298        "defer" => "New trade: Not now",
299        "skip" => "New trade: No",
300        _ => "New trade: Waiting",
301    };
302    let why = if review.entry_reasoning.trim().is_empty() {
303        "No candidate met our entry rules this round.".into()
304    } else {
305        plain_sentence(&review.entry_reasoning, 280)
306    };
307    format!("{headline}\n{why}")
308}
309
310fn format_what_to_do(review: &LlmReview) -> String {
311    if review.entry_recommendation.eq_ignore_ascii_case("proceed") {
312        return "What to do: Review is favorable — the agent may place a limit order if risk limits allow.".into();
313    }
314    if !review.urgent_close_positions().is_empty() {
315        return "What to do: Urgent — review the open position; a close may be warranted.".into();
316    }
317    if review
318        .position_reviews
319        .iter()
320        .any(|p| p.urgency.eq_ignore_ascii_case("high"))
321    {
322        return "What to do: Watch closely today — elevated risk on an open spread.".into();
323    }
324    if review
325        .position_reviews
326        .iter()
327        .any(|p| p.recommendation.eq_ignore_ascii_case("watch"))
328    {
329        return "What to do: No action required — keep an eye on the position; auto-exit rules are still in control.".into();
330    }
331    "What to do: Nothing right now — mechanical profit, stop, and expiration rules have not triggered.".into()
332}
333
334fn short_position_label(position_id: &str) -> String {
335    let parts: Vec<&str> = position_id.split('|').collect();
336    if parts.len() >= 3 {
337        return format!("{} {}", parts[1], parts[2]);
338    }
339    position_id.to_string()
340}
341
342fn plain_rec_label(rec: &str) -> &'static str {
343    match rec.to_lowercase().as_str() {
344        "hold" => "Hold",
345        "watch" => "Watch",
346        "close" => "Consider closing",
347        "enter" => "Candidate entry",
348        _ => "Review",
349    }
350}
351
352fn plain_sentence(text: &str, max_chars: usize) -> String {
353    let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
354    if collapsed.chars().count() <= max_chars {
355        return collapsed;
356    }
357    let mut out = String::new();
358    for word in collapsed.split_whitespace() {
359        if !out.is_empty() {
360            if out.chars().count() + 1 + word.chars().count() > max_chars.saturating_sub(1) {
361                out.push('…');
362                return out;
363            }
364            out.push(' ');
365        }
366        out.push_str(word);
367    }
368    out
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use crate::agent::llm::LlmReview;
375
376    fn sample_review() -> LlmReview {
377        LlmReview {
378            phase: "selection".into(),
379            model: "test".into(),
380            used_web: false,
381            raw: serde_json::json!({}),
382            market_commentary: "long technical essay".into(),
383            web_insights: vec![],
384            position_reviews: vec![PositionReview {
385                position_id: "ACC|IWM|2026-07-31|vertical|P280L_P282S".into(),
386                recommendation: "hold".into(),
387                urgency: "low".into(),
388                reasoning: "Small paper loss; stop not hit.".into(),
389            }],
390            entry_recommendation: "defer".into(),
391            entry_reasoning: "Already have IWM exposure; wait for a better setup.".into(),
392            risk_alerts: vec!["concentration".into()],
393        }
394    }
395
396    #[test]
397    fn telegram_llm_is_plain_language() {
398        let msg = format_llm_review_telegram(&sample_review(), &[]);
399        assert!(msg.contains("Options update"));
400        assert!(msg.contains("New trade: Not now"));
401        assert!(msg.contains("What to do:"));
402        assert!(!msg.contains("market_commentary"));
403        assert!(!msg.contains("risk_alerts"));
404    }
405
406    #[test]
407    fn skipped_orders_not_telegrammed() {
408        let detail = serde_json::json!({
409            "fill_status": "SKIPPED",
410            "reason": "max_portfolio_risk_usd exceeded",
411            "signal": { "params": { "underlying": "IWM" } }
412        });
413        assert!(format_action_telegram("ORDER", &detail).is_none());
414    }
415
416    #[test]
417    fn filled_order_is_plain() {
418        let detail = serde_json::json!({
419            "fill_status": "FILLED",
420            "signal": {
421                "params": {
422                    "underlying": "IWM",
423                    "expiry": "2026-08-07",
424                    "short_strike": 281.0,
425                    "long_strike": 279.0,
426                    "limit_credit": 0.27,
427                    "contracts": 1.0
428                },
429                "estimated_credit": 0.27
430            }
431        });
432        let msg = format_action_telegram("ENTRY FILLED", &detail).unwrap();
433        assert!(msg.contains("Trade filled"));
434        assert!(msg.contains("IWM"));
435        assert!(!msg.contains("{"));
436    }
437
438    #[test]
439    fn defer_with_alerts_not_urgent() {
440        let review = sample_review();
441        assert!(!is_llm_urgent(&review));
442    }
443
444    #[test]
445    fn proceed_is_urgent() {
446        let mut review = sample_review();
447        review.entry_recommendation = "proceed".into();
448        assert!(is_llm_urgent(&review));
449    }
450
451    #[test]
452    fn digest_dedupes_same_message() {
453        let config = TelegramNotifyConfig::default();
454        let mut state = AgentState::default();
455        let review = sample_review();
456        let now = Utc::now();
457        assert!(should_send_llm_telegram(&review, &config, &state, now));
458        record_llm_telegram_sent(&mut state, &review, now);
459        assert!(!should_send_llm_telegram(&review, &config, &state, now));
460    }
461}