scope-bca-cli 0.8.4

Scope Blockchain Analysis - Command-line interface library
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
//! # Market Command
//!
//! Reports peg and order book health for stablecoin markets.
//! Fetches level-2 depth from CEX (Binance, Biconomy) or DEX (Ethereum, Solana) venues
//! and runs configurable health checks including volume and execution estimates.
//! Supports one-shot or repeated runs with configurable frequency and duration.

use crate::cli::candles;
use crate::cli::crawl::{self, Period};
use crate::cli::output::{Output, SummaryView};
use crate::{note, out, outln};
use clap::{Args, Subcommand};
use scope::chains::{ChainClientFactory, TokenAnalytics};
use scope::config::Config;

use super::health_args::HealthArgs;
use crate::cli::repeat::{self, RunOutput, Schedule};
use crate::cli::resolve::{
    BindingStore, ResolveContext, VenueCandidates, VenueKind, picker_for, resolve,
};
use scope::display::terminal as t;
use scope::error::{Result, ScopeError};
use scope::http::HttpClient;
use scope::market::assets::TokenAddress;
use scope::market::{
    DexAnalyticsSource, ExchangeClient, HealthThresholds, MarketSummary, MarketVenue, OrderBook,
    Pair, VENUE_HELP, VenueRegistry,
};
use scope::metrics as series;
use std::sync::Arc;
use std::time::Duration;

/// Help for every market pair argument; the rule is `scope::market::Pair::parse`.
const PAIR_HELP: &str = "Pair or base symbol. BASE_QUOTE, BASE/QUOTE and BASE-QUOTE work for any quote \
    (BTC_ETH). BASEQUOTE works only for a stable or fiat quote (OPUSDT, BTCEUR); WETH stays \
    WETH. A bare base (USDC) uses the venue's default quote.";

/// Default interval between summary runs when in repeat mode (60 seconds).
/// Watchlists use the same default (#47, Q7).
pub const DEFAULT_EVERY_SECS: u64 = scope::watch::time::DEFAULT_INTERVAL_SECS;

/// Default total duration when in repeat mode (1 hour).
pub const DEFAULT_DURATION_SECS: u64 = scope::watch::time::DEFAULT_DURATION_SECS;

/// Market subcommands.
#[derive(Debug, Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum MarketCommands {
    /// One-screen peg and order book health summary.
    ///
    /// Displays best bid/ask, mid price, spread, order book levels,
    /// and configurable health checks (peg safety, bid/ask ratio, depth thresholds).
    ///
    /// Use --every and --duration to run repeatedly (e.g., every 30s for 1 hour).
    Summary(SummaryArgs),

    /// Fetch OHLC/candlestick (kline) data from a CEX venue.
    Ohlc(OhlcArgs),

    /// Fetch recent trades from a CEX venue.
    Trades(TradesArgs),
}

/// Arguments for `scope market summary`.
///
/// Default thresholds (min_levels, min_depth, peg_range) originated from
/// stablecoin market-making defaults and are tunable for other markets.
#[derive(Debug, Args)]
#[command(
    after_help = "\x1b[1mExamples:\x1b[0m
  scope market summary DAI --venue binance
  scope market summary @dai-token --venue binance         \x1b[2m# address book shortcut\x1b[0m
  scope market summary USDC --venue binance --format json
  scope market summary DAI --venue binance --every 30s --duration 1h
  scope market summary DAI --venue binance --report health.md --csv peg.csv",
    after_long_help = "\x1b[1mExamples:\x1b[0m

  \x1b[1m$ scope market summary DAI --venue binance\x1b[0m

  +-- DAI/USDT (binance) ----------------------------+
  |                                                     |
  |-- Metrics                                           |
  |  Best Bid           0.9999  (-0.010%)               |
  |  Best Ask           1.0001  (+0.010%)               |
  |  Mid Price          1.0000  (+0.000%)               |
  |  Spread             0.0002  (0.020%)                |
  |  Volume (24h)       125.00K USDT                    |
  |                                                     |
  |-- Health Checks                                     |
  |  + No sells below peg                               |
  |  + Bid/Ask ratio: 0.93x                             |
  |  + Bid levels: 12 >= 10 minimum                     |
  |  + Bid depth: 42000 USDT >= 3000 USDT minimum       |
  |                                                     |
  |  HEALTHY                                            |
  +-----------------------------------------------------+

  \x1b[1m$ scope market summary DAI --venue binance --every 30s --duration 1h\x1b[0m

  Monitoring DAI/USDT (binance) every 30s for 1h...
  [2026-02-16 10:00:00] Mid=1.0000 Spread=0.020% Depth=42K/45K HEALTHY
  [2026-02-16 10:00:30] Mid=1.0000 Spread=0.020% Depth=42K/44K HEALTHY
  [2026-02-16 10:01:00] Mid=0.9999 Spread=0.030% Depth=41K/44K HEALTHY
  ..."
)]
pub struct SummaryArgs {
    #[arg(default_value = scope::market::DEFAULT_PAIR, value_name = "SYMBOL", help = PAIR_HELP)]
    pub pair: String,

    #[arg(long, default_value = scope::market::DEFAULT_VENUE, value_name = "VENUE", help = VENUE_HELP)]
    pub venue: String,

    /// The base token's contract: use it and skip the lookup and the
    /// venue check.
    #[arg(long = "token", value_name = "CONTRACT")]
    pub token_contract: Option<String>,

    /// Chain for a DEX venue. The venue already names its chain, so this is
    /// only a check: a different chain is an error. Ignored for CEX venues.
    #[arg(long, value_name = "CHAIN")]
    pub chain: Option<String>,

    /// Health threshold overrides (flag > config `market.health` > default).
    #[command(flatten)]
    pub health: HealthArgs,

    /// Output format.
    #[arg(short, long, default_value = "text")]
    pub format: SummaryFormat,

    /// Run repeatedly at this interval (e.g., 30s, 5m, 1h).
    /// Default when in repeat mode: 60s.
    #[arg(long, value_name = "INTERVAL")]
    pub every: Option<String>,

    /// Run for this total duration (e.g., 10m, 1h, 24h), or `forever`
    /// (also `inf`) to run until Esc or Ctrl-C.
    /// Default when in repeat mode: 1h.
    #[arg(long, value_name = "DURATION")]
    pub duration: Option<String>,

    /// Save markdown report to file (one-shot mode) or final report (repeat mode).
    #[arg(long, value_name = "PATH")]
    pub report: Option<std::path::PathBuf>,

    /// Append time-series CSV of peg/spread/depth to this path (repeat mode only).
    #[arg(long, value_name = "PATH")]
    pub csv: Option<std::path::PathBuf>,
}

#[derive(Debug, Clone, Copy, Default, clap::ValueEnum)]
pub enum SummaryFormat {
    /// Human-readable text report (default).
    #[default]
    Text,
    /// JSON for programmatic consumption.
    Json,
}

/// Arguments for `scope market ohlc`.
#[derive(Debug, Args)]
#[command(
    after_help = "\x1b[1mExamples:\x1b[0m
  scope market ohlc BTC
  scope market ohlc DAI --venue binance --interval 1d
  scope market ohlc ETH --venue mexc --limit 50 --format json",
    after_long_help = "\x1b[1mExamples:\x1b[0m

  \x1b[1m$ scope market ohlc BTC\x1b[0m

  ┌─ OHLC — BTCUSDT (binance) ───────────────────
  │ 82060.9 ┤  ▄█▄  ╷
  │         │ █▀ ▀██▄ ▄▄
  │ 79439.2 ┤      ▀█▀ ▀
  │           10-23 08:00             10-26 07:00
  │  Interval          1h · 72 candles
  │  Open              80512.3
  │  High              82060.9
  │  Low               79439.2
  │  Close             80391.7 (-0.15%)
  │  Volume            61734.1
  └──────────────────────────────────────────────

  One column per candle, sized to the terminal (or the TUI pane);
  --table adds the full table, --limit fetches a set number.

  \x1b[1m$ scope market ohlc BTC --format json --limit 2\x1b[0m

  [
    {
      \"open_time\": 1739696400000,
      \"open\": 97250.12,
      \"high\": 97380.54,
      \"low\": 97210.98,
      \"close\": 97345.67,
      \"volume\": 1234.56,
      \"close_time\": null
    },
    ...
  ]"
)]
pub struct OhlcArgs {
    #[arg(default_value = scope::market::DEFAULT_PAIR, value_name = "SYMBOL", help = PAIR_HELP)]
    pub pair: String,

    /// Exchange venue (e.g., binance, mexc, bybit).
    #[arg(long, default_value = scope::market::DEFAULT_VENUE, value_name = "VENUE")]
    pub venue: String,

    /// The base token's contract: use it and skip the lookup and the
    /// venue check.
    #[arg(long = "token", value_name = "CONTRACT")]
    pub token_contract: Option<String>,

    /// Candle interval (e.g., 1m, 5m, 15m, 1h, 4h, 1d).
    #[arg(long, default_value = "1h", value_name = "INTERVAL")]
    pub interval: String,

    /// How many candles to fetch. By default, as many as the chart fits
    /// in the terminal (or the TUI pane).
    #[arg(long, value_name = "LIMIT")]
    pub limit: Option<u32>,

    /// Also print every candle in a table under the chart.
    #[arg(long)]
    pub table: bool,

    /// Output format.
    #[arg(long, default_value = "text")]
    pub format: OhlcFormat,
}

/// Arguments for `scope market trades`.
#[derive(Debug, Args)]
#[command(after_help = "\x1b[1mExamples:\x1b[0m
  scope market trades BTC
  scope market trades DAI --venue binance --limit 20
  scope market trades ETH --venue okx --format json")]
pub struct TradesArgs {
    #[arg(default_value = scope::market::DEFAULT_PAIR, value_name = "SYMBOL", help = PAIR_HELP)]
    pub pair: String,

    /// Exchange venue (e.g., binance, mexc, bybit).
    #[arg(long, default_value = scope::market::DEFAULT_VENUE, value_name = "VENUE")]
    pub venue: String,

    /// The base token's contract: use it and skip the lookup and the
    /// venue check.
    #[arg(long = "token", value_name = "CONTRACT")]
    pub token_contract: Option<String>,

    /// Maximum number of trades to fetch.
    #[arg(long, default_value = "50", value_name = "LIMIT")]
    pub limit: u32,

    /// Output format.
    #[arg(long, default_value = "text")]
    pub format: OhlcFormat,
}

/// Output format for market data commands.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum OhlcFormat {
    /// Human-readable text table (default).
    #[default]
    Text,
    /// JSON for programmatic consumption.
    Json,
}

/// Run the market command.
pub async fn run(
    args: MarketCommands,
    config: &Config,
    factory: &dyn ChainClientFactory,
    out: &Output,
) -> Result<()> {
    match args {
        MarketCommands::Summary(summary_args) => {
            run_summary(summary_args, config, factory, out).await
        }
        MarketCommands::Ohlc(ohlc_args) => run_ohlc(ohlc_args, factory.http(), out).await,
        MarketCommands::Trades(trades_args) => run_trades(trades_args, factory.http(), out).await,
    }
}

/// The venue symbol for user pair input (see [`Pair::parse`]).
///
/// Kept only for the monitor (`monitor/mod.rs`), which still calls it; the
/// market commands call `venue_symbol` directly.
pub(crate) fn venue_pair(exchange: &scope::market::ExchangeClient, input: &str) -> String {
    exchange.venue_symbol(&Pair::parse(input))
}

/// Token analytics from the crawl pipeline: the CLI and web adapter for the
/// core [`DexAnalyticsSource`] port.
pub struct CrawlDexSource<'a> {
    /// Chain clients for the token lookup.
    pub factory: &'a dyn ChainClientFactory,
    /// Where the crawl reports progress and warnings.
    pub out: &'a Output,
    /// The base token's contract, when it is already resolved: the lookup
    /// then uses it and does not search.
    pub token: Option<String>,
}

#[async_trait::async_trait]
impl DexAnalyticsSource for CrawlDexSource<'_> {
    async fn token_analytics(&self, token: &str, chain: &str) -> Result<TokenAnalytics> {
        // Without a resolved contract, resolve on this venue's chain: the
        // crawl rule (`ethereum` means every chain) must not apply here.
        let input = match &self.token {
            Some(contract) => contract.clone(),
            None => {
                let dex = self.factory.create_dex_client();
                resolve_dex_token(token, chain, None, dex.as_ref(), false, self.out).await?
            }
        };
        crawl::fetch_analytics_for_input(
            &input,
            chain,
            Period::Hour24,
            10,
            self.factory,
            None,
            self.out,
        )
        .await
    }
}

/// Parse duration strings like "30s", "5m", "1h", "24h" into seconds.
fn parse_duration(s: &str) -> Result<u64> {
    scope::watch::time::parse_duration(s).map_err(ScopeError::Chain)
}

/// Builds markdown report content for a market summary.
pub(crate) fn market_summary_to_markdown(
    summary: &MarketSummary,
    venue: &str,
    pair: &str,
) -> String {
    let mut md = format!(
        "# Market Health Report: {}  \n\
        **Generated:** {}  \n\n",
        pair,
        chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC"),
    );
    md.push_str(&summary.format_markdown(Some(venue)));
    md.push_str(&scope::display::report::report_footer());
    md
}

/// Fetches the book and volume for the summary arguments. `--chain`, when
/// given, must name the DEX venue's chain.
/// The book, the 24h volume, and the recent trades for the bot-pattern
/// advisory (or why there are none).
async fn fetch_book_and_volume(
    args: &SummaryArgs,
    thresholds: &HealthThresholds,
    factory: &dyn ChainClientFactory,
    out: &Output,
) -> Result<(
    OrderBook,
    Option<f64>,
    std::result::Result<Vec<scope::market::Trade>, String>,
)> {
    let venue = MarketVenue::from_name_with_http(&args.venue, factory.http())?;
    if let Some(chain) = &args.chain {
        venue.require_chain(chain)?;
    }
    let dex = CrawlDexSource {
        factory,
        out,
        token: args.token_contract.clone(),
    };
    let pair = Pair::parse(&args.pair);
    let (book, volume) =
        scope::market::fetch_book_and_volume(&venue, &pair, thresholds, &dex).await?;
    let trades = scope::market::fetch_pattern_trades(&venue, &pair).await;
    Ok((book, volume, trades))
}

/// On a CEX venue, proves which token the base symbol is: a saved binding
/// must match the venue's coin list, and a symbol on several networks is a
/// choice (asked, or an error without a terminal). The venue symbol itself
/// does not change.
pub(crate) async fn check_cex_token(
    client: &ExchangeClient,
    base: &str,
    chain: Option<String>,
    token_flag: Option<String>,
    store: &mut dyn BindingStore,
    json: bool,
    out: &Output,
) -> Result<()> {
    let ctx = ResolveContext {
        chain,
        venue: VenueKind::Cex(client.venue_id().to_string()),
        token_flag,
        yes: false,
        save: false,
    };
    let source = VenueCandidates { client };
    let picker = picker_for(out, json);
    resolve(base, &ctx, &source, picker.as_ref(), store, out)
        .await
        .map(|_| ())
}

/// The base token's contract for a summary, resolved once per command: on
/// a DEX venue through the resolver on the venue's own chain (`--token`
/// wins); on a CEX venue `None`, after [`check_cex_token`].
async fn resolve_market_token(
    args: &SummaryArgs,
    factory: &dyn ChainClientFactory,
    out: &Output,
) -> Result<Option<String>> {
    let json = matches!(args.format, SummaryFormat::Json);
    let base = Pair::parse(&args.pair).base;
    match MarketVenue::from_name_with_http(&args.venue, factory.http())? {
        MarketVenue::Dex(dex) => {
            let client = factory.create_dex_client();
            let flag = args.token_contract.clone();
            resolve_dex_token(&base, dex.chain(), flag, client.as_ref(), json, out)
                .await
                .map(Some)
        }
        MarketVenue::Cex(client) => {
            let mut aliases = scope::tokens::TokenAliases::load();
            let (chain, flag) = (args.chain.clone(), args.token_contract.clone());
            check_cex_token(&client, &base, chain, flag, &mut aliases, json, out)
                .await
                .map(|()| None)
        }
    }
}

/// `symbol` on the DEX `chain`, through the resolver: the chain is
/// explicit, so a search never offers a token from another chain.
pub(crate) async fn resolve_dex_token(
    symbol: &str,
    chain: &str,
    token_flag: Option<String>,
    dex: &dyn scope::chains::DexDataSource,
    json: bool,
    out: &Output,
) -> Result<String> {
    let ctx = ResolveContext {
        chain: Some(chain.to_string()),
        venue: VenueKind::Dex,
        token_flag,
        yes: false,
        save: false,
    };
    let source = crate::cli::resolve::DexCandidates {
        dex,
        out,
        fallback: None,
    };
    let picker = picker_for(out, json);
    let mut aliases = scope::tokens::TokenAliases::load();
    let r = resolve(symbol, &ctx, &source, picker.as_ref(), &mut aliases, out).await?;
    Ok(r.address.unwrap_or_else(|| symbol.to_string()))
}

/// [`check_cex_token`] for a command's venue name and pair, once per
/// command; a DEX venue resolves its token in the analytics lookup.
async fn check_venue_token(
    venue: &str,
    pair: &str,
    chain: Option<String>,
    token_flag: Option<String>,
    json: bool,
    http: Arc<dyn HttpClient>,
    out: &Output,
) -> Result<()> {
    let Ok(MarketVenue::Cex(client)) = MarketVenue::from_name_with_http(venue, http) else {
        return Ok(());
    };
    let base = Pair::parse(pair).base;
    let mut aliases = scope::tokens::TokenAliases::load();
    check_cex_token(&client, &base, chain, token_flag, &mut aliases, json, out).await
}

/// The pair's tokens on the venue (network and contract), when the venue
/// lists its assets. A failed lookup is noted and gives no lines: the
/// summary itself does not depend on it.
async fn token_addresses(
    args: &SummaryArgs,
    http: Arc<dyn HttpClient>,
    out: &Output,
) -> Vec<TokenAddress> {
    let Ok(MarketVenue::Cex(client)) = MarketVenue::from_name_with_http(&args.venue, http) else {
        return Vec::new();
    };
    match client.fetch_token_addresses(&Pair::parse(&args.pair)).await {
        None => Vec::new(),
        Some(Ok(tokens)) => tokens,
        Some(Err(e)) => {
            note!(out, "Token addresses are not available: {e}");
            Vec::new()
        }
    }
}

/// One summary run: the summary and its report, as the CLI prints it.
async fn summary_run(
    args: &SummaryArgs,
    factory: &dyn ChainClientFactory,
    thresholds: &HealthThresholds,
    tokens: &[TokenAddress],
    run_num: Option<u64>,
    out: &Output,
) -> Result<(MarketSummary, String)> {
    let (book, volume_24h, trades) = fetch_book_and_volume(args, thresholds, factory, out).await?;
    let mut summary = MarketSummary::from_order_book(&book, thresholds, volume_24h);
    summary.check_bot_patterns(trades.as_deref().map_err(String::as_str));
    let report = match args.format {
        SummaryFormat::Text => summary.format_text_with_tokens(Some(&args.venue), tokens),
        SummaryFormat::Json => {
            let mut json = summary.to_json();
            if let Some(obj) = json.as_object_mut() {
                obj.insert("run".to_string(), serde_json::json!(run_num));
                obj.insert("venue".to_string(), serde_json::json!(args.venue));
                if !tokens.is_empty() {
                    obj.insert("tokens".to_string(), serde_json::json!(tokens));
                }
            }
            format!("{}\n", serde_json::to_string_pretty(&json)?)
        }
    };
    Ok((summary, report))
}

/// Writes the `--report` file for `summary`, when one was asked for.
fn write_report(args: &SummaryArgs, summary: &MarketSummary, out: &Output) -> Result<()> {
    if let Some(ref report_path) = args.report {
        let md = market_summary_to_markdown(summary, &args.venue, &args.pair);
        std::fs::write(report_path, md)?;
        out.note_saved("Report", report_path.display());
    }
    Ok(())
}

/// The `--every`/`--duration` schedule, when either flag is set.
fn summary_schedule(args: &SummaryArgs) -> Result<Option<Schedule>> {
    if args.every.is_none() && args.duration.is_none() {
        return Ok(None);
    }
    let secs = |flag: &Option<String>, default| {
        flag.as_deref()
            .map(parse_duration)
            .transpose()
            .map(|v| v.unwrap_or(default))
    };
    let every = Duration::from_secs(secs(&args.every, DEFAULT_EVERY_SECS)?);
    if args.duration.as_deref().is_some_and(is_until_cancelled) {
        return Schedule::until_cancelled(every).map(Some);
    }
    let duration = secs(&args.duration, DEFAULT_DURATION_SECS)?;
    Schedule::new(every, Duration::from_secs(duration)).map(Some)
}

/// `--duration forever` or `inf`: run until cancelled (#96).
fn is_until_cancelled(s: &str) -> bool {
    scope::watch::time::is_until_cancelled(s)
}

async fn run_summary(
    args: SummaryArgs,
    config: &Config,
    factory: &dyn ChainClientFactory,
    out: &Output,
) -> Result<()> {
    let thresholds = args.health.resolve(config);
    // Bad flags fail before any lookup.
    let schedule = summary_schedule(&args)?;
    let mut args = args;
    // Once per command, so an --every run asks at most once.
    if let Some(contract) = resolve_market_token(&args, factory, out).await? {
        args.token_contract = Some(contract);
    }
    // Once per command: the coin list does not change between runs.
    let tokens = token_addresses(&args, factory.http(), out).await;

    let Some(schedule) = schedule else {
        let (summary, report) =
            summary_run(&args, factory, &thresholds, &tokens, None, out).await?;
        out!(out, "{report}")?;
        out.record_view(SummaryView {
            summary: summary.clone(),
            venue: args.venue.clone(),
            tokens: tokens.clone(),
        });
        return write_report(&args, &summary, out);
    };

    note!(
        out,
        "Running market summary every {}s {} (Ctrl+C to stop)\n",
        schedule.every.as_secs(),
        match schedule.duration {
            Some(d) => format!("for {}s", d.as_secs()),
            None => "until cancelled".to_string(),
        }
    );
    let metrics = series::summary_metrics(&thresholds);
    let last = repeat::run(&schedule, &metrics, args.csv.as_deref(), out, |n| {
        let (args, thresholds, metrics, tokens) = (&args, &thresholds, &metrics, &tokens);
        async move {
            let (summary, report) =
                summary_run(args, factory, thresholds, tokens, Some(n), out).await?;
            Ok(RunOutput {
                sample: series::sample(&summary, metrics),
                snapshot: report,
                view: Some(SummaryView {
                    summary: summary.clone(),
                    venue: args.venue.clone(),
                    tokens: tokens.to_vec(),
                }),
                value: summary,
            })
        }
    })
    .await?;

    if let Some(summary) = last {
        write_report(&args, &summary, out)?;
    }
    if let Some(ref csv_path) = args.csv {
        out.note_saved("Time-series CSV", csv_path.display());
    }
    Ok(())
}

// =============================================================================
// OHLC Command
// =============================================================================

/// Execute the `scope market ohlc` command.
async fn run_ohlc(args: OhlcArgs, http: Arc<dyn HttpClient>, out: &Output) -> Result<()> {
    let json = matches!(args.format, OhlcFormat::Json);
    check_venue_token(
        &args.venue,
        &args.pair,
        None,
        args.token_contract.clone(),
        json,
        http.clone(),
        out,
    )
    .await?;
    let client = VenueRegistry::load()?.create_exchange_client_with_http(&args.venue, http)?;
    run_ohlc_with(&client, args, out).await
}

/// `scope market ohlc` on `client`, the venue that `args.venue` names.
async fn run_ohlc_with(client: &ExchangeClient, args: OhlcArgs, out: &Output) -> Result<()> {
    let pair = client.venue_symbol(&Pair::parse(&args.pair));
    let width = t::terminal_width();
    // The axis is not known before the prices are; ten columns is room for
    // most of them, and the chart takes the newest that fit.
    let limit = args.limit.unwrap_or(candles::columns_for(width, 10) as u32);

    let mut candles = client.fetch_ohlc(&pair, &args.interval, limit).await?;
    // Venues send newest or oldest first; the chart and the table read
    // oldest first.
    candles.sort_by_key(|c| c.open_time);

    match args.format {
        OhlcFormat::Json => {
            let json_str = serde_json::to_string_pretty(&candles)
                .map_err(|e| ScopeError::Chain(format!("JSON serialization failed: {e}")))?;
            outln!(out, "{json_str}")?;
        }
        OhlcFormat::Text => {
            outln!(
                out,
                "{}",
                t::section_header(&format!("OHLC — {} ({})", pair, args.venue))
            )?;
            write_candle_chart(&candles, &args.interval, width, out)?;
            if args.table {
                write_candle_table(&candles, out)?;
            }
            outln!(out, "{}", t::section_footer())?;
        }
    }
    Ok(())
}

/// The chart of the newest candles that fit in `width`, then the summary of
/// every candle fetched.
fn write_candle_chart(
    all: &[scope::market::Candle],
    interval: &str,
    width: usize,
    out: &Output,
) -> Result<()> {
    let Some(sum) = candles::summary(all) else {
        outln!(out, "{}", t::info_row("No candles returned"))?;
        return Ok(());
    };
    let columns = candles::columns_for(width, candles::axis_cols(sum.low, sum.high));
    let shown = &all[all.len().saturating_sub(columns)..];
    // Days and longer read as dates; shorter intervals with the hour.
    let daily = interval.ends_with(['d', 'w', 'M']);
    let time = |ms: u64| {
        chrono::DateTime::from_timestamp_millis(ms as i64)
            .map(|d| {
                let local = d.with_timezone(&chrono::Local);
                if daily {
                    local.format("%Y-%m-%d").to_string()
                } else {
                    local.format("%m-%d %H:%M").to_string()
                }
            })
            .unwrap_or_default()
    };
    for line in candles::chart(shown, candles::CHART_ROWS, t::painter(), time) {
        outln!(out, "{}", t::chart_row(&line))?;
    }
    let count = if shown.len() < all.len() {
        format!(
            "{interval} · {} candles (the chart shows the last {})",
            all.len(),
            shown.len()
        )
    } else {
        format!("{interval} · {} candles", all.len())
    };
    outln!(out, "{}", t::kv_row("Interval", &count))?;
    let price = scope::display::format::format_price;
    outln!(out, "{}", t::kv_row("Open", &price(sum.open)))?;
    outln!(out, "{}", t::kv_row("High", &price(sum.high)))?;
    outln!(out, "{}", t::kv_row("Low", &price(sum.low)))?;
    let close = match sum.change_pct {
        Some(pct) => format!("{} ({pct:+.2}%)", price(sum.close)),
        None => price(sum.close),
    };
    outln!(out, "{}", t::kv_row("Close", &close))?;
    outln!(
        out,
        "{}",
        t::kv_row("Volume", &scope::display::format_large_number(sum.volume))
    )?;
    Ok(())
}

/// Every candle in a table (`--table`).
fn write_candle_table(candles: &[scope::market::Candle], out: &Output) -> Result<()> {
    let cols = [
        t::Col {
            label: "Open Time",
            width: 19,
            align: '>',
        },
        t::Col {
            label: "Open",
            width: 12,
            align: '>',
        },
        t::Col {
            label: "High",
            width: 12,
            align: '>',
        },
        t::Col {
            label: "Low",
            width: 12,
            align: '>',
        },
        t::Col {
            label: "Close",
            width: 12,
            align: '>',
        },
        t::Col {
            label: "Volume",
            width: 14,
            align: '>',
        },
    ];
    outln!(out, "{}", t::table_header(&cols))?;
    for c in candles {
        let dt = chrono::DateTime::from_timestamp_millis(c.open_time as i64)
            .map(|d| d.format("%Y-%m-%d %H:%M").to_string())
            .unwrap_or_else(|| format!("{}", c.open_time));
        let open_str = format!("{:.6}", c.open);
        let high_str = format!("{:.6}", c.high);
        let low_str = format!("{:.6}", c.low);
        let close_str = format!("{:.6}", c.close);
        let volume_str = format!("{:.2}", c.volume);
        let values = [
            dt.as_str(),
            open_str.as_str(),
            high_str.as_str(),
            low_str.as_str(),
            close_str.as_str(),
            volume_str.as_str(),
        ];
        outln!(out, "{}", t::table_row(&cols, &values))?;
    }
    outln!(
        out,
        "{}",
        t::info_row(&format!("{} candles returned", candles.len()))
    )?;
    Ok(())
}

// =============================================================================
// Trades Command
// =============================================================================

/// Execute the `scope market trades` command.
async fn run_trades(args: TradesArgs, http: Arc<dyn HttpClient>, out: &Output) -> Result<()> {
    let json = matches!(args.format, OhlcFormat::Json);
    check_venue_token(
        &args.venue,
        &args.pair,
        None,
        args.token_contract.clone(),
        json,
        http.clone(),
        out,
    )
    .await?;
    let client = VenueRegistry::load()?.create_exchange_client_with_http(&args.venue, http)?;
    run_trades_with(&client, args, out).await
}

/// `scope market trades` on `client`, the venue that `args.venue` names.
async fn run_trades_with(client: &ExchangeClient, args: TradesArgs, out: &Output) -> Result<()> {
    let pair = client.venue_symbol(&Pair::parse(&args.pair));

    let trades = client.fetch_recent_trades(&pair, args.limit).await?;

    match args.format {
        OhlcFormat::Json => {
            let json_str = serde_json::to_string_pretty(&trades)
                .map_err(|e| ScopeError::Chain(format!("JSON serialization failed: {e}")))?;
            outln!(out, "{json_str}")?;
        }
        OhlcFormat::Text => {
            outln!(
                out,
                "{}",
                t::section_header(&format!("Recent Trades — {} ({})", pair, args.venue))
            )?;

            let cols = [
                t::Col {
                    label: "Time",
                    width: 10,
                    align: '>',
                },
                t::Col {
                    label: "Side",
                    width: 5,
                    align: '>',
                },
                t::Col {
                    label: "Price",
                    width: 12,
                    align: '>',
                },
                t::Col {
                    label: "Qty",
                    width: 12,
                    align: '>',
                },
            ];
            outln!(out, "{}", t::table_header(&cols))?;

            for t in &trades {
                let time = chrono::DateTime::from_timestamp_millis(t.timestamp_ms as i64)
                    .map(|d| d.format("%H:%M:%S").to_string())
                    .unwrap_or_else(|| "?".to_string());
                let side_str = match t.side {
                    scope::market::TradeSide::Buy => "BUY",
                    scope::market::TradeSide::Sell => "SELL",
                };
                let price_str = format!("{:.6}", t.price);
                let qty_str = format!("{:.2}", t.quantity);
                let values = [
                    time.as_str(),
                    side_str,
                    price_str.as_str(),
                    qty_str.as_str(),
                ];
                outln!(out, "{}", t::table_row(&cols, &values))?;
            }

            outln!(
                out,
                "{}",
                t::info_row(&format!("{} trades returned", trades.len()))
            )?;
            outln!(out, "{}", t::section_footer())?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use scope::chains::DefaultClientFactory;
    use scope::market::DexVenue;

    fn quiet() -> crate::cli::output::Output {
        crate::cli::output::Output::capture().0
    }

    /// Helper to create a mock venue YAML pointing at the given mock server URL.
    /// Writes a temporary venue descriptor to the user venues directory so the
    /// registry picks it up. Returns the venue id.
    #[allow(dead_code)]
    fn setup_mock_venue(server_url: &str) -> (String, tempfile::TempDir) {
        let venue_id = format!("test_mock_{}", std::process::id());
        let yaml = format!(
            r#"
id: {venue_id}
name: Test Mock Venue
base_url: {server_url}
timeout_secs: 5
symbol:
  template: "{{base}}_{{quote}}"
  default_quote: USDT
capabilities:
  order_book:
    path: /api/v1/depth
    params:
      symbol: "{{pair}}"
    response:
      asks_key: asks
      bids_key: bids
      level_format: positional
  ticker:
    path: /api/v1/ticker
    params:
      symbol: "{{pair}}"
    response:
      last_price: last
      volume_24h: vol
"#
        );
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join(format!("{}.yaml", venue_id));
        std::fs::write(&file_path, yaml).unwrap();
        // We can't easily inject into the registry, so instead
        // create a ConfigurableExchangeClient directly in tests.
        (venue_id, dir)
    }

    #[tokio::test]
    async fn test_run_summary_with_mock_orderbook() {
        // This test uses the DEX path since mock HTTP with the registry is complex.
        // Tested in integration tests and exchange module unit tests instead.
        // Test duration parsing and summary formatting here.
        let args = SummaryArgs {
            pair: "USDC".to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.01),
                min_levels: Some(1),
                min_depth: Some(50.0),
                min_bid_ask_ratio: Some(0.1),
                max_bid_ask_ratio: Some(10.0),
                ..Default::default()
            },
            format: SummaryFormat::Text,
            every: None,
            duration: None,
            report: None,
            csv: None,
        };

        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        // DEX path: will hit real DexScreener API, may fail in offline environments
        let _result = run_summary(args, &Config::default(), &factory, &quiet()).await;
        // We don't assert success because it depends on network, just confirm no panic
    }

    #[tokio::test]
    async fn test_run_summary_json_format() {
        let args = SummaryArgs {
            pair: "USDC".to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.01),
                min_levels: Some(1),
                min_depth: Some(50.0),
                min_bid_ask_ratio: Some(0.1),
                max_bid_ask_ratio: Some(10.0),
                ..Default::default()
            },
            format: SummaryFormat::Json,
            every: None,
            duration: None,
            report: None,
            csv: None,
        };

        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let _result = run_summary(args, &Config::default(), &factory, &quiet()).await;
    }

    #[test]
    fn test_duration_forever_has_no_end_and_the_default_stays_one_hour() {
        // #96: `--duration forever` (or `inf`) runs until cancelled; leaving
        // the flag out keeps the 1 h default so scripts do not change.
        let args = |duration: Option<&str>| SummaryArgs {
            pair: "USDC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs::default(),
            format: SummaryFormat::Text,
            every: Some("30s".to_string()),
            duration: duration.map(str::to_string),
            report: None,
            csv: None,
        };
        for word in ["forever", "inf", "FOREVER"] {
            let s = summary_schedule(&args(Some(word))).unwrap().unwrap();
            assert_eq!(s.duration, None, "{word}");
        }
        let s = summary_schedule(&args(None)).unwrap().unwrap();
        assert_eq!(s.duration, Some(Duration::from_secs(DEFAULT_DURATION_SECS)));
        let s = summary_schedule(&args(Some("10m"))).unwrap().unwrap();
        assert_eq!(s.duration, Some(Duration::from_secs(600)));
    }

    #[test]
    fn test_parse_duration_seconds() {
        assert_eq!(parse_duration("30s").unwrap(), 30);
        assert!(
            parse_duration("forever").is_err(),
            "not a span; --duration only"
        );
        assert_eq!(parse_duration("1").unwrap(), 1);
        assert_eq!(parse_duration("60sec").unwrap(), 60);
    }

    #[test]
    fn test_parse_duration_minutes() {
        assert_eq!(parse_duration("5m").unwrap(), 300);
        assert_eq!(parse_duration("1min").unwrap(), 60);
        assert_eq!(parse_duration("2.5m").unwrap(), 150);
    }

    #[test]
    fn test_parse_duration_hours() {
        assert_eq!(parse_duration("1h").unwrap(), 3600);
        assert_eq!(parse_duration("24h").unwrap(), 86400);
    }

    #[test]
    fn test_parse_duration_invalid() {
        assert!(parse_duration("").is_err());
        assert!(parse_duration("abc").is_err());
        assert!(parse_duration("30x").is_err());
    }

    #[test]
    fn test_parse_duration_unknown_unit_error_message() {
        let result = parse_duration("30z");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Unknown duration unit"));
        assert!(err.to_string().contains("z"));
    }

    #[test]
    fn test_parse_duration_invalid_number_error() {
        let result = parse_duration("abc30s");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_duration_non_positive() {
        assert!(parse_duration("0").is_err());
        assert!(parse_duration("-5s").is_err());
    }

    // ====================================================================
    // base_symbol_from_pair tests
    // ====================================================================

    #[test]
    fn test_base_symbol_from_pair_underscore() {
        assert_eq!(Pair::parse("DAI_USDT").base, "DAI");
        assert_eq!(Pair::parse("USDC_USDT").base, "USDC");
    }

    #[test]
    fn test_base_symbol_from_pair_lowercase_underscore() {
        assert_eq!(Pair::parse("dai_usdt").base, "dai");
    }

    #[test]
    fn test_base_symbol_from_pair_slash() {
        assert_eq!(Pair::parse("USDC/USDT").base, "USDC");
    }

    #[test]
    fn test_base_symbol_from_pair_concat() {
        assert_eq!(Pair::parse("USDCUSDT").base, "USDC");
        assert_eq!(Pair::parse("DAIUSDT").base, "DAI");
    }

    #[test]
    fn test_base_symbol_from_pair_plain() {
        assert_eq!(Pair::parse("USDC").base, "USDC");
        assert_eq!(Pair::parse("ETH").base, "ETH");
    }

    #[test]
    fn test_base_symbol_from_pair_whitespace() {
        assert_eq!(Pair::parse("  DAI_USDT  ").base, "DAI");
    }

    #[test]
    fn test_normalize_pair_input_key_value() {
        assert_eq!(Pair::parse("pair=USDT_PUSD").to_string(), "USDT/PUSD");
        assert_eq!(
            Pair::parse("pair_symbol=USDT_PUSD").to_string(),
            "USDT/PUSD"
        );
        assert_eq!(Pair::parse("USDT_PUSD").to_string(), "USDT/PUSD");
    }

    #[test]
    fn test_parse_pair_components_delimited() {
        assert_eq!(Pair::parse("USDT_PUSD").to_string(), "USDT/PUSD");
        assert_eq!(Pair::parse("ETH/USDC").to_string(), "ETH/USDC");
        assert_eq!(Pair::parse("BTC-USDT").to_string(), "BTC/USDT");
    }

    #[test]
    fn test_parse_pair_components_concat_common_quote() {
        assert_eq!(Pair::parse("BTCUSDT").to_string(), "BTC/USDT");
        assert_eq!(Pair::parse("ETHUSD").to_string(), "ETH/USD");
        assert_eq!(Pair::parse("ARB").quote, None);
    }

    // ====================================================================
    // market_summary_to_markdown tests
    // ====================================================================

    #[test]
    fn test_market_summary_to_markdown_basic() {
        use scope::market::{HealthCheck, MarketSummary};
        let summary = MarketSummary {
            pair: "USDCUSDT".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: Some(0.9999),
            best_ask: Some(1.0001),
            mid_price: Some(1.0000),
            spread: Some(0.0002),
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: Some(1_000_000.0),
            bid_depth: 50_000.0,
            ask_depth: 50_000.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: true,
            bot_patterns: None,
            checks: vec![HealthCheck::Pass("Spread within range".to_string())],
            execution_10k_buy: None,
            execution_10k_sell: None,
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "Binance", "USDCUSDT");
        assert!(md.contains("Market Health Report"));
        assert!(md.contains("USDCUSDT"));
        assert!(md.contains("Binance"));
        assert!(md.contains("Peg Target"));
        assert!(md.contains("1.0000"));
        assert!(md.contains("Healthy"));
    }

    #[test]
    fn test_market_summary_to_markdown_no_prices() {
        use scope::market::{HealthCheck, MarketSummary};
        let summary = MarketSummary {
            pair: "TESTUSDT".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: None,
            best_ask: None,
            mid_price: None,
            spread: None,
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: None,
            bid_depth: 0.0,
            ask_depth: 0.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: false,
            bot_patterns: None,
            checks: vec![HealthCheck::Fail("No data".to_string())],
            execution_10k_buy: None,
            execution_10k_sell: None,
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "Test", "TESTUSDT");
        assert!(md.contains("Market Health Report"));
        assert!(md.contains("-")); // missing data shown as "-"
    }

    // ====================================================================
    // parse_duration — additional edge cases
    // ====================================================================

    #[test]
    fn test_parse_duration_days() {
        assert_eq!(parse_duration("1d").unwrap(), 86400);
        assert_eq!(parse_duration("7d").unwrap(), 604800);
        assert_eq!(parse_duration("1day").unwrap(), 86400);
        assert_eq!(parse_duration("2days").unwrap(), 172800);
    }

    #[test]
    fn test_parse_duration_long_names() {
        assert_eq!(parse_duration("30seconds").unwrap(), 30);
        assert_eq!(parse_duration("5minutes").unwrap(), 300);
        assert_eq!(parse_duration("2hours").unwrap(), 7200);
    }

    #[test]
    fn test_parse_duration_fractional() {
        assert_eq!(parse_duration("0.5h").unwrap(), 1800);
        assert_eq!(parse_duration("1.5m").unwrap(), 90);
    }

    // ====================================================================
    // SummaryFormat tests
    // ====================================================================

    #[test]
    fn test_summary_format_default() {
        let fmt = SummaryFormat::default();
        assert!(matches!(fmt, SummaryFormat::Text));
    }

    #[test]
    fn test_summary_format_debug() {
        let text = format!("{:?}", SummaryFormat::Text);
        assert_eq!(text, "Text");
        let json = format!("{:?}", SummaryFormat::Json);
        assert_eq!(json, "Json");
    }

    // ====================================================================
    // MarketCommands parsing tests
    // ====================================================================

    #[test]
    fn test_ohlc_args_deserialization() {
        use crate::cli::{Cli, Commands};
        use clap::Parser;
        let cli = Cli::try_parse_from([
            "scope",
            "market",
            "ohlc",
            "USDC",
            "--venue",
            "binance",
            "--interval",
            "1h",
            "--limit",
            "50",
        ])
        .unwrap();
        if let Commands::Market(MarketCommands::Ohlc(args)) = cli.command {
            assert_eq!(args.pair, "USDC");
            assert_eq!(args.venue, "binance");
            assert_eq!(args.interval, "1h");
            assert_eq!(args.limit, Some(50));
        } else {
            panic!("Expected Market Ohlc command");
        }
    }

    #[test]
    fn test_trades_args_deserialization() {
        use crate::cli::{Cli, Commands};
        use clap::Parser;
        let cli = Cli::try_parse_from([
            "scope", "market", "trades", "BTC", "--venue", "mexc", "--limit", "100",
        ])
        .unwrap();
        if let Commands::Market(MarketCommands::Trades(args)) = cli.command {
            assert_eq!(args.pair, "BTC");
            assert_eq!(args.venue, "mexc");
            assert_eq!(args.limit, 100);
        } else {
            panic!("Expected Market Trades command");
        }
    }

    #[test]
    fn test_base_symbol_from_pair_various_inputs() {
        // Additional coverage for edge cases
        assert_eq!(Pair::parse("USDC").base, "USDC");
        assert_eq!(Pair::parse("BTCUSDT").base, "BTC");
        assert_eq!(Pair::parse("ETH/USDT").base, "ETH");
        assert_eq!(Pair::parse("DAI_USDT").base, "DAI");
        assert_eq!(Pair::parse("X").base, "X"); // short symbol, no USDT suffix
        assert_eq!(Pair::parse("").base, "");
    }

    #[test]
    fn test_summary_args_debug() {
        let args = SummaryArgs {
            pair: "USDC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.001),
                min_levels: Some(6),
                min_depth: Some(3000.0),
                min_bid_ask_ratio: Some(0.2),
                max_bid_ask_ratio: Some(5.0),
                ..Default::default()
            },
            format: SummaryFormat::Text,
            every: None,
            duration: None,
            report: None,
            csv: None,
        };
        let debug = format!("{:?}", args);
        assert!(debug.contains("SummaryArgs"));
        assert!(debug.contains("USDC"));
    }

    #[test]
    fn test_default_constants() {
        assert_eq!(DEFAULT_EVERY_SECS, 60);
        assert_eq!(DEFAULT_DURATION_SECS, 3600);
    }

    #[test]
    fn test_markdown_leaves_out_the_peg_deviation_when_there_is_none() {
        // A peg target of 0 has no deviation: no "(+0.000%)", the same as the text report.
        use scope::market::{BookSource, OrderBook, OrderBookLevel};
        let level = |price| OrderBookLevel {
            price,
            quantity: 100.0,
        };
        let book = OrderBook {
            pair: "USDC/USDT".to_string(),
            source: BookSource::Exchange,
            bids: vec![level(0.9999)],
            asks: vec![level(1.0001)],
        };
        let thresholds = HealthThresholds {
            peg_target: 0.0,
            ..HealthThresholds::default()
        };
        let summary = MarketSummary::from_order_book(&book, &thresholds, None);
        let md = market_summary_to_markdown(&summary, "binance", "USDC");
        assert!(md.contains("0.9999") && !md.contains("0.9999 ("), "{md}");
        assert!(!md.contains("(+0.000%)"), "{md}");
    }

    #[test]
    fn test_market_summary_to_markdown_with_execution_estimates() {
        use scope::market::{ExecutionEstimate, ExecutionSide, HealthCheck, MarketSummary};
        let summary = MarketSummary {
            pair: "TESTUSDT".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: Some(0.9999),
            best_ask: Some(1.0001),
            mid_price: Some(1.0000),
            spread: Some(0.0002),
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: Some(1_000_000.0),
            bid_depth: 50_000.0,
            ask_depth: 50_000.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: true,
            bot_patterns: None,
            checks: vec![HealthCheck::Pass("Spread within range".to_string())],
            execution_10k_buy: Some(ExecutionEstimate {
                notional_usdt: 10_000.0,
                side: ExecutionSide::Buy,
                vwap: 1.0001,
                slippage_bps: 1.5,
                fillable: true,
            }),
            execution_10k_sell: Some(ExecutionEstimate {
                notional_usdt: 10_000.0,
                side: ExecutionSide::Sell,
                vwap: 0.0,
                slippage_bps: 0.0,
                fillable: false,
            }),
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "TestVenue", "TESTUSDT");
        assert!(md.contains("Market Health Report"));
        assert!(md.contains("TESTUSDT"));
        assert!(md.contains("TestVenue"));
        // Check for fillable buy slippage (should show "1.50 bps")
        assert!(md.contains("1.50 bps"));
        // Check for unfillable sell (should show "insufficient")
        assert!(md.contains("insufficient"));
    }

    #[tokio::test]
    async fn test_run_with_summary_command() {
        // Test the run() dispatcher with a DEX venue (doesn't require mock HTTP)
        let args = MarketCommands::Summary(SummaryArgs {
            pair: "USDC".to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.01),
                min_levels: Some(1),
                min_depth: Some(50.0),
                min_bid_ask_ratio: Some(0.1),
                max_bid_ask_ratio: Some(10.0),
                ..Default::default()
            },
            format: SummaryFormat::Text,
            every: None,
            duration: None,
            report: None,
            csv: None,
        });

        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let config = Config::default();
        let _result = run(args, &config, &factory, &quiet()).await;
        // Don't assert success - depends on network
    }

    #[test]
    fn test_is_dex_venue() {
        assert!(DexVenue::parse("eth").is_some());
        assert!(DexVenue::parse("ethereum").is_some());
        assert!(DexVenue::parse("Ethereum").is_some());
        assert!(DexVenue::parse("solana").is_some());
        assert!(DexVenue::parse("Solana").is_some());
        assert!(DexVenue::parse("binance").is_none());
        assert!(DexVenue::parse("okx").is_none());
        assert!(DexVenue::parse("mexc").is_none());
    }

    #[test]
    fn test_dex_venue_to_chain() {
        assert_eq!(
            DexVenue::parse("eth").map(DexVenue::chain),
            Some("ethereum")
        );
        assert_eq!(
            DexVenue::parse("ethereum").map(DexVenue::chain),
            Some("ethereum")
        );
        assert_eq!(
            DexVenue::parse("Ethereum").map(DexVenue::chain),
            Some("ethereum")
        );
        assert_eq!(
            DexVenue::parse("solana").map(DexVenue::chain),
            Some("solana")
        );
    }

    #[test]
    fn test_venue_registry_loaded_in_cex_path() {
        // Verify the registry loads and can create an exchange client for any built-in venue
        let registry = VenueRegistry::load().unwrap();
        assert!(registry.contains("binance"));
        let client =
            registry.create_exchange_client_with_http("binance", scope::http::test_transport());
        assert!(client.is_ok());
    }

    #[test]
    fn test_venue_registry_error_for_unknown() {
        let registry = VenueRegistry::load().unwrap();
        let result =
            registry.create_exchange_client_with_http("kracken", scope::http::test_transport());
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Unknown venue"));
        assert!(err.contains("Did you mean")); // should suggest kraken (distance 1)
    }

    #[tokio::test]
    async fn test_run_summary_json_format_with_mock() {
        let args = SummaryArgs {
            pair: "USDC".to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.01),
                min_levels: Some(1),
                min_depth: Some(50.0),
                min_bid_ask_ratio: Some(0.1),
                max_bid_ask_ratio: Some(10.0),
                ..Default::default()
            },
            format: SummaryFormat::Json,
            every: None,
            duration: None,
            report: None,
            csv: None,
        };

        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let _result = run_summary(args, &Config::default(), &factory, &quiet()).await;
    }

    // ====================================================================
    // OHLC command tests
    // ====================================================================

    #[test]
    fn test_ohlc_format_default() {
        let fmt: OhlcFormat = Default::default();
        assert_eq!(fmt, OhlcFormat::Text);
    }

    #[test]
    fn test_ohlc_format_display() {
        // ValueEnum-derived parsing
        assert_eq!(format!("{:?}", OhlcFormat::Text), "Text");
        assert_eq!(format!("{:?}", OhlcFormat::Json), "Json");
    }

    #[test]
    fn test_ohlc_args_default_values() {
        // Verify we can construct OhlcArgs with defaults
        let args = OhlcArgs {
            pair: "BTC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            interval: "1h".to_string(),
            limit: Some(100),
            table: false,
            format: OhlcFormat::Text,
        };
        assert_eq!(args.pair, "BTC");
        assert_eq!(args.venue, "binance");
        assert_eq!(args.interval, "1h");
        assert_eq!(args.limit, Some(100));
    }

    #[test]
    fn test_trades_args_construction() {
        let args = TradesArgs {
            pair: "ETH".to_string(),
            venue: "okx".to_string(),
            token_contract: None,
            limit: 50,
            format: OhlcFormat::Json,
        };
        assert_eq!(args.pair, "ETH");
        assert_eq!(args.venue, "okx");
        assert_eq!(args.limit, 50);
    }

    #[tokio::test]
    async fn test_run_ohlc_unknown_venue() {
        let args = OhlcArgs {
            pair: "BTC".to_string(),
            venue: "nonexistent_venue".to_string(),
            token_contract: None,
            interval: "1h".to_string(),
            limit: Some(10),
            table: false,
            format: OhlcFormat::Text,
        };
        let result = run_ohlc(args, scope::http::test_transport(), &quiet()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Unknown venue"),
            "expected 'Unknown venue' error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_run_trades_unknown_venue() {
        let args = TradesArgs {
            pair: "BTC".to_string(),
            venue: "nonexistent_venue".to_string(),
            token_contract: None,
            limit: 10,
            format: OhlcFormat::Text,
        };
        let result = run_trades(args, scope::http::test_transport(), &quiet()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Unknown venue"),
            "expected 'Unknown venue' error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_run_dispatches_ohlc() {
        let cmd = MarketCommands::Ohlc(OhlcArgs {
            pair: "BTC".to_string(),
            venue: "nonexistent_test_venue".to_string(),
            token_contract: None,
            interval: "1h".to_string(),
            limit: Some(5),
            table: false,
            format: OhlcFormat::Text,
        });
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let config = Config::default();
        let result = run(cmd, &config, &factory, &quiet()).await;
        // Should error with venue not found
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_run_dispatches_trades() {
        let cmd = MarketCommands::Trades(TradesArgs {
            pair: "ETH".to_string(),
            venue: "nonexistent_test_venue".to_string(),
            token_contract: None,
            limit: 5,
            format: OhlcFormat::Json,
        });
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let config = Config::default();
        let result = run(cmd, &config, &factory, &quiet()).await;
        assert!(result.is_err());
    }

    /// A venue at `server` whose coin list is `/coins`.
    fn venue_with_coins(server: &mockito::ServerGuard) -> ExchangeClient {
        let mut desc = VenueRegistry::load()
            .unwrap()
            .get("binance")
            .unwrap()
            .clone();
        desc.base_url = server.url();
        desc.capabilities.assets =
            Some(serde_saphyr::from_str("path: /coins\nresponse: {}\n").unwrap());
        ExchangeClient::from_descriptor_with_http(&desc, scope::http::test_transport())
    }

    async fn coins(server: &mut mockito::ServerGuard, body: &str) -> mockito::Mock {
        server
            .mock("GET", "/coins")
            .with_status(200)
            .with_body(body)
            .create_async()
            .await
    }

    #[tokio::test]
    async fn test_a_cex_run_stops_when_the_saved_token_is_not_the_venues() {
        // A saved USDN on ethereum (0xAAA); the venue lists USDN on ETH as
        // 0xBBB. The summary must not report on the venue's token.
        let mut server = mockito::Server::new_async().await;
        let _m = coins(
            &mut server,
            r#"[{"coin":"USDN","networkList":[{"network":"ETH","contractAddress":"0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}]}]"#,
        )
        .await;
        let client = venue_with_coins(&server);
        let mut store = scope::tokens::TokenAliases::default();
        store.add_binding(
            "USDN",
            "ethereum",
            "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            "USDN",
            Some("binance"),
        );
        let err = check_cex_token(
            &client,
            "USDN",
            Some("ethereum".into()),
            None,
            &mut store,
            false,
            &quiet(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ScopeError::TokenMismatch { .. }), "{err}");
    }

    #[tokio::test]
    async fn test_a_cex_symbol_on_two_networks_stops_without_a_terminal() {
        let mut server = mockito::Server::new_async().await;
        let _m = coins(
            &mut server,
            r#"[{"coin":"USDN","networkList":[
                {"network":"ETH","contractAddress":"0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"},
                {"network":"BSC","contractAddress":"0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}]}]"#,
        )
        .await;
        let client = venue_with_coins(&server);
        let mut store = scope::tokens::TokenAliases::default();
        let err = check_cex_token(&client, "USDN", None, None, &mut store, false, &quiet())
            .await
            .unwrap_err();
        assert!(matches!(err, ScopeError::AmbiguousToken { .. }), "{err}");
        // With --token the run goes on.
        assert!(
            check_cex_token(
                &client,
                "USDN",
                None,
                Some("0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into()),
                &mut store,
                false,
                &quiet()
            )
            .await
            .is_ok()
        );
    }

    /// The binance mapping with a local reply, so the test needs no network (#39).
    fn binance_at(server: &mockito::ServerGuard) -> ExchangeClient {
        scope::market::testing::venue_at("binance", &server.url())
    }

    const KLINES: &str = r#"[[1700000000000,"1.0","1.5","0.5","1.25","1000.5",1700003599999],
        [1700003600000,"1.25","2.0","1.0","1.75","20.25",1700007199999]]"#;
    const TRADES: &str = r#"[{"id":1,"price":"1.5","qty":"2.5","quoteQty":"3.75","time":1700000000000,"isBuyerMaker":true},
        {"id":2,"price":"1.6","qty":"1.0","quoteQty":"1.6","time":1700000001000,"isBuyerMaker":false}]"#;

    fn ohlc_args(format: OhlcFormat) -> OhlcArgs {
        OhlcArgs {
            pair: "BTC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            interval: "1h".to_string(),
            limit: Some(2),
            table: false,
            format,
        }
    }

    fn trades_args(format: OhlcFormat) -> TradesArgs {
        TradesArgs {
            pair: "BTC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            limit: 2,
            format,
        }
    }

    async fn serve(path: &str, body: &str) -> mockito::ServerGuard {
        let mut server = mockito::Server::new_async().await;
        server
            .mock("GET", path)
            .match_query(mockito::Matcher::UrlEncoded(
                "symbol".into(),
                "BTCUSDT".into(),
            ))
            .with_body(body)
            .create_async()
            .await;
        server
    }

    #[tokio::test]
    async fn test_ohlc_text_is_a_chart_and_a_summary() {
        let server = serve("/api/v3/klines", KLINES).await;
        let (out, cap) = Output::capture();
        run_ohlc_with(&binance_at(&server), ohlc_args(OhlcFormat::Text), &out)
            .await
            .unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(text.contains("OHLC — BTCUSDT (binance)"), "{text}");
        // The chart: price axis and both candles' bodies.
        assert!(text.contains("2.000000 ┤"), "{text}");
        assert!(text.contains("0.500000 ┤"), "{text}");
        assert!(text.contains('█'), "{text}");
        // The summary of the window: 1.0 → 1.75 is +75%.
        assert!(text.contains("1h · 2 candles"), "{text}");
        assert!(text.contains("1.7500 (+75.00%)"), "{text}");
        assert!(text.contains("1.02K"), "volume 1000.5 + 20.25: {text}");
        // No table without --table.
        assert!(!text.contains("candles returned"), "{text}");
    }

    #[tokio::test]
    async fn test_ohlc_table_adds_every_candle() {
        let server = serve("/api/v3/klines", KLINES).await;
        let (out, cap) = Output::capture();
        let args = OhlcArgs {
            table: true,
            ..ohlc_args(OhlcFormat::Text)
        };
        run_ohlc_with(&binance_at(&server), args, &out)
            .await
            .unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(text.contains("1.250000"), "{text}");
        assert!(text.contains("1000.50"), "{text}");
        assert!(text.contains("2 candles returned"), "{text}");
    }

    #[tokio::test]
    async fn test_ohlc_reads_newest_first_venues_oldest_first() {
        // The same two candles, newest first (as weex sends them).
        const REVERSED: &str = r#"[[1700003600000,"1.25","2.0","1.0","1.75","20.25",1700007199999],
            [1700000000000,"1.0","1.5","0.5","1.25","1000.5",1700003599999]]"#;
        let server = serve("/api/v3/klines", REVERSED).await;
        let (out, cap) = Output::capture();
        run_ohlc_with(&binance_at(&server), ohlc_args(OhlcFormat::Text), &out)
            .await
            .unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(
            text.contains("1.7500 (+75.00%)"),
            "open is the oldest: {text}"
        );
    }

    #[tokio::test]
    async fn test_ohlc_json_keeps_every_field() {
        let server = serve("/api/v3/klines", KLINES).await;
        let (out, cap) = Output::capture();
        run_ohlc_with(&binance_at(&server), ohlc_args(OhlcFormat::Json), &out)
            .await
            .unwrap();
        let v: serde_json::Value = serde_json::from_str(&cap.out()).unwrap();
        assert_eq!(v.as_array().unwrap().len(), 2);
        assert_eq!(v[0]["open_time"], 1_700_000_000_000u64);
        assert_eq!(v[1]["close"], 1.75);
        assert_eq!(v[1]["volume"], 20.25);
    }

    #[tokio::test]
    async fn test_trades_text_shows_side_price_and_quantity() {
        let server = serve("/api/v3/trades", TRADES).await;
        let (out, cap) = Output::capture();
        run_trades_with(&binance_at(&server), trades_args(OhlcFormat::Text), &out)
            .await
            .unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(text.contains("Recent Trades — BTCUSDT (binance)"), "{text}");
        // isBuyerMaker true is a sell; false is a buy.
        assert!(text.contains("SELL") && text.contains("BUY"), "{text}");
        assert!(text.contains("1.500000") && text.contains("2.50"), "{text}");
        assert!(text.contains("2 trades returned"), "{text}");
    }

    #[tokio::test]
    async fn test_trades_json_keeps_every_field() {
        let server = serve("/api/v3/trades", TRADES).await;
        let (out, cap) = Output::capture();
        run_trades_with(&binance_at(&server), trades_args(OhlcFormat::Json), &out)
            .await
            .unwrap();
        let v: serde_json::Value = serde_json::from_str(&cap.out()).unwrap();
        assert_eq!(v[0]["side"], "sell");
        assert_eq!(v[1]["side"], "buy");
        assert_eq!(v[0]["id"], "1");
        assert_eq!(v[0]["quote_quantity"], 3.75);
        assert_eq!(v[1]["timestamp_ms"], 1_700_000_001_000u64);
    }

    // ====================================================================
    // parse_duration — additional edge cases for full coverage
    // ====================================================================

    #[test]
    fn test_parse_duration_whitespace_empty() {
        assert!(parse_duration("").is_err());
        assert!(parse_duration("   ").is_err());
    }

    #[test]
    fn test_parse_duration_sec_secs_second_seconds() {
        assert_eq!(parse_duration("1sec").unwrap(), 1);
        assert_eq!(parse_duration("2secs").unwrap(), 2);
        assert_eq!(parse_duration("1second").unwrap(), 1);
        assert_eq!(parse_duration("3seconds").unwrap(), 3);
    }

    #[test]
    fn test_parse_duration_minute_minutes() {
        assert_eq!(parse_duration("1minute").unwrap(), 60);
        assert_eq!(parse_duration("2minutes").unwrap(), 120);
    }

    #[test]
    fn test_parse_duration_hr_hrs_hour_hours() {
        assert_eq!(parse_duration("1hr").unwrap(), 3600);
        assert_eq!(parse_duration("2hrs").unwrap(), 7200);
        assert_eq!(parse_duration("1hour").unwrap(), 3600);
        assert_eq!(parse_duration("0.5hours").unwrap(), 1800);
    }

    #[test]
    fn test_parse_duration_number_only_defaults_to_seconds() {
        assert_eq!(parse_duration("1.5").unwrap(), 1);
        assert_eq!(parse_duration("42").unwrap(), 42);
    }

    #[test]
    fn test_parse_duration_trimmed_input() {
        assert_eq!(parse_duration("  30s  ").unwrap(), 30);
        assert_eq!(parse_duration(" 5m ").unwrap(), 300);
    }

    #[test]
    fn test_parse_duration_invalid_number_format() {
        assert!(parse_duration("1.2.3s").is_err());
        assert!(parse_duration("abc").is_err());
    }

    // ====================================================================
    // An unknown venue is not a DEX venue (it used to map to ethereum)
    // ====================================================================

    #[test]
    fn test_unknown_venue_is_not_a_dex_venue() {
        assert_eq!(DexVenue::parse("binance"), None);
        assert_eq!(DexVenue::parse("kraken"), None);
        assert_eq!(DexVenue::parse("unknown"), None);
    }

    // ====================================================================
    // market_summary_to_markdown — mixed Pass/Fail checks
    // ====================================================================

    #[test]
    fn test_market_summary_to_markdown_mixed_pass_fail_checks() {
        use scope::market::{HealthCheck, MarketSummary};
        let summary = MarketSummary {
            pair: "TESTUSDT".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: Some(0.9999),
            best_ask: Some(1.0001),
            mid_price: Some(1.0000),
            spread: Some(0.0002),
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: Some(500_000.0),
            bid_depth: 40_000.0,
            ask_depth: 45_000.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: false,
            bot_patterns: None,
            checks: vec![
                HealthCheck::Pass("Spread within range".to_string()),
                HealthCheck::Fail("Bid depth below minimum".to_string()),
            ],
            execution_10k_buy: None,
            execution_10k_sell: None,
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "TestVenue", "TESTUSDT");
        assert!(md.contains("✓ Spread within range"));
        assert!(md.contains("✗ Bid depth below minimum"));
        assert!(md.contains("✗")); // unhealthy indicator in table
    }

    #[test]
    fn test_market_summary_to_markdown_empty_checks() {
        use scope::market::MarketSummary;
        let summary = MarketSummary {
            pair: "X".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: Some(1.0),
            best_ask: Some(1.0),
            mid_price: Some(1.0),
            spread: Some(0.0),
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: None,
            bid_depth: 100.0,
            ask_depth: 100.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: true,
            bot_patterns: None,
            checks: vec![],
            execution_10k_buy: None,
            execution_10k_sell: None,
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "Venue", "X");
        assert!(md.contains("Market Health Report"));
        // No checks, no checks section.
        assert!(!md.contains("Health Checks:"));
    }

    // ====================================================================
    // OhlcFormat / SummaryFormat trait coverage
    // ====================================================================

    #[test]
    fn test_ohlc_format_partial_eq() {
        assert_eq!(OhlcFormat::Text, OhlcFormat::Text);
        assert_eq!(OhlcFormat::Json, OhlcFormat::Json);
        assert_ne!(OhlcFormat::Text, OhlcFormat::Json);
    }

    #[test]
    fn test_summary_format_clone_copy() {
        let text = SummaryFormat::Text;
        let cloned = text;
        assert!(matches!(cloned, SummaryFormat::Text));
        assert!(matches!(text, SummaryFormat::Text));
    }

    // ====================================================================
    // run_summary — error paths and report/csv
    // ====================================================================

    #[tokio::test]
    async fn test_run_summary_interval_zero_error() {
        let args = SummaryArgs {
            pair: "USDC".to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.01),
                min_levels: Some(1),
                min_depth: Some(50.0),
                min_bid_ask_ratio: Some(0.1),
                max_bid_ask_ratio: Some(10.0),
                ..Default::default()
            },
            format: SummaryFormat::Text,
            every: Some("0.1s".to_string()),
            duration: Some("1m".to_string()),
            report: None,
            csv: None,
        };
        let http: std::sync::Arc<dyn scope::http::HttpClient> =
            std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
        let factory = DefaultClientFactory {
            chains_config: Default::default(),
            http,
        };
        let result = run_summary(args, &Config::default(), &factory, &quiet()).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Interval must be positive") || err.contains("positive"),
            "expected interval error, got: {}",
            err
        );
    }

    // ====================================================================
    // MarketCommands and struct Debug/construction
    // ====================================================================

    #[test]
    fn test_market_commands_debug() {
        let cmd = MarketCommands::Summary(SummaryArgs {
            pair: "USDC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.001),
                min_levels: Some(6),
                min_depth: Some(3000.0),
                min_bid_ask_ratio: Some(0.2),
                max_bid_ask_ratio: Some(5.0),
                ..Default::default()
            },
            format: SummaryFormat::Text,
            every: None,
            duration: None,
            report: None,
            csv: None,
        });
        let debug = format!("{:?}", cmd);
        assert!(debug.contains("Summary"));

        let ohlc_cmd = MarketCommands::Ohlc(OhlcArgs {
            pair: "BTC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            interval: "1h".to_string(),
            limit: Some(100),
            table: false,
            format: OhlcFormat::Text,
        });
        assert!(format!("{:?}", ohlc_cmd).contains("Ohlc"));

        let trades_cmd = MarketCommands::Trades(TradesArgs {
            pair: "ETH".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            limit: 50,
            format: OhlcFormat::Json,
        });
        assert!(format!("{:?}", trades_cmd).contains("Trades"));
    }

    #[test]
    fn test_summary_args_with_report_csv_options() {
        let args = SummaryArgs {
            pair: "DAI".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs {
                peg_target: Some(1.0),
                peg_range: Some(0.001),
                min_levels: Some(6),
                min_depth: Some(3000.0),
                min_bid_ask_ratio: Some(0.2),
                max_bid_ask_ratio: Some(5.0),
                ..Default::default()
            },
            format: SummaryFormat::Json,
            every: Some("30s".to_string()),
            duration: Some("1h".to_string()),
            report: Some(std::path::PathBuf::from("/tmp/report.md")),
            csv: Some(std::path::PathBuf::from("/tmp/data.csv")),
        };
        assert_eq!(args.pair, "DAI");
        assert_eq!(args.venue, "binance");
        assert!(args.every.is_some());
        assert!(args.duration.is_some());
        assert!(args.report.is_some());
        assert!(args.csv.is_some());
    }

    #[test]
    fn test_base_symbol_from_pair_4char_usdt() {
        // "USDT" itself has len 4, so doesn't satisfy p.len() > 4
        assert_eq!(Pair::parse("USDT").base, "USDT");
    }

    #[test]
    fn test_market_summary_to_markdown_unhealthy() {
        use scope::market::{HealthCheck, MarketSummary};
        let summary = MarketSummary {
            pair: "X".to_string(),
            source: scope::market::BookSource::Exchange,
            peg_target: 1.0,
            peg_range: scope::market::health::DEFAULT_PEG_RANGE,
            best_bid: Some(0.99),
            best_ask: Some(1.01),
            mid_price: Some(1.0),
            spread: Some(0.02),
            spread_pct: None,
            top_depth: Default::default(),
            volume_24h: None,
            bid_depth: 100.0,
            ask_depth: 100.0,
            bid_outliers: 0,
            ask_outliers: 0,
            healthy: false,
            bot_patterns: None,
            checks: vec![HealthCheck::Fail("Peg deviation too high".to_string())],
            execution_10k_buy: None,
            execution_10k_sell: None,
            asks: vec![],
            bids: vec![],
        };
        let md = market_summary_to_markdown(&summary, "Test", "X");
        assert!(md.contains("✗"));
        assert!(md.contains("Peg deviation too high"));
    }

    #[test]
    fn test_ohlc_format_eq() {
        assert_eq!(OhlcFormat::Text, OhlcFormat::Text);
        assert_ne!(OhlcFormat::Text, OhlcFormat::Json);
    }

    #[test]
    fn test_trades_args_default_venue() {
        let args = TradesArgs {
            pair: "USDC".to_string(),
            venue: "binance".to_string(),
            token_contract: None,
            limit: 50,
            format: OhlcFormat::Text,
        };
        assert_eq!(args.pair, "USDC");
        assert_eq!(args.venue, "binance");
    }

    // ------------------------------------------------------------------
    // Offline DEX-path tests (mock factory, no network)
    // ------------------------------------------------------------------

    const USDC_ADDR: &str = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";

    /// Mock factory whose DEX data has the given pairs (liquidity, volume).
    fn dex_factory(pairs: &[(f64, f64)]) -> scope::chains::mocks::MockClientFactory {
        let mut factory = scope::chains::mocks::MockClientFactory::new();
        let data = factory.mock_dex.token_data.as_mut().unwrap();
        data.symbol = "USDC".to_string();
        data.pairs = pairs
            .iter()
            .enumerate()
            .map(|(i, &(liquidity_usd, volume_24h))| scope::chains::DexPair {
                dex_name: format!("DEX {i}"),
                pair_address: format!("0xpair{i}"),
                base_token: "USDC".to_string(),
                quote_token: "USDT".to_string(),
                price_usd: 1.0,
                volume_24h,
                liquidity_usd,
                liquidity_base: None,
                price_change_24h: 0.0,
                buys_24h: 0,
                sells_24h: 0,
                buys_6h: 0,
                sells_6h: 0,
                buys_1h: 0,
                sells_1h: 0,
                pair_created_at: None,
                url: None,
            })
            .collect();
        factory
    }

    fn dex_args(format: SummaryFormat) -> SummaryArgs {
        SummaryArgs {
            pair: USDC_ADDR.to_string(),
            venue: "eth".to_string(),
            token_contract: None,
            chain: None,
            health: HealthArgs::default(),
            format,
            every: None,
            duration: None,
            report: None,
            csv: None,
        }
    }

    fn two_chain_usdn(factory: &mut scope::chains::mocks::MockClientFactory) {
        let usdn = |chain: &str, address: &str| scope::chains::dex::TokenSearchResult {
            address: address.into(),
            symbol: "USDN".into(),
            name: "USDN".into(),
            chain: chain.into(),
            price_usd: Some(1.0),
            volume_24h: 0.0,
            liquidity_usd: 1.0,
            market_cap: None,
        };
        factory.mock_dex.search_results = vec![usdn("bsc", "0xB"), usdn("ethereum", "0xA")];
    }

    #[tokio::test]
    async fn test_a_dex_venue_resolves_on_its_own_chain() {
        // Review C2: the `eth` venue must not offer, or report, a bsc token.
        let mut factory = dex_factory(&[(50_000.0, 777.0)]);
        two_chain_usdn(&mut factory);
        let mut args = dex_args(SummaryFormat::Text);
        args.pair = "USDN".into();
        let token = resolve_market_token(&args, &factory, &quiet())
            .await
            .unwrap();
        assert_eq!(token.as_deref(), Some("0xA"));
    }

    #[tokio::test]
    async fn test_a_dex_venue_takes_the_token_flag_without_a_search() {
        // Review C1: --token on a DEX venue was ignored.
        let mut factory = dex_factory(&[(50_000.0, 777.0)]);
        two_chain_usdn(&mut factory);
        let mut args = dex_args(SummaryFormat::Text);
        args.pair = "USDN".into();
        args.token_contract = Some("0xT".into());
        let token = resolve_market_token(&args, &factory, &quiet())
            .await
            .unwrap();
        assert_eq!(token.as_deref(), Some("0xT"));
    }

    #[tokio::test]
    async fn test_dex_book_uses_most_liquid_pair() {
        // The synthetic book must come from the deepest pool, not the first one.
        let factory = dex_factory(&[(1_000.0, 10.0), (50_000.0, 777.0), (2_000.0, 20.0)]);
        let (book, volume, trades) = fetch_book_and_volume(
            &dex_args(SummaryFormat::Text),
            &HealthThresholds::default(),
            &factory,
            &quiet(),
        )
        .await
        .unwrap();
        assert_eq!(volume, Some(777.0));
        // A DEX pool has no tape: the bot-pattern advisory says so.
        assert_eq!(trades.unwrap_err(), "a DEX pool has no trade tape here");
        let depth = book.total_depth(scope::market::BookSide::Bid)
            + book.total_depth(scope::market::BookSide::Ask);
        assert!((depth - 50_000.0).abs() < 1.0, "depth {depth}");
    }

    /// `--venue sol` is the Solana DEX (it used to go to the CEX registry
    /// and fail with "unknown venue").
    #[tokio::test]
    async fn test_venue_sol_reads_the_solana_dex() {
        let factory = dex_factory(&[(50_000.0, 777.0)]);
        let mut args = dex_args(SummaryFormat::Text);
        args.venue = "sol".to_string();
        let result =
            fetch_book_and_volume(&args, &HealthThresholds::default(), &factory, &quiet()).await;
        let (book, volume, _trades) = result.unwrap();
        assert_eq!(volume, Some(777.0));
        assert_eq!(book.pair, "USDC/USD");
    }

    /// `--chain` is one rule with the venue: a chain that is not the DEX
    /// venue's chain is an error, in any case.
    #[tokio::test]
    async fn test_chain_must_match_the_dex_venue() {
        let factory = dex_factory(&[(50_000.0, 1.0)]);
        let mut args = dex_args(SummaryFormat::Text);
        args.chain = Some("Solana".to_string());
        let err = fetch_book_and_volume(&args, &HealthThresholds::default(), &factory, &quiet())
            .await
            .unwrap_err();
        assert!(err.to_string().contains("reads chain ethereum"), "{err}");

        args.chain = Some("ETH".to_string());
        assert!(
            fetch_book_and_volume(&args, &HealthThresholds::default(), &factory, &quiet())
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn test_unknown_venue_is_an_error() {
        let factory = dex_factory(&[(50_000.0, 1.0)]);
        let mut args = dex_args(SummaryFormat::Text);
        args.venue = "polygon".to_string();
        let err = fetch_book_and_volume(&args, &HealthThresholds::default(), &factory, &quiet())
            .await
            .unwrap_err();
        assert!(
            err.to_string().contains("Unknown venue \"polygon\""),
            "{err}"
        );
    }

    #[tokio::test]
    async fn test_dex_no_pairs_is_error() {
        let factory = dex_factory(&[]);
        let err = fetch_book_and_volume(
            &dex_args(SummaryFormat::Text),
            &HealthThresholds::default(),
            &factory,
            &quiet(),
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("No DEX pairs found"), "{err}");
    }

    #[tokio::test]
    async fn test_run_summary_once_json_reflects_resolved_thresholds() {
        let factory = dex_factory(&[(50_000.0, 1_000.0)]);
        let mut args = dex_args(SummaryFormat::Json);
        // A one-level synthetic book is healthy only with loosened thresholds.
        args.health = HealthArgs {
            min_levels: Some(1),
            min_top10_depth: Some(1.0),
            ..Default::default()
        };
        let thresholds = args.health.resolve(&Config::default());
        let (summary, _) = summary_run(&args, &factory, &thresholds, &[], Some(1), &quiet())
            .await
            .unwrap();
        assert!(summary.healthy, "{:?}", summary.checks);

        let strict = HealthThresholds::default();
        let (summary, _) = summary_run(&args, &factory, &strict, &[], None, &quiet())
            .await
            .unwrap();
        assert!(!summary.healthy);
    }

    #[tokio::test]
    async fn test_dex_json_shows_amm_source_and_na_checks() {
        // #37 acceptance: JSON shows "status": "n/a", and the book source.
        let mut factory = dex_factory(&[(20_000_000.0, 1_000.0)]);
        factory.mock_dex.token_data.as_mut().unwrap().pairs[0].liquidity_base = Some(10_000_000.0);
        let args = dex_args(SummaryFormat::Json);
        let thresholds = args.health.resolve(&Config::default());
        let (summary, report) = summary_run(&args, &factory, &thresholds, &[], None, &quiet())
            .await
            .unwrap();
        assert!(summary.healthy, "{:?}", summary.checks);
        let v: serde_json::Value = serde_json::from_str(&report).unwrap();
        assert_eq!(v["book_source"], "synthetic_amm");
        let statuses: Vec<&str> = v["checks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|c| c["status"].as_str().unwrap())
            .collect();
        // Three book checks, and the bot-pattern advisory: a pool has no
        // tape, and its curve is an even ladder by design.
        assert_eq!(
            statuses.iter().filter(|s| **s == "n/a").count(),
            4,
            "{:?}",
            statuses
        );
        assert!(!statuses.contains(&"fail"));
        assert_eq!(
            v["checks"].as_array().unwrap().last().unwrap()["message"],
            "Bot patterns: not checked (a DEX pool has no trade tape here)"
        );
        assert_eq!(v["bot_patterns"]["book_checked"], false);
    }

    #[tokio::test]
    async fn test_dex_without_reserves_says_estimate() {
        let factory = dex_factory(&[(50_000.0, 1_000.0)]);
        let args = dex_args(SummaryFormat::Text);
        let thresholds = args.health.resolve(&Config::default());
        let (_, report) = summary_run(&args, &factory, &thresholds, &[], None, &quiet())
            .await
            .unwrap();
        assert!(report.contains("pool reserves not reported"), "{report}");
    }

    #[tokio::test]
    async fn test_run_summary_one_shot_writes_report() {
        let dir = tempfile::tempdir().unwrap();
        let report = dir.path().join("report.md");
        let factory = dex_factory(&[(50_000.0, 1_000.0)]);
        let mut args = dex_args(SummaryFormat::Text);
        args.report = Some(report.clone());
        run_summary(args, &Config::default(), &factory, &quiet())
            .await
            .unwrap();
        let md = std::fs::read_to_string(&report).unwrap();
        assert!(md.contains("Market Health Report"), "{md}");
        assert!(md.contains(USDC_ADDR), "{md}");
    }

    // The paused clock: a slow run on a loaded machine must not change
    // the count.
    #[tokio::test(start_paused = true)]
    async fn test_run_summary_repeat_mode_writes_csv_rows_and_report() {
        let dir = tempfile::tempdir().unwrap();
        let csv = dir.path().join("series.csv");
        let report = dir.path().join("final.md");
        let factory = dex_factory(&[(50_000.0, 1_000.0)]);
        let mut args = dex_args(SummaryFormat::Json);
        args.every = Some("1s".to_string());
        args.duration = Some("1s".to_string());
        args.csv = Some(csv.clone());
        args.report = Some(report.clone());
        run_summary(args, &Config::default(), &factory, &quiet())
            .await
            .unwrap();

        let body = std::fs::read_to_string(&csv).unwrap();
        let mut lines = body.lines();
        // Today's columns stay first and in order; #58 appends the rest.
        let header = lines.next().unwrap();
        assert!(
            header.starts_with(
                "timestamp,run,best_bid,best_ask,mid_price,spread,bid_depth,ask_depth,healthy,"
            ),
            "{header}"
        );
        assert!(
            header.contains("spread_pct") && header.ends_with("ask_top10_depth"),
            "{header}"
        );
        // One run at t=0, one after the 1s sleep: the loop must not stop early.
        let rows: Vec<_> = lines.collect();
        assert_eq!(rows.len(), 2, "{body}");
        assert!(rows[0].split(',').nth(1) == Some("1"));
        assert!(rows[1].split(',').nth(1) == Some("2"));
        assert!(report.exists());
    }

    // The paused clock: a slow run on a loaded machine must not change
    // the count.
    #[tokio::test(start_paused = true)]
    async fn test_run_summary_repeat_publishes_run_progress() {
        // The TUI draws `run N of M` from this hook, so the total must be
        // known at the start and the run number must advance.
        let (out, captured) = Output::capture_merged();
        let hook = out.progress_hook().expect("a merged capture has a hook");
        let factory = dex_factory(&[(50_000.0, 1_000.0)]);
        let mut args = dex_args(SummaryFormat::Json);
        args.every = Some("1s".to_string());
        args.duration = Some("2s".to_string());
        run_summary(args, &Config::default(), &factory, &out)
            .await
            .unwrap();
        let p = hook.lock().unwrap().clone();
        // Runs at 0s, 1s and 2s.
        assert_eq!(p.total, Some(3), "{p:?}");
        assert_eq!(p.run, 3, "{p:?}");
        assert_eq!(p.next_at, None, "no next run after the last: {p:?}");
        assert!(captured.out().contains("every 1s for 2s"));
        assert!(captured.out().contains("Completed 3 run(s)"));
    }

    #[tokio::test]
    async fn test_a_failed_run_ends_a_repeating_summary() {
        // A run that errors stops the repeat and returns the error, so the
        // pane footer is `✗ Failed in`. It does not skip to the next run.
        let (out, _captured) = Output::capture_merged();
        let hook = out.progress_hook().unwrap();
        let factory = dex_factory(&[]);
        let mut args = dex_args(SummaryFormat::Json);
        args.every = Some("1s".to_string());
        args.duration = Some("30s".to_string());
        let started = std::time::Instant::now();
        let result = run_summary(args, &Config::default(), &factory, &out).await;
        assert!(result.is_err(), "no DEX pairs is a failed run");
        assert_eq!(hook.lock().unwrap().run, 1, "no second run after the error");
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "it did not sleep on"
        );
    }

    fn hourly(n: u64, step_ms: u64) -> Vec<scope::market::Candle> {
        (0..n)
            .map(|i| scope::market::Candle {
                open_time: 1_700_000_000_000 + i * step_ms,
                open: 1.0,
                high: 2.0,
                low: 0.5,
                close: 1.5,
                volume: 1.0,
                close_time: 0,
            })
            .collect()
    }

    #[test]
    fn test_more_candles_than_columns_says_the_chart_shows_the_last() {
        let (out, cap) = Output::capture();
        write_candle_chart(&hourly(200, 3_600_000), "1h", 60, &out).unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(
            text.contains("1h · 200 candles (the chart shows the last"),
            "{text}"
        );
    }

    #[test]
    fn test_daily_candles_read_as_dates_and_no_candles_say_so() {
        let (out, cap) = Output::capture();
        write_candle_chart(&hourly(40, 86_400_000), "1d", 120, &out).unwrap();
        let text = crate::cli::ansi::strip(&cap.out());
        assert!(text.contains("2023-11-"), "dates, no hours: {text}");
        assert!(!text.contains(":00 "), "{text}");
        let (out, cap) = Output::capture();
        write_candle_chart(&[], "1h", 120, &out).unwrap();
        assert!(cap.out().contains("No candles returned"), "{}", cap.out());
    }
}