Skip to main content

indodax_cli/commands/
alert.rs

1use crate::client::IndodaxClient;
2use crate::commands::helpers;
3use crate::output::CommandOutput;
4use anyhow::Result;
5use colored::*;
6use futures_util::{SinkExt, StreamExt};
7use serde::{Deserialize, Serialize};
8use std::fs;
9use std::path::PathBuf;
10use tokio_tungstenite::{connect_async, tungstenite::Message};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct PriceAlert {
14    pub id: u64,
15    pub pair: String,
16    pub condition: AlertCondition,
17    pub created_at: u64,
18    pub triggered_at: Option<u64>,
19    pub status: AlertStatus,
20    pub note: Option<String>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24#[serde(tag = "type")]
25pub enum AlertCondition {
26    #[serde(rename = "above")]
27    Above { price: f64 },
28    #[serde(rename = "below")]
29    Below { price: f64 },
30    #[serde(rename = "change_up")]
31    ChangeUp { percent: f64, from_price: f64 },
32    #[serde(rename = "change_down")]
33    ChangeDown { percent: f64, from_price: f64 },
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37#[serde(rename_all = "lowercase")]
38pub enum AlertStatus {
39    Active,
40    Triggered,
41    Cancelled,
42}
43
44#[derive(Debug, clap::Subcommand)]
45pub enum AlertCommand {
46    #[command(name = "add", about = "Add a price alert")]
47    Add {
48        #[arg(short = 'p', long, help = "Trading pair (e.g. btc_idr)")]
49        pair: String,
50        #[arg(long, help = "Alert when price goes above this value")]
51        above: Option<f64>,
52        #[arg(long, help = "Alert when price goes below this value")]
53        below: Option<f64>,
54        #[arg(short = '%', long, help = "Alert when price increases by this percent")]
55        percent_up: Option<f64>,
56        #[arg(long, help = "Alert when price decreases by this percent")]
57        percent_down: Option<f64>,
58        #[arg(short = 'n', long, help = "Note for this alert")]
59        note: Option<String>,
60    },
61
62    #[command(name = "list", about = "List all price alerts")]
63    List {
64        #[arg(long, help = "Include triggered and cancelled alerts")]
65        history: bool,
66    },
67
68    #[command(name = "cancel", about = "Cancel a price alert")]
69    Cancel {
70        #[arg(short = 'i', long, help = "Alert ID to cancel")]
71        id: Option<u64>,
72        #[arg(long, help = "Cancel all alerts")]
73        all: bool,
74    },
75
76    #[command(name = "check", about = "Check alerts against current prices")]
77    Check {
78        #[arg(short = 'i', long, help = "Check specific alert by ID")]
79        id: Option<u64>,
80        #[arg(short = 'p', long, help = "Filter by pair (e.g. btc_idr)")]
81        pair: Option<String>,
82    },
83
84    #[command(name = "watch", about = "Monitor alerts in real-time via WebSocket")]
85    Watch {
86        #[arg(short = 'i', long, help = "Filter by alert ID")]
87        id: Option<u64>,
88        #[arg(short = 'p', long, help = "Filter by pair (e.g. btc_idr)")]
89        pair: Option<String>,
90        #[arg(long, default_value = "60", help = "Price change threshold (%) to trigger")]
91        threshold: f64,
92    },
93
94    #[command(name = "triggered", about = "Show triggered alerts")]
95    Triggered,
96}
97
98pub async fn execute(
99    client: &IndodaxClient,
100    _creds: &Option<crate::config::ResolvedCredentials>,
101    cmd: &AlertCommand,
102) -> Result<CommandOutput> {
103    match cmd {
104        AlertCommand::Add { pair, above, below, percent_up, percent_down, note } => {
105            let pair = helpers::normalize_pair(pair);
106            alert_add(&pair, *above, *below, *percent_up, *percent_down, note.clone(), client).await
107        }
108        AlertCommand::List { history } => alert_list(*history),
109        AlertCommand::Cancel { id, all } => alert_cancel(*id, *all),
110        AlertCommand::Check { id, pair } => {
111            let pair = pair.as_ref().map(|p| helpers::normalize_pair(p));
112            alert_check(client, *id, pair.as_deref()).await
113        }
114        AlertCommand::Watch { id, pair, threshold } => {
115            let pair = pair.as_ref().map(|p| helpers::normalize_pair(p));
116            alert_watch(client, *id, pair.as_deref(), *threshold).await
117        }
118        AlertCommand::Triggered => alert_triggered(),
119    }
120}
121
122pub fn alerts_path() -> PathBuf {
123    let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
124    let indodax_dir = config_dir.join("indodax");
125    fs::create_dir_all(&indodax_dir).ok();
126    indodax_dir.join("alerts.json")
127}
128
129fn load_alerts() -> Vec<PriceAlert> {
130    let path = alerts_path();
131    if path.exists() {
132        match fs::read_to_string(&path) {
133            Ok(content) => serde_json::from_str(&content).unwrap_or_default(),
134            Err(_) => Vec::new(),
135        }
136    } else {
137        Vec::new()
138    }
139}
140
141fn save_alerts(alerts: &[PriceAlert]) -> Result<()> {
142    let path = alerts_path();
143    let content = serde_json::to_string_pretty(alerts)?;
144    #[cfg(unix)]
145    {
146        use std::io::Write;
147        use std::os::unix::fs::OpenOptionsExt;
148        let mut file = std::fs::OpenOptions::new()
149            .write(true)
150            .create(true)
151            .truncate(true)
152            .mode(0o600)
153            .open(&path)?;
154        file.write_all(content.as_bytes())?;
155    }
156    #[cfg(not(unix))]
157    {
158        fs::write(&path, content)?;
159    }
160    Ok(())
161}
162
163fn get_next_id(alerts: &[PriceAlert]) -> u64 {
164    alerts.iter().map(|a| a.id).max().unwrap_or(0) + 1
165}
166
167fn now_millis() -> u64 {
168    std::time::SystemTime::now()
169        .duration_since(std::time::UNIX_EPOCH)
170        .unwrap_or_default()
171        .as_millis() as u64
172}
173
174async fn alert_add(
175    pair: &str,
176    above: Option<f64>,
177    below: Option<f64>,
178    percent_up: Option<f64>,
179    percent_down: Option<f64>,
180    note: Option<String>,
181    client: &IndodaxClient,
182) -> Result<CommandOutput> {
183    let condition_count = [above.is_some(), below.is_some(), percent_up.is_some(), percent_down.is_some()]
184        .iter().filter(|&&x| x).count();
185
186    if condition_count == 0 {
187        return Err(anyhow::anyhow!(
188            "Must specify one of: --above, --below, --percent-up, or --percent-down"
189        ));
190    }
191
192    if condition_count > 1 {
193        return Err(anyhow::anyhow!(
194            "Only one condition allowed per alert (--above, --below, --percent-up, --percent-down)"
195        ));
196    }
197
198    let condition = if let Some(price) = above {
199        if price <= 0.0 {
200            return Err(anyhow::anyhow!("Price must be positive, got {}", price));
201        }
202        AlertCondition::Above { price }
203    } else if let Some(price) = below {
204        if price <= 0.0 {
205            return Err(anyhow::anyhow!("Price must be positive, got {}", price));
206        }
207        AlertCondition::Below { price }
208    } else if let Some(percent) = percent_up {
209        if percent <= 0.0 || percent > 1000.0 {
210            return Err(anyhow::anyhow!("Percent must be between 0 and 1000, got {}", percent));
211        }
212        let from_price = fetch_price(client, pair).await?;
213        AlertCondition::ChangeUp { percent, from_price }
214    } else {
215        let percent = percent_down.unwrap();
216        if percent <= 0.0 || percent > 1000.0 {
217            return Err(anyhow::anyhow!("Percent must be between 0 and 1000, got {}", percent));
218        }
219        let from_price = fetch_price(client, pair).await?;
220        AlertCondition::ChangeDown { percent, from_price }
221    };
222
223    let mut alerts = load_alerts();
224    let id = get_next_id(&alerts);
225    let alert = PriceAlert {
226        id,
227        pair: pair.to_string(),
228        condition,
229        created_at: now_millis(),
230        triggered_at: None,
231        status: AlertStatus::Active,
232        note,
233    };
234
235    alerts.push(alert.clone());
236    save_alerts(&alerts)?;
237
238    let condition_str = match &alert.condition {
239        AlertCondition::Above { price } => format!("above {}", format_number(*price)),
240        AlertCondition::Below { price } => format!("below {}", format_number(*price)),
241        AlertCondition::ChangeUp { percent, from_price } => format!("+{:.1}% from {}", percent, format_number(*from_price)),
242        AlertCondition::ChangeDown { percent, from_price } => format!("-{:.1}% from {}", percent, format_number(*from_price)),
243    };
244
245    let data = serde_json::json!({
246        "status": "ok",
247        "id": id,
248        "pair": pair,
249        "condition": condition_str,
250        "created_at": alert.created_at,
251    });
252
253    let headers = vec!["Field".into(), "Value".into()];
254    let rows = vec![
255        vec!["Alert ID".into(), id.to_string()],
256        vec!["Pair".into(), pair.to_string()],
257        vec!["Condition".into(), condition_str.clone()],
258        vec!["Created".into(), chrono::DateTime::from_timestamp_millis(alert.created_at.min(i64::MAX as u64) as i64)
259            .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
260            .unwrap_or_default()],
261    ];
262
263    Ok(CommandOutput::new(data, headers, rows)
264        .with_addendum(format!("[ALERT] Created {} alert for {} @ {}", id, pair, condition_str)))
265}
266
267fn alert_list(include_history: bool) -> Result<CommandOutput> {
268    let alerts = load_alerts();
269
270    let filtered: Vec<&PriceAlert> = if include_history {
271        alerts.iter().collect()
272    } else {
273        alerts.iter().filter(|a| a.status == AlertStatus::Active).collect()
274    };
275
276    if filtered.is_empty() {
277        return Ok(CommandOutput::json(serde_json::json!({
278            "status": "ok",
279            "message": if include_history { "No alerts" } else { "No active alerts" },
280            "alerts": [],
281        })));
282    }
283
284    let mut headers = vec!["ID".into(), "Pair".into(), "Condition".into(), "Status".into(), "Created".into()];
285    if include_history {
286        headers.push("Triggered".into());
287    }
288
289    let mut rows: Vec<Vec<String>> = Vec::new();
290    for alert in &filtered {
291        let condition_str = match &alert.condition {
292            AlertCondition::Above { price } => format!("> {}", format_number(*price)),
293            AlertCondition::Below { price } => format!("< {}", format_number(*price)),
294            AlertCondition::ChangeUp { percent, from_price } => format!("+{:.1}% from {}", percent, format_number(*from_price)),
295            AlertCondition::ChangeDown { percent, from_price } => format!("-{:.1}% from {}", percent, format_number(*from_price)),
296        };
297
298        let mut row = vec![
299            alert.id.to_string(),
300            alert.pair.clone(),
301            condition_str.clone(),
302            format!("{:?}", alert.status),
303            chrono::DateTime::from_timestamp_millis(alert.created_at.min(i64::MAX as u64) as i64)
304                .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
305                .unwrap_or_default(),
306        ];
307
308        if include_history {
309            let triggered = alert.triggered_at.map(|t| {
310                chrono::DateTime::from_timestamp_millis(t.min(i64::MAX as u64) as i64)
311                    .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
312                    .unwrap_or_default()
313            }).unwrap_or_else(|| "-".to_string());
314            row.push(triggered);
315        }
316
317        rows.push(row);
318    }
319
320    let data = serde_json::json!({
321        "status": "ok",
322        "count": filtered.len(),
323    });
324
325    Ok(CommandOutput::new(data, headers, rows)
326        .with_addendum(format!("[ALERT] {} alert(s)", filtered.len())))
327}
328
329fn alert_cancel(id: Option<u64>, cancel_all: bool) -> Result<CommandOutput> {
330    let mut alerts = load_alerts();
331
332    if cancel_all {
333        let count = alerts.iter().filter(|a| a.status == AlertStatus::Active).count();
334        for alert in alerts.iter_mut() {
335            if alert.status == AlertStatus::Active {
336                alert.status = AlertStatus::Cancelled;
337            }
338        }
339        save_alerts(&alerts)?;
340
341        return Ok(CommandOutput::json(serde_json::json!({
342            "status": "ok",
343            "message": format!("Cancelled {} alert(s)", count),
344            "cancelled": count,
345        })).with_addendum(format!("[ALERT] Cancelled {} alert(s)", count)));
346    }
347
348    if let Some(target_id) = id {
349        let alert = alerts.iter_mut().find(|a| a.id == target_id);
350        match alert {
351            Some(a) if a.status == AlertStatus::Active => {
352                a.status = AlertStatus::Cancelled;
353                save_alerts(&alerts)?;
354
355                Ok(CommandOutput::json(serde_json::json!({
356                    "status": "ok",
357                    "message": format!("Cancelled alert {}", target_id),
358                    "id": target_id,
359                })).with_addendum(format!("[ALERT] Cancelled alert {}", target_id)))
360            }
361            Some(_) => Err(anyhow::anyhow!("Alert {} is already cancelled or triggered", target_id)),
362            None => Err(anyhow::anyhow!("Alert {} not found", target_id)),
363        }
364    } else {
365        Err(anyhow::anyhow!("Must specify --id or --all"))
366    }
367}
368
369async fn alert_check(
370    client: &IndodaxClient,
371    id: Option<u64>,
372    pair_filter: Option<&str>,
373) -> Result<CommandOutput> {
374    let mut alerts = load_alerts();
375
376    let to_check: Vec<&mut PriceAlert> = if let Some(target_id) = id {
377        alerts.iter_mut().filter(|a| a.id == target_id && a.status == AlertStatus::Active).collect()
378    } else {
379        let filter = pair_filter.unwrap_or("*");
380        alerts.iter_mut()
381            .filter(|a| a.status == AlertStatus::Active && (filter == "*" || a.pair == filter))
382            .collect()
383    };
384
385    if to_check.is_empty() {
386        return Ok(CommandOutput::json(serde_json::json!({
387            "status": "ok",
388            "message": "No active alerts to check",
389            "triggered": [],
390        })));
391    }
392
393    let mut triggered_alerts: Vec<PriceAlert> = Vec::new();
394
395    for alert in to_check {
396        let price = match fetch_price(client, &alert.pair).await {
397            Ok(p) => p,
398            Err(_) => continue,
399        };
400
401        let should_trigger = match &alert.condition {
402            AlertCondition::Above { price: threshold } => price >= *threshold,
403            AlertCondition::Below { price: threshold } => price <= *threshold,
404            AlertCondition::ChangeUp { percent, from_price } => {
405                let change = ((price - from_price) / from_price) * 100.0;
406                change >= *percent
407            }
408            AlertCondition::ChangeDown { percent, from_price } => {
409                let change = ((from_price - price) / from_price) * 100.0;
410                change >= *percent
411            }
412        };
413
414        if should_trigger {
415            alert.status = AlertStatus::Triggered;
416            alert.triggered_at = Some(now_millis());
417            triggered_alerts.push(alert.clone());
418        }
419    }
420
421    save_alerts(&alerts)?;
422
423    if triggered_alerts.is_empty() {
424        return Ok(CommandOutput::json(serde_json::json!({
425            "status": "ok",
426            "message": "No alerts triggered",
427            "triggered": [],
428        })).with_addendum("[ALERT] No alerts triggered"));
429    }
430
431    let headers = vec!["ID".into(), "Pair".into(), "Condition".into(), "Price".into(), "Triggered At".into()];
432    let mut rows: Vec<Vec<String>> = Vec::new();
433
434    for alert in &triggered_alerts {
435        let current_price = fetch_price(client, &alert.pair).await.unwrap_or(0.0);
436        let condition_str = match &alert.condition {
437            AlertCondition::Above { price } => format!("> {}", format_number(*price)),
438            AlertCondition::Below { price } => format!("< {}", format_number(*price)),
439            AlertCondition::ChangeUp { percent, from_price } => format!("+{:.1}% from {}", percent, format_number(*from_price)),
440            AlertCondition::ChangeDown { percent, from_price } => format!("-{:.1}% from {}", percent, format_number(*from_price)),
441        };
442
443        rows.push(vec![
444            alert.id.to_string(),
445            alert.pair.clone(),
446            condition_str.clone(),
447            format_number(current_price),
448            chrono::DateTime::from_timestamp_millis(alert.triggered_at.unwrap().min(i64::MAX as u64) as i64)
449                .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
450                .unwrap_or_default(),
451        ]);
452    }
453
454    let data = serde_json::json!({
455        "status": "ok",
456        "triggered": triggered_alerts,
457        "count": triggered_alerts.len(),
458    });
459
460    Ok(CommandOutput::new(data, headers, rows)
461        .with_addendum(format!("[ALERT] {} alert(s) triggered!", triggered_alerts.len())))
462}
463
464fn alert_triggered() -> Result<CommandOutput> {
465    let alerts = load_alerts();
466    let triggered: Vec<&PriceAlert> = alerts.iter()
467        .filter(|a| a.status == AlertStatus::Triggered)
468        .collect();
469
470    if triggered.is_empty() {
471        return Ok(CommandOutput::json(serde_json::json!({
472            "status": "ok",
473            "message": "No triggered alerts",
474            "count": 0,
475        })));
476    }
477
478    let headers = vec!["ID".into(), "Pair".into(), "Condition".into(), "Triggered At".into()];
479    let mut rows: Vec<Vec<String>> = Vec::new();
480
481    for alert in &triggered {
482        let condition_str = match &alert.condition {
483            AlertCondition::Above { price } => format!("> {}", format_number(*price)),
484            AlertCondition::Below { price } => format!("< {}", format_number(*price)),
485            AlertCondition::ChangeUp { percent, from_price } => format!("+{:.1}% from {}", percent, format_number(*from_price)),
486            AlertCondition::ChangeDown { percent, from_price } => format!("-{:.1}% from {}", percent, format_number(*from_price)),
487        };
488
489        rows.push(vec![
490            alert.id.to_string(),
491            alert.pair.clone(),
492            condition_str.clone(),
493            chrono::DateTime::from_timestamp_millis(alert.triggered_at.unwrap().min(i64::MAX as u64) as i64)
494                .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
495                .unwrap_or_default(),
496        ]);
497    }
498
499    Ok(CommandOutput::new(
500        serde_json::json!({"status": "ok", "count": triggered.len()}),
501        headers,
502        rows,
503    ).with_addendum(format!("[ALERT] {} triggered alert(s)", triggered.len())))
504}
505
506async fn fetch_price(client: &IndodaxClient, pair: &str) -> Result<f64> {
507    let response: serde_json::Value = client.public_get(&format!("/api/ticker/{}", pair)).await?;
508
509    let price = response.get("ticker")
510        .and_then(|t| t.get("last"))
511        .and_then(|v| v.as_str())
512        .and_then(|s| s.parse::<f64>().ok())
513        .or_else(|| {
514            response.get("ticker")
515                .and_then(|t| t.get("last"))
516                .and_then(|v| v.as_f64())
517        })
518        .ok_or_else(|| anyhow::anyhow!("Failed to parse price for {}", pair))?;
519
520    Ok(price)
521}
522
523async fn alert_watch(
524    client: &IndodaxClient,
525    id: Option<u64>,
526    pair_filter: Option<&str>,
527    _threshold: f64,
528) -> Result<CommandOutput> {
529    let mut alerts = load_alerts();
530
531    let target_ids: std::collections::HashSet<u64> = if let Some(target_id) = id {
532        alerts.iter().filter(|a| a.id == target_id && a.status == AlertStatus::Active).map(|a| a.id).collect()
533    } else {
534        let filter = pair_filter.unwrap_or("*");
535        alerts.iter()
536            .filter(|a| a.status == AlertStatus::Active && (filter == "*" || a.pair == filter))
537            .map(|a| a.id)
538            .collect()
539    };
540
541    if target_ids.is_empty() {
542        return Ok(CommandOutput::json(serde_json::json!({
543            "status": "ok",
544            "message": "No active alerts to watch",
545            "watching": [],
546        })));
547    }
548
549    let pairs: Vec<String> = alerts.iter()
550        .filter(|a| target_ids.contains(&a.id))
551        .map(|a| a.pair.clone())
552        .collect();
553    let pair_set: std::collections::HashSet<String> = pairs.iter().cloned().collect();
554    let watching = pair_set.len();
555
556    eprintln!("[ALERT] Watching {} alerts for {} pair(s): {}", target_ids.len(), watching, pairs.join(", "));
557    eprintln!("[ALERT] Press Ctrl+C to stop monitoring");
558    eprintln!();
559
560    const PUBLIC_WS_URL: &str = "wss://ws3.indodax.com/ws/";
561
562    let token = helpers::fetch_public_ws_token(client).await?;
563
564    let (ws_stream, _) = connect_async(PUBLIC_WS_URL).await
565        .map_err(|e| anyhow::anyhow!("Failed to connect to WebSocket: {}", e))?;
566
567    let (mut write, mut read) = ws_stream.split();
568
569    let auth_msg = serde_json::json!({
570        "params": { "token": token },
571        "id": 1
572    });
573    write.send(Message::Text(auth_msg.to_string())).await
574        .map_err(|e| anyhow::anyhow!("Failed to authenticate: {}", e))?;
575
576    let mut authed = false;
577    let mut last_prices: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
578    let mut triggered_count = 0;
579
580    let mut triggered_ids = std::collections::HashSet::new();
581
582    while let Some(msg) = read.next().await {
583        match msg {
584            Ok(Message::Text(text)) => {
585                if let Ok(data) = serde_json::from_str::<serde_json::Value>(&text) {
586                    if !authed {
587                        if data.get("id").and_then(|v| v.as_i64()) == Some(1)
588                            && data.get("result").is_some()
589                        {
590                            authed = true;
591                            eprintln!("[WS] Authenticated, subscribing to pairs...");
592                            for pair in &pair_set {
593                                let sub_msg = serde_json::json!({
594                                    "method": "subscribe",
595                                    "params": { "channel": format!("chart:tick-{}", pair) },
596                                    "id": 2
597                                });
598                                write.send(Message::Text(sub_msg.to_string())).await.ok();
599                            }
600                        }
601                        continue;
602                    }
603
604                    if let Some(result) = data.get("result").or(data.get("data")) {
605                        let pair = result.get("pair").or(data.get("pair")).and_then(|v| v.as_str()).unwrap_or("");
606                        let price = result.get("price").or(result.get("c")).or(result.get("close"))
607                            .and_then(|v| v.as_str().and_then(|s| s.parse::<f64>().ok()))
608                            .or_else(|| result.get("price").or(result.get("c")).and_then(|v| v.as_f64()));
609
610                        if let Some(price) = price {
611                            let prev_price = last_prices.get(pair).copied();
612                            last_prices.insert(pair.to_string(), price);
613
614                            if let Some(prev) = prev_price {
615                                let change_pct = ((price - prev) / prev * 100.0).abs();
616                                if change_pct > 0.1 {
617                                    eprintln!("[PRICE] {} {} (change: {:.2}%)",
618                                        pair,
619                                        format_number(price),
620                                        if price > prev { '+' } else { '-' });
621                                }
622                            }
623
624                            for alert in alerts.iter_mut().filter(|a| a.pair == pair && target_ids.contains(&a.id) && a.status == AlertStatus::Active) {
625                                let should_trigger = match &alert.condition {
626                                    AlertCondition::Above { price: threshold } => price >= *threshold,
627                                    AlertCondition::Below { price: threshold } => price <= *threshold,
628                                    AlertCondition::ChangeUp { percent, from_price } => {
629                                        let change = ((price - from_price) / from_price) * 100.0;
630                                        change >= *percent
631                                    }
632                                    AlertCondition::ChangeDown { percent, from_price } => {
633                                        let change = ((from_price - price) / from_price) * 100.0;
634                                        change >= *percent
635                                    }
636                                };
637
638                                if should_trigger {
639                                    alert.status = AlertStatus::Triggered;
640                                    alert.triggered_at = Some(now_millis());
641                                    triggered_ids.insert(alert.id);
642                                    triggered_count += 1;
643                                    let condition_str = match &alert.condition {
644                                        AlertCondition::Above { price } => format!("> {}", format_number(*price)),
645                                        AlertCondition::Below { price } => format!("< {}", format_number(*price)),
646                                        AlertCondition::ChangeUp { percent, from_price } => format!("+{:.1}% from {}", percent, format_number(*from_price)),
647                                        AlertCondition::ChangeDown { percent, from_price } => format!("-{:.1}% from {}", percent, format_number(*from_price)),
648                                    };
649                                    eprintln!();
650                                    eprintln!("{}", "=".repeat(60).yellow());
651                                    eprintln!("{} TRIGGERED {} {}", "[ALERT]".bold().green(), format!("#{}", alert.id).bold(), "!".green().bold());
652                                    eprintln!("  Pair:      {}", pair);
653                                    eprintln!("  Condition: {}", condition_str);
654                                    eprintln!("  Price:     {} (triggered)", format_number(price));
655                                    if let Some(note) = &alert.note {
656                                        eprintln!("  Note:      {}", note);
657                                    }
658                                    eprintln!("{}", "=".repeat(60).yellow());
659                                    eprintln!();
660                                }
661                            }
662                        }
663                    }
664                }
665            }
666            Ok(Message::Ping(data)) => {
667                write.send(Message::Pong(data)).await.ok();
668            }
669            Ok(Message::Close(_)) => {
670                break;
671            }
672            Err(e) => {
673                eprintln!("[WARN] WebSocket error: {}", e);
674                break;
675            }
676            _ => {}
677        }
678    }
679
680    eprintln!("\n[ALERT] Monitoring stopped. {} alert(s) triggered.", triggered_count);
681
682    if triggered_count > 0 {
683        save_alerts(&alerts)?;
684    }
685
686    let data = serde_json::json!({
687        "status": "ok",
688        "watching": target_ids.len(),
689        "pairs": pairs,
690        "triggered": triggered_count,
691    });
692
693    Ok(CommandOutput::new(data, vec![], vec![]).with_addendum(format!(
694        "[ALERT] Watched {} alert(s) for {} pair(s). {} triggered.",
695        target_ids.len(), watching, triggered_count
696    )))
697}
698
699fn format_number(n: f64) -> String {
700    if n >= 1_000_000_000.0 {
701        format!("{:.2}B", n / 1_000_000_000.0)
702    } else if n >= 1_000_000.0 {
703        format!("{:.2}M", n / 1_000_000.0)
704    } else if n >= 1_000.0 {
705        format!("{:.2}K", n / 1_000.0)
706    } else if n >= 1.0 {
707        format!("{:.2}", n)
708    } else {
709        format!("{:.8}", n)
710    }
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716
717    #[test]
718    fn test_format_number() {
719        assert_eq!(format_number(1_500_000_000.0), "1.50B");
720        assert_eq!(format_number(100_000_000.0), "100.00M");
721        assert_eq!(format_number(50_000.0), "50.00K");
722        assert_eq!(format_number(1_000.0), "1.00K");
723        assert_eq!(format_number(100.0), "100.00");
724        assert_eq!(format_number(0.00001), "0.00001000");
725    }
726
727    #[test]
728    fn test_alert_condition_serialization() {
729        let above = AlertCondition::Above { price: 100000000.0 };
730        let json = serde_json::to_string(&above).unwrap();
731        assert!(json.contains("\"type\":\"above\""));
732
733        let below = AlertCondition::Below { price: 50000000.0 };
734        let json = serde_json::to_string(&below).unwrap();
735        assert!(json.contains("\"type\":\"below\""));
736
737        let change_up = AlertCondition::ChangeUp { percent: 5.0, from_price: 100000000.0 };
738        let json = serde_json::to_string(&change_up).unwrap();
739        assert!(json.contains("\"type\":\"change_up\""));
740        assert!(json.contains("5.0"));
741
742        let change_down = AlertCondition::ChangeDown { percent: 10.0, from_price: 150000000.0 };
743        let json = serde_json::to_string(&change_down).unwrap();
744        assert!(json.contains("\"type\":\"change_down\""));
745    }
746
747    #[test]
748    fn test_alert_status_serialization() {
749        let active = AlertStatus::Active;
750        let json = serde_json::to_string(&active).unwrap();
751        assert_eq!(json, "\"active\"");
752
753        let triggered = AlertStatus::Triggered;
754        let json = serde_json::to_string(&triggered).unwrap();
755        assert_eq!(json, "\"triggered\"");
756    }
757}