scope-bca-core 0.6.0

Scope Blockchain Analysis - Core library for blockchain data analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Order book health analysis and market summary.
//!
//! Provides configurable health checks for stablecoin market monitoring:
//! peg deviation, spread, bid/ask balance, level count, and depth thresholds.

use super::types::{ExecutionEstimate, HealthCheck, OrderBook, OrderBookLevel};
use serde::{Deserialize, Serialize};

/// Default peg target (USD stablecoins).
pub const DEFAULT_PEG_TARGET: f64 = 1.0;
/// Default peg range for outlier filtering (peg ± range×5).
pub const DEFAULT_PEG_RANGE: f64 = 0.001;
/// Default minimum valid levels per side.
pub const DEFAULT_MIN_LEVELS: usize = 10;
/// Default minimum in-band depth per side (quote, e.g. USDT).
pub const DEFAULT_MIN_DEPTH: f64 = 3000.0;
/// Default bid/ask ratio floor.
pub const DEFAULT_MIN_BID_ASK_RATIO: f64 = 0.2;
/// Default bid/ask ratio ceiling.
pub const DEFAULT_MAX_BID_ASK_RATIO: f64 = 5.0;
/// Default maximum best-bid/best-ask spread, in percent of mid price.
pub const DEFAULT_MAX_SPREAD_PCT: f64 = 3.0;
/// Default minimum depth of the top 3 valid levels per side (quote).
pub const DEFAULT_MIN_TOP3_DEPTH: f64 = 300.0;
/// Default minimum depth of the top 10 valid levels per side (quote).
pub const DEFAULT_MIN_TOP10_DEPTH: f64 = 2000.0;

/// Number of levels summed for the top-3 depth check.
pub const TOP3_LEVELS: usize = 3;
/// Number of levels summed for the top-10 depth check.
pub const TOP10_LEVELS: usize = 10;

/// Health check thresholds for order book validation.
///
/// Built-in defaults are the `DEFAULT_*` constants in this module. The
/// `market.health` section of the config file replaces any of them, and
/// [`HealthOverrides`] (CLI flags, web request fields) replaces the result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HealthThresholds {
    /// Peg target (e.g., 1.0 for USD stablecoins).
    pub peg_target: f64,
    /// Price range for "near peg" orders (outliers excluded outside peg ± range×5).
    pub peg_range: f64,
    /// Minimum valid levels (price > 0, quantity > 0) per side.
    pub min_levels: usize,
    /// Minimum in-band depth per side in quote terms (e.g., USDT).
    pub min_depth: f64,
    /// Bid/ask ratio below which to warn (bid side thin).
    pub min_bid_ask_ratio: f64,
    /// Bid/ask ratio above which to warn (ask side thin).
    pub max_bid_ask_ratio: f64,
    /// Maximum spread between best valid bid and ask, in percent of mid price.
    pub max_spread_pct: f64,
    /// Minimum depth of the top 3 valid levels per side (quote).
    pub min_top3_depth: f64,
    /// Minimum depth of the top 10 valid levels per side (quote).
    pub min_top10_depth: f64,
}

impl Default for HealthThresholds {
    fn default() -> Self {
        Self {
            peg_target: DEFAULT_PEG_TARGET,
            peg_range: DEFAULT_PEG_RANGE,
            min_levels: DEFAULT_MIN_LEVELS,
            min_depth: DEFAULT_MIN_DEPTH,
            min_bid_ask_ratio: DEFAULT_MIN_BID_ASK_RATIO,
            max_bid_ask_ratio: DEFAULT_MAX_BID_ASK_RATIO,
            max_spread_pct: DEFAULT_MAX_SPREAD_PCT,
            min_top3_depth: DEFAULT_MIN_TOP3_DEPTH,
            min_top10_depth: DEFAULT_MIN_TOP10_DEPTH,
        }
    }
}

