scope-bca-core 0.8.2

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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
//! Bot-pattern signals in a venue's recent trades and order book, for the
//! market summary's health advisory.
//!
//! Market making is legitimate, so a signal never fails a summary: it warns,
//! with the evidence, where the tape or the book looks machine-made. The
//! signals:
//!
//! - **Repeated sizes:** one exact trade size makes up a large share of the
//!   tape, or a few sizes make up half of it.
//! - **Metronome timing:** trades come at an almost fixed interval.
//! - **Cadence:** most gaps between trades are one interval, even when a bot
//!   trades in bursts with pauses between them (so the gaps as a whole are
//!   not a metronome).
//! - **Ping-pong:** a buy and a sell of the same size at nearly the same
//!   price, seconds apart (the shape of wash trading).
//! - **Ladder quotes:** consecutive book levels at even price steps whose
//!   sizes are equal, or rise or fall level by level (a quoting curve).
//!
//! The functions are pure: they read trades and levels and fetch nothing.

use super::types::{BookSide, OrderBookLevel, Trade, TradeSide};
use serde::Serialize;

/// How many recent trades the summary asks the venue for.
pub const TRADE_SAMPLE: u32 = 500;

/// Fewest trades the tape signals need. Below this they are not judged.
pub const MIN_TRADES: usize = 30;

/// One exact size in at least this share of the trades is a signal.
pub const REPEATED_SIZE_SHARE: f64 = 0.30;

/// How many sizes the few-sizes signal adds up.
pub const FEW_SIZES: usize = 3;

/// The [`FEW_SIZES`] most common sizes in at least this share of the trades
/// are a signal.
pub const FEW_SIZES_SHARE: f64 = 0.50;

/// A size counts toward the few-sizes signal only with at least this share
/// of the trades on its own.
pub const FEW_SIZES_MIN_SHARE: f64 = 0.05;

/// Fewest gaps between trade events the timing signal needs.
pub const MIN_GAPS: usize = 20;

/// Gaps whose standard deviation is under this share of their mean are a
/// metronome.
pub const METRONOME_MAX_CV: f64 = 0.10;

/// Gaps within this share of an interval count as that interval.
pub const CADENCE_TOLERANCE: f64 = 0.02;

/// Gaps at one interval, as a share of all gaps, at or above this are a
/// cadence. Random arrivals put at most about 1.5% of gaps in any ±2% band.
pub const CADENCE_SHARE: f64 = 0.30;

/// Shortest interval the cadence signal judges: some venues print whole
/// seconds, which would put many short random gaps on one value.
pub const CADENCE_MIN_GAP_MS: f64 = 5_000.0;

/// A ping-pong pair is at most this far apart in time.
pub const PING_PONG_WINDOW_MS: u64 = 5_000;

/// A ping-pong pair's prices differ by at most this, in percent.
pub const PING_PONG_PRICE_TOLERANCE_PCT: f64 = 0.05;

/// Trades in ping-pong pairs, as a share of all trades, at or above this
/// are a signal.
pub const PING_PONG_SHARE: f64 = 0.20;

/// Fewest ping-pong pairs that count as a signal.
pub const MIN_PING_PONG_PAIRS: usize = 5;

/// Fewest consecutive levels that make a ladder.
pub const LADDER_MIN_LEVELS: usize = 8;

/// Levels of a ladder differ in size by at most this share.
pub const LADDER_SIZE_TOLERANCE: f64 = 0.01;

/// Price steps of a ladder differ by at most this share of the first step.
pub const LADDER_STEP_TOLERANCE: f64 = 0.05;

/// How many levels from the top of each side the ladder signal reads.
pub const LADDER_DEPTH: usize = 25;

/// Sizes are compared at this many decimal places, so that floats parsed
/// from the same decimal string compare equal.
const SIZE_DECIMALS: f64 = 1e8;

/// One signal that was found, with its evidence.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Finding {
    /// `count` of `of` trades have the exact size `size` (base units).
    RepeatedSize { size: f64, count: usize, of: usize },
    /// `count` of `of` trades have one of the exact sizes `sizes`, most
    /// common first.
    FewSizes {
        sizes: Vec<f64>,
        count: usize,
        of: usize,
    },
    /// Gaps between trade events average `mean_gap_ms`, with a coefficient
    /// of variation `cv`, over `gaps` gaps. `dominant_size` is set when the
    /// cadence is that of the repeated-size trades only.
    Metronome {
        mean_gap_ms: f64,
        cv: f64,
        gaps: usize,
        dominant_size: Option<f64>,
    },
    /// `share` of `gaps` gaps between trade events are `gap_ms` apart
    /// (within [`CADENCE_TOLERANCE`]).
    Cadence {
        gap_ms: f64,
        share: f64,
        gaps: usize,
    },
    /// `pairs` buy/sell pairs of the same size, close in time and price,
    /// cover `share` of the trades.
    PingPong { pairs: usize, share: f64 },
    /// `levels` consecutive `side` levels at steps of about `step_pct`
    /// percent, from `size` at the first to `last_size` (base units),
    /// shaped as `shape`.
    Ladder {
        side: BookSide,
        levels: usize,
        shape: LadderShape,
        size: f64,
        last_size: f64,
        step_pct: f64,
    },
}

/// How a ladder's sizes run, from the best level out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LadderShape {
    /// One size at every level.
    Even,
    /// Each level is smaller than or as large as the one before.
    Falling,
    /// Each level is larger than or as large as the one before.
    Rising,
}

