1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
// -------------------------------------------------------------------------------------------------
// Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
// https://nautechsystems.io
//
// Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// -------------------------------------------------------------------------------------------------
//! Provides an ergonomic wrapper around the **OKX v5 REST API** –
//! <https://www.okx.com/docs-v5/en/>.
//!
//! The core type exported by this module is [`OKXHttpClient`]. It offers an
//! interface to all exchange endpoints currently required by NautilusTrader.
//!
//! Key responsibilities handled internally:
//! • Request signing and header composition for private routes (HMAC-SHA256).
//! • Rate-limiting based on the public OKX specification.
//! • Deserialization of JSON payloads into domain models.
//! • Conversion of raw exchange errors into the rich [`OKXHttpError`] enum.
//!
//! # Official Documentation
//!
//! | Endpoint | Reference |
//! |--------------------------------------|--------------------------------------------------------|
//! | Market data | <https://www.okx.com/docs-v5/en/#rest-api-market-data> |
//! | Account & positions | <https://www.okx.com/docs-v5/en/#rest-api-account> |
//! | Funding & asset balances | <https://www.okx.com/docs-v5/en/#rest-api-funding> |
use std::{
collections::HashMap,
fmt::Debug,
num::NonZeroU32,
str::FromStr,
sync::{
Arc, LazyLock,
atomic::{AtomicBool, Ordering},
},
};
use ahash::{AHashMap, AHashSet};
use anyhow::Context;
use chrono::{DateTime, Utc};
use nautilus_core::{
AtomicMap, AtomicTime, UnixNanos, consts::NAUTILUS_USER_AGENT,
datetime::NANOSECONDS_IN_MILLISECOND, env::get_or_env_var, string::secret::REDACTED,
time::get_atomic_clock_realtime,
};
use nautilus_model::{
data::{
Bar, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
OrderBookDelta, OrderBookDeltas, TradeTick, forward::ForwardPrice,
},
enums::{
AggregationSource, BarAggregation, BookAction, BookType, OrderSide, OrderType,
PositionSide, RecordFlag, TimeInForce, TriggerType,
},
events::AccountState,
identifiers::{AccountId, ClientOrderId, InstrumentId},
instruments::{Instrument, InstrumentAny},
orderbook::OrderBook,
reports::{FillReport, OrderStatusReport, PositionStatusReport},
types::{Price, Quantity},
};
use nautilus_network::{
http::{HttpClient, Method, StatusCode, USER_AGENT},
ratelimiter::quota::Quota,
retry::{RetryConfig, RetryManager},
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use tokio_util::sync::CancellationToken;
use ustr::Ustr;
use super::{
error::OKXHttpError,
models::{
OKXAccount, OKXAmendAlgoOrderRequest, OKXAmendAlgoOrderResponse, OKXAttachAlgoOrdRequest,
OKXCancelAlgoOrderRequest, OKXCancelAlgoOrderResponse, OKXFeeRate, OKXFundingRateHistory,
OKXIndexTicker, OKXMarkPrice, OKXOptionSummary, OKXOrderAlgo, OKXOrderBookSnapshot,
OKXOrderHistory, OKXPlaceAlgoOrderRequest, OKXPlaceAlgoOrderResponse, OKXPlaceOrderRequest,
OKXPlaceOrderResponse, OKXPosition, OKXPositionHistory, OKXPositionTier, OKXServerTime,
OKXTransactionDetail,
},
query::{
GetAlgoOrdersParams, GetAlgoOrdersParamsBuilder, GetCandlesticksParams,
GetCandlesticksParamsBuilder, GetFundingRateHistoryParams, GetIndexTickerParams,
GetIndexTickerParamsBuilder, GetInstrumentsParams, GetInstrumentsParamsBuilder,
GetMarkPriceParams, GetMarkPriceParamsBuilder, GetOptionSummaryParams, GetOrderBookParams,
GetOrderHistoryParams, GetOrderHistoryParamsBuilder, GetOrderListParams,
GetOrderListParamsBuilder, GetPositionTiersParams, GetPositionsHistoryParams,
GetPositionsParams, GetPositionsParamsBuilder, GetTradeFeeParams, GetTradesParams,
GetTradesParamsBuilder, GetTransactionDetailsParams, GetTransactionDetailsParamsBuilder,
SetPositionModeParams, SetPositionModeParamsBuilder,
},
};
use crate::{
common::{
consts::{
OKX_FIELD_SCODE, OKX_FIELD_SMSG, OKX_HTTP_URL, OKX_NAUTILUS_BROKER_ID,
OKX_SUPPORTED_ORDER_TYPES, OKX_SUPPORTED_TIME_IN_FORCE, should_retry_error_code,
},
credential::Credential,
enums::{
OKXAlgoOrderType, OKXContractType, OKXEnvironment, OKXInstrumentStatus,
OKXInstrumentType, OKXOrderStatus, OKXOrderType, OKXPositionMode, OKXPositionSide,
OKXSide, OKXTargetCurrency, OKXTradeMode, OKXTriggerType,
conditional_order_to_algo_type,
},
models::OKXInstrument,
parse::{
extract_inst_family, okx_instrument_type, okx_instrument_type_from_symbol,
parse_account_state, parse_base_quote_from_symbol, parse_candlestick,
parse_fill_report, parse_funding_rate, parse_index_price_update, parse_instrument_any,
parse_instrument_id, parse_mark_price_update, parse_order_status_report,
parse_position_status_report, parse_price, parse_quantity,
parse_spot_margin_position_from_balance, parse_trade_tick,
},
},
http::{
models::{OKXCandlestick, OKXTrade},
query::GetOrderParams,
},
websocket::{messages::OKXAlgoOrderMsg, parse::parse_algo_order_status_report},
};
const OKX_SUCCESS_CODE: &str = "0";
/// Ranks a spot instrument's quote currency for deterministic tie-breaking
/// when multiple pairs share the same base. Matches OKX's dominant-quote
/// ordering so spot-margin position reports stay on a stable instrument id
/// across restarts.
fn spot_quote_priority(symbol: &str) -> u8 {
symbol.rsplit_once('-').map_or(4, |(_, quote)| match quote {
"USDT" => 0,
"USDC" => 1,
"USD" => 2,
_ => 3,
})
}
fn resolve_okx_error_message(response_body: &[u8], top_level_msg: &str) -> String {
let message = top_level_msg.trim();
let is_generic_top_level = message.eq_ignore_ascii_case("All operations failed");
if !message.is_empty() && !is_generic_top_level {
return message.to_string();
}
if let Ok(payload) = serde_json::from_slice::<serde_json::Value>(response_body)
&& let Some(first_item) = payload
.get("data")
.and_then(serde_json::Value::as_array)
.and_then(|items| items.first())
{
if let Some(s_msg) = first_item
.get(OKX_FIELD_SMSG)
.and_then(serde_json::Value::as_str)
{
let s_msg = s_msg.trim();
if !s_msg.is_empty() {
return s_msg.to_string();
}
}
if let Some(s_code) = first_item
.get(OKX_FIELD_SCODE)
.and_then(serde_json::Value::as_str)
{
let s_code = s_code.trim();
if !s_code.is_empty() {
return s_code.to_string();
}
}
}
String::new()
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::resolve_okx_error_message;
#[rstest]
fn test_resolve_okx_error_message_prefers_detailed_s_msg_over_generic_top_level() {
let body = br#"{
"code": "1",
"msg": "All operations failed",
"data": [
{
"sCode": "51046",
"sMsg": "Test detailed failure"
}
]
}"#;
assert_eq!(
resolve_okx_error_message(body, "All operations failed"),
"Test detailed failure",
);
}
#[rstest]
#[case("BTC-USD")]
#[case("BTC-USD-241217")]
#[case("BTC-USD-241217-92000")]
fn test_option_summary_expiry_key_rejects_short_symbol(#[case] symbol: &str) {
let result = super::OKXHttpClient::option_summary_expiry_key(symbol);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Expected OKX option symbol with expiry"),
"unexpected error: {err}"
);
}
#[rstest]
fn test_option_summary_expiry_key_extracts_base_quote_expiry() {
let result =
super::OKXHttpClient::option_summary_expiry_key("BTC-USD-241217-92000-C").unwrap();
assert_eq!(result, "BTC-USD-241217");
}
#[rstest]
#[case("BTC-USD")]
#[case("BTC-USD-241217")]
#[case("BTC-USD-241217-92000")]
fn test_option_summary_exp_time_rejects_short_symbol(#[case] symbol: &str) {
let result = super::OKXHttpClient::option_summary_exp_time(symbol);
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("Expected OKX option symbol with expiry"),
"unexpected error: {err}"
);
}
#[rstest]
fn test_option_summary_exp_time_extracts_expiry() {
let result =
super::OKXHttpClient::option_summary_exp_time("BTC-USD-241217-92000-C").unwrap();
assert_eq!(result, Some("241217".to_string()));
}
}
/// Default OKX REST API rate limit: 500 requests per 2 seconds.
///
/// - Sub-account order limit: 1000 requests per 2 seconds.
/// - Account balance: 10 requests per 2 seconds.
/// - Account instruments: 20 requests per 2 seconds.
///
/// We use a conservative 250 requests per second (500 per 2 seconds) as a general limit
/// that should accommodate most use cases while respecting OKX's documented limits.
pub static OKX_REST_QUOTA: LazyLock<Quota> = LazyLock::new(|| {
Quota::per_second(NonZeroU32::new(250).expect("non-zero")).expect("valid constant")
});
const OKX_GLOBAL_RATE_KEY: &str = "okx:global";
// OKX returns at most 100 records per page for order, fill, and algo endpoints
const OKX_PAGE_SIZE: usize = 100;
// Safety cap on paginated reconciliation fetches to avoid unbounded loops
const MAX_RECONCILIATION_PAGES: usize = 50;
/// Represents an OKX HTTP response.
#[derive(Debug, Serialize, Deserialize)]
pub struct OKXResponse<T> {
/// The OKX response code, which is `"0"` for success.
pub code: String,
/// A message string which can be informational or describe an error cause.
pub msg: String,
/// The typed data returned by the OKX endpoint.
pub data: Vec<T>,
}
/// Provides a raw HTTP client for interacting with the [OKX](https://okx.com) REST API.
///
/// This client wraps the underlying [`HttpClient`] to handle functionality
/// specific to OKX, such as request signing (for authenticated endpoints),
/// forming request URLs, and deserializing responses into OKX specific data models.
pub struct OKXRawHttpClient {
base_url: String,
client: HttpClient,
credential: Option<Credential>,
retry_manager: RetryManager<OKXHttpError>,
cancellation_token: CancellationToken,
environment: OKXEnvironment,
}
impl Default for OKXRawHttpClient {
fn default() -> Self {
Self::new(None, 60, 3, 1000, 10_000, OKXEnvironment::Live, None)
.expect("Failed to create default OKXRawHttpClient")
}
}
impl Debug for OKXRawHttpClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let credential = self.credential.as_ref().map(|_| REDACTED);
f.debug_struct(stringify!(OKXRawHttpClient))
.field("base_url", &self.base_url)
.field("credential", &credential)
.finish_non_exhaustive()
}
}
impl OKXRawHttpClient {
fn rate_limiter_quotas() -> Vec<(String, Quota)> {
vec![
(OKX_GLOBAL_RATE_KEY.to_string(), *OKX_REST_QUOTA),
(
"okx:/api/v5/account/balance".to_string(),
Quota::per_second(NonZeroU32::new(5).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/public/instruments".to_string(),
Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/market/candles".to_string(),
Quota::per_second(NonZeroU32::new(50).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/market/history-candles".to_string(),
Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/market/history-trades".to_string(),
Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/order".to_string(),
Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"), // 60 requests / 2 seconds (per instrument)
),
(
"okx:/api/v5/trade/orders-pending".to_string(),
Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/orders-history".to_string(),
Quota::per_second(NonZeroU32::new(20).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/fills".to_string(),
Quota::per_second(NonZeroU32::new(30).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/order-algo".to_string(),
Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/cancel-algos".to_string(),
Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
),
(
"okx:/api/v5/trade/amend-algos".to_string(),
Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant"),
),
]
}
fn rate_limit_keys(endpoint: &str) -> Vec<Ustr> {
let normalized = endpoint.split('?').next().unwrap_or(endpoint);
let route = format!("okx:{normalized}");
vec![Ustr::from(OKX_GLOBAL_RATE_KEY), Ustr::from(route.as_str())]
}
/// Cancel all pending HTTP requests.
pub fn cancel_all_requests(&self) {
self.cancellation_token.cancel();
}
/// Get the cancellation token for this client.
pub fn cancellation_token(&self) -> &CancellationToken {
&self.cancellation_token
}
/// Creates a new [`OKXHttpClient`] using the default OKX HTTP URL,
/// optionally overridden with a custom base URL.
///
/// This version of the client has **no credentials**, so it can only
/// call publicly accessible endpoints.
///
/// # Errors
///
/// Returns an error if the retry manager cannot be created.
pub fn new(
base_url: Option<String>,
timeout_secs: u64,
max_retries: u32,
retry_delay_ms: u64,
retry_delay_max_ms: u64,
environment: OKXEnvironment,
proxy_url: Option<String>,
) -> Result<Self, OKXHttpError> {
let retry_config = RetryConfig {
max_retries,
initial_delay_ms: retry_delay_ms,
max_delay_ms: retry_delay_max_ms,
backoff_factor: 2.0,
jitter_ms: 1000,
operation_timeout_ms: Some(60_000),
immediate_first: false,
max_elapsed_ms: Some(180_000),
};
let retry_manager = RetryManager::new(retry_config);
Ok(Self {
base_url: base_url.unwrap_or(OKX_HTTP_URL.to_string()),
client: HttpClient::new(
Self::default_headers(environment),
vec![],
Self::rate_limiter_quotas(),
Some(*OKX_REST_QUOTA),
Some(timeout_secs),
proxy_url,
)
.map_err(|e| {
OKXHttpError::ValidationError(format!("Failed to create HTTP client: {e}"))
})?,
credential: None,
retry_manager,
cancellation_token: CancellationToken::new(),
environment,
})
}
/// Creates a new [`OKXHttpClient`] configured with credentials
/// for authenticated requests, optionally using a custom base URL.
///
/// # Errors
///
/// Returns an error if the retry manager cannot be created.
#[expect(clippy::too_many_arguments)]
pub fn with_credentials(
api_key: String,
api_secret: String,
api_passphrase: String,
base_url: String,
timeout_secs: u64,
max_retries: u32,
retry_delay_ms: u64,
retry_delay_max_ms: u64,
environment: OKXEnvironment,
proxy_url: Option<String>,
) -> Result<Self, OKXHttpError> {
let retry_config = RetryConfig {
max_retries,
initial_delay_ms: retry_delay_ms,
max_delay_ms: retry_delay_max_ms,
backoff_factor: 2.0,
jitter_ms: 1000,
operation_timeout_ms: Some(60_000),
immediate_first: false,
max_elapsed_ms: Some(180_000),
};
let retry_manager = RetryManager::new(retry_config);
Ok(Self {
base_url,
client: HttpClient::new(
Self::default_headers(environment),
vec![],
Self::rate_limiter_quotas(),
Some(*OKX_REST_QUOTA),
Some(timeout_secs),
proxy_url,
)
.map_err(|e| {
OKXHttpError::ValidationError(format!("Failed to create HTTP client: {e}"))
})?,
credential: Some(Credential::new(api_key, api_secret, api_passphrase)),
retry_manager,
cancellation_token: CancellationToken::new(),
environment,
})
}
/// Builds the default headers to include with each request (e.g., `User-Agent`).
fn default_headers(environment: OKXEnvironment) -> HashMap<String, String> {
let mut headers =
HashMap::from([(USER_AGENT.to_string(), NAUTILUS_USER_AGENT.to_string())]);
if environment == OKXEnvironment::Demo {
headers.insert("x-simulated-trading".to_string(), "1".to_string());
}
headers
}
/// Signs an OKX request with timestamp, API key, passphrase, and signature.
///
/// # Errors
///
/// Returns [`OKXHttpError::MissingCredentials`] if no credentials are set
/// but the request requires authentication.
fn sign_request(
&self,
method: &Method,
path: &str,
body: Option<&[u8]>,
) -> Result<HashMap<String, String>, OKXHttpError> {
let credential = match self.credential.as_ref() {
Some(c) => c,
None => return Err(OKXHttpError::MissingCredentials),
};
let api_key = credential.api_key().to_string();
let api_passphrase = credential.api_passphrase().to_string();
// OKX requires milliseconds in the timestamp (ISO 8601 with milliseconds)
let now = Utc::now();
let millis = now.timestamp_subsec_millis();
let timestamp = now.format("%Y-%m-%dT%H:%M:%S").to_string() + &format!(".{millis:03}Z");
let signature = credential.sign_bytes(×tamp, method.as_str(), path, body);
let mut headers = HashMap::new();
headers.insert("OK-ACCESS-KEY".to_string(), api_key);
headers.insert("OK-ACCESS-PASSPHRASE".to_string(), api_passphrase);
headers.insert("OK-ACCESS-TIMESTAMP".to_string(), timestamp);
headers.insert("OK-ACCESS-SIGN".to_string(), signature);
Ok(headers)
}
/// Sends an HTTP request to OKX and parses the response into `Vec<T>`.
///
/// Internally, this method handles:
/// - Building the URL from `base_url` + `path`.
/// - Optionally signing the request.
/// - Deserializing JSON responses into typed models, or returning a [`OKXHttpError`].
/// - Retrying with exponential backoff on transient errors.
///
/// # Errors
///
/// Returns an error if:
/// - The HTTP request fails.
/// - Authentication is required but credentials are missing.
/// - The response cannot be deserialized into the expected type.
/// - The OKX API returns an error response.
async fn send_request<T: DeserializeOwned, P: Serialize>(
&self,
method: Method,
path: &str,
params: Option<&P>,
body: Option<Vec<u8>>,
authenticate: bool,
) -> Result<Vec<T>, OKXHttpError> {
let url = format!("{}{path}", self.base_url);
// Pre-compute rate limit keys once outside the retry closure
let rate_keys: Vec<String> = Self::rate_limit_keys(path)
.into_iter()
.map(|k| k.to_string())
.collect();
let operation = || {
let url = url.clone();
let method = method.clone();
let body = body.clone();
let rate_keys = rate_keys.clone();
async move {
// Serialize params to query string for signing (if needed)
let query_string = if let Some(p) = params {
serde_urlencoded::to_string(p).map_err(|e| {
OKXHttpError::JsonError(format!("Failed to serialize params: {e}"))
})?
} else {
String::new()
};
// Build full path with query string for signing
let full_path = if query_string.is_empty() {
path.to_string()
} else {
format!("{path}?{query_string}")
};
let mut headers = if authenticate {
self.sign_request(&method, &full_path, body.as_deref())?
} else {
HashMap::new()
};
// Always set Content-Type header when body is present
if body.is_some() {
headers.insert("Content-Type".to_string(), "application/json".to_string());
}
let resp = self
.client
.request_with_params(
method.clone(),
url,
params,
Some(headers),
body,
None,
Some(rate_keys),
)
.await?;
log::trace!("Response: {resp:?}");
if resp.status.is_success() {
let okx_response: OKXResponse<T> =
serde_json::from_slice(&resp.body).map_err(|e| {
log::error!("Failed to deserialize OKXResponse: {e}");
OKXHttpError::JsonError(e.to_string())
})?;
if okx_response.code != OKX_SUCCESS_CODE {
return Err(OKXHttpError::OkxError {
error_code: okx_response.code,
message: resolve_okx_error_message(&resp.body, &okx_response.msg),
});
}
Ok(okx_response.data)
} else {
let error_body = String::from_utf8_lossy(&resp.body);
if resp.status.as_u16() == StatusCode::NOT_FOUND.as_u16() {
log::debug!("HTTP 404 with body: {error_body}");
} else {
log::error!(
"HTTP error {} with body: {error_body}",
resp.status.as_str()
);
}
if let Ok(parsed_error) = serde_json::from_slice::<OKXResponse<T>>(&resp.body) {
return Err(OKXHttpError::OkxError {
error_code: parsed_error.code,
message: resolve_okx_error_message(&resp.body, &parsed_error.msg),
});
}
Err(OKXHttpError::UnexpectedStatus {
// Fall back to 500 if the venue returns a non-standard
// code so we never panic in the error path.
status: StatusCode::from_u16(resp.status.as_u16())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
body: error_body.to_string(),
})
}
}
};
// Retry strategy based on OKX error responses and HTTP status codes:
//
// 1. Network errors: always retry (transient connection issues)
// 2. HTTP 5xx/429: server errors and rate limiting should be retried
// 3. OKX specific retryable error codes (defined in common::consts)
//
// Note: OKX returns many permanent errors which should NOT be retried
// (e.g., "Invalid instrument", "Insufficient balance", "Invalid API Key")
let should_retry = |error: &OKXHttpError| -> bool {
match error {
OKXHttpError::HttpClientError(_) => true,
OKXHttpError::UnexpectedStatus { status, .. } => {
status.as_u16() >= 500 || status.as_u16() == 429
}
OKXHttpError::OkxError { error_code, .. } => should_retry_error_code(error_code),
_ => false,
}
};
let create_error = |msg: String| -> OKXHttpError {
if msg == "canceled" {
OKXHttpError::Canceled("Adapter disconnecting or shutting down".to_string())
} else {
OKXHttpError::ValidationError(msg)
}
};
self.retry_manager
.execute_with_retry_with_cancel(
path,
operation,
should_retry,
create_error,
&self.cancellation_token,
)
.await
}
/// Sets the position mode for an account.
///
/// # Errors
///
/// Returns an error if JSON serialization of `params` fails, if the HTTP
/// request fails, or if the response body cannot be deserialized.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-set-position-mode>
pub async fn set_position_mode(
&self,
params: SetPositionModeParams,
) -> Result<Vec<serde_json::Value>, OKXHttpError> {
let path = "/api/v5/account/set-position-mode";
let body = serde_json::to_vec(¶ms)?;
self.send_request::<_, ()>(Method::POST, path, None, Some(body), true)
.await
}
/// Requests position tiers information, maximum leverage depends on your borrowings and margin ratio.
///
/// # Errors
///
/// Returns an error if the HTTP request fails, authentication is rejected
/// or the response cannot be deserialized.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-position-tiers>
pub async fn get_position_tiers(
&self,
params: GetPositionTiersParams,
) -> Result<Vec<OKXPositionTier>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/public/position-tiers",
Some(¶ms),
None,
false,
)
.await
}
/// Requests a list of instruments with open contracts.
///
/// # Errors
///
/// Returns an error if JSON serialization of `params` fails, if the HTTP
/// request fails, or if the response body cannot be deserialized.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-instruments>
pub async fn get_instruments(
&self,
params: GetInstrumentsParams,
) -> Result<Vec<OKXInstrument>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/public/instruments",
Some(¶ms),
None,
false,
)
.await
}
/// Requests option market data for an instrument family.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or the response cannot be deserialized.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-option-market-data>
pub async fn get_option_summary(
&self,
params: GetOptionSummaryParams,
) -> Result<Vec<OKXOptionSummary>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/public/opt-summary",
Some(¶ms),
None,
false,
)
.await
}
/// Requests the current server time from OKX.
///
/// Retrieves the OKX system time in Unix timestamp (milliseconds). This is useful for
/// synchronizing local clocks with the exchange server and logging time drift.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or if the response body
/// cannot be parsed into [`OKXServerTime`].
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-system-time>
pub async fn get_server_time(&self) -> Result<u64, OKXHttpError> {
let response: Vec<OKXServerTime> = self
.send_request::<_, ()>(Method::GET, "/api/v5/public/time", None, None, false)
.await?;
response
.first()
.map(|t| t.ts)
.ok_or_else(|| OKXHttpError::JsonError("Empty server time response".to_string()))
}
/// Requests a mark price.
///
/// We set the mark price based on the SPOT index and at a reasonable basis to prevent individual
/// users from manipulating the market and causing the contract price to fluctuate.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or if the response body
/// cannot be parsed into [`OKXMarkPrice`].
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-mark-price>
pub async fn get_mark_price(
&self,
params: GetMarkPriceParams,
) -> Result<Vec<OKXMarkPrice>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/public/mark-price",
Some(¶ms),
None,
false,
)
.await
}
/// Requests the latest index price.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-index-tickers>
pub async fn get_index_tickers(
&self,
params: GetIndexTickerParams,
) -> Result<Vec<OKXIndexTicker>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/market/index-tickers",
Some(¶ms),
None,
false,
)
.await
}
/// Requests trades history.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-trades-history>
pub async fn get_history_trades(
&self,
params: GetTradesParams,
) -> Result<Vec<OKXTrade>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/market/history-trades",
Some(¶ms),
None,
false,
)
.await
}
/// Requests order book snapshot.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-order-book>
pub async fn get_order_book(
&self,
params: GetOrderBookParams,
) -> Result<Vec<OKXOrderBookSnapshot>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/market/books",
Some(¶ms),
None,
false,
)
.await
}
/// Requests funding rate history.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#public-data-rest-api-get-funding-rate-history>
pub async fn get_funding_rate_history(
&self,
params: GetFundingRateHistoryParams,
) -> Result<Vec<OKXFundingRateHistory>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/public/funding-rate-history",
Some(¶ms),
None,
false,
)
.await
}
/// Requests recent candlestick data.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks>
pub async fn get_candles(
&self,
params: GetCandlesticksParams,
) -> Result<Vec<OKXCandlestick>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/market/candles",
Some(¶ms),
None,
false,
)
.await
}
/// Requests historical candlestick data.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks-history>
pub async fn get_history_candles(
&self,
params: GetCandlesticksParams,
) -> Result<Vec<OKXCandlestick>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/market/history-candles",
Some(¶ms),
None,
false,
)
.await
}
/// Requests a list of assets (with non-zero balance), remaining balance, and available amount
/// in the trading account.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance>
pub async fn get_balance(&self) -> Result<Vec<OKXAccount>, OKXHttpError> {
let path = "/api/v5/account/balance";
self.send_request::<_, ()>(Method::GET, path, None, None, true)
.await
}
/// Requests fee rates for the account.
///
/// Returns fee rates for the specified instrument type and the user's VIP level.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-fee-rates>
pub async fn get_trade_fee(
&self,
params: GetTradeFeeParams,
) -> Result<Vec<OKXFeeRate>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/account/trade-fee",
Some(¶ms),
None,
true,
)
.await
}
/// Retrieves a single order’s details.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order>
pub async fn get_order(
&self,
params: GetOrderParams,
) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/order",
Some(¶ms),
None,
true,
)
.await
}
/// Requests order list (pending orders).
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-list>
pub async fn get_orders_pending(
&self,
params: GetOrderListParams,
) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/orders-pending",
Some(¶ms),
None,
true,
)
.await
}
/// Requests historical order records.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-orders-history>
pub async fn get_orders_history(
&self,
params: GetOrderHistoryParams,
) -> Result<Vec<OKXOrderHistory>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/orders-history",
Some(¶ms),
None,
true,
)
.await
}
/// Requests pending algo orders.
///
/// # Errors
///
/// Returns an error if the operation fails.
pub async fn get_order_algo_pending(
&self,
params: GetAlgoOrdersParams,
) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/orders-algo-pending",
Some(¶ms),
None,
true,
)
.await
}
/// Requests historical algo orders.
///
/// # Errors
///
/// Returns an error if the operation fails.
pub async fn get_order_algo_history(
&self,
params: GetAlgoOrdersParams,
) -> Result<Vec<OKXOrderAlgo>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/orders-algo-history",
Some(¶ms),
None,
true,
)
.await
}
/// Requests transaction details (fills) for the given parameters.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-days>
pub async fn get_fills(
&self,
params: GetTransactionDetailsParams,
) -> Result<Vec<OKXTransactionDetail>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/trade/fills",
Some(¶ms),
None,
true,
)
.await
}
/// Requests information on your positions. When the account is in net mode, net positions will
/// be displayed, and when the account is in long/short mode, long or short positions will be
/// displayed. Returns in reverse chronological order using ctime.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions>
pub async fn get_positions(
&self,
params: GetPositionsParams,
) -> Result<Vec<OKXPosition>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/account/positions",
Some(¶ms),
None,
true,
)
.await
}
/// Requests closed or historical position data.
///
/// # Errors
///
/// Returns an error if the operation fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions-history>
pub async fn get_positions_history(
&self,
params: GetPositionsHistoryParams,
) -> Result<Vec<OKXPositionHistory>, OKXHttpError> {
self.send_request(
Method::GET,
"/api/v5/account/positions-history",
Some(¶ms),
None,
true,
)
.await
}
}
/// Provides a higher-level HTTP client for the [OKX](https://okx.com) REST API.
///
/// This client wraps the underlying `OKXHttpInnerClient` to handle conversions
/// into the Nautilus domain model.
#[derive(Debug)]
#[cfg_attr(
feature = "python",
pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.okx", from_py_object)
)]
#[cfg_attr(
feature = "python",
pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.okx")
)]
pub struct OKXHttpClient {
pub(crate) inner: Arc<OKXRawHttpClient>,
pub(crate) instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
clock: &'static AtomicTime,
cache_initialized: AtomicBool,
}
impl Clone for OKXHttpClient {
fn clone(&self) -> Self {
let cache_initialized = AtomicBool::new(false);
let is_initialized = self.cache_initialized.load(Ordering::Acquire);
if is_initialized {
cache_initialized.store(true, Ordering::Release);
}
Self {
inner: self.inner.clone(),
instruments_cache: self.instruments_cache.clone(),
cache_initialized,
clock: self.clock,
}
}
}
impl Default for OKXHttpClient {
fn default() -> Self {
Self::new(None, 60, 3, 1000, 10_000, OKXEnvironment::Live, None)
.expect("Failed to create default OKXHttpClient")
}
}
impl OKXHttpClient {
/// Creates a new [`OKXHttpClient`] using the default OKX HTTP URL,
/// optionally overridden with a custom base url.
///
/// This version of the client has **no credentials**, so it can only
/// call publicly accessible endpoints.
///
/// # Errors
///
/// Returns an error if the retry manager cannot be created.
pub fn new(
base_url: Option<String>,
timeout_secs: u64,
max_retries: u32,
retry_delay_ms: u64,
retry_delay_max_ms: u64,
environment: OKXEnvironment,
proxy_url: Option<String>,
) -> anyhow::Result<Self> {
Ok(Self {
inner: Arc::new(OKXRawHttpClient::new(
base_url,
timeout_secs,
max_retries,
retry_delay_ms,
retry_delay_max_ms,
environment,
proxy_url,
)?),
instruments_cache: Arc::new(AtomicMap::new()),
cache_initialized: AtomicBool::new(false),
clock: get_atomic_clock_realtime(),
})
}
/// Generates a timestamp for initialization.
fn generate_ts_init(&self) -> UnixNanos {
self.clock.get_time_ns()
}
/// Creates a new authenticated [`OKXHttpClient`] using environment variables and
/// the default OKX HTTP base url.
///
/// # Errors
///
/// Returns an error if the operation fails.
pub fn from_env() -> anyhow::Result<Self> {
Self::with_credentials(
None,
None,
None,
None,
60,
3,
1000,
10_000,
OKXEnvironment::Live,
None,
)
}
/// Creates a new [`OKXHttpClient`] configured with credentials
/// for authenticated requests, optionally using a custom base url.
///
/// # Errors
///
/// Returns an error if the operation fails.
#[expect(clippy::too_many_arguments)]
pub fn with_credentials(
api_key: Option<String>,
api_secret: Option<String>,
api_passphrase: Option<String>,
base_url: Option<String>,
timeout_secs: u64,
max_retries: u32,
retry_delay_ms: u64,
retry_delay_max_ms: u64,
environment: OKXEnvironment,
proxy_url: Option<String>,
) -> anyhow::Result<Self> {
let api_key = get_or_env_var(api_key, "OKX_API_KEY")?;
let api_secret = get_or_env_var(api_secret, "OKX_API_SECRET")?;
let api_passphrase = get_or_env_var(api_passphrase, "OKX_API_PASSPHRASE")?;
let base_url = base_url.unwrap_or(OKX_HTTP_URL.to_string());
Ok(Self {
inner: Arc::new(OKXRawHttpClient::with_credentials(
api_key,
api_secret,
api_passphrase,
base_url,
timeout_secs,
max_retries,
retry_delay_ms,
retry_delay_max_ms,
environment,
proxy_url,
)?),
instruments_cache: Arc::new(AtomicMap::new()),
cache_initialized: AtomicBool::new(false),
clock: get_atomic_clock_realtime(),
})
}
/// Retrieves an instrument from the cache.
///
/// # Errors
///
/// Returns an error if the instrument is not found in the cache.
fn instrument_from_cache(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
self.instruments_cache
.get_cloned(&symbol)
.ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not in cache"))
}
/// Cancel all pending HTTP requests.
pub fn cancel_all_requests(&self) {
self.inner.cancel_all_requests();
}
/// Get the cancellation token for this client.
pub fn cancellation_token(&self) -> &CancellationToken {
self.inner.cancellation_token()
}
/// Returns the base url being used by the client.
pub fn base_url(&self) -> &str {
self.inner.base_url.as_str()
}
/// Returns the public API key being used by the client.
pub fn api_key(&self) -> Option<&str> {
self.inner.credential.as_ref().map(|c| c.api_key())
}
/// Returns a masked version of the API key for logging purposes.
#[must_use]
pub fn api_key_masked(&self) -> Option<String> {
self.inner.credential.as_ref().map(|c| c.api_key_masked())
}
/// Returns whether the client is configured for demo trading.
#[must_use]
pub fn is_demo(&self) -> bool {
self.inner.environment == OKXEnvironment::Demo
}
/// Requests the current server time from OKX.
///
/// Returns the OKX system time as a Unix timestamp in milliseconds.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or if the response cannot be parsed.
pub async fn get_server_time(&self) -> Result<u64, OKXHttpError> {
self.inner.get_server_time().await
}
/// Checks if the client is initialized.
///
/// The client is considered initialized if any instruments have been cached from the venue.
#[must_use]
pub fn is_initialized(&self) -> bool {
self.cache_initialized.load(Ordering::Acquire)
}
/// Returns a snapshot of all instrument symbols currently held in the
/// internal cache.
#[must_use]
pub fn get_cached_symbols(&self) -> Vec<String> {
self.instruments_cache
.load()
.keys()
.map(|k| k.to_string())
.collect()
}
/// Caches multiple instruments.
///
/// Any existing instruments with the same symbols will be replaced.
pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
self.instruments_cache.rcu(|m| {
for inst in instruments {
m.insert(inst.raw_symbol().inner(), inst.clone());
}
});
self.cache_initialized.store(true, Ordering::Release);
}
/// Caches a single instrument.
///
/// Any existing instrument with the same symbol will be replaced.
pub fn cache_instrument(&self, instrument: InstrumentAny) {
self.instruments_cache
.insert(instrument.raw_symbol().inner(), instrument);
self.cache_initialized.store(true, Ordering::Release);
}
/// Gets an instrument from the cache by symbol.
pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
self.instruments_cache.get_cloned(symbol)
}
/// Requests the account state for the `account_id` from OKX.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or no account state is returned.
pub async fn request_account_state(
&self,
account_id: AccountId,
) -> anyhow::Result<AccountState> {
let resp = self
.inner
.get_balance()
.await
.map_err(|e| anyhow::anyhow!(e))?;
let ts_init = self.generate_ts_init();
let raw = resp
.first()
.ok_or_else(|| anyhow::anyhow!("No account state returned from OKX"))?;
let account_state = parse_account_state(raw, account_id, ts_init)?;
Ok(account_state)
}
/// Sets the position mode for the account.
///
/// Defaults to NetMode if no position mode is provided.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or the position mode cannot be set.
///
/// # Note
///
/// This endpoint only works for accounts with derivatives trading enabled.
/// If the account only has spot trading, this will return an error.
pub async fn set_position_mode(&self, position_mode: OKXPositionMode) -> anyhow::Result<()> {
let mut params = SetPositionModeParamsBuilder::default();
params.pos_mode(position_mode);
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
match self.inner.set_position_mode(params).await {
Ok(_) => Ok(()),
Err(e) => {
if let OKXHttpError::OkxError {
error_code,
message,
} = &e
&& error_code == "50115"
{
log::warn!(
"Account does not support position mode setting (derivatives trading not enabled): {message}"
);
return Ok(()); // Gracefully handle this case
}
anyhow::bail!(e)
}
}
}
/// Requests all instruments for the `instrument_type` from OKX.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or instrument parsing fails.
///
/// # Returns
///
/// A tuple containing:
/// - `Vec<InstrumentAny>`: The parsed instruments
/// - `Vec<(Ustr, u64)>`: Mappings of inst_id to inst_id_code for WebSocket order operations
pub async fn request_instruments(
&self,
instrument_type: OKXInstrumentType,
instrument_family: Option<String>,
) -> anyhow::Result<(Vec<InstrumentAny>, Vec<(Ustr, u64)>)> {
let mut params = GetInstrumentsParamsBuilder::default();
params.inst_type(instrument_type);
if let Some(family) = instrument_family.clone() {
params.inst_family(family);
}
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self
.inner
.get_instruments(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let fee_rate_opt = {
let fee_params = GetTradeFeeParams {
inst_type: instrument_type,
uly: None,
inst_family: instrument_family,
};
match self.inner.get_trade_fee(fee_params).await {
Ok(rates) => rates.into_iter().next(),
Err(OKXHttpError::MissingCredentials) => {
log::debug!("Missing credentials for fee rates, using None");
None
}
Err(e) => {
log::warn!("Failed to fetch fee rates for {instrument_type}: {e}");
None
}
}
};
let ts_init = self.generate_ts_init();
let mut instruments: Vec<InstrumentAny> = Vec::new();
let mut inst_id_codes: Vec<(Ustr, u64)> = Vec::new();
for inst in &resp {
// Collect inst_id_code mappings for WebSocket order operations
if let Some(code) = inst.inst_id_code {
inst_id_codes.push((inst.inst_id, code));
}
// Skip pre-open instruments which have incomplete/empty field values
// Keep suspended instruments as they have valid metadata and may return to live
if inst.state == OKXInstrumentStatus::Preopen {
continue;
}
// Determine which fee fields to use based on contract type
// OKX fee rate convention: positive = rebate, negative = commission
// Nautilus convention: negative = rebate, positive = commission
// Negate to convert between conventions
let (maker_fee, taker_fee) = if let Some(ref fee_rate) = fee_rate_opt {
let is_usdt_margined = inst.ct_type == OKXContractType::Linear;
let (maker_str, taker_str) = if is_usdt_margined {
(&fee_rate.maker_u, &fee_rate.taker_u)
} else {
(&fee_rate.maker, &fee_rate.taker)
};
let maker = if maker_str.is_empty() {
None
} else {
Decimal::from_str(maker_str).ok().map(|v| -v)
};
let taker = if taker_str.is_empty() {
None
} else {
Decimal::from_str(taker_str).ok().map(|v| -v)
};
(maker, taker)
} else {
(None, None)
};
match parse_instrument_any(inst, None, None, maker_fee, taker_fee, ts_init) {
Ok(Some(instrument_any)) => {
instruments.push(instrument_any);
}
Ok(None) => {
// Unsupported instrument type, skip silently
}
Err(e) => {
log::warn!("Failed to parse instrument {}: {e}", inst.inst_id);
}
}
}
Ok((instruments, inst_id_codes))
}
/// Requests a single instrument by `instrument_id` from OKX.
///
/// Fetches the instrument from the API, caches it, and returns it.
///
/// # Errors
///
/// This function will return an error if:
/// - The API request fails.
/// - The instrument is not found.
/// - Failed to parse instrument data.
pub async fn request_instrument(
&self,
instrument_id: InstrumentId,
) -> anyhow::Result<InstrumentAny> {
let symbol = instrument_id.symbol.as_str();
let instrument_type = okx_instrument_type_from_symbol(symbol);
let mut params = GetInstrumentsParamsBuilder::default();
params.inst_type(instrument_type);
params.inst_id(symbol);
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self
.inner
.get_instruments(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let raw_inst = resp
.first()
.ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not found"))?;
// Skip pre-open instruments which have incomplete/empty field values
if raw_inst.state == OKXInstrumentStatus::Preopen {
anyhow::bail!("Instrument {symbol} is in pre-open state");
}
let fee_rate_opt = {
let fee_params = GetTradeFeeParams {
inst_type: instrument_type,
uly: None,
inst_family: None,
};
match self.inner.get_trade_fee(fee_params).await {
Ok(rates) => rates.into_iter().next(),
Err(OKXHttpError::MissingCredentials) => {
log::debug!("Missing credentials for fee rates, using None");
None
}
Err(e) => {
log::warn!("Failed to fetch fee rates for {symbol}: {e}");
None
}
}
};
// OKX fee rate convention: positive = rebate, negative = commission
// Nautilus convention: negative = rebate, positive = commission
// Negate to convert between conventions
let (maker_fee, taker_fee) = if let Some(ref fee_rate) = fee_rate_opt {
let is_usdt_margined = raw_inst.ct_type == OKXContractType::Linear;
let (maker_str, taker_str) = if is_usdt_margined {
(&fee_rate.maker_u, &fee_rate.taker_u)
} else {
(&fee_rate.maker, &fee_rate.taker)
};
let maker = if maker_str.is_empty() {
None
} else {
Decimal::from_str(maker_str).ok().map(|v| -v)
};
let taker = if taker_str.is_empty() {
None
} else {
Decimal::from_str(taker_str).ok().map(|v| -v)
};
(maker, taker)
} else {
(None, None)
};
let ts_init = self.generate_ts_init();
let instrument = parse_instrument_any(raw_inst, None, None, maker_fee, taker_fee, ts_init)?
.ok_or_else(|| anyhow::anyhow!("Unsupported instrument type for {symbol}"))?;
self.cache_instrument(instrument.clone());
Ok(instrument)
}
/// Requests forward prices for OKX options using the option summary endpoint.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or no usable instrument family can be resolved.
pub async fn request_forward_prices(
&self,
underlying: &str,
instrument_id: Option<InstrumentId>,
) -> anyhow::Result<Vec<ForwardPrice>> {
let requests = self.resolve_forward_price_requests(underlying, instrument_id.as_ref())?;
let requested_symbol = instrument_id.as_ref().map(|id| id.symbol.inner());
let requested_instrument_id = instrument_id.as_ref();
let ts_init = self.generate_ts_init();
let mut forward_prices = Vec::new();
let mut seen_expiries = AHashSet::new();
for (inst_family, exp_time) in requests {
let summaries = self
.inner
.get_option_summary(GetOptionSummaryParams {
inst_family,
exp_time,
})
.await
.map_err(|e| anyhow::anyhow!(e))?;
for summary in summaries {
if summary.inst_type != OKXInstrumentType::Option {
continue;
}
if let Some(symbol) = requested_symbol
&& summary.inst_id != symbol
{
continue;
}
let forward_price = match Decimal::from_str(&summary.fwd_px) {
Ok(price) if !price.is_zero() => price,
Ok(_) => continue,
Err(e) => {
log::warn!(
"Skipping invalid OKX forward price for {}: {e}",
summary.inst_id
);
continue;
}
};
if requested_symbol.is_none() {
let expiry_key = Self::option_summary_expiry_key(summary.inst_id.as_str())?;
if !seen_expiries.insert(expiry_key) {
continue;
}
}
let ts_event =
UnixNanos::from(summary.ts.saturating_mul(NANOSECONDS_IN_MILLISECOND));
let instrument_id = if let Some(inst_id) = requested_instrument_id {
*inst_id
} else {
parse_instrument_id(summary.inst_id)
};
forward_prices.push(ForwardPrice::new(
instrument_id,
forward_price,
Some(summary.uly.to_string()),
ts_event,
ts_init,
));
}
}
Ok(forward_prices)
}
/// Requests the latest mark price for the `instrument_type` from OKX.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or no mark price is returned.
pub async fn request_mark_price(
&self,
instrument_id: InstrumentId,
) -> anyhow::Result<MarkPriceUpdate> {
let mut params = GetMarkPriceParamsBuilder::default();
params.inst_id(instrument_id.symbol.inner());
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self
.inner
.get_mark_price(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let raw = resp
.first()
.ok_or_else(|| anyhow::anyhow!("No mark price returned from OKX"))?;
let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
let ts_init = self.generate_ts_init();
let mark_price =
parse_mark_price_update(raw, instrument_id, inst.price_precision(), ts_init)
.map_err(|e| anyhow::anyhow!(e))?;
Ok(mark_price)
}
fn resolve_forward_price_requests(
&self,
underlying: &str,
instrument_id: Option<&InstrumentId>,
) -> anyhow::Result<Vec<(String, Option<String>)>> {
if let Some(inst_id) = instrument_id {
let symbol = inst_id.symbol.inner().as_str();
let inst_family = extract_inst_family(symbol)?.to_string();
let exp_time = Self::option_summary_exp_time(symbol)?;
return Ok(vec![(inst_family, exp_time)]);
}
let underlying = Ustr::from(underlying);
let mut families = AHashSet::new();
for instrument in self.instruments_cache.load().values() {
let InstrumentAny::CryptoOption(option) = instrument else {
continue;
};
if option.underlying.code != underlying {
continue;
}
let inst_family = extract_inst_family(option.id.symbol.inner().as_str())?;
families.insert(inst_family.to_string());
}
let mut families: Vec<String> = families.into_iter().collect();
families.sort_unstable();
anyhow::ensure!(
!families.is_empty(),
"No cached OKX option families for underlying {underlying}; provide a sample instrument or pre-load option instruments"
);
Ok(families.into_iter().map(|family| (family, None)).collect())
}
fn option_summary_expiry_key(symbol: &str) -> anyhow::Result<String> {
let parts: Vec<&str> = symbol.split('-').collect();
anyhow::ensure!(
parts.len() >= 5,
"Expected OKX option symbol with expiry, received {symbol}"
);
Ok(format!("{}-{}-{}", parts[0], parts[1], parts[2]))
}
fn option_summary_exp_time(symbol: &str) -> anyhow::Result<Option<String>> {
let parts: Vec<&str> = symbol.split('-').collect();
anyhow::ensure!(
parts.len() >= 5,
"Expected OKX option symbol with expiry, received {symbol}"
);
Ok(Some(parts[2].to_string()))
}
/// Requests the latest index price for the `instrument_id` from OKX.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or no index price is returned.
pub async fn request_index_price(
&self,
instrument_id: InstrumentId,
) -> anyhow::Result<IndexPriceUpdate> {
// Index tickers endpoint requires base pair format (e.g., BTC-USDT)
let symbol = instrument_id.symbol.inner();
let (base, quote) = parse_base_quote_from_symbol(symbol.as_str())?;
let inst_id = format!("{base}-{quote}");
let mut params = GetIndexTickerParamsBuilder::default();
params.inst_id(Ustr::from(&inst_id));
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self
.inner
.get_index_tickers(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let raw = resp
.first()
.ok_or_else(|| anyhow::anyhow!("No index price returned from OKX"))?;
let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
let ts_init = self.generate_ts_init();
let index_price =
parse_index_price_update(raw, instrument_id, inst.price_precision(), ts_init)
.map_err(|e| anyhow::anyhow!(e))?;
Ok(index_price)
}
/// Requests an order book snapshot for the `instrument_id`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or book parsing fails.
pub async fn request_book_snapshot(
&self,
instrument_id: InstrumentId,
depth: Option<u32>,
) -> anyhow::Result<OrderBook> {
let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
let price_precision = inst.price_precision();
let size_precision = inst.size_precision();
let params = GetOrderBookParams {
inst_id: instrument_id.symbol.to_string(),
sz: depth,
};
let resp = self
.inner
.get_order_book(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let snapshot = resp
.first()
.ok_or_else(|| anyhow::anyhow!("No order book returned from OKX"))?;
let ts_event = UnixNanos::from(snapshot.ts * NANOSECONDS_IN_MILLISECOND);
let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
for (i, level) in snapshot.bids.iter().enumerate() {
let price = parse_price(&level.0, price_precision)?;
let size = parse_quantity(&level.1, size_precision)?;
let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
book.add(order, 0, i as u64, ts_event);
}
let bids_len = snapshot.bids.len();
for (i, level) in snapshot.asks.iter().enumerate() {
let price = parse_price(&level.0, price_precision)?;
let size = parse_quantity(&level.1, size_precision)?;
let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
book.add(order, 0, (bids_len + i) as u64, ts_event);
}
log::info!(
"Fetched order book for {} with {} bids and {} asks",
instrument_id,
snapshot.bids.len(),
snapshot.asks.len(),
);
Ok(book)
}
/// Requests an order book snapshot as `OrderBookDeltas` for the `instrument_id`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or parsing fails.
pub async fn request_orderbook_snapshot(
&self,
instrument_id: InstrumentId,
depth: Option<u32>,
) -> anyhow::Result<OrderBookDeltas> {
let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
let price_precision = inst.price_precision();
let size_precision = inst.size_precision();
let params = GetOrderBookParams {
inst_id: instrument_id.symbol.to_string(),
sz: depth,
};
let resp = self
.inner
.get_order_book(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let snapshot = resp
.first()
.ok_or_else(|| anyhow::anyhow!("No order book returned from OKX"))?;
let ts_event = UnixNanos::from(snapshot.ts * NANOSECONDS_IN_MILLISECOND);
let total_levels = snapshot.bids.len() + snapshot.asks.len();
let mut deltas = Vec::with_capacity(total_levels + 1);
let mut clear = OrderBookDelta::clear(instrument_id, 0, ts_event, ts_event);
if total_levels == 0 {
clear.flags |= RecordFlag::F_LAST as u8;
}
deltas.push(clear);
let mut processed = 0_usize;
for (i, level) in snapshot.bids.iter().enumerate() {
let price = parse_price(&level.0, price_precision)?;
let size = parse_quantity(&level.1, size_precision)?;
let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
processed += 1;
let mut flags = RecordFlag::F_SNAPSHOT as u8;
if processed == total_levels {
flags |= RecordFlag::F_LAST as u8;
}
deltas.push(OrderBookDelta::new(
instrument_id,
BookAction::Add,
order,
flags,
0,
ts_event,
ts_event,
));
}
let bids_len = snapshot.bids.len();
for (i, level) in snapshot.asks.iter().enumerate() {
let price = parse_price(&level.0, price_precision)?;
let size = parse_quantity(&level.1, size_precision)?;
let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
processed += 1;
let mut flags = RecordFlag::F_SNAPSHOT as u8;
if processed == total_levels {
flags |= RecordFlag::F_LAST as u8;
}
deltas.push(OrderBookDelta::new(
instrument_id,
BookAction::Add,
order,
flags,
0,
ts_event,
ts_event,
));
}
log::info!(
"Fetched order book snapshot for {} with {} bids and {} asks",
instrument_id,
snapshot.bids.len(),
snapshot.asks.len(),
);
OrderBookDeltas::new_checked(instrument_id, deltas)
.context("failed to assemble OrderBookDeltas from OKX snapshot")
}
/// Requests historical funding rates for the `instrument_id`.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or parsing fails.
pub async fn request_funding_rates(
&self,
instrument_id: InstrumentId,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
limit: Option<u32>,
) -> anyhow::Result<Vec<FundingRateUpdate>> {
let mut params = GetFundingRateHistoryParams {
inst_id: instrument_id.symbol.to_string(),
..Default::default()
};
// OKX uses "before" for newer-than and "after" for older-than
if let Some(start) = start {
params.before = Some(start.timestamp_millis().to_string());
}
if let Some(end) = end {
params.after = Some(end.timestamp_millis().to_string());
}
params.limit = limit;
let resp = self
.inner
.get_funding_rate_history(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let mut rates = Vec::with_capacity(resp.len());
for window in resp.windows(2) {
let raw = &window[0];
let interval_millis = raw
.funding_time
.checked_sub(window[1].funding_time)
.context("funding interval negative, funding rates out of order")?;
let rate = parse_funding_rate(raw, instrument_id, Some(interval_millis))?;
rates.push(rate);
}
if let Some(last_raw) = resp.last() {
// oldest funding update has no previous one to compute interval
let rate = parse_funding_rate(last_raw, instrument_id, None)?;
rates.push(rate);
}
// OKX returns newest-first; reverse to chronological order so that
// cache.add_funding_rates (which push_fronts) leaves the newest at front
rates.reverse();
log::info!(
"Fetched {} funding rates for {}",
rates.len(),
instrument_id,
);
Ok(rates)
}
/// Requests trades for the `instrument_id` and `start` -> `end` time range.
///
/// # Errors
///
/// Returns an error if the HTTP request fails or trade parsing fails.
pub async fn request_trades(
&self,
instrument_id: InstrumentId,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
limit: Option<u32>,
) -> anyhow::Result<Vec<TradeTick>> {
const OKX_TRADES_MAX_LIMIT: u32 = 100;
const MAX_PAGES: usize = 500;
const MAX_CONSECUTIVE_EMPTY: usize = 3;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Latest,
Backward,
Range,
}
let limit = if limit == Some(0) { None } else { limit };
if let (Some(s), Some(e)) = (start, end) {
anyhow::ensure!(s < e, "Invalid time range: start={s:?} end={e:?}");
}
let now = Utc::now();
if let Some(s) = start
&& s > now
{
return Ok(Vec::new());
}
let end = if let Some(e) = end
&& e > now
{
Some(now)
} else {
end
};
let mode = match (start, end) {
(None, None) => Mode::Latest,
(Some(_), None) => Mode::Backward,
(None, Some(_)) => Mode::Backward,
(Some(_), Some(_)) => Mode::Range,
};
let start_ms = start.map(|s| s.timestamp_millis());
let end_ms = end.map(|e| e.timestamp_millis());
let ts_init = self.generate_ts_init();
let inst = self.instrument_from_cache(instrument_id.symbol.inner())?;
// Historical pagination walks backwards using trade IDs, OKX does not honour timestamps for
// standalone `before` requests (type=2)
if matches!(mode, Mode::Backward | Mode::Range) {
let mut before_trade_id: Option<String> = None;
let mut pages = 0usize;
let mut page_results: Vec<Vec<TradeTick>> = Vec::new();
let mut seen_trades: AHashSet<(String, i64)> = AHashSet::new();
let mut unique_count = 0usize;
let mut consecutive_empty_pages = 0usize;
// Only apply default limit when there's no start boundary
// (start provides a natural stopping point, end alone allows infinite backward pagination)
let effective_limit = if start.is_some() {
limit.unwrap_or(u32::MAX)
} else {
limit.unwrap_or(OKX_TRADES_MAX_LIMIT)
};
log::debug!(
"Starting trades pagination: mode={mode:?}, start={start:?}, end={end:?}, limit={limit:?}, effective_limit={effective_limit}"
);
loop {
if pages >= MAX_PAGES {
log::warn!("Hit MAX_PAGES limit of {MAX_PAGES}");
break;
}
if effective_limit < u32::MAX && unique_count >= effective_limit as usize {
log::debug!("Reached effective limit: unique_count={unique_count}");
break;
}
let remaining = (effective_limit as usize).saturating_sub(unique_count);
let page_cap = remaining.min(OKX_TRADES_MAX_LIMIT as usize) as u32;
log::debug!(
"Requesting page {}: before_id={:?}, page_cap={}, unique_count={}",
pages + 1,
before_trade_id,
page_cap,
unique_count
);
let mut params_builder = GetTradesParamsBuilder::default();
params_builder
.inst_id(instrument_id.symbol.inner())
.limit(page_cap)
.pagination_type(1);
// Use 'after' to get older trades (OKX API: after=cursor means < cursor)
if let Some(ref before_id) = before_trade_id {
params_builder.after(before_id.clone());
}
let params = params_builder.build().map_err(anyhow::Error::new)?;
let raw = self
.inner
.get_history_trades(params)
.await
.map_err(anyhow::Error::new)?;
log::debug!("Received {} raw trades from API", raw.len());
if let (Some(first), Some(last)) = (raw.first(), raw.last()) {
log::debug!(
"Raw response trade ID range: first={} (newest), last={} (oldest)",
first.trade_id,
last.trade_id,
);
}
if raw.is_empty() {
log::debug!("API returned empty page, stopping pagination");
break;
}
pages += 1;
let mut page_trades: Vec<TradeTick> = Vec::with_capacity(raw.len());
let mut hit_start_boundary = false;
let mut filtered_out = 0usize;
let mut duplicates = 0usize;
for r in &raw {
match parse_trade_tick(
r,
instrument_id,
inst.price_precision(),
inst.size_precision(),
ts_init,
) {
Ok(trade) => {
let ts_ms = trade.ts_event.as_i64() / 1_000_000;
if let Some(e_ms) = end_ms
&& ts_ms > e_ms
{
filtered_out += 1;
continue;
}
if let Some(s_ms) = start_ms
&& ts_ms < s_ms
{
hit_start_boundary = true;
filtered_out += 1;
break;
}
let trade_key = (trade.trade_id.to_string(), trade.ts_event.as_i64());
if seen_trades.insert(trade_key) {
unique_count += 1;
page_trades.push(trade);
} else {
duplicates += 1;
}
}
Err(e) => log::error!("{e}"),
}
}
log::debug!(
"Page {} processed: {} trades kept, {} filtered out, {} duplicates, hit_start_boundary={}",
pages,
page_trades.len(),
filtered_out,
duplicates,
hit_start_boundary
);
// Extract oldest unique trade ID for next page cursor
let oldest_trade_id = if page_trades.is_empty() {
// Only apply consecutive empty guard if we've already collected some trades
// This allows historical backfills to paginate through empty prelude
if unique_count > 0 {
consecutive_empty_pages += 1;
if consecutive_empty_pages >= MAX_CONSECUTIVE_EMPTY {
log::debug!(
"Stopping: {consecutive_empty_pages} consecutive pages with no trades in range after collecting {unique_count} trades"
);
break;
}
}
// No unique trades on page, use raw response for cursor
raw.last().map(|t| {
let id = t.trade_id.to_string();
log::debug!(
"Setting cursor from raw response (no unique trades): oldest_id={id}"
);
id
})
} else {
// Use oldest deduplicated trade ID before reversing
let oldest_id = page_trades.last().map(|t| {
let id = t.trade_id.to_string();
log::debug!(
"Setting cursor from deduplicated trades: oldest_id={}, ts_event={}",
id,
t.ts_event.as_i64()
);
id
});
page_trades.reverse();
page_results.push(page_trades);
consecutive_empty_pages = 0;
oldest_id
};
if let Some(ref old_id) = before_trade_id
&& oldest_trade_id.as_ref() == Some(old_id)
{
break;
}
if oldest_trade_id.is_none() {
break;
}
before_trade_id = oldest_trade_id;
if hit_start_boundary {
break;
}
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
}
log::debug!(
"Pagination complete: {pages} pages, {unique_count} unique trades collected"
);
let mut out: Vec<TradeTick> = Vec::new();
for page in page_results.into_iter().rev() {
out.extend(page);
}
// Deduplicate by (trade_id, ts_event) composite key
let mut dedup_keys = AHashSet::new();
let pre_dedup_len = out.len();
out.retain(|trade| {
dedup_keys.insert((trade.trade_id.to_string(), trade.ts_event.as_i64()))
});
if out.len() < pre_dedup_len {
log::debug!(
"Removed {} duplicate trades during final dedup",
pre_dedup_len - out.len()
);
}
if let Some(lim) = limit
&& lim > 0
&& out.len() > lim as usize
{
let excess = out.len() - lim as usize;
log::debug!("Trimming {excess} oldest trades to respect limit={lim}");
out.drain(0..excess);
}
log::debug!("Returning {} trades", out.len());
return Ok(out);
}
let req_limit = limit
.unwrap_or(OKX_TRADES_MAX_LIMIT)
.min(OKX_TRADES_MAX_LIMIT);
let params = GetTradesParamsBuilder::default()
.inst_id(instrument_id.symbol.inner())
.limit(req_limit)
.build()
.map_err(anyhow::Error::new)?;
let raw = self
.inner
.get_history_trades(params)
.await
.map_err(anyhow::Error::new)?;
let mut trades: Vec<TradeTick> = Vec::with_capacity(raw.len());
for r in &raw {
match parse_trade_tick(
r,
instrument_id,
inst.price_precision(),
inst.size_precision(),
ts_init,
) {
Ok(trade) => trades.push(trade),
Err(e) => log::error!("{e}"),
}
}
// OKX returns newest-first, reverse to oldest-first
trades.reverse();
if let Some(lim) = limit
&& lim > 0
&& trades.len() > lim as usize
{
trades.drain(0..trades.len() - lim as usize);
}
Ok(trades)
}
/// Requests historical bars for the given bar type and time range.
///
/// The aggregation source must be `EXTERNAL`. Time range validation ensures start < end.
/// Returns bars sorted oldest to newest.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # Endpoint Selection
///
/// The OKX API has different endpoints with different limits:
/// - Regular endpoint (`/api/v5/market/candles`): ≤ 300 rows/call, ≤ 40 req/2s
/// - Used when: start is None OR age ≤ 100 days
/// - History endpoint (`/api/v5/market/history-candles`): ≤ 100 rows/call, ≤ 20 req/2s
/// - Used when: start is Some AND age > 100 days
///
/// Age is calculated as `Utc::now() - start` at the time of the first request.
///
/// # Supported Aggregations
///
/// Maps to OKX bar query parameter:
/// - `Second` → `{n}s`
/// - `Minute` → `{n}m`
/// - `Hour` → `{n}H`
/// - `Day` → `{n}D`
/// - `Week` → `{n}W`
/// - `Month` → `{n}M`
///
/// # Pagination
///
/// - Uses `before` parameter for backwards pagination
/// - Pages backwards from end time (or now) to start time
/// - Stops when: limit reached, time window covered, or API returns empty
/// - Rate limit safety: ≥ 50ms between requests
///
/// # References
///
/// - <https://tr.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks>
/// - <https://tr.okx.com/docs-v5/en/#order-book-trading-market-data-get-candlesticks-history>
pub async fn request_bars(
&self,
bar_type: BarType,
start: Option<DateTime<Utc>>,
mut end: Option<DateTime<Utc>>,
limit: Option<u32>,
) -> anyhow::Result<Vec<Bar>> {
const HISTORY_SPLIT_DAYS: i64 = 100;
const MAX_PAGES_SOFT: usize = 500;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
Latest,
Backward,
Range,
}
let limit = if limit == Some(0) { None } else { limit };
anyhow::ensure!(
bar_type.aggregation_source() == AggregationSource::External,
"Only EXTERNAL aggregation is supported"
);
if let (Some(s), Some(e)) = (start, end) {
anyhow::ensure!(s < e, "Invalid time range: start={s:?} end={e:?}");
}
let now = Utc::now();
if let Some(s) = start
&& s > now
{
return Ok(Vec::new());
}
if let Some(e) = end
&& e > now
{
end = Some(now);
}
let spec = bar_type.spec();
let step = spec.step.get();
let bar_param = match spec.aggregation {
BarAggregation::Second => format!("{step}s"),
BarAggregation::Minute => format!("{step}m"),
BarAggregation::Hour => format!("{step}H"),
BarAggregation::Day => format!("{step}D"),
BarAggregation::Week => format!("{step}W"),
BarAggregation::Month => format!("{step}M"),
a => anyhow::bail!("OKX does not support {a:?} aggregation"),
};
let slot_ms: i64 = match spec.aggregation {
BarAggregation::Second => (step as i64) * 1_000,
BarAggregation::Minute => (step as i64) * 60_000,
BarAggregation::Hour => (step as i64) * 3_600_000,
BarAggregation::Day => (step as i64) * 86_400_000,
BarAggregation::Week => (step as i64) * 7 * 86_400_000,
BarAggregation::Month => (step as i64) * 30 * 86_400_000,
_ => unreachable!("Unsupported aggregation should have been caught above"),
};
let slot_ns: i64 = slot_ms * 1_000_000;
let mode = match (start, end) {
(None, None) => Mode::Latest,
(Some(_), None) => Mode::Backward, // Changed: when only start is provided, work backward from now
(None, Some(_)) => Mode::Backward,
(Some(_), Some(_)) => Mode::Range,
};
let start_ns = start.and_then(|s| s.timestamp_nanos_opt());
let end_ns = end.and_then(|e| e.timestamp_nanos_opt());
// Floor start and ceiling end to bar boundaries for cleaner API requests
let start_ms = start.map(|s| {
let ms = s.timestamp_millis();
if slot_ms > 0 {
(ms / slot_ms) * slot_ms // Floor to nearest bar boundary
} else {
ms
}
});
let end_ms = end.map(|e| {
let ms = e.timestamp_millis();
if slot_ms > 0 {
((ms + slot_ms - 1) / slot_ms) * slot_ms // Ceiling to nearest bar boundary
} else {
ms
}
});
let now_ms = now.timestamp_millis();
let symbol = bar_type.instrument_id().symbol;
let inst = self.instrument_from_cache(symbol.inner())?;
let mut out: Vec<Bar> = Vec::new();
let mut pages = 0usize;
// IMPORTANT: OKX API has COUNTER-INTUITIVE semantics (same for bars and trades):
// - after=X returns records with timestamp < X (upper bound, despite the name!)
// - before=X returns records with timestamp > X (lower bound, despite the name!)
// For Range [start, end], use: before=start (lower bound), after=end (upper bound)
let mut after_ms: Option<i64> = match mode {
Mode::Range => end_ms.or(Some(now_ms)), // Upper bound: bars < end
_ => None,
};
let mut before_ms: Option<i64> = match mode {
Mode::Backward => end_ms.map(|v| v.saturating_sub(1)),
Mode::Range => start_ms, // Lower bound: bars > start
Mode::Latest => None,
};
// For Range mode, we'll paginate backwards like Backward mode
let mut forward_prepend_mode = matches!(mode, Mode::Range);
// Adjust before_ms to ensure we get data from the API
// OKX API might not have bars for the very recent past
// This handles both explicit end=now and the actor layer setting end=now when it's None
if matches!(mode, Mode::Backward | Mode::Range)
&& let Some(b) = before_ms
{
// OKX endpoints have different data availability windows:
// - Regular endpoint: has most recent data but limited depth
// - History endpoint: has deep history but lags behind current time
// Use a small buffer to avoid the "dead zone"
let buffer_ms = slot_ms.max(60_000); // At least 1 minute or 1 bar
if b >= now_ms.saturating_sub(buffer_ms) {
before_ms = Some(now_ms.saturating_sub(buffer_ms));
}
}
let mut have_latest_first_page = false;
let mut progressless_loops = 0u8;
loop {
if let Some(lim) = limit
&& lim > 0
&& out.len() >= lim as usize
{
break;
}
if pages >= MAX_PAGES_SOFT {
break;
}
let pivot_ms = if let Some(a) = after_ms {
a
} else if let Some(b) = before_ms {
b
} else {
now_ms
};
// Choose endpoint based on how old the data is:
// - Use regular endpoint for recent data (< 1 hour old)
// - Use history endpoint for older data (> 1 hour old)
// This avoids the "gap" where history endpoint has no recent data
// and regular endpoint has limited depth
let age_ms = now_ms.saturating_sub(pivot_ms);
let age_hours = age_ms / (60 * 60 * 1000);
let using_history = age_hours > 1; // Use history if data is > 1 hour old
let page_ceiling = if using_history { 100 } else { 300 };
let remaining = limit
.filter(|&l| l > 0) // Treat limit=0 as no limit
.map_or(page_ceiling, |l| (l as usize).saturating_sub(out.len()));
let page_cap = remaining.min(page_ceiling);
let mut p = GetCandlesticksParamsBuilder::default();
p.inst_id(symbol.as_str())
.bar(&bar_param)
.limit(page_cap as u32);
// Track whether this planned request uses BEFORE or AFTER.
let mut req_used_before = false;
match mode {
Mode::Latest => {
if have_latest_first_page && let Some(b) = before_ms {
p.before_ms(b);
req_used_before = true;
}
}
Mode::Backward => {
// Use 'after' to get older bars (OKX API: after=cursor means < cursor)
if let Some(b) = before_ms {
p.after_ms(b);
}
}
Mode::Range => {
// For Range mode, use both after and before to specify the full range
// This is much more efficient than pagination
if let Some(a) = after_ms {
p.after_ms(a);
}
if let Some(b) = before_ms {
p.before_ms(b);
req_used_before = true;
}
}
}
let params = p.build().map_err(anyhow::Error::new)?;
let mut raw = if using_history {
self.inner
.get_history_candles(params.clone())
.await
.map_err(anyhow::Error::new)?
} else {
self.inner
.get_candles(params.clone())
.await
.map_err(anyhow::Error::new)?
};
// --- Fallbacks on empty page ---
if raw.is_empty() {
// LATEST: retry same cursor via history, then step back a page-interval before giving up
if matches!(mode, Mode::Latest)
&& have_latest_first_page
&& !using_history
&& let Some(b) = before_ms
{
let mut p2 = GetCandlesticksParamsBuilder::default();
p2.inst_id(symbol.as_str())
.bar(&bar_param)
.limit(page_cap as u32);
p2.before_ms(b);
let params2 = p2.build().map_err(anyhow::Error::new)?;
let raw2 = self
.inner
.get_history_candles(params2)
.await
.map_err(anyhow::Error::new)?;
if raw2.is_empty() {
// Step back one page interval and retry loop
let jump = (page_cap as i64).saturating_mul(slot_ms.max(1));
before_ms = Some(b.saturating_sub(jump));
progressless_loops = progressless_loops.saturating_add(1);
if progressless_loops >= 3 {
break;
}
continue;
} else {
raw = raw2;
}
}
// Range mode doesn't need special bootstrap - it uses the normal flow with before_ms set
// If still empty: for Range after first page, try a single backstep window using BEFORE
if raw.is_empty() && matches!(mode, Mode::Range) && pages > 0 {
let backstep_ms = (page_cap as i64).saturating_mul(slot_ms.max(1));
let pivot_back = after_ms.unwrap_or(now_ms).saturating_sub(backstep_ms);
let mut p2 = GetCandlesticksParamsBuilder::default();
p2.inst_id(symbol.as_str())
.bar(&bar_param)
.limit(page_cap as u32)
.before_ms(pivot_back);
let params2 = p2.build().map_err(anyhow::Error::new)?;
let raw2 = if (now_ms.saturating_sub(pivot_back)) / (24 * 60 * 60 * 1000)
> HISTORY_SPLIT_DAYS
{
self.inner.get_history_candles(params2).await
} else {
self.inner.get_candles(params2).await
}
.map_err(anyhow::Error::new)?;
if raw2.is_empty() {
break;
} else {
raw = raw2;
forward_prepend_mode = true;
req_used_before = true;
}
}
// First LATEST page empty: jump back >100d to force history, then continue loop
if raw.is_empty()
&& matches!(mode, Mode::Latest)
&& !have_latest_first_page
&& !using_history
{
let jump_days_ms = (HISTORY_SPLIT_DAYS + 1) * 86_400_000;
before_ms = Some(now_ms.saturating_sub(jump_days_ms));
have_latest_first_page = true;
continue;
}
// Still empty for any other case? Just break.
if raw.is_empty() {
break;
}
}
// --- end fallbacks ---
pages += 1;
// Parse, oldest → newest
let ts_init = self.generate_ts_init();
let mut page: Vec<Bar> = Vec::with_capacity(raw.len());
for r in &raw {
page.push(parse_candlestick(
r,
bar_type,
inst.price_precision(),
inst.size_precision(),
ts_init,
)?);
}
page.reverse();
let page_oldest_ms = page.first().map(|b| b.ts_event.as_i64() / 1_000_000);
let page_newest_ms = page.last().map(|b| b.ts_event.as_i64() / 1_000_000);
// Range filter (inclusive)
// For Range mode, if we have no bars yet and this is an early page,
// be more tolerant with the start boundary to handle gaps in data
let mut filtered: Vec<Bar> = if matches!(mode, Mode::Range)
&& out.is_empty()
&& pages < 2
{
// On first pages of Range mode with no data yet, include the most recent bar
// even if it's slightly before our start time (within 2 bar periods)
// BUT we want ALL bars in the page that are within our range
let tolerance_ns = slot_ns * 2; // Allow up to 2 bar periods before start
// Debug: log the page range
if let (Some(first), Some(last)) = (page.first(), page.last()) {
log::debug!(
"Range mode bootstrap page: {} bars from {} to {}, filtering with start={:?} end={:?}",
page.len(),
first.ts_event.as_i64() / 1_000_000,
last.ts_event.as_i64() / 1_000_000,
start_ms,
end_ms,
);
}
let result: Vec<Bar> = page
.clone()
.into_iter()
.filter(|b| {
let ts = b.ts_event.as_i64();
// Accept bars from (start - tolerance) to end
let ok_after =
start_ns.is_none_or(|sns| ts >= sns.saturating_sub(tolerance_ns));
let ok_before = end_ns.is_none_or(|ens| ts <= ens);
ok_after && ok_before
})
.collect();
result
} else {
// Normal filtering
page.clone()
.into_iter()
.filter(|b| {
let ts = b.ts_event.as_i64();
let ok_after = start_ns.is_none_or(|sns| ts >= sns);
let ok_before = end_ns.is_none_or(|ens| ts <= ens);
ok_after && ok_before
})
.collect()
};
if !page.is_empty() && filtered.is_empty() {
// For Range mode, if all bars are before our start time, there's no point continuing
if matches!(mode, Mode::Range)
&& !forward_prepend_mode
&& let (Some(newest_ms), Some(start_ms)) = (page_newest_ms, start_ms)
&& newest_ms < start_ms.saturating_sub(slot_ms * 2)
{
// Bars are too old (more than 2 bar periods before start), stop
break;
}
}
// Track contribution for progress guard
let contribution;
if out.is_empty() {
contribution = filtered.len();
out = filtered;
} else {
match mode {
Mode::Backward | Mode::Latest => {
if let Some(first) = out.first() {
filtered.retain(|b| b.ts_event < first.ts_event);
}
contribution = filtered.len();
if contribution != 0 {
let mut new_out = Vec::with_capacity(out.len() + filtered.len());
new_out.extend_from_slice(&filtered);
new_out.extend_from_slice(&out);
out = new_out;
}
}
Mode::Range => {
if forward_prepend_mode || req_used_before {
// We are backfilling older pages: prepend them.
if let Some(first) = out.first() {
filtered.retain(|b| b.ts_event < first.ts_event);
}
contribution = filtered.len();
if contribution != 0 {
let mut new_out = Vec::with_capacity(out.len() + filtered.len());
new_out.extend_from_slice(&filtered);
new_out.extend_from_slice(&out);
out = new_out;
}
} else {
// Normal forward: append newer pages.
if let Some(last) = out.last() {
filtered.retain(|b| b.ts_event > last.ts_event);
}
contribution = filtered.len();
out.extend(filtered);
}
}
}
}
// Duplicate-window mitigation for Latest/Backward/Range
if contribution == 0
&& matches!(mode, Mode::Latest | Mode::Backward | Mode::Range)
&& let Some(b) = before_ms
{
let jump = (page_cap as i64).saturating_mul(slot_ms.max(1));
let new_b = b.saturating_sub(jump);
if new_b != b {
before_ms = Some(new_b);
}
}
if contribution == 0 {
progressless_loops = progressless_loops.saturating_add(1);
if progressless_loops >= 3 {
break;
}
} else {
progressless_loops = 0;
// Advance cursors only when we made progress
match mode {
Mode::Latest | Mode::Backward => {
if let Some(oldest) = page_oldest_ms {
before_ms = Some(oldest.saturating_sub(1));
have_latest_first_page = true;
} else {
break;
}
}
Mode::Range => {
if forward_prepend_mode || req_used_before {
if let Some(oldest) = page_oldest_ms {
// Move back by at least one bar period to avoid getting the same data
let jump_back = slot_ms.max(60_000); // At least 1 minute
before_ms = Some(oldest.saturating_sub(jump_back));
after_ms = None;
} else {
break;
}
} else if let Some(newest) = page_newest_ms {
after_ms = Some(newest.saturating_add(1));
before_ms = None;
} else {
break;
}
}
}
}
// Stop conditions
if let Some(lim) = limit
&& lim > 0
&& out.len() >= lim as usize
{
break;
}
if let Some(ens) = end_ns
&& let Some(last) = out.last()
&& last.ts_event.as_i64() >= ens
{
break;
}
if let Some(sns) = start_ns
&& let Some(first) = out.first()
&& (matches!(mode, Mode::Backward) || forward_prepend_mode)
&& first.ts_event.as_i64() <= sns
{
// For Range mode, check if we have all bars up to the end time
if matches!(mode, Mode::Range) {
// Don't stop if we haven't reached the end time yet
if let Some(ens) = end_ns
&& let Some(last) = out.last()
{
let last_ts = last.ts_event.as_i64();
if last_ts < ens {
// We have bars before start but haven't reached end, need to continue forward
// Switch from backward to forward pagination
forward_prepend_mode = false;
after_ms = Some((last_ts / 1_000_000).saturating_add(1));
before_ms = None;
continue;
}
}
}
break;
}
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
}
// Final rescue for FORWARD/RANGE when nothing gathered
if out.is_empty() && matches!(mode, Mode::Range) {
let pivot = end_ms.unwrap_or(now_ms.saturating_sub(1));
let hist = (now_ms.saturating_sub(pivot)) / (24 * 60 * 60 * 1000) > HISTORY_SPLIT_DAYS;
let mut p = GetCandlesticksParamsBuilder::default();
p.inst_id(symbol.as_str())
.bar(&bar_param)
.limit(300)
.before_ms(pivot);
let params = p.build().map_err(anyhow::Error::new)?;
let raw = if hist {
self.inner.get_history_candles(params).await
} else {
self.inner.get_candles(params).await
}
.map_err(anyhow::Error::new)?;
if !raw.is_empty() {
let ts_init = self.generate_ts_init();
let mut page: Vec<Bar> = Vec::with_capacity(raw.len());
for r in &raw {
page.push(parse_candlestick(
r,
bar_type,
inst.price_precision(),
inst.size_precision(),
ts_init,
)?);
}
page.reverse();
out = page
.into_iter()
.filter(|b| {
let ts = b.ts_event.as_i64();
let ok_after = start_ns.is_none_or(|sns| ts >= sns);
let ok_before = end_ns.is_none_or(|ens| ts <= ens);
ok_after && ok_before
})
.collect();
}
}
// Trim against end bound if needed (keep ≤ end)
if let Some(ens) = end_ns {
while out.last().is_some_and(|b| b.ts_event.as_i64() > ens) {
out.pop();
}
}
// Clamp first bar for Range when using forward pagination
if matches!(mode, Mode::Range)
&& !forward_prepend_mode
&& let Some(sns) = start_ns
{
let lower = sns.saturating_sub(slot_ns);
while out.first().is_some_and(|b| b.ts_event.as_i64() < lower) {
out.remove(0);
}
}
// Keep the most recent N bars when limit is specified
if let Some(lim) = limit
&& lim > 0
&& out.len() > lim as usize
{
let start = out.len() - lim as usize;
out.drain(..start);
}
Ok(out)
}
/// Requests historical order status reports for the given parameters.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// - <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-7-days>.
/// - <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-order-history-last-3-months>.
#[expect(clippy::too_many_arguments)]
pub async fn request_order_status_reports(
&self,
account_id: AccountId,
instrument_type: Option<OKXInstrumentType>,
instrument_id: Option<InstrumentId>,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
open_only: bool,
limit: Option<u32>,
) -> anyhow::Result<Vec<OrderStatusReport>> {
let instrument_type = if let Some(instrument_type) = instrument_type {
instrument_type
} else {
let instrument_id = instrument_id.ok_or_else(|| {
anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
})?;
let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
okx_instrument_type(&instrument)?
};
let mut history_base = GetOrderHistoryParamsBuilder::default();
history_base.inst_type(instrument_type);
if let Some(instrument_id) = instrument_id.as_ref() {
history_base.inst_id(instrument_id.symbol.inner().to_string());
}
let history_base = history_base.build().map_err(|e| anyhow::anyhow!(e))?;
let mut pending_base = GetOrderListParamsBuilder::default();
pending_base.inst_type(instrument_type);
if let Some(instrument_id) = instrument_id.as_ref() {
pending_base.inst_id(instrument_id.symbol.inner().to_string());
}
let pending_base = pending_base.build().map_err(|e| anyhow::anyhow!(e))?;
let combined_resp = if open_only {
self.paginate_orders_pending(&pending_base, limit).await?
} else {
let (history, pending) = tokio::try_join!(
self.paginate_orders_history(&history_base, limit),
self.paginate_orders_pending(&pending_base, limit),
)?;
let mut combined_resp = history;
combined_resp.extend(pending);
combined_resp
};
// Prepare time range filter
let start_ns = start.map(UnixNanos::from);
let end_ns = end.map(UnixNanos::from);
let ts_init = self.generate_ts_init();
let mut reports = Vec::with_capacity(combined_resp.len());
// Use a seen filter in case pending orders are within the histories "2hr reserve window"
let mut seen: AHashSet<String> = AHashSet::new();
for order in combined_resp {
let seen_key = if !order.cl_ord_id.is_empty() {
order.cl_ord_id.as_str().to_string()
} else if let Some(algo_cl_ord_id) = order
.algo_cl_ord_id
.as_ref()
.filter(|value| !value.as_str().is_empty())
{
algo_cl_ord_id.as_str().to_string()
} else if let Some(algo_id) = order
.algo_id
.as_ref()
.filter(|value| !value.as_str().is_empty())
{
algo_id.as_str().to_string()
} else {
order.ord_id.as_str().to_string()
};
if !seen.insert(seen_key) {
continue; // Reserved pending already reported
}
let Ok(inst) = self.instrument_from_cache(order.inst_id) else {
log::debug!(
"Skipping order report for instrument not in cache: symbol={}",
order.inst_id,
);
continue;
};
let report = match parse_order_status_report(
&order,
account_id,
inst.id(),
inst.price_precision(),
inst.size_precision(),
ts_init,
) {
Ok(report) => report,
Err(e) => {
log::error!("Failed to parse order status report: {e}");
continue;
}
};
if let Some(start_ns) = start_ns
&& report.ts_last < start_ns
{
continue;
}
if let Some(end_ns) = end_ns
&& report.ts_last > end_ns
{
continue;
}
reports.push(report);
}
Ok(reports)
}
// Paginates through order history using `ord_id` as the cursor
async fn paginate_orders_history(
&self,
base: &GetOrderHistoryParams,
limit: Option<u32>,
) -> anyhow::Result<Vec<OKXOrderHistory>> {
let mut all = Vec::new();
let mut cursor: Option<String> = None;
let mut exhausted = true;
for _ in 0..MAX_RECONCILIATION_PAGES {
let mut params = base.clone();
params.after = cursor.take();
let page = self
.inner
.get_orders_history(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let page_len = page.len();
cursor = page.last().map(|o| o.ord_id.to_string());
all.extend(page);
if page_len < OKX_PAGE_SIZE {
exhausted = false;
break;
}
if let Some(lim) = limit
&& all.len() >= lim as usize
{
exhausted = false;
break;
}
}
if exhausted && !all.is_empty() {
log::warn!(
"Order history pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
results may be truncated ({} records)",
all.len()
);
}
if let Some(lim) = limit {
all.truncate(lim as usize);
}
Ok(all)
}
// Paginates through pending orders using `ord_id` as the cursor
async fn paginate_orders_pending(
&self,
base: &GetOrderListParams,
limit: Option<u32>,
) -> anyhow::Result<Vec<OKXOrderHistory>> {
let mut all = Vec::new();
let mut cursor: Option<String> = None;
let mut exhausted = true;
for _ in 0..MAX_RECONCILIATION_PAGES {
let mut params = base.clone();
params.after = cursor.take();
let page = self
.inner
.get_orders_pending(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let page_len = page.len();
cursor = page.last().map(|o| o.ord_id.to_string());
all.extend(page);
if page_len < OKX_PAGE_SIZE {
exhausted = false;
break;
}
if let Some(lim) = limit
&& all.len() >= lim as usize
{
exhausted = false;
break;
}
}
if exhausted && !all.is_empty() {
log::warn!(
"Pending orders pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
results may be truncated ({} records)",
all.len()
);
}
if let Some(lim) = limit {
all.truncate(lim as usize);
}
Ok(all)
}
// Paginates through transaction details (fills) using `bill_id` as the cursor
async fn paginate_fills(
&self,
base: &GetTransactionDetailsParams,
limit: Option<u32>,
) -> anyhow::Result<Vec<OKXTransactionDetail>> {
let mut all = Vec::new();
let mut cursor: Option<String> = None;
let mut exhausted = true;
for _ in 0..MAX_RECONCILIATION_PAGES {
let mut params = base.clone();
params.after = cursor.take();
let page = self
.inner
.get_fills(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let page_len = page.len();
cursor = page.last().map(|o| o.bill_id.to_string());
all.extend(page);
if page_len < OKX_PAGE_SIZE {
exhausted = false;
break;
}
if let Some(lim) = limit
&& all.len() >= lim as usize
{
exhausted = false;
break;
}
}
if exhausted && !all.is_empty() {
log::warn!(
"Fill pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
results may be truncated ({} records)",
all.len()
);
}
if let Some(lim) = limit {
all.truncate(lim as usize);
}
Ok(all)
}
// Paginates through pending algo orders using `algo_id` as the cursor
async fn paginate_algo_pending(
&self,
base: &GetAlgoOrdersParams,
limit: Option<usize>,
) -> anyhow::Result<Vec<OKXOrderAlgo>> {
let mut all = Vec::new();
let mut cursor: Option<String> = None;
let mut exhausted = true;
for _ in 0..MAX_RECONCILIATION_PAGES {
let mut params = base.clone();
params.after = cursor.take();
let page = match self.inner.get_order_algo_pending(params).await {
Ok(result) => result,
Err(OKXHttpError::UnexpectedStatus { status, .. })
if status == StatusCode::NOT_FOUND =>
{
exhausted = false;
break;
}
Err(e) => return Err(e.into()),
};
let page_len = page.len();
cursor = page.last().map(|o| o.algo_id.clone());
all.extend(page);
if page_len < OKX_PAGE_SIZE {
exhausted = false;
break;
}
if let Some(lim) = limit
&& all.len() >= lim
{
exhausted = false;
break;
}
}
if exhausted && !all.is_empty() {
log::warn!(
"Algo pending pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
results may be truncated ({} records)",
all.len()
);
}
Ok(all)
}
// Paginates through historical algo orders using `algo_id` as the cursor
async fn paginate_algo_history(
&self,
base: &GetAlgoOrdersParams,
limit: Option<usize>,
) -> anyhow::Result<Vec<OKXOrderAlgo>> {
let mut all = Vec::new();
let mut cursor: Option<String> = None;
let mut exhausted = true;
for _ in 0..MAX_RECONCILIATION_PAGES {
let mut params = base.clone();
params.after = cursor.take();
let page = match self.inner.get_order_algo_history(params).await {
Ok(result) => result,
Err(OKXHttpError::UnexpectedStatus { status, .. })
if status == StatusCode::NOT_FOUND =>
{
exhausted = false;
break;
}
Err(e) => return Err(e.into()),
};
let page_len = page.len();
cursor = page.last().map(|o| o.algo_id.clone());
all.extend(page);
if page_len < OKX_PAGE_SIZE {
exhausted = false;
break;
}
if let Some(lim) = limit
&& all.len() >= lim
{
exhausted = false;
break;
}
}
if exhausted && !all.is_empty() {
log::warn!(
"Algo history pagination hit {MAX_RECONCILIATION_PAGES} page cap, \
results may be truncated ({} records)",
all.len()
);
}
Ok(all)
}
/// Requests fill reports (transaction details) for the given parameters.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-get-transaction-details-last-3-days>.
pub async fn request_fill_reports(
&self,
account_id: AccountId,
instrument_type: Option<OKXInstrumentType>,
instrument_id: Option<InstrumentId>,
start: Option<DateTime<Utc>>,
end: Option<DateTime<Utc>>,
limit: Option<u32>,
) -> anyhow::Result<Vec<FillReport>> {
let mut params = GetTransactionDetailsParamsBuilder::default();
let instrument_type = if let Some(instrument_type) = instrument_type {
instrument_type
} else {
let instrument_id = instrument_id.ok_or_else(|| {
anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
})?;
let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
okx_instrument_type(&instrument)?
};
params.inst_type(instrument_type);
if let Some(instrument_id) = instrument_id {
let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
let instrument_type = okx_instrument_type(&instrument)?;
params.inst_type(instrument_type);
params.inst_id(instrument_id.symbol.inner().to_string());
}
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self.paginate_fills(¶ms, limit).await?;
// Prepare time range filter
let start_ns = start.map(UnixNanos::from);
let end_ns = end.map(UnixNanos::from);
let ts_init = self.generate_ts_init();
let mut reports = Vec::with_capacity(resp.len());
for detail in resp {
// Skip fills with zero or negative quantity (cancelled orders, etc)
if detail.fill_sz.is_empty() {
continue;
}
if let Ok(qty) = detail.fill_sz.parse::<f64>() {
if qty <= 0.0 {
continue;
}
} else {
// Skip unparsable quantities
continue;
}
let Ok(inst) = self.instrument_from_cache(detail.inst_id) else {
log::debug!(
"Skipping fill report for instrument not in cache: symbol={}",
detail.inst_id,
);
continue;
};
let report = match parse_fill_report(
&detail,
account_id,
inst.id(),
inst.price_precision(),
inst.size_precision(),
ts_init,
) {
Ok(report) => report,
Err(e) => {
log::error!("Failed to parse fill report: {e}");
continue;
}
};
if let Some(start_ns) = start_ns
&& report.ts_event < start_ns
{
continue;
}
if let Some(end_ns) = end_ns
&& report.ts_event > end_ns
{
continue;
}
reports.push(report);
}
Ok(reports)
}
/// Requests current position status reports for the given parameters.
///
/// # Position Modes
///
/// OKX supports two position modes, which affects how position data is returned:
///
/// ## Net Mode (One-way)
/// - `posSide` field will be `"net"`
/// - `pos` field uses **signed quantities**:
/// - Positive value = Long position
/// - Negative value = Short position
/// - Zero = Flat/no position
///
/// ## Long/Short Mode (Hedge/Dual-side)
/// - `posSide` field will be `"long"` or `"short"`
/// - `pos` field is **always positive** (use `posSide` to determine actual side)
/// - Allows holding simultaneous long and short positions on the same instrument
/// - Position IDs are suffixed with `-LONG` or `-SHORT` for uniqueness
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions>
pub async fn request_position_status_reports(
&self,
account_id: AccountId,
instrument_type: Option<OKXInstrumentType>,
instrument_id: Option<InstrumentId>,
) -> anyhow::Result<Vec<PositionStatusReport>> {
let mut params = GetPositionsParamsBuilder::default();
let instrument_type = if let Some(instrument_type) = instrument_type {
instrument_type
} else {
let instrument_id = instrument_id.ok_or_else(|| {
anyhow::anyhow!("Instrument ID required if `instrument_type` not provided")
})?;
let instrument = self.instrument_from_cache(instrument_id.symbol.inner())?;
okx_instrument_type(&instrument)?
};
params.inst_type(instrument_type);
instrument_id
.as_ref()
.map(|i| params.inst_id(i.symbol.inner()));
let params = params.build().map_err(|e| anyhow::anyhow!(e))?;
let resp = self
.inner
.get_positions(params)
.await
.map_err(|e| anyhow::anyhow!(e))?;
let ts_init = self.generate_ts_init();
let mut reports = Vec::with_capacity(resp.len());
for position in resp {
let Ok(inst) = self.instrument_from_cache(position.inst_id) else {
log::debug!(
"Skipping position report for instrument not in cache: symbol={}",
position.inst_id,
);
continue;
};
match parse_position_status_report(
&position,
account_id,
inst.id(),
inst.size_precision(),
ts_init,
) {
Ok(report) => reports.push(report),
Err(e) => {
log::error!("Failed to parse position status report: {e}");
}
}
}
Ok(reports)
}
/// Requests spot margin position status reports from account balance.
///
/// Spot margin positions appear in `/api/v5/account/balance` as balance sheet items
/// with non-zero `liab` (liability) or `spotInUseAmt` fields, rather than in the
/// positions endpoint. This method fetches the balance and converts any margin
/// positions into position status reports.
///
/// # Errors
///
/// Returns an error if the request fails or parsing fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-balance>
pub async fn request_spot_margin_position_reports(
&self,
account_id: AccountId,
) -> anyhow::Result<Vec<PositionStatusReport>> {
let accounts = self
.inner
.get_balance()
.await
.map_err(|e| anyhow::anyhow!(e))?;
let ts_init = self.generate_ts_init();
let mut reports = Vec::new();
// Build a base-currency lookup over the cached spot pairs once per
// call. Restricting to `CurrencyPair` (spot) ensures a derivative
// sharing the same base (e.g. `BTC-USDT-SWAP`) is never reported as
// a spot margin position with the wrong instrument id or size
// precision.
//
// When multiple spot pairs share the same base currency, prefer the
// dominant OKX quote (USDT, then USDC, then USD) so a live
// `BTC-USDT` margin position stays reported under `BTC-USDT.OKX`
// rather than being redirected to `BTC-USD.OKX` or any other
// lexically-earlier pair. Unknown quotes fall back to a stable
// lexical order by symbol, matching OKX's own listing precedence
// and keeping the selection deterministic across runs.
let cache_snapshot = self.instruments_cache.load();
let mut candidates: Vec<&InstrumentAny> = cache_snapshot
.values()
.filter(|inst| matches!(inst, InstrumentAny::CurrencyPair(_)))
.collect();
candidates.sort_by(|a, b| {
let a_sym = a.id().symbol.as_str().to_string();
let b_sym = b.id().symbol.as_str().to_string();
spot_quote_priority(&a_sym)
.cmp(&spot_quote_priority(&b_sym))
.then_with(|| a_sym.cmp(&b_sym))
});
let mut by_base: AHashMap<Ustr, (InstrumentId, u8)> = AHashMap::new();
for inst in candidates {
if let Some(base) = inst.base_currency() {
let base_code = Ustr::from(base.code.as_str());
by_base
.entry(base_code)
.or_insert_with(|| (inst.id(), inst.size_precision()));
}
}
for account in accounts {
for balance in account.details {
let ccy_str = balance.ccy.as_str();
let Some((instrument_id, size_precision)) =
by_base.get(&Ustr::from(ccy_str)).copied()
else {
log::debug!("Skipping balance for {ccy_str} - no matching instrument in cache");
continue;
};
match parse_spot_margin_position_from_balance(
&balance,
account_id,
instrument_id,
size_precision,
ts_init,
) {
Ok(Some(report)) => reports.push(report),
Ok(None) => {} // No margin position for this currency
Err(e) => {
log::error!(
"Failed to parse spot margin position from balance for {ccy_str}: {e}"
);
}
}
}
}
Ok(reports)
}
/// Places a regular order via HTTP.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-trade-post-place-order>
pub async fn place_order(
&self,
request: OKXPlaceOrderRequest,
) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
let body =
serde_json::to_vec(&request).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXPlaceOrderResponse> = self
.inner
.send_request::<_, ()>(Method::POST, "/api/v5/trade/order", None, Some(body), true)
.await?;
resp.into_iter()
.next()
.ok_or_else(|| OKXHttpError::ValidationError("Empty response".to_string()))
}
/// Places an algo order via HTTP.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order>
pub async fn place_algo_order(
&self,
request: OKXPlaceAlgoOrderRequest,
) -> Result<OKXPlaceAlgoOrderResponse, OKXHttpError> {
let body =
serde_json::to_vec(&request).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXPlaceAlgoOrderResponse> = self
.inner
.send_request::<_, ()>(
Method::POST,
"/api/v5/trade/order-algo",
None,
Some(body),
true,
)
.await?;
let item = resp
.into_iter()
.next()
.ok_or_else(|| OKXHttpError::ValidationError("Empty response".to_string()))?;
if let Some(ref code) = item.s_code
&& code != "0"
{
let msg = item.s_msg.clone().unwrap_or_default();
return Err(OKXHttpError::OkxError {
error_code: code.clone(),
message: msg,
});
}
Ok(item)
}
/// Cancels an algo order via HTTP.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order>
pub async fn cancel_algo_order(
&self,
request: OKXCancelAlgoOrderRequest,
) -> Result<OKXCancelAlgoOrderResponse, OKXHttpError> {
// OKX expects an array for cancel-algos endpoint
// Serialize once to bytes to keep signing and sending identical
let body =
serde_json::to_vec(&[request]).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXCancelAlgoOrderResponse> = self
.inner
.send_request::<_, ()>(
Method::POST,
"/api/v5/trade/cancel-algos",
None,
Some(body),
true,
)
.await?;
let item = resp
.into_iter()
.next()
.ok_or_else(|| OKXHttpError::ValidationError("Empty response".to_string()))?;
if let Some(ref code) = item.s_code
&& code != "0"
{
let msg = item.s_msg.clone().unwrap_or_default();
return Err(OKXHttpError::OkxError {
error_code: code.clone(),
message: msg,
});
}
Ok(item)
}
/// Cancels multiple algo orders via HTTP in a single request.
///
/// Items with non-zero `sCode` are logged as warnings but do not
/// fail the entire batch.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-algo-order>
pub async fn cancel_algo_orders(
&self,
requests: Vec<OKXCancelAlgoOrderRequest>,
) -> Result<Vec<OKXCancelAlgoOrderResponse>, OKXHttpError> {
if requests.is_empty() {
return Ok(Vec::new());
}
let body =
serde_json::to_vec(&requests).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXCancelAlgoOrderResponse> = self
.inner
.send_request::<_, ()>(
Method::POST,
"/api/v5/trade/cancel-algos",
None,
Some(body),
true,
)
.await?;
for item in &resp {
if let Some(ref code) = item.s_code
&& code != "0"
{
let msg = item.s_msg.as_deref().unwrap_or("");
log::warn!(
"Algo cancel rejected: algo_id={} sCode={code} sMsg={msg}",
item.algo_id
);
}
}
Ok(resp)
}
/// Cancels advance algo orders (trailing stop, iceberg, TWAP) via HTTP.
///
/// These order types cannot use the standard `cancel-algos` endpoint.
/// Items with non-zero `sCode` are logged as warnings.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-cancel-advance-algo-order>
pub async fn cancel_advance_algo_orders(
&self,
requests: Vec<OKXCancelAlgoOrderRequest>,
) -> Result<Vec<OKXCancelAlgoOrderResponse>, OKXHttpError> {
if requests.is_empty() {
return Ok(Vec::new());
}
let body =
serde_json::to_vec(&requests).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXCancelAlgoOrderResponse> = self
.inner
.send_request::<_, ()>(
Method::POST,
"/api/v5/trade/cancel-advance-algos",
None,
Some(body),
true,
)
.await?;
for item in &resp {
if let Some(ref code) = item.s_code
&& code != "0"
{
let msg = item.s_msg.as_deref().unwrap_or("");
log::warn!(
"Advance algo cancel rejected: algo_id={} sCode={code} sMsg={msg}",
item.algo_id
);
}
}
Ok(resp)
}
/// Amends an algo order via HTTP.
///
/// # Errors
///
/// Returns an error if the request fails.
///
/// # References
///
/// <https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-amend-algo-order>
pub async fn amend_algo_order(
&self,
request: OKXAmendAlgoOrderRequest,
) -> Result<OKXAmendAlgoOrderResponse, OKXHttpError> {
let body =
serde_json::to_vec(&request).map_err(|e| OKXHttpError::JsonError(e.to_string()))?;
let resp: Vec<OKXAmendAlgoOrderResponse> = self
.inner
.send_request::<_, ()>(
Method::POST,
"/api/v5/trade/amend-algos",
None,
Some(body),
true,
)
.await?;
resp.into_iter()
.next()
.ok_or_else(|| OKXHttpError::ValidationError("Empty response".to_string()))
}
/// Amends an algo order using domain types.
///
/// This is a convenience method that accepts Nautilus domain types
/// and builds the appropriate OKX request structure internally.
///
/// # Errors
///
/// Returns an error if the request fails.
#[expect(clippy::too_many_arguments)]
pub async fn amend_algo_order_with_domain_types(
&self,
instrument_id: InstrumentId,
algo_id: String,
new_trigger_price: Option<Price>,
new_limit_price: Option<Price>,
new_quantity: Option<Quantity>,
new_callback_ratio: Option<String>,
new_callback_spread: Option<String>,
new_activation_price: Option<Price>,
) -> Result<OKXAmendAlgoOrderResponse, OKXHttpError> {
let request = OKXAmendAlgoOrderRequest {
inst_id: instrument_id.symbol.as_str().to_string(),
algo_id,
algo_cl_ord_id: None,
new_sz: new_quantity.map(|q| q.to_string()),
new_trigger_px: new_trigger_price.map(|p| p.to_string()),
new_order_px: new_limit_price.map(|p| p.to_string()),
new_callback_ratio,
new_callback_spread,
new_active_px: new_activation_price.map(|p| p.to_string()),
};
self.amend_algo_order(request).await
}
/// Places an algo order using domain types.
///
/// This is a convenience method that accepts Nautilus domain types
/// and builds the appropriate OKX request structure internally.
///
/// # Errors
///
/// Returns an error if the request fails.
#[expect(clippy::too_many_arguments)]
pub async fn place_order_with_domain_types(
&self,
instrument_id: InstrumentId,
td_mode: OKXTradeMode,
client_order_id: ClientOrderId,
order_side: OrderSide,
order_type: OrderType,
quantity: Quantity,
time_in_force: Option<TimeInForce>,
price: Option<Price>,
post_only: Option<bool>,
reduce_only: Option<bool>,
quote_quantity: Option<bool>,
position_side: Option<PositionSide>,
attach_algo_ords: Option<Vec<OKXAttachAlgoOrdRequest>>,
px_usd: Option<String>,
px_vol: Option<String>,
) -> Result<OKXPlaceOrderResponse, OKXHttpError> {
if !OKX_SUPPORTED_ORDER_TYPES.contains(&order_type) {
return Err(OKXHttpError::ValidationError(format!(
"Unsupported order type: {order_type:?}",
)));
}
if matches!(
order_type,
OrderType::StopMarket
| OrderType::StopLimit
| OrderType::MarketIfTouched
| OrderType::LimitIfTouched
| OrderType::TrailingStopMarket
) {
return Err(OKXHttpError::ValidationError(
"Conditional order types must use OKX algo order placement".to_string(),
));
}
if let Some(tif) = time_in_force
&& !OKX_SUPPORTED_TIME_IN_FORCE.contains(&tif)
{
return Err(OKXHttpError::ValidationError(format!(
"Unsupported time in force: {tif:?}",
)));
}
if !matches!(order_side, OrderSide::Buy | OrderSide::Sell) {
return Err(OKXHttpError::ValidationError(
"Invalid order side".to_string(),
));
}
let instrument = self
.instrument_from_cache(instrument_id.symbol.inner())
.map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
let instrument_type = okx_instrument_type(&instrument)
.map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
// OKX options only support limit-style orders
if instrument_type == OKXInstrumentType::Option
&& matches!(order_type, OrderType::Market | OrderType::MarketToLimit)
{
return Err(OKXHttpError::ValidationError(
"Market orders are not supported for OKX options, use Limit orders instead"
.to_string(),
));
}
let side = OKXSide::from(order_side.as_specified());
let pos_side = position_side.map(Into::into).or({
if matches!(
instrument_type,
OKXInstrumentType::Swap | OKXInstrumentType::Futures | OKXInstrumentType::Option
) {
Some(OKXPositionSide::Net)
} else {
None
}
});
let tgt_ccy = if instrument_type == OKXInstrumentType::Spot
&& order_type == OrderType::Market
&& td_mode == OKXTradeMode::Cash
{
match quote_quantity {
Some(true) => Some(OKXTargetCurrency::QuoteCcy),
Some(false) if order_side == OrderSide::Buy => Some(OKXTargetCurrency::BaseCcy),
_ => None,
}
} else {
None
};
let (ord_type, px) = if post_only.unwrap_or(false) {
(OKXOrderType::PostOnly, price)
} else if let Some(tif) = time_in_force {
match (order_type, tif) {
(OrderType::Market, TimeInForce::Fok) => {
return Err(OKXHttpError::ValidationError(
"Market orders with FOK time-in-force are not supported by OKX. Use Limit order with FOK instead.".to_string(),
));
}
(OrderType::Market, TimeInForce::Ioc) => {
// optimal_limit_ioc only works for SWAP/FUTURES
if matches!(
instrument_type,
OKXInstrumentType::Spot | OKXInstrumentType::Option
) {
(OKXOrderType::Market, price)
} else {
(OKXOrderType::OptimalLimitIoc, price)
}
}
(OrderType::Limit, TimeInForce::Fok) => {
// OKX uses op_fok for options FOK orders
if instrument_type == OKXInstrumentType::Option {
(OKXOrderType::OpFok, price)
} else {
(OKXOrderType::Fok, price)
}
}
(OrderType::Limit, TimeInForce::Ioc) => (OKXOrderType::Ioc, price),
_ => (OKXOrderType::from(order_type), price),
}
} else {
(OKXOrderType::from(order_type), price)
};
// reduceOnly is not applicable to options per OKX docs
let reduce_only = if instrument_type == OKXInstrumentType::Option {
None
} else {
reduce_only
};
// For options: pxUsd/pxVol are mutually exclusive with px
let (px, px_usd, px_vol) = if px_usd.is_some() {
(None, px_usd, None)
} else if px_vol.is_some() {
(None, None, px_vol)
} else {
(px.map(|p| p.to_string()), None, None)
};
let request = OKXPlaceOrderRequest {
inst_id: instrument_id.symbol.as_str().to_string(),
td_mode,
ccy: None,
cl_ord_id: Some(client_order_id.as_str().to_string()),
tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
side,
pos_side,
ord_type,
sz: quantity.to_string(),
px,
px_usd,
px_vol,
reduce_only,
tgt_ccy,
attach_algo_ords,
};
self.place_order(request).await
}
/// Places an algo order using domain types.
///
/// This is a convenience method that accepts Nautilus domain types
/// and builds the appropriate OKX request structure internally.
///
/// # Errors
///
/// Returns an error if the request fails.
#[expect(clippy::too_many_arguments)]
pub async fn place_algo_order_with_domain_types(
&self,
instrument_id: InstrumentId,
td_mode: OKXTradeMode,
client_order_id: ClientOrderId,
order_side: OrderSide,
order_type: OrderType,
quantity: Quantity,
trigger_price: Option<Price>,
trigger_type: Option<TriggerType>,
limit_price: Option<Price>,
reduce_only: Option<bool>,
close_fraction: Option<String>,
callback_ratio: Option<String>,
callback_spread: Option<String>,
activation_price: Option<Price>,
) -> Result<OKXPlaceAlgoOrderResponse, OKXHttpError> {
if !matches!(order_side, OrderSide::Buy | OrderSide::Sell) {
return Err(OKXHttpError::ValidationError(
"Invalid order side".to_string(),
));
}
let okx_side = OKXSide::from(order_side.as_specified());
// Map trigger type to OKX format
let trigger_px_type_enum = trigger_type.map_or(OKXTriggerType::Last, Into::into);
let uses_close_fraction = close_fraction.is_some();
let (
algo_type,
sz,
trigger_px,
order_px,
trigger_px_type,
sl_trigger_px,
sl_ord_px,
sl_trigger_px_type,
tp_trigger_px,
tp_ord_px,
tp_trigger_px_type,
pos_side,
reduce_only,
) = if uses_close_fraction {
if order_type == OrderType::TrailingStopMarket {
return Err(OKXHttpError::ValidationError(
"OKX close_fraction does not support TrailingStopMarket".to_string(),
));
}
let trigger_px = trigger_price.map(|p| p.to_string()).ok_or_else(|| {
OKXHttpError::ValidationError(
"OKX close_fraction orders require trigger_price".to_string(),
)
})?;
let close_order_px =
if matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched) {
limit_price.map(|p| p.to_string()).ok_or_else(|| {
OKXHttpError::ValidationError(format!(
"OKX {order_type:?} close_fraction orders require limit_price"
))
})?
} else {
"-1".to_string()
};
let (
sl_trigger_px,
sl_ord_px,
sl_trigger_px_type,
tp_trigger_px,
tp_ord_px,
tp_trigger_px_type,
) = match order_type {
OrderType::StopMarket | OrderType::StopLimit => (
Some(trigger_px),
Some(close_order_px),
Some(trigger_px_type_enum),
None,
None,
None,
),
OrderType::MarketIfTouched | OrderType::LimitIfTouched => (
None,
None,
None,
Some(trigger_px),
Some(close_order_px),
Some(trigger_px_type_enum),
),
_ => {
return Err(OKXHttpError::ValidationError(format!(
"OKX close_fraction is only supported for stop/touched conditional orders, received {order_type:?}"
)));
}
};
(
OKXAlgoOrderType::Conditional,
None,
None,
None,
None,
sl_trigger_px,
sl_ord_px,
sl_trigger_px_type,
tp_trigger_px,
tp_ord_px,
tp_trigger_px_type,
Some(OKXPositionSide::Net),
Some(true),
)
} else {
let algo_type = conditional_order_to_algo_type(order_type)
.map_err(|e| OKXHttpError::ValidationError(e.to_string()))?;
let order_px = if matches!(order_type, OrderType::StopLimit | OrderType::LimitIfTouched)
{
limit_price.map(|p| p.to_string())
} else if order_type == OrderType::TrailingStopMarket {
None
} else {
Some("-1".to_string())
};
(
algo_type,
Some(quantity.to_string()),
trigger_price.map(|p| p.to_string()),
order_px,
Some(trigger_px_type_enum),
None,
None,
None,
None,
None,
None,
None,
reduce_only,
)
};
let request = OKXPlaceAlgoOrderRequest {
inst_id: instrument_id.symbol.as_str().to_string(),
inst_id_code: None,
td_mode,
side: okx_side,
ord_type: algo_type,
sz,
algo_cl_ord_id: Some(client_order_id.as_str().to_string()),
trigger_px,
order_px,
trigger_px_type,
sl_trigger_px,
sl_ord_px,
sl_trigger_px_type,
tp_trigger_px,
tp_ord_px,
tp_trigger_px_type,
tgt_ccy: None,
pos_side,
close_position: None,
tag: Some(OKX_NAUTILUS_BROKER_ID.to_string()),
reduce_only,
close_fraction,
callback_ratio,
callback_spread,
active_px: activation_price.map(|p| p.to_string()),
};
self.place_algo_order(request).await
}
/// Cancels an algo order using domain types.
///
/// This is a convenience method that accepts Nautilus domain types
/// and builds the appropriate OKX request structure internally.
///
/// # Errors
///
/// Returns an error if the request fails.
pub async fn cancel_algo_order_with_domain_types(
&self,
instrument_id: InstrumentId,
algo_id: String,
) -> Result<OKXCancelAlgoOrderResponse, OKXHttpError> {
let request = OKXCancelAlgoOrderRequest {
inst_id: instrument_id.symbol.to_string(),
inst_id_code: None,
algo_id: Some(algo_id),
algo_cl_ord_id: None,
};
self.cancel_algo_order(request).await
}
/// Requests algo order status reports.
///
/// # Errors
///
/// Returns an error if the request fails.
#[expect(clippy::too_many_arguments)]
pub async fn request_algo_order_status_reports(
&self,
account_id: AccountId,
instrument_type: Option<OKXInstrumentType>,
instrument_id: Option<InstrumentId>,
algo_id: Option<String>,
algo_client_order_id: Option<ClientOrderId>,
state: Option<OKXOrderStatus>,
limit: Option<u32>,
) -> anyhow::Result<Vec<OrderStatusReport>> {
let mut instruments_cache: AHashMap<Ustr, InstrumentAny> = AHashMap::new();
let has_specific_lookup = algo_id.is_some() || algo_client_order_id.is_some();
let inst_type = if let Some(inst_type) = instrument_type {
inst_type
} else if let Some(inst_id) = instrument_id {
let instrument = self.instrument_from_cache(inst_id.symbol.inner())?;
let inst_type = okx_instrument_type(&instrument)?;
instruments_cache.insert(inst_id.symbol.inner(), instrument);
inst_type
} else {
anyhow::bail!("instrument_type or instrument_id required for algo order query")
};
let ts_init = self.generate_ts_init();
let mut reports = Vec::new();
let mut seen: AHashSet<(String, String)> = AHashSet::new();
for ord_type in [
OKXAlgoOrderType::Oco,
OKXAlgoOrderType::Conditional,
OKXAlgoOrderType::Trigger,
OKXAlgoOrderType::MoveOrderStop,
] {
let mut params_builder = GetAlgoOrdersParamsBuilder::default();
params_builder.inst_type(inst_type);
params_builder.ord_type(ord_type);
if let Some(inst_id) = instrument_id {
params_builder.inst_id(inst_id.symbol.inner().to_string());
}
if let Some(algo_id) = algo_id.as_ref() {
params_builder.algo_id(algo_id.clone());
}
if let Some(client_order_id) = algo_client_order_id.as_ref() {
params_builder.algo_cl_ord_id(client_order_id.as_str().to_string());
}
if let Some(state) = state {
params_builder.state(state);
}
let params = params_builder
.build()
.map_err(|e| anyhow::anyhow!(format!("Failed to build algo order params: {e}")))?;
let remaining = limit.map(|l| (l as usize).saturating_sub(reports.len()));
let pending = self.paginate_algo_pending(¶ms, remaining).await?;
self.collect_algo_reports(
account_id,
&pending,
&mut instruments_cache,
ts_init,
&mut seen,
&mut reports,
)
.await?;
if has_specific_lookup && !reports.is_empty() {
return Ok(reports);
}
if let Some(lim) = limit
&& reports.len() >= lim as usize
{
reports.truncate(lim as usize);
return Ok(reports);
}
// OKX's `/orders-algo-history` endpoint rejects calls that
// carry neither a `state` nor an `algoId` / `algoClOrdId`
// narrowing with code 50015. The reconciliation path wants
// only currently-live algo orders (those already appear in
// the pending response above), so skip the history leg when
// the caller supplied no narrowing. Specific-lookup callers
// still hit history because `has_specific_lookup` implies
// `algoId` or `algoClOrdId`, which the endpoint accepts.
if state.is_some() || has_specific_lookup {
let remaining = limit.map(|l| (l as usize).saturating_sub(reports.len()));
let history = self.paginate_algo_history(¶ms, remaining).await?;
self.collect_algo_reports(
account_id,
&history,
&mut instruments_cache,
ts_init,
&mut seen,
&mut reports,
)
.await?;
if has_specific_lookup && !reports.is_empty() {
return Ok(reports);
}
if let Some(lim) = limit
&& reports.len() >= lim as usize
{
reports.truncate(lim as usize);
return Ok(reports);
}
}
}
Ok(reports)
}
/// Requests an algo order status report by client order identifier.
///
/// # Errors
///
/// Returns an error if the request fails.
pub async fn request_algo_order_status_report(
&self,
account_id: AccountId,
instrument_id: InstrumentId,
algo_client_order_id: ClientOrderId,
) -> anyhow::Result<Option<OrderStatusReport>> {
let reports = self
.request_algo_order_status_reports(
account_id,
None,
Some(instrument_id),
None,
Some(algo_client_order_id),
None,
Some(50_u32),
)
.await?;
Ok(reports.into_iter().next())
}
/// Exposes raw HTTP client for testing purposes
pub fn raw_client(&self) -> &Arc<OKXRawHttpClient> {
&self.inner
}
async fn collect_algo_reports(
&self,
account_id: AccountId,
orders: &[OKXOrderAlgo],
instruments_cache: &mut AHashMap<Ustr, InstrumentAny>,
ts_init: UnixNanos,
seen: &mut AHashSet<(String, String)>,
reports: &mut Vec<OrderStatusReport>,
) -> anyhow::Result<()> {
for order in orders {
let key = (order.algo_id.clone(), order.algo_cl_ord_id.clone());
if !seen.insert(key) {
continue;
}
let instrument = if let Some(instrument) = instruments_cache.get(&order.inst_id) {
instrument.clone()
} else {
let Ok(instrument) = self.instrument_from_cache(order.inst_id) else {
log::debug!(
"Skipping algo order report for instrument not in cache: symbol={}",
order.inst_id,
);
continue;
};
instruments_cache.insert(order.inst_id, instrument.clone());
instrument
};
match parse_http_algo_order(order, account_id, &instrument, ts_init) {
Ok(report) => reports.push(report),
Err(e) => {
log::error!("Failed to parse algo order report: {e}");
}
}
}
Ok(())
}
}
fn parse_http_algo_order(
order: &OKXOrderAlgo,
account_id: AccountId,
instrument: &InstrumentAny,
ts_init: UnixNanos,
) -> anyhow::Result<OrderStatusReport> {
let ord_px = if order.ord_px.is_empty() {
"-1".to_string()
} else {
order.ord_px.clone()
};
let reduce_only = if order.reduce_only.is_empty() {
"false".to_string()
} else {
order.reduce_only.clone()
};
let msg = OKXAlgoOrderMsg {
algo_id: order.algo_id.clone(),
algo_cl_ord_id: order.algo_cl_ord_id.clone(),
cl_ord_id: order.cl_ord_id.clone(),
ord_id: order.ord_id.clone(),
inst_id: order.inst_id,
inst_type: order.inst_type,
ord_type: order.ord_type,
state: order.state,
side: order.side,
pos_side: order.pos_side,
sz: order.sz.clone(),
trigger_px: order.trigger_px.clone(),
trigger_px_type: order.trigger_px_type.unwrap_or(OKXTriggerType::None),
sl_trigger_px: order.sl_trigger_px.clone(),
sl_ord_px: order.sl_ord_px.clone(),
sl_trigger_px_type: order.sl_trigger_px_type.unwrap_or(OKXTriggerType::None),
tp_trigger_px: order.tp_trigger_px.clone(),
tp_ord_px: order.tp_ord_px.clone(),
tp_trigger_px_type: order.tp_trigger_px_type.unwrap_or(OKXTriggerType::None),
ord_px,
td_mode: order.td_mode,
lever: order.lever.clone(),
reduce_only,
close_fraction: order.close_fraction.clone(),
actual_px: order.actual_px.clone(),
actual_sz: order.actual_sz.clone(),
notional_usd: order.notional_usd.clone(),
c_time: order.c_time,
u_time: order.u_time,
trigger_time: order.trigger_time.clone(),
tag: order.tag.clone(),
callback_ratio: order.callback_ratio.clone(),
callback_spread: order.callback_spread.clone(),
active_px: order.active_px.clone(),
ccy: None,
tgt_ccy: None,
fee: None,
fee_ccy: None,
advance_ord_type: None,
};
parse_algo_order_status_report(&msg, instrument, account_id, ts_init)
}