/// Per-request threshold overrides. A `None` field keeps the base value.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HealthOverrides {
    /// Peg target. The web API sends this as `peg`.
    #[serde(alias = "peg")]
    pub peg_target: Option<f64>,
    pub peg_range: Option<f64>,
    pub min_levels: Option<usize>,
    pub min_depth: Option<f64>,
    pub min_bid_ask_ratio: Option<f64>,
    pub max_bid_ask_ratio: Option<f64>,
    pub max_spread_pct: Option<f64>,
    pub min_top3_depth: Option<f64>,
    pub min_top10_depth: Option<f64>,
}

impl HealthThresholds {
    /// Returns a copy of `self` with each `Some` field in `o` applied.
    pub fn with_overrides(&self, o: &HealthOverrides) -> Self {
        Self {
            peg_target: o.peg_target.unwrap_or(self.peg_target),
            peg_range: o.peg_range.unwrap_or(self.peg_range),
            min_levels: o.min_levels.unwrap_or(self.min_levels),
            min_depth: o.min_depth.unwrap_or(self.min_depth),
            min_bid_ask_ratio: o.min_bid_ask_ratio.unwrap_or(self.min_bid_ask_ratio),
            max_bid_ask_ratio: o.max_bid_ask_ratio.unwrap_or(self.max_bid_ask_ratio),
            max_spread_pct: o.max_spread_pct.unwrap_or(self.max_spread_pct),
            min_top3_depth: o.min_top3_depth.unwrap_or(self.min_top3_depth),
            min_top10_depth: o.min_top10_depth.unwrap_or(self.min_top10_depth),
        }
    }
}

/// A level is valid when it has a positive price and quantity.
fn is_valid_level(level: &OrderBookLevel) -> bool {
    level.price > 0.0 && level.quantity > 0.0
}

/// Sum of quote value over the first `n` valid levels (book order = best first).
fn top_n_depth(levels: &[OrderBookLevel], n: usize) -> f64 {
    levels
        .iter()
        .filter(|l| is_valid_level(l))
        .take(n)
        .map(OrderBookLevel::value)
        .sum()
}

/// Aggregated market summary with order book snapshot and health results.
#[derive(Debug, Clone)]
pub struct MarketSummary {
    /// Pair label (e.g., "USDC/USDT").
    pub pair: String,
    /// Peg target.
    pub peg_target: f64,
    /// Best bid (raw, no outlier filtering).
    pub best_bid: Option<f64>,
    /// Best ask.
    pub best_ask: Option<f64>,
    /// Mid price.
    pub mid_price: Option<f64>,
    /// Spread.
    pub spread: Option<f64>,
    /// 24h volume in quote (e.g. USDT) if available.
    pub volume_24h: Option<f64>,
    /// Execution estimate for 10k USDT buy (slippage).
    pub execution_10k_buy: Option<ExecutionEstimate>,
    /// Execution estimate for 10k USDT sell (slippage).
    pub execution_10k_sell: Option<ExecutionEstimate>,
    /// Asks within peg range (for display).
    pub asks: Vec<OrderBookLevel>,
    /// Bids within peg range.
    pub bids: Vec<OrderBookLevel>,
    /// Count of ask levels excluded as outliers.
    pub ask_outliers: usize,
    /// Count of bid levels excluded as outliers.
    pub bid_outliers: usize,
    /// Ask depth (quote) within range.
    pub ask_depth: f64,
    /// Bid depth (quote) within range.
    pub bid_depth: f64,
    /// Health check results.
    pub checks: Vec<HealthCheck>,
    /// Overall healthy (no failures).
    pub healthy: bool,
}

impl MarketSummary {
    /// Build summary from order book; the peg is `thresholds.peg_target`.
    /// Optionally includes 24h volume (from venue ticker) and execution estimates for 10k USDT.
    pub fn from_order_book(
        book: &OrderBook,
        thresholds: &HealthThresholds,
        volume_24h: Option<f64>,
    ) -> Self {
        let peg_target = thresholds.peg_target;
        let price_lo = peg_target - thresholds.peg_range * 5.0;
        let price_hi = peg_target + thresholds.peg_range * 5.0;

        let asks: Vec<OrderBookLevel> = book
            .asks
            .iter()
            .filter(|l| l.price <= price_hi)
            .cloned()
            .collect();
        let bids: Vec<OrderBookLevel> = book
            .bids
            .iter()
            .filter(|l| l.price >= price_lo)
            .cloned()
            .collect();

        let ask_outliers = book.asks.len().saturating_sub(asks.len());
        let bid_outliers = book.bids.len().saturating_sub(bids.len());

        let ask_depth: f64 = asks.iter().map(OrderBookLevel::value).sum();
        let bid_depth: f64 = bids.iter().map(OrderBookLevel::value).sum();

        let mut checks = Vec::new();

        // Peg safety: sells below peg
        let below_peg: Vec<_> = asks.iter().filter(|a| a.price < peg_target).collect();
        if below_peg.is_empty() {
            checks.push(HealthCheck::Pass("No sells below peg".to_string()));
        } else {
            let usdt = below_peg.iter().map(|a| a.value()).sum::<f64>();
            checks.push(HealthCheck::Fail(format!(
                "{} sell(s) below peg ({:.0} USDT)",
                below_peg.len(),
                usdt
            )));
        }

        // Bid/ask ratio
        let ratio = if ask_depth > 0.0 {
            bid_depth / ask_depth
        } else {
            0.0
        };
        if ratio < thresholds.min_bid_ask_ratio || ratio > thresholds.max_bid_ask_ratio {
            checks.push(HealthCheck::Fail(format!("Bid/Ask ratio: {:.2}x", ratio)));
        } else {
            checks.push(HealthCheck::Pass(format!("Bid/Ask ratio: {:.2}x", ratio)));
        }

        let valid_bids = book.bids.iter().filter(|l| is_valid_level(l)).count();
        let valid_asks = book.asks.iter().filter(|l| is_valid_level(l)).count();

        // Spread between best valid bid and best valid ask
        let best_valid_bid = book.bids.iter().find(|l| is_valid_level(l));
        let best_valid_ask = book.asks.iter().find(|l| is_valid_level(l));
        match (best_valid_bid, best_valid_ask) {
            (Some(b), Some(a)) => {
                let mid = (a.price + b.price) / 2.0;
                let spread_pct = (a.price - b.price) / mid * 100.0;
                let msg = format!(
                    "Spread: {:.3}% (max {:.1}%)",
                    spread_pct, thresholds.max_spread_pct
                );
                if spread_pct > thresholds.max_spread_pct {
                    checks.push(HealthCheck::Fail(msg));
                } else {
                    checks.push(HealthCheck::Pass(msg));
                }
            }
            _ => checks.push(HealthCheck::Fail("Spread: no valid bid or ask".to_string())),
        }

        // Bid levels
        if valid_bids < thresholds.min_levels {
            checks.push(HealthCheck::Fail(format!(
                "Bid levels: {} < {} minimum",
                valid_bids, thresholds.min_levels
            )));
        }

        // Bid depth
        if bid_depth < thresholds.min_depth {
            checks.push(HealthCheck::Fail(format!(
                "Bid depth: {:.0} USDT < {:.0} USDT minimum",
                bid_depth, thresholds.min_depth
            )));
        }

        // Ask levels
        if valid_asks < thresholds.min_levels {
            checks.push(HealthCheck::Fail(format!(
                "Ask levels: {} < {} minimum",
                valid_asks, thresholds.min_levels
            )));
        }

        // Ask depth
        if ask_depth < thresholds.min_depth {
            checks.push(HealthCheck::Fail(format!(
                "Ask depth: {:.0} USDT < {:.0} USDT minimum",
                ask_depth, thresholds.min_depth
            )));
        }

        // Top-N depth per side (valid levels, best first)
        for (side, levels) in [("Bid", &book.bids), ("Ask", &book.asks)] {
            for (n, min) in [
                (TOP3_LEVELS, thresholds.min_top3_depth),
                (TOP10_LEVELS, thresholds.min_top10_depth),
            ] {
                let depth = top_n_depth(levels, n);
                if depth < min {
                    checks.push(HealthCheck::Fail(format!(
                        "{side} top-{n} depth: {depth:.0} USDT < {min:.0} USDT minimum"
                    )));
                }
            }
        }

        let healthy = checks.iter().all(|c| matches!(c, HealthCheck::Pass(_)));

        let execution_10k_buy = book.estimate_buy_execution(10_000.0);
        let execution_10k_sell = book.estimate_sell_execution(10_000.0);

        Self {
            pair: book.pair.clone(),
            peg_target,
            best_bid: book.best_bid(),
            best_ask: book.best_ask(),
            mid_price: book.mid_price(),
            spread: book.spread(),
            volume_24h,
            execution_10k_buy,
            execution_10k_sell,
            asks,
            bids,
            ask_outliers,
            bid_outliers,
            ask_depth,
            bid_depth,
            checks,
            healthy,
        }
    }

    /// Format as human-readable text report.
    /// When `venue_or_chain` is provided, it is displayed in the header (e.g. binance, ethereum).
    pub fn format_text(&self, venue_or_chain: Option<&str>) -> String {
        use crate::display::terminal as t;

        let mut out = String::new();

        let title = match venue_or_chain {
            Some(c) => format!("{} ({})", self.pair, c),
            None => self.pair.clone(),
        };
        out.push_str(&t::section_header(&title));
        out.push('\n');

        // Metrics subsection
        out.push_str(&t::subsection_header("Metrics"));
        out.push('\n');
        if let Some(c) = venue_or_chain {
            out.push_str(&t::kv_row("Venue", c));
            out.push('\n');
        }
        out.push_str(&t::kv_row("Peg Target", &format!("{:.4}", self.peg_target)));
        out.push('\n');

        if let Some(bb) = self.best_bid {
            let pct = (bb - self.peg_target) / self.peg_target * 100.0;
            out.push_str(&t::kv_row(
                "Best Bid",
                &format!(
                    "{}  ({:+.3}%)",
                    t::format_price_peg(bb, self.peg_target),
                    pct
                ),
            ));
            out.push('\n');
        }
        if let Some(ba) = self.best_ask {
            let pct = (ba - self.peg_target) / self.peg_target * 100.0;
            out.push_str(&t::kv_row(
                "Best Ask",
                &format!(
                    "{}  ({:+.3}%)",
                    t::format_price_peg(ba, self.peg_target),
                    pct
                ),
            ));
            out.push('\n');
        }
        if let Some(mid) = self.mid_price {
            let pct = (mid - self.peg_target) / self.peg_target * 100.0;
            out.push_str(&t::kv_row(
                "Mid Price",
                &format!(
                    "{}  ({:+.3}%)",
                    t::format_price_peg(mid, self.peg_target),
                    pct
                ),
            ));
            out.push('\n');
        }
        if let (Some(spread), Some(mid)) = (self.spread, self.mid_price)
            && mid > 0.0
        {
            out.push_str(&t::kv_row(
                "Spread",
                &format!("{:.4}  ({:.3}%)", spread, spread / mid * 100.0),
            ));
            out.push('\n');
        }

        if let Some(v) = self.volume_24h {
            out.push_str(&t::kv_row("Volume (24h)", &format!("{:.0} USDT", v)));
            out.push('\n');
        }

        if let Some(e) = &self.execution_10k_buy {
            let msg = if e.fillable {
                format!("~{:.2} bps slippage", e.slippage_bps)
            } else {
                "insufficient liquidity".to_string()
            };
            out.push_str(&t::kv_row("Exec 10K buy", &msg));
            out.push('\n');
        }
        if let Some(e) = &self.execution_10k_sell {
            let msg = if e.fillable {
                format!("~{:.2} bps slippage", e.slippage_bps)
            } else {
                "insufficient liquidity".to_string()
            };
            out.push_str(&t::kv_row("Exec 10K sell", &msg));
            out.push('\n');
        }

        // Ask side
        let base_symbol = self.pair.split('/').next().unwrap_or("BASE");
        let ask_label = if self.ask_outliers > 0 {
            format!(
                "Ask Side — {} levels, {:.0} USDT (+{} outliers excl.)",
                self.asks.len(),
                self.ask_depth,
                self.ask_outliers
            )
        } else {
            format!(
                "Ask Side — {} levels, {:.0} USDT",
                self.asks.len(),
                self.ask_depth
            )
        };
        out.push_str(&t::subsection_header(&ask_label));
        out.push('\n');
        for level in self.asks.iter().take(8) {
            out.push_str(&t::orderbook_level(
                level.price,
                level.quantity,
                base_symbol,
                level.value(),
                self.peg_target,
            ));
            out.push('\n');
        }
        if self.asks.len() > 8 {
            out.push_str(&t::blank_row());
            out.push_str(&format!("    ... +{} more levels\n", self.asks.len() - 8));
        }

        // Bid side
        let bid_label = if self.bid_outliers > 0 {
            format!(
                "Bid Side — {} levels, {:.0} USDT (+{} outliers excl.)",
                self.bids.len(),
                self.bid_depth,
                self.bid_outliers
            )
        } else {
            format!(
                "Bid Side — {} levels, {:.0} USDT",
                self.bids.len(),
                self.bid_depth
            )
        };
        out.push_str(&t::subsection_header(&bid_label));
        out.push('\n');
        for level in self.bids.iter().take(8) {
            out.push_str(&t::orderbook_level(
                level.price,
                level.quantity,
                base_symbol,
                level.value(),
                self.peg_target,
            ));
            out.push('\n');
        }
        if self.bids.len() > 8 {
            out.push_str(&t::blank_row());
            out.push_str(&format!("    ... +{} more levels\n", self.bids.len() - 8));
        }

        // Health checks
        out.push_str(&t::subsection_header("Health Checks"));
        out.push('\n');
        for check in &self.checks {
            match check {
                HealthCheck::Pass(msg) => {
                    out.push_str(&t::check_pass(msg));
                    out.push('\n');
                }
                HealthCheck::Fail(msg) => {
                    out.push_str(&t::check_fail(msg));
                    out.push('\n');
                }
            }
        }
        out.push_str(&t::blank_row());
        out.push('\n');
        out.push_str(&t::status_line(self.healthy));
        out.push('\n');
        out.push_str(&t::section_footer());
        out.push('\n');

        out
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    /// Side of `qtys.len()` levels stepping away from `start` by `step` per level.
    fn side(start: f64, step: f64, qtys: &[f64]) -> Vec<OrderBookLevel> {
        qtys.iter()
            .enumerate()
            .map(|(i, &quantity)| OrderBookLevel {
                price: start + step * i as f64,
                quantity,
            })
            .collect()
    }

    /// Book that passes every default check: 10 levels × 400 per side near peg.
    fn healthy_book() -> OrderBook {
        OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: side(0.9999, -0.0001, &[400.0; 10]),
            asks: side(1.0001, 0.0001, &[400.0; 10]),
        }
    }

    fn summarize(book: &OrderBook) -> MarketSummary {
        MarketSummary::from_order_book(book, &HealthThresholds::default(), None)
    }

    fn failed(summary: &MarketSummary) -> Vec<String> {
        summary
            .checks
            .iter()
            .filter_map(|c| match c {
                HealthCheck::Fail(m) => Some(m.clone()),
                HealthCheck::Pass(_) => None,
            })
            .collect()
    }

    #[test]
    fn test_market_summary_from_order_book() {
        let summary = summarize(&healthy_book());

        assert!(summary.healthy, "{:?}", failed(&summary));
        assert_eq!(summary.bids.len(), 10);
        assert_eq!(summary.asks.len(), 10);
        assert!(summary.bid_depth > 3000.0);
        assert!(summary.ask_depth > 3000.0);
    }

    #[test]
    fn test_peg_comes_from_thresholds() {
        // Asks at 1.0001+ are below a 1.01 peg, so the peg check must fail.
        // Before, callers passed a literal 1.0 and --peg had no effect.
        let thresholds = HealthThresholds {
            peg_target: 1.01,
            peg_range: 0.01,
            ..HealthThresholds::default()
        };
        let summary = MarketSummary::from_order_book(&healthy_book(), &thresholds, None);
        assert_eq!(summary.peg_target, 1.01);
        assert!(
            failed(&summary).iter().any(|m| m.contains("below peg")),
            "{:?}",
            failed(&summary)
        );
    }

    #[test]
    fn test_default_criteria_values() {
        // Pins the agreed "healthy" spec so a silent default change fails here.
        let t = HealthThresholds::default();
        assert_eq!(t.min_levels, 10);
        assert_eq!(t.max_spread_pct, 3.0);
        assert_eq!(t.min_top3_depth, 300.0);
        assert_eq!(t.min_top10_depth, 2000.0);
        assert_eq!(t.min_depth, 3000.0);
    }

    #[test]
    fn test_nine_levels_is_unhealthy() {
        let mut book = healthy_book();
        // Keep total depth high so only the level-count rule can fail.
        book.bids = side(0.9999, -0.0001, &[1000.0; 9]);
        let summary = summarize(&book);
        assert!(!summary.healthy);
        assert_eq!(failed(&summary), vec!["Bid levels: 9 < 10 minimum"]);
    }

    #[test]
    fn test_zero_quantity_level_is_not_valid() {
        let mut book = healthy_book();
        book.asks[9].quantity = 0.0;
        book.asks.push(OrderBookLevel {
            price: 1.0011,
            quantity: 0.0,
        });
        let summary = summarize(&book);
        assert!(
            failed(&summary).contains(&"Ask levels: 9 < 10 minimum".to_string()),
            "{:?}",
            failed(&summary)
        );
    }

    #[test]
    fn test_spread_over_three_percent_is_unhealthy() {
        let mut book = healthy_book();
        // Best ask 1.0400 vs best bid 0.9999: ~3.94% of mid.
        book.asks = side(1.04, 0.0001, &[400.0; 10]);
        let summary = summarize(&book);
        assert!(!summary.healthy);
        assert!(
            failed(&summary).iter().any(|m| m.starts_with("Spread:")),
            "{:?}",
            failed(&summary)
        );
    }

    #[test]
    fn test_spread_under_three_percent_passes_spread_check() {
        let mut book = healthy_book();
        // Best ask 1.0200 vs best bid 0.9999: ~1.98% of mid.
        book.asks = side(1.02, 0.0001, &[400.0; 10]);
        let summary = summarize(&book);
        assert!(
            !failed(&summary).iter().any(|m| m.starts_with("Spread:")),
            "{:?}",
            failed(&summary)
        );
    }

    #[test]
    fn test_thin_top3_is_unhealthy_even_with_deep_book() {
        let mut book = healthy_book();
        // Top 3 hold ~150 USDT; levels 4-10 hold 3500, so only top-3 fails.
        let mut qtys = vec![50.0; 3];
        qtys.extend([500.0; 7]);
        book.bids = side(0.9999, -0.0001, &qtys);
        let summary = summarize(&book);
        assert_eq!(
            failed(&summary),
            vec!["Bid top-3 depth: 150 USDT < 300 USDT minimum"]
        );
    }

    #[test]
    fn test_top10_counts_only_first_ten_levels() {
        let mut book = healthy_book();
        // First 10 levels hold ~1500; level 11 adds 2000 so total depth passes.
        let mut qtys = vec![150.0; 10];
        qtys.push(2000.0);
        book.asks = side(1.0001, 0.0001, &qtys);
        let summary = summarize(&book);
        assert!(summary.ask_depth >= 3000.0);
        let fails = failed(&summary);
        assert_eq!(fails.len(), 1, "{fails:?}");
        assert!(fails[0].starts_with("Ask top-10 depth:"), "{fails:?}");
    }

    #[test]
    fn test_format_text_with_chain() {
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: vec![OrderBookLevel {
                price: 1.0,
                quantity: 100.0,
            }],
            asks: vec![OrderBookLevel {
                price: 1.0,
                quantity: 100.0,
            }],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let out = summary.format_text(Some("biconomy"));
        assert!(out.contains("biconomy"));
        assert!(out.contains("Venue"));
    }

    #[test]
    fn test_format_text_without_chain() {
        let book = OrderBook {
            pair: "X/Y".to_string(),
            bids: vec![OrderBookLevel {
                price: 1.0,
                quantity: 10.0,
            }],
            asks: vec![],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let out = summary.format_text(None);
        assert!(out.contains("X/Y"));
        assert!(!out.contains("Venue"));
    }

    #[test]
    fn test_health_check_sells_below_peg() {
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: vec![OrderBookLevel {
                price: 0.9995,
                quantity: 1000.0,
            }],
            asks: vec![
                OrderBookLevel {
                    price: 0.9990,
                    quantity: 100.0,
                }, // below peg
                OrderBookLevel {
                    price: 1.0001,
                    quantity: 500.0,
                },
            ],
        };

        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);

        assert!(!summary.healthy);
        let has_fail = summary
            .checks
            .iter()
            .any(|c| matches!(c, HealthCheck::Fail(m) if m.contains("sell")));
        assert!(has_fail);
    }

    #[test]
    fn test_format_text_with_volume_and_spread() {
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: vec![
                OrderBookLevel {
                    price: 0.9999,
                    quantity: 1000.0,
                },
                OrderBookLevel {
                    price: 0.9998,
                    quantity: 1000.0,
                },
            ],
            asks: vec![
                OrderBookLevel {
                    price: 1.0001,
                    quantity: 1000.0,
                },
                OrderBookLevel {
                    price: 1.0002,
                    quantity: 1000.0,
                },
            ],
        };
        let summary =
            MarketSummary::from_order_book(&book, &HealthThresholds::default(), Some(50_000.0));
        let out = summary.format_text(Some("binance"));
        assert!(out.contains("Volume (24h)"));
        assert!(out.contains("50000"));
        assert!(out.contains("Spread"));
    }

    #[test]
    fn test_format_text_with_outliers_and_many_levels() {
        // Book with levels outside peg range (peg_range*5 = 0.005) -> outliers
        // price_lo=0.995, price_hi=1.005 - asks above 1.005 excluded
        let mut asks: Vec<OrderBookLevel> = (0..12)
            .map(|i| OrderBookLevel {
                price: 1.0 + 0.0001 * (i + 1) as f64, // 1.0001 .. 1.0012
                quantity: 500.0,
            })
            .collect();
        asks.push(OrderBookLevel {
            price: 1.01, // outlier
            quantity: 100.0,
        });
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: vec![
                OrderBookLevel {
                    price: 0.9999,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 0.9998,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 0.9997,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 0.9996,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 0.9995,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 0.9994,
                    quantity: 600.0,
                },
            ],
            asks,
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let out = summary.format_text(None);
        assert!(
            out.contains("outliers excl.") || summary.ask_outliers > 0 || summary.bid_outliers > 0
        );
        assert!(out.contains("... +")); // truncation for > 8 levels
    }

    #[test]
    fn test_format_text_execution_fillable() {
        // Sufficient liquidity for 10k buy/sell -> fillable
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids: vec![OrderBookLevel {
                price: 0.9999,
                quantity: 20_000.0,
            }],
            asks: vec![OrderBookLevel {
                price: 1.0001,
                quantity: 20_000.0,
            }],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let out = summary.format_text(Some("cex"));
        assert!(out.contains("Exec 10K buy"));
        assert!(out.contains("Exec 10K sell"));
        assert!(out.contains("slippage") || out.contains("insufficient"));
    }

    #[test]
    fn test_format_text_bid_outliers_and_many_bid_levels() {
        // Many bid levels + bid outlier → covers lines 328-330, 354-355
        let mut bids: Vec<OrderBookLevel> = (0..12)
            .map(|i| OrderBookLevel {
                price: 1.0 - 0.0001 * (i + 1) as f64,
                quantity: 500.0,
            })
            .collect();
        bids.push(OrderBookLevel {
            price: 0.98, // bid outlier far below peg
            quantity: 100.0,
        });
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            bids,
            asks: vec![
                OrderBookLevel {
                    price: 1.0001,
                    quantity: 600.0,
                },
                OrderBookLevel {
                    price: 1.0002,
                    quantity: 600.0,
                },
            ],
        };
        let summary = MarketSummary::from_order_book(&book, &HealthThresholds::default(), None);
        let out = summary.format_text(None);
        assert!(summary.bid_outliers > 0);
        assert!(out.contains("outliers excl."));
        assert!(out.contains("... +"));
    }
}