/// The bot-pattern result of one summary.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BotPatterns {
    /// Trades the tape signals read (0 when there was no tape).
    pub trades_sampled: usize,
    /// Why the tape signals did not run, when they did not.
    pub tape_note: Option<String>,
    /// The signals found.
    pub findings: Vec<Finding>,
    /// Share of the sampled trades, in percent, that a repeated-size or
    /// ping-pong signal covers. Reported only: it changes no volume figure.
    pub bot_like_pct: Option<f64>,
    /// The same trades' share of the sampled volume (price × quantity), in
    /// percent: many tiny bot trades can be little of the volume.
    pub bot_like_volume_pct: Option<f64>,
    /// True when a real exchange book was read for ladders.
    pub book_checked: bool,
}

/// A trade size as a comparable key.
fn size_key(quantity: f64) -> i64 {
    (quantity * SIZE_DECIMALS).round() as i64
}

/// The exact sizes, most common first, each with the trades that have it.
fn sizes_by_count(trades: &[Trade]) -> Vec<(f64, Vec<usize>)> {
    let mut by_size: std::collections::HashMap<i64, Vec<usize>> = Default::default();
    for (i, t) in trades.iter().enumerate() {
        if t.quantity > 0.0 {
            by_size.entry(size_key(t.quantity)).or_default().push(i);
        }
    }
    let mut sizes: Vec<Vec<usize>> = by_size.into_values().collect();
    // Ties go to the size seen first, so the order does not depend on the
    // hash order.
    sizes.sort_by(|a, b| b.len().cmp(&a.len()).then(a[0].cmp(&b[0])));
    sizes
        .into_iter()
        .map(|idx| (trades[idx[0]].quantity, idx))
        .collect()
}

/// The most common exact size and the trades that have it.
fn dominant_size(trades: &[Trade]) -> Option<(f64, Vec<usize>)> {
    sizes_by_count(trades).into_iter().next()
}

/// Repeated sizes: the dominant size and the trades it covers, when it
/// reaches [`REPEATED_SIZE_SHARE`].
pub fn repeated_size(trades: &[Trade]) -> Option<(Finding, Vec<usize>)> {
    if trades.len() < MIN_TRADES {
        return None;
    }
    let (size, idx) = dominant_size(trades)?;
    (idx.len() as f64 / trades.len() as f64 >= REPEATED_SIZE_SHARE).then_some((
        Finding::RepeatedSize {
            size,
            count: idx.len(),
            of: trades.len(),
        },
        idx,
    ))
}

/// Few sizes: the [`FEW_SIZES`] most common sizes (each with at least
/// [`FEW_SIZES_MIN_SHARE`]) cover [`FEW_SIZES_SHARE`] of the trades. A bot
/// that rotates through a few sizes passes under [`repeated_size`].
pub fn few_sizes(trades: &[Trade]) -> Option<(Finding, Vec<usize>)> {
    if trades.len() < MIN_TRADES {
        return None;
    }
    let n = trades.len() as f64;
    let top: Vec<(f64, Vec<usize>)> = sizes_by_count(trades)
        .into_iter()
        .take(FEW_SIZES)
        .filter(|(_, idx)| idx.len() as f64 / n >= FEW_SIZES_MIN_SHARE)
        .collect();
    let idx: Vec<usize> = top
        .iter()
        .flat_map(|(_, idx)| idx.iter().copied())
        .collect();
    (top.len() > 1 && idx.len() as f64 / n >= FEW_SIZES_SHARE).then(|| {
        (
            Finding::FewSizes {
                sizes: top.iter().map(|(s, _)| *s).collect(),
                count: idx.len(),
                of: trades.len(),
            },
            idx,
        )
    })
}

/// Gaps between trade events. Trades with the same timestamp are one event:
/// one taker order that fills several makers prints them together.
fn event_gaps(mut times: Vec<u64>) -> Vec<f64> {
    times.sort_unstable();
    times.dedup();
    times.windows(2).map(|w| (w[1] - w[0]) as f64).collect()
}

/// Mean and coefficient of variation of `gaps`.
fn mean_cv(gaps: &[f64]) -> Option<(f64, f64)> {
    let n = gaps.len() as f64;
    let mean = gaps.iter().sum::<f64>() / n;
    if mean <= 0.0 {
        return None;
    }
    let var = gaps.iter().map(|g| (g - mean).powi(2)).sum::<f64>() / n;
    Some((mean, var.sqrt() / mean))
}

/// Metronome timing: the whole tape, else the dominant size's trades, at a
/// near-fixed interval.
pub fn metronome(trades: &[Trade]) -> Option<Finding> {
    if trades.len() < MIN_TRADES {
        return None;
    }
    let judge = |times: Vec<u64>, dominant: Option<f64>| {
        let gaps = event_gaps(times);
        if gaps.len() < MIN_GAPS {
            return None;
        }
        let (mean, cv) = mean_cv(&gaps)?;
        (cv < METRONOME_MAX_CV).then_some(Finding::Metronome {
            mean_gap_ms: mean,
            cv,
            gaps: gaps.len(),
            dominant_size: dominant,
        })
    };
    judge(trades.iter().map(|t| t.timestamp_ms).collect(), None).or_else(|| {
        let (size, idx) = dominant_size(trades)?;
        judge(
            idx.iter().map(|&i| trades[i].timestamp_ms).collect(),
            Some(size),
        )
    })
}

/// Cadence: the interval (of at least [`CADENCE_MIN_GAP_MS`]) that the most
/// gaps between trade events are at, within [`CADENCE_TOLERANCE`], when
/// those gaps are at least [`CADENCE_SHARE`] of all gaps.
pub fn cadence(trades: &[Trade]) -> Option<Finding> {
    if trades.len() < MIN_TRADES {
        return None;
    }
    let mut gaps = event_gaps(trades.iter().map(|t| t.timestamp_ms).collect());
    if gaps.len() < MIN_GAPS {
        return None;
    }
    gaps.sort_by(f64::total_cmp);
    // For each gap as the interval, the gaps in its band: two pointers over
    // the sorted gaps.
    let (mut lo, mut hi) = (0, 0);
    let mut best: Option<(usize, usize)> = None; // (count, index of the interval)
    for (i, &g) in gaps.iter().enumerate() {
        if g < CADENCE_MIN_GAP_MS {
            continue;
        }
        while gaps[lo] < g * (1.0 - CADENCE_TOLERANCE) {
            lo += 1;
        }
        hi = hi.max(i);
        while hi + 1 < gaps.len() && gaps[hi + 1] <= g * (1.0 + CADENCE_TOLERANCE) {
            hi += 1;
        }
        let count = hi + 1 - lo;
        if best.is_none_or(|(c, _)| count > c) {
            best = Some((count, i));
        }
    }
    let (count, i) = best?;
    let share = count as f64 / gaps.len() as f64;
    (share >= CADENCE_SHARE).then_some(Finding::Cadence {
        gap_ms: gaps[i],
        share,
        gaps: gaps.len(),
    })
}

/// Ping-pong: buy/sell pairs of the same size within
/// [`PING_PONG_WINDOW_MS`] and [`PING_PONG_PRICE_TOLERANCE_PCT`]. Each trade
/// is in one pair at most. Returns the finding and the paired trades.
pub fn ping_pong(trades: &[Trade]) -> Option<(Finding, Vec<usize>)> {
    if trades.len() < MIN_TRADES {
        return None;
    }
    let mut order: Vec<usize> = (0..trades.len()).collect();
    order.sort_by_key(|&i| trades[i].timestamp_ms);
    let mut paired = vec![false; trades.len()];
    let mut members = Vec::new();
    for (pos, &i) in order.iter().enumerate() {
        if paired[i] {
            continue;
        }
        let a = &trades[i];
        for &j in &order[pos + 1..] {
            let b = &trades[j];
            if b.timestamp_ms - a.timestamp_ms > PING_PONG_WINDOW_MS {
                break;
            }
            let opposite = matches!(
                (&a.side, &b.side),
                (TradeSide::Buy, TradeSide::Sell) | (TradeSide::Sell, TradeSide::Buy)
            );
            let near = a.price > 0.0
                && ((b.price - a.price).abs() / a.price * 100.0) <= PING_PONG_PRICE_TOLERANCE_PCT;
            if !paired[j] && opposite && near && size_key(a.quantity) == size_key(b.quantity) {
                paired[i] = true;
                paired[j] = true;
                members.extend([i, j]);
                break;
            }
        }
    }
    let pairs = members.len() / 2;
    let share = members.len() as f64 / trades.len() as f64;
    (pairs >= MIN_PING_PONG_PAIRS && share >= PING_PONG_SHARE)
        .then_some((Finding::PingPong { pairs, share }, members))
}

/// -1, 0 or 1 as `b` is smaller than, about (within
/// [`LADDER_SIZE_TOLERANCE`]) or larger than `a`.
fn size_direction(a: f64, b: f64) -> i8 {
    if (b - a).abs() <= a * LADDER_SIZE_TOLERANCE {
        0
    } else if b > a {
        1
    } else {
        -1
    }
}

/// The longest ladder in `levels` (best first): consecutive levels at about
/// one price step whose sizes stay equal or run one way, never both.
fn ladder_side(levels: &[OrderBookLevel], side: BookSide) -> Option<Finding> {
    let levels: Vec<&OrderBookLevel> = levels
        .iter()
        .filter(|l| l.price > 0.0 && l.quantity > 0.0)
        .take(LADDER_DEPTH)
        .collect();
    let mut best: Option<(usize, usize, i8)> = None; // (start, length, direction)
    let mut start = 0;
    while start + 1 < levels.len() {
        let step = (levels[start + 1].price - levels[start].price).abs();
        let mut dir = 0;
        let mut end = start + 1;
        while end < levels.len() {
            let this_step = (levels[end].price - levels[end - 1].price).abs();
            let same_step = step > 0.0 && (this_step - step).abs() <= step * LADDER_STEP_TOLERANCE;
            let d = size_direction(levels[end - 1].quantity, levels[end].quantity);
            if !same_step || (d != 0 && dir != 0 && d != dir) {
                break;
            }
            if d != 0 {
                dir = d;
            }
            end += 1;
        }
        let len = end - start;
        if best.is_none_or(|(_, l, _)| len > l) {
            best = Some((start, len, dir));
        }
        // The level a run ended on can start the next one (the top of a
        // falling curve after a rising first level).
        start = (end - 1).max(start + 1);
    }
    let (s, len, dir) = best?;
    if len < LADDER_MIN_LEVELS {
        return None;
    }
    let (first, last) = (levels[s].quantity, levels[s + len - 1].quantity);
    let even = levels[s..s + len]
        .iter()
        .all(|l| size_direction(first, l.quantity) == 0);
    let shape = match dir {
        _ if even => LadderShape::Even,
        1 => LadderShape::Rising,
        _ => LadderShape::Falling,
    };
    let step = (levels[s + 1].price - levels[s].price).abs();
    Some(Finding::Ladder {
        side,
        levels: len,
        shape,
        size: first,
        last_size: last,
        step_pct: step / levels[s].price * 100.0,
    })
}

/// Ladder quotes on either side of a real exchange book.
pub fn ladders(bids: &[OrderBookLevel], asks: &[OrderBookLevel]) -> Vec<Finding> {
    [
        ladder_side(bids, BookSide::Bid),
        ladder_side(asks, BookSide::Ask),
    ]
    .into_iter()
    .flatten()
    .collect()
}

/// Runs every signal. `trades` is the venue's recent tape, or why there is
/// none. `book` is the bids and asks of a real exchange book, or `None`
/// for a synthetic one (a DEX pool's curve is an even ladder by design).
pub fn detect(
    trades: Result<&[Trade], &str>,
    book: Option<(&[OrderBookLevel], &[OrderBookLevel])>,
) -> BotPatterns {
    let mut findings = Vec::new();
    let mut tape_note = None;
    let mut bot_like_pct = None;
    let mut bot_like_volume_pct = None;
    let mut sampled = 0;
    match trades {
        Err(why) => tape_note = Some(why.to_string()),
        Ok(t) if t.len() < MIN_TRADES => {
            sampled = t.len();
            tape_note = Some(format!(
                "only {} recent trades; the tape signals need {MIN_TRADES}",
                t.len()
            ));
        }
        Ok(t) => {
            sampled = t.len();
            let mut covered = vec![false; t.len()];
            // A few sizes only when no one size is enough on its own.
            if let Some((f, idx)) = repeated_size(t).or_else(|| few_sizes(t)) {
                idx.iter().for_each(|&i| covered[i] = true);
                findings.push(f);
            }
            // A cadence only when the gaps are not a metronome already.
            if let Some(f) = metronome(t).or_else(|| cadence(t)) {
                findings.push(f);
            }
            if let Some((f, idx)) = ping_pong(t) {
                idx.iter().for_each(|&i| covered[i] = true);
                findings.push(f);
            }
            let n = covered.iter().filter(|c| **c).count();
            bot_like_pct = Some(n as f64 / t.len() as f64 * 100.0);
            let value = |tr: &Trade| tr.quote_quantity.unwrap_or(tr.price * tr.quantity);
            let total: f64 = t.iter().map(value).sum();
            let bot: f64 = t
                .iter()
                .zip(&covered)
                .filter(|(_, c)| **c)
                .map(|(tr, _)| value(tr))
                .sum();
            bot_like_volume_pct = (total > 0.0).then(|| bot / total * 100.0);
        }
    }
    if let Some((bids, asks)) = book {
        findings.extend(ladders(bids, asks));
    }
    BotPatterns {
        trades_sampled: sampled,
        tape_note,
        findings,
        bot_like_pct,
        bot_like_volume_pct,
        book_checked: book.is_some(),
    }
}

/// A size or step in short form: up to 6 significant digits.
fn short(v: f64) -> String {
    let s = format!("{:.6}", v);
    let s = s.trim_end_matches('0').trim_end_matches('.');
    if v.abs() >= 1000.0 {
        format!("{v:.0}")
    } else {
        s.to_string()
    }
}

/// A price step in percent, to 2 significant digits: a 1-tick step of
/// 0.010002% reads `0.01`.
fn step(pct: f64) -> String {
    if pct <= 0.0 {
        return short(pct);
    }
    let decimals = (1 - pct.log10().floor() as i32).max(0) as usize;
    let s = format!("{pct:.decimals$}");
    if s.contains('.') {
        s.trim_end_matches('0').trim_end_matches('.').to_string()
    } else {
        s
    }
}

impl Finding {
    /// One clause of evidence for the advisory line.
    pub fn describe(&self) -> String {
        match self {
            Finding::RepeatedSize { size, count, of } => format!(
                "{:.0}% of {of} trades are exactly {}",
                *count as f64 / *of as f64 * 100.0,
                short(*size)
            ),
            Finding::Metronome {
                mean_gap_ms,
                cv,
                gaps,
                dominant_size,
            } => {
                let whose = dominant_size
                    .map(|s| format!("size-{} trades", short(s)))
                    .unwrap_or_else(|| "trades".to_string());
                format!(
                    "{whose} every {:.1}s ±{:.0}% over {gaps} gaps",
                    mean_gap_ms / 1000.0,
                    cv * 100.0
                )
            }
            Finding::FewSizes { sizes, count, of } => format!(
                "{:.0}% of {of} trades are one of {} sizes: {}",
                *count as f64 / *of as f64 * 100.0,
                sizes.len(),
                sizes
                    .iter()
                    .map(|s| short(*s))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Finding::Cadence {
                gap_ms,
                share,
                gaps,
            } => format!(
                "{:.0}% of {gaps} gaps between trades are {:.1}s ±{:.0}%",
                share * 100.0,
                gap_ms / 1000.0,
                CADENCE_TOLERANCE * 100.0
            ),
            Finding::PingPong { pairs, share } => format!(
                "{pairs} buy/sell ping-pong pairs ({:.0}% of trades)",
                share * 100.0
            ),
            Finding::Ladder {
                side,
                levels,
                shape,
                size,
                last_size,
                step_pct,
            } => {
                let side = match side {
                    BookSide::Bid => "bid",
                    BookSide::Ask => "ask",
                };
                let sizes = match shape {
                    LadderShape::Even => format!("× {}", short(*size)),
                    LadderShape::Falling => {
                        format!("falling {} → {}", short(*size), short(*last_size))
                    }
                    LadderShape::Rising => {
                        format!("rising {} → {}", short(*size), short(*last_size))
                    }
                };
                format!(
                    "{side} ladder of {levels} levels {sizes} at {}% steps",
                    step(*step_pct)
                )
            }
        }
    }
}

impl BotPatterns {
    /// The health check line. A finding warns; nothing found passes when
    /// the tape was read; with no tape and no ladder it does not apply.
    pub fn check(&self) -> super::types::HealthCheck {
        use super::types::HealthCheck;
        if !self.findings.is_empty() {
            let evidence: Vec<String> = self.findings.iter().map(Finding::describe).collect();
            let share = match (
                self.bot_like_pct.filter(|p| *p > 0.0),
                self.bot_like_volume_pct,
            ) {
                (Some(p), Some(v)) => {
                    format!("; {p:.0}% of sampled trades ({v:.1}% of their volume) look bot-made")
                }
                (Some(p), None) => format!("; {p:.0}% of sampled trades look bot-made"),
                _ => String::new(),
            };
            return HealthCheck::Warn(format!(
                "Bot patterns (likely market-making bots): {}{share}",
                evidence.join("; ")
            ));
        }
        let book = if self.book_checked {
            " or the book"
        } else {
            ""
        };
        match &self.tape_note {
            None => HealthCheck::Pass(format!(
                "No bot patterns in {} recent trades{book}",
                self.trades_sampled
            )),
            Some(why) if self.book_checked => HealthCheck::NotApplicable(format!(
                "Bot patterns: no ladder in the book; trades not checked ({why})"
            )),
            Some(why) => HealthCheck::NotApplicable(format!("Bot patterns: not checked ({why})")),
        }
    }
}

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

    fn trade(ms: u64, price: f64, qty: f64, side: TradeSide) -> Trade {
        Trade {
            price,
            quantity: qty,
            quote_quantity: None,
            timestamp_ms: ms,
            side,
            id: None,
        }
    }

    /// An organic-looking tape: varied sizes, irregular gaps, sides mixed.
    fn organic(n: usize) -> Vec<Trade> {
        let mut ms = 1_000_000;
        (0..n)
            .map(|i| {
                ms += 300 + (i as u64 * 7919) % 4_000;
                let qty = 10.0 + ((i * 37) % 97) as f64 * 1.37;
                let side = if (i * 13) % 3 == 0 {
                    TradeSide::Buy
                } else {
                    TradeSide::Sell
                };
                trade(ms, 1.0 + ((i * 11) % 7) as f64 * 0.0001, qty, side)
            })
            .collect()
    }

    fn level(price: f64, quantity: f64) -> OrderBookLevel {
        OrderBookLevel { price, quantity }
    }

    #[test]
    fn test_an_organic_tape_and_book_show_nothing() {
        let t = organic(200);
        let bids: Vec<_> = (0..20)
            .map(|i| {
                level(
                    0.999 - i as f64 * 0.0001 * (1.0 + (i % 3) as f64),
                    100.0 + (i * 53 % 211) as f64,
                )
            })
            .collect();
        let p = detect(Ok(&t), Some((&bids, &[])));
        assert!(p.findings.is_empty(), "{:?}", p.findings);
        assert_eq!(p.bot_like_pct, Some(0.0));
        assert!(matches!(
            p.check(),
            crate::market::types::HealthCheck::Pass(_)
        ));
    }

    #[test]
    fn test_one_size_in_a_third_of_the_tape_is_repeated_size() {
        let mut t = organic(100);
        for tr in t.iter_mut().step_by(3) {
            tr.quantity = 1000.0;
        }
        let (f, idx) = repeated_size(&t).unwrap();
        assert_eq!(idx.len(), 34);
        assert!(matches!(f, Finding::RepeatedSize { size, count: 34, of: 100 } if size == 1000.0));
        assert!(
            f.describe().contains("34% of 100 trades are exactly 1000"),
            "{}",
            f.describe()
        );
        // A quarter is not enough.
        let mut t = organic(100);
        for tr in t.iter_mut().step_by(4) {
            tr.quantity = 1000.0;
        }
        assert!(repeated_size(&t).is_none());
    }

    #[test]
    fn test_a_fixed_cadence_is_a_metronome_and_same_ms_fills_are_one_event() {
        // 60 trades every 2s, some printed twice in the same millisecond.
        let mut t = Vec::new();
        for i in 0..60u64 {
            t.push(trade(i * 2_000, 1.0, 5.0 + i as f64, TradeSide::Buy));
            if i % 5 == 0 {
                t.push(trade(i * 2_000, 1.0, 7.0, TradeSide::Buy));
            }
        }
        let Some(Finding::Metronome {
            mean_gap_ms,
            cv,
            dominant_size: None,
            ..
        }) = metronome(&t)
        else {
            panic!("no metronome")
        };
        assert_eq!(mean_gap_ms, 2_000.0);
        assert!(cv < 1e-9);
        assert!(metronome(&organic(200)).is_none());
    }

    #[test]
    fn test_a_bot_cadence_hidden_in_organic_trades_is_found_by_its_size() {
        // Organic trades plus a bot printing size 250 every 3s.
        let mut t = organic(80);
        let start = t[0].timestamp_ms;
        for i in 0..45u64 {
            t.push(trade(start + 7 + i * 3_000, 1.0, 250.0, TradeSide::Sell));
        }
        let Some(Finding::Metronome {
            dominant_size: Some(s),
            mean_gap_ms,
            ..
        }) = metronome(&t)
        else {
            panic!("no metronome: {:?}", metronome(&t))
        };
        assert_eq!(s, 250.0);
        assert_eq!(mean_gap_ms, 3_000.0);
    }

    #[test]
    fn test_buy_sell_pairs_of_one_size_are_ping_pong() {
        let mut t = organic(60);
        let start = t.last().unwrap().timestamp_ms + 10_000;
        for i in 0..15u64 {
            let ms = start + i * 20_000;
            let qty = 100.0 + i as f64; // a new size per pair
            t.push(trade(ms, 1.0, qty, TradeSide::Buy));
            t.push(trade(ms + 800, 1.0002, qty, TradeSide::Sell));
        }
        let (f, idx) = ping_pong(&t).unwrap();
        assert_eq!(idx.len(), 30);
        assert!(matches!(f, Finding::PingPong { pairs: 15, .. }), "{f:?}");
        // Too far apart in time, or in price, is not a pair.
        let mut slow = organic(60);
        for i in 0..15u64 {
            let ms = 9_000_000 + i * 20_000;
            slow.push(trade(ms, 1.0, 50.5, TradeSide::Buy));
            slow.push(trade(
                ms + PING_PONG_WINDOW_MS + 1,
                1.0,
                50.5,
                TradeSide::Sell,
            ));
        }
        assert!(ping_pong(&slow).is_none());
        let mut far = organic(60);
        for i in 0..15u64 {
            let ms = 9_000_000 + i * 20_000;
            far.push(trade(ms, 1.0, 50.5, TradeSide::Buy));
            far.push(trade(ms + 100, 1.01, 50.5, TradeSide::Sell));
        }
        assert!(ping_pong(&far).is_none());
    }

    #[test]
    fn test_many_dust_bot_trades_are_little_of_the_volume() {
        // Seen live on BTC/USDT: most trades are one tiny size.
        let mut t: Vec<Trade> = (0..90)
            .map(|i| trade(1_000 + i * 977, 100.0, 0.001, TradeSide::Buy))
            .collect();
        t.extend(
            (0..10).map(|i| trade(500_000 + i * 3_331, 100.0, 50.0 + i as f64, TradeSide::Sell)),
        );
        let p = detect(Ok(&t), None);
        assert_eq!(p.bot_like_pct, Some(90.0));
        let v = p.bot_like_volume_pct.unwrap();
        assert!(v < 0.05, "{v}");
        let crate::market::types::HealthCheck::Warn(m) = p.check() else {
            panic!()
        };
        assert!(
            m.contains("90% of sampled trades (0.0% of their volume) look bot-made"),
            "{m}"
        );
    }

    #[test]
    fn test_equal_levels_at_even_steps_are_a_ladder() {
        let asks: Vec<_> = (0..12)
            .map(|i| level(1.0001 + i as f64 * 0.0001, 5_000.0))
            .collect();
        // Even steps, but sizes up and down: no ladder.
        let bids: Vec<_> = (0..12)
            .map(|i| level(0.9999 - i as f64 * 0.0001, 100.0 + (i * 53 % 211) as f64))
            .collect();
        let found = ladders(&bids, &asks);
        assert_eq!(found.len(), 1);
        let Finding::Ladder {
            side,
            levels,
            shape,
            size,
            step_pct,
            ..
        } = &found[0]
        else {
            panic!()
        };
        assert_eq!(
            (*side, *levels, *shape, *size),
            (BookSide::Ask, 12, LadderShape::Even, 5_000.0)
        );
        assert!((step_pct - 0.01).abs() < 0.001, "{step_pct}");
        // Seven levels are not a ladder.
        let short_run: Vec<_> = (0..7)
            .map(|i| level(1.0 + i as f64 * 0.0001, 5_000.0))
            .collect();
        assert!(ladders(&[], &short_run).is_empty());
    }

    #[test]
    fn test_findings_warn_with_their_evidence_and_the_bot_like_share() {
        let mut t = organic(100);
        for tr in t.iter_mut().step_by(2) {
            tr.quantity = 1000.0;
        }
        let p = detect(Ok(&t), None);
        let crate::market::types::HealthCheck::Warn(m) = p.check() else {
            panic!("{:?}", p.check())
        };
        assert!(
            m.starts_with(
                "Bot patterns (likely market-making bots): 50% of 100 trades are exactly 1000"
            ),
            "{m}"
        );
        assert!(m.contains("50% of sampled trades ("), "{m}");
        assert!(m.contains("% of their volume) look bot-made"), "{m}");
        assert_eq!(p.bot_like_pct, Some(50.0));
    }

    #[test]
    fn test_no_tape_or_a_short_tape_says_why_and_still_reads_the_book() {
        let p = detect(Err("the venue gives no trade feed"), None);
        assert_eq!(p.trades_sampled, 0);
        let crate::market::types::HealthCheck::NotApplicable(m) = p.check() else {
            panic!()
        };
        assert!(m.contains("the venue gives no trade feed"), "{m}");
        // A ladder still warns without a tape.
        let asks: Vec<_> = (0..10)
            .map(|i| level(1.0 + i as f64 * 0.001, 42.0))
            .collect();
        let p = detect(Err("x"), Some((&[], &asks)));
        assert!(matches!(
            p.check(),
            crate::market::types::HealthCheck::Warn(_)
        ));
        // Fewer than MIN_TRADES: the tape signals do not run.
        let t = organic(MIN_TRADES - 1);
        let p = detect(Ok(&t), None);
        assert!(p.tape_note.unwrap().contains("only 29 recent trades"));
        assert!(p.bot_like_pct.is_none());
    }

    #[test]
    fn test_each_tape_signal_alone_refuses_a_short_tape() {
        // detect() checks the length first, but the signals are public and
        // must not judge a tape too short on their own either: 29 trades of
        // one size, every 2s, in buy/sell pairs, would trip all three.
        let t: Vec<Trade> = (0..MIN_TRADES as u64 - 1)
            .map(|i| {
                let side = if i % 2 == 0 {
                    TradeSide::Buy
                } else {
                    TradeSide::Sell
                };
                trade(i * 2_000, 1.0, 10.0, side)
            })
            .collect();
        assert!(repeated_size(&t).is_none());
        assert!(metronome(&t).is_none());
        assert!(ping_pong(&t).is_none());
    }

    #[test]
    fn test_a_bid_ladder_is_described_as_a_bid_ladder() {
        let bids: Vec<_> = (0..9)
            .map(|i| level(0.999 - i as f64 * 0.001, 250.0))
            .collect();
        let found = ladders(&bids, &[]);
        assert_eq!(found.len(), 1);
        let d = found[0].describe();
        assert!(d.starts_with("bid ladder of 9 levels × 250 at "), "{d}");
    }

    #[test]
    fn test_a_tape_with_no_volume_gives_the_trade_share_only() {
        // Zero-price prints have no volume to take a share of, so the
        // advisory gives the trade share alone.
        let t: Vec<Trade> = (0..40)
            .map(|i| trade(1_000 + i * 977, 0.0, 3.0, TradeSide::Buy))
            .collect();
        let p = detect(Ok(&t), None);
        assert_eq!(p.bot_like_pct, Some(100.0));
        assert_eq!(p.bot_like_volume_pct, None);
        let crate::market::types::HealthCheck::Warn(m) = p.check() else {
            panic!("{:?}", p.check())
        };
        assert!(m.ends_with("; 100% of sampled trades look bot-made"), "{m}");
    }

    /// The USDN/USDT book on weex, read live on 2026-10-24: ten levels a
    /// side at one tick, sizes falling level by level from the second.
    fn weex_book() -> (Vec<OrderBookLevel>, Vec<OrderBookLevel>) {
        let bids = [
            (0.9999, 410.046),
            (0.9998, 540.108),
            (0.9997, 450.135),
            (0.9996, 370.148),
            (0.9995, 370.185),
            (0.9994, 360.2161),
            (0.9993, 300.2101),
            (0.9992, 220.1761),
            (0.9991, 160.1441),
            (0.9990, 120.1201),
            (0.0022, 3636.3636),
        ];
        let asks = [
            (1.0001, 427.318),
            (1.0002, 1349.73),
            (1.0003, 1209.6371),
            (1.0004, 1029.5881),
            (1.0005, 959.5202),
            (1.0006, 919.4483),
            (1.0007, 799.4403),
            (1.0008, 619.5043),
            (1.0009, 399.6403),
            (1.0010, 299.7002),
            (1.0500, 4.8046),
        ];
        let side = |l: &[(f64, f64)]| l.iter().map(|&(p, q)| level(p, q)).collect();
        (side(&bids), side(&asks))
    }

    /// The USDN/USDT tape on weex, as its bot prints it: every ~29 minutes
    /// two sells, four buys of one size (498.11 or 68.01) exactly 45 s
    /// apart, then three shrinking buys, each 45 s after the last.
    fn weex_tape(cycles: u64) -> Vec<Trade> {
        let mut t = Vec::new();
        for c in 0..cycles {
            let start = 1_000_000 + c * 1_760_000;
            let burst = if c % 2 == 0 { 498.11 } else { 68.01 };
            let script = [
                (0.9999, 500.0, TradeSide::Sell),
                (0.9999, 60.05 + (c % 3) as f64 * 10.0, TradeSide::Sell),
                (1.0001, burst, TradeSide::Buy),
                (1.0001, burst, TradeSide::Buy),
                (1.0001, burst, TradeSide::Buy),
                (1.0001, burst, TradeSide::Buy),
                (1.0001, 300.0 + c as f64 * 7.3, TradeSide::Buy),
                (1.0001, 60.0 + c as f64 * 1.9, TradeSide::Buy),
                (1.0001, 12.0 + c as f64 * 0.37, TradeSide::Buy),
            ];
            for (k, (price, qty, side)) in script.into_iter().enumerate() {
                // A few ms of jitter, as the live prints have.
                let jitter = (c * 7 + k as u64 * 13) % 40;
                t.push(trade(start + k as u64 * 45_000 + jitter, price, qty, side));
            }
        }
        t
    }

    #[test]
    fn test_the_weex_usdn_bot_is_caught_on_the_tape_and_the_book() {
        let tape = weex_tape(40);
        let (bids, asks) = weex_book();
        let p = detect(Ok(&tape), Some((&bids, &asks)));
        let kinds: Vec<&str> = p
            .findings
            .iter()
            .map(|f| match f {
                Finding::RepeatedSize { .. } => "repeated",
                Finding::FewSizes { .. } => "few",
                Finding::Metronome { .. } => "metronome",
                Finding::Cadence { .. } => "cadence",
                Finding::PingPong { .. } => "ping-pong",
                Finding::Ladder { .. } => "ladder",
            })
            .collect();
        assert_eq!(
            kinds,
            ["few", "cadence", "ladder", "ladder"],
            "{:?}",
            p.findings
        );
        let crate::market::types::HealthCheck::Warn(m) = p.check() else {
            panic!("{:?}", p.check())
        };
        assert!(
            m.contains("trades are one of 3 sizes: 498.11, 68.01, 500"),
            "{m}"
        );
        assert!(m.contains("gaps between trades are 45.0s ±2%"), "{m}");
        assert!(
            m.contains("bid ladder of 9 levels falling 540.108 → 120.1201 at 0.01% steps"),
            "{m}"
        );
        assert!(
            m.contains("ask ladder of 9 levels falling 1350 → 299.7002 at 0.01% steps"),
            "{m}"
        );
    }

    #[test]
    fn test_a_few_sizes_in_half_the_tape_is_a_signal_one_rare_size_is_not() {
        let mut t = organic(100);
        for (i, tr) in t.iter_mut().enumerate() {
            match i % 10 {
                0 | 1 => tr.quantity = 498.11,
                2 | 3 => tr.quantity = 68.01,
                4 | 5 => tr.quantity = 500.0,
                _ => {}
            }
        }
        // 20 trades each, 60 in all; no one size reaches 30%.
        assert!(repeated_size(&t).is_none());
        let (f, idx) = few_sizes(&t).unwrap();
        assert_eq!(idx.len(), 60);
        assert!(
            matches!(&f, Finding::FewSizes { sizes, count: 60, of: 100 } if sizes == &[498.11, 68.01, 500.0]),
            "{f:?}"
        );
        // 45% is not half.
        let mut t = organic(100);
        for (i, tr) in t.iter_mut().enumerate() {
            if i % 20 < 9 {
                tr.quantity = if i % 2 == 0 { 498.11 } else { 68.01 };
            }
        }
        assert!(few_sizes(&t).is_none(), "{:?}", few_sizes(&t));
        assert!(few_sizes(&organic(200)).is_none());
    }

    #[test]
    fn test_short_tapes_and_few_gaps_are_not_judged() {
        let short_tape = weex_tape(3);
        assert!(short_tape.len() < MIN_TRADES);
        assert!(few_sizes(&short_tape).is_none());
        assert!(cadence(&short_tape).is_none());
        // Enough trades, but printed in fewer than MIN_GAPS + 1 instants.
        let bunched: Vec<Trade> = (0..60u64)
            .map(|i| trade((i % 10) * 45_000, 1.0, 5.0 + i as f64, TradeSide::Buy))
            .collect();
        assert!(cadence(&bunched).is_none());
        // Every trade in the same millisecond has no gaps to judge.
        let same: Vec<Trade> = (0..40)
            .map(|i| trade(7, 1.0, 5.0 + i as f64, TradeSide::Buy))
            .collect();
        assert!(metronome(&same).is_none());
    }

    #[test]
    fn test_steps_read_to_two_significant_digits() {
        assert_eq!(step(0.010002), "0.01");
        assert_eq!(step(0.123), "0.12");
        assert_eq!(step(0.5), "0.5");
        assert_eq!(step(12.3), "12");
        assert_eq!(step(0.0), "0");
    }

    #[test]
    fn test_bursts_at_one_interval_are_a_cadence_but_not_a_metronome() {
        let t = weex_tape(30);
        assert!(metronome(&t).is_none());
        let Some(Finding::Cadence { gap_ms, share, .. }) = cadence(&t) else {
            panic!("{:?}", cadence(&t))
        };
        assert!((gap_ms - 45_000.0).abs() < 50.0, "{gap_ms}");
        assert!(share > 0.85, "{share}");
        assert!(cadence(&organic(300)).is_none());
    }

    #[test]
    fn test_random_gaps_in_whole_seconds_are_not_a_cadence() {
        // Gaps of 1 to 40 s, printed in whole seconds, in a fixed mix.
        let mut ms = 0;
        let t: Vec<Trade> = (0..400u64)
            .map(|i| {
                ms += 1_000 * (1 + (i * 7919 + i * i * 31) % 40);
                trade(ms, 1.0, 5.0 + i as f64, TradeSide::Buy)
            })
            .collect();
        assert!(cadence(&t).is_none(), "{:?}", cadence(&t));
        // Short gaps are not judged, however regular in whole seconds.
        let fast: Vec<Trade> = (0..100u64)
            .map(|i| {
                trade(
                    i * 1_000 + (i % 2) * 2_000,
                    1.0,
                    5.0 + i as f64,
                    TradeSide::Buy,
                )
            })
            .collect();
        assert!(cadence(&fast).is_none(), "{:?}", cadence(&fast));
    }

    #[test]
    fn test_sizes_that_fall_or_rise_level_by_level_are_a_shaped_ladder() {
        let (bids, asks) = weex_book();
        let found = ladders(&bids, &asks);
        assert_eq!(found.len(), 2, "{found:?}");
        for f in &found {
            assert!(
                matches!(
                    f,
                    Finding::Ladder {
                        levels: 9,
                        shape: LadderShape::Falling,
                        ..
                    }
                ),
                "{f:?}"
            );
        }
        let rising: Vec<_> = (0..10)
            .map(|i| level(0.9999 - i as f64 * 0.0001, 100.0 + i as f64 * 25.0))
            .collect();
        let found = ladders(&rising, &[]);
        assert!(
            matches!(
                found[..],
                [Finding::Ladder {
                    levels: 10,
                    shape: LadderShape::Rising,
                    ..
                }]
            ),
            "{found:?}"
        );
        assert!(
            found[0].describe().contains("rising 100 → 325"),
            "{}",
            found[0].describe()
        );
        // Up then down then up: no ladder of 8.
        let zigzag: Vec<_> = [
            100.0, 200.0, 150.0, 300.0, 250.0, 400.0, 350.0, 500.0, 450.0,
        ]
        .iter()
        .enumerate()
        .map(|(i, &q)| level(1.0001 + i as f64 * 0.0001, q))
        .collect();
        assert!(ladders(&[], &zigzag).is_empty());
    }
}