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
//! The [broker API](https://docs.alpaca.markets/us/docs/about-broker-api) client.
//!
//! Two things differ from every other client in this crate. It authenticates
//! with HTTP basic auth rather than the `APCA-*` headers, and it acts *on behalf
//! of* an account, so most routes carry an account id in the path.
use futures_util::Stream;
use reqwest::Method;
use std::collections::HashSet;
use uuid::Uuid;
use crate::auth::Credentials;
use crate::broker::enums::ACHRelationshipStatus;
use crate::broker::events::{BrokerEvent, EventVersion, GetEventsRequest};
use crate::broker::fixed_income::{
EntryRequirement, GetEntryRequirementsRequest, GetUsCorporatesRequest, GetUsTreasuriesRequest,
UsCorporates, UsTreasuries,
};
use crate::broker::fpsl::{
FpslAnalytics, FpslLoansPage, FpslTier, GetFpslAnalyticsRequest, GetFpslLoansRequest,
};
use crate::broker::funding_wallet::{
BatchCreateFundingWalletsRequest, CreateRecipientBankRequest, CreateWithdrawalRequest,
DemoFundingRequest, FundingWallet, FundingWalletTransfer, FundingWalletTransfers,
FundingWallets, GetFundingDetailsRequest, RecipientBank,
};
use crate::broker::instant_funding::{
AccountInstantFundingLimits, CreateInstantFundingRequest,
CreateInstantFundingSettlementRequest, GetAccountLimitsRequest, GetInstantFundingReportRequest,
GetInstantFundingRequest, InstantFunding, InstantFundingLimits, InstantFundingReport,
};
use crate::broker::ipos::{GetIpoOfferingsRequest, IpoOfferingResponse, IpoOfferingsPage};
use crate::broker::jit::{
CreateJitSettlementRequest, GetJitBalancesRequest, GetJitReportRequest, JitLedger,
JitLedgerBalances, JitReport, JitTradingLimits,
};
use crate::broker::models::{
ACHRelationship, Account, AllAccountsPositions, Bank, BatchJournalResponse, CIPInfo, Journal,
Order, Portfolio, RebalancingRun, RunsPage, Subscription, SubscriptionsPage, TradeAccount,
TradeDocument, Transfer,
};
use crate::broker::oauth::{
GetOAuthClientRequest, OAuthClient, OAuthCode, OAuthRequest, OAuthToken,
};
use crate::broker::onboarding::{
CountryInfo, EstimateOrderRequest, GetOnfidoTokenRequest, GetOptionsApprovalsRequest,
IraExcessContribution, OnfidoToken, OptionsApproval, OptionsApprovalsPage,
RequestOptionsApprovalRequest, TradingLimits, UpdateOnfidoOutcomeRequest,
};
use crate::broker::reporting::{
AggregatePosition, AprTiers, CashInterestReport, EodPositions, GetAggregatePositionsRequest,
GetCashInterestRequest, GetEodPositionsRequest,
};
use crate::broker::requests::{
CreateACHRelationshipRequest, CreateAccountRequest, CreateBankRequest,
CreateBatchJournalRequest, CreateJournalRequest, CreateOptionExerciseRequest,
CreatePortfolioRequest, CreateReverseBatchJournalRequest, CreateRunRequest,
CreateSubscriptionRequest, CreateTransferRequest, GetAccountActivitiesRequest,
GetJournalsRequest, GetPortfoliosRequest, GetRunsRequest, GetSubscriptionsRequest,
GetTradeDocumentsRequest, GetTransfersRequest, ListAccountsRequest, OrderRequest,
UpdateAccountRequest, UpdatePortfolioRequest, UploadDocument,
};
use crate::broker::settlements::{GetSettlementsRequest, Settlement, Settlements};
use crate::config::BaseUrl;
use crate::error::Result;
use crate::rest::{Empty, RestClient, RestConfig};
use crate::sse::EventStreamRequest;
use crate::trading::{Activity, Position, Watchlist};
use crate::types::path::segment;
use crate::types::serde_util::OneOrMany;
/// A conventional ceiling on documents per upload.
///
/// Not documented by Alpaca — neither the reference nor the spec mentions a
/// count limit, only a 10MB ceiling on each document's contents. It is exposed
/// so a caller who wants a bound can apply one, and deliberately **not**
/// enforced by [`BrokerClient::upload_documents_to_account`]: an undocumented
/// limit is a guess, and rejecting a request Alpaca would have accepted is the
/// worse of the two errors.
pub const DOCUMENT_UPLOAD_LIMIT: usize = 10;
/// The id an activity pages from, whichever kind it is.
fn activity_id(activity: &Activity) -> &str {
match activity {
Activity::Trade(trade) => &trade.id,
Activity::NonTrade(non_trade) => &non_trade.id,
}
}
/// The page size assumed for the token-paginated broker routes when the caller
/// sets none. Alpaca's own default for these is 100.
const DEFAULT_PAGE_SIZE: u32 = 100;
/// Moves a page into `collected`, skipping anything already seen, and reports
/// whether the page taught the walk anything.
///
/// Every walker on this client derives its next cursor from data the server
/// controls — a last-id, a running offset, an echoed page token — and ends on an
/// empty page. A server that does not advance therefore spins the walk forever
/// with `collected` growing on every pass. That is not hypothetical: the
/// activities route is documented to ignore paging entirely when `date` is set,
/// which is exactly a non-empty page that never advances.
///
/// Progress is measured in *new* items rather than in cursor movement, because a
/// cursor comparison would miss a server cycling between two pages. `seen`
/// already knows the answer. This mirrors `walk_orders` in the trading client,
/// where the same reasoning is spelled out at length.
fn extend_with_new<T, K>(
collected: &mut Vec<T>,
seen: &mut HashSet<K>,
page: Vec<T>,
id_of: impl Fn(&T) -> K,
) -> bool
where
K: Eq + std::hash::Hash,
{
let before = collected.len();
for item in page {
if seen.insert(id_of(&item)) {
collected.push(item);
}
}
collected.len() != before
}
/// The page size to ask for, given a cap on the total.
///
/// The last request is narrowed to exactly what is still wanted rather than
/// fetching a full page and discarding the tail — one fewer record crossing the
/// wire, and the cap is honoured exactly. Returns `None` when there is no cap,
/// leaving the caller's own page size alone.
fn page_limit(configured: &Option<u32>, max_items: Option<usize>, collected: usize) -> Option<u32> {
let max_items = max_items?;
let page_size = configured.unwrap_or(DEFAULT_PAGE_SIZE);
let remaining = u32::try_from(max_items.saturating_sub(collected)).unwrap_or(u32::MAX);
Some(page_size.min(remaining))
}
/// A client for Alpaca's broker API.
///
/// ```no_run
/// # use alpaca_sdk::{Credentials, broker::BrokerClient};
/// # async fn example() -> alpaca_sdk::Result<()> {
/// // Broker credentials authenticate with basic auth; the client converts
/// // a key pair for you.
/// let client = BrokerClient::new(&Credentials::from_env()?, true)?;
///
/// let accounts = client.list_accounts(None).await?;
/// println!("{} accounts", accounts.len());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct BrokerClient {
rest: RestClient,
/// The client the event streams are read through.
///
/// They need a response body read incrementally rather than decoded whole,
/// and they carry **no timeout**: a total deadline on a `text/event-stream`
/// caps the life of the subscription rather than bounding a slow call.
events: reqwest::Client,
/// The client the two document downloads use.
///
/// Separate from `events` because a download is an ordinary call with a body
/// that ends, so a total deadline is the right shape for it — where an event
/// stream's body never finishes and a deadline would cap the life of the
/// subscription. One client cannot be both, which is why there are two.
///
/// It follows redirects — the download answers `301` to a presigned storage
/// URL — and what keeps broker credentials off that storage provider is not
/// this client but the credential *form*: `with_config` converts to basic
/// auth, and reqwest strips `Authorization` when a redirect crosses hosts.
plain: reqwest::Client,
}
impl BrokerClient {
/// A client targeting the broker sandbox or production environment.
///
/// The credentials are converted to basic auth, which is what this API
/// expects; passing an already-basic or OAuth credential leaves it alone.
///
/// # Errors
/// Returns an error if the credentials cannot be encoded as headers.
pub fn new(credentials: &Credentials, sandbox: bool) -> Result<Self> {
Self::with_config(
credentials,
RestConfig::from(BaseUrl::broker(sandbox)).api_version("v1"),
)
}
/// A client with a custom endpoint, retry policy, or timeout.
///
/// # Errors
/// Returns an error if the credentials cannot be encoded as headers.
pub fn with_config(credentials: &Credentials, config: RestConfig) -> Result<Self> {
// The broker API authenticates with HTTP basic auth over the key pair,
// where the trading and data APIs take the pair as two headers.
let credentials = credentials.clone().into_basic();
Ok(Self {
events: crate::sse::streaming_client(&credentials)?,
plain: crate::sse::download_client(&credentials, config.timeout)?,
rest: RestClient::new(&credentials, config)?,
})
}
/// The underlying transport, for routes this client does not wrap.
#[must_use]
pub fn rest(&self) -> &RestClient {
&self.rest
}
/// Issues a request whose response body is discarded.
///
/// Several broker routes answer `204 No Content`, and the exercise route
/// answers with a bare string that is not JSON.
async fn send_void<B: serde::Serialize + ?Sized>(
&self,
method: Method,
path: &str,
body: Option<&B>,
) -> Result<()> {
self.rest
.request_raw(
method,
crate::rest::Replay::ByMethod,
path,
None::<&Empty>,
body,
)
.await?;
Ok(())
}
// ---------------------------------------------------------- accounts
/// Fetches one account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_account_by_id(&self, account_id: Uuid) -> Result<Account> {
self.rest
.get(&format!("/accounts/{account_id}"), &Empty)
.await
}
/// Lists accounts, optionally filtered.
///
/// This route returns a reduced view of each account by default; name
/// [`entities`](ListAccountsRequest::entities) to fill the rest back in.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn list_accounts(
&self,
filter: Option<&ListAccountsRequest>,
) -> Result<Vec<Account>> {
match filter {
Some(filter) => self.rest.get("/accounts", filter).await,
None => self.rest.get("/accounts", &Empty).await,
}
}
/// Opens a new account.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if a field Alpaca requires on a
/// new account is missing; see [`CreateAccountRequest::validate`].
pub async fn create_account(&self, account: &CreateAccountRequest) -> Result<Account> {
account.validate()?;
self.rest.post("/accounts", account).await
}
/// Updates an account.
///
/// Unset fields are not sent, so an update touches only what it names.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn update_account(
&self,
account_id: Uuid,
update: &UpdateAccountRequest,
) -> Result<Account> {
self.rest
.patch(&format!("/accounts/{account_id}"), update)
.await
}
/// Closes an active account.
///
/// The account's records survive; only trading is stopped. Every position
/// must be closed and every dollar withdrawn first — that is the caller's
/// responsibility, and Alpaca rejects the request otherwise.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn close_account(&self, account_id: Uuid) -> Result<()> {
self.send_void(
Method::POST,
&format!("/accounts/{account_id}/actions/close"),
None::<&Empty>,
)
.await
}
/// Positions held across every account, as of the last market close.
///
/// **Deprecated by Alpaca.** Use
/// [`get_eod_positions`](Self::get_eod_positions), which calls the
/// `/v1/reporting/eod/positions` route Alpaca names as the replacement.
/// No sunset date is published, so this still answers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
#[deprecated(
since = "0.1.0",
note = "Alpaca deprecated this route; use `BrokerClient::get_eod_positions`, which calls the \
/v1/reporting/eod/positions route Alpaca names as its replacement"
)]
pub async fn get_all_accounts_positions(
&self,
page: Option<u32>,
) -> Result<AllAccountsPositions> {
// The only parameter the route takes, and it is not cosmetic: without
// it a caller with more accounts than fit on one page cannot reach the
// rest of them.
match page {
Some(page) => {
self.rest
.get("/accounts/positions", &[("page", page.to_string())])
.await
}
None => self.rest.get("/accounts/positions", &Empty).await,
}
}
// ----------------------------------------------------------- funding
/// Opens an ACH relationship between an account and a bank account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_ach_relationship_for_account(
&self,
account_id: Uuid,
relationship: &CreateACHRelationshipRequest,
) -> Result<ACHRelationship> {
self.rest
.post(
&format!("/accounts/{account_id}/ach_relationships"),
relationship,
)
.await
}
/// Lists an account's ACH relationships, optionally filtered by status.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_ach_relationships_for_account(
&self,
account_id: Uuid,
statuses: &[ACHRelationshipStatus],
) -> Result<Vec<ACHRelationship>> {
let path = format!("/accounts/{account_id}/ach_relationships");
if statuses.is_empty() {
return self.rest.get(&path, &Empty).await;
}
// One comma-separated parameter, not a repeated one.
let statuses = statuses
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",");
self.rest.get(&path, &[("statuses", statuses)]).await
}
/// Deletes an ACH relationship.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn delete_ach_relationship_for_account(
&self,
account_id: Uuid,
ach_relationship_id: Uuid,
) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/accounts/{account_id}/ach_relationships/{ach_relationship_id}"),
None::<&Empty>,
)
.await
}
/// Connects a recipient bank to an account, for wires.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the address fields do not
/// match the bank code type; see [`CreateBankRequest::validate`].
pub async fn create_bank_for_account(
&self,
account_id: Uuid,
bank: &CreateBankRequest,
) -> Result<Bank> {
bank.validate()?;
self.rest
.post(&format!("/accounts/{account_id}/recipient_banks"), bank)
.await
}
/// Lists an account's connected banks.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_banks_for_account(&self, account_id: Uuid) -> Result<Vec<Bank>> {
self.rest
.get(&format!("/accounts/{account_id}/recipient_banks"), &Empty)
.await
}
/// Deletes a bank connection.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn delete_bank_for_account(&self, account_id: Uuid, bank_id: Uuid) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/accounts/{account_id}/recipient_banks/{bank_id}"),
None::<&Empty>,
)
.await
}
/// Moves money into or out of an account.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the amount is not positive.
pub async fn create_transfer_for_account(
&self,
account_id: Uuid,
transfer: &CreateTransferRequest,
) -> Result<Transfer> {
transfer.validate()?;
self.rest
.post(&format!("/accounts/{account_id}/transfers"), transfer)
.await
}
/// Fetches one page of an account's transfers.
///
/// Exactly one request, honouring whatever `limit` and `offset` the filter
/// carries. Use
/// [`get_all_transfers_for_account`](Self::get_all_transfers_for_account) to
/// walk every page.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_transfers_for_account(
&self,
account_id: Uuid,
filter: Option<&GetTransfersRequest>,
) -> Result<Vec<Transfer>> {
let path = format!("/accounts/{account_id}/transfers");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Walks every page of an account's transfers.
///
/// Requests pages until one comes back empty, then returns the lot.
/// `max_items` caps the total across every page, not per page.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_transfers_for_account(
&self,
account_id: Uuid,
filter: Option<&GetTransfersRequest>,
max_items: Option<usize>,
) -> Result<Vec<Transfer>> {
let mut filter = filter.cloned().unwrap_or_default();
let mut collected: Vec<Transfer> = Vec::new();
let mut seen: HashSet<Uuid> = HashSet::new();
// Counts rows the server has handed over, not rows kept. The two differ
// only when a page repeats something already collected, and the offset
// has to keep describing the server's own position rather than ours.
let mut fetched: usize = 0;
loop {
// The offset is the running count on every pass, including the
// first, so a caller-supplied offset is overwritten once the walk
// starts. Honouring it would make the cap mean something different
// on the first page than on the rest.
filter.offset = Some(u32::try_from(fetched).map_err(|_| {
crate::Error::InvalidRequest("too many transfers to page through".to_owned())
})?);
let page: Vec<Transfer> = self
.rest
.get(&format!("/accounts/{account_id}/transfers"), &filter)
.await?;
// An empty page is how this endpoint says it is done; it carries no
// token or total to check instead.
if page.is_empty() {
break;
}
fetched += page.len();
let progressed =
extend_with_new(&mut collected, &mut seen, page, |transfer| transfer.id);
if let Some(max_items) = max_items
&& collected.len() >= max_items
{
collected.truncate(max_items);
break;
}
// A server that ignores `offset` answers every request with the same
// non-empty page, which is not an ending this endpoint can express.
if !progressed {
tracing::warn!(
account_id = %account_id,
"the transfers walk stopped making progress; every transfer \
on the last page had already been seen"
);
break;
}
}
Ok(collected)
}
/// Cancels a transfer that has not yet settled.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn cancel_transfer_for_account(
&self,
account_id: Uuid,
transfer_id: Uuid,
) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/accounts/{account_id}/transfers/{transfer_id}"),
None::<&Empty>,
)
.await
}
// ------------------------------------------------------------ events
/// Streams account status changes as they happen.
///
/// A v1 stream, and current: Alpaca publishes no v2 successor.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_account_status_events(
&self,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.events(EventVersion::V1, "/events/accounts/status", filter)
.await
}
/// Streams trade events as they happen.
///
/// Subscribes to `/v2/events/trades`. The v1 route is documented as "fully
/// deprecated and no longer available", and calling it ships a stream that
/// does not answer.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_trade_events(
&self,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.events(EventVersion::V2, "/events/trades", filter)
.await
}
/// Streams journal status changes as they happen.
///
/// Subscribes to `/v2/events/journals/status`. The v1 stream still exists
/// but is legacy, and Alpaca warns the two are not interchangeable: "there
/// is no compatibility between /v1/events/journals/status and
/// /v2/events/journals/status, the ids (ulid) are always different". A
/// cursor saved from the v1 stream is meaningless here.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_journal_events(
&self,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.events(EventVersion::V2, "/events/journals/status", filter)
.await
}
/// Streams funding status changes as they happen.
///
/// Subscribes to `/v2/events/funding/status`, which supersedes the v1
/// transfer stream. That route is deprecated and open only to broker
/// partners who already had it; new partners cannot use it at all.
///
/// The v2 stream is broader than this method's name suggests: it covers bank
/// relationships, wire banks and funding wallets as well as transfers.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_transfer_events(
&self,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.events(EventVersion::V2, "/events/funding/status", filter)
.await
}
/// Streams non-trading activity events as they happen.
///
/// A v1 stream, and current. Alpaca documents two filters this crate does
/// not expose — `include_preprocessing` and `group_id` — which are unique to
/// this stream.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_non_trading_activity_events(
&self,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.events(EventVersion::V1, "/events/nta", filter).await
}
/// Streams account activity events as they happen.
///
/// A `v2beta1` stream, and the account-activity counterpart to the polled
/// [`get_account_activities`](Self::get_account_activities).
///
/// Takes [`EventStreamRequest`] rather than [`GetEventsRequest`]: this
/// stream bounds its window by timestamp where the older ones use a date.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_activity_events(
&self,
filter: Option<&EventStreamRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.event_stream(EventVersion::V2Beta1, "/events/activities", filter)
.await
}
/// Streams admin actions as they happen.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_admin_action_events(
&self,
filter: Option<&EventStreamRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.event_stream(EventVersion::V2, "/events/admin-actions", filter)
.await
}
/// Streams IPO events as they happen.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_ipo_events(
&self,
filter: Option<&EventStreamRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.event_stream(EventVersion::V2, "/events/ipos", filter)
.await
}
/// Streams system events as they happen.
///
/// # Errors
/// Propagates transport failures and any non-success status the server
/// answers the subscription with.
pub async fn get_system_events(
&self,
filter: Option<&EventStreamRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
self.event_stream(EventVersion::V2, "/events/system", filter)
.await
}
/// Fetches one account activity event by its ULID.
///
/// The way to re-read an event whose id came off
/// [`get_activity_events`](Self::get_activity_events), rather than
/// replaying the stream from a cursor.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_account_activity_event(
&self,
account_id: Uuid,
event_id: &str,
) -> Result<serde_json::Value> {
// Untyped for the same reason the streams are: no captured payload
// exists for this route in any SDK, and inventing a struct from the
// spec alone would claim more than is known.
let path = format!(
"/accounts/{account_id}/events/activities/{}",
segment(event_id)?
);
// Its own version segment, like the stream it pairs with — which is what
// `at_version` is for. It went through the raw client once, and that cost
// it the retry loop, the caller's timeout and the redirect refusal that
// every other route here gets.
self.rest.at_version("v2beta1").get(&path, &Empty).await
}
/// Opens one of the broker's event streams.
///
/// The version comes from the stream rather than from the client's
/// `api_version`: Alpaca versions these endpoints individually, so of the
/// nine, two are v1, six are v2 and one is `v2beta1`.
async fn events(
&self,
version: EventVersion,
path: &str,
filter: Option<&GetEventsRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
let url = format!(
"{}/{}{path}",
self.rest.config().base_url.trim_end_matches('/'),
version.segment()
);
// Rendered per version: the cursor parameter is named differently on
// each, and means something different under the v1 name.
let query = filter
.map(|filter| version.query(filter))
.unwrap_or_default();
crate::sse::subscribe(&self.events, &url, path, &query).await
}
/// Opens one of the timestamp-bounded event streams.
///
/// The four streams the reference sweep found take an RFC-3339 window where
/// the five older ones take a date, so they take a different filter type
/// rather than sharing one that would be wrong half the time.
async fn event_stream(
&self,
version: EventVersion,
path: &str,
filter: Option<&EventStreamRequest>,
) -> Result<impl Stream<Item = Result<BrokerEvent>> + use<>> {
let url = format!(
"{}/{}{path}",
self.rest.config().base_url.trim_end_matches('/'),
version.segment()
);
let query = filter.map(EventStreamRequest::query).unwrap_or_default();
crate::sse::subscribe(&self.events, &url, path, &query).await
}
// ------------------------------------------------- account activities
/// Fetches one page of account activities.
///
/// Unlike the trading API's equivalent, this route spans every account the
/// correspondent serves; filter by `account_id` for one of them. The
/// response mixes trade and non-trade activities, which is why it decodes to
/// [`crate::trading::Activity`].
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the filter combines `category`
/// with `activity_types`.
pub async fn get_account_activities(
&self,
filter: Option<&GetAccountActivitiesRequest>,
) -> Result<Vec<Activity>> {
match filter {
Some(filter) => {
filter.validate()?;
self.rest.get("/accounts/activities", filter).await
}
None => self.rest.get("/accounts/activities", &Empty).await,
}
}
/// Walks every page of account activities.
///
/// This route pages by *cursor*, not by offset or by a server-supplied
/// token: the next page starts after the `id` of the last activity already
/// seen. An empty array ends the walk.
///
/// Setting `date` on the filter changes the endpoint's behaviour — Alpaca
/// may then return everything in one response and ignore paging. The walk
/// stops on the second request in that case: the cursor has no effect, the
/// same activities come back, and a page that repeats what is already
/// collected ends the walk rather than restarting it. `max_items` still
/// holds.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the filter combines `category`
/// with `activity_types`.
pub async fn get_all_account_activities(
&self,
filter: Option<&GetAccountActivitiesRequest>,
max_items: Option<usize>,
) -> Result<Vec<Activity>> {
let mut filter = filter.cloned().unwrap_or_default();
filter.validate()?;
let mut collected: Vec<Activity> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
loop {
if let Some(page_size) = page_limit(&filter.page_size, max_items, collected.len()) {
filter.page_size = Some(page_size);
}
let page: Vec<Activity> = self.rest.get("/accounts/activities", &filter).await?;
let Some(last) = page.last() else {
break;
};
// The cursor is the last activity's id, so it is taken before the
// page is moved into the accumulator.
let cursor = activity_id(last).to_owned();
let progressed = extend_with_new(&mut collected, &mut seen, page, |activity| {
activity_id(activity).to_owned()
});
if let Some(max_items) = max_items
&& collected.len() >= max_items
{
collected.truncate(max_items);
break;
}
if !progressed {
tracing::warn!(
"the account activities walk stopped making progress; every \
activity on the last page had already been seen"
);
break;
}
filter.page_token = Some(cursor);
}
Ok(collected)
}
// ---------------------------------------------------------------- CIP
/// Fetches an account's Customer Identification Program record.
///
/// **Unverified.** No captured response exists for this route — the sandbox
/// is reported to answer 404 for it — so [`CIPInfo`] is derived from the
/// broker spec rather than from a payload. Treat a decode failure on the
/// first real response as expected work, not a regression.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_cip_data_for_account_by_id(&self, account_id: Uuid) -> Result<CIPInfo> {
self.rest
.get(&format!("/accounts/{account_id}/cip"), &Empty)
.await
}
/// Submits an account's Customer Identification Program record.
///
/// **Unverified**, for the same reason as
/// [`get_cip_data_for_account_by_id`](Self::get_cip_data_for_account_by_id).
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn upload_cip_data_for_account_by_id(
&self,
account_id: Uuid,
cip: &CIPInfo,
) -> Result<CIPInfo> {
self.rest
.post(&format!("/accounts/{account_id}/cip"), cip)
.await
}
// --------------------------------------------------------- documents
/// Lists an account's trade documents: statements, confirmations, tax forms.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the filter's date window is
/// the wrong way round.
pub async fn get_trade_documents_for_account(
&self,
account_id: Uuid,
filter: Option<&GetTradeDocumentsRequest>,
) -> Result<Vec<TradeDocument>> {
let path = format!("/accounts/{account_id}/documents");
match filter {
Some(filter) => {
filter.validate()?;
self.rest.get(&path, filter).await
}
None => self.rest.get(&path, &Empty).await,
}
}
/// Fetches one trade document's metadata.
///
/// This is the record, not the file; see
/// [`download_trade_document_for_account_by_id`](Self::download_trade_document_for_account_by_id)
/// for the contents.
///
/// **Undocumented, and possibly not real.** This route appears in neither
/// the `OpenAPI` spec nor the published reference, which list only the
/// collection, the upload and the download; no captured payload exists for
/// it either. It is implemented because other clients call it, and that is
/// the whole of the evidence. Prefer
/// [`get_trade_documents_for_account`](Self::get_trade_documents_for_account)
/// and filter, and treat a 404 here as the route not existing rather than
/// the document not existing. See `COVERAGE.md`.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_trade_document_for_account_by_id(
&self,
account_id: Uuid,
document_id: Uuid,
) -> Result<TradeDocument> {
self.rest
.get(
&format!("/accounts/{account_id}/documents/{document_id}"),
&Empty,
)
.await
}
/// Downloads a trade document's contents.
///
/// This route answers `301` with a presigned storage URL rather than the
/// file, so it cannot go through [`RestClient`], which refuses redirects on
/// purpose. It uses a second client that follows them and sheds the broker
/// credentials on the way — a presigned URL carries its own authorisation
/// and has no business seeing an API key.
///
/// The bytes are returned rather than written, so the caller decides where
/// they go — a document small enough to hold in memory is the common case,
/// and streaming to a path is a policy this crate has no business setting.
///
/// # Errors
/// Propagates transport and API failures. Retries follow the client's retry
/// configuration, as every other route does.
pub async fn download_trade_document_for_account_by_id(
&self,
account_id: Uuid,
document_id: Uuid,
) -> Result<Vec<u8>> {
let path = format!("/accounts/{account_id}/documents/{document_id}/download");
self.download(&path).await
}
/// Fetches a route that answers `301` to a presigned storage URL.
///
/// Two routes do: the trade document download and the W-8BEN download.
/// Neither can go through [`RestClient`], which refuses redirects on
/// purpose, so both use the `plain` client, which follows them. What keeps
/// the credentials off the storage provider is not that client but their
/// *form*: `with_config` converts them to basic auth, and reqwest strips
/// `Authorization` on a cross-host hop.
///
/// The retry policy is the client's own — same status set, same backoff
/// curve, same `Retry-After` handling — so these behave like every other
/// route under a 429 or a 5xx.
async fn download(&self, path: &str) -> Result<Vec<u8>> {
let config = self.rest.config();
let url = format!(
"{}/{}{path}",
config.base_url.trim_end_matches('/'),
config.api_version
);
let retry = &config.retry;
// Saturating because `attempts` is a caller-supplied `u32`: `u32::MAX`
// would overflow, panicking in debug and wrapping to a zero-iteration
// loop in release.
let total_attempts = retry.attempts.saturating_add(1);
for attempt in 1..=total_attempts {
let response = self
.plain
.get(&url)
.send()
.await
.map_err(crate::Error::transport)?;
let status = response.status().as_u16();
if response.status().is_success() {
return Ok(response
.bytes()
.await
.map_err(crate::Error::transport)?
.to_vec());
}
// Read before the body: `text()` consumes the response, headers
// and all.
let retry_after = crate::rest::retry_after(response.headers());
let body = response.text().await.unwrap_or_default();
let api_error = crate::error::ApiError::from_body(status, path, body);
if !retry.should_retry(status) {
return Err(crate::Error::Api(api_error));
}
if attempt == total_attempts {
return Err(crate::Error::RetriesExhausted {
attempts: total_attempts,
last: api_error,
});
}
// The same delay policy `RestClient` uses, rather than a flat wait
// that ignores both the backoff curve and the server's own answer.
// This loop is hand-rolled only because the response body is bytes;
// there is no reason for it to retry differently.
let delay = retry_after.map_or_else(
|| retry.delay(attempt),
|after| after.min(retry.retry_after_cap()),
);
tokio::time::sleep(delay).await;
}
unreachable!("retry loop exited without returning")
}
/// Uploads documents to an account.
///
/// Contents are base64-encoded, and capped at 10MB each when Alpaca does
/// the KYC. The route answers `204`, so a success returns nothing.
///
/// [`DOCUMENT_UPLOAD_LIMIT`] is a conventional ceiling on how many documents
/// go in one call. It is not in the reference or the spec, and it is not
/// enforced here: it may well be real, but rejecting a request Alpaca would
/// have accepted is the worse of the two failures, and the server's answer
/// says more than a guess of ours would.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if any document fails
/// [`UploadDocument::validate`].
pub async fn upload_documents_to_account(
&self,
account_id: Uuid,
documents: &[UploadDocument],
) -> Result<()> {
for document in documents {
document.validate()?;
}
self.send_void(
Method::POST,
&format!("/accounts/{account_id}/documents/upload"),
Some(documents),
)
.await
}
// ------------------------------------------------------- rebalancing
/// Creates a portfolio accounts can be rebalanced towards.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if any weight is not positive
/// or an asset weight names no symbol.
pub async fn create_portfolio(&self, portfolio: &CreatePortfolioRequest) -> Result<Portfolio> {
portfolio.validate()?;
self.rest.post("/rebalancing/portfolios", portfolio).await
}
/// Lists portfolios, optionally filtered.
///
/// This route answers with a bare array — unlike subscriptions and runs, it
/// does not paginate.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_portfolios(
&self,
filter: Option<&GetPortfoliosRequest>,
) -> Result<Vec<Portfolio>> {
match filter {
Some(filter) => self.rest.get("/rebalancing/portfolios", filter).await,
None => self.rest.get("/rebalancing/portfolios", &Empty).await,
}
}
/// Fetches one portfolio.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_portfolio_by_id(&self, portfolio_id: Uuid) -> Result<Portfolio> {
self.rest
.get(&format!("/rebalancing/portfolios/{portfolio_id}"), &Empty)
.await
}
/// Changes a portfolio.
///
/// Changing the weights or the conditions re-evaluates every subscribed
/// account at the next opportunity, subject to the cooldown.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if any weight the update sets is
/// not positive or an asset weight names no symbol.
pub async fn update_portfolio_by_id(
&self,
portfolio_id: Uuid,
update: &UpdatePortfolioRequest,
) -> Result<Portfolio> {
update.validate()?;
self.rest
.patch(&format!("/rebalancing/portfolios/{portfolio_id}"), update)
.await
}
/// Retires a portfolio.
///
/// Permitted only when nothing subscribes to it and no active portfolio
/// lists it as a weight. The record survives; it just stops being usable.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn inactivate_portfolio_by_id(&self, portfolio_id: Uuid) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/rebalancing/portfolios/{portfolio_id}"),
None::<&Empty>,
)
.await
}
/// Subscribes an account to a portfolio.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_subscription(
&self,
subscription: &CreateSubscriptionRequest,
) -> Result<Subscription> {
self.rest
.post("/rebalancing/subscriptions", subscription)
.await
}
/// Fetches one page of subscriptions.
///
/// The page carries the token for the next one; see
/// [`get_all_subscriptions`](Self::get_all_subscriptions) to walk them all.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_subscriptions(
&self,
filter: Option<&GetSubscriptionsRequest>,
) -> Result<SubscriptionsPage> {
match filter {
Some(filter) => self.rest.get("/rebalancing/subscriptions", filter).await,
None => self.rest.get("/rebalancing/subscriptions", &Empty).await,
}
}
/// Walks every page of subscriptions.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_subscriptions(
&self,
filter: Option<&GetSubscriptionsRequest>,
max_items: Option<usize>,
) -> Result<Vec<Subscription>> {
let mut filter = filter.cloned().unwrap_or_default();
let mut collected: Vec<Subscription> = Vec::new();
let mut seen: HashSet<Uuid> = HashSet::new();
loop {
if let Some(limit) = page_limit(&filter.limit, max_items, collected.len()) {
filter.limit = Some(limit);
}
let page: SubscriptionsPage =
self.rest.get("/rebalancing/subscriptions", &filter).await?;
if page.subscriptions.is_empty() {
break;
}
let progressed = extend_with_new(
&mut collected,
&mut seen,
page.subscriptions,
|subscription| subscription.id,
);
if let Some(max_items) = max_items
&& collected.len() >= max_items
{
collected.truncate(max_items);
break;
}
// A server echoing a token it has already sent would otherwise page
// in a circle; the token itself cannot be trusted to advance.
if !progressed {
tracing::warn!(
"the subscriptions walk stopped making progress; every \
subscription on the last page had already been seen"
);
break;
}
// No token means this was the last page.
match page.next_page_token {
Some(token) => filter.page_token = Some(token),
None => break,
}
}
Ok(collected)
}
/// Fetches one subscription.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_subscription_by_id(&self, subscription_id: Uuid) -> Result<Subscription> {
self.rest
.get(
&format!("/rebalancing/subscriptions/{subscription_id}"),
&Empty,
)
.await
}
/// Ends a subscription, stopping the account's rebalancing.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn unsubscribe_account(&self, subscription_id: Uuid) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/rebalancing/subscriptions/{subscription_id}"),
None::<&Empty>,
)
.await
}
/// Starts a rebalancing run by hand.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if any weight is not positive
/// or an asset weight names no symbol.
pub async fn create_manual_run(&self, run: &CreateRunRequest) -> Result<RebalancingRun> {
run.validate()?;
self.rest.post("/rebalancing/runs", run).await
}
/// Fetches one page of rebalancing runs.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_runs(&self, filter: Option<&GetRunsRequest>) -> Result<RunsPage> {
match filter {
Some(filter) => self.rest.get("/rebalancing/runs", filter).await,
None => self.rest.get("/rebalancing/runs", &Empty).await,
}
}
/// Walks every page of rebalancing runs.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_runs(
&self,
filter: Option<&GetRunsRequest>,
max_items: Option<usize>,
) -> Result<Vec<RebalancingRun>> {
let mut filter = filter.cloned().unwrap_or_default();
let mut collected: Vec<RebalancingRun> = Vec::new();
let mut seen: HashSet<Uuid> = HashSet::new();
loop {
if let Some(limit) = page_limit(&filter.limit, max_items, collected.len()) {
filter.limit = Some(limit);
}
let page: RunsPage = self.rest.get("/rebalancing/runs", &filter).await?;
if page.runs.is_empty() {
break;
}
let progressed = extend_with_new(&mut collected, &mut seen, page.runs, |run| run.id);
if let Some(max_items) = max_items
&& collected.len() >= max_items
{
collected.truncate(max_items);
break;
}
// As with subscriptions: an echoed token cannot end the walk on its
// own, so progress is measured in new runs.
if !progressed {
tracing::warn!(
"the rebalancing runs walk stopped making progress; every \
run on the last page had already been seen"
);
break;
}
match page.next_page_token {
Some(token) => filter.page_token = Some(token),
None => break,
}
}
Ok(collected)
}
/// Fetches one rebalancing run.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_run_by_id(&self, run_id: Uuid) -> Result<RebalancingRun> {
self.rest
.get(&format!("/rebalancing/runs/{run_id}"), &Empty)
.await
}
/// Cancels a rebalancing run.
///
/// Only queued and in-progress runs can be cancelled, and any orders already
/// submitted are cancelled on a best-effort basis.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn cancel_run_by_id(&self, run_id: Uuid) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/rebalancing/runs/{run_id}"),
None::<&Empty>,
)
.await
}
// ---------------------------------------------------------- journals
/// Opens a journal between two accounts.
///
/// Journals are not account-scoped: both accounts are named in the body, so
/// the route sits at the top level.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the fields set do not match
/// the entry type; see [`CreateJournalRequest::validate`].
pub async fn create_journal(&self, journal: &CreateJournalRequest) -> Result<Journal> {
journal.validate()?;
self.rest.post("/journals", journal).await
}
/// Moves cash out of one account into many.
///
/// Each entry succeeds or fails on its own: the response carries one record
/// per entry, and a failed one explains itself in
/// [`error_message`](BatchJournalResponse::error_message) rather than
/// failing the request.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_batch_journal(
&self,
batch: &CreateBatchJournalRequest,
) -> Result<Vec<BatchJournalResponse>> {
self.rest.post("/journals/batch", batch).await
}
/// Moves cash into one account out of many.
///
/// Per-entry outcomes work as they do for
/// [`create_batch_journal`](Self::create_batch_journal).
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_reverse_batch_journal(
&self,
batch: &CreateReverseBatchJournalRequest,
) -> Result<Vec<BatchJournalResponse>> {
self.rest.post("/journals/reverse_batch", batch).await
}
/// Lists journals, optionally filtered.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_journals(&self, filter: Option<&GetJournalsRequest>) -> Result<Vec<Journal>> {
match filter {
Some(filter) => self.rest.get("/journals", filter).await,
None => self.rest.get("/journals", &Empty).await,
}
}
/// Fetches one journal.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_journal_by_id(&self, journal_id: Uuid) -> Result<Journal> {
self.rest
.get(&format!("/journals/{journal_id}"), &Empty)
.await
}
/// Cancels a journal that has not yet executed.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn cancel_journal_by_id(&self, journal_id: Uuid) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/journals/{journal_id}"),
None::<&Empty>,
)
.await
}
// ------------------------------------------- trading on behalf of an account
/// The trading view of an account: buying power, cash, equity.
///
/// This is the same record [`crate::trading::TradingClient::get_account`]
/// returns, for an account the broker acts on behalf of.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_trade_account_by_id(&self, account_id: Uuid) -> Result<TradeAccount> {
self.rest
.get(&format!("/trading/accounts/{account_id}/account"), &Empty)
.await
}
/// An account's trading configuration.
///
/// **Undocumented.** Alpaca documents the `PATCH` on this path but no `GET`,
/// in neither the spec nor the reference. It is implemented anyway because a
/// captured payload proves it answers — which is stronger evidence than the
/// documentation's silence is against it. See `COVERAGE.md`.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_trade_configuration_for_account(
&self,
account_id: Uuid,
) -> Result<crate::trading::AccountConfiguration> {
self.rest
.get(
&format!("/trading/accounts/{account_id}/account/configurations"),
&Empty,
)
.await
}
/// Positions held by one account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_positions_for_account(&self, account_id: Uuid) -> Result<Vec<Position>> {
self.rest
.get(&format!("/trading/accounts/{account_id}/positions"), &Empty)
.await
}
/// One account's position in a single asset.
///
/// # Errors
/// Returns an API error if the account holds no position in the asset.
pub async fn get_open_position_for_account(
&self,
account_id: Uuid,
asset: &crate::types::AssetIdent,
) -> Result<Position> {
self.rest
.get(
&format!(
"/trading/accounts/{account_id}/positions/{}",
asset.as_path_segment()?
),
&Empty,
)
.await
}
/// Liquidates every position held by one account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn close_all_positions_for_account(
&self,
account_id: Uuid,
cancel_orders: Option<bool>,
) -> Result<Vec<crate::trading::ClosePositionResponse>> {
let path = format!("/trading/accounts/{account_id}/positions");
match cancel_orders {
Some(cancel) => {
self.rest
.delete_effectful(&path, &[("cancel_orders", cancel)])
.await
}
None => self.rest.delete_effectful(&path, &Empty).await,
}
}
/// Liquidates one position held by an account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn close_position_for_account(
&self,
account_id: Uuid,
asset: &crate::types::AssetIdent,
close: Option<&crate::trading::ClosePositionRequest>,
) -> Result<Order> {
let path = format!(
"/trading/accounts/{account_id}/positions/{}",
asset.as_path_segment()?
);
match close {
Some(close) => self.rest.delete_effectful(&path, &close.to_query()).await,
None => self.rest.delete_effectful(&path, &Empty).await,
}
}
/// Exercises an option contract held by an account.
///
/// Every held share of the contract is exercised; Alpaca offers no partial
/// exercise. Requests submitted outside market hours are rejected.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn exercise_options_position_for_account_by_id(
&self,
account_id: Uuid,
contract: &crate::types::AssetIdent,
exercise: &CreateOptionExerciseRequest,
) -> Result<()> {
self.send_void(
Method::POST,
&format!(
"/trading/accounts/{account_id}/positions/{}/exercise",
contract.as_path_segment()?
),
Some(exercise),
)
.await
}
// ------------------------------------------------------------- orders
/// Submits an order on behalf of an account.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the order fails
/// [`crate::trading::OrderRequest::validate`], or an API error if Alpaca
/// rejects it.
pub async fn submit_order_for_account(
&self,
account_id: Uuid,
order: &OrderRequest,
) -> Result<Order> {
order.validate()?;
self.rest
.post(&format!("/trading/accounts/{account_id}/orders"), order)
.await
}
/// Lists an account's orders, optionally filtered.
///
/// **One page.** Alpaca returns 50 orders by default and at most 500, and
/// this sends exactly what it is given — so an account with more history
/// than that gets a silently truncated list rather than an error. Use
/// [`get_all_orders_for_account`](Self::get_all_orders_for_account) to walk
/// the whole history.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_orders_for_account(
&self,
account_id: Uuid,
filter: Option<&crate::trading::GetOrdersRequest>,
) -> Result<Vec<Order>> {
let path = format!("/trading/accounts/{account_id}/orders");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Every order on an account matching `filter`, following the cursor across
/// pages.
///
/// The broker route takes the same request type and the same 500-order page
/// cap as the trading one, so it needs the same walk — a correspondent
/// reconciling an account's history hits the identical silent truncation
/// otherwise. See
/// [`TradingClient::get_all_orders`](crate::trading::TradingClient::get_all_orders)
/// for how the cursor works and which two filter fields it overrides.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_orders_for_account(
&self,
account_id: Uuid,
filter: Option<&crate::trading::GetOrdersRequest>,
max_items: Option<usize>,
) -> Result<Vec<Order>> {
let path = format!("/trading/accounts/{account_id}/orders");
let mut request = filter.cloned().unwrap_or_default();
request.limit = Some(crate::config::ORDERS_MAX_LIMIT);
request.direction = Some(crate::types::Sort::Desc);
crate::trading::client::walk_orders(
&self.rest,
&path,
request,
max_items,
|order: &Order| order.order.id,
)
.await
}
/// Fetches one of an account's orders by its Alpaca id.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_order_for_account_by_id(
&self,
account_id: Uuid,
order_id: Uuid,
filter: Option<&crate::trading::GetOrderByIdRequest>,
) -> Result<Order> {
let path = format!("/trading/accounts/{account_id}/orders/{order_id}");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Fetches one of an account's orders by the client order id it was
/// submitted with.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_order_for_account_by_client_id(
&self,
account_id: Uuid,
client_order_id: &str,
) -> Result<Order> {
self.rest
.get(
&format!("/trading/accounts/{account_id}/orders:by_client_order_id"),
&[("client_order_id", client_order_id)],
)
.await
}
/// Replaces one of an account's open orders, returning the new order.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the replacement fails
/// [`crate::trading::ReplaceOrderRequest::validate`], or an API error if
/// Alpaca rejects it.
pub async fn replace_order_for_account_by_id(
&self,
account_id: Uuid,
order_id: Uuid,
replacement: Option<&crate::trading::ReplaceOrderRequest>,
) -> Result<Order> {
let path = format!("/trading/accounts/{account_id}/orders/{order_id}");
match replacement {
Some(replacement) => {
replacement.validate()?;
self.rest.patch(&path, replacement).await
}
None => self.rest.patch(&path, &Empty).await,
}
}
/// Cancels every open order for an account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn cancel_orders_for_account(
&self,
account_id: Uuid,
) -> Result<Vec<crate::trading::CancelOrderResponse>> {
self.rest
.delete(&format!("/trading/accounts/{account_id}/orders"), &Empty)
.await
}
/// Cancels one of an account's open orders.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn cancel_order_for_account_by_id(
&self,
account_id: Uuid,
order_id: Uuid,
) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/trading/accounts/{account_id}/orders/{order_id}"),
None::<&Empty>,
)
.await
}
/// The account's value over time.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_portfolio_history_for_account(
&self,
account_id: Uuid,
filter: Option<&crate::trading::GetPortfolioHistoryRequest>,
) -> Result<crate::trading::PortfolioHistory> {
let path = format!("/trading/accounts/{account_id}/account/portfolio/history");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Updates an account's trading configuration.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn update_trade_configuration_for_account(
&self,
account_id: Uuid,
configuration: &crate::trading::AccountConfiguration,
) -> Result<crate::trading::AccountConfiguration> {
self.rest
.patch(
&format!("/trading/accounts/{account_id}/account/configurations"),
configuration,
)
.await
}
// -------------------------------------------------------- watchlists
/// Lists an account's watchlists.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_watchlists_for_account(&self, account_id: Uuid) -> Result<Vec<Watchlist>> {
self.rest
.get(
&format!("/trading/accounts/{account_id}/watchlists"),
&Empty,
)
.await
}
/// Fetches one of an account's watchlists.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_watchlist_for_account_by_id(
&self,
account_id: Uuid,
watchlist_id: Uuid,
) -> Result<Watchlist> {
self.rest
.get(
&format!("/trading/accounts/{account_id}/watchlists/{watchlist_id}"),
&Empty,
)
.await
}
/// Creates a watchlist for an account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_watchlist_for_account(
&self,
account_id: Uuid,
watchlist: &crate::trading::CreateWatchlistRequest,
) -> Result<Watchlist> {
self.rest
.post(
&format!("/trading/accounts/{account_id}/watchlists"),
watchlist,
)
.await
}
/// Replaces a watchlist's name and symbols.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if neither field is set.
pub async fn update_watchlist_for_account_by_id(
&self,
account_id: Uuid,
watchlist_id: Uuid,
update: &crate::trading::UpdateWatchlistRequest,
) -> Result<Watchlist> {
update.validate()?;
self.rest
.put(
&format!("/trading/accounts/{account_id}/watchlists/{watchlist_id}"),
update,
)
.await
}
/// Adds one asset to an account's watchlist.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn add_asset_to_watchlist_for_account_by_id(
&self,
account_id: Uuid,
watchlist_id: Uuid,
symbol: &str,
) -> Result<Watchlist> {
self.rest
.post(
&format!("/trading/accounts/{account_id}/watchlists/{watchlist_id}"),
&serde_json::json!({ "symbol": symbol }),
)
.await
}
/// Removes one asset from an account's watchlist.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn remove_asset_from_watchlist_for_account_by_id(
&self,
account_id: Uuid,
watchlist_id: Uuid,
symbol: &str,
) -> Result<Watchlist> {
self.rest
.delete(
&format!(
"/trading/accounts/{account_id}/watchlists/{watchlist_id}/{}",
segment(symbol)?
),
&Empty,
)
.await
}
/// Deletes one of an account's watchlists. This is permanent.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn delete_watchlist_from_account_by_id(
&self,
account_id: Uuid,
watchlist_id: Uuid,
) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/trading/accounts/{account_id}/watchlists/{watchlist_id}"),
None::<&Empty>,
)
.await
}
// ------------------------------------------------------------- assets
/// Lists tradable assets, optionally filtered.
///
/// This route is not account-scoped: the asset master is the same for every
/// account the broker serves.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_all_assets(
&self,
filter: Option<&crate::trading::GetAssetsRequest>,
) -> Result<Vec<crate::trading::Asset>> {
match filter {
Some(filter) => self.rest.get("/assets", filter).await,
None => self.rest.get("/assets", &Empty).await,
}
}
/// Fetches one asset by symbol or id.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_asset(
&self,
asset: &crate::types::AssetIdent,
) -> Result<crate::trading::Asset> {
self.rest
.get(&format!("/assets/{}", asset.as_path_segment()?), &Empty)
.await
}
// ---------------------------------------------- corporate announcements
/// Searches corporate action announcements.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the date window exceeds 90
/// days, or an API error if Alpaca rejects the request.
#[deprecated(
since = "0.1.0",
note = "Alpaca deprecated this route; use `CorporateActionsClient::get_corporate_actions` \
(the /v1/corporate-actions market data route) instead. No sunset date is published"
)]
pub async fn get_corporate_announcements(
&self,
filter: &crate::trading::GetCorporateAnnouncementsRequest,
) -> Result<Vec<crate::trading::CorporateActionAnnouncement>> {
filter.validate()?;
self.rest
.get("/corporate_actions/announcements", &filter.to_query())
.await
}
/// Fetches one corporate action announcement.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
#[deprecated(
since = "0.1.0",
note = "Alpaca deprecated this route; use `CorporateActionsClient::get_corporate_actions` \
(the /v1/corporate-actions market data route) instead. No sunset date is published"
)]
pub async fn get_corporate_announcement_by_id(
&self,
announcement_id: Uuid,
) -> Result<crate::trading::CorporateActionAnnouncement> {
self.rest
.get(
&format!("/corporate_actions/announcements/{announcement_id}"),
&Empty,
)
.await
}
// ------------------------------------------------------ market status
/// The broker API's market clock.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_clock(&self) -> Result<crate::trading::Clock> {
self.rest.get("/clock", &Empty).await
}
/// The broker API's market calendar.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_calendar(
&self,
filter: Option<&crate::trading::GetCalendarRequest>,
) -> Result<Vec<crate::trading::Calendar>> {
match filter {
Some(filter) => self.rest.get("/calendar", filter).await,
None => self.rest.get("/calendar", &Empty).await,
}
}
/// A named market's calendar.
///
/// **A `v2` route**, where the trading API's equivalent is `v3`. The models
/// are shared with
/// [`TradingClient::get_market_calendar`](crate::trading::TradingClient::get_market_calendar);
/// the version is not.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_market_calendar(
&self,
market: &crate::trading::Market,
filter: Option<&crate::trading::GetMarketCalendarRequest>,
) -> Result<crate::trading::MarketCalendar> {
let path = format!("/calendar/{}", segment(market)?);
match filter {
Some(filter) => self.rest.at_version("v2").get(&path, filter).await,
None => self.rest.at_version("v2").get(&path, &Empty).await,
}
}
/// A company logo, as PNG bytes.
///
/// **A `v1beta1` route.** Unverified: a data plan that reaches SIP still
/// answers `403 Subscription does not permit querying logos`.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn get_logo(
&self,
symbol: &str,
request: &crate::types::LogoRequest,
) -> Result<Vec<u8>> {
let path = format!("/logos/{}", segment(symbol)?);
self.rest
.at_version("v1beta1")
.get_bytes(&path, request)
.await
}
// ---------------------------------------------- activities by type
/// Account activities of one type, across every account.
///
/// The narrowed counterpart to
/// [`get_account_activities`](Self::get_account_activities): the type moves
/// from the query string into the path, so `activity_types` has nothing
/// left to say here.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the filter combines
/// `activity_types` with `category`. Otherwise propagates transport, API,
/// and decoding failures.
pub async fn get_account_activities_by_type(
&self,
activity_type: &crate::trading::ActivityType,
filter: Option<&GetAccountActivitiesRequest>,
) -> Result<Vec<Activity>> {
let path = format!("/accounts/activities/{}", segment(activity_type)?);
match filter {
Some(filter) => {
filter.validate()?;
self.rest.get(&path, filter).await
}
None => self.rest.get(&path, &Empty).await,
}
}
// --------------------------------------------------- fixed income
/// The US corporate bond master list.
///
/// One of the few spec-derived broker routes with a real captured payload
/// behind it, harvested from the Go SDK's tests: see `fixtures/go/`.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_us_corporates(
&self,
filter: Option<&GetUsCorporatesRequest>,
) -> Result<UsCorporates> {
match filter {
Some(filter) => {
self.rest
.get("/assets/fixed_income/us_corporates", filter)
.await
}
None => {
self.rest
.get("/assets/fixed_income/us_corporates", &Empty)
.await
}
}
}
/// The US treasury master list.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_us_treasuries(
&self,
filter: Option<&GetUsTreasuriesRequest>,
) -> Result<UsTreasuries> {
match filter {
Some(filter) => {
self.rest
.get("/assets/fixed_income/us_treasuries", filter)
.await
}
None => {
self.rest
.get("/assets/fixed_income/us_treasuries", &Empty)
.await
}
}
}
/// What Regulation T requires to hold the named symbols.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_entry_requirements(
&self,
request: &GetEntryRequirementsRequest,
) -> Result<Vec<EntryRequirement>> {
self.rest.get("/assets/entry-requirements", request).await
}
// ------------------------------------------------- instant funding
/// Lists instant funding advances.
///
/// Pages by offset, unlike the token-paginated broker routes.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding(
&self,
filter: Option<&GetInstantFundingRequest>,
) -> Result<Vec<InstantFunding>> {
match filter {
Some(filter) => self.rest.get("/instant_funding", filter).await,
None => self.rest.get("/instant_funding", &Empty).await,
}
}
/// Advances cash against a deposit that has not cleared.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the amount is not positive.
pub async fn create_instant_funding(
&self,
request: &CreateInstantFundingRequest,
) -> Result<InstantFunding> {
request.validate()?;
self.rest.post("/instant_funding", request).await
}
/// Fetches one advance.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_by_id(&self, funding_id: &str) -> Result<InstantFunding> {
self.rest
.get(
&format!("/instant_funding/{}", segment(funding_id)?),
&Empty,
)
.await
}
/// Cancels an advance.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn cancel_instant_funding(&self, funding_id: &str) -> Result<()> {
self.send_void(
Method::DELETE,
&format!("/instant_funding/{}", segment(funding_id)?),
None::<&Empty>,
)
.await
}
/// How much instant funding the correspondent may have outstanding.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_limits(&self) -> Result<InstantFundingLimits> {
self.rest.get("/instant_funding/limits", &Empty).await
}
/// The named accounts' shares of that limit.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_account_limits(
&self,
request: &GetAccountLimitsRequest,
) -> Result<Vec<AccountInstantFundingLimits>> {
self.rest
.get("/instant_funding/limits/accounts", request)
.await
}
/// A day's instant funding position, by account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_reports(
&self,
filter: Option<&GetInstantFundingReportRequest>,
) -> Result<Vec<InstantFundingReport>> {
match filter {
Some(filter) => self.rest.get("/instant_funding/reports", filter).await,
None => self.rest.get("/instant_funding/reports", &Empty).await,
}
}
/// Lists instant funding settlements.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_settlements(
&self,
filter: Option<&GetSettlementsRequest>,
) -> Result<Settlements> {
match filter {
Some(filter) => self.rest.get("/instant_funding/settlements", filter).await,
None => self.rest.get("/instant_funding/settlements", &Empty).await,
}
}
/// Settles one or more advances.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if no transfers are named.
pub async fn create_instant_funding_settlement(
&self,
request: &CreateInstantFundingSettlementRequest,
) -> Result<Settlement> {
request.validate()?;
self.rest
.post("/instant_funding/settlements", request)
.await
}
/// Fetches one instant funding settlement.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_instant_funding_settlement(&self, settlement_id: Uuid) -> Result<Settlement> {
self.rest
.get(
&format!("/instant_funding/settlements/{settlement_id}"),
&Empty,
)
.await
}
// --------------------------------------------------------- JIT
/// The correspondent's JIT ledgers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_ledgers(&self) -> Result<Vec<JitLedger>> {
self.rest.get("/transfers/jit/ledgers", &Empty).await
}
/// One ledger's balances over a window, and the movements behind them.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_ledger_balances(
&self,
ledger_id: &str,
filter: Option<&GetJitBalancesRequest>,
) -> Result<JitLedgerBalances> {
let path = format!("/transfers/jit/{}/balances", segment(ledger_id)?);
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// The correspondent's trading limits for the day.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_trading_limits(&self) -> Result<JitTradingLimits> {
self.rest.get("/transfers/jit/limits", &Empty).await
}
/// A JIT report, inline or as a link.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_report(&self, request: &GetJitReportRequest) -> Result<JitReport> {
self.rest.get("/transfers/jit/reports", request).await
}
/// Lists JIT settlements.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_settlements(
&self,
filter: Option<&GetSettlementsRequest>,
) -> Result<Settlements> {
match filter {
Some(filter) => self.rest.get("/jit/settlements", filter).await,
None => self.rest.get("/jit/settlements", &Empty).await,
}
}
/// Settles a day's JIT obligation.
///
/// **Documented by the spec and not by the reference**, which is the same
/// footing as the other routes this crate calls on the spec's word alone.
/// It is implemented rather than left out — undocumented is not absent —
/// but a live sandbox is what would confirm it.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the settlement names no
/// accounts or a non-positive amount.
pub async fn create_jit_settlement(
&self,
request: &CreateJitSettlementRequest,
) -> Result<Settlement> {
request.validate()?;
self.rest.post("/jit/settlements", request).await
}
/// Fetches one JIT settlement.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_jit_settlement(&self, settlement_id: Uuid) -> Result<Settlement> {
self.rest
.get(&format!("/jit/settlements/{settlement_id}"), &Empty)
.await
}
// -------------------------------------------------------- FPSL
/// Lists fully-paid securities lending loans.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_fpsl_loans(
&self,
filter: Option<&GetFpslLoansRequest>,
) -> Result<FpslLoansPage> {
match filter {
Some(filter) => self.rest.get("/fpsl/loans", filter).await,
None => self.rest.get("/fpsl/loans", &Empty).await,
}
}
/// The revenue-split tiers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_fpsl_tiers(&self) -> Result<Vec<FpslTier>> {
self.rest.get("/fpsl/tiers", &Empty).await
}
/// One account's lending activity over a window.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_fpsl_analytics(
&self,
account_id: Uuid,
filter: Option<&GetFpslAnalyticsRequest>,
) -> Result<FpslAnalytics> {
let path = format!("/fpsl/analytics/{account_id}/loans");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
// -------------------------------------------------------- IPOs
/// Lists IPO offerings.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_ipo_offerings(
&self,
filter: Option<&GetIpoOfferingsRequest>,
) -> Result<IpoOfferingsPage> {
match filter {
Some(filter) => self.rest.get("/ipos", filter).await,
None => self.rest.get("/ipos", &Empty).await,
}
}
/// Fetches one offering.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_ipo_offering(&self, offering_reference: &str) -> Result<IpoOfferingResponse> {
self.rest
.get(&format!("/ipos/{}", segment(offering_reference)?), &Empty)
.await
}
// --------------------------------------------------- reporting
/// Positions across accounts as of one close.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_eod_positions(
&self,
filter: Option<&GetEodPositionsRequest>,
) -> Result<EodPositions> {
match filter {
Some(filter) => self.rest.get("/reporting/eod/positions", filter).await,
None => self.rest.get("/reporting/eod/positions", &Empty).await,
}
}
/// The same positions summed by symbol.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_aggregate_positions(
&self,
request: &GetAggregatePositionsRequest,
) -> Result<Vec<AggregatePosition>> {
self.rest
.get("/reporting/eod/aggregate_positions", request)
.await
}
/// What each account earned on its idle cash.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_eod_cash_interest(
&self,
filter: Option<&GetCashInterestRequest>,
) -> Result<CashInterestReport> {
match filter {
Some(filter) => self.rest.get("/reporting/eod/cash_interest", filter).await,
None => self.rest.get("/reporting/eod/cash_interest", &Empty).await,
}
}
/// The cash interest rate tiers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_apr_tiers(&self) -> Result<AprTiers> {
self.rest.get("/cash_interest/apr_tiers", &Empty).await
}
// ------------------------------------------------------- OAuth
/// Looks up a registered third-party application.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_oauth_client(
&self,
client_id: Uuid,
filter: Option<&GetOAuthClientRequest>,
) -> Result<OAuthClient> {
let path = format!("/oauth/clients/{client_id}");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Authorizes an application against an account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn authorize_oauth(&self, request: &OAuthRequest) -> Result<OAuthCode> {
self.rest.post("/oauth/authorize", request).await
}
/// Issues a bearer token.
///
/// Takes a JSON body, not the form encoding OAuth token endpoints
/// conventionally use. See [`crate::broker::oauth`].
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn issue_oauth_token(&self, request: &OAuthRequest) -> Result<OAuthToken> {
self.rest.post("/oauth/token", request).await
}
// ---------------------------------------------- funding wallets
/// Opens funding wallets for several accounts at once.
///
/// **A `v1beta` route**, like every other funding wallet route.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn batch_create_funding_wallets(
&self,
request: &BatchCreateFundingWalletsRequest,
) -> Result<FundingWallets> {
self.rest
.at_version("v1beta")
.post("/accounts/funding_wallet", request)
.await
}
/// An account's funding wallet.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_funding_wallet(&self, account_id: Uuid) -> Result<FundingWallet> {
let path = format!("/accounts/{account_id}/funding_wallet");
self.rest.at_version("v1beta").get(&path, &Empty).await
}
/// Opens an account's funding wallet.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_funding_wallet(&self, account_id: Uuid) -> Result<FundingWallet> {
let path = format!("/accounts/{account_id}/funding_wallet");
self.rest.at_version("v1beta").post(&path, &Empty).await
}
/// The banking details money should be sent to.
///
/// Returned untyped: the reference documents no response schema for this
/// route at all, and inventing one would claim more than is known.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_funding_details(
&self,
account_id: Uuid,
filter: Option<&GetFundingDetailsRequest>,
) -> Result<serde_json::Value> {
let path = format!("/accounts/{account_id}/funding_wallet/funding_details");
match filter {
Some(filter) => self.rest.at_version("v1beta").get(&path, filter).await,
None => self.rest.at_version("v1beta").get(&path, &Empty).await,
}
}
/// The bank withdrawals are sent to.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_recipient_bank(&self, account_id: Uuid) -> Result<RecipientBank> {
let path = format!("/accounts/{account_id}/funding_wallet/recipient_bank");
self.rest.at_version("v1beta").get(&path, &Empty).await
}
/// Registers the bank withdrawals are sent to.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_recipient_bank(
&self,
account_id: Uuid,
request: &CreateRecipientBankRequest,
) -> Result<RecipientBank> {
let path = format!("/accounts/{account_id}/funding_wallet/recipient_bank");
self.rest.at_version("v1beta").post(&path, request).await
}
/// Removes the registered bank.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn delete_recipient_bank(&self, account_id: Uuid) -> Result<()> {
let path = format!("/accounts/{account_id}/funding_wallet/recipient_bank");
self.rest.at_version("v1beta").delete(&path, &Empty).await
}
/// Money in and out of an account's funding wallet.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_funding_wallet_transfers(
&self,
account_id: Uuid,
) -> Result<FundingWalletTransfers> {
let path = format!("/accounts/{account_id}/funding_wallet/transfers");
self.rest.at_version("v1beta").get(&path, &Empty).await
}
/// One funding wallet transfer.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_funding_wallet_transfer(
&self,
account_id: Uuid,
transfer_id: Uuid,
) -> Result<FundingWalletTransfer> {
let path = format!("/accounts/{account_id}/funding_wallet/transfers/{transfer_id}");
self.rest.at_version("v1beta").get(&path, &Empty).await
}
/// Sends money out of an account's funding wallet.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the amount is not positive.
pub async fn create_funding_wallet_withdrawal(
&self,
account_id: Uuid,
request: &CreateWithdrawalRequest,
) -> Result<FundingWalletTransfer> {
request.validate()?;
let path = format!("/accounts/{account_id}/funding_wallet/withdrawal");
self.rest.at_version("v1beta").post(&path, request).await
}
/// Simulates an incoming deposit. Sandbox only.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_demo_funding(
&self,
request: &DemoFundingRequest,
) -> Result<DemoFundingRequest> {
self.rest
.at_version("v1beta")
.post("/demo/banking/funding", request)
.await
}
// ------------------------------------------- account onboarding extras
/// Requests options trading for an account. **BETA.**
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn request_options_approval(
&self,
account_id: Uuid,
request: &RequestOptionsApprovalRequest,
) -> Result<OptionsApproval> {
let path = format!("/accounts/{account_id}/options/approval");
self.rest.post(&path, request).await
}
/// Lists options approval requests. **BETA.**
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_options_approvals(
&self,
filter: Option<&GetOptionsApprovalsRequest>,
) -> Result<OptionsApprovalsPage> {
match filter {
Some(filter) => self.rest.get("/accounts/options/approvals", filter).await,
None => self.rest.get("/accounts/options/approvals", &Empty).await,
}
}
/// A token for Onfido's client-side identity-verification SDK.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_onfido_token(
&self,
account_id: Uuid,
filter: Option<&GetOnfidoTokenRequest>,
) -> Result<OnfidoToken> {
let path = format!("/accounts/{account_id}/onfido/sdk/tokens");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Reports what Onfido's SDK concluded.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn update_onfido_outcome(
&self,
account_id: Uuid,
request: &UpdateOnfidoOutcomeRequest,
) -> Result<()> {
self.send_void(
Method::PATCH,
&format!("/accounts/{account_id}/onfido/sdk"),
Some(request),
)
.await
}
/// What Alpaca will serve in each country, keyed by country code.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_country_info(&self) -> Result<std::collections::HashMap<String, CountryInfo>> {
self.rest.get("/country-info", &Empty).await
}
/// IRA contributions that exceeded the annual limit.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_ira_excess_contributions(&self) -> Result<Vec<IraExcessContribution>> {
self.rest
.get("/accounts/ira_excess_contributions", &Empty)
.await
}
/// Downloads an account's W-8BEN document.
///
/// A different route from the general document download, and the reference
/// documents no response schema for it, so this returns the bytes as they
/// arrive. Like that download it may answer `301` to a presigned URL, so it
/// goes through the redirect-following client rather than [`RestClient`].
///
/// # Errors
/// Propagates transport and API failures.
pub async fn download_w8ben_document(
&self,
account_id: Uuid,
document_id: Uuid,
) -> Result<Vec<u8>> {
let path = format!("/accounts/{account_id}/documents/w8ben/{document_id}/download");
self.download(&path).await
}
// ------------------------------------------------- trading extras
/// What an account may still trade today.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_trading_limits(&self, account_id: Uuid) -> Result<TradingLimits> {
let path = format!("/trading/accounts/{account_id}/limits");
self.rest.get(&path, &Empty).await
}
/// Costs an order without placing it.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn estimate_order(
&self,
account_id: Uuid,
request: &EstimateOrderRequest,
) -> Result<Order> {
let path = format!("/trading/accounts/{account_id}/orders/estimation");
self.rest.post(&path, request).await
}
/// Declines to exercise an in-the-money option position at expiry.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn do_not_exercise(
&self,
account_id: Uuid,
contract: &crate::types::AssetIdent,
) -> Result<()> {
self.send_void(
Method::POST,
&format!(
"/trading/accounts/{account_id}/positions/{}/do-not-exercise",
contract.as_path_segment()?
),
None::<&Empty>,
)
.await
}
// -------------------------------------------------- tokenization
/// Mints a tokenized asset from an account's position.
///
/// The account-scoped counterpart to
/// [`TradingClient::mint_token`](crate::trading::TradingClient::mint_token);
/// the models are shared.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if `qty` is not positive.
pub async fn mint_token_for_account(
&self,
account_id: Uuid,
request: &crate::trading::MintTokenRequest,
) -> Result<crate::trading::TokenizationRequest> {
request.validate()?;
let path = format!("/accounts/{account_id}/tokenization/mint");
self.rest.post(&path, request).await
}
/// Lists an account's tokenization requests.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_tokenization_requests_for_account(
&self,
account_id: Uuid,
filter: Option<&crate::trading::GetTokenizationRequestsRequest>,
) -> Result<Vec<crate::trading::TokenizationRequest>> {
let path = format!("/accounts/{account_id}/tokenization/requests");
match filter {
Some(filter) => self.rest.get(&path, filter).await,
None => self.rest.get(&path, &Empty).await,
}
}
/// Fetches one of an account's tokenization requests.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_tokenization_request_for_account(
&self,
account_id: Uuid,
request_id: Uuid,
) -> Result<crate::trading::TokenizationRequest> {
let path = format!("/accounts/{account_id}/tokenization/requests/{request_id}");
self.rest.get(&path, &Empty).await
}
/// Fetches one by the caller's own request id.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_tokenization_request_by_client_id_for_account(
&self,
account_id: Uuid,
request: &crate::trading::ByClientRequestId,
) -> Result<crate::trading::TokenizationRequest> {
let path = format!("/accounts/{account_id}/tokenization/requests:by_client_request_id");
self.rest.get(&path, request).await
}
/// Fetches one by the issuer's request id.
///
/// Has no counterpart on the trading API, which knows only the client id.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_tokenization_request_by_issuer_id_for_account(
&self,
account_id: Uuid,
issuer_request_id: &str,
) -> Result<crate::trading::TokenizationRequest> {
let path = format!("/accounts/{account_id}/tokenization/requests:by_issuer_request_id");
self.rest
.get(&path, &[("issuer_request_id", issuer_request_id)])
.await
}
/// Acknowledges an issuer's mint callback.
///
/// Answers with the confirmed request, which is the ordinary
/// [`TokenizationRequest`](crate::trading::TokenizationRequest) the mint and
/// lookup routes already return — the spec gives this route that same
/// schema, so it gets the shipping type rather than a near-duplicate.
///
/// No captured payload exists for this route — paper trading answers 404 on
/// this surface — so the response is decoded against a spec-derived model
/// and is unverified against a live response.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the body does not name
/// exactly one account; see
/// [`TokenizationMintCallback::validate`](crate::trading::TokenizationMintCallback::validate).
/// Otherwise propagates transport, API, and decoding failures.
pub async fn tokenization_mint_callback(
&self,
account_id: Uuid,
body: &crate::trading::TokenizationMintCallback,
) -> Result<crate::trading::TokenizationRequest> {
body.validate()?;
let path = format!("/accounts/{account_id}/tokenization/callback/mint");
self.rest.post(&path, body).await
}
/// Acknowledges an issuer's redeem callback.
///
/// Answers with a [`TokenizationRedeemResponse`](crate::trading::TokenizationRedeemResponse)
/// rather than the [`TokenizationRequest`](crate::trading::TokenizationRequest)
/// the mint callback returns; the spec gives the two routes two schemas.
///
/// No captured payload exists for this route — paper trading answers 404 on
/// this surface — so the response is decoded against a spec-derived model
/// and is unverified against a live response.
///
/// # Errors
/// Returns [`crate::Error::InvalidRequest`] if the body does not name
/// exactly one account; see
/// [`TokenizationRedeemRequest::validate`](crate::trading::TokenizationRedeemRequest::validate).
/// Otherwise propagates transport, API, and decoding failures.
pub async fn tokenization_redeem_callback(
&self,
account_id: Uuid,
body: &crate::trading::TokenizationRedeemRequest,
) -> Result<crate::trading::TokenizationRedeemResponse> {
body.validate()?;
let path = format!("/accounts/{account_id}/tokenization/callback/redeem");
self.rest.post(&path, body).await
}
// ------------------------------------------------- crypto wallets
/// An account's crypto deposit wallets.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_crypto_wallets_for_account(
&self,
account_id: Uuid,
filter: Option<&crate::trading::GetCryptoWalletsRequest>,
) -> Result<Vec<crate::trading::CryptoWallet>> {
let path = format!("/accounts/{account_id}/wallets");
let wallets: OneOrMany<crate::trading::CryptoWallet> = match filter {
Some(filter) => self.rest.get(&path, filter).await?,
None => self.rest.get(&path, &Empty).await?,
};
Ok(wallets.into_vec())
}
/// An account's on-chain transfers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_crypto_transfers_for_account(
&self,
account_id: Uuid,
) -> Result<Vec<crate::trading::CryptoTransfer>> {
let path = format!("/accounts/{account_id}/wallets/transfers");
let transfers: OneOrMany<crate::trading::CryptoTransfer> =
self.rest.get(&path, &Empty).await?;
Ok(transfers.into_vec())
}
/// Fetches one of an account's on-chain transfers.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_crypto_transfer_for_account(
&self,
account_id: Uuid,
transfer_id: &str,
) -> Result<crate::trading::CryptoTransfer> {
let path = format!(
"/accounts/{account_id}/wallets/transfers/{}",
segment(transfer_id)?
);
self.rest.get(&path, &Empty).await
}
/// Withdraws crypto from an account.
///
/// **This route is not deprecated, and its trading-API counterpart is.**
/// `POST /v2/wallets/transfers` sunsets 2026-10-09 with the web app as its
/// replacement; this one carries no such notice, which is why the crate has
/// the broker withdrawal and not the trading one.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_crypto_transfer_for_account(
&self,
account_id: Uuid,
request: &crate::trading::CreateCryptoTransferRequest,
) -> Result<crate::trading::CryptoTransfer> {
let path = format!("/accounts/{account_id}/wallets/transfers");
self.rest.post(&path, request).await
}
/// The addresses an account may withdraw to.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn get_whitelisted_addresses_for_account(
&self,
account_id: Uuid,
) -> Result<Vec<crate::trading::WhitelistedAddress>> {
let path = format!("/accounts/{account_id}/wallets/whitelists");
let addresses: OneOrMany<crate::trading::WhitelistedAddress> =
self.rest.get(&path, &Empty).await?;
Ok(addresses.into_vec())
}
/// Allowlists a withdrawal address for an account.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn create_whitelisted_address_for_account(
&self,
account_id: Uuid,
request: &crate::trading::CreateWhitelistedAddressRequest,
) -> Result<crate::trading::WhitelistedAddress> {
let path = format!("/accounts/{account_id}/wallets/whitelists");
self.rest.post(&path, request).await
}
/// Removes an allowlisted address.
///
/// # Errors
/// Propagates transport and API failures.
pub async fn delete_whitelisted_address_for_account(
&self,
account_id: Uuid,
address_id: &str,
) -> Result<()> {
self.send_void(
Method::DELETE,
&format!(
"/accounts/{account_id}/wallets/whitelists/{}",
segment(address_id)?
),
None::<&Empty>,
)
.await
}
/// What a proposed crypto transfer would cost in gas.
///
/// **A `v1` route here and `v2` on the trading API**, for the same
/// operation and the same response.
///
/// # Errors
/// Propagates transport, API, and decoding failures.
pub async fn estimate_crypto_transfer_fee(
&self,
request: &crate::trading::TransferFeeEstimateRequest,
) -> Result<crate::trading::TransferFeeEstimate> {
self.rest.get("/wallets/fees/estimate", request).await
}
}