rustrade-execution 0.2.0

Stream private account data from financial venues, and execute (live or mock) orders.
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
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
// Alpaca ExecutionClient implementation
//
// Uses raw reqwest for REST and rustrade-integration tungstenite for WebSocket.
// No official Alpaca Rust SDK — built directly on reqwest + rustrade-integration
// to avoid supply chain risk in a trading system that handles real money.
//
// Architecture:
// - REST (reqwest): account_snapshot, fetch_balances, fetch_open_orders,
//   fetch_trades, open_order, cancel_order
// - WebSocket (tungstenite): account_stream via Alpaca's trade_updates stream
//   at wss://[paper-]api.alpaca.markets/stream
//
// Auth: header-based (APCA-API-KEY-ID + APCA-API-SECRET-KEY), no HMAC signing.
// A reqwest::Client is built with these as default headers so every request
// carries them automatically.
//
// Resilience features:
// - Rate limit handling: reads X-Ratelimit-Remaining / X-Ratelimit-Reset headers;
//   backs off on 429 with up to MAX_RATE_LIMIT_ATTEMPTS total attempts
// - Reconnection: account_stream reconnects on WS close/error with exponential
//   backoff (1 s → 30 s, max 10 attempts)
// - Heartbeat monitoring: reconnects if no WS message for HEARTBEAT_TIMEOUT_SECS
// - Fill recovery: after reconnect, fetches missed fills via GET /v2/account/activities
//   since disconnect_time; sent through the dedup cache to filter duplicates
// - Dedup cache: LRU keyed on "{order_id}:{cumulative_filled_qty}" prevents
//   duplicate fills arising from the overlap between WS events before disconnect
//   and the fill-recovery REST window
//
// Known limitations:
// - Only FILL activities are recovered after reconnect; order lifecycle events
//   (new, cancelled, expired) are not — callers must call fetch_open_orders after
//   each reconnect to reconcile open-order state.

use crate::{
    AccountEventKind, AccountSnapshot, InstrumentAccountSnapshot, UnindexedAccountEvent,
    UnindexedAccountSnapshot,
    balance::{AssetBalance, Balance},
    client::{BracketOrderClient, ExecutionClient},
    error::{ApiError, ConnectivityError, OrderError, UnindexedClientError, UnindexedOrderError},
    order::{
        Order, OrderKey, OrderKind, TimeInForce, TrailingOffsetType,
        bracket::{
            BracketOrderRequest as UnifiedBracketOrderRequest,
            BracketOrderResult as UnifiedBracketOrderResult,
        },
        id::{ClientOrderId, OrderId, StrategyId},
        request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
        state::{Cancelled, Filled, Open, OrderState, UnindexedOrderState},
    },
    trade::{AssetFees, Trade, TradeId},
};
use chrono::{DateTime, Utc};
use fnv::FnvHashMap;
use futures::{SinkExt as _, StreamExt as _, stream::BoxStream};
use indexmap::IndexMap;
use itertools::Itertools as _;
use lru::LruCache;
use rust_decimal::Decimal;
use rustrade_instrument::{
    Side, asset::name::AssetNameExchange, exchange::ExchangeId,
    instrument::name::InstrumentNameExchange,
};
use rustrade_integration::protocol::websocket::{WebSocket, WsMessage};
use serde::{Deserialize, Serialize};
use smol_str::{SmolStr, format_smolstr};
use std::{num::NonZeroUsize, pin::Pin, str::FromStr, sync::Arc, time::Duration};
use tokio::sync::mpsc;
use tracing::{debug, error, info, trace, warn};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const INITIAL_BACKOFF_MS: u64 = 1_000;
const MAX_BACKOFF_MS: u64 = 30_000;
const MAX_RECONNECT_ATTEMPTS: u32 = 10;
/// If no WS activity for this long, force reconnect.
const HEARTBEAT_TIMEOUT_SECS: u64 = 35;
/// Timeout for fill recovery REST queries after reconnect.
const FILL_RECOVERY_TIMEOUT_SECS: u64 = 30;
/// Extra lookback from disconnect timestamp to cover Tokio scheduling jitter and
/// client/server clock drift on cloud VMs. The dedup cache absorbs resulting duplicates.
const SIGNAL_RECOVERY_LOOKBACK_MS: i64 = 1_500;
/// Alpaca's activity page size limit.
const ALPACA_MAX_ACTIVITIES: usize = 100;
/// Default cooldown when rate-limited (if X-Ratelimit-Reset header is absent).
const DEFAULT_RATE_LIMIT_DELAY_SECS: u64 = 60;
/// Total REST attempts (1 initial + retries) before giving up on rate-limit errors.
/// The loop runs `0..MAX_RATE_LIMIT_ATTEMPTS`, retrying while `attempt + 1 < MAX`.
const MAX_RATE_LIMIT_ATTEMPTS: u32 = 4;
/// Dedup LRU cache size. Each entry is a ~50–70 byte String (UUID + decimal).
/// 2_000 entries ≈ 120–140 KB — ample for options trading fill rates.
const DEDUP_CACHE_SIZE: usize = 2_000;
/// Timeout for the initial WS auth+subscribe handshake.
const WS_HANDSHAKE_TIMEOUT_SECS: u64 = 15;
/// Timeout for a graceful WS close. Prevents indefinite blocking when the
/// server does not respond to the close frame before reconnect/shutdown.
const WS_CLOSE_TIMEOUT_SECS: u64 = 5;

// ---------------------------------------------------------------------------
// GracefulShutdownStream
// ---------------------------------------------------------------------------

/// Wrapper stream that signals the `connection_manager` task to shut down gracefully
/// when dropped, allowing it to send an orderly WebSocket close frame.
///
/// # Shutdown sequence
/// Dropping this stream drops `inner` (the channel receiver), which makes `tx.closed()`
/// resolve on the `connection_manager`'s next `select!` poll. The `tx.closed()` arm
/// sends a WebSocket close frame (with `WS_CLOSE_TIMEOUT_SECS` timeout) and then
/// returns, dropping the task cleanly.
///
/// `JoinHandle::drop` detaches the task — it is NOT aborted. The task exits within
/// the current `select!` iteration (if the receiver is already dropped when polled)
/// or after the current heartbeat window / backoff sleep at most.
struct GracefulShutdownStream<S> {
    inner: S,
    /// Keeps the `JoinHandle` alive until this stream is dropped. Dropping
    /// the `JoinHandle` detaches (not cancels) the task, allowing it to keep
    /// running until `tx.closed()` resolves. Without this field the handle
    /// would be detached immediately at `connection_manager` spawn time,
    /// preventing any future `.await` or abort if the design changes.
    _handle: tokio::task::JoinHandle<()>,
}

impl<S> GracefulShutdownStream<S> {
    fn new(inner: S, handle: tokio::task::JoinHandle<()>) -> Self {
        Self {
            inner,
            _handle: handle,
        }
    }
}

impl<S: futures::Stream + Unpin> futures::Stream for GracefulShutdownStream<S> {
    type Item = S::Item;
    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx)
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl<S> Drop for GracefulShutdownStream<S> {
    fn drop(&mut self) {
        // Do not abort. Dropping `self.inner` (the channel receiver) makes `tx.closed()`
        // resolve, which causes `connection_manager` to send a graceful WS close frame
        // and return. Dropping the JoinHandle here detaches (not cancels) the task.
    }
}

// ---------------------------------------------------------------------------
// Rate limit tracker
// ---------------------------------------------------------------------------

/// Thread-safe rate-limit state shared across all clones of AlpacaClient.
struct RateLimitTracker {
    blocked_until: parking_lot::Mutex<Option<tokio::time::Instant>>,
}

impl RateLimitTracker {
    fn new() -> Self {
        Self {
            blocked_until: parking_lot::Mutex::new(None),
        }
    }

    /// Sleep until the current cooldown expires. Returns immediately if not blocked.
    async fn wait_if_blocked(&self) {
        loop {
            // Capture the current time once per iteration — reused for both the
            // expired-deadline check inside the lock and the sleep calculation below.
            // Eliminates one vDSO call per REST request on the common non-blocked path.
            let now = tokio::time::Instant::now();
            // Read and conditionally clear the deadline in a single lock acquisition.
            // The guard is dropped before the `.await` below — holding a sync Mutex
            // across an await would deadlock. A TOCTOU window still exists between the
            // guard drop and `sleep_until`: a concurrent `on_rate_limited` call could
            // extend the deadline after we read it. The loop re-reads on wake and
            // corrects any extended deadline, so the race is recovered from on the next
            // iteration rather than being fully prevented.
            let deadline = {
                let mut guard = self.blocked_until.lock();
                let d = *guard;
                if matches!(d, Some(t) if t <= now) {
                    // Clear expired deadline so on_rate_limited correctly
                    // distinguishes "new rate-limit event" from "extended cooldown".
                    *guard = None;
                }
                d
            };
            match deadline {
                None => return,
                Some(until) => {
                    if until <= now {
                        // Deadline was expired and cleared above; no sleep needed.
                        return;
                    }
                    // as_millis() returns u128; truncation impossible (u64::MAX ms ≈ 584M years)
                    #[allow(clippy::cast_possible_truncation)]
                    let delay_ms = (until - now).as_millis() as u64;
                    debug!(delay_ms, "Alpaca REST rate-limited, waiting before request");
                    tokio::time::sleep_until(until).await;
                }
            }
        }
    }

    /// Record a rate-limit event, extending any existing cooldown if longer.
    fn on_rate_limited(&self, retry_after: Option<Duration>) {
        let delay = retry_after.unwrap_or(Duration::from_secs(DEFAULT_RATE_LIMIT_DELAY_SECS));
        let new_deadline = tokio::time::Instant::now() + delay;
        let mut guard = self.blocked_until.lock();
        let was_blocked = guard.is_some();
        *guard = Some(guard.map_or(new_deadline, |existing| existing.max(new_deadline)));
        if was_blocked {
            debug!(
                delay_secs = delay.as_secs(),
                "Alpaca rate-limit cooldown extended"
            );
        } else {
            warn!(
                delay_secs = delay.as_secs(),
                "Alpaca entering rate-limit degradation mode"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Exponential backoff
// ---------------------------------------------------------------------------

struct ExponentialBackoff {
    attempt: u32,
    max_attempts: u32,
    initial_ms: u64,
    max_ms: u64,
}

impl ExponentialBackoff {
    fn new() -> Self {
        Self {
            attempt: 0,
            max_attempts: MAX_RECONNECT_ATTEMPTS,
            initial_ms: INITIAL_BACKOFF_MS,
            max_ms: MAX_BACKOFF_MS,
        }
    }

    fn reset(&mut self) {
        self.attempt = 0;
    }

    /// Waits for the current backoff duration. Returns `false` if max attempts exhausted.
    async fn wait(&mut self) -> bool {
        if self.attempt >= self.max_attempts {
            return false;
        }
        let delay_ms = self
            .initial_ms
            .saturating_mul(2u64.saturating_pow(self.attempt))
            .min(self.max_ms);
        self.attempt += 1;
        debug!(
            attempt = self.attempt,
            max = self.max_attempts,
            delay_ms,
            "Alpaca reconnect backoff"
        );
        tokio::time::sleep(Duration::from_millis(delay_ms)).await;
        true
    }
}

// ---------------------------------------------------------------------------
// Dedup cache
// ---------------------------------------------------------------------------

/// LRU cache keyed on `trade.id`, which both paths synthesise as
/// `"{order_id}:{cumulative_filled_qty}"`.
///
/// WS fills: `convert_trade_update` sets `trade_id = order.id + ":" + order.filled_qty`
/// (cumulative from the order update payload).
///
/// REST fills: `recover_fills` accumulates per-execution qty per order and overrides
/// `trade.id` to the same format before inserting into the cache.
///
/// Using cumulative qty (not per-execution qty) means two equal-size partial fills
/// on the same order produce distinct keys (`order:1` and `order:2`), preventing
/// silent fill drops.
///
/// [`SmolStr`] keys avoid heap allocation for IDs ≤22 bytes. UUID-length keys
/// (36 chars) always heap-allocate in `SmolStr`; `format_smolstr!` uses an
/// internal `String` buffer for long keys, identical in allocation cost to
/// `format!(…).into::<SmolStr>()`. The type is kept for API consistency with
/// other key types in this codebase.
type SharedDedupCache = Arc<parking_lot::Mutex<LruCache<SmolStr, ()>>>;

fn new_dedup_cache() -> SharedDedupCache {
    // allow(clippy::unwrap_used) — NonZeroUsize::new on a non-zero constant
    // cannot fail at runtime.
    #[allow(clippy::unwrap_used)]
    Arc::new(parking_lot::Mutex::new(LruCache::new(
        NonZeroUsize::new(DEDUP_CACHE_SIZE).unwrap(),
    )))
}

/// Returns `true` if this key was already seen (duplicate). Inserts if new.
fn is_duplicate(cache: &SharedDedupCache, key: &SmolStr) -> bool {
    let mut guard = cache.lock();
    // peek avoids promoting to MRU on the duplicate (discard) path
    if guard.peek(key).is_some() {
        return true;
    }
    // Clone on the insert (non-duplicate) path only. UUID-length SmolStr keys
    // heap-allocate, but the WS path is single-threaded — there is no mutex
    // contention to justify cloning before the lock on the duplicate fast-path.
    guard.put(key.clone(), ());
    false
}

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// Configuration for the Alpaca execution client.
// Serialize intentionally omitted — would expose secret_key in plaintext.
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AlpacaConfig {
    // Private fields prevent accidental credential exposure via struct access.
    api_key: String,
    secret_key: String,
    /// Use paper trading endpoints instead of production.
    pub paper: bool,
    /// Test-only: override the REST base URL (e.g., to point at a wiremock server).
    #[cfg(test)]
    pub base_url_override: Option<String>,
}

// Custom Debug to avoid leaking credentials in logs.
impl std::fmt::Debug for AlpacaConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AlpacaConfig")
            .field("api_key", &"***")
            .field("secret_key", &"***")
            .field("paper", &self.paper)
            .finish()
    }
}

impl AlpacaConfig {
    pub fn new(api_key: String, secret_key: String, paper: bool) -> Self {
        Self {
            api_key,
            secret_key,
            paper,
            #[cfg(test)]
            base_url_override: None,
        }
    }

    /// Test-only: create config with a custom base URL for wiremock testing.
    #[cfg(test)]
    pub fn with_base_url(api_key: String, secret_key: String, base_url: String) -> Self {
        Self {
            api_key,
            secret_key,
            paper: true,
            base_url_override: Some(base_url),
        }
    }

    pub fn api_key(&self) -> &str {
        &self.api_key
    }

    /// Base URL for REST API calls.
    ///
    /// In test builds, checks `base_url_override` first to allow wiremock testing.
    pub fn rest_base_url(&self) -> &str {
        #[cfg(test)]
        if let Some(ref url) = self.base_url_override {
            return url.as_str();
        }
        if self.paper {
            "https://paper-api.alpaca.markets"
        } else {
            "https://api.alpaca.markets"
        }
    }

    /// WebSocket URL for trade_updates stream.
    pub fn ws_url(&self) -> &'static str {
        if self.paper {
            "wss://paper-api.alpaca.markets/stream"
        } else {
            "wss://api.alpaca.markets/stream"
        }
    }
}

// ---------------------------------------------------------------------------
// REST response serde types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct AlpacaAccount {
    equity: String,
    buying_power: String,
    options_buying_power: Option<String>,
    // crypto_buying_power is present in Alpaca's account response and represents
    // available buying power specifically for crypto orders. Not currently used in
    // balance logic (buying_power serves as the general free USD balance), but
    // retained so serde doesn't error on accounts where the field is present.
    #[allow(dead_code)]
    // retained for serde completeness; may be used for per-asset-class reporting
    crypto_buying_power: Option<String>,
}

/// A single position returned by GET /v2/positions.
#[derive(Debug, Deserialize)]
struct AlpacaPosition {
    /// Exchange symbol (e.g., "BTC/USD" for crypto, "AAPL" for equity).
    symbol: String,
    /// Asset class: "us_equity", "crypto", "us_option".
    asset_class: String,
    /// Total quantity held (base currency for crypto).
    qty: String,
    /// Quantity available to trade (not locked in open orders).
    qty_available: String,
}

#[derive(Debug, Deserialize)]
struct AlpacaOrderResponse {
    id: String,
    client_order_id: Option<String>,
    symbol: String,
    qty: Option<String>,
    filled_qty: String,
    side: String,
    #[serde(rename = "type")]
    order_type: String,
    time_in_force: String,
    limit_price: Option<String>,
    stop_price: Option<String>,
    trail_percent: Option<String>,
    trail_price: Option<String>,
    created_at: String,
}

#[derive(Debug, Deserialize)]
struct AlpacaActivity {
    id: String,
    order_id: String,
    symbol: String,
    side: String,
    price: String,
    qty: String,
    transaction_time: String,
}

#[derive(Debug, Deserialize)]
struct AlpacaApiError {
    message: String,
}

// ---------------------------------------------------------------------------
// AlpacaPositionIntent
// ---------------------------------------------------------------------------

/// Explicit position intent for Alpaca order placement.
///
/// Required for options orders; valid (but optional) for equities.
/// Omit entirely for crypto orders (causes 422 Unprocessable Entity).
///
/// Use `AlpacaClient::open_order_with_intent` to supply a specific intent
/// instead of the heuristic mapping used by the `ExecutionClient` trait impl.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AlpacaPositionIntent {
    BuyToOpen,
    BuyToClose,
    SellToOpen,
    SellToClose,
}

// ---------------------------------------------------------------------------
// Bracket order types
// ---------------------------------------------------------------------------

/// Take-profit parameters for Alpaca bracket orders.
///
/// The take-profit leg is always a limit order at the specified price.
#[derive(Debug, Serialize)]
struct TakeProfitParams {
    limit_price: String,
}

/// Stop-loss parameters for Alpaca bracket orders.
///
/// When `limit_price` is `None`, the stop-loss is a stop (market) order.
/// When `limit_price` is `Some`, the stop-loss becomes a stop-limit order.
#[derive(Debug, Serialize)]
struct StopLossParams {
    stop_price: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    limit_price: Option<String>,
}

/// Request to place a bracket order (entry + take-profit + stop-loss).
///
/// A bracket order consists of three linked orders submitted in a single request:
/// 1. **Entry**: Limit order to enter the position
/// 2. **Take Profit**: Limit order to exit at profit target
/// 3. **Stop Loss**: Stop or stop-limit order to exit at loss limit
///
/// When either the take-profit or stop-loss fills, Alpaca automatically cancels
/// the other leg.
///
/// # Constraints
///
/// - `time_in_force` must be `Day` or `GoodUntilCancelled` (no extended hours)
/// - Entry order type is always `Limit`
/// - Take-profit is always a `Limit` order
/// - Stop-loss is a `Stop` order (or `StopLimit` if `stop_loss_limit_price` is set)
///
/// # Example
///
/// ```ignore
/// let request = AlpacaBracketOrderRequest::new(
///     "AAPL".into(),
///     StrategyId::new("momentum"),
///     ClientOrderId::new("bracket-001"),
///     Side::Buy,
///     dec!(10),
///     dec!(150.00),  // entry
///     dec!(160.00),  // take profit
///     dec!(145.00),  // stop loss
///     TimeInForce::GoodUntilCancelled { post_only: false },
/// );
/// // For stop-limit SL: .with_stop_loss_limit_price(dec!(144.00))
/// let result = client.open_bracket_order(request).await;
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct AlpacaBracketOrderRequest {
    /// Instrument to trade.
    pub instrument: InstrumentNameExchange,
    /// Strategy identifier for order correlation.
    pub strategy: StrategyId,
    /// Client order ID for the parent (entry) order.
    pub cid: ClientOrderId,
    /// Buy or Sell for the entry order (exits use opposite side).
    pub side: Side,
    /// Number of shares/contracts.
    pub quantity: Decimal,
    /// Entry limit price.
    pub entry_price: Decimal,
    /// Take-profit limit price.
    pub take_profit_price: Decimal,
    /// Stop-loss trigger price.
    pub stop_loss_price: Decimal,
    /// Optional stop-loss limit price. When set, makes the stop-loss a stop-limit order.
    pub stop_loss_limit_price: Option<Decimal>,
    /// Time-in-force for all legs. Must be `Day` or `GoodUntilCancelled`.
    pub time_in_force: TimeInForce,
}

impl AlpacaBracketOrderRequest {
    /// Create a new bracket order request.
    ///
    /// For a stop-limit stop-loss leg, chain `.with_stop_loss_limit_price()`.
    #[allow(clippy::too_many_arguments)] // Bracket orders inherently need many params
    pub fn new(
        instrument: InstrumentNameExchange,
        strategy: StrategyId,
        cid: ClientOrderId,
        side: Side,
        quantity: Decimal,
        entry_price: Decimal,
        take_profit_price: Decimal,
        stop_loss_price: Decimal,
        time_in_force: TimeInForce,
    ) -> Self {
        Self {
            instrument,
            strategy,
            cid,
            side,
            quantity,
            entry_price,
            take_profit_price,
            stop_loss_price,
            stop_loss_limit_price: None,
            time_in_force,
        }
    }

    /// Set the stop-loss limit price, converting the SL leg to a stop-limit order.
    #[must_use]
    pub fn with_stop_loss_limit_price(mut self, price: Decimal) -> Self {
        self.stop_loss_limit_price = Some(price);
        self
    }
}

/// Result of placing an Alpaca bracket order.
///
/// Contains the parent order with its state. The take-profit and stop-loss legs
/// are managed by Alpaca and their status can be queried via `fetch_open_orders`.
///
/// # Note
///
/// Unlike IBKR which returns three separate orders, Alpaca's bracket API returns
/// a single parent order. The child legs (TP/SL) are implicitly created and linked
/// by Alpaca. Use `fetch_open_orders` to retrieve all legs after placement.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct AlpacaBracketOrderResult {
    /// Parent (entry) order with its current state.
    pub parent: Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
}

// ---------------------------------------------------------------------------
// REST order request body
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
struct AlpacaOrderRequest<'a> {
    symbol: &'a str,
    qty: String,
    side: &'static str,
    #[serde(rename = "type")]
    order_type: &'static str,
    time_in_force: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    limit_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stop_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    trail_percent: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    trail_price: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    client_order_id: Option<&'a str>,
    // position_intent: heuristic mapping (buy→buy_to_open, sell→sell_to_close).
    // Correct for directional long-only strategies. Omit for exchanges/asset
    // classes that don't require it (stocks/crypto ignore this field).
    #[serde(skip_serializing_if = "Option::is_none")]
    position_intent: Option<AlpacaPositionIntent>,
    // Bracket order fields (order_class, take_profit, stop_loss).
    // Set order_class to "bracket" and populate TP/SL for bracket orders.
    #[serde(skip_serializing_if = "Option::is_none")]
    order_class: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    take_profit: Option<TakeProfitParams>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stop_loss: Option<StopLossParams>,
}

// ---------------------------------------------------------------------------
// WebSocket message types
// ---------------------------------------------------------------------------

/// Outer container for all Alpaca stream messages.
///
/// `data` is kept as a [`serde_json::value::RawValue`] to avoid allocating a full DOM tree
/// for heartbeats and auth/listening acks that never reach `AlpacaTradeUpdate` parsing.
#[derive(Debug, Deserialize)]
struct AlpacaStreamMessage<'a> {
    // Short well-known values ("trade_updates", "listening", "authorization")
    // all fit inline in SmolStr — avoids one heap alloc per WS message.
    stream: SmolStr,
    #[serde(borrow)]
    data: &'a serde_json::value::RawValue,
}

/// Parsed payload of a `trade_updates` event.
///
/// Numeric and timestamp fields borrow directly from the `RawValue` input buffer
/// (`#[serde(borrow)]`), propagating the zero-copy design of `AlpacaStreamMessage`.
/// This eliminates 4–6 heap allocations per fill event. The borrow is valid because
/// Alpaca's numeric and timestamp strings contain no JSON escape sequences.
#[derive(Debug, Deserialize)]
struct AlpacaTradeUpdate<'a> {
    // Short event tag ("fill", "partial_fill", "new", ...) — fits inline.
    event: SmolStr,
    #[serde(borrow)]
    order: AlpacaOrderWs<'a>,
    /// Fill price for this specific execution (None for non-fill events).
    #[serde(borrow)]
    price: Option<&'a str>,
    /// Quantity for this specific execution (None for non-fill events).
    #[serde(borrow)]
    qty: Option<&'a str>,
    #[serde(borrow)]
    timestamp: Option<&'a str>,
}

/// Order state embedded in a `trade_updates` WebSocket event.
#[derive(Debug, Deserialize)]
struct AlpacaOrderWs<'a> {
    // UUIDs (36 chars) heap-allocate in SmolStr, but using SmolStr directly avoids
    // an intermediate String allocation when serde deserialises the field.
    id: SmolStr,
    client_order_id: Option<SmolStr>,
    // Ticker symbols ("AAPL", "BTC/USD") fit inline in SmolStr (≤23 bytes),
    // eliminating the heap allocation entirely for most symbols.
    symbol: SmolStr,
    #[serde(borrow)]
    qty: Option<&'a str>,
    // Alpaca guarantees `filled_qty` for fill/partial_fill and most lifecycle
    // events, but some event types (e.g. `rejected`) may omit the field.
    // Using Option avoids a deserialization failure that would silently drop
    // the event. Call sites use `.unwrap_or("0")`.
    #[serde(borrow)]
    filled_qty: Option<&'a str>,
    // Short enums ("buy"/"sell", "market"/"limit"/..., "day"/"gtc"/..., status)
    // — all fit inline in SmolStr.
    side: SmolStr,
    #[serde(rename = "type")]
    order_type: SmolStr,
    time_in_force: SmolStr,
    #[serde(borrow)]
    limit_price: Option<&'a str>,
    #[serde(borrow)]
    stop_price: Option<&'a str>,
    #[serde(borrow)]
    trail_percent: Option<&'a str>,
    #[serde(borrow)]
    trail_price: Option<&'a str>,
    status: SmolStr,
}

// ---------------------------------------------------------------------------
// AlpacaClient
// ---------------------------------------------------------------------------

/// Alpaca execution client supporting options, equities, and crypto via the
/// single unified Alpaca trading API.
///
/// All three asset classes share the same REST and WebSocket endpoints. The
/// key behavioral differences handled transparently:
/// - Options: `position_intent` field is required (detected by OCC symbol format)
/// - Crypto: `position_intent` is omitted (not a valid field for crypto orders);
///   fractional quantities are supported natively via `Decimal::to_string()`
/// - Equities: `position_intent` is valid but optional for long-only strategies
///
/// Cloning is cheap: all inner state is behind `Arc`.
#[derive(Clone)]
pub struct AlpacaClient {
    config: Arc<AlpacaConfig>,
    /// reqwest client with APCA-API-KEY-ID and APCA-API-SECRET-KEY pre-set as
    /// default headers — every request carries auth automatically.
    http: reqwest::Client,
    rate_limiter: Arc<RateLimitTracker>,
    /// Pre-allocated `/v2/orders` endpoint URL to avoid allocation per request.
    orders_url: String,
}

impl std::fmt::Debug for AlpacaClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AlpacaClient")
            .field("paper", &self.config.paper)
            .finish_non_exhaustive()
    }
}

impl AlpacaClient {
    /// Build a `reqwest::Client` with Alpaca auth headers pre-set.
    ///
    /// # Panics
    ///
    /// Panics if the API key or secret contains characters that are invalid
    /// in an HTTP header value (non-ASCII or control characters).
    #[allow(clippy::expect_used)] // Documented panic: invalid credentials detected at startup
    fn build_http(config: &AlpacaConfig) -> reqwest::Client {
        use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
        let mut headers = HeaderMap::new();
        // HTTP header names are case-insensitive; use lowercase per HTTP/2 convention.
        headers.insert(
            HeaderName::from_static("apca-api-key-id"),
            HeaderValue::from_str(&config.api_key)
                .expect("Alpaca API key contains invalid header characters"),
        );
        headers.insert(
            HeaderName::from_static("apca-api-secret-key"),
            HeaderValue::from_str(&config.secret_key)
                .expect("Alpaca secret key contains invalid header characters"),
        );
        reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .expect("failed to build reqwest client for Alpaca")
    }

    fn base_url(&self) -> &str {
        self.config.rest_base_url()
    }
}

// ---------------------------------------------------------------------------
// REST helper: rate-limited request with retry
// ---------------------------------------------------------------------------

/// Parse the `X-Ratelimit-Reset` response header into a cooldown [`Duration`].
///
/// The header value is a Unix epoch timestamp (seconds). Returns the duration
/// from now until that timestamp, clamped to a minimum of 1 second to avoid
/// a zero-delay busy loop. Returns `None` if the header is absent or malformed;
/// callers should fall back to [`DEFAULT_RATE_LIMIT_DELAY_SECS`].
fn parse_rate_limit_delay(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
    headers
        .get("x-ratelimit-reset")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse::<u64>().ok())
        .map(|reset_ts| {
            let now_secs = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
            Duration::from_secs(reset_ts.saturating_sub(now_secs).max(1))
        })
}

/// Execute a REST request with rate-limit awareness and retry.
///
/// The `build_request` closure is called on every attempt so the caller doesn't
/// need a clone of `RequestBuilder` (which may not be cloneable with streaming bodies).
/// For GET/POST/DELETE with fixed bodies, the closure is a cheap re-construction.
///
/// On HTTP 429, reads `X-Ratelimit-Reset` (Unix epoch) to determine the cooldown
/// duration and retries up to `MAX_RATE_LIMIT_ATTEMPTS - 1` times.
async fn rest_with_retry<T>(
    rate_limiter: &RateLimitTracker,
    mut build_request: impl FnMut() -> reqwest::RequestBuilder,
) -> Result<T, UnindexedClientError>
where
    T: for<'de> Deserialize<'de>,
{
    for attempt in 0..MAX_RATE_LIMIT_ATTEMPTS {
        rate_limiter.wait_if_blocked().await;
        let response = build_request()
            .send()
            .await
            .map_err(|e| connectivity_err(format!("Alpaca REST request failed: {e}")))?;

        // Check X-Ratelimit-Remaining as an early warning; if exactly 0, the next
        // request will 429. We don't proactively pause here — let the 429 handle it —
        // but log at debug level so it's visible in traces.
        if response
            .headers()
            .get("x-ratelimit-remaining")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u32>().ok())
            == Some(0)
        {
            debug!("Alpaca REST rate-limit bucket exhausted (X-Ratelimit-Remaining: 0)");
        }

        let status = response.status();

        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let reset_delay = parse_rate_limit_delay(response.headers());

            if attempt + 1 < MAX_RATE_LIMIT_ATTEMPTS {
                warn!(
                    attempt = attempt + 1,
                    max_attempts = MAX_RATE_LIMIT_ATTEMPTS,
                    "Alpaca REST rate-limited (429), retrying"
                );
                rate_limiter.on_rate_limited(reset_delay);
                continue;
            }

            // Final attempt still rate-limited — return typed error.
            warn!(
                max_attempts = MAX_RATE_LIMIT_ATTEMPTS,
                "Alpaca REST rate-limit retries exhausted"
            );
            return Err(UnindexedClientError::Api(ApiError::RateLimit));
        }

        // 204 No Content is only valid for DELETE endpoints; use rest_delete_with_retry
        // for those. Reaching here for a 204 indicates API misuse — return a clear error
        // rather than a misleading "EOF while parsing" JSON failure.
        if status == reqwest::StatusCode::NO_CONTENT {
            return Err(connectivity_err(
                "Alpaca REST returned 204 No Content — use rest_delete_with_retry for DELETE endpoints"
                    .to_string(),
            ));
        }

        let bytes = response
            .bytes()
            .await
            .map_err(|e| connectivity_err(format!("Alpaca REST read body failed: {e}")))?;

        if status.is_success() {
            return serde_json::from_slice::<T>(&bytes).map_err(|e| {
                connectivity_err(format!(
                    "Alpaca REST JSON parse error ({status}): {e} | body: {}",
                    String::from_utf8_lossy(&bytes)
                        .chars()
                        .take(200)
                        .collect::<String>()
                ))
            });
        }

        // Parse API error body for a better error message.
        let api_err = serde_json::from_slice::<AlpacaApiError>(&bytes)
            .map(|e| e.message)
            .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).into_owned());

        // 4xx = API-level rejection (wrong parameters, auth failure, insufficient funds).
        // 5xx / other = server-side failure treated as connectivity error.
        // Callers that pattern-match on UnindexedClientError (e.g. open_order_inner) rely
        // on Api(ApiError) to classify business rejections vs connectivity failures.
        //
        // Uses parse_api_error for consistent classification: 422 "insufficient funds"
        // maps to BalanceInsufficient (not generic OrderRejected), enabling callers to
        // trigger balance refresh on insufficient-funds rejections.
        if status.is_client_error() {
            return Err(UnindexedClientError::Api(parse_api_error(status, &api_err)));
        }
        return Err(connectivity_err(format!(
            "Alpaca REST error {status}: {api_err}"
        )));
    }
    unreachable!("Alpaca REST retry loop exited without returning")
}

/// Execute a DELETE request, returning an order error on rejection.
///
/// Handles 204 No Content (success), 422 / 403 (API rejection), and 429 (rate limit).
async fn rest_delete_with_retry(
    rate_limiter: &RateLimitTracker,
    mut build_request: impl FnMut() -> reqwest::RequestBuilder,
) -> Result<(), UnindexedOrderError> {
    for attempt in 0..MAX_RATE_LIMIT_ATTEMPTS {
        rate_limiter.wait_if_blocked().await;
        let response = build_request().send().await.map_err(|e| {
            UnindexedOrderError::Connectivity(ConnectivityError::Socket(format!(
                "Alpaca cancel request failed: {e}"
            )))
        })?;

        let status = response.status();

        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let reset_delay = parse_rate_limit_delay(response.headers());

            if attempt + 1 < MAX_RATE_LIMIT_ATTEMPTS {
                warn!(
                    attempt = attempt + 1,
                    max_attempts = MAX_RATE_LIMIT_ATTEMPTS,
                    "Alpaca cancel rate-limited (429), retrying"
                );
                rate_limiter.on_rate_limited(reset_delay);
                continue;
            }

            // Final attempt still rate-limited — return typed error.
            warn!(
                max_attempts = MAX_RATE_LIMIT_ATTEMPTS,
                "Alpaca cancel rate-limit retries exhausted"
            );
            return Err(UnindexedOrderError::Rejected(ApiError::RateLimit));
        }

        // 204 No Content: cancel succeeded.
        if status == reqwest::StatusCode::NO_CONTENT || status.is_success() {
            return Ok(());
        }

        let bytes = response
            .bytes()
            .await
            .inspect_err(
                |e| warn!(%e, %status, "Alpaca cancel_order: failed to read error response body"),
            )
            .unwrap_or_default();
        let msg = serde_json::from_slice::<AlpacaApiError>(&bytes)
            .map(|e| e.message)
            .unwrap_or_else(|_| String::from_utf8_lossy(&bytes).into_owned());

        return Err(parse_order_error(status, &msg));
    }
    unreachable!("Alpaca cancel retry loop exited without returning")
}

// ---------------------------------------------------------------------------
// ExecutionClient implementation
// ---------------------------------------------------------------------------

impl ExecutionClient for AlpacaClient {
    const EXCHANGE: ExchangeId = ExchangeId::AlpacaBroker;
    type Config = AlpacaConfig;
    type AccountStream = BoxStream<'static, UnindexedAccountEvent>;

    /// # Panics
    ///
    /// Panics if the API key or secret key contains characters invalid in an
    /// HTTP header value.
    fn new(config: Self::Config) -> Self {
        let http = Self::build_http(&config);
        let orders_url = format!("{}/v2/orders", config.rest_base_url());
        Self {
            config: Arc::new(config),
            http,
            rate_limiter: Arc::new(RateLimitTracker::new()),
            orders_url,
        }
    }

    /// # Rate limit note
    ///
    /// When both USD and non-USD assets are requested (the common startup case), this
    /// method fetches `/v2/account` and `/v2/positions` in parallel for ~100-300ms
    /// latency savings. Under rate pressure, both requests may hit 429 simultaneously
    /// and retry independently. Operators approaching Alpaca rate limits should call
    /// with explicit asset filters to serialize requests if needed.
    async fn account_snapshot(
        &self,
        assets: &[AssetNameExchange],
        instruments: &[InstrumentNameExchange],
    ) -> Result<UnindexedAccountSnapshot, UnindexedClientError> {
        let base = self.base_url();
        let http = self.http.clone();
        let rl = &self.rate_limiter;

        let wants_usd = assets.is_empty()
            || assets
                .iter()
                .any(|a| a.name().as_str().eq_ignore_ascii_case("usd"));
        let wants_non_usd = assets.is_empty()
            || assets
                .iter()
                .any(|a| !a.name().as_str().eq_ignore_ascii_case("usd"));

        // Fetch account + positions in parallel when both are needed (common startup case).
        // URLs are extracted before the closures to avoid re-allocating on each retry attempt.
        let account_url = format!("{base}/v2/account");
        let positions_url = format!("{base}/v2/positions");
        let balances = match (wants_usd, wants_non_usd) {
            (true, true) => {
                let (account, positions): (AlpacaAccount, Vec<AlpacaPosition>) = tokio::try_join!(
                    rest_with_retry(rl, || http.get(&account_url)),
                    rest_with_retry(rl, || http.get(&positions_url)),
                )?;
                let mut balances = convert_account_to_balances(&account, assets);
                balances.extend(convert_positions_to_balances(&positions, assets));
                balances
            }
            (true, false) => {
                let account: AlpacaAccount = rest_with_retry(rl, || http.get(&account_url)).await?;
                convert_account_to_balances(&account, assets)
            }
            (false, true) => {
                let positions: Vec<AlpacaPosition> =
                    rest_with_retry(rl, || http.get(&positions_url)).await?;
                convert_positions_to_balances(&positions, assets)
            }
            (false, false) => Vec::new(),
        };

        let open_orders = fetch_raw_open_orders(&http, rl, base, instruments).await?;

        // Group open orders by instrument symbol, building InstrumentAccountSnapshots.
        let instrument_snapshots = build_instrument_snapshots(open_orders, instruments);

        Ok(AccountSnapshot::new(
            ExchangeId::AlpacaBroker,
            balances,
            instrument_snapshots,
        ))
    }

    /// Returns a live stream of account events (fills, order updates).
    ///
    /// # Startup race window
    ///
    /// Fills arriving between `account_snapshot` and this method being called by the
    /// caller are not recovered automatically — the WebSocket connection does not exist
    /// yet during that window. Fills that arrive after the connection is established but
    /// before the first poll are buffered in the tungstenite internal buffer and delivered
    /// normally. Callers requiring fill completeness at startup **must** call
    /// [`ExecutionClient::fetch_trades`] with a ~1 s lookback after calling this method.
    ///
    /// This gap also applies on every **reconnect**: during the auth+subscribe handshake
    /// (`connect_and_subscribe`), any `trade_updates` messages that arrive are consumed
    /// by the handshake loop and not forwarded. Fill events in this window are recovered
    /// via the REST activities endpoint (anchored to `disconnect_time`). Lifecycle events
    /// (`new`, `canceled`, `rejected`) consumed during the handshake are **not** recovered
    /// — callers must call `fetch_open_orders` after each reconnect to reconcile order state.
    ///
    /// # Fill recovery ordering
    ///
    /// After a reconnect, missed fills are recovered from the REST activities endpoint
    /// using `direction=asc` to match the chronological order in which the WS stream
    /// advanced `filled_qty`. The dedup key `"{order_id}:{cum_qty}"` is synthesised
    /// by accumulating per-execution qty in that order. If Alpaca returns activities
    /// out of chronological order (e.g. at pagination boundaries), dedup keys will
    /// diverge and fills may be dropped or duplicated for that order.
    ///
    /// # Lifecycle event deduplication
    ///
    /// Order lifecycle events (`new`, `canceled`, `expired`) are **not** deduplicated
    /// across reconnects — only fill events carry a dedup key. After a reconnect, Alpaca
    /// re-delivers lifecycle events for orders that were active at disconnect time.
    /// Specifically, Alpaca re-delivers a `new` event for **every order open at disconnect
    /// time**, not only orders that changed during the gap.
    /// Callers must make [`AccountEventKind::OrderSnapshot`] and
    /// [`AccountEventKind::OrderCancelled`] processing idempotent, or call
    /// [`ExecutionClient::fetch_open_orders`] after each reconnect to reconcile state.
    ///
    /// # Rejected orders
    ///
    /// Alpaca `rejected` events are delivered as `AccountEventKind::OrderCancelled` with
    /// `state: Err(OrderRejected(...))`. Match on `response.state.is_err()` to distinguish
    /// rejections from true cancels — do not call `.unwrap()` on `OrderCancelled.state`.
    ///
    /// # Stream drop behaviour
    ///
    /// Dropping the returned `BoxStream` initiates a graceful shutdown of the
    /// background `connection_manager` task: the channel close causes the task
    /// to send a WebSocket close frame and exit within the current heartbeat
    /// window (≤60 s). Any `AccountEvent` items already queued but not yet
    /// polled are discarded. Callers who drop and re-subscribe must call
    /// [`ExecutionClient::fetch_trades`] with a short lookback to recover the gap.
    async fn account_stream(
        &self,
        _assets: &[AssetNameExchange], // ignored — Alpaca's trade_updates stream delivers all asset classes on one channel
        // instruments is used to filter fill recovery (REST) after a reconnect only.
        // Live WS events are NOT filtered by instrument: Alpaca's trade_updates stream
        // delivers all account events on one channel with no per-symbol subscription.
        instruments: &[InstrumentNameExchange],
    ) -> Result<Self::AccountStream, UnindexedClientError> {
        // Verify the initial connection before returning the stream; distinguishes
        // "can't connect at all" from "connected but later disconnected".
        let initial_ws = connect_and_subscribe(&self.config).await?;

        // Unbounded channel — memory grows if the consumer is slow, but fills
        // are never silently dropped. Silent fill loss corrupts position state;
        // OOM is loudly observable. The WS delivery path uses non-blocking send()
        // which only fails if the receiver is dropped.
        let (tx, rx) = mpsc::unbounded_channel::<UnindexedAccountEvent>();
        let dedup = new_dedup_cache();
        let config = self.config.clone();
        let http = self.http.clone();
        let rate_limiter = self.rate_limiter.clone();
        let instruments = instruments.to_vec();

        let cm_handle = tokio::spawn(connection_manager(
            tx,
            dedup,
            config,
            http,
            rate_limiter,
            instruments,
            Some(initial_ws),
        ));

        let rx_stream = tokio_stream::wrappers::UnboundedReceiverStream::new(rx);
        let guarded = GracefulShutdownStream::new(rx_stream, cm_handle);
        Ok(futures::StreamExt::boxed(guarded))
    }

    async fn cancel_order(
        &self,
        request: OrderRequestCancel<ExchangeId, &InstrumentNameExchange>,
    ) -> Option<UnindexedOrderResponseCancel> {
        let key = crate::order::OrderKey {
            exchange: request.key.exchange,
            instrument: request.key.instrument.clone(),
            strategy: request.key.strategy.clone(),
            cid: request.key.cid.clone(),
        };

        // Require the exchange order ID — Alpaca's DELETE endpoint uses the UUID.
        // If only clientOrderId is available, the caller should first resolve it
        // via fetch_open_orders.
        let order_id: SmolStr = match &request.state.id {
            Some(id) => id.0.clone(),
            None => {
                warn!(
                    instrument = %key.instrument,
                    "Alpaca cancel_order: no exchange order ID available (clientOrderId-only cancel not supported)"
                );
                return Some(crate::order::request::OrderResponseCancel {
                    key,
                    state: Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(
                        "exchange order ID required for cancel (fetch_open_orders to resolve)"
                            .into(),
                    ))),
                });
            }
        };

        let base = self.base_url();
        let http = self.http.clone();
        let url = format!("{base}/v2/orders/{order_id}");

        match rest_delete_with_retry(&self.rate_limiter, || http.delete(&url)).await {
            Ok(()) => {
                let exchange_order_id = OrderId(order_id);
                // REST DELETE returns no response body, so filled_qty unavailable.
                // Use ZERO; downstream can reconcile via WS events or fetch_open_orders.
                Some(crate::order::request::OrderResponseCancel {
                    key,
                    state: Ok(Cancelled::new(exchange_order_id, Utc::now(), Decimal::ZERO)),
                })
            }
            Err(e) => Some(crate::order::request::OrderResponseCancel { key, state: Err(e) }),
        }
    }

    /// # Position intent derivation
    ///
    /// Alpaca options/equities require explicit `position_intent`. This impl derives
    /// intent from `RequestOpen::reduce_only` and `side`:
    ///
    /// | reduce_only | side | intent       | use case                          |
    /// |-------------|------|--------------|-----------------------------------|
    /// | false       | Buy  | BuyToOpen    | open long / add to long position  |
    /// | false       | Sell | SellToOpen   | open short / write option         |
    /// | true        | Buy  | BuyToClose   | close short position              |
    /// | true        | Sell | SellToClose  | close long position               |
    ///
    /// For explicit control, use [`AlpacaClient::open_order_with_intent`].
    ///
    /// # Market order price
    ///
    /// The returned `Order.price` echoes the request price. For market orders this is
    /// typically `Decimal::ZERO` (a placeholder). The **actual fill price** arrives via
    /// the WebSocket `trade_updates` stream as a `Trade` event. Do not rely on
    /// `Order.price` from this REST ack for market order fill prices.
    async fn open_order(
        &self,
        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
    ) -> Option<Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> {
        let side = request.state.side;
        let reduce_only = request.state.reduce_only;
        self.open_order_inner(request, map_position_intent(side, reduce_only))
            .await
    }

    /// Fetches balances sequentially (unlike `account_snapshot` which parallelizes).
    ///
    /// Sequential fetch is intentional for live operation: under rate pressure, parallel
    /// requests may both hit 429 simultaneously and retry independently, doubling the
    /// backoff delay. The startup latency savings from `account_snapshot`'s parallel
    /// fetch are worth the tradeoff there; for periodic balance refreshes during live
    /// trading, sequential is safer.
    async fn fetch_balances(
        &self,
        assets: &[AssetNameExchange],
    ) -> Result<Vec<AssetBalance<AssetNameExchange>>, UnindexedClientError> {
        let base = self.base_url();
        let http = self.http.clone();
        let mut result = Vec::new();

        // Only fetch the account (USD balance) when USD is among the requested assets.
        // Crypto-only requests skip this call to conserve rate-limit budget.
        let wants_usd = assets.is_empty()
            || assets
                .iter()
                .any(|a| a.name().as_str().eq_ignore_ascii_case("usd"));
        if wants_usd {
            // Pre-allocate URL to avoid re-allocation on each retry attempt.
            let account_url = format!("{base}/v2/account");
            let account: AlpacaAccount =
                rest_with_retry(&self.rate_limiter, || http.get(&account_url)).await?;
            result.extend(convert_account_to_balances(&account, assets));
        }

        // Fetch positions for non-USD asset balances (e.g., BTC, ETH from crypto holdings).
        let wants_non_usd = assets.is_empty()
            || assets
                .iter()
                .any(|a| !a.name().as_str().eq_ignore_ascii_case("usd"));
        if wants_non_usd {
            // Pre-allocate URL to avoid re-allocation on each retry attempt.
            let positions_url = format!("{base}/v2/positions");
            let positions: Vec<AlpacaPosition> =
                rest_with_retry(&self.rate_limiter, || http.get(&positions_url)).await?;
            result.extend(convert_positions_to_balances(&positions, assets));
        }

        Ok(result)
    }

    async fn fetch_open_orders(
        &self,
        instruments: &[InstrumentNameExchange],
    ) -> Result<Vec<Order<ExchangeId, InstrumentNameExchange, Open>>, UnindexedClientError> {
        let base = self.base_url();
        let http = self.http.clone();

        let open_orders =
            fetch_raw_open_orders(&http, &self.rate_limiter, base, instruments).await?;

        let result = open_orders
            .into_iter()
            .filter_map(|o| convert_open_order(&o))
            .collect();
        Ok(result)
    }

    async fn fetch_trades(
        &self,
        time_since: DateTime<Utc>,
        instruments: &[InstrumentNameExchange],
    ) -> Result<Vec<Trade<AssetNameExchange, InstrumentNameExchange>>, UnindexedClientError> {
        let after_str = time_since.to_rfc3339();
        let base = self.base_url();
        let http = self.http.clone();

        let page = paginate_activities(&http, &self.rate_limiter, base, &after_str).await?;

        // Propagate truncation as an error so callers can detect incomplete results.
        // The crypto repo can match on `Truncated` and alert operators.
        if page.truncated {
            return Err(UnindexedClientError::Truncated {
                limit: MAX_ACTIVITY_PAGES,
            });
        }

        // Empty instruments slice means "all instruments" — same convention as
        // fetch_open_orders. Build a set only when filtering is needed.
        let trades = if instruments.is_empty() {
            page.activities
                .into_iter()
                .filter_map(|a| convert_activity_to_trade(&a))
                .collect()
        } else {
            let instrument_set: fnv::FnvHashSet<&str> =
                instruments.iter().map(|i| i.name().as_str()).collect();
            page.activities
                .into_iter()
                .filter(|a| instrument_set.contains(a.symbol.as_str()))
                .filter_map(|a| convert_activity_to_trade(&a))
                .collect()
        };

        Ok(trades)
    }
}

// ---------------------------------------------------------------------------
// AlpacaClient public extension methods (not on ExecutionClient trait)
// ---------------------------------------------------------------------------

impl AlpacaClient {
    /// Place an order with an explicit `position_intent` override.
    ///
    /// Use this instead of `ExecutionClient::open_order` when you need to specify
    /// exact position intent (e.g. `SellToOpen` for writing a short option, or
    /// `BuyToClose` for closing a short position by buying).
    ///
    /// `intent` is only sent for non-crypto symbols. For crypto symbols (those
    /// containing `/`) the field is always omitted regardless of `intent`.
    ///
    /// # Caller obligations
    /// The caller is responsible for passing the semantically correct intent.
    /// No validation is performed against the order side or existing position.
    pub async fn open_order_with_intent(
        &self,
        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
        intent: AlpacaPositionIntent,
    ) -> Option<Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> {
        self.open_order_inner(request, intent).await
    }

    /// Place a bracket order (entry + take-profit + stop-loss) in a single request.
    ///
    /// A bracket order consists of three linked orders:
    /// 1. **Entry**: Limit order to enter the position
    /// 2. **Take Profit**: Limit order to exit at profit target
    /// 3. **Stop Loss**: Stop (or stop-limit) order to exit at loss limit
    ///
    /// When the entry order fills, Alpaca activates both exit legs. When either
    /// exit leg fills, Alpaca automatically cancels the other.
    ///
    /// # Constraints
    ///
    /// - `time_in_force` must be `Day` or `GoodUntilCancelled` (Alpaca rejects others)
    /// - No extended hours trading with bracket orders
    /// - Entry is always a limit order
    ///
    /// # Example
    ///
    /// ```ignore
    /// let request = AlpacaBracketOrderRequest::new(
    ///     "AAPL".into(),
    ///     StrategyId::new("momentum"),
    ///     ClientOrderId::new("bracket-001"),
    ///     Side::Buy,
    ///     dec!(10),
    ///     dec!(150.00),  // entry
    ///     dec!(160.00),  // take profit
    ///     dec!(145.00),  // stop loss
    ///     TimeInForce::GoodUntilCancelled { post_only: false },
    /// );
    /// let result = client.open_bracket_order(request).await;
    /// ```
    pub async fn open_bracket_order(
        &self,
        request: AlpacaBracketOrderRequest,
    ) -> AlpacaBracketOrderResult {
        let order_key = crate::order::OrderKey::new(
            ExchangeId::AlpacaBroker,
            request.instrument.clone(),
            request.strategy.clone(),
            request.cid.clone(),
        );

        // Validate time_in_force: bracket orders only support day or gtc
        let tif_str = match request.time_in_force {
            TimeInForce::GoodUntilEndOfDay => "day",
            TimeInForce::GoodUntilCancelled { post_only } => {
                if post_only {
                    return AlpacaBracketOrderResult {
                        parent: Order {
                            key: order_key,
                            side: request.side,
                            price: Some(request.entry_price),
                            quantity: request.quantity,
                            kind: OrderKind::Limit,
                            time_in_force: request.time_in_force,
                            state: OrderState::inactive(OrderError::Rejected(
                                ApiError::OrderRejected(
                                    "Alpaca does not support post_only for bracket orders"
                                        .to_string(),
                                ),
                            )),
                        },
                    };
                }
                "gtc"
            }
            other => {
                return AlpacaBracketOrderResult {
                    parent: Order {
                        key: order_key,
                        side: request.side,
                        price: Some(request.entry_price),
                        quantity: request.quantity,
                        kind: OrderKind::Limit,
                        time_in_force: request.time_in_force,
                        state: OrderState::inactive(OrderError::Rejected(ApiError::OrderRejected(
                            format!(
                                "Alpaca bracket orders only support Day or GTC time_in_force, got {:?}",
                                other
                            ),
                        ))),
                    },
                };
            }
        };

        // Validate price ordering. Alpaca rejects mis-ordered brackets with a
        // generic 422; surface a structured local error before round-trip.
        let price_ordering_ok = match request.side {
            Side::Buy => {
                request.stop_loss_price < request.entry_price
                    && request.entry_price < request.take_profit_price
            }
            Side::Sell => {
                request.take_profit_price < request.entry_price
                    && request.entry_price < request.stop_loss_price
            }
        };
        if !price_ordering_ok {
            return AlpacaBracketOrderResult {
                parent: Order {
                    key: order_key,
                    side: request.side,
                    price: Some(request.entry_price),
                    quantity: request.quantity,
                    kind: OrderKind::Limit,
                    time_in_force: request.time_in_force,
                    state: OrderState::inactive(OrderError::Rejected(ApiError::OrderRejected(
                        format!(
                            "Invalid bracket price ordering for {:?} side: entry={}, take_profit={}, stop_loss={}",
                            request.side,
                            request.entry_price,
                            request.take_profit_price,
                            request.stop_loss_price,
                        ),
                    ))),
                },
            };
        }

        // Validate stop-loss limit price if provided. For a Buy bracket, the SL
        // is a sell stop(-limit); the limit must be at or below the trigger so
        // the order can fill if price gaps down. Reverse for Sell brackets.
        if let Some(sl_limit) = request.stop_loss_limit_price {
            let sl_limit_ok = match request.side {
                Side::Buy => sl_limit <= request.stop_loss_price,
                Side::Sell => sl_limit >= request.stop_loss_price,
            };
            if !sl_limit_ok {
                return AlpacaBracketOrderResult {
                    parent: Order {
                        key: order_key,
                        side: request.side,
                        price: Some(request.entry_price),
                        quantity: request.quantity,
                        kind: OrderKind::Limit,
                        time_in_force: request.time_in_force,
                        state: OrderState::inactive(OrderError::Rejected(ApiError::OrderRejected(
                            format!(
                                "Invalid stop-loss limit price for {:?} bracket: \
                                 stop_loss_price={}, stop_loss_limit_price={}",
                                request.side, request.stop_loss_price, sl_limit,
                            ),
                        ))),
                    },
                };
            }
        }

        // Build the bracket order request
        let body = AlpacaOrderRequest {
            symbol: request.instrument.name().as_str(),
            qty: request.quantity.to_string(),
            side: map_side(request.side),
            order_type: "limit",
            time_in_force: tif_str,
            limit_price: Some(request.entry_price.to_string()),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            client_order_id: Some(request.cid.0.as_str()),
            position_intent: if is_options_or_equity_symbol(request.instrument.name().as_str()) {
                Some(map_position_intent(request.side, false))
            } else {
                None
            },
            order_class: Some("bracket"),
            take_profit: Some(TakeProfitParams {
                limit_price: request.take_profit_price.to_string(),
            }),
            stop_loss: Some(StopLossParams {
                stop_price: request.stop_loss_price.to_string(),
                limit_price: request.stop_loss_limit_price.map(|p| p.to_string()),
            }),
        };

        let http = self.http.clone();
        let rl = &self.rate_limiter;

        let result: Result<AlpacaOrderResponse, UnindexedClientError> =
            rest_with_retry(rl, || http.post(&self.orders_url).json(&body)).await;

        match result {
            Ok(resp) => {
                let exchange_order_id = OrderId(SmolStr::new(&resp.id));
                let time_exchange = parse_timestamp(&resp.created_at).unwrap_or_else(Utc::now);
                let filled_qty = Decimal::from_str(&resp.filled_qty).unwrap_or(Decimal::ZERO);

                let state = if filled_qty >= request.quantity {
                    OrderState::fully_filled(Filled::new(
                        exchange_order_id,
                        time_exchange,
                        filled_qty,
                        None,
                    ))
                } else {
                    OrderState::active(Open::new(exchange_order_id, time_exchange, filled_qty))
                };

                AlpacaBracketOrderResult {
                    parent: Order {
                        key: order_key,
                        side: request.side,
                        price: Some(request.entry_price),
                        quantity: request.quantity,
                        kind: OrderKind::Limit,
                        time_in_force: request.time_in_force,
                        state,
                    },
                }
            }
            Err(e) => {
                let order_err = match e {
                    UnindexedClientError::Connectivity(ce) => OrderError::Connectivity(ce),
                    UnindexedClientError::Api(ae) => OrderError::Rejected(ae),
                    UnindexedClientError::TaskFailed(_)
                    | UnindexedClientError::Internal(_)
                    | UnindexedClientError::Truncated { .. }
                    | UnindexedClientError::TruncatedSnapshot { .. } => {
                        unreachable!("rest_with_retry (order path) does not produce these variants")
                    }
                };
                AlpacaBracketOrderResult {
                    parent: Order {
                        key: order_key,
                        side: request.side,
                        price: Some(request.entry_price),
                        quantity: request.quantity,
                        kind: OrderKind::Limit,
                        time_in_force: request.time_in_force,
                        state: OrderState::inactive(order_err),
                    },
                }
            }
        }
    }

    async fn open_order_inner(
        &self,
        request: OrderRequestOpen<ExchangeId, &InstrumentNameExchange>,
        intent: AlpacaPositionIntent,
    ) -> Option<Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>> {
        let instrument = request.key.instrument.clone();
        let side = request.state.side;
        let price = request.state.price;
        let quantity = request.state.quantity;
        let kind = request.state.kind;
        let time_in_force = request.state.time_in_force;
        let cid = request.key.cid.clone();

        let order_key = crate::order::OrderKey::new(
            ExchangeId::AlpacaBroker,
            instrument.clone(),
            request.key.strategy.clone(),
            cid.clone(),
        );

        // Validate time_in_force before building the request — reject post_only early.
        let tif_str = match map_time_in_force(time_in_force) {
            Ok(s) => s,
            Err(msg) => {
                return Some(Order {
                    key: order_key,
                    side,
                    price,
                    quantity,
                    kind,
                    time_in_force,
                    state: OrderState::inactive(OrderError::Rejected(ApiError::OrderRejected(
                        msg.to_string(),
                    ))),
                });
            }
        };

        // Validate order kind — reject unsupported types early.
        let order_type_str = match map_order_kind(kind) {
            Some(s) => s,
            None => {
                return Some(Order {
                    key: order_key,
                    side,
                    price,
                    quantity,
                    kind,
                    time_in_force,
                    state: OrderState::inactive(OrderError::UnsupportedOrderType(format!(
                        "Alpaca connector does not yet support OrderKind::{kind:?}"
                    ))),
                });
            }
        };

        // Validate trailing stop offset type — Alpaca only supports percent and absolute.
        if let OrderKind::TrailingStop {
            offset_type: TrailingOffsetType::BasisPoints,
            ..
        } = kind
        {
            return Some(Order {
                key: order_key,
                side,
                price,
                quantity,
                kind,
                time_in_force,
                state: OrderState::inactive(OrderError::UnsupportedOrderType(
                    "Alpaca does not support TrailingOffsetType::BasisPoints; \
                     use Percentage or Absolute"
                        .to_string(),
                )),
            });
        }

        // StopLimit requires Order.price (the limit price applied once trigger fires).
        // Guard locally to avoid a wire round-trip producing a generic 422.
        if matches!(kind, OrderKind::StopLimit { .. }) && price.is_none() {
            return Some(Order {
                key: order_key,
                side,
                price,
                quantity,
                kind,
                time_in_force,
                state: OrderState::inactive(OrderError::Rejected(ApiError::OrderRejected(
                    "StopLimit order requires Order.price (the limit price) to be set".to_string(),
                ))),
            });
        }

        // Extract stop/trailing parameters based on order kind.
        let (stop_price, trail_percent, trail_price) = match kind {
            OrderKind::Stop { trigger_price } | OrderKind::StopLimit { trigger_price } => {
                (Some(trigger_price.to_string()), None, None)
            }
            OrderKind::TrailingStop {
                offset,
                offset_type,
            } => match offset_type {
                TrailingOffsetType::Percentage => (None, Some(offset.to_string()), None),
                TrailingOffsetType::Absolute => (None, None, Some(offset.to_string())),
                TrailingOffsetType::BasisPoints => unreachable!("validated above"),
            },
            OrderKind::Market | OrderKind::Limit | OrderKind::TrailingStopLimit { .. } => {
                (None, None, None)
            }
        };

        let body = AlpacaOrderRequest {
            symbol: instrument.name().as_str(),
            qty: quantity.to_string(),
            side: map_side(side),
            order_type: order_type_str,
            time_in_force: tif_str,
            limit_price: match kind {
                OrderKind::Limit | OrderKind::StopLimit { .. } => price.map(|p| p.to_string()),
                _ => None,
            },
            stop_price,
            trail_percent,
            trail_price,
            client_order_id: Some(cid.0.as_str()),
            // position_intent is required for options orders and valid (but optional)
            // for equities. It is NOT a valid field for crypto orders and must be
            // omitted, or Alpaca will return 422 Unprocessable Entity.
            // We detect options by OCC symbol format; equities also get the field
            // as it aids intent tracking on margin accounts.
            position_intent: if is_options_or_equity_symbol(instrument.name().as_str()) {
                Some(intent)
            } else {
                None
            },
            // Non-bracket order: no bracket fields
            order_class: None,
            take_profit: None,
            stop_loss: None,
        };

        let http = self.http.clone();
        let rl = &self.rate_limiter;

        let result: Result<AlpacaOrderResponse, UnindexedClientError> =
            rest_with_retry(rl, || http.post(&self.orders_url).json(&body)).await;

        match result {
            Ok(resp) => {
                let exchange_order_id = OrderId(SmolStr::new(&resp.id));
                let time_exchange = parse_timestamp(&resp.created_at).unwrap_or_else(Utc::now);
                let filled_qty = Decimal::from_str(&resp.filled_qty).unwrap_or(Decimal::ZERO);

                let state = if filled_qty >= quantity {
                    // Order was fully filled immediately (market order or aggressive limit)
                    OrderState::fully_filled(Filled::new(
                        exchange_order_id,
                        time_exchange,
                        filled_qty,
                        None, // Alpaca order response doesn't include avg_price
                    ))
                } else {
                    // Order is resting on the order book (partially filled or unfilled)
                    OrderState::active(Open::new(exchange_order_id, time_exchange, filled_qty))
                };

                Some(Order {
                    key: order_key,
                    side,
                    price,
                    quantity,
                    kind,
                    time_in_force,
                    state,
                })
            }
            Err(e) => {
                let order_err = match e {
                    UnindexedClientError::Connectivity(ce) => OrderError::Connectivity(ce),
                    UnindexedClientError::Api(ae) => OrderError::Rejected(ae),
                    // TaskFailed, Internal, Truncated, and TruncatedSnapshot are not
                    // returned by rest_with_retry (REST-only path for orders), but matching
                    // explicitly ensures any new ClientError variant causes a compile error
                    // here rather than being silently misclassified. If a future refactor
                    // makes them reachable, the panic surfaces the bug loudly rather than
                    // producing a wrong error type.
                    UnindexedClientError::TaskFailed(_)
                    | UnindexedClientError::Internal(_)
                    | UnindexedClientError::Truncated { .. }
                    | UnindexedClientError::TruncatedSnapshot { .. } => {
                        unreachable!(
                            "rest_with_retry (order path) does not produce TaskFailed/Internal/Truncated/TruncatedSnapshot variants"
                        )
                    }
                };
                Some(Order {
                    key: order_key,
                    side,
                    price,
                    quantity,
                    kind,
                    time_in_force,
                    state: OrderState::inactive(order_err),
                })
            }
        }
    }
}

// ---------------------------------------------------------------------------
// REST helpers
// ---------------------------------------------------------------------------

/// Maximum number of open orders returned by a single `/v2/orders` request.
///
/// Alpaca's API caps at 500; accounts exceeding this have an incomplete snapshot.
const MAX_OPEN_ORDERS: usize = 500;

/// Fetch all open orders from Alpaca, optionally filtered by symbol.
///
/// # Errors
///
/// Returns [`UnindexedClientError::TruncatedSnapshot`] when exactly 500 results
/// are returned, indicating the API limit was likely hit and data may be incomplete.
/// This is an Alpaca API limitation with no pagination support for open orders.
async fn fetch_raw_open_orders(
    http: &reqwest::Client,
    rate_limiter: &RateLimitTracker,
    base: &str,
    instruments: &[InstrumentNameExchange],
) -> Result<Vec<AlpacaOrderResponse>, UnindexedClientError> {
    let orders: Vec<AlpacaOrderResponse> = if instruments.is_empty() {
        rest_with_retry(rate_limiter, || {
            http.get(format!("{base}/v2/orders"))
                .query(&[("status", "open"), ("limit", "500")])
        })
        .await?
    } else {
        let symbols = instruments.iter().map(|i| i.name().as_str()).join(",");
        rest_with_retry(rate_limiter, || {
            http.get(format!("{base}/v2/orders")).query(&[
                ("status", "open"),
                ("limit", "500"),
                ("symbols", &symbols),
            ])
        })
        .await?
    };
    if orders.len() == MAX_OPEN_ORDERS {
        warn!(
            limit = MAX_OPEN_ORDERS,
            "Alpaca fetch_raw_open_orders: received exactly {MAX_OPEN_ORDERS} results — \
             response is likely truncated"
        );
        return Err(UnindexedClientError::TruncatedSnapshot {
            limit: MAX_OPEN_ORDERS,
        });
    }
    Ok(orders)
}

// ---------------------------------------------------------------------------
// Activity pagination
// ---------------------------------------------------------------------------

/// Maximum number of pages fetched by [`paginate_activities`].
///
/// 50 pages × 100 items = 5 000 fills. Exceeding this during recovery indicates
/// an unusually long outage; we warn and truncate rather than looping forever.
const MAX_ACTIVITY_PAGES: usize = 50;

/// Result of [`paginate_activities`] including truncation status.
///
/// When `truncated` is true, the `activities` vector contains a partial result
/// capped at [`MAX_ACTIVITY_PAGES`] pages. Callers should handle this case
/// appropriately — typically by alerting operators about potential data loss.
struct ActivityPage {
    activities: Vec<AlpacaActivity>,
    truncated: bool,
}

/// Fetch all FILL activities since `after` using token-based pagination.
///
/// Alpaca returns up to `ALPACA_MAX_ACTIVITIES` per page. If a full page is
/// returned, the next request uses the last item's `id` as the `page_token`.
/// Pagination terminates when a page has fewer items than `page_size`, or after
/// [`MAX_ACTIVITY_PAGES`] pages (whichever comes first).
///
/// Returns [`ActivityPage`] with `truncated = true` if the page limit was reached,
/// allowing callers to detect and handle partial results.
// Compile-time string form of ALPACA_MAX_ACTIVITIES (avoids runtime to_string() allocation).
const PAGE_SIZE_STR: &str = "100"; // must match ALPACA_MAX_ACTIVITIES
const _: () = assert!(
    ALPACA_MAX_ACTIVITIES == 100,
    "PAGE_SIZE_STR must be updated to match ALPACA_MAX_ACTIVITIES",
);

async fn paginate_activities(
    http: &reqwest::Client,
    rate_limiter: &RateLimitTracker,
    base: &str,
    after: &str,
) -> Result<ActivityPage, UnindexedClientError> {
    let mut all = Vec::with_capacity(ALPACA_MAX_ACTIVITIES);
    let mut page_token: Option<String> = None;
    let mut pages = 0usize;
    let mut truncated = false;

    loop {
        if pages >= MAX_ACTIVITY_PAGES {
            truncated = true;
            break;
        }
        pages += 1;
        // Borrow page_token as &str so the closure can capture by reference without cloning.
        let page_token_ref = page_token.as_deref();
        let activities: Vec<AlpacaActivity> = rest_with_retry(rate_limiter, || {
            let mut req = http.get(format!("{base}/v2/account/activities")).query(&[
                ("activity_type", "FILL"),
                ("after", after),
                ("page_size", PAGE_SIZE_STR),
                ("direction", "asc"),
            ]);
            if let Some(token) = page_token_ref {
                req = req.query(&[("page_token", token)]);
            }
            req
        })
        .await?;

        let page_len = activities.len();
        // Capture the page token from the current page BEFORE extending `all`, so that
        // any future filtering between here and all.extend cannot shift the last element
        // and cause the same page to be re-fetched indefinitely.
        //
        // Alpaca activity IDs are ULID-format (monotonically increasing) and are accepted
        // as exclusive page_token cursors by GET /v2/account/activities: the next page
        // begins with the item AFTER the token, so the boundary item is not re-delivered.
        // The pagination contract relies on this property — verify against Alpaca API docs
        // if behaviour changes.
        let page_token_candidate = activities.last().map(|a| a.id.clone());
        all.extend(activities);

        if page_len < ALPACA_MAX_ACTIVITIES {
            break;
        }
        match page_token_candidate {
            Some(token) if !token.is_empty() => {
                debug!("Alpaca paginate_activities: fetching next page ({page_len} results)");
                page_token = Some(token);
            }
            // Empty token or no last item — pagination complete.
            // Guard against empty string to prevent infinite loop if Alpaca ever
            // returns a full page with last.id = "" (would restart from beginning).
            _ => break,
        }
    }

    Ok(ActivityPage {
        activities: all,
        truncated,
    })
}

// ---------------------------------------------------------------------------
// WebSocket connection manager
// ---------------------------------------------------------------------------

/// Long-running task managing the WebSocket lifecycle for account_stream.
///
/// Loop: connect → auth → subscribe → stream events → on disconnect → backoff
/// → fill recovery → reconnect. The `tx` channel persists across reconnections
/// so the consumer sees a seamless event stream.
///
/// Terminates when the consumer drops the stream or max reconnect attempts are
/// exhausted.
#[allow(clippy::cognitive_complexity)] // the inner select! loop owns `ws` and mutates `backoff` —
// extracting to a function requires threading 4 non-Clone values (ws, tx, dedup, backoff)
// through the call, which adds more complexity than it removes
async fn connection_manager(
    tx: mpsc::UnboundedSender<UnindexedAccountEvent>,
    dedup: SharedDedupCache,
    config: Arc<AlpacaConfig>,
    http: reqwest::Client,
    rate_limiter: Arc<RateLimitTracker>,
    instruments: Vec<InstrumentNameExchange>,
    initial_ws: Option<WebSocket>,
) {
    let mut backoff = ExponentialBackoff::new();
    let mut disconnect_time: Option<DateTime<Utc>> = None;
    let mut current_ws = initial_ws;

    'outer: loop {
        // --- Connect (skip on first iteration if initial_ws was provided) ---
        let mut ws = match current_ws.take() {
            Some(ws) => ws,
            None => match connect_and_subscribe(&config).await {
                Ok(ws) => ws,
                Err(e) => {
                    error!(%e, "Alpaca WS connect/subscribe failed");
                    if !backoff.wait().await {
                        error!("Alpaca max reconnect attempts exhausted");
                        break;
                    }
                    continue;
                }
            },
        };
        info!("Alpaca account_stream connected and subscribed");
        // Session established — reset backoff regardless of whether any text events
        // arrive. Without this, a heartbeat-only session (Pings only, no trade_updates)
        // would never call process_ws_text and therefore never reset the counter,
        // causing the next disconnect to exhaust the reconnect budget faster than expected.
        //
        // Edge case: if the server accepts the WS handshake and immediately closes the
        // connection (fast-accept-close loop), backoff resets on every iteration, causing
        // all MAX_RECONNECT_ATTEMPTS attempts to run at INITIAL_BACKOFF_MS rather than
        // escalating. This is accepted behaviour for this pathological server scenario —
        // the 10-attempt budget still provides ~10 s of protection before giving up.
        backoff.reset();

        // --- Fill recovery after reconnect ---
        // Runs before the event loop so live events arriving during recovery are
        // captured by the already-connected WS session. The dedup cache prevents
        // duplicates between recovered REST fills and live WS events.
        if let Some(dt) = disconnect_time.take() {
            let base = config.rest_base_url();
            let after_str = dt.to_rfc3339();
            match tokio::time::timeout(
                Duration::from_secs(FILL_RECOVERY_TIMEOUT_SECS),
                recover_fills(
                    &http,
                    &rate_limiter,
                    &instruments,
                    base,
                    &after_str,
                    &tx,
                    &dedup,
                ),
            )
            .await
            {
                Ok(()) => {}
                Err(_) => warn!(
                    timeout_secs = FILL_RECOVERY_TIMEOUT_SECS,
                    "Alpaca fill recovery timed out — some fills may be missing"
                ),
            }
        }

        // --- Stream events ---
        // Each iteration of the inner loop polls ws.next(), a heartbeat timer,
        // and tx.closed() simultaneously via select!. The heartbeat deadline is
        // reset on every received message (rolling window).
        //
        // The timer is pinned once and reset in-place via Sleep::reset(), avoiding
        // a new Sleep allocation and Tokio timer-wheel registration per loop iteration.
        // Track the wall-clock time of the last received message. Used to anchor
        // fill recovery after a heartbeat timeout: Utc::now() at reconnect time
        // would be ~HEARTBEAT_TIMEOUT_SECS after the last real message, causing
        // the recovery window to miss fills in that silent period.

        let mut last_message_time = Utc::now();
        let heartbeat = tokio::time::sleep(Duration::from_secs(HEARTBEAT_TIMEOUT_SECS));
        tokio::pin!(heartbeat);

        // Resets the rolling heartbeat deadline and records the wall-clock receive time.
        // Pin<&mut Sleep> cannot be passed to a regular function, so a macro avoids
        // repeating the same two-line block across every message-bearing select! arm.
        // NOTE: must be defined AFTER the variables it captures for macro hygiene.
        macro_rules! reset_heartbeat {
            () => {
                heartbeat.as_mut().reset(
                    tokio::time::Instant::now() + Duration::from_secs(HEARTBEAT_TIMEOUT_SECS),
                );
                last_message_time = Utc::now();
            };
        }
        loop {
            tokio::select! {
                msg = ws.next() => {
                    match msg {
                        Some(Ok(WsMessage::Ping(_))) => {
                            // tokio-tungstenite automatically queues a Pong when poll_next
                            // returns a Ping; sending a second Pong would be a duplicate.
                            reset_heartbeat!();
                        }
                        Some(Ok(WsMessage::Text(text))) => {
                            process_ws_text(text.as_str(), &tx, &dedup, &mut backoff);
                            reset_heartbeat!();
                        }
                        Some(Ok(WsMessage::Binary(bytes))) => {
                            // Alpaca paper trading sends binary-framed JSON.
                            match std::str::from_utf8(&bytes) {
                                Ok(text) => {
                                    process_ws_text(text, &tx, &dedup, &mut backoff);
                                    // Only reset heartbeat for valid UTF-8 frames that may carry
                                    // real events. A corrupt binary frame (e.g. from a proxy)
                                    // must not keep the watchdog from firing.
                                    reset_heartbeat!();
                                }
                                Err(e) => warn!(%e, "Alpaca WS binary frame: not valid UTF-8"),
                            }
                        }
                        Some(Ok(WsMessage::Close(frame))) => {
                            warn!(frame = ?frame, "Alpaca WS closed by server");
                            break;
                        }
                        Some(Ok(_)) => {} // Pong, Frame — ignore
                        Some(Err(e)) => {
                            warn!(%e, "Alpaca WS error, reconnecting");
                            break;
                        }
                        None => {
                            warn!("Alpaca WS stream ended, reconnecting");
                            break;
                        }
                    }
                }
                _ = &mut heartbeat => {
                    warn!(
                        timeout_secs = HEARTBEAT_TIMEOUT_SECS,
                        "Alpaca heartbeat timeout, reconnecting"
                    );
                    // Heartbeat timeout is a failure — do NOT reset backoff here.
                    // Backoff resets on successful event receipt in process_ws_text.
                    break;
                }
                _ = tx.closed() => {
                    debug!("Alpaca account_stream consumer dropped, terminating");
                    let _ = tokio::time::timeout(
                        Duration::from_secs(WS_CLOSE_TIMEOUT_SECS),
                        ws.close(None),
                    ).await;
                    break 'outer;
                }
            }
        }

        // --- Record disconnect time for fill recovery ---
        // Anchor to last_message_time, not Utc::now(). For heartbeat-triggered
        // disconnects, Utc::now() would be ~HEARTBEAT_TIMEOUT_SECS after the last
        // real message, causing the recovery window to miss fills in that gap.
        disconnect_time =
            Some(last_message_time - chrono::Duration::milliseconds(SIGNAL_RECOVERY_LOOKBACK_MS));

        // --- Close stale WS ---
        let _ =
            tokio::time::timeout(Duration::from_secs(WS_CLOSE_TIMEOUT_SECS), ws.close(None)).await;

        if tx.is_closed() {
            break;
        }
        if !backoff.wait().await {
            error!("Alpaca max reconnect attempts exhausted, stream terminating");
            break;
        }
    }
}

/// Error during WebSocket handshake (auth + subscribe).
///
/// Separates transport errors (network issues, connection drops) from auth errors
/// (invalid credentials) so callers can apply appropriate retry logic.
#[derive(Debug)]
enum HandshakeError {
    /// Network-level failure (WS send failed, connection dropped).
    /// Transient — retry with backoff.
    Transport(String),
    /// Authentication rejected by Alpaca (invalid/expired credentials).
    /// Not transient — do not retry without credential changes.
    Auth(String),
}

/// Connect to the Alpaca WebSocket, authenticate, and subscribe to trade_updates.
///
/// On auth or subscribe failure the connection is closed cleanly.
async fn connect_and_subscribe(config: &AlpacaConfig) -> Result<WebSocket, UnindexedClientError> {
    let url = config.ws_url();
    debug!(%url, "Alpaca: connecting to WebSocket");

    let mut ws = rustrade_integration::protocol::websocket::connect(url)
        .await
        .map_err(|e| {
            UnindexedClientError::Connectivity(ConnectivityError::Socket(format!(
                "WS connect: {e}"
            )))
        })?;

    // auth + subscribe with overall timeout
    let result = tokio::time::timeout(
        Duration::from_secs(WS_HANDSHAKE_TIMEOUT_SECS),
        ws_handshake(&mut ws, config),
    )
    .await;

    match result {
        Ok(Ok(())) => Ok(ws),
        Ok(Err(HandshakeError::Transport(e))) => {
            let _ = ws.close(None).await;
            Err(UnindexedClientError::Connectivity(
                ConnectivityError::Socket(e),
            ))
        }
        Ok(Err(HandshakeError::Auth(e))) => {
            let _ = ws.close(None).await;
            Err(UnindexedClientError::Api(ApiError::Unauthenticated(e)))
        }
        Err(_) => {
            let _ = ws.close(None).await;
            Err(UnindexedClientError::Connectivity(
                ConnectivityError::Timeout,
            ))
        }
    }
}

/// Perform the Alpaca WS auth + subscribe sequence on a connected WebSocket.
///
/// Protocol:
/// 1. Send `{"action":"auth","key":...,"secret":...}`
/// 2. Await `{"stream":"authorization","data":{"status":"authorized",...}}`
/// 3. Send `{"action":"listen","data":{"streams":["trade_updates"]}}`
/// 4. Await `{"stream":"listening","data":{"streams":["trade_updates"]}}`
async fn ws_handshake(ws: &mut WebSocket, config: &AlpacaConfig) -> Result<(), HandshakeError> {
    // Step 1: send auth
    let auth = serde_json::json!({
        "action": "auth",
        "key": config.api_key(),
        // direct field access within module — secret_key has no pub getter to
        // prevent external credential exposure
        "secret": config.secret_key,
    })
    .to_string();
    ws.send(WsMessage::Text(auth.into()))
        .await
        .map_err(|e| HandshakeError::Transport(format!("WS auth send: {e}")))?;

    // Step 2: wait for authorization message
    loop {
        match ws.next().await {
            Some(Ok(WsMessage::Text(text))) => {
                if let Some(result) = check_auth_response(text.as_str()) {
                    result?;
                    break;
                }
            }
            Some(Ok(WsMessage::Binary(bytes))) => {
                if let Ok(text) = std::str::from_utf8(&bytes)
                    && let Some(result) = check_auth_response(text)
                {
                    result?;
                    break;
                }
            }
            Some(Err(e)) => {
                return Err(HandshakeError::Transport(format!(
                    "WS error during auth: {e}"
                )));
            }
            None => {
                return Err(HandshakeError::Transport(
                    "WS closed before auth response".into(),
                ));
            }
            _ => {} // ping/pong during auth — ignore
        }
    }

    // Step 3: subscribe to trade_updates
    let sub = serde_json::json!({
        "action": "listen",
        "data": { "streams": ["trade_updates"] }
    })
    .to_string();
    ws.send(WsMessage::Text(sub.into()))
        .await
        .map_err(|e| HandshakeError::Transport(format!("WS subscribe send: {e}")))?;

    // Step 4: wait for listening acknowledgment (optional but confirms subscription)
    loop {
        match ws.next().await {
            Some(Ok(WsMessage::Text(text))) => {
                if check_listen_ack(text.as_str()) {
                    break;
                }
                // Other messages in this window are NOT buffered and are permanently
                // dropped — callers must reconcile order state via fetch_open_orders
                // after each (re)connect, as documented in account_stream's doc comment.
                // Log at warn! for trade_updates (fill/lifecycle events) to ensure
                // production operators see dropped events; trace! for other streams.
                if let Ok(msg) = serde_json::from_str::<AlpacaStreamMessage<'_>>(text.as_str()) {
                    if msg.stream == "trade_updates" {
                        warn!(stream = %msg.stream, "WS trade_updates event dropped during listen-ack handshake — will be recovered via REST for fills, but lifecycle events (new/canceled) are lost");
                    } else {
                        trace!(stream = %msg.stream, "WS message dropped during listen-ack handshake");
                    }
                } else {
                    trace!(
                        bytes = text.len(),
                        "WS non-stream message dropped during listen-ack handshake"
                    );
                }
            }
            Some(Ok(WsMessage::Binary(bytes))) => {
                if let Ok(text) = std::str::from_utf8(&bytes)
                    && check_listen_ack(text)
                {
                    break;
                }
                trace!(
                    bytes = bytes.len(),
                    "WS binary message dropped during listen-ack handshake"
                );
            }
            Some(Err(e)) => {
                return Err(HandshakeError::Transport(format!(
                    "WS error during subscribe: {e}"
                )));
            }
            None => {
                return Err(HandshakeError::Transport(
                    "WS closed before subscribe ack".into(),
                ));
            }
            _ => {}
        }
    }

    info!("Alpaca WS authenticated and subscribed to trade_updates");
    Ok(())
}

/// Parse a WS message to check for authorization response.
/// Returns `None` if the message is not an authorization response.
/// Returns `Some(Ok(()))` on success, `Some(Err(HandshakeError::Auth(...)))` on auth failure.
///
/// Uses `AlpacaStreamMessage` for consistency with the rest of the WS parsing pipeline.
fn check_auth_response(text: &str) -> Option<Result<(), HandshakeError>> {
    let msg = serde_json::from_str::<AlpacaStreamMessage<'_>>(text).ok()?;
    if msg.stream != "authorization" {
        return None;
    }
    #[derive(Deserialize)]
    struct AuthData<'a> {
        status: &'a str,
    }
    let data = serde_json::from_str::<AuthData<'_>>(msg.data.get()).ok()?;
    if data.status == "authorized" {
        Some(Ok(()))
    } else {
        Some(Err(HandshakeError::Auth(format!(
            "Alpaca WS auth failed: status={}",
            data.status
        ))))
    }
}

/// Returns `true` if the WS message is a listening acknowledgment for trade_updates.
///
/// Uses `AlpacaStreamMessage` for consistency with the rest of the WS parsing pipeline.
fn check_listen_ack(text: &str) -> bool {
    let Ok(msg) = serde_json::from_str::<AlpacaStreamMessage<'_>>(text) else {
        return false;
    };
    if msg.stream != "listening" {
        return false;
    }
    #[derive(Deserialize)]
    struct ListenData<'a> {
        #[serde(borrow)]
        streams: Vec<&'a str>,
    }
    let Ok(data) = serde_json::from_str::<ListenData<'_>>(msg.data.get()) else {
        return false;
    };
    data.streams.contains(&"trade_updates")
}

// ---------------------------------------------------------------------------
// Process incoming WS messages
// ---------------------------------------------------------------------------

/// Parse a raw WS text message and forward relevant account events to `tx`.
fn process_ws_text(
    text: &str,
    tx: &mpsc::UnboundedSender<UnindexedAccountEvent>,
    dedup: &SharedDedupCache,
    backoff: &mut ExponentialBackoff,
) {
    let msg: AlpacaStreamMessage<'_> = match serde_json::from_str(text) {
        Ok(m) => m,
        Err(e) => {
            trace!(
                %e,
                raw = ?&text[..text.len().min(200)],
                "Alpaca WS: skipped non-JSON message"
            );
            return;
        }
    };

    // Any successfully-parsed frame proves the connection is alive — reset backoff here
    // so that unrecognised event types (pending_cancel, replaced, etc.) also reset it.
    backoff.reset();

    match msg.stream.as_str() {
        "trade_updates" => {
            let update: AlpacaTradeUpdate<'_> = match serde_json::from_str(msg.data.get()) {
                Ok(u) => u,
                Err(e) => {
                    // Use warn (not trace): the outer frame was valid trade_updates JSON,
                    // so failure here signals an unexpected payload format. Could indicate
                    // an Alpaca API change or a missing required field dropping a real
                    // event (e.g. a rejected order). Visible at production log levels.
                    warn!(
                        %e,
                        raw = ?&msg.data.get()[..msg.data.get().len().min(200)],
                        "Alpaca WS trade_updates: failed to deserialize event — event dropped"
                    );
                    return;
                }
            };

            // PERF: Check dedup BEFORE constructing the full event for fill events.
            // This avoids heap allocations (Trade, InstrumentNameExchange, TradeId) on
            // duplicate fills, which occur on every reconnect during recovery overlap.
            if is_fill_event(&update) {
                let key = early_dedup_key(&update);
                if is_duplicate(dedup, &key) {
                    trace!("Alpaca WS: skipping duplicate fill event (early check)");
                    return;
                }
            }

            if let Some(event) = convert_trade_update(update) {
                // Consumer dropped errors are benign; connection_manager will detect
                // tx.closed() on the next select! poll and exit cleanly.
                let _ = tx.send(event);
            }
        }
        "authorization" | "listening" => {
            // Ack messages can appear during initial stream if the handshake was
            // not fully awaited. These are benign.
            trace!(stream = %msg.stream, "Alpaca WS: auth/listen ack received during stream");
        }
        other => {
            trace!(%other, "Alpaca WS: ignoring unknown stream type");
        }
    }
}

/// Extract a dedup key from an account event, if applicable.
///
/// Uses `trade.id` as the key. Both the WS path (`convert_trade_update`) and the
/// REST recovery path (`recover_fills`) synthesise `TradeId` as
/// `"{order_id}:{cumulative_filled_qty}"`, ensuring the same fill produces the
/// same key regardless of which path delivered it.
fn fill_dedup_key_from_event(event: &UnindexedAccountEvent) -> Option<&SmolStr> {
    match &event.kind {
        // Return a reference to avoid cloning the SmolStr; is_duplicate takes &SmolStr.
        AccountEventKind::Trade(trade) => Some(&trade.id.0),
        _ => None,
    }
}

/// Returns `true` if this event type produces a fill (Trade) event.
///
/// Used for early dedup check before allocating the full event.
#[inline]
fn is_fill_event(update: &AlpacaTradeUpdate<'_>) -> bool {
    matches!(update.event.as_str(), "fill" | "partial_fill")
}

/// Construct the dedup key from raw WS update fields without allocating the full event.
///
/// Key format: `"{order_id}:{cumulative_filled_qty}"` — same as `convert_trade_update`
/// and `recover_fills` produce, ensuring cross-source dedup works correctly.
///
/// Note: The `format_smolstr!` call heap-allocates for UUID-length order IDs (36 chars
/// exceeds SmolStr's 22-byte inline limit). This is unavoidable given the key length.
/// Passing the Decimal directly to format_smolstr! (rather than via intermediate String)
/// lets Decimal's Display impl write directly into the buffer, eliminating one allocation.
fn early_dedup_key(update: &AlpacaTradeUpdate<'_>) -> SmolStr {
    let filled_qty = update.order.filled_qty.unwrap_or("0");
    // Parse and normalize to match convert_trade_update's key format exactly.
    // Decimal::from_str + normalize() are stack-only; no heap allocation until format_smolstr!.
    let qty = Decimal::from_str(filled_qty).unwrap_or(Decimal::ZERO);
    format_smolstr!("{}:{}", update.order.id, qty.normalize())
}

// ---------------------------------------------------------------------------
// Fill recovery
// ---------------------------------------------------------------------------

/// Fetch fills missed during a WS disconnect and forward through the dedup cache.
async fn recover_fills(
    http: &reqwest::Client,
    rate_limiter: &RateLimitTracker,
    instruments: &[InstrumentNameExchange],
    base: &str,
    after: &str,
    tx: &mpsc::UnboundedSender<UnindexedAccountEvent>,
    dedup: &SharedDedupCache,
) {
    // Empty `instruments` means "recover for all subscribed symbols" (same convention as
    // `fetch_trades` / `fetch_open_orders`). Skip the set allocation when not filtering.
    info!(%after, instruments = instruments.len(), "Alpaca recovering fills after reconnect");
    let instrument_set: fnv::FnvHashSet<&str> = if instruments.is_empty() {
        fnv::FnvHashSet::default()
    } else {
        instruments.iter().map(|i| i.name().as_str()).collect()
    };

    let page = match paginate_activities(http, rate_limiter, base, after).await {
        Ok(p) => p,
        Err(e) => {
            error!(%e, "Alpaca fill recovery: REST request failed");
            return;
        }
    };

    // Log truncation as error — the returned data is partial and some fills are
    // permanently lost. Callers cannot propagate this error (recover_fills returns ()),
    // but the log ensures operators are alerted.
    if page.truncated {
        error!(
            max_pages = MAX_ACTIVITY_PAGES,
            "Alpaca fill recovery: max page limit reached, truncating — \
             fills from this outage are permanently lost. Manual reconciliation required."
        );
    }

    let activities = page.activities;

    let mut recovered = 0u32;
    let mut duplicates = 0u32;

    // Track cumulative filled qty per order so that the synthesised TradeId matches
    // the WS path: both produce "{order_id}:{cumulative_filled_qty}". This prevents
    // same-size partial fill collisions (e.g. two 1-lot fills on a 2-lot order)
    // and ensures cross-source dedup works correctly after reconnect.
    //
    // Activities are fetched with direction=asc so they arrive in chronological order.
    // Cumulative accumulation here must match the WS path's order.filled_qty progression.
    // If Alpaca violates this ordering guarantee, dedup keys will diverge and fills
    // may be dropped or duplicated.
    // Borrow `activities` so &str keys into order_id strings remain valid for the
    // entire loop. Consuming iteration would drop each activity at end of its iteration,
    // invalidating keys that still need to be looked up by later fills on the same order.
    let mut cumulative_qty: FnvHashMap<&str, Decimal> = FnvHashMap::default();

    for activity in &activities {
        if !instrument_set.is_empty() && !instrument_set.contains(activity.symbol.as_str()) {
            // Safe to skip without advancing cumulative_qty: each Alpaca order is bound
            // to exactly one symbol, so no fill for a different symbol can ever share
            // the same order_id as a fill we're tracking.
            continue;
        }

        // Advance cumulative_qty for every activity, regardless of whether parsing
        // succeeds. The WS path uses Alpaca's cumulative filled_qty, which counts ALL
        // fills — including those with malformed fields. Skipping the counter for a bad
        // fill causes subsequent fills to produce dedup keys that diverge from the WS
        // path (off by the bad fill's qty), so the next good fill appears as a duplicate
        // on one path and a new fill on the other, resulting in either a missed or a
        // double-delivered fill for that execution.
        //
        // activity.qty is always populated for FILL activities (Alpaca guarantees it).
        // unwrap_or(ZERO) guards against unexpected API changes; a zero qty skips
        // incrementing the cumulative counter for that activity. Note: a non-empty
        // but non-parseable qty string (e.g. an API regression sending "abc") also
        // produces exec_qty=ZERO — the counter stalls, causing subsequent fills on
        // the same order to produce dedup keys that diverge from the WS path.
        let exec_qty = Decimal::from_str(&activity.qty).unwrap_or(Decimal::ZERO);
        let cum = cumulative_qty
            .entry(activity.order_id.as_str())
            .or_default();
        *cum += exec_qty;
        let cumulative = *cum;

        let mut trade = match convert_activity_to_trade(activity) {
            Some(t) => t,
            None => {
                warn!(id = %activity.id, symbol = %activity.symbol, "Alpaca: skipping activity with unparseable fields");
                continue; // Counter already advanced; dedup key sequence stays aligned with WS.
            }
        };

        // Override trade.id to match the WS synthesised format so that
        // fill_dedup_key_from_event produces the same key for both sources.
        // Normalise the cumulative Decimal to strip trailing zeros so the string
        // representation matches the WS path (e.g. "1" == "1.00" after normalize).
        trade.id = TradeId(format_smolstr!(
            "{}:{}",
            activity.order_id,
            cumulative.normalize()
        ));

        let event =
            UnindexedAccountEvent::new(ExchangeId::AlpacaBroker, AccountEventKind::Trade(trade));

        // Re-use fill_dedup_key_from_event so the key logic is in one place.
        if fill_dedup_key_from_event(&event).is_some_and(|k| is_duplicate(dedup, k)) {
            duplicates += 1;
            continue;
        }
        if tx.send(event).is_err() {
            debug!("Alpaca fill recovery: consumer dropped during recovery");
            return;
        }
        recovered += 1;
    }

    info!(recovered, duplicates, "Alpaca fill recovery complete");
}

// ---------------------------------------------------------------------------
// Type conversion helpers
// ---------------------------------------------------------------------------

/// Convert an Alpaca account response to rustrade balance entries.
///
/// Returns a single USD balance with:
/// - `total` = equity (total account value including open positions)
/// - `free` = options_buying_power (if available) or buying_power
///
/// If `assets` is non-empty, only returns the balance if "usd" (case-insensitive)
/// is in the requested set. An empty `assets` slice returns the USD balance unconditionally.
fn convert_account_to_balances(
    account: &AlpacaAccount,
    assets: &[AssetNameExchange],
) -> Vec<AssetBalance<AssetNameExchange>> {
    // Preserve the caller's casing for the USD asset name (e.g. "USD" vs "usd").
    // When no filter is given, fall back to lowercase "usd" as the canonical form.
    let usd_entry = assets
        .iter()
        .find(|a| a.name().as_str().eq_ignore_ascii_case("usd"));

    // Filter check: if assets is specified, only return USD balance if requested.
    if !assets.is_empty() && usd_entry.is_none() {
        return Vec::new();
    }

    let usd_name = usd_entry
        .cloned()
        .unwrap_or_else(|| AssetNameExchange::new("usd"));

    let total = Decimal::from_str(&account.equity).unwrap_or(Decimal::ZERO);
    let free = account
        .options_buying_power
        .as_deref()
        .and_then(|s| Decimal::from_str(s).ok())
        // Filter out zero: Alpaca returns options_buying_power="0.00" for equity-only
        // accounts (options not enabled) rather than omitting the field. Without this
        // filter, unwrap_or_else never fires and the engine reports free=0, blocking
        // all orders on an account that may have substantial buying_power.
        .filter(|d| !d.is_zero())
        .unwrap_or_else(|| Decimal::from_str(&account.buying_power).unwrap_or(Decimal::ZERO));

    vec![AssetBalance::new(
        usd_name,
        Balance::new(total, free),
        Utc::now(),
    )]
}

/// Convert Alpaca positions to crypto asset balance entries.
///
/// Only positions with `asset_class == "crypto"` are included. The base asset
/// is extracted from the symbol (e.g., `"BTC/USD"` → `"btc"`).
///
/// - `total` = quantity of the holding in base currency units (e.g. 0.5 BTC)
/// - `free`  = qty_available (base currency units not locked in open orders)
///
/// If `assets` is non-empty, only positions whose base asset name matches an
/// entry in the slice (case-insensitive) are returned.
fn convert_positions_to_balances(
    positions: &[AlpacaPosition],
    assets: &[AssetNameExchange],
) -> Vec<AssetBalance<AssetNameExchange>> {
    let now = Utc::now();
    positions
        .iter()
        .filter(|p| p.asset_class.eq_ignore_ascii_case("crypto"))
        .filter_map(|p| {
            // Alpaca crypto symbols are "BASE/QUOTE" (e.g., "BTC/USD").
            // Extract the base currency as the asset name.
            let base = p
                .symbol
                .split('/')
                .next()
                .map(|s| s.to_ascii_lowercase())
                .unwrap_or_else(|| p.symbol.to_ascii_lowercase());

            // Apply assets filter if specified.
            if !assets.is_empty()
                && !assets
                    .iter()
                    .any(|a| a.name().as_str().eq_ignore_ascii_case(&base))
            {
                return None;
            }

            // total and free are in base currency units (e.g., BTC), not USD,
            // consistent with AssetBalance semantics for currency/crypto assets.
            let total = Decimal::from_str(&p.qty).unwrap_or(Decimal::ZERO);
            let free = Decimal::from_str(&p.qty_available).unwrap_or(Decimal::ZERO);
            let asset_name = AssetNameExchange::new(base);
            Some(AssetBalance::new(
                asset_name,
                Balance::new(total, free),
                now,
            ))
        })
        .collect()
}

/// Group a list of open orders into per-instrument snapshots for account_snapshot.
///
/// When `instruments` is non-empty, a snapshot is returned for every requested instrument
/// (possibly with an empty orders list). When empty, only instruments with open orders
/// are returned.
fn build_instrument_snapshots(
    orders: Vec<AlpacaOrderResponse>,
    instruments: &[InstrumentNameExchange],
) -> Vec<InstrumentAccountSnapshot<ExchangeId, AssetNameExchange, InstrumentNameExchange>> {
    // Build ordered map from symbol → snapshot to preserve deterministic ordering.
    let mut by_symbol: IndexMap<SmolStr, Vec<_>> = IndexMap::new();

    for order in orders {
        let sym = SmolStr::new(&order.symbol);
        if let Some(converted) = convert_open_order(&order) {
            let wrapped = crate::order::Order {
                key: converted.key,
                side: converted.side,
                price: converted.price,
                quantity: converted.quantity,
                kind: converted.kind,
                time_in_force: converted.time_in_force,
                state: OrderState::active(converted.state),
            };
            by_symbol.entry(sym).or_default().push(wrapped);
        }
    }

    // If instruments is empty, return all; otherwise filter to requested set.
    if instruments.is_empty() {
        by_symbol
            .into_iter()
            .map(|(sym, orders)| {
                InstrumentAccountSnapshot::new(InstrumentNameExchange::new(sym), orders, None)
            })
            .collect()
    } else {
        instruments
            .iter()
            .map(|inst| {
                // swap_remove is O(1); output order is determined by the `instruments`
                // slice, not by the internal IndexMap order of `by_symbol`.
                let orders = by_symbol
                    .swap_remove(inst.name().as_str())
                    .unwrap_or_default();
                InstrumentAccountSnapshot::new(inst.clone(), orders, None)
            })
            .collect()
    }
}

/// Convert an Alpaca REST order into rustrade's Open state order.
fn convert_open_order(
    o: &AlpacaOrderResponse,
) -> Option<Order<ExchangeId, InstrumentNameExchange, Open>> {
    let order_id = OrderId(SmolStr::new(&o.id));
    let cid = o
        .client_order_id
        .as_deref()
        .map(ClientOrderId::new)
        .unwrap_or_else(|| ClientOrderId::new(o.id.as_str()));

    let instrument = InstrumentNameExchange::new(&o.symbol);
    let side = parse_side(&o.side)?;
    let quantity = Decimal::from_str(o.qty.as_deref().unwrap_or("0")).ok()?;
    // Notional orders (placed by dollar value, qty=null) have no representable quantity.
    // Skip them rather than recording a zero-quantity order that would corrupt reconciliation.
    if quantity.is_zero() {
        return None;
    }
    let price = o
        .limit_price
        .as_deref()
        .and_then(|s| Decimal::from_str(s).ok());
    let filled_qty = Decimal::from_str(&o.filled_qty).unwrap_or(Decimal::ZERO);
    let kind = parse_order_kind(
        &o.order_type,
        o.stop_price.as_deref(),
        o.trail_percent.as_deref(),
        o.trail_price.as_deref(),
    )?;
    let time_in_force = parse_time_in_force(&o.time_in_force);
    let time_exchange = parse_timestamp(&o.created_at).unwrap_or_else(Utc::now);

    Some(Order {
        key: OrderKey::new(
            ExchangeId::AlpacaBroker,
            instrument,
            // Alpaca doesn't carry strategy IDs in any response field.
            StrategyId::unknown(),
            cid,
        ),
        side,
        price,
        quantity,
        kind,
        time_in_force,
        state: Open::new(order_id, time_exchange, filled_qty),
    })
}

/// Convert an Alpaca FILL activity into a rustrade Trade.
fn convert_activity_to_trade(
    a: &AlpacaActivity,
) -> Option<Trade<AssetNameExchange, InstrumentNameExchange>> {
    let trade_id = TradeId::new(&a.id);
    let order_id = OrderId(SmolStr::new(&a.order_id));
    let instrument = InstrumentNameExchange::new(&a.symbol);
    let side = parse_side(&a.side)?;
    let price = Decimal::from_str(&a.price).ok()?;
    let quantity = Decimal::from_str(&a.qty).ok()?;
    let time_exchange = parse_timestamp(&a.transaction_time).unwrap_or_else(|| {
        warn!(id = %a.id, "Alpaca activity: unparseable transaction_time, using now");
        Utc::now()
    });

    // Alpaca equities and options are commission-free. Crypto trades incur
    // maker/taker fees (currently 0.15–0.25%) charged in the credited asset,
    // but fee info is not available in trade responses — use Activities API
    // for end-of-day fee reconciliation.
    Some(Trade::new(
        trade_id,
        order_id,
        instrument,
        StrategyId::unknown(),
        time_exchange,
        side,
        price,
        quantity,
        AssetFees::new(
            AssetNameExchange::from("USD"),
            Decimal::ZERO,
            Some(Decimal::ZERO),
        ),
    ))
}

/// Convert a WebSocket trade_update event into a rustrade AccountEvent.
fn convert_trade_update(update: AlpacaTradeUpdate<'_>) -> Option<UnindexedAccountEvent> {
    // Early exit for unrecognised event types before incurring allocations for
    // instrument/order_id/cid — those are wasted for unknown events.
    let event_str = update.event.as_str();
    if !matches!(
        event_str,
        "fill"
            | "partial_fill"
            | "new"
            | "accepted"
            | "pending_new"
            | "canceled"
            | "expired"
            | "replaced"
            | "done_for_day"
            | "rejected"
    ) {
        trace!(event = %event_str, "Alpaca WS: ignoring trade_updates event type");
        return None;
    }

    let order = &update.order;
    let instrument = InstrumentNameExchange::new(&*order.symbol);
    let order_id = OrderId(order.id.clone());
    let cid = order
        .client_order_id
        .as_deref()
        .map(ClientOrderId::new)
        .unwrap_or_else(|| ClientOrderId::new(order.id.as_str()));

    match event_str {
        "fill" | "partial_fill" => {
            // Use event-level price/qty for the per-execution trade.
            let price = update.price.and_then(|s| Decimal::from_str(s).ok())?;
            let quantity = update.qty.and_then(|s| Decimal::from_str(s).ok())?;
            let side = parse_side(&order.side)?;
            let time_exchange = update
                .timestamp
                .and_then(parse_timestamp)
                .unwrap_or_else(Utc::now);

            // Trade ID: synthesise from order_id + cumulative filled qty since
            // Alpaca WS trade_updates don't include an activity ID.
            // Normalise via Decimal to strip trailing zeros so the key matches the
            // REST recovery path (e.g. "1.00" and "1" both normalise to "1").
            //
            // If filled_qty is unparseable (API regression), cum_qty falls back to
            // zero. Two consecutive bad fills on the same order would produce the same
            // dedup key ("order_id:0"), causing the second fill to be silently dropped.
            // Warn loudly so API regressions are surfaced immediately.
            let cum_qty = Decimal::from_str(order.filled_qty.unwrap_or("0"))
                .inspect_err(|e| {
                    warn!(
                        order_id = %order.id,
                        filled_qty = ?order.filled_qty,
                        %e,
                        "Alpaca WS: failed to parse filled_qty — dedup key will use 0, \
                         a second malformed fill on the same order would be deduplicated away"
                    );
                })
                .unwrap_or(Decimal::ZERO);
            let trade_id = TradeId(format_smolstr!("{}:{}", order.id, cum_qty.normalize()));

            // Alpaca equities and options are commission-free. Crypto trades incur
            // maker/taker fees (currently 0.15–0.25%) in the credited asset, but
            // fee info is not available in WebSocket updates.
            let trade = Trade::new(
                trade_id,
                order_id,
                instrument,
                StrategyId::unknown(),
                time_exchange,
                side,
                price,
                quantity,
                AssetFees::new(
                    AssetNameExchange::from("USD"),
                    Decimal::ZERO,
                    Some(Decimal::ZERO),
                ),
            );
            Some(UnindexedAccountEvent::new(
                ExchangeId::AlpacaBroker,
                AccountEventKind::Trade(trade),
            ))
        }

        "new" | "accepted" | "pending_new" => {
            // Order acknowledged by Alpaca — emit an OrderSnapshot.
            let side = parse_side(&order.side)?;
            let quantity = Decimal::from_str(order.qty.unwrap_or("0")).unwrap_or(Decimal::ZERO);
            // Notional orders (placed by dollar value) have qty=null, yielding quantity=0.
            // Emitting an OrderSnapshot with quantity=0 would corrupt OMS state — skip,
            // consistent with convert_open_order which also returns None for zero-qty orders.
            if quantity.is_zero() {
                trace!(order_id = %order.id, "Alpaca WS: skipping notional order snapshot (qty=None)");
                return None;
            }
            let price = order.limit_price.and_then(|s| Decimal::from_str(s).ok());
            let filled_qty =
                Decimal::from_str(order.filled_qty.unwrap_or("0")).unwrap_or(Decimal::ZERO);
            let kind = parse_order_kind(
                &order.order_type,
                order.stop_price,
                order.trail_percent,
                order.trail_price,
            )?;
            let time_in_force = parse_time_in_force(&order.time_in_force);
            let time_exchange = update
                .timestamp
                .and_then(parse_timestamp)
                .unwrap_or_else(Utc::now);

            let open_state = Open::new(order_id, time_exchange, filled_qty);
            let order_snapshot = crate::order::Order {
                key: OrderKey::new(
                    ExchangeId::AlpacaBroker,
                    instrument,
                    StrategyId::unknown(),
                    cid,
                ),
                side,
                price,
                quantity,
                kind,
                time_in_force,
                state: OrderState::active(open_state),
            };
            Some(UnindexedAccountEvent::new(
                ExchangeId::AlpacaBroker,
                AccountEventKind::OrderSnapshot(
                    rustrade_integration::collection::snapshot::Snapshot(order_snapshot),
                ),
            ))
        }

        "canceled" | "expired" | "replaced" | "done_for_day" => {
            // Order no longer active.
            //
            // NOTE on "replaced": Alpaca's replace operation cancels the original order
            // and creates a NEW order with a different order ID. This arm correctly marks
            // the original as cancelled, but callers must call `fetch_open_orders` to
            // discover the replacement order (which has a new ID and won't appear in OMS
            // state automatically).
            let time_exchange = update
                .timestamp
                .and_then(parse_timestamp)
                .unwrap_or_else(Utc::now);
            let filled_qty =
                Decimal::from_str(order.filled_qty.unwrap_or("0")).unwrap_or(Decimal::ZERO);
            let cancelled = Cancelled::new(order_id, time_exchange, filled_qty);
            let response = crate::order::request::OrderResponseCancel {
                key: OrderKey::new(
                    ExchangeId::AlpacaBroker,
                    instrument,
                    StrategyId::unknown(),
                    cid,
                ),
                state: Ok(cancelled),
            };
            Some(UnindexedAccountEvent::new(
                ExchangeId::AlpacaBroker,
                AccountEventKind::OrderCancelled(response),
            ))
        }

        "rejected" => {
            let response = crate::order::request::OrderResponseCancel {
                key: OrderKey::new(
                    ExchangeId::AlpacaBroker,
                    instrument,
                    StrategyId::unknown(),
                    cid,
                ),
                state: Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(
                    format!("order rejected: status={}", order.status),
                ))),
            };
            Some(UnindexedAccountEvent::new(
                ExchangeId::AlpacaBroker,
                AccountEventKind::OrderCancelled(response),
            ))
        }

        // All recognised event types are handled above; the early-return guard at the
        // top of this function ensures we never reach here for unknown event types.
        _ => unreachable!("convert_trade_update: unrecognised event passed early-return guard"),
    }
}

// ---------------------------------------------------------------------------
// Field parsers
// ---------------------------------------------------------------------------

fn parse_side(s: &str) -> Option<Side> {
    match s {
        "buy" | "Buy" | "BUY" => Some(Side::Buy),
        "sell" | "Sell" | "SELL" => Some(Side::Sell),
        other => {
            trace!(%other, "Alpaca: unknown order side");
            None
        }
    }
}

fn parse_order_kind(
    order_type: &str,
    stop_price: Option<&str>,
    trail_percent: Option<&str>,
    trail_price: Option<&str>,
) -> Option<OrderKind> {
    match order_type {
        "market" | "Market" => Some(OrderKind::Market),
        "limit" | "Limit" => Some(OrderKind::Limit),
        "stop" | "Stop" => {
            let trigger_price = stop_price.and_then(|s| Decimal::from_str(s).ok())?;
            Some(OrderKind::Stop { trigger_price })
        }
        "stop_limit" | "Stop_limit" => {
            let trigger_price = stop_price.and_then(|s| Decimal::from_str(s).ok())?;
            Some(OrderKind::StopLimit { trigger_price })
        }
        "trailing_stop" | "Trailing_stop" => {
            // Alpaca returns either trail_percent or trail_price, not both.
            if let Some(pct) = trail_percent.and_then(|s| Decimal::from_str(s).ok()) {
                Some(OrderKind::TrailingStop {
                    offset: pct,
                    offset_type: TrailingOffsetType::Percentage,
                })
            } else if let Some(price) = trail_price.and_then(|s| Decimal::from_str(s).ok()) {
                Some(OrderKind::TrailingStop {
                    offset: price,
                    offset_type: TrailingOffsetType::Absolute,
                })
            } else {
                trace!("Alpaca: trailing_stop missing trail_percent and trail_price");
                None
            }
        }
        other => {
            trace!(%other, "Alpaca: unsupported order type, skipping");
            None
        }
    }
}

fn parse_time_in_force(s: &str) -> TimeInForce {
    match s {
        "gtc" | "GTC" => TimeInForce::GoodUntilCancelled { post_only: false },
        "day" | "DAY" => TimeInForce::GoodUntilEndOfDay,
        "fok" | "FOK" => TimeInForce::FillOrKill,
        "ioc" | "IOC" => TimeInForce::ImmediateOrCancel,
        other => {
            warn!(%other, "Alpaca: unknown time_in_force, defaulting to GoodUntilEndOfDay");
            TimeInForce::GoodUntilEndOfDay
        }
    }
}

fn parse_timestamp(s: &str) -> Option<DateTime<Utc>> {
    DateTime::parse_from_rfc3339(s)
        .ok()
        .map(|dt| dt.with_timezone(&Utc))
}

fn map_side(side: Side) -> &'static str {
    match side {
        Side::Buy => "buy",
        Side::Sell => "sell",
    }
}

fn map_order_kind(kind: OrderKind) -> Option<&'static str> {
    match kind {
        OrderKind::Market => Some("market"),
        OrderKind::Limit => Some("limit"),
        OrderKind::Stop { .. } => Some("stop"),
        OrderKind::StopLimit { .. } => Some("stop_limit"),
        OrderKind::TrailingStop { .. } => Some("trailing_stop"),
        // Alpaca does not support trailing stop-limit orders.
        OrderKind::TrailingStopLimit { .. } => None,
    }
}

/// Map rustrade's `TimeInForce` to Alpaca's string representation.
///
/// # Errors
///
/// Returns `Err` if `post_only: true` is requested. Alpaca does not support
/// post-only orders — silently placing a taker-eligible GTC order would be
/// the opposite of caller intent, risking unexpected taker fees. Callers
/// requiring maker-only execution must use a different venue or strategy.
fn map_time_in_force(tif: TimeInForce) -> Result<&'static str, &'static str> {
    match tif {
        TimeInForce::GoodUntilCancelled { post_only } => {
            if post_only {
                return Err("Alpaca does not support post_only orders");
            }
            Ok("gtc")
        }
        TimeInForce::GoodUntilEndOfDay => Ok("day"),
        TimeInForce::FillOrKill => Ok("fok"),
        TimeInForce::ImmediateOrCancel => Ok("ioc"),
        TimeInForce::AtOpen => Ok("opg"),
        TimeInForce::AtClose => Ok("cls"),
        // Alpaca's `gtd` requires an `expired_at` timestamp on the order request,
        // which this client does not currently surface. Reject to avoid silently
        // dropping the expiry semantics.
        TimeInForce::GoodTillDate { .. } => {
            Err("Alpaca GoodTillDate is not yet wired through this client")
        }
    }
}

/// Returns `true` if the symbol is an equity or options symbol (i.e., NOT crypto).
///
/// Crypto symbols on Alpaca always contain a forward slash (e.g., `"BTC/USD"`).
/// Equities and OCC option symbols never contain a slash. We use this to decide
/// whether to include `position_intent` in the order request: the field is valid
/// for equities and required for options, but causes a 422 on crypto orders.
///
/// NOTE: relies on Alpaca's documented symbol format (as of 2025 API). If Alpaca
/// introduces a new asset class whose symbols contain `/`, `position_intent` would
/// be silently omitted for those orders, causing 422 errors.
fn is_options_or_equity_symbol(symbol: &str) -> bool {
    !symbol.contains('/')
}

/// Derives Alpaca's `position_intent` from the generic `reduce_only` flag and `side`.
///
/// | reduce_only | side | intent       | use case                          |
/// |-------------|------|--------------|-----------------------------------|
/// | false       | Buy  | BuyToOpen    | open long / add to long position  |
/// | false       | Sell | SellToOpen   | open short / write option         |
/// | true        | Buy  | BuyToClose   | close short position              |
/// | true        | Sell | SellToClose  | close long position               |
fn map_position_intent(side: Side, reduce_only: bool) -> AlpacaPositionIntent {
    match (reduce_only, side) {
        (false, Side::Buy) => AlpacaPositionIntent::BuyToOpen,
        (false, Side::Sell) => AlpacaPositionIntent::SellToOpen,
        (true, Side::Buy) => AlpacaPositionIntent::BuyToClose,
        (true, Side::Sell) => AlpacaPositionIntent::SellToClose,
    }
}

/// Classifies an HTTP error status + body into a typed [`ApiError`].
///
/// Used by both `rest_with_retry` (for general REST calls) and `rest_delete_with_retry`
/// (for cancel operations) to ensure consistent error classification across all REST paths.
fn parse_api_error(status: reqwest::StatusCode, message: &str) -> crate::error::UnindexedApiError {
    // Fast path: 429 doesn't need message parsing.
    if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
        return ApiError::RateLimit;
    }

    // Compute lowercase once for all match guards that inspect the message body.
    let lower = message.to_ascii_lowercase();
    match status.as_u16() {
        // Match "already" before "insufficient": if Alpaca ever sends a 422 body
        // containing both substrings, this arm wins and maps to OrderAlreadyCancelled,
        // which is more specific than BalanceInsufficient.
        422 if lower.contains("already") => ApiError::OrderAlreadyCancelled,
        // Alpaca returns 422 for business-rule rejections including insufficient
        // funds. 403 is *Forbidden* — auth/permission failure — and must NOT be
        // mapped to BalanceInsufficient even if the body happens to contain the
        // substring "insufficient".
        422 if lower.contains("insufficient") => {
            ApiError::BalanceInsufficient(AssetNameExchange::new("usd"), message.to_owned())
        }
        401 => ApiError::Unauthenticated(format!("unauthorized: {message}")),
        403 => ApiError::Unauthenticated(format!("forbidden: {message}")),
        404 => ApiError::OrderRejected(format!("order not found: {message}")),
        _ => ApiError::OrderRejected(message.to_owned()),
    }
}

/// Wraps [`parse_api_error`] for order-specific error handling (e.g., cancel_order).
fn parse_order_error(status: reqwest::StatusCode, message: &str) -> UnindexedOrderError {
    UnindexedOrderError::Rejected(parse_api_error(status, message))
}

fn connectivity_err(msg: impl Into<String>) -> UnindexedClientError {
    UnindexedClientError::Connectivity(ConnectivityError::Socket(msg.into()))
}

// ---------------------------------------------------------------------------
// BracketOrderClient implementation
// ---------------------------------------------------------------------------

impl BracketOrderClient for AlpacaClient {
    async fn open_bracket_order(
        &self,
        request: UnifiedBracketOrderRequest<ExchangeId, &InstrumentNameExchange>,
    ) -> UnifiedBracketOrderResult {
        let alpaca_request = AlpacaBracketOrderRequest {
            instrument: request.key.instrument.clone(),
            strategy: request.key.strategy.clone(),
            cid: request.key.cid.clone(),
            side: request.state.side,
            quantity: request.state.quantity,
            entry_price: request.state.entry_price,
            take_profit_price: request.state.take_profit_price,
            stop_loss_price: request.state.stop_loss_price,
            stop_loss_limit_price: request.state.stop_loss_limit_price,
            time_in_force: request.state.time_in_force,
        };

        let result = self.open_bracket_order(alpaca_request).await;

        UnifiedBracketOrderResult::parent_only(result.parent)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;

    #[test]
    fn test_alpaca_config_debug_redacts_credentials() {
        let cfg = AlpacaConfig::new("my_key".into(), "my_secret".into(), true);
        let debug = format!("{cfg:?}");
        assert!(!debug.contains("my_key"), "api_key should be redacted");
        assert!(
            !debug.contains("my_secret"),
            "secret_key should be redacted"
        );
        assert!(debug.contains("paper: true"));
    }

    #[test]
    fn test_alpaca_config_urls() {
        let paper = AlpacaConfig::new("k".into(), "s".into(), true);
        assert!(paper.rest_base_url().contains("paper-api"));
        assert!(paper.ws_url().contains("paper-api"));

        let live = AlpacaConfig::new("k".into(), "s".into(), false);
        assert!(!live.rest_base_url().contains("paper-api"));
        assert!(!live.ws_url().contains("paper-api"));
    }

    #[test]
    fn test_parse_side() {
        assert_eq!(parse_side("buy"), Some(Side::Buy));
        assert_eq!(parse_side("sell"), Some(Side::Sell));
        assert_eq!(parse_side("Buy"), Some(Side::Buy));
        assert_eq!(parse_side("BUY"), Some(Side::Buy));
        assert_eq!(parse_side("unknown"), None);
    }

    #[test]
    fn test_parse_order_kind() {
        // Market and Limit don't need extra params
        assert_eq!(
            parse_order_kind("market", None, None, None),
            Some(OrderKind::Market)
        );
        assert_eq!(
            parse_order_kind("limit", None, None, None),
            Some(OrderKind::Limit)
        );

        // Stop requires stop_price
        assert_eq!(
            parse_order_kind("stop", Some("150.00"), None, None),
            Some(OrderKind::Stop {
                trigger_price: Decimal::from_str("150.00").unwrap()
            })
        );
        assert_eq!(parse_order_kind("stop", None, None, None), None);

        // StopLimit requires stop_price
        assert_eq!(
            parse_order_kind("stop_limit", Some("145.00"), None, None),
            Some(OrderKind::StopLimit {
                trigger_price: Decimal::from_str("145.00").unwrap()
            })
        );

        // TrailingStop with percentage
        assert_eq!(
            parse_order_kind("trailing_stop", None, Some("5.0"), None),
            Some(OrderKind::TrailingStop {
                offset: Decimal::from_str("5.0").unwrap(),
                offset_type: TrailingOffsetType::Percentage,
            })
        );

        // TrailingStop with absolute price
        assert_eq!(
            parse_order_kind("trailing_stop", None, None, Some("2.50")),
            Some(OrderKind::TrailingStop {
                offset: Decimal::from_str("2.50").unwrap(),
                offset_type: TrailingOffsetType::Absolute,
            })
        );

        // TrailingStop without either offset returns None
        assert_eq!(parse_order_kind("trailing_stop", None, None, None), None);

        // Unknown type returns None
        assert_eq!(parse_order_kind("unknown", None, None, None), None);
    }

    #[test]
    fn test_map_order_kind() {
        assert_eq!(map_order_kind(OrderKind::Market), Some("market"));
        assert_eq!(map_order_kind(OrderKind::Limit), Some("limit"));
        assert_eq!(
            map_order_kind(OrderKind::Stop {
                trigger_price: Decimal::from_str("150.00").unwrap()
            }),
            Some("stop")
        );
        assert_eq!(
            map_order_kind(OrderKind::StopLimit {
                trigger_price: Decimal::from_str("145.00").unwrap()
            }),
            Some("stop_limit")
        );
        assert_eq!(
            map_order_kind(OrderKind::TrailingStop {
                offset: Decimal::from_str("5.0").unwrap(),
                offset_type: TrailingOffsetType::Percentage,
            }),
            Some("trailing_stop")
        );
        assert_eq!(
            map_order_kind(OrderKind::TrailingStop {
                offset: Decimal::from_str("2.50").unwrap(),
                offset_type: TrailingOffsetType::Absolute,
            }),
            Some("trailing_stop")
        );
        // TrailingStopLimit is not supported by Alpaca
        assert_eq!(
            map_order_kind(OrderKind::TrailingStopLimit {
                offset: Decimal::from_str("5.0").unwrap(),
                offset_type: TrailingOffsetType::Percentage,
                limit_offset: Decimal::from_str("1.0").unwrap(),
            }),
            None
        );
    }

    #[test]
    fn test_map_time_in_force_roundtrip() {
        assert_eq!(
            map_time_in_force(TimeInForce::GoodUntilCancelled { post_only: false }),
            Ok("gtc")
        );
        assert_eq!(map_time_in_force(TimeInForce::GoodUntilEndOfDay), Ok("day"));
        assert_eq!(map_time_in_force(TimeInForce::FillOrKill), Ok("fok"));
        assert_eq!(map_time_in_force(TimeInForce::ImmediateOrCancel), Ok("ioc"));
    }

    #[test]
    fn test_map_time_in_force_rejects_post_only() {
        let result = map_time_in_force(TimeInForce::GoodUntilCancelled { post_only: true });
        assert!(result.is_err(), "post_only must be rejected");
        assert!(result.unwrap_err().contains("post_only"));
    }

    // =========================================================================
    // Bracket Order Serialization Tests
    // =========================================================================

    #[test]
    fn test_bracket_order_serializes_with_stop_loss_stop_order() {
        // Bracket order with stop-loss as a simple stop order (no limit_price)
        let body = AlpacaOrderRequest {
            symbol: "AAPL",
            qty: "10".to_string(),
            side: "buy",
            order_type: "limit",
            time_in_force: "gtc",
            limit_price: Some("150.00".to_string()),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            client_order_id: Some("bracket-001"),
            position_intent: Some(AlpacaPositionIntent::BuyToOpen),
            order_class: Some("bracket"),
            take_profit: Some(TakeProfitParams {
                limit_price: "160.00".to_string(),
            }),
            stop_loss: Some(StopLossParams {
                stop_price: "145.00".to_string(),
                limit_price: None,
            }),
        };

        let json = serde_json::to_value(&body).unwrap();

        assert_eq!(json["symbol"], "AAPL");
        assert_eq!(json["qty"], "10");
        assert_eq!(json["side"], "buy");
        assert_eq!(json["type"], "limit");
        assert_eq!(json["time_in_force"], "gtc");
        assert_eq!(json["limit_price"], "150.00");
        assert_eq!(json["order_class"], "bracket");

        // Take profit should have limit_price
        assert_eq!(json["take_profit"]["limit_price"], "160.00");

        // Stop loss should have stop_price but NO limit_price
        assert_eq!(json["stop_loss"]["stop_price"], "145.00");
        assert!(
            json["stop_loss"].get("limit_price").is_none(),
            "stop_loss.limit_price should be omitted when None"
        );
    }

    #[test]
    fn test_bracket_order_serializes_with_stop_loss_stop_limit_order() {
        // Bracket order with stop-loss as a stop-limit order (has limit_price)
        let body = AlpacaOrderRequest {
            symbol: "SPY",
            qty: "5".to_string(),
            side: "sell",
            order_type: "limit",
            time_in_force: "day",
            limit_price: Some("450.00".to_string()),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            client_order_id: Some("bracket-002"),
            position_intent: Some(AlpacaPositionIntent::SellToClose),
            order_class: Some("bracket"),
            take_profit: Some(TakeProfitParams {
                limit_price: "440.00".to_string(),
            }),
            stop_loss: Some(StopLossParams {
                stop_price: "455.00".to_string(),
                limit_price: Some("456.00".to_string()),
            }),
        };

        let json = serde_json::to_value(&body).unwrap();

        assert_eq!(json["symbol"], "SPY");
        assert_eq!(json["side"], "sell");
        assert_eq!(json["time_in_force"], "day");
        assert_eq!(json["order_class"], "bracket");

        // Take profit
        assert_eq!(json["take_profit"]["limit_price"], "440.00");

        // Stop loss with limit_price (stop-limit order)
        assert_eq!(json["stop_loss"]["stop_price"], "455.00");
        assert_eq!(
            json["stop_loss"]["limit_price"], "456.00",
            "stop_loss.limit_price should be present for stop-limit orders"
        );
    }

    // =========================================================================
    // Bracket Order Validation Tests
    // =========================================================================

    #[tokio::test]
    async fn test_open_bracket_order_rejects_invalid_tif() {
        use rust_decimal_macros::dec;
        use rustrade_instrument::instrument::name::InstrumentNameExchange;

        // Create a minimal client with dummy credentials (no network call will be made)
        let config = AlpacaConfig::new("dummy_key".into(), "dummy_secret".into(), true);
        let client = AlpacaClient::new(config);

        let request = AlpacaBracketOrderRequest::new(
            InstrumentNameExchange::new("SPY"),
            crate::order::id::StrategyId::new("test"),
            crate::order::id::ClientOrderId::new("test-tif"),
            Side::Buy,
            dec!(1),
            dec!(100.00),
            dec!(120.00),
            dec!(90.00),
            TimeInForce::ImmediateOrCancel, // Invalid for brackets
        );

        let result = client.open_bracket_order(request).await;

        assert!(
            result.parent.state.is_failed(),
            "Bracket order with IOC TIF should be rejected locally"
        );
    }

    #[tokio::test]
    async fn test_open_bracket_order_rejects_invalid_price_ordering() {
        use rust_decimal_macros::dec;
        use rustrade_instrument::instrument::name::InstrumentNameExchange;

        let config = AlpacaConfig::new("dummy_key".into(), "dummy_secret".into(), true);
        let client = AlpacaClient::new(config);

        // Buy bracket with SL > entry (invalid)
        let request = AlpacaBracketOrderRequest::new(
            InstrumentNameExchange::new("SPY"),
            crate::order::id::StrategyId::new("test"),
            crate::order::id::ClientOrderId::new("test-price"),
            Side::Buy,
            dec!(1),
            dec!(100.00),
            dec!(120.00),
            dec!(105.00), // Invalid: SL > entry for buy
            TimeInForce::GoodUntilCancelled { post_only: false },
        );

        let result = client.open_bracket_order(request).await;

        assert!(
            result.parent.state.is_failed(),
            "Bracket order with invalid price ordering should be rejected locally"
        );
    }

    #[tokio::test]
    async fn test_open_bracket_order_rejects_invalid_sl_limit_price() {
        use rust_decimal_macros::dec;
        use rustrade_instrument::instrument::name::InstrumentNameExchange;

        let config = AlpacaConfig::new("dummy_key".into(), "dummy_secret".into(), true);
        let client = AlpacaClient::new(config);

        // Buy bracket with SL limit > SL trigger (invalid for sell stop-limit)
        let request = AlpacaBracketOrderRequest::new(
            InstrumentNameExchange::new("SPY"),
            crate::order::id::StrategyId::new("test"),
            crate::order::id::ClientOrderId::new("test-sl-limit"),
            Side::Buy,
            dec!(1),
            dec!(100.00),
            dec!(120.00),
            dec!(90.00),
            TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .with_stop_loss_limit_price(dec!(95.00)); // Invalid: limit > trigger for sell SL

        let result = client.open_bracket_order(request).await;

        assert!(
            result.parent.state.is_failed(),
            "Bracket order with invalid SL limit price should be rejected locally"
        );
    }

    #[test]
    fn test_non_bracket_order_omits_bracket_fields() {
        // Regular limit order should not have bracket fields
        let body = AlpacaOrderRequest {
            symbol: "AAPL",
            qty: "1".to_string(),
            side: "buy",
            order_type: "limit",
            time_in_force: "gtc",
            limit_price: Some("150.00".to_string()),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            client_order_id: Some("regular-001"),
            position_intent: Some(AlpacaPositionIntent::BuyToOpen),
            order_class: None,
            take_profit: None,
            stop_loss: None,
        };

        let json = serde_json::to_value(&body).unwrap();

        assert_eq!(json["symbol"], "AAPL");
        assert!(
            json.get("order_class").is_none(),
            "order_class should be omitted for non-bracket orders"
        );
        assert!(
            json.get("take_profit").is_none(),
            "take_profit should be omitted for non-bracket orders"
        );
        assert!(
            json.get("stop_loss").is_none(),
            "stop_loss should be omitted for non-bracket orders"
        );
    }

    #[test]
    fn test_parse_timestamp_valid() {
        let ts = parse_timestamp("2025-04-18T14:30:00Z");
        assert!(ts.is_some());
        let ts2 = parse_timestamp("2025-04-18T14:30:00.123456Z");
        assert!(ts2.is_some());
        assert_eq!(parse_timestamp("not-a-timestamp"), None);
    }

    #[test]
    fn test_check_auth_response_authorized() {
        let msg =
            r#"{"stream":"authorization","data":{"status":"authorized","action":"authenticate"}}"#;
        assert!(matches!(check_auth_response(msg), Some(Ok(()))));
    }

    #[test]
    fn test_check_auth_response_unauthorized() {
        let msg = r#"{"stream":"authorization","data":{"status":"unauthorized"}}"#;
        assert!(matches!(
            check_auth_response(msg),
            Some(Err(HandshakeError::Auth(_)))
        ));
    }

    #[test]
    fn test_check_auth_response_non_auth_message() {
        let msg = r#"{"stream":"trade_updates","data":{}}"#;
        assert!(check_auth_response(msg).is_none());
    }

    #[test]
    fn test_check_listen_ack() {
        let ack = r#"{"stream":"listening","data":{"streams":["trade_updates"]}}"#;
        assert!(check_listen_ack(ack));

        let other = r#"{"stream":"authorization","data":{}}"#;
        assert!(!check_listen_ack(other));
    }

    #[test]
    fn test_dedup_cache() {
        let cache = new_dedup_cache();
        let key = SmolStr::new("order-1:1");
        assert!(
            !is_duplicate(&cache, &key),
            "first time should not be duplicate"
        );
        assert!(
            is_duplicate(&cache, &key),
            "second time should be duplicate"
        );
    }

    #[tokio::test]
    async fn test_exponential_backoff_progression_and_exhaustion() {
        tokio::time::pause();

        let mut b = ExponentialBackoff::new();

        // First wait should succeed and increment attempt.
        assert!(b.wait().await, "first wait should return true");
        assert_eq!(b.attempt, 1);

        // Drain remaining attempts.
        while b.wait().await {}

        // Attempt counter saturates at max_attempts.
        assert_eq!(b.attempt, MAX_RECONNECT_ATTEMPTS);

        // Once exhausted, wait returns false immediately without sleeping.
        assert!(!b.wait().await, "exhausted backoff should return false");

        // reset() restores attempt to 0.
        b.reset();
        assert_eq!(b.attempt, 0);

        // After reset, wait works again.
        assert!(b.wait().await, "wait should succeed after reset");
        assert_eq!(b.attempt, 1);
    }

    #[test]
    fn test_convert_account_to_balances_empty_assets() {
        let account = AlpacaAccount {
            equity: "12000.00".into(),
            buying_power: "10000.00".into(),
            options_buying_power: Some("8000.00".into()),
            crypto_buying_power: None,
        };
        let balances = convert_account_to_balances(&account, &[]);
        assert_eq!(balances.len(), 1);
        assert_eq!(
            balances[0].balance.total,
            Decimal::from_str("12000.00").unwrap()
        );
        // options_buying_power is preferred for free
        assert_eq!(
            balances[0].balance.free,
            Decimal::from_str("8000.00").unwrap()
        );
    }

    #[test]
    fn test_convert_account_to_balances_usd_filter() {
        let account = AlpacaAccount {
            equity: "12000.00".into(),
            buying_power: "10000.00".into(),
            options_buying_power: None,
            crypto_buying_power: None,
        };
        let usd = vec![AssetNameExchange::new("USD")];
        let balances = convert_account_to_balances(&account, &usd);
        assert_eq!(balances.len(), 1);

        let non_usd = vec![AssetNameExchange::new("BTC")];
        let balances = convert_account_to_balances(&account, &non_usd);
        assert!(balances.is_empty());
    }

    #[test]
    fn test_is_options_or_equity_symbol() {
        // Crypto symbols contain '/'
        assert!(!is_options_or_equity_symbol("BTC/USD"));
        assert!(!is_options_or_equity_symbol("ETH/USD"));
        assert!(!is_options_or_equity_symbol("SOL/USD"));

        // Equity symbols — no slash
        assert!(is_options_or_equity_symbol("AAPL"));
        assert!(is_options_or_equity_symbol("SPY"));
        assert!(is_options_or_equity_symbol("MSFT"));

        // OCC option symbols — no slash
        assert!(is_options_or_equity_symbol("SPY250418C00450000"));
        assert!(is_options_or_equity_symbol("AAPL250418P00145000"));
    }

    #[test]
    fn test_parse_order_error_already_cancelled() {
        // Locks in match arm ordering: a 422 with "already" but NOT "insufficient"
        // must map to OrderAlreadyCancelled, not BalanceInsufficient.
        assert!(matches!(
            parse_order_error(
                reqwest::StatusCode::UNPROCESSABLE_ENTITY,
                "order is already cancelled"
            ),
            UnindexedOrderError::Rejected(ApiError::OrderAlreadyCancelled)
        ));
    }

    #[test]
    fn test_parse_order_error_already_wins_over_insufficient_on_422() {
        // If Alpaca sends a body containing both "already" and "insufficient",
        // the "already" arm must win (it appears first in the match).
        assert!(matches!(
            parse_order_error(
                reqwest::StatusCode::UNPROCESSABLE_ENTITY,
                "order already cancelled due to insufficient margin"
            ),
            UnindexedOrderError::Rejected(ApiError::OrderAlreadyCancelled)
        ));
    }

    fn make_order_ws<'a>(
        id: &str,
        symbol: &str,
        side: &str,
        filled_qty: &'a str,
    ) -> AlpacaOrderWs<'a> {
        AlpacaOrderWs {
            id: SmolStr::new(id),
            client_order_id: None,
            symbol: SmolStr::new(symbol),
            qty: Some("2"),
            filled_qty: Some(filled_qty),
            side: SmolStr::new(side),
            order_type: SmolStr::new("limit"),
            time_in_force: SmolStr::new("day"),
            limit_price: Some("100.00"),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            status: SmolStr::new("partially_filled"),
        }
    }

    #[test]
    fn test_convert_trade_update_fill_produces_trade_with_dedup_key() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("fill"),
            order: make_order_ws("ord-1", "SPY", "buy", "1"),
            price: Some("150.00"),
            qty: Some("1"),
            timestamp: Some("2025-04-18T14:30:00Z"),
        };
        let event = convert_trade_update(update).expect("fill should produce an event");
        let AccountEventKind::Trade(trade) = event.kind else {
            panic!("expected Trade, got {:?}", event.kind);
        };
        // Trade ID must be "{order_id}:{cumulative_filled_qty}" for dedup to match REST path.
        assert_eq!(trade.id.0.as_str(), "ord-1:1");
        assert_eq!(trade.price, Decimal::from_str("150.00").unwrap());
        assert_eq!(trade.quantity, Decimal::from_str("1").unwrap());
    }

    #[test]
    fn test_convert_trade_update_partial_fill() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("partial_fill"),
            order: make_order_ws("ord-2", "AAPL", "sell", "0.5"),
            price: Some("200.00"),
            qty: Some("0.5"),
            timestamp: None,
        };
        let event = convert_trade_update(update).expect("partial_fill should produce an event");
        assert!(matches!(event.kind, AccountEventKind::Trade(_)));
    }

    #[test]
    fn test_convert_trade_update_new_order_produces_snapshot() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("new"),
            order: AlpacaOrderWs {
                id: SmolStr::new("ord-new"),
                client_order_id: Some(SmolStr::new("cid-1")),
                symbol: SmolStr::new("AAPL"),
                qty: Some("10"),
                filled_qty: Some("0"),
                side: SmolStr::new("buy"),
                order_type: SmolStr::new("limit"),
                time_in_force: SmolStr::new("day"),
                limit_price: Some("150.00"),
                stop_price: None,
                trail_percent: None,
                trail_price: None,
                status: SmolStr::new("new"),
            },
            price: None,
            qty: None,
            timestamp: Some("2025-04-18T14:30:00Z"),
        };
        let event = convert_trade_update(update).expect("new event should produce an event");
        assert!(matches!(event.kind, AccountEventKind::OrderSnapshot(_)));
    }

    #[test]
    fn test_convert_trade_update_canceled_produces_cancel() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("canceled"),
            order: make_order_ws("ord-3", "AAPL", "sell", "0"),
            price: None,
            qty: None,
            timestamp: Some("2025-04-18T14:30:00Z"),
        };
        let event = convert_trade_update(update).expect("canceled should produce an event");
        let AccountEventKind::OrderCancelled(response) = event.kind else {
            panic!("expected OrderCancelled, got {:?}", event.kind);
        };
        assert!(response.state.is_ok());
    }

    #[test]
    fn test_convert_trade_update_rejected_produces_error() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("rejected"),
            order: make_order_ws("ord-4", "SPY", "buy", "0"),
            price: None,
            qty: None,
            timestamp: None,
        };
        let event = convert_trade_update(update).expect("rejected should produce an event");
        let AccountEventKind::OrderCancelled(response) = event.kind else {
            panic!("expected OrderCancelled, got {:?}", event.kind);
        };
        assert!(response.state.is_err());
    }

    #[test]
    fn test_convert_open_order_notional_qty_none_is_skipped() {
        // qty=None means this is a notional order (placed by dollar value).
        // Recording it with quantity=0 would corrupt reconciliation, so it must be skipped.
        let order = AlpacaOrderResponse {
            id: "ord-notional".to_string(),
            client_order_id: None,
            symbol: "SPY".to_string(),
            qty: None,
            filled_qty: "0".to_string(),
            side: "buy".to_string(),
            order_type: "market".to_string(),
            time_in_force: "day".to_string(),
            limit_price: None,
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            created_at: "2025-04-18T14:30:00Z".to_string(),
        };
        assert!(convert_open_order(&order).is_none());
    }

    #[test]
    fn test_convert_activity_to_trade_bad_price_returns_none() {
        // When price is unparseable, convert_activity_to_trade must return None.
        // recover_fills advances cumulative_qty BEFORE this check so that the dedup
        // key sequence stays aligned with the WS path even when a fill is skipped.
        let activity = AlpacaActivity {
            id: "act-1".to_string(),
            order_id: "ord-1".to_string(),
            symbol: "SPY250418C00450000".to_string(),
            side: "buy".to_string(),
            price: "not-a-number".to_string(),
            qty: "1".to_string(),
            transaction_time: "2025-04-18T14:30:00Z".to_string(),
        };
        assert!(convert_activity_to_trade(&activity).is_none());
    }

    #[test]
    fn test_convert_positions_to_balances_crypto() {
        let positions = vec![
            AlpacaPosition {
                symbol: "BTC/USD".into(),
                asset_class: "crypto".into(),
                qty: "0.5".into(),
                qty_available: "0.4".into(),
            },
            AlpacaPosition {
                symbol: "ETH/USD".into(),
                asset_class: "crypto".into(),
                qty: "2.0".into(),
                qty_available: "2.0".into(),
            },
            // Equity positions should be filtered out
            AlpacaPosition {
                symbol: "AAPL".into(),
                asset_class: "us_equity".into(),
                qty: "10".into(),
                qty_available: "10".into(),
            },
        ];

        // All crypto assets
        let balances = convert_positions_to_balances(&positions, &[]);
        assert_eq!(balances.len(), 2, "only crypto positions returned");
        assert_eq!(balances[0].asset.name().as_str(), "btc");
        // total = qty (0.5 BTC), free = qty_available (0.4 BTC)
        assert_eq!(balances[0].balance.total, Decimal::from_str("0.5").unwrap());
        assert_eq!(balances[0].balance.free, Decimal::from_str("0.4").unwrap());

        // Filter to BTC only
        let btc_only = vec![AssetNameExchange::new("BTC")];
        let balances = convert_positions_to_balances(&positions, &btc_only);
        assert_eq!(balances.len(), 1);
        assert_eq!(balances[0].asset.name().as_str(), "btc");
    }

    fn make_order_response(id: &str, symbol: &str) -> AlpacaOrderResponse {
        AlpacaOrderResponse {
            id: id.to_string(),
            client_order_id: None,
            symbol: symbol.to_string(),
            qty: Some("1".to_string()),
            filled_qty: "0".to_string(),
            side: "buy".to_string(),
            order_type: "limit".to_string(),
            time_in_force: "day".to_string(),
            limit_price: Some("100.00".to_string()),
            stop_price: None,
            trail_percent: None,
            trail_price: None,
            created_at: "2025-04-18T14:30:00Z".to_string(),
        }
    }

    #[test]
    fn test_build_instrument_snapshots_empty_instruments_returns_only_with_orders() {
        let orders = vec![
            make_order_response("o1", "AAPL"),
            make_order_response("o2", "SPY"),
        ];
        let snapshots = build_instrument_snapshots(orders, &[]);
        assert_eq!(snapshots.len(), 2);
        let symbols: Vec<&str> = snapshots
            .iter()
            .map(|s| s.instrument.name().as_str())
            .collect();
        assert!(symbols.contains(&"AAPL"));
        assert!(symbols.contains(&"SPY"));
    }

    #[test]
    fn test_build_instrument_snapshots_requested_instrument_no_orders_gets_empty_snapshot() {
        // When instruments list is provided, every requested instrument must appear
        // even if it has no open orders — callers depend on this for reconciliation.
        let orders = vec![make_order_response("o1", "AAPL")];
        let instruments = vec![
            InstrumentNameExchange::new("AAPL"),
            InstrumentNameExchange::new("SPY"),
        ];
        let snapshots = build_instrument_snapshots(orders, &instruments);
        assert_eq!(snapshots.len(), 2);
        let spy = snapshots
            .iter()
            .find(|s| s.instrument.name().as_str() == "SPY")
            .expect("SPY snapshot must be present even with no orders");
        assert!(spy.orders.is_empty());
    }

    #[test]
    fn test_build_instrument_snapshots_non_requested_instrument_excluded() {
        // An instrument with open orders that is NOT in the requested list must
        // not appear in the output when the instruments list is non-empty.
        let orders = vec![
            make_order_response("o1", "AAPL"),
            make_order_response("o2", "MSFT"), // not requested
        ];
        let instruments = vec![InstrumentNameExchange::new("AAPL")];
        let snapshots = build_instrument_snapshots(orders, &instruments);
        assert_eq!(snapshots.len(), 1);
        assert_eq!(snapshots[0].instrument.name().as_str(), "AAPL");
    }

    /// Verifies that the dedup key synthesised by `recover_fills` (REST path) matches
    /// the key produced by `convert_trade_update` (WS path) for the same partial fills.
    ///
    /// This is the critical invariant for cross-source dedup after a reconnect:
    /// both paths must produce `"{order_id}:{cumulative_filled_qty}"` for the same fill.
    #[test]
    fn test_recover_fills_dedup_key_matches_ws_path() {
        let order_id = "ord-1";

        // WS path: Alpaca sends cumulative filled_qty with each event.
        // Two partial fills of 1 lot each → filled_qty "1" then "2".
        let ws_keys: Vec<SmolStr> = ["1", "2"]
            .iter()
            .filter_map(|filled_qty| {
                let update = AlpacaTradeUpdate {
                    event: SmolStr::new("partial_fill"),
                    order: make_order_ws(order_id, "SPY", "buy", filled_qty),
                    price: Some("150.00"),
                    qty: Some("1"),
                    timestamp: None,
                };
                let event = convert_trade_update(update)?;
                fill_dedup_key_from_event(&event).cloned()
            })
            .collect();

        // REST path: recover_fills accumulates cumulative qty from per-execution activities.
        // Two activities with exec qty "1" each → cumulative 1 then 2.
        let mut cumulative = Decimal::ZERO;
        let rest_keys: Vec<SmolStr> = ["1", "1"]
            .iter()
            .map(|exec_qty| {
                cumulative += Decimal::from_str(exec_qty).unwrap();
                format_smolstr!("{}:{}", order_id, cumulative.normalize())
            })
            .collect();

        assert_eq!(
            ws_keys, rest_keys,
            "REST recovery dedup keys must match WS path keys for cross-source dedup to work"
        );
        assert_eq!(ws_keys[0].as_str(), "ord-1:1");
        assert_eq!(ws_keys[1].as_str(), "ord-1:2");
    }

    /// Verifies that `early_dedup_key` produces the same key as the full event path.
    ///
    /// The early dedup check (M-1 optimization) extracts the key from raw WS fields
    /// before constructing the full event. This test ensures both paths produce
    /// identical keys, otherwise duplicate detection would fail.
    #[test]
    fn early_dedup_key_matches_full_event_path() {
        let update = AlpacaTradeUpdate {
            event: SmolStr::new("fill"),
            order: make_order_ws("ord-abc", "SPY", "buy", "5"),
            price: Some("150.00"),
            qty: Some("5"),
            timestamp: None,
        };

        // Early path: extract key before full event construction
        let early_key = early_dedup_key(&update);

        // Full path: construct event then extract key
        let event = convert_trade_update(update).expect("fill should produce an event");
        let full_key =
            fill_dedup_key_from_event(&event).expect("fill event should have a dedup key");

        assert_eq!(
            early_key.as_str(),
            full_key.as_str(),
            "early_dedup_key must produce the same key as the full event path"
        );
        assert_eq!(early_key.as_str(), "ord-abc:5");
    }

    /// Verifies that `early_dedup_key` correctly normalizes decimal strings.
    ///
    /// Alpaca may send "1.00" or "1" for the same fill. Both must produce the same
    /// dedup key to avoid false negatives in duplicate detection.
    #[test]
    fn early_dedup_key_normalizes_decimal_strings() {
        // Test with trailing zeros: "1.00" should normalize to "1"
        let update1 = AlpacaTradeUpdate {
            event: SmolStr::new("fill"),
            order: AlpacaOrderWs {
                id: SmolStr::new("ord-x"),
                client_order_id: Some(SmolStr::new("cid")),
                symbol: SmolStr::new("AAPL"),
                qty: Some("10"),
                filled_qty: Some("1.00"),
                side: SmolStr::new("buy"),
                order_type: SmolStr::new("market"),
                time_in_force: SmolStr::new("day"),
                limit_price: None,
                stop_price: None,
                trail_percent: None,
                trail_price: None,
                status: SmolStr::new("filled"),
            },
            price: Some("100.00"),
            qty: Some("10"),
            timestamp: None,
        };
        assert_eq!(early_dedup_key(&update1).as_str(), "ord-x:1");

        // Test already normalized: "1" stays "1"
        let update2 = AlpacaTradeUpdate {
            event: SmolStr::new("fill"),
            order: AlpacaOrderWs {
                id: SmolStr::new("ord-x"),
                client_order_id: Some(SmolStr::new("cid")),
                symbol: SmolStr::new("AAPL"),
                qty: Some("10"),
                filled_qty: Some("1"),
                side: SmolStr::new("buy"),
                order_type: SmolStr::new("market"),
                time_in_force: SmolStr::new("day"),
                limit_price: None,
                stop_price: None,
                trail_percent: None,
                trail_price: None,
                status: SmolStr::new("filled"),
            },
            price: Some("100.00"),
            qty: Some("10"),
            timestamp: None,
        };
        assert_eq!(early_dedup_key(&update2).as_str(), "ord-x:1");

        // Test single trailing zero: "1.0" normalizes to "1"
        let update3 = AlpacaTradeUpdate {
            event: SmolStr::new("fill"),
            order: AlpacaOrderWs {
                id: SmolStr::new("ord-x"),
                client_order_id: Some(SmolStr::new("cid")),
                symbol: SmolStr::new("AAPL"),
                qty: Some("10"),
                filled_qty: Some("1.0"),
                side: SmolStr::new("buy"),
                order_type: SmolStr::new("market"),
                time_in_force: SmolStr::new("day"),
                limit_price: None,
                stop_price: None,
                trail_percent: None,
                trail_price: None,
                status: SmolStr::new("filled"),
            },
            price: Some("100.00"),
            qty: Some("10"),
            timestamp: None,
        };
        assert_eq!(early_dedup_key(&update3).as_str(), "ord-x:1");
    }

    /// Regression guard for HIGH-2: a `rejected` event without `filled_qty` in the JSON
    /// previously caused the entire AlpacaTradeUpdate to fail deserialization, silently
    /// dropping the event. After the fix, `filled_qty` is Option and defaults to None
    /// (unwrapped to "0" at use-sites), so the event reaches the `rejected` branch.
    #[test]
    fn process_ws_text_rejected_event_without_filled_qty_is_not_dropped() {
        let (tx, mut rx) = mpsc::unbounded_channel();
        let dedup = new_dedup_cache();
        let mut backoff = ExponentialBackoff::new();

        // Minimal rejected-event JSON — no `filled_qty` field in the order object.
        let json = r#"{"stream":"trade_updates","data":{"event":"rejected","order":{"id":"test-rej-id","client_order_id":"test-cid","symbol":"AAPL","qty":"10","side":"buy","type":"limit","time_in_force":"day","limit_price":"100.00","status":"rejected"}}}"#;

        process_ws_text(json, &tx, &dedup, &mut backoff);

        // The event must NOT be silently dropped — an OrderCancelled must be emitted.
        let event = rx.try_recv()
            .expect("rejected event without filled_qty must produce an AccountEvent, not be silently dropped");
        assert!(
            matches!(event.kind, AccountEventKind::OrderCancelled(_)),
            "rejected event must map to OrderCancelled, got: {:?}",
            event.kind
        );
    }

    /// Pins the string representation of `Decimal::ZERO.normalize()`, which is used
    /// as the dedup key fallback when `filled_qty` is unparseable: `"{order_id}:0"`.
    #[test]
    fn decimal_zero_normalize_is_zero_str() {
        assert_eq!(Decimal::ZERO.normalize().to_string(), "0");
    }

    /// Verifies that trailing zeros are stripped by `normalize()`, ensuring dedup keys
    /// match regardless of whether Alpaca returns `"1.00"` or `"1"` for the same qty.
    /// This is the critical invariant for REST/WS dedup key equivalence.
    #[test]
    fn decimal_normalize_strips_trailing_zeros() {
        // Alpaca may return "1.00" in REST but WS cumulative may be "1" — must match.
        let from_rest = Decimal::from_str("1.00").unwrap().normalize();
        let from_ws = Decimal::from_str("1").unwrap().normalize();
        assert_eq!(from_rest.to_string(), from_ws.to_string());
        assert_eq!(from_rest.to_string(), "1");

        // More edge cases: various trailing zero representations.
        assert_eq!(
            Decimal::from_str("100.000")
                .unwrap()
                .normalize()
                .to_string(),
            "100"
        );
        assert_eq!(
            Decimal::from_str("0.10").unwrap().normalize().to_string(),
            "0.1"
        );
        assert_eq!(
            Decimal::from_str("0.100").unwrap().normalize().to_string(),
            "0.1"
        );
    }

    // H-2: zero options_buying_power falls back to buying_power (not free=0).
    // Alpaca returns options_buying_power="0.00" on equity-only accounts (options
    // not enabled) rather than omitting the field. Without the .filter(!is_zero())
    // guard the engine would see free=0 and block all orders.
    #[test]
    fn convert_account_to_balances_zero_options_buying_power_falls_back_to_buying_power() {
        let account = AlpacaAccount {
            equity: "12000.00".into(),
            buying_power: "10000.00".into(),
            options_buying_power: Some("0.00".into()), // equity-only: options not enabled
            crypto_buying_power: None,
        };
        let balances = convert_account_to_balances(&account, &[]);
        assert_eq!(balances.len(), 1);
        assert_eq!(
            balances[0].balance.free,
            Decimal::from_str("10000.00").unwrap(),
            "zero options_buying_power must fall back to buying_power, not report free=0"
        );
    }

    // M-2: map_position_intent derives intent from (reduce_only, side).
    #[test]
    fn map_position_intent_open_buy_maps_to_buy_to_open() {
        assert_eq!(
            map_position_intent(Side::Buy, false),
            AlpacaPositionIntent::BuyToOpen
        );
    }

    #[test]
    fn map_position_intent_open_sell_maps_to_sell_to_open() {
        assert_eq!(
            map_position_intent(Side::Sell, false),
            AlpacaPositionIntent::SellToOpen
        );
    }

    #[test]
    fn map_position_intent_reduce_buy_maps_to_buy_to_close() {
        assert_eq!(
            map_position_intent(Side::Buy, true),
            AlpacaPositionIntent::BuyToClose
        );
    }

    #[test]
    fn map_position_intent_reduce_sell_maps_to_sell_to_close() {
        assert_eq!(
            map_position_intent(Side::Sell, true),
            AlpacaPositionIntent::SellToClose
        );
    }

    // M-1: parse_order_error — pin all status-code branches not covered by existing tests.
    #[test]
    fn parse_order_error_401_maps_to_unauthenticated() {
        // 401 Unauthorized: invalid/expired API credentials.
        assert!(matches!(
            parse_order_error(reqwest::StatusCode::UNAUTHORIZED, "bad credentials"),
            UnindexedOrderError::Rejected(ApiError::Unauthenticated(_))
        ));
    }

    #[test]
    fn parse_order_error_403_maps_to_unauthenticated() {
        // 403 Forbidden indicates auth/permission failure — use Unauthenticated, not
        // OrderRejected or BalanceInsufficient (which could trigger incorrect retry logic).
        assert!(matches!(
            parse_order_error(reqwest::StatusCode::FORBIDDEN, "account suspended"),
            UnindexedOrderError::Rejected(ApiError::Unauthenticated(_))
        ));
    }

    #[test]
    fn parse_order_error_404_maps_to_order_rejected_with_not_found_prefix() {
        let err = parse_order_error(reqwest::StatusCode::NOT_FOUND, "order not found");
        let UnindexedOrderError::Rejected(ApiError::OrderRejected(msg)) = err else {
            panic!("expected OrderRejected, got {err:?}");
        };
        assert!(
            msg.contains("order not found"),
            "message should contain 'order not found': {msg}"
        );
    }

    #[test]
    fn parse_order_error_422_insufficient_only_maps_to_balance_insufficient() {
        // No "already" in body → must not match OrderAlreadyCancelled; must be BalanceInsufficient.
        assert!(matches!(
            parse_order_error(
                reqwest::StatusCode::UNPROCESSABLE_ENTITY,
                "insufficient funds for this order"
            ),
            UnindexedOrderError::Rejected(ApiError::BalanceInsufficient(_, _))
        ));
    }

    #[test]
    fn parse_order_error_429_maps_to_rate_limit() {
        assert!(matches!(
            parse_order_error(reqwest::StatusCode::TOO_MANY_REQUESTS, "rate limited"),
            UnindexedOrderError::Rejected(ApiError::RateLimit)
        ));
    }

    // M-4: parse_time_in_force — pin the unknown-value fallback to GoodUntilEndOfDay.
    // If Alpaca adds a new TIF (e.g. "opg" for at-the-open), orders continue to be
    // tracked with EOD expiry until this function is updated; the warn! makes it visible.
    #[test]
    fn parse_time_in_force_unknown_value_falls_back_to_good_until_end_of_day() {
        assert_eq!(
            parse_time_in_force("opg"),
            TimeInForce::GoodUntilEndOfDay,
            "unknown TIF must fall back to GoodUntilEndOfDay (with a warn! in production)"
        );
    }

    // L-4: build_instrument_snapshots — output order must match the instruments slice,
    // not the internal IndexMap insertion order of the orders vec.
    #[test]
    fn build_instrument_snapshots_output_order_matches_instruments_slice() {
        // Orders arrive in symbol order: SPY, AAPL, MSFT.
        let orders = vec![
            make_order_response("o1", "SPY"),
            make_order_response("o2", "AAPL"),
            make_order_response("o3", "MSFT"),
        ];
        // Request a different order: MSFT first, then AAPL.
        let instruments = vec![
            InstrumentNameExchange::new("MSFT"),
            InstrumentNameExchange::new("AAPL"),
        ];
        let snapshots = build_instrument_snapshots(orders, &instruments);
        assert_eq!(snapshots.len(), 2);
        assert_eq!(
            snapshots[0].instrument.name().as_str(),
            "MSFT",
            "first snapshot must be MSFT (first in instruments slice)"
        );
        assert_eq!(
            snapshots[1].instrument.name().as_str(),
            "AAPL",
            "second snapshot must be AAPL (second in instruments slice)"
        );
    }

    // ---------------------------------------------------------------------------
    // HTTP-mocked tests — paginate_activities (H-1) and fetch_raw_open_orders (H-3)
    // ---------------------------------------------------------------------------
    //
    // These tests use wiremock to stand up a local HTTP server, verifying the full
    // pagination loop and truncation logic without touching the real Alpaca API.
    mod http_tests {
        use super::super::*;
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};

        /// Serves pre-configured JSON pages in registration order.
        ///
        /// Each call to `respond` advances an atomic counter and returns the next
        /// page body. Panics if called more times than pages were configured —
        /// surfaces unexpected extra requests as an explicit test failure rather
        /// than silently returning a stale response.
        struct Sequential {
            call: std::sync::atomic::AtomicU32,
            pages: Vec<serde_json::Value>,
        }

        impl Sequential {
            fn new(pages: Vec<serde_json::Value>) -> Self {
                Self {
                    call: std::sync::atomic::AtomicU32::new(0),
                    pages,
                }
            }
        }

        impl Respond for Sequential {
            fn respond(&self, _: &Request) -> ResponseTemplate {
                let i = self.call.fetch_add(1, std::sync::atomic::Ordering::Relaxed) as usize;
                let body = self.pages.get(i).unwrap_or_else(|| {
                    panic!(
                        "Sequential: request #{i} has no configured response \
                         (only {} page(s) supplied)",
                        self.pages.len()
                    )
                });
                ResponseTemplate::new(200).set_body_json(body)
            }
        }

        /// Build a JSON array of N minimal AlpacaActivity objects with unique IDs.
        fn make_activities_json(count: usize, id_prefix: &str) -> serde_json::Value {
            serde_json::Value::Array(
                (0..count)
                    .map(|i| {
                        serde_json::json!({
                            "id": format!("{id_prefix}-{i:05}"),
                            "order_id": "ord-1",
                            "symbol": "SPY",
                            "side": "buy",
                            "price": "100.00",
                            "qty": "1",
                            "transaction_time": "2025-04-18T14:30:00Z"
                        })
                    })
                    .collect(),
            )
        }

        /// Build a JSON array of N minimal AlpacaOrderResponse objects with unique IDs.
        fn make_orders_json(count: usize) -> serde_json::Value {
            serde_json::Value::Array(
                (0..count)
                    .map(|i| {
                        serde_json::json!({
                            "id": format!("order-{i:05}"),
                            "client_order_id": null,
                            "symbol": "SPY",
                            "qty": "1",
                            "filled_qty": "0",
                            "side": "buy",
                            "type": "limit",
                            "time_in_force": "day",
                            "limit_price": "100.00",
                            "created_at": "2025-04-18T14:30:00Z"
                        })
                    })
                    .collect(),
            )
        }

        // --- H-1: paginate_activities ---

        /// Single page with fewer items than the page limit — loop terminates immediately,
        /// no further request issued.
        #[tokio::test]
        async fn paginate_activities_single_page_below_max_returns_all_not_truncated() {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/v2/account/activities"))
                .respond_with(
                    ResponseTemplate::new(200).set_body_json(make_activities_json(5, "act")),
                )
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = paginate_activities(&http, &rl, &server.uri(), "2025-01-01T00:00:00Z")
                .await
                .unwrap();

            assert_eq!(result.activities.len(), 5);
            assert!(!result.truncated);
            assert_eq!(server.received_requests().await.unwrap().len(), 1);
        }

        /// First page has exactly ALPACA_MAX_ACTIVITIES items, which triggers a second
        /// request. The second page is empty, so the loop terminates without truncation.
        #[tokio::test]
        async fn paginate_activities_exactly_page_size_items_fetches_second_page() {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/v2/account/activities"))
                .respond_with(Sequential::new(vec![
                    make_activities_json(ALPACA_MAX_ACTIVITIES, "act"),
                    serde_json::json!([]), // empty second page → loop stops
                ]))
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = paginate_activities(&http, &rl, &server.uri(), "2025-01-01T00:00:00Z")
                .await
                .unwrap();

            assert_eq!(result.activities.len(), ALPACA_MAX_ACTIVITIES);
            assert!(!result.truncated);
            assert_eq!(
                server.received_requests().await.unwrap().len(),
                2,
                "exactly 2 requests: first full page + second empty page"
            );
        }

        /// Two-page case: 100 items on page 1, 37 on page 2 — all accumulated,
        /// loop terminates on the partial second page without truncation.
        #[tokio::test]
        async fn paginate_activities_two_pages_returns_combined_activities_not_truncated() {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/v2/account/activities"))
                .respond_with(Sequential::new(vec![
                    make_activities_json(ALPACA_MAX_ACTIVITIES, "p1"),
                    make_activities_json(37, "p2"),
                ]))
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = paginate_activities(&http, &rl, &server.uri(), "2025-01-01T00:00:00Z")
                .await
                .unwrap();

            assert_eq!(result.activities.len(), ALPACA_MAX_ACTIVITIES + 37);
            assert!(!result.truncated);
            assert_eq!(server.received_requests().await.unwrap().len(), 2);
        }

        /// When every page is full the loop runs until MAX_ACTIVITY_PAGES pages have been
        /// fetched, then sets truncated=true and stops. Exactly MAX_ACTIVITY_PAGES HTTP
        /// requests are issued (the truncation guard fires before the (N+1)th call).
        #[tokio::test]
        async fn paginate_activities_at_max_pages_sets_truncated_true() {
            let server = MockServer::start().await;

            // Always return a full page — the loop must enforce the cap itself.
            Mock::given(method("GET"))
                .and(path("/v2/account/activities"))
                .respond_with(
                    ResponseTemplate::new(200)
                        .set_body_json(make_activities_json(ALPACA_MAX_ACTIVITIES, "act")),
                )
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = paginate_activities(&http, &rl, &server.uri(), "2025-01-01T00:00:00Z")
                .await
                .unwrap();

            assert!(
                result.truncated,
                "must be truncated after MAX_ACTIVITY_PAGES pages"
            );
            assert_eq!(
                result.activities.len(),
                MAX_ACTIVITY_PAGES * ALPACA_MAX_ACTIVITIES,
                "must accumulate exactly MAX_ACTIVITY_PAGES * page_size activities"
            );
            // The truncation check fires at the top of the loop when pages == MAX_ACTIVITY_PAGES,
            // before the (MAX_ACTIVITY_PAGES+1)th request would be issued.
            assert_eq!(
                server.received_requests().await.unwrap().len(),
                MAX_ACTIVITY_PAGES,
                "loop must issue exactly MAX_ACTIVITY_PAGES requests then stop"
            );
        }

        // --- H-3: fetch_raw_open_orders truncation boundary ---

        /// 499 orders (one below MAX_OPEN_ORDERS) is not truncated — returns Ok.
        #[tokio::test]
        async fn fetch_raw_open_orders_499_results_returns_ok() {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/v2/orders"))
                .respond_with(
                    ResponseTemplate::new(200).set_body_json(make_orders_json(MAX_OPEN_ORDERS - 1)),
                )
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = fetch_raw_open_orders(&http, &rl, &server.uri(), &[]).await;

            assert!(
                result.is_ok(),
                "499 orders must not trigger truncation: {result:?}"
            );
            assert_eq!(result.unwrap().len(), MAX_OPEN_ORDERS - 1);
        }

        /// Exactly MAX_OPEN_ORDERS results triggers TruncatedSnapshot because Alpaca's
        /// API cap means the response is likely incomplete. An off-by-one here would
        /// either silently corrupt OMS state or incorrectly reject a valid account.
        #[tokio::test]
        async fn fetch_raw_open_orders_500_results_returns_truncated_snapshot_error() {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/v2/orders"))
                .respond_with(
                    ResponseTemplate::new(200).set_body_json(make_orders_json(MAX_OPEN_ORDERS)),
                )
                .mount(&server)
                .await;

            let http = reqwest::Client::new();
            let rl = RateLimitTracker::new();
            let result = fetch_raw_open_orders(&http, &rl, &server.uri(), &[]).await;

            assert!(
                matches!(
                    result,
                    Err(UnindexedClientError::TruncatedSnapshot { limit }) if limit == MAX_OPEN_ORDERS
                ),
                "500 orders must return TruncatedSnapshot, got: {result:?}"
            );
        }

        // --- L-2: open_order passes reduce_only through to position_intent ---

        /// Verifies that `open_order` correctly derives `position_intent` from
        /// `reduce_only` and `side`. This test exercises the full path:
        /// `open_order` → `map_position_intent` → `open_order_inner` → HTTP request.
        ///
        /// Uses wiremock to capture the request body and verify position_intent.
        #[tokio::test]
        async fn open_order_reduce_only_sell_sends_sell_to_close_intent() {
            use crate::client::ExecutionClient;
            use crate::order::request::{OrderRequestOpen, RequestOpen};
            use crate::order::{
                OrderKey, OrderKind, TimeInForce,
                id::{ClientOrderId, StrategyId},
            };
            use rust_decimal::Decimal;
            use rustrade_instrument::Side;
            use rustrade_instrument::exchange::ExchangeId;
            use rustrade_instrument::instrument::name::InstrumentNameExchange;
            use wiremock::matchers::{method, path};

            let server = MockServer::start().await;

            // Mock POST /v2/orders to return a valid order response.
            // Use a custom responder to capture and verify the request body.
            let captured_body = std::sync::Arc::new(parking_lot::Mutex::new(None));
            let captured_clone = captured_body.clone();

            Mock::given(method("POST"))
                .and(path("/v2/orders"))
                .respond_with(move |req: &Request| {
                    // Capture the request body for later assertion
                    let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap();
                    *captured_clone.lock() = Some(body);

                    ResponseTemplate::new(200).set_body_json(serde_json::json!({
                        "id": "test-order-id",
                        "client_order_id": "test-cid",
                        "symbol": "AAPL",
                        "qty": "10",
                        "filled_qty": "0",
                        "side": "sell",
                        "type": "market",
                        "time_in_force": "ioc",
                        "limit_price": null,
                        "created_at": "2025-04-18T14:30:00Z"
                    }))
                })
                .mount(&server)
                .await;

            // Create client with base_url_override pointing to mock server
            let config =
                AlpacaConfig::with_base_url("test-key".into(), "test-secret".into(), server.uri());
            let client = AlpacaClient::new(config);

            // Create a Sell order with reduce_only=true (should map to SellToClose)
            let request = OrderRequestOpen {
                key: OrderKey {
                    exchange: ExchangeId::AlpacaBroker,
                    instrument: InstrumentNameExchange::new("AAPL"),
                    strategy: StrategyId::new("test-strategy"),
                    cid: ClientOrderId::new("test-cid"),
                },
                state: RequestOpen {
                    side: Side::Sell,
                    price: None,
                    quantity: Decimal::new(10, 0),
                    kind: OrderKind::Market,
                    time_in_force: TimeInForce::ImmediateOrCancel,
                    position_id: None,
                    reduce_only: true, // This should map to SellToClose
                },
            };

            // Call open_order (borrows instrument)
            let result = client
                .open_order(OrderRequestOpen {
                    key: OrderKey {
                        exchange: request.key.exchange,
                        instrument: &request.key.instrument,
                        strategy: request.key.strategy.clone(),
                        cid: request.key.cid.clone(),
                    },
                    state: request.state.clone(),
                })
                .await;

            // Verify the order was accepted
            assert!(result.is_some(), "open_order should return a result");
            let order = result.unwrap();
            assert!(
                order.state.is_accepted(),
                "order should be accepted: {:?}",
                order.state
            );

            // Verify the request body contained position_intent=sell_to_close
            let body = captured_body
                .lock()
                .take()
                .expect("request body should be captured");
            assert_eq!(
                body.get("position_intent").and_then(|v| v.as_str()),
                Some("sell_to_close"),
                "reduce_only=true + Side::Sell should produce position_intent=sell_to_close, got: {body}"
            );
        }

        /// Verifies that reduce_only=false + Buy produces BuyToOpen intent.
        #[tokio::test]
        async fn open_order_not_reduce_only_buy_sends_buy_to_open_intent() {
            use crate::client::ExecutionClient;
            use crate::order::request::{OrderRequestOpen, RequestOpen};
            use crate::order::{
                OrderKey, OrderKind, TimeInForce,
                id::{ClientOrderId, StrategyId},
            };
            use rust_decimal::Decimal;
            use rustrade_instrument::Side;
            use rustrade_instrument::exchange::ExchangeId;
            use rustrade_instrument::instrument::name::InstrumentNameExchange;

            let server = MockServer::start().await;

            let captured_body = std::sync::Arc::new(parking_lot::Mutex::new(None));
            let captured_clone = captured_body.clone();

            Mock::given(method("POST"))
                .and(path("/v2/orders"))
                .respond_with(move |req: &Request| {
                    let body: serde_json::Value = serde_json::from_slice(&req.body).unwrap();
                    *captured_clone.lock() = Some(body);

                    ResponseTemplate::new(200).set_body_json(serde_json::json!({
                        "id": "test-order-id",
                        "client_order_id": "test-cid",
                        "symbol": "AAPL",
                        "qty": "10",
                        "filled_qty": "0",
                        "side": "buy",
                        "type": "market",
                        "time_in_force": "ioc",
                        "limit_price": null,
                        "created_at": "2025-04-18T14:30:00Z"
                    }))
                })
                .mount(&server)
                .await;

            let config =
                AlpacaConfig::with_base_url("test-key".into(), "test-secret".into(), server.uri());
            let client = AlpacaClient::new(config);

            let instrument = InstrumentNameExchange::new("AAPL");
            let request = OrderRequestOpen {
                key: OrderKey {
                    exchange: ExchangeId::AlpacaBroker,
                    instrument: &instrument,
                    strategy: StrategyId::new("test-strategy"),
                    cid: ClientOrderId::new("test-cid"),
                },
                state: RequestOpen {
                    side: Side::Buy,
                    price: None,
                    quantity: Decimal::new(10, 0),
                    kind: OrderKind::Market,
                    time_in_force: TimeInForce::ImmediateOrCancel,
                    position_id: None,
                    reduce_only: false, // This should map to BuyToOpen
                },
            };

            let result = client.open_order(request).await;

            assert!(result.is_some(), "open_order should return a result");
            let order = result.unwrap();
            assert!(
                order.state.is_accepted(),
                "order should be accepted: {:?}",
                order.state
            );

            let body = captured_body
                .lock()
                .take()
                .expect("request body should be captured");
            assert_eq!(
                body.get("position_intent").and_then(|v| v.as_str()),
                Some("buy_to_open"),
                "reduce_only=false + Side::Buy should produce position_intent=buy_to_open, got: {body}"
            );
        }
    }
}