1use chrono::{DateTime, Utc};
4use serde_json::Value;
5
6use crate::agent::llm::{LlmReview, PositionReview};
7use crate::agent::state::AgentState;
8use crate::rules::TelegramNotifyConfig;
9
10pub 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
41pub 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
83pub 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>) -> String {
124 let Some(pb) = playbook else {
125 return "Market is open. Your agent is watching open positions.".into();
126 };
127 let mut out = "Market is open.\n\n".to_string();
128 if let Some(positions) = pb.get("positions").and_then(|v| v.as_array()) {
129 for pos in positions {
130 let id = pos
131 .get("position_id")
132 .and_then(|v| v.as_str())
133 .unwrap_or("position");
134 let rec = pos
135 .get("recommendation")
136 .and_then(|v| v.as_str())
137 .unwrap_or("watch");
138 out.push_str(&format!(
139 "Overnight note for {}: {}.\n",
140 short_position_label(id),
141 plain_rec_label(rec)
142 ));
143 }
144 }
145 if let Some(alerts) = pb.get("risk_alerts").and_then(|v| v.as_array()) {
146 if !alerts.is_empty() {
147 out.push_str("\nHeads up at the open:\n");
148 for alert in alerts.iter().take(3) {
149 if let Some(s) = alert.as_str() {
150 out.push_str("• ");
151 out.push_str(&plain_sentence(s, 200));
152 out.push('\n');
153 }
154 }
155 }
156 }
157 out.trim_end().to_string()
158}
159
160pub fn format_action_telegram(kind: &str, detail: &Value) -> Option<String> {
162 if let Some(fill) = detail.get("fill_status").and_then(|v| v.as_str()) {
163 return format_order_telegram(kind, fill, detail);
164 }
165 if detail.get("exit").is_some() || kind.contains("EXIT") {
166 let underlying = detail
167 .pointer("/signal/underlying")
168 .and_then(|v| v.as_str())
169 .unwrap_or("position");
170 let reason = detail
171 .pointer("/signal/reason")
172 .and_then(|v| v.as_str())
173 .unwrap_or("rule");
174 let reason_plain = match reason {
175 "profit_target" => "profit target hit",
176 "stop_loss" => "stop loss hit",
177 "dte_close" => "approaching expiration",
178 "llm_recommendation" => "advisor recommendation",
179 other => other,
180 };
181 return Some(format!("Position closed: {underlying}\nReason: {reason_plain}"));
182 }
183 None
184}
185
186fn format_order_telegram(kind: &str, fill_status: &str, detail: &Value) -> Option<String> {
187 if fill_status.eq_ignore_ascii_case("SKIPPED") {
188 return None;
189 }
190
191 let signal = detail.get("signal").unwrap_or(detail);
192 let underlying = signal
193 .pointer("/params/underlying")
194 .or_else(|| signal.get("underlying"))
195 .and_then(|v| v.as_str())
196 .unwrap_or("?");
197 let expiry = signal
198 .pointer("/params/expiry")
199 .and_then(|v| v.as_str())
200 .unwrap_or("");
201 let short = signal.pointer("/params/short_strike").and_then(|v| v.as_f64());
202 let long = signal.pointer("/params/long_strike").and_then(|v| v.as_f64());
203 let credit = signal
204 .get("estimated_credit")
205 .or_else(|| signal.pointer("/params/limit_credit"))
206 .and_then(|v| v.as_f64());
207 let contracts = signal
208 .pointer("/params/contracts")
209 .and_then(|v| v.as_f64())
210 .unwrap_or(1.0)
211 .round() as u32;
212
213 let strikes = match (short, long) {
214 (Some(s), Some(l)) => format!("${s:.0}/${l:.0}"),
215 _ => "spread".into(),
216 };
217
218 let status_line = match fill_status {
219 "FILLED" => "Trade filled",
220 "WORKING" | "ACCEPTED" | "PENDING_ACTIVATION" | "QUEUED" => "Limit order working",
221 "REJECTED" | "CANCELED" | "EXPIRED" => "Order not filled",
222 _ if kind.contains("REJECTED") => "Order not filled",
223 _ => "Order update",
224 };
225
226 let mut msg = format!(
227 "{status_line}\n{underlying} put spread {strikes}, exp {expiry}"
228 );
229 if let Some(c) = credit {
230 msg.push_str(&format!("\nCredit ~${c:.2}"));
231 }
232 if contracts > 1 {
233 msg.push_str(&format!("\n{contracts} contracts"));
234 }
235 if fill_status == "REJECTED" || fill_status == "CANCELED" {
236 if let Some(note) = detail.get("note").and_then(|v| v.as_str()) {
237 msg.push_str(&format!("\n{note}"));
238 }
239 }
240 Some(msg)
241}
242
243fn format_position_snapshot(pos: &Value) -> String {
244 let underlying = pos
245 .get("underlying")
246 .and_then(|v| v.as_str())
247 .unwrap_or("?");
248 let expiry = pos.get("expiry").and_then(|v| v.as_str()).unwrap_or("?");
249 let short = pos
250 .pointer("/market_context/short_strike")
251 .and_then(|v| v.as_f64());
252 let long = pos
253 .pointer("/market_context/long_strike")
254 .and_then(|v| v.as_f64());
255 let px = pos
256 .pointer("/market_context/underlying_price")
257 .and_then(|v| v.as_f64());
258 let profit = pos.get("profit_pct").and_then(|v| v.as_f64());
259 let dte = pos
260 .get("dte")
261 .and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)));
262
263 let strikes = match (short, long) {
264 (Some(s), Some(l)) => format!(" (${s:.0}/${l:.0})"),
265 _ => String::new(),
266 };
267 let mut line = format!("{underlying} spread{strikes}, exp {expiry}");
268 if let Some(p) = px {
269 line.push_str(&format!(" — {underlying} ${p:.2}"));
270 }
271 if let Some(pnl) = profit {
272 line.push_str(&format!(" — {pnl:+.0}% on paper"));
273 }
274 if let Some(d) = dte {
275 line.push_str(&format!(" — {d} days left"));
276 }
277 line
278}
279
280fn format_position_advice(pos: &PositionReview) -> String {
281 let label = short_position_label(&pos.position_id);
282 let action = plain_rec_label(&pos.recommendation);
283 let why = plain_sentence(&pos.reasoning, 240);
284 format!("{label}: {action}\n{why}")
285}
286
287fn format_entry_advice(review: &LlmReview) -> String {
288 let rec = review.entry_recommendation.to_lowercase();
289 let headline = match rec.as_str() {
290 "proceed" => "New trade: Yes — ready to open if rules allow",
291 "defer" => "New trade: Not now",
292 "skip" => "New trade: No",
293 _ => "New trade: Waiting",
294 };
295 let why = if review.entry_reasoning.trim().is_empty() {
296 "No candidate met our entry rules this round.".into()
297 } else {
298 plain_sentence(&review.entry_reasoning, 280)
299 };
300 format!("{headline}\n{why}")
301}
302
303fn format_what_to_do(review: &LlmReview) -> String {
304 if review.entry_recommendation.eq_ignore_ascii_case("proceed") {
305 return "What to do: Review is favorable — the agent may place a limit order if risk limits allow.".into();
306 }
307 if !review.urgent_close_positions().is_empty() {
308 return "What to do: Urgent — review the open position; a close may be warranted.".into();
309 }
310 if review
311 .position_reviews
312 .iter()
313 .any(|p| p.urgency.eq_ignore_ascii_case("high"))
314 {
315 return "What to do: Watch closely today — elevated risk on an open spread.".into();
316 }
317 if review
318 .position_reviews
319 .iter()
320 .any(|p| p.recommendation.eq_ignore_ascii_case("watch"))
321 {
322 return "What to do: No action required — keep an eye on the position; auto-exit rules are still in control.".into();
323 }
324 "What to do: Nothing right now — mechanical profit, stop, and expiration rules have not triggered.".into()
325}
326
327fn short_position_label(position_id: &str) -> String {
328 let parts: Vec<&str> = position_id.split('|').collect();
329 if parts.len() >= 3 {
330 return format!("{} {}", parts[1], parts[2]);
331 }
332 position_id.to_string()
333}
334
335fn plain_rec_label(rec: &str) -> &'static str {
336 match rec.to_lowercase().as_str() {
337 "hold" => "Hold",
338 "watch" => "Watch",
339 "close" => "Consider closing",
340 "enter" => "Candidate entry",
341 _ => "Review",
342 }
343}
344
345fn plain_sentence(text: &str, max_chars: usize) -> String {
346 let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
347 if collapsed.chars().count() <= max_chars {
348 return collapsed;
349 }
350 let mut out = String::new();
351 for word in collapsed.split_whitespace() {
352 if !out.is_empty() {
353 if out.chars().count() + 1 + word.chars().count() > max_chars.saturating_sub(1) {
354 out.push('…');
355 return out;
356 }
357 out.push(' ');
358 }
359 out.push_str(word);
360 }
361 out
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use crate::agent::llm::LlmReview;
368
369 fn sample_review() -> LlmReview {
370 LlmReview {
371 phase: "selection".into(),
372 model: "test".into(),
373 used_web: false,
374 raw: serde_json::json!({}),
375 market_commentary: "long technical essay".into(),
376 web_insights: vec![],
377 position_reviews: vec![PositionReview {
378 position_id: "ACC|IWM|2026-07-31|vertical|P280L_P282S".into(),
379 recommendation: "hold".into(),
380 urgency: "low".into(),
381 reasoning: "Small paper loss; stop not hit.".into(),
382 }],
383 entry_recommendation: "defer".into(),
384 entry_reasoning: "Already have IWM exposure; wait for a better setup.".into(),
385 risk_alerts: vec!["concentration".into()],
386 }
387 }
388
389 #[test]
390 fn telegram_llm_is_plain_language() {
391 let msg = format_llm_review_telegram(&sample_review(), &[]);
392 assert!(msg.contains("Options update"));
393 assert!(msg.contains("New trade: Not now"));
394 assert!(msg.contains("What to do:"));
395 assert!(!msg.contains("market_commentary"));
396 assert!(!msg.contains("risk_alerts"));
397 }
398
399 #[test]
400 fn skipped_orders_not_telegrammed() {
401 let detail = serde_json::json!({
402 "fill_status": "SKIPPED",
403 "reason": "max_portfolio_risk_usd exceeded",
404 "signal": { "params": { "underlying": "IWM" } }
405 });
406 assert!(format_action_telegram("ORDER", &detail).is_none());
407 }
408
409 #[test]
410 fn filled_order_is_plain() {
411 let detail = serde_json::json!({
412 "fill_status": "FILLED",
413 "signal": {
414 "params": {
415 "underlying": "IWM",
416 "expiry": "2026-08-07",
417 "short_strike": 281.0,
418 "long_strike": 279.0,
419 "limit_credit": 0.27,
420 "contracts": 1.0
421 },
422 "estimated_credit": 0.27
423 }
424 });
425 let msg = format_action_telegram("ENTRY FILLED", &detail).unwrap();
426 assert!(msg.contains("Trade filled"));
427 assert!(msg.contains("IWM"));
428 assert!(!msg.contains("{"));
429 }
430
431 #[test]
432 fn defer_with_alerts_not_urgent() {
433 let review = sample_review();
434 assert!(!is_llm_urgent(&review));
435 }
436
437 #[test]
438 fn proceed_is_urgent() {
439 let mut review = sample_review();
440 review.entry_recommendation = "proceed".into();
441 assert!(is_llm_urgent(&review));
442 }
443
444 #[test]
445 fn digest_dedupes_same_message() {
446 let config = TelegramNotifyConfig::default();
447 let mut state = AgentState::default();
448 let review = sample_review();
449 let now = Utc::now();
450 assert!(should_send_llm_telegram(&review, &config, &state, now));
451 record_llm_telegram_sent(&mut state, &review, now);
452 assert!(!should_send_llm_telegram(&review, &config, &state, now));
453 }
454}