patisson-bybit-sdk 0.3.0

Unofficial Rust SDK for the Bybit exchange API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
use crate::{
    Environment, Error, ServerClock, Timestamp,
    crypto::{SensitiveString, Signer, timestamp},
    enums::Category,
    http::{
        APIErrorResponse, APIKeyInformation, AccountCoinBalance, AccountInfo,
        AmendOrderBatchRequest, AmendOrderBatchResult, AmendOrderRequest, AmendOrderResponse,
        AssetInfoResult, BorrowHistoryEntry, CancelAllOrdersRequest, CancelAllOrdersResponse,
        CancelOrderBatchRequest, CancelOrderBatchResult, CancelOrderRequest, CancelOrderResponse,
        CancelWithdrawalRequest, CancelWithdrawalResult, ClosedPnl, CoinGreeks, CoinInfoResult,
        CollateralInfoEntry, CursorPagination, DeliveryPrice, DeliveryRecord, DepositAddress,
        DepositAllowedCoinInfoResult, DepositRecords, EmptyResult, ExchangeOrderRecords,
        ExecutionEntry, FeeRateEntry, FundingRateHistory, GetAccountCoinBalanceParams,
        GetAssetInfoParams, GetBorrowHistoryParams, GetClosedPnlParams, GetCoinGreeksParams,
        GetCoinInfoParams, GetCollateralInfoParams, GetDeliveryPriceParams,
        GetDeliveryRecordParams, GetDepositAddressParams, GetDepositAllowedCoinInfoParams,
        GetDepositRecordsParams, GetExchangeOrderRecordParams, GetExecutionListParams,
        GetFeeRateParams, GetFundingRateHistoryParams, GetHistoricalVolatilityParams,
        GetInstrumentsInfoParams, GetInsuranceParams, GetInternalTransferRecordsParams,
        GetKLinesParams, GetLeverageTokenInfoParams, GetLeverageTokenMarketParams,
        GetLeverageTokenOrderRecordsParams, GetOpenClosedOrdersParams, GetOpenInterestParams,
        GetOrderHistoryParams, GetOrderbookParams, GetPositionInfoParams, GetRiskLimitParams,
        GetSettlementRecordParams, GetSpotBorrowCheckParams, GetSubDepositAddressParams,
        GetSubDepositRecordsParams, GetTickersParams, GetTradesParams, GetTransactionLogParams,
        GetTransferableCoinsParams, GetUniversalTransferRecordsParams, GetWalletBalanceParams,
        GetWithdrawableAmountParams, GetWithdrawalRecordsParams, Headers,
        HistoricalVolatilityEntry, InstrumentsInfo, Insurance, InternalTransferEntry,
        InternalTransferRequest, KLine, LeverageTokenInfo, LeverageTokenMarket,
        LeverageTokenOrderRecord, List, OpenInterest, Order, Orderbook, PlaceOrderBatchRequest,
        PlaceOrderBatchResult, PlaceOrderRequest, PlaceOrderResponse, Position, PriceKLine,
        PurchaseLeverageTokenRequest, PurchaseLeverageTokenResult, RedeemLeverageTokenRequest,
        RedeemLeverageTokenResult, Resp, Response, RiskLimit, SaveTransferSubMemberRequest,
        ServerTime, SetAutoAddMarginRequest, SetLeverageRequest, SetMarginModeRequest,
        SetMarginModeResponse, SetRiskLimitRequest, SetRiskLimitResponse,
        SetSpotMarginLeverageRequest, SetTradingStopRequest, SettlementRecord, SpotBorrowCheck,
        SwitchCrossIsolatedMarginRequest, SwitchPositionModeRequest, SwitchSpotMarginModeRequest,
        SwitchSpotMarginModeResult, Ticker, Trade, TransactionLog, TransferResult,
        TransferableSubMembers, UniversalTransferEntry, UniversalTransferRequest,
        UpgradeToUtaResult, WalletBalance, WithdrawRecords, WithdrawRequest, WithdrawResult,
        WithdrawableAmountResult,
    },
    serde::{deserialize_json, serialize_json, serialize_query},
    url::*,
};
use reqwest::{
    self, Method, RequestBuilder, StatusCode,
    header::{CONTENT_TYPE, HeaderMap, HeaderValue},
};
use std::{sync::Arc, time::Duration};

use super::rate_limiter::{RateLimitKey, RateLimiter, RateLimiterConfig, Rejection};

/// Default total timeout of one HTTP request.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
/// Default timeout of establishing a TCP/TLS connection.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Default `X-BAPI-RECV-WINDOW`, milliseconds.
pub const DEFAULT_RECV_WINDOW: Timestamp = 5000;

/// Maximum number of bytes of a non-2xx response body kept in [`Error::Http`].
const MAX_ERROR_BODY_LEN: usize = 1024;

/// Configuration of a [`Client`]; start with [`Config::new`] or [`Config::for_env`].
pub struct Config {
    /// REST base URL, e.g. `https://api.bybit.com`.
    pub base_url: String,
    /// API key for private endpoints (see [`Config::credentials`]).
    pub api_key: Option<SensitiveString>,
    /// API secret for private endpoints (see [`Config::credentials`]).
    pub api_secret: Option<SensitiveString>,
    /// Milliseconds.
    pub recv_window: Timestamp,
    /// HTTP the header for broker users only.
    pub referer: Option<String>,
    /// Optional rate limiter. When `Some`, every request is pre-flight-checked
    /// against a local token bucket and the last server-reported limit status.
    /// Set to `None` to disable rate limiting entirely.
    pub rate_limiter: Option<RateLimiterConfig>,
    /// Total timeout of one request (connect + send + receive).
    /// `None` disables it, which is not recommended: a hung request would
    /// then wait forever.
    pub timeout: Option<Duration>,
    /// Timeout of establishing a connection. `None` disables it.
    pub connect_timeout: Option<Duration>,
    /// HTTP(S) proxy for REST requests, e.g. `http://127.0.0.1:8080`. `None`
    /// uses the system proxy settings (`HTTP(S)_PROXY`). WebSocket streams do
    /// not use it.
    pub proxy: Option<String>,
    /// When Bybit rejects a signed request's timestamp (`retCode` 10002),
    /// call [`Client::sync_time`] and send the request once more, signed with
    /// the server time. Safe: the rejected request was not executed.
    /// Enabled by default.
    pub resync_time_on_timestamp_error: bool,
}

impl Config {
    /// Config for public endpoints with default timeouts and no rate limiter.
    pub fn new(base_url: impl Into<String>) -> Self {
        Self {
            base_url: base_url.into(),
            api_key: None,
            api_secret: None,
            recv_window: DEFAULT_RECV_WINDOW,
            referer: None,
            rate_limiter: None,
            timeout: Some(DEFAULT_TIMEOUT),
            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
            resync_time_on_timestamp_error: true,
            proxy: None,
        }
    }

    /// Config for the REST API of `env`, e.g. `Config::for_env(Environment::Demo)`.
    pub fn for_env(env: Environment) -> Self {
        Self::new(env.api_url())
    }

    /// Credentials required by private endpoints.
    pub fn credentials(
        mut self,
        api_key: impl Into<SensitiveString>,
        api_secret: impl Into<SensitiveString>,
    ) -> Self {
        self.api_key = Some(api_key.into());
        self.api_secret = Some(api_secret.into());
        self
    }

    /// Milliseconds.
    pub fn recv_window(mut self, recv_window: Timestamp) -> Self {
        self.recv_window = recv_window;
        self
    }

    /// Broker referer header (`X-Referer`).
    pub fn referer(mut self, referer: impl Into<String>) -> Self {
        self.referer = Some(referer.into());
        self
    }

    /// Enable the local rate limiter.
    pub fn rate_limiter(mut self, rate_limiter: RateLimiterConfig) -> Self {
        self.rate_limiter = Some(rate_limiter);
        self
    }

    /// Total timeout of one request; `None` disables it.
    pub fn timeout(mut self, timeout: Option<Duration>) -> Self {
        self.timeout = timeout;
        self
    }

    /// Timeout of establishing a connection; `None` disables it.
    pub fn connect_timeout(mut self, connect_timeout: Option<Duration>) -> Self {
        self.connect_timeout = connect_timeout;
        self
    }

    /// HTTP(S) proxy for REST requests, e.g. `http://127.0.0.1:8080`.
    pub fn proxy(mut self, url: impl Into<String>) -> Self {
        self.proxy = Some(url.into());
        self
    }

    /// Re-synchronize the clock and retry once when Bybit rejects a
    /// request timestamp (`retCode` 10002). Enabled by default.
    pub fn resync_time_on_timestamp_error(mut self, enabled: bool) -> Self {
        self.resync_time_on_timestamp_error = enabled;
        self
    }
}

/// Bybit V5 REST client.
///
/// Cloning is cheap, and clones share the connection pool, the rate limiter
/// state and the clock offset measured by [`Client::sync_time`]: clone the
/// client into tasks instead of wrapping it in `Arc`.
#[derive(Debug, Clone)]
pub struct Client {
    base_url: String,
    headers: HeaderMap,
    client: reqwest::Client,
    signer: Option<Arc<Signer>>,
    rate_limiter: Option<Arc<RateLimiter>>,
    /// Offset to the server clock (see [`Client::sync_time`]).
    clock: ServerClock,
    resync_time_on_timestamp_error: bool,
}

impl Client {
    /// Create a client. Fails if a header value (API key, referer) is invalid, `api_secret` is set without `api_key`, or the proxy URL is invalid.
    pub fn new(cfg: Config) -> Result<Self, Error> {
        let mut headers = HeaderMap::new();

        if let Some(api_key) = cfg.api_key.as_ref() {
            let api_key = api_key.expose().parse()?;
            headers.append(HEADER_X_BAPI_API_KEY, api_key);
        }

        let recv_window = cfg.recv_window.to_string().parse()?;
        headers.append(HEADER_X_BAPI_RECV_WINDOW, recv_window);

        if let Some(referer) = cfg.referer {
            let referer = referer.parse()?;
            headers.append(HEADER_X_REFERER, referer);
        }

        let signer = cfg
            .api_secret
            .map(|api_secret| -> Result<Arc<Signer>, Error> {
                let api_key = cfg
                    .api_key
                    .ok_or_else(|| Error::from("api_key is required when api_secret is set"))?;
                Ok(Arc::new(Signer::new(
                    api_key,
                    api_secret,
                    cfg.recv_window,
                    None,
                )))
            })
            .transpose()?;

        let rate_limiter = cfg
            .rate_limiter
            .map(|config| Arc::new(RateLimiter::new(config)));

        // Bybit requires `Content-Type: application/json` for POST bodies;
        // it is harmless on GET requests.
        let mut default_headers = HeaderMap::new();
        default_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        let mut builder = reqwest::Client::builder().default_headers(default_headers);
        if let Some(timeout) = cfg.timeout {
            builder = builder.timeout(timeout);
        }
        if let Some(connect_timeout) = cfg.connect_timeout {
            builder = builder.connect_timeout(connect_timeout);
        }
        if let Some(proxy) = &cfg.proxy {
            builder = builder.proxy(reqwest::Proxy::all(proxy)?);
        }

        Ok(Self {
            base_url: cfg.base_url,
            headers,
            client: builder.build()?,
            signer,
            rate_limiter,
            clock: ServerClock::new(),
            resync_time_on_timestamp_error: cfg.resync_time_on_timestamp_error,
        })
    }

    /// Measure the offset between the Bybit server clock and the local clock
    /// and use it for all signed requests from now on. Returns the offset in
    /// milliseconds (positive: the local clock is behind).
    ///
    /// Bybit rejects signed requests whose timestamp is not within
    /// `[server_time - recv_window, server_time + 1000)` (`retCode` 10002).
    /// Call this after creating the client, periodically in long-running
    /// programs (clocks drift) and after a 10002 error. The offset is
    /// estimated as `server_time - (sent_at + received_at) / 2`, so its error
    /// is at most half the round trip.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn sync_time(&self) -> Result<i64, Error> {
        // Not via `get_server_time`: `send_weighted` may itself call
        // `sync_time` when a timestamp is rejected.
        let url = format!("{}{}", self.base_url, Path::MarketServerTime);
        let request = self.client.request(Method::GET, url).build()?;
        let key = RateLimitKey::new(Path::MarketServerTime);

        let sent_at = timestamp();
        let response: Response<ServerTime> = self.execute_once(key, 1, request).await?;
        let received_at = timestamp();

        let server_ms = response.result.time_nano / 1_000_000;
        let offset = estimate_time_offset(sent_at, received_at, server_ms);
        self.clock.set_offset(offset);
        tracing::debug!(offset_ms = offset, "server time synchronized");
        Ok(offset)
    }

    /// Offset applied to signed requests: server clock minus local clock,
    /// milliseconds. `0` until [`Client::sync_time`] is called.
    pub fn time_offset(&self) -> i64 {
        self.clock.offset()
    }

    /// The server clock estimate used for signing. Clones share the offset;
    /// pass it to [`ws::Config::server_clock`](crate::ws::Config::server_clock)
    /// so that stream authentication uses the same offset.
    pub fn clock(&self) -> ServerClock {
        self.clock.clone()
    }

    /// Current server time estimated from the local clock and
    /// [`Client::time_offset`], milliseconds. Use it for the WebSocket
    /// `auth` message ([`create_outgoing_message_auth_at`](crate::ws::create_outgoing_message_auth_at)).
    pub fn server_timestamp(&self) -> Timestamp {
        self.clock.now()
    }

    fn get_signed_headers(&self, s: &str) -> Result<HeaderMap, Error> {
        let signer = self.signer.as_ref().ok_or(Error::MissingCredentials)?;
        let mut headers = self.headers.clone();

        let timestamp = self.server_timestamp();
        let signature = signer.sign_at(s, timestamp);
        headers.append(HEADER_X_BAPI_SIGN, signature.parse()?);
        headers.append(HEADER_X_BAPI_TIMESTAMP, timestamp.to_string().parse()?);

        Ok(headers)
    }
}

/// Server clock minus local clock, assuming the server read its clock halfway
/// between `sent_at` and `received_at` (local milliseconds).
fn estimate_time_offset(sent_at: Timestamp, received_at: Timestamp, server_ms: Timestamp) -> i64 {
    let midpoint = sent_at + received_at.saturating_sub(sent_at) / 2;
    server_ms as i64 - midpoint as i64
}

// Market.
impl Client {
    /// Get Bybit Server Time. See also [`Client::sync_time`].
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_server_time(&self) -> Result<Response<ServerTime>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketServerTime);

        let request = self.client.request(Method::GET, url);

        let response = self.send(Path::MarketServerTime, request).await?;
        Ok(response)
    }

    /// Get Kline.
    /// Query the kline data. Charts are returned in groups based on the requested interval.
    ///
    /// Covers: Spot / USDT contract / USDC contract / Inverse contract
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_kline(&self, params: &GetKLinesParams) -> Result<Response<KLine>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketKline);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketKline, request).await?;
        Ok(response)
    }

    /// Get Mark Price Kline.
    /// Query the mark price kline data. Charts are returned in groups based on the requested interval.
    ///
    /// Covers: linear / inverse
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_mark_price_kline(
        &self,
        params: &GetKLinesParams,
    ) -> Result<Response<PriceKLine>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketMarkPriceKline);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketMarkPriceKline, request).await?;
        Ok(response)
    }

    /// Get Index Price Kline.
    /// Query the index price kline data. Charts are returned in groups based on the requested interval.
    ///
    /// Covers: linear / inverse
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_index_price_kline(
        &self,
        params: &GetKLinesParams,
    ) -> Result<Response<PriceKLine>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketIndexPriceKline);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketIndexPriceKline, request).await?;
        Ok(response)
    }

    /// Get Premium Index Price Kline.
    /// Retrieve the premium index price kline data. Charts are returned in groups based on the requested interval.
    ///
    /// Covers: linear
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_premium_index_price_kline(
        &self,
        params: &GetKLinesParams,
    ) -> Result<Response<PriceKLine>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketPremiumIndexPriceKline);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self
            .send(Path::MarketPremiumIndexPriceKline, request)
            .await?;
        Ok(response)
    }

    /// Get Tickers
    /// Query for the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.
    /// If category=option, symbol or baseCoin must be passed.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_tickers(&self, params: &GetTickersParams) -> Result<Response<Ticker>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketTickers);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketTickers, request).await?;
        Ok(response)
    }

    /// Get Orderbook.
    /// Query for orderbook depth data.
    ///
    /// Covers: Spot / USDT contract / USDC contract / Inverse contract / Option
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_orderbook(
        &self,
        params: &GetOrderbookParams,
    ) -> Result<Response<Orderbook>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketOrderbook);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketOrderbook, request).await?;
        Ok(response)
    }

    /// Get Instruments Info.
    /// Query the specifications of online trading pairs.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_instruments_info(
        &self,
        params: &GetInstrumentsInfoParams,
    ) -> Result<Response<InstrumentsInfo>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketInstrumentsInfo);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketInstrumentsInfo, request).await?;
        Ok(response)
    }

    /// Get Recent Public Trades.
    /// Query recent public trading data.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_public_recent_trading_history(
        &self,
        params: &GetTradesParams,
    ) -> Result<Response<Trade>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketRecentTrade);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketRecentTrade, request).await?;
        Ok(response)
    }

    /// Get Funding Rate History.
    /// Query for historical funding rates. Each request returns up to 200 rows of data.
    ///
    /// Covers: linear / inverse
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_funding_rate_history(
        &self,
        params: &GetFundingRateHistoryParams,
    ) -> Result<Response<FundingRateHistory>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketFundingHistory);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketFundingHistory, request).await?;
        Ok(response)
    }

    /// Get Open Interest.
    /// Get the open interest of each symbol.
    ///
    /// Covers: linear / inverse
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_open_interest(
        &self,
        params: &GetOpenInterestParams,
    ) -> Result<Response<OpenInterest>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketOpenInterest);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketOpenInterest, request).await?;
        Ok(response)
    }

    /// Get Historical Volatility.
    /// Query option historical volatility.
    ///
    /// Covers: option only
    ///
    /// Note: the result is returned as a top-level JSON array, so the response
    /// wraps `Vec<HistoricalVolatilityEntry>` directly.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_historical_volatility(
        &self,
        params: &GetHistoricalVolatilityParams,
    ) -> Result<Response<Vec<HistoricalVolatilityEntry>>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketHistoricalVolatility);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketHistoricalVolatility, request).await?;
        Ok(response)
    }

    /// Get Insurance.
    /// Query for Bybit insurance pool data (1 day delay).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_insurance(
        &self,
        params: &GetInsuranceParams,
    ) -> Result<Response<Insurance>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketInsurance);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketInsurance, request).await?;
        Ok(response)
    }

    /// Get Risk Limit.
    /// Query for the risk limit.
    ///
    /// Covers: linear / inverse
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_risk_limit(
        &self,
        params: &GetRiskLimitParams,
    ) -> Result<Response<RiskLimit>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketRiskLimit);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketRiskLimit, request).await?;
        Ok(response)
    }

    /// Get Delivery Price.
    /// Get the delivery price for option and USDC futures contracts.
    ///
    /// Covers: linear / inverse / option
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_delivery_price(
        &self,
        params: &GetDeliveryPriceParams,
    ) -> Result<Response<DeliveryPrice>, Error> {
        let url = format!("{}{}", self.base_url, Path::MarketDeliveryPrice);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::MarketDeliveryPrice, request).await?;
        Ok(response)
    }
}

// Trade.
impl Client {
    /// Place Order
    /// This endpoint supports to create the order for Spot, Margin trading, USDT perpetual, USDT futures, USDC perpetual, USDC futures, Inverse Futures and Options.
    ///
    /// INFO:
    /// Supported order type (orderType):
    /// Limit order: orderType=Limit, it is necessary to specify order qty and price.
    ///
    /// Market order: orderType=Market, execute at the best price in the Bybit market until the transaction is completed. When selecting a market order, the "price" can be empty. In the futures trading system, in order to protect traders against the serious slippage of the Market order, Bybit trading engine will convert the market order into an IOC limit order for matching. If there are no orderbook entries within price slippage limit, the order will not be executed. If there is insufficient liquidity, the order will be cancelled. The slippage threshold refers to the percentage that the order price deviates from the mark price. You can learn more here: Adjustments to Bybit's Derivative Trading Price Limit Mechanism
    /// Supported timeInForce strategy:
    /// GTC
    /// IOC
    /// FOK
    /// PostOnly: If the order would be filled immediately when submitted, it will be cancelled. The purpose of this is to protect your order during the submission process. If the matching system cannot entrust the order to the order book due to price changes on the market, it will be cancelled.
    /// RPI: Retail Price Improvement order. Assigned market maker can place this kind of order, and it is a post only order, only match with the order from Web or APP.
    ///
    /// How to create a conditional order:
    /// When submitting an order, if triggerPrice is set, the order will be automatically converted into a conditional order. In addition, the conditional order does not occupy the margin. If the margin is insufficient after the conditional order is triggered, the order will be cancelled.
    ///
    /// Take profit / Stop loss: You can set TP/SL while placing orders. Besides, you could modify the position's TP/SL.
    ///
    /// Order quantity: The quantity of perpetual contracts you are going to buy/sell. For the order quantity, Bybit only supports positive number at present.
    ///
    /// Order price: Place a limit order, this parameter is required. If you have position, the price should be higher than the liquidation price. For the minimum unit of the price change, please refer to the priceFilter > tickSize field in the instruments-info endpoint.
    ///
    /// orderLinkId: You can customize the active order ID. We can link this ID to the order ID in the system. Once the active order is successfully created, we will send the unique order ID in the system to you. Then, you can use this order ID to cancel active orders, and if both orderId and orderLinkId are entered in the parameter input, Bybit will prioritize the orderId to process the corresponding order. Meanwhile, your customized order ID should be no longer than 36 characters and should be unique.
    ///
    /// Open orders up limit:
    /// Perps & Futures:
    /// a) Each account can hold a maximum of 500 active orders simultaneously per symbol.
    /// b) conditional orders: each account can hold a maximum of 10 active orders simultaneously per symbol.
    /// Spot: 500 orders in total, including a maximum of 30 open TP/SL orders, a maximum of 30 open conditional orders for each symbol per account
    /// Option: a maximum of 50 open orders per account
    ///
    /// Rate limit:
    /// Please refer to rate limit table. If you need to raise the rate limit, please contact your client manager or submit an application via here
    ///
    /// Risk control limit notice:
    /// Bybit will monitor on your API requests. When the total number of orders of a single user (aggregated the number of orders across main account and subaccounts) within a day (UTC 0 - UTC 24) exceeds a certain upper limit, the platform will reserve the right to remind, warn, and impose necessary restrictions. Customers who use API default to acceptance of these terms and have the obligation to cooperate with adjustments.
    ///
    /// Reduce only orders:
    /// If reduceOnly=true and order qty > max order qty, the order will automatically be split up into multiple orders.
    ///
    /// Spot Stop Order
    /// Spot supports TP/SL order, Conditional order, however, the system logic is different between classic account and Unified account
    /// classic account: When the stop order is created, you will get an order ID. After it is triggered, you will get a new order ID
    /// Unified account: When the stop order is created, you will get an order ID. After it is triggered, the order ID will not be changed
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn place_order(
        &self,
        request: &PlaceOrderRequest,
    ) -> Result<Response<PlaceOrderResponse>, Error> {
        let category = request.category;
        let url = format!("{}{}", self.base_url, Path::TradeOrderCreate);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderCreate, Some(category), 1, request)
            .await?;
        Ok(response)
    }

    /// Amend Order
    /// info
    /// You can only modify unfilled or partially filled orders.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn amend_order(
        &self,
        request: &AmendOrderRequest,
    ) -> Result<Response<AmendOrderResponse>, Error> {
        let category = request.category;
        let url = format!("{}{}", self.base_url, Path::TradeOrderAmend);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderAmend, Some(category), 1, request)
            .await?;
        Ok(response)
    }

    /// Cancel Order
    /// important
    /// You must specify orderId or orderLinkId to cancel the order.
    /// If orderId and orderLinkId do not match, the system will process orderId first.
    /// You can only cancel unfilled or partially filled orders.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn cancel_order(
        &self,
        request: &CancelOrderRequest,
    ) -> Result<Response<CancelOrderResponse>, Error> {
        let category = request.category;
        let url = format!("{}{}", self.base_url, Path::TradeOrderCancel);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderCancel, Some(category), 1, request)
            .await?;
        Ok(response)
    }

    /// Get Open & Closed Orders.
    /// Primarily query unfilled or partially filled orders in real-time, but also supports querying recent 500 closed status (Cancelled, Filled) orders. Please see the usage of request param openOnly.
    /// And to query older order records, please use the order history interface.
    ///
    /// Tip
    /// UTA2.0 can query filled, canceled, and rejected orders to the most recent 500 orders for spot, linear, inverse and option categories
    /// UTA1.0 can query filled, canceled, and rejected orders to the most recent 500 orders for spot, linear, and option categories. The inverse category is not subject to this limitation.
    /// You can query by symbol, baseCoin, orderId and orderLinkId, and if you pass multiple params, the system will process them according to this priority: orderId > orderLinkId > symbol > baseCoin.
    /// The records are sorted by the createdTime from newest to oldest.
    ///
    /// info
    /// classic account spot can return open orders only
    /// After a server release or restart, filled, canceled, and rejected orders of Unified account should only be queried through order history.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_open_closed_orders(
        &self,
        params: &GetOpenClosedOrdersParams,
    ) -> Result<Response<CursorPagination<Order>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::TradeOrderRealtime);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::TradeOrderRealtime, request).await?;
        Ok(response)
    }

    /// Collect all pages of open/closed orders into a single `Vec`.
    /// Repeatedly calls [`get_open_closed_orders`](Client::get_open_closed_orders) following `next_page_cursor`
    /// until the last page is reached (see [`MAX_PAGES`]).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_open_closed_orders_all(
        &self,
        params: &GetOpenClosedOrdersParams,
    ) -> Result<Vec<Order>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_open_closed_orders(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Cancel All Orders.
    /// Cancel all open orders. Support linear, inverse, spot, and option.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn cancel_all_orders(
        &self,
        request: &CancelAllOrdersRequest,
    ) -> Result<Response<CancelAllOrdersResponse>, Error> {
        let category = request.category;
        let url = format!("{}{}", self.base_url, Path::TradeOrderCancelAll);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderCancelAll, Some(category), 1, request)
            .await?;
        Ok(response)
    }

    /// Get Order History.
    /// Query order history. As order creation/cancellation is asynchronous, the data returned may be delayed.
    /// Supports up to 2 years of data.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_order_history(
        &self,
        params: &GetOrderHistoryParams,
    ) -> Result<Response<CursorPagination<Order>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::TradeOrderHistory);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::TradeOrderHistory, request).await?;
        Ok(response)
    }

    /// Collect all pages of order history into a single `Vec`.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_order_history_all(
        &self,
        params: &GetOrderHistoryParams,
    ) -> Result<Vec<Order>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_order_history(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Place Batch Orders.
    /// Supports up to 20 orders per request.
    /// Per-item results are in `response.ret_ext_info.list` (parallel to `response.result.list`).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn place_orders_batch(
        &self,
        request: &PlaceOrderBatchRequest,
    ) -> Result<Response<List<PlaceOrderBatchResult>>, Error> {
        let category = request.category;
        let cost = request.request.len() as u32;
        let url = format!("{}{}", self.base_url, Path::TradeOrderCreateBatch);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderCreateBatch, Some(category), cost, request)
            .await?;
        Ok(response)
    }

    /// Amend Batch Orders.
    /// Supports up to 20 orders per request.
    /// Per-item results are in `response.ret_ext_info.list` (parallel to `response.result.list`).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn amend_orders_batch(
        &self,
        request: &AmendOrderBatchRequest,
    ) -> Result<Response<List<AmendOrderBatchResult>>, Error> {
        let category = request.category;
        let cost = request.request.len() as u32;
        let url = format!("{}{}", self.base_url, Path::TradeOrderAmendBatch);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderAmendBatch, Some(category), cost, request)
            .await?;
        Ok(response)
    }

    /// Cancel Batch Orders.
    /// Supports up to 20 orders per request.
    /// Per-item results are in `response.ret_ext_info.list` (parallel to `response.result.list`).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn cancel_orders_batch(
        &self,
        request: &CancelOrderBatchRequest,
    ) -> Result<Response<List<CancelOrderBatchResult>>, Error> {
        let category = request.category;
        let cost = request.request.len() as u32;
        let url = format!("{}{}", self.base_url, Path::TradeOrderCancelBatch);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self
            .send_weighted(Path::TradeOrderCancelBatch, Some(category), cost, request)
            .await?;
        Ok(response)
    }

    /// Get Spot Borrow Check.
    /// Query the maximum quantity for purchase or sale, and check the borrowable quantity based on the fee types.
    ///
    /// Covers: spot only. Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_spot_borrow_check(
        &self,
        params: &GetSpotBorrowCheckParams,
    ) -> Result<Response<SpotBorrowCheck>, Error> {
        let url = format!("{}{}", self.base_url, Path::TradeOrderSpotBorrowCheck);
        let query = serialize_query(params)?;
        let headers = self.get_signed_headers(&query)?;

        let request = self
            .client
            .request(Method::GET, url)
            .headers(headers)
            .query(params);

        let response = self.send(Path::TradeOrderSpotBorrowCheck, request).await?;
        Ok(response)
    }
}

// Position.
impl Client {
    /// Query real-time position data, such as position size, cumulative realized PNL, etc.
    /// Query real-time position data, such as position size, cumulative realized PNL, etc.
    ///
    /// INFO
    // UTA2.0(inverse)
    // You can query all open positions with /v5/position/list?category=inverse;
    // Cannot query multiple symbols in one request
    // UTA1.0(inverse) & Classic (inverse)
    // You can query all open positions with /v5/position/list?category=inverse;
    // symbol parameter can pass up to 10 symbols, e.g., symbol=BTCUSD,ETHUSD
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_position_info(
        &self,
        params: &GetPositionInfoParams,
    ) -> Result<Response<CursorPagination<Position>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::PositionList);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::PositionList, request).await?;
        Ok(response)
    }

    /// Collect all pages of position info into a single `Vec`.
    /// Repeatedly calls [`get_position_info`](Client::get_position_info) following `next_page_cursor`
    /// until the last page is reached (see [`MAX_PAGES`]).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_position_info_all(
        &self,
        params: &GetPositionInfoParams,
    ) -> Result<Vec<Position>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_position_info(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Set Leverage.
    /// Set the leverage for a position. Only for isolated margin mode.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_leverage(
        &self,
        request: &SetLeverageRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionSetLeverage);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionSetLeverage, request).await?;
        Ok(response)
    }

    /// Set Trading Stop.
    /// Set take profit, stop loss, or trailing stop for a position.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_trading_stop(
        &self,
        request: &SetTradingStopRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionTradingStop);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionTradingStop, request).await?;
        Ok(response)
    }

    /// Switch Cross/Isolated Margin.
    /// Switch the margin mode for a symbol between cross and isolated.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn switch_cross_isolated_margin(
        &self,
        request: &SwitchCrossIsolatedMarginRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionSwitchIsolated);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionSwitchIsolated, request).await?;
        Ok(response)
    }

    /// Switch Position Mode.
    /// Switch between one-way (merged single) and hedge (both sides) position mode.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn switch_position_mode(
        &self,
        request: &SwitchPositionModeRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionSwitchMode);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionSwitchMode, request).await?;
        Ok(response)
    }

    /// Set Auto Add Margin.
    /// Turn on/off auto-add-margin for an isolated margin position.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_auto_add_margin(
        &self,
        request: &SetAutoAddMarginRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionSetAutoAddMargin);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionSetAutoAddMargin, request).await?;
        Ok(response)
    }

    /// Set Risk Limit.
    /// Set the risk limit for a position. The response includes the new risk limit and its value.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_risk_limit(
        &self,
        request: &SetRiskLimitRequest,
    ) -> Result<Response<SetRiskLimitResponse>, Error> {
        let url = format!("{}{}", self.base_url, Path::PositionSetRiskLimit);
        let json = serialize_json(request)?;
        let headers = self.get_signed_headers(&json)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(json);

        let response = self.send(Path::PositionSetRiskLimit, request).await?;
        Ok(response)
    }

    /// Get Closed P&L.
    /// Query the closed profit and loss records of positions.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_closed_pnl(
        &self,
        params: &GetClosedPnlParams,
    ) -> Result<Response<CursorPagination<ClosedPnl>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::PositionClosedPnl);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::PositionClosedPnl, request).await?;
        Ok(response)
    }

    /// Collect all pages of closed P&L into a single `Vec`.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_closed_pnl_all(
        &self,
        params: &GetClosedPnlParams,
    ) -> Result<Vec<ClosedPnl>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_closed_pnl(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Get Execution List.
    /// Query users' execution (trading) records, sorted by execTime descending.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_execution_list(
        &self,
        params: &GetExecutionListParams,
    ) -> Result<Response<CursorPagination<ExecutionEntry>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::ExecutionList);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::ExecutionList, request).await?;
        Ok(response)
    }

    /// Collect all pages of execution list entries into a single `Vec`.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_execution_list_all(
        &self,
        params: &GetExecutionListParams,
    ) -> Result<Vec<ExecutionEntry>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_execution_list(&p).await.map(|r| r.result) }
        })
        .await
    }
}

// Account.
impl Client {
    /// Obtain wallet balance, query asset information of each currency. By default, currency information with assets or liabilities of 0 is not returned.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_wallet_balance(
        &self,
        params: &GetWalletBalanceParams,
    ) -> Result<Response<List<WalletBalance>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AccountWalletBalance);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AccountWalletBalance, request).await?;
        Ok(response)
    }

    /// Get Transaction Log
    /// Query for transaction logs in your Unified account. It supports up to 2 years worth of data.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_transaction_log(
        &self,
        params: &GetTransactionLogParams,
    ) -> Result<Response<CursorPagination<TransactionLog>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AccountTransactionLog);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AccountTransactionLog, request).await?;
        Ok(response)
    }

    /// Collect all pages of transaction log entries into a single `Vec`.
    /// Repeatedly calls [`get_transaction_log`](Client::get_transaction_log) following `next_page_cursor`
    /// until the last page is reached (see [`MAX_PAGES`]).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_transaction_log_all(
        &self,
        params: &GetTransactionLogParams,
    ) -> Result<Vec<TransactionLog>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_transaction_log(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Query the account information, like margin mode, account mode, etc.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_account_info(&self) -> Result<Response<AccountInfo>, Error> {
        let url = format!("{}{}", self.base_url, Path::AccountInfo);
        let query = "";
        let headers = self.get_signed_headers(query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AccountInfo, request).await?;
        Ok(response)
    }

    /// Get Fee Rate.
    /// Get the trading fee rate.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_fee_rate(
        &self,
        params: &GetFeeRateParams,
    ) -> Result<Response<List<FeeRateEntry>>, Error> {
        let url = format!("{}{}", self.base_url, Path::AccountFeeRate);
        let query = serialize_query(params)?;
        let headers = self.get_signed_headers(&query)?;

        let request = self
            .client
            .request(Method::GET, url)
            .headers(headers)
            .query(params);

        let response = self.send(Path::AccountFeeRate, request).await?;
        Ok(response)
    }

    /// Set Margin Mode.
    /// Switch between regular margin, isolated margin, and portfolio margin.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_margin_mode(
        &self,
        request_body: &SetMarginModeRequest,
    ) -> Result<Response<SetMarginModeResponse>, Error> {
        let url = format!("{}{}", self.base_url, Path::AccountSetMarginMode);
        let body = serialize_json(request_body)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::AccountSetMarginMode, request).await?;
        Ok(response)
    }

    /// Upgrade to Unified Account (Pro).
    /// Upgrades an account to Unified Account Pro (UTA2.0 Pro). No open orders may exist
    /// during the upgrade.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn upgrade_to_uta(&self) -> Result<Response<UpgradeToUtaResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AccountUpgradeToUta);
        let body = "{}".to_owned();
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::AccountUpgradeToUta, request).await?;
        Ok(response)
    }

    /// Get Borrow History.
    /// Get interest records, sorted in reverse order of creation time.
    ///
    /// Requires authentication. Unified account only.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_borrow_history(
        &self,
        params: &GetBorrowHistoryParams,
    ) -> Result<Response<CursorPagination<BorrowHistoryEntry>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AccountBorrowHistory);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AccountBorrowHistory, request).await?;
        Ok(response)
    }

    /// Collect all pages of borrow history entries into a single `Vec`.
    /// Repeatedly calls [`get_borrow_history`](Client::get_borrow_history) following
    /// `next_page_cursor` until the last page is reached.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_borrow_history_all(
        &self,
        params: &GetBorrowHistoryParams,
    ) -> Result<Vec<BorrowHistoryEntry>, Error> {
        collect_pages(|cursor| {
            let p = match cursor {
                Some(cursor) => params.clone().with_cursor(cursor),
                None => params.clone(),
            };
            async move { self.get_borrow_history(&p).await.map(|r| r.result) }
        })
        .await
    }

    /// Get Collateral Info.
    /// Query the collateral ratio, and information of the collateral ratio tier, for each
    /// currency.
    ///
    /// Requires authentication. Unified account only.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_collateral_info(
        &self,
        params: &GetCollateralInfoParams,
    ) -> Result<Response<List<CollateralInfoEntry>>, Error> {
        let url = format!("{}{}", self.base_url, Path::AccountCollateralInfo);
        let query = serialize_query(params)?;
        let headers = self.get_signed_headers(&query)?;

        let request = self
            .client
            .request(Method::GET, url)
            .headers(headers)
            .query(params);

        let response = self.send(Path::AccountCollateralInfo, request).await?;
        Ok(response)
    }
}

// User.
impl Client {
    /// Get API Key Information.
    /// Get the information of the api key. Use the api key pending to be checked to call the endpoint. Both master and sub user's api key are applicable.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_api_key_information(&self) -> Result<Response<APIKeyInformation>, Error> {
        let url = format!("{}{}", self.base_url, Path::UserQueryApi);
        let query = "";
        let headers = self.get_signed_headers(query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::UserQueryApi, request).await?;
        Ok(response)
    }
}

// Asset.
impl Client {
    /// Create Internal Transfer.
    /// Transfer between different account types under the same UID.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn internal_transfer(
        &self,
        request: &InternalTransferRequest,
    ) -> Result<Response<TransferResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetTransferInterTransfer);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::AssetTransferInterTransfer, request).await?;
        Ok(response)
    }

    /// Get Internal Transfer Records.
    /// Query the internal transfer records between different account types under the same UID.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_internal_transfer_records(
        &self,
        params: &GetInternalTransferRecordsParams,
    ) -> Result<Response<CursorPagination<InternalTransferEntry>>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetTransferQueryInterTransferList
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQueryInterTransferList, request)
            .await?;
        Ok(response)
    }

    /// Create Universal Transfer.
    /// Transfer between a master account and its sub-accounts, or between two sub-accounts.
    ///
    /// Requires authentication. Requires the master UID's API key, or a sub-account key with
    /// the `SubMemberTransferList` permission (may only transfer to the master account).
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn universal_transfer(
        &self,
        request: &UniversalTransferRequest,
    ) -> Result<Response<TransferResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetTransferUniversalTransfer);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self
            .send(Path::AssetTransferUniversalTransfer, request)
            .await?;
        Ok(response)
    }

    /// Get Universal Transfer Records.
    ///
    /// Requires authentication. Requires the master UID's API key, or a sub-account key with
    /// the `SubMemberTransferList` permission.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_universal_transfer_records(
        &self,
        params: &GetUniversalTransferRecordsParams,
    ) -> Result<Response<CursorPagination<UniversalTransferEntry>>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetTransferQueryUniversalTransferList
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQueryUniversalTransferList, request)
            .await?;
        Ok(response)
    }

    /// Get Transferable Coin.
    /// Query the transferable coins between two account types.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_transferable_coins(
        &self,
        params: &GetTransferableCoinsParams,
    ) -> Result<Response<List<String>>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetTransferQueryTransferCoinList
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQueryTransferCoinList, request)
            .await?;
        Ok(response)
    }

    /// Enable Universal Transfer For Sub UID.
    ///
    /// Deprecated by Bybit: all sub UIDs are now automatically enabled for universal transfer,
    /// so this call is no longer necessary. Kept for completeness. Requires the master UID's
    /// API key.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn save_transfer_sub_member(
        &self,
        request: &SaveTransferSubMemberRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!(
            "{}{}",
            self.base_url,
            Path::AssetTransferSaveTransferSubMember
        );
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self
            .send(Path::AssetTransferSaveTransferSubMember, request)
            .await?;
        Ok(response)
    }

    /// Get Sub UID (for universal transfer).
    /// Query the sub UIDs under a master account, and which of them are enabled for universal
    /// transfer.
    ///
    /// Requires authentication. Requires the master UID's API key.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_transferable_sub_members(
        &self,
    ) -> Result<Response<TransferableSubMembers>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetTransferQuerySubMemberList);
        let query = "";
        let headers = self.get_signed_headers(query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQuerySubMemberList, request)
            .await?;
        Ok(response)
    }

    /// Get Single Coin Balance.
    /// Query the balance of a specific coin in a specific account type, or the balance that is
    /// safe to transfer between two accounts.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_account_coin_balance(
        &self,
        params: &GetAccountCoinBalanceParams,
    ) -> Result<Response<AccountCoinBalance>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetTransferQueryAccountCoinBalance
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQueryAccountCoinBalance, request)
            .await?;
        Ok(response)
    }

    /// Get Asset Info (Spot).
    /// Query for the balance of the Spot account.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_asset_info(
        &self,
        params: &GetAssetInfoParams,
    ) -> Result<Response<AssetInfoResult>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetTransferQueryAssetInfo
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetTransferQueryAssetInfo, request)
            .await?;
        Ok(response)
    }

    /// Get Allowed Deposit Coin Info.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_deposit_allowed_coin_info(
        &self,
        params: &GetDepositAllowedCoinInfoParams,
    ) -> Result<Response<DepositAllowedCoinInfoResult>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetDepositQueryAllowedList
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetDepositQueryAllowedList, request)
            .await?;
        Ok(response)
    }

    /// Get Deposit Records (on-chain).
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_deposit_records(
        &self,
        params: &GetDepositRecordsParams,
    ) -> Result<Response<DepositRecords>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AssetDepositQueryRecord);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetDepositQueryRecord, request).await?;
        Ok(response)
    }

    /// Get Sub Account Deposit Records (on-chain).
    ///
    /// Requires authentication. Requires the master UID's API key.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_sub_deposit_records(
        &self,
        params: &GetSubDepositRecordsParams,
    ) -> Result<Response<DepositRecords>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetDepositQuerySubMemberRecord
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetDepositQuerySubMemberRecord, request)
            .await?;
        Ok(response)
    }

    /// Get Master Deposit Address.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_deposit_address(
        &self,
        params: &GetDepositAddressParams,
    ) -> Result<Response<DepositAddress>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetDepositQueryAddress
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetDepositQueryAddress, request).await?;
        Ok(response)
    }

    /// Get Sub Account Deposit Address.
    ///
    /// Requires authentication. Requires the master account's API key.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_sub_deposit_address(
        &self,
        params: &GetSubDepositAddressParams,
    ) -> Result<Response<DepositAddress>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetDepositQuerySubMemberAddress
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetDepositQuerySubMemberAddress, request)
            .await?;
        Ok(response)
    }

    /// Get Withdrawal Records.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_withdrawal_records(
        &self,
        params: &GetWithdrawalRecordsParams,
    ) -> Result<Response<WithdrawRecords>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetWithdrawQueryRecord
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetWithdrawQueryRecord, request).await?;
        Ok(response)
    }

    /// Get Withdrawable Amount.
    /// Query the amount available to withdraw for a coin, combined across the FUND, UTA, SPOT
    /// and EARN wallets, along with any amount still frozen pending deposit risk review.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_withdrawable_amount(
        &self,
        params: &GetWithdrawableAmountParams,
    ) -> Result<Response<WithdrawableAmountResult>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetWithdrawWithdrawableAmount
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self
            .send(Path::AssetWithdrawWithdrawableAmount, request)
            .await?;
        Ok(response)
    }

    /// Withdraw.
    /// Create a withdrawal request.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn withdraw(
        &self,
        request: &WithdrawRequest,
    ) -> Result<Response<WithdrawResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetWithdrawCreate);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::AssetWithdrawCreate, request).await?;
        Ok(response)
    }

    /// Cancel Withdrawal.
    /// Cancel a pending withdrawal request.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn cancel_withdrawal(
        &self,
        request: &CancelWithdrawalRequest,
    ) -> Result<Response<CancelWithdrawalResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetWithdrawCancel);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::AssetWithdrawCancel, request).await?;
        Ok(response)
    }

    /// Get Coin Info.
    /// Query coin information, including chains, deposit/withdrawal limits, and fees.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_coin_info(
        &self,
        params: &GetCoinInfoParams,
    ) -> Result<Response<CoinInfoResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::AssetCoinQueryInfo);
        let query = serialize_query(params)?;
        let headers = self.get_signed_headers(&query)?;

        let request = self
            .client
            .request(Method::GET, url)
            .headers(headers)
            .query(params);

        let response = self.send(Path::AssetCoinQueryInfo, request).await?;
        Ok(response)
    }

    /// Get Coin Exchange Records.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_exchange_order_record(
        &self,
        params: &GetExchangeOrderRecordParams,
    ) -> Result<Response<ExchangeOrderRecords>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::AssetExchangeOrderRecord
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetExchangeOrderRecord, request).await?;
        Ok(response)
    }

    /// Get Delivery Record.
    /// Query delivery records of USDC futures and Options, sorted by descending delivery time.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_delivery_record(
        &self,
        params: &GetDeliveryRecordParams,
    ) -> Result<Response<CursorPagination<DeliveryRecord>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AssetDeliveryRecord);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetDeliveryRecord, request).await?;
        Ok(response)
    }

    /// Get USDC Session Settlement.
    /// Query session settlement records of USDC perpetual contracts.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_settlement_record(
        &self,
        params: &GetSettlementRecordParams,
    ) -> Result<Response<CursorPagination<SettlementRecord>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AssetSettlementRecord);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetSettlementRecord, request).await?;
        Ok(response)
    }

    /// Get Coin Greeks.
    /// Query the current account's Greeks information. Option only.
    ///
    /// Requires authentication.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_coin_greeks(
        &self,
        params: &GetCoinGreeksParams,
    ) -> Result<Response<List<CoinGreeks>>, Error> {
        let query = serialize_query(params)?;
        let url = format!("{}{}?{query}", self.base_url, Path::AssetCoinGreeks);
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::AssetCoinGreeks, request).await?;
        Ok(response)
    }
}

// Spot Leveraged Token: shut down by Bybit on 2025-07-04 (changelog of
// 2025-06-30); the methods are deprecated and will be removed.
impl Client {
    /// Get Leverage Token Info.
    /// Query leveraged token information, such as purchase/redeem limits and fees.
    ///
    /// No authentication required.
    #[deprecated(
        since = "0.3.0",
        note = "Bybit shut down the leveraged token API on 2025-07-04; the endpoint returns HTTP 404"
    )]
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_leverage_token_info(
        &self,
        params: &GetLeverageTokenInfoParams,
    ) -> Result<Response<List<LeverageTokenInfo>>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotLeverTokenInfo);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::SpotLeverTokenInfo, request).await?;
        Ok(response)
    }

    /// Get Leverage Token Market.
    /// Query the leveraged token market data, such as net asset value and real leverage.
    ///
    /// No authentication required.
    #[deprecated(
        since = "0.3.0",
        note = "Bybit shut down the leveraged token API on 2025-07-04; the endpoint returns HTTP 404"
    )]
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_leverage_token_market(
        &self,
        params: &GetLeverageTokenMarketParams,
    ) -> Result<Response<LeverageTokenMarket>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotLeverTokenReference);

        let request = self.client.request(Method::GET, url).query(params);

        let response = self.send(Path::SpotLeverTokenReference, request).await?;
        Ok(response)
    }

    /// Purchase.
    /// Purchase a leveraged token.
    ///
    /// Requires authentication.
    #[deprecated(
        since = "0.3.0",
        note = "Bybit shut down the leveraged token API on 2025-07-04; the endpoint returns HTTP 404"
    )]
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn purchase_leverage_token(
        &self,
        request: &PurchaseLeverageTokenRequest,
    ) -> Result<Response<PurchaseLeverageTokenResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotLeverTokenPurchase);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::SpotLeverTokenPurchase, request).await?;
        Ok(response)
    }

    /// Redeem.
    /// Redeem a leveraged token.
    ///
    /// Requires authentication.
    #[deprecated(
        since = "0.3.0",
        note = "Bybit shut down the leveraged token API on 2025-07-04; the endpoint returns HTTP 404"
    )]
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn redeem_leverage_token(
        &self,
        request: &RedeemLeverageTokenRequest,
    ) -> Result<Response<RedeemLeverageTokenResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotLeverTokenRedeem);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::SpotLeverTokenRedeem, request).await?;
        Ok(response)
    }

    /// Get Purchase/Redemption Records.
    ///
    /// Requires authentication.
    #[deprecated(
        since = "0.3.0",
        note = "Bybit shut down the leveraged token API on 2025-07-04; the endpoint returns HTTP 404"
    )]
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn get_leverage_token_order_records(
        &self,
        params: &GetLeverageTokenOrderRecordsParams,
    ) -> Result<Response<List<LeverageTokenOrderRecord>>, Error> {
        let query = serialize_query(params)?;
        let url = format!(
            "{}{}?{query}",
            self.base_url,
            Path::SpotLeverTokenOrderRecord
        );
        let headers = self.get_signed_headers(&query)?;

        let request = self.client.request(Method::GET, url).headers(headers);

        let response = self.send(Path::SpotLeverTokenOrderRecord, request).await?;
        Ok(response)
    }
}

// Spot Margin Trade (UTA).
impl Client {
    /// Toggle Margin Trade.
    /// Turn spot margin trade on or off for the Unified account.
    ///
    /// Requires authentication. The account must have completed spot margin activation
    /// (including the required quiz) beforehand.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn switch_spot_margin_mode(
        &self,
        request: &SwitchSpotMarginModeRequest,
    ) -> Result<Response<SwitchSpotMarginModeResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotMarginTradeSwitchMode);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::SpotMarginTradeSwitchMode, request).await?;
        Ok(response)
    }

    /// Set Leverage.
    /// Set the maximum leverage for spot margin trade.
    ///
    /// Requires authentication. The account must have completed spot margin activation
    /// (including the required quiz) beforehand.
    #[tracing::instrument(level = "debug", skip_all, err(level = "debug"))]
    pub async fn set_spot_margin_leverage(
        &self,
        request: &SetSpotMarginLeverageRequest,
    ) -> Result<Response<EmptyResult>, Error> {
        let url = format!("{}{}", self.base_url, Path::SpotMarginTradeSetLeverage);
        let body = serialize_json(request)?;
        let headers = self.get_signed_headers(&body)?;

        let request = self
            .client
            .request(Method::POST, url)
            .headers(headers)
            .body(body);

        let response = self.send(Path::SpotMarginTradeSetLeverage, request).await?;
        Ok(response)
    }
}

impl Client {
    /// Send a request against a category-independent rate-limit bucket, with a cost of 1.
    async fn send<T>(&self, path: Path, request: RequestBuilder) -> Result<Response<T>, Error>
    where
        T: serde::de::DeserializeOwned,
    {
        self.send_weighted(path, None, 1, request).await
    }

    /// Send a request against the bucket identified by `path` and `category`, consuming
    /// `cost` units of that bucket's quota. Use `cost > 1` for batch endpoints, where Bybit
    /// consumes one unit per order in the batch rather than one per request.
    async fn send_weighted<T>(
        &self,
        path: Path,
        category: Option<Category>,
        cost: u32,
        request: RequestBuilder,
    ) -> Result<Response<T>, Error>
    where
        T: serde::de::DeserializeOwned,
    {
        let key = RateLimitKey { path, category };
        let request = request.build()?;
        let signed = request.headers().contains_key(HEADER_X_BAPI_SIGN);
        let retry = (signed && self.resync_time_on_timestamp_error)
            .then(|| request.try_clone())
            .flatten();

        match self.execute_once(key, cost, request).await {
            Err(e) if e.is_timestamp_error() && retry.is_some() => {
                let mut retry = retry.expect("checked above");
                let offset_ms = self.sync_time().await?;
                tracing::debug!(%path, offset_ms, "timestamp rejected, retrying with server time");
                self.resign(&mut retry)?;
                self.execute_once(key, cost, retry).await
            }
            result => result,
        }
    }

    /// Rate-limit check, send, rate-limit bookkeeping and response parsing for
    /// one attempt.
    async fn execute_once<T>(
        &self,
        key: RateLimitKey,
        cost: u32,
        request: reqwest::Request,
    ) -> Result<Response<T>, Error>
    where
        T: serde::de::DeserializeOwned,
    {
        let path = key.path;
        if let Some(rl) = &self.rate_limiter {
            rl.check(key, cost).map_err(|rejection| match rejection {
                Rejection::RetryAfter(retry_after_ms) => Error::RateLimited { retry_after_ms },
                Rejection::Unsatisfiable { cost, burst } => {
                    Error::RateLimitUnsatisfiable { cost, burst }
                }
            })?;
        }

        let start = std::time::Instant::now();
        let response = self.client.execute(request).await?;
        let elapsed_ms = start.elapsed().as_millis();
        let status = response.status();
        let headers = parse_headers(response.headers());

        if let Some(rl) = &self.rate_limiter {
            rl.update(
                key,
                headers.api_limit_status,
                headers.api_limit_reset_timestamp,
            );
        }

        let body = response.text().await?;
        let result = parse_response(status, headers, &body);
        match &result {
            Ok(response) => tracing::debug!(
                %path,
                elapsed_ms,
                api_limit = response.headers.api_limit,
                api_limit_status = response.headers.api_limit_status,
                "api call completed"
            ),
            Err(e) => tracing::debug!(%path, elapsed_ms, error = %e, "api call failed"),
        }
        result
    }

    /// Sign `request` again with the current server time. The signed payload
    /// is what is actually sent: the body of a POST, the query of a GET.
    fn resign(&self, request: &mut reqwest::Request) -> Result<(), Error> {
        let signer = self.signer.as_ref().ok_or(Error::MissingCredentials)?;
        let payload = match request.body().and_then(|body| body.as_bytes()) {
            Some(body) => String::from_utf8_lossy(body).into_owned(),
            None => request.url().query().unwrap_or_default().to_owned(),
        };
        let timestamp = self.server_timestamp();
        let signature = signer.sign_at(&payload, timestamp);
        let headers = request.headers_mut();
        headers.insert(HEADER_X_BAPI_SIGN, signature.parse()?);
        headers.insert(HEADER_X_BAPI_TIMESTAMP, timestamp.to_string().parse()?);
        Ok(())
    }
}

/// Upper bound on the number of pages fetched by the `*_all` methods.
pub const MAX_PAGES: usize = 1000;

/// Follow `next_page_cursor` until the last page and concatenate the lists.
///
/// `fetch` receives `None` for the first page and the cursor of the next page
/// afterwards. Stops when there is no cursor, when a page is empty or when the
/// server repeats the previous cursor (guards against endless loops), and
/// fails with [`Error::TooManyPages`] after [`MAX_PAGES`] pages.
async fn collect_pages<T, F, Fut>(mut fetch: F) -> Result<Vec<T>, Error>
where
    F: FnMut(Option<String>) -> Fut,
    Fut: std::future::Future<Output = Result<CursorPagination<T>, Error>>,
{
    let mut all = Vec::new();
    let mut cursor: Option<String> = None;
    for _ in 0..MAX_PAGES {
        let page = fetch(cursor.clone()).await?;
        let empty = page.list.is_empty();
        all.extend(page.list);
        match page.next_page_cursor {
            Some(next) if !empty && cursor.as_ref() != Some(&next) => cursor = Some(next),
            _ => return Ok(all),
        }
    }
    Err(Error::TooManyPages { max: MAX_PAGES })
}

/// Turn a raw HTTP response into a [`Response`] or an [`Error`].
///
/// A non-2xx status is reported as [`Error::Api`] when the body is a Bybit
/// error envelope and as [`Error::Http`] otherwise (e.g. an HTML page from a
/// CDN or gateway). For a 2xx status the `retCode` of the body decides.
fn parse_response<T>(status: StatusCode, headers: Headers, body: &str) -> Result<Response<T>, Error>
where
    T: serde::de::DeserializeOwned,
{
    let envelope = deserialize_json::<APIErrorResponse>(body);

    if !status.is_success() {
        return Err(match envelope {
            Ok(envelope) if envelope.ret_code != 0 => envelope.into(),
            _ => Error::Http {
                status: status.as_u16(),
                body: truncate(body, MAX_ERROR_BODY_LEN).to_owned(),
            },
        });
    }

    let envelope = envelope?;
    if envelope.ret_code != 0 {
        return Err(envelope.into());
    }

    let response: Resp<T> = deserialize_json(body)?;
    Ok(Response {
        result: response.result,
        time: response.time,
        headers,
        ret_ext_info: response.ret_ext_info,
    })
}

/// Longest prefix of `s` not exceeding `max` bytes that ends on a char boundary.
fn truncate(s: &str, max: usize) -> &str {
    if s.len() <= max {
        return s;
    }
    let mut end = max;
    while !s.is_char_boundary(end) {
        end -= 1;
    }
    &s[..end]
}

/// Parse response headers: ret_code, traceid, timenow, X-Bapi-Limit, X-Bapi-Limit-Status, X-Bapi-Limit-Reset-Timestamp
fn parse_headers(headers: &HeaderMap) -> Headers {
    let ret_code = headers
        .get(HEADER_RET_CODE)
        .and_then(|h| h.to_str().unwrap_or_default().parse().ok());
    let trace_id = headers
        .get(HEADER_TRACE_ID)
        .and_then(|h| h.to_str().map(|str| str.into()).ok());
    let time_now = headers
        .get(HEADER_TIME_NOW)
        .and_then(|h| h.to_str().unwrap_or_default().parse().ok());

    let api_limit = headers
        .get(HEADER_X_BAPI_LIMIT)
        .and_then(|h| h.to_str().unwrap_or_default().parse().ok());
    let api_limit_status = headers
        .get(HEADER_X_BAPI_LIMIT_STATUS)
        .and_then(|h| h.to_str().unwrap_or_default().parse().ok());
    let api_limit_reset_timestamp = headers
        .get(HEADER_X_BAPI_LIMIT_RESET_TIMESTAMP)
        .and_then(|h| h.to_str().unwrap_or_default().parse().ok());

    Headers {
        ret_code,
        trace_id,
        time_now,
        api_limit,
        api_limit_status,
        api_limit_reset_timestamp,
    }
}

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

    fn headers() -> Headers {
        parse_headers(&HeaderMap::new())
    }

    #[test]
    fn parse_response_success() {
        let body = r#"{"retCode":0,"retMsg":"OK","result":{"timeSecond":"1688639403","timeNano":"1688639403423213947"},"retExtInfo":{},"time":1688639403423}"#;

        let response: Response<ServerTime> =
            parse_response(StatusCode::OK, headers(), body).unwrap();

        assert_eq!(response.time, Some(1688639403423));
    }

    #[test]
    fn parse_response_api_error_with_http_200() {
        let body = r#"{"retCode":10001,"retMsg":"params error","result":{},"retExtInfo":{},"time":1688639403423}"#;

        let err = parse_response::<ServerTime>(StatusCode::OK, headers(), body).unwrap_err();

        assert!(matches!(err, Error::Api { code: 10001, ref msg } if msg == "params error"));
    }

    #[test]
    fn parse_response_api_error_with_http_error_status() {
        let body = r#"{"retCode":10006,"retMsg":"Too many visits!","result":{},"retExtInfo":{},"time":1688639403423}"#;

        let err = parse_response::<ServerTime>(StatusCode::TOO_MANY_REQUESTS, headers(), body)
            .unwrap_err();

        assert!(matches!(err, Error::Api { code: 10006, .. }));
    }

    #[test]
    fn parse_response_non_json_error_page() {
        let body = "<html><body>403 Forbidden</body></html>";

        let err = parse_response::<ServerTime>(StatusCode::FORBIDDEN, headers(), body).unwrap_err();

        assert!(matches!(err, Error::Http { status: 403, body: ref b } if b == body));
    }

    #[test]
    fn truncate_respects_char_boundaries() {
        assert_eq!(truncate("abc", 10), "abc");
        assert_eq!(truncate("ab\u{00e9}c", 3), "ab");
    }

    fn page(list: Vec<u32>, cursor: Option<&str>) -> CursorPagination<u32> {
        CursorPagination {
            category: None,
            next_page_cursor: cursor.map(String::from),
            list,
        }
    }

    /// Serves `pages` in order and records the cursors it was asked for.
    async fn collect_from(
        pages: Vec<CursorPagination<u32>>,
    ) -> (Result<Vec<u32>, Error>, Vec<Option<String>>) {
        let mut pages = pages.into_iter();
        let mut requested = Vec::new();
        let result = collect_pages(|cursor| {
            requested.push(cursor);
            let page = pages.next().expect("unexpected extra request");
            async move { Ok(page) }
        })
        .await;
        (result, requested)
    }

    #[tokio::test]
    async fn collect_pages_follows_cursor_until_none() {
        let (result, requested) = collect_from(vec![
            page(vec![1, 2], Some("a")),
            page(vec![3], Some("b")),
            page(vec![4], None),
        ])
        .await;

        assert_eq!(result.unwrap(), vec![1, 2, 3, 4]);
        assert_eq!(requested, vec![None, Some("a".into()), Some("b".into())]);
    }

    #[tokio::test]
    async fn collect_pages_stops_on_repeated_cursor() {
        let (result, _) =
            collect_from(vec![page(vec![1], Some("a")), page(vec![2], Some("a"))]).await;

        assert_eq!(result.unwrap(), vec![1, 2]);
    }

    #[tokio::test]
    async fn collect_pages_stops_on_empty_page_with_cursor() {
        let (result, _) =
            collect_from(vec![page(vec![1], Some("a")), page(vec![], Some("b"))]).await;

        assert_eq!(result.unwrap(), vec![1]);
    }

    #[tokio::test]
    async fn collect_pages_fails_after_max_pages() {
        let mut n = 0;
        let result = collect_pages(|_| {
            n += 1;
            let cursor = n.to_string();
            async move { Ok(page(vec![1], Some(&cursor))) }
        })
        .await;

        assert!(matches!(
            result,
            Err(Error::TooManyPages { max: MAX_PAGES })
        ));
        assert_eq!(n, MAX_PAGES);
    }

    #[test]
    fn time_offset_is_measured_from_the_middle_of_the_round_trip() {
        // Request sent at 1000, answer received at 1100, server said 61050.
        assert_eq!(estimate_time_offset(1000, 1100, 61_050), 60_000);
        // Local clock ahead of the server.
        assert_eq!(estimate_time_offset(1000, 1000, 400), -600);
    }

    /// Minimal HTTP server: answers every request with `body_for(path)` and
    /// records the request heads it received.
    /// Minimal HTTP server: answers every request with `body_for(request)`
    /// (request line, headers and body) and records the requests.
    async fn spawn_http_server(
        body_for: fn(&str) -> String,
    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let requests = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let recorded = requests.clone();
        tokio::spawn(async move {
            while let Ok((mut tcp, _)) = listener.accept().await {
                let mut head = Vec::new();
                let mut buf = [0u8; 1024];
                while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                    match tcp.read(&mut buf).await {
                        Ok(0) | Err(_) => break,
                        Ok(n) => head.extend_from_slice(&buf[..n]),
                    }
                }
                let text = String::from_utf8_lossy(&head).into_owned();
                let content_length: usize = text
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse().unwrap_or(0))
                    })
                    .unwrap_or(0);
                let header_len = head
                    .windows(4)
                    .position(|w| w == b"\r\n\r\n")
                    .map_or(head.len(), |i| i + 4);
                while head.len() < header_len + content_length {
                    match tcp.read(&mut buf).await {
                        Ok(0) | Err(_) => break,
                        Ok(n) => head.extend_from_slice(&buf[..n]),
                    }
                }
                let request = String::from_utf8_lossy(&head).into_owned();
                recorded.lock().unwrap().push(request.clone());
                let body = body_for(&request);
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                let _ = tcp.write_all(response.as_bytes()).await;
            }
        });
        (format!("http://{addr}"), requests)
    }

    /// The fake server's clock runs this far ahead of the local one.
    const SERVER_AHEAD_MS: u64 = 60_000;

    fn request_path(request: &str) -> &str {
        request.split_whitespace().nth(1).unwrap_or_default()
    }

    fn header<'a>(request: &'a str, name: &str) -> Option<&'a str> {
        request.lines().find_map(|line| {
            let (n, value) = line.split_once(':')?;
            n.eq_ignore_ascii_case(name).then(|| value.trim())
        })
    }

    fn server_time_body() -> String {
        let server_ms = timestamp() + SERVER_AHEAD_MS;
        format!(
            r#"{{"retCode":0,"retMsg":"OK","result":{{"timeSecond":"{}","timeNano":"{}"}},"retExtInfo":{{}},"time":{server_ms}}}"#,
            server_ms / 1000,
            server_ms * 1_000_000
        )
    }

    /// Like Bybit with key "key" / secret "secret": rejects signed requests
    /// whose timestamp is off the (60 s ahead) server clock or whose
    /// signature does not match the query (GET) or body (POST).
    fn strict_bybit(request: &str) -> String {
        let path = request_path(request);
        if path.starts_with("/v5/market/time") {
            return server_time_body();
        }
        let server_ms = (timestamp() + SERVER_AHEAD_MS) as i64;
        let ts: i64 = header(request, HEADER_X_BAPI_TIMESTAMP)
            .unwrap()
            .parse()
            .unwrap();
        let payload = match path.split_once('?') {
            Some((_, query)) => query.to_owned(),
            None => request
                .split_once("\r\n\r\n")
                .map(|(_, b)| b.to_owned())
                .unwrap_or_default(),
        };
        let expected = crate::hmac_sha256("secret", format!("{ts}key5000{payload}"));
        let sign_ok = header(request, HEADER_X_BAPI_SIGN) == Some(expected.as_str());
        if (ts - server_ms).abs() > 5_000 {
            r#"{"retCode":10002,"retMsg":"timestamp","result":{},"retExtInfo":{},"time":1}"#
                .to_owned()
        } else if !sign_ok {
            r#"{"retCode":10004,"retMsg":"sign","result":{},"retExtInfo":{},"time":1}"#.to_owned()
        } else {
            r#"{"retCode":0,"retMsg":"OK","result":{"list":[],"nextPageCursor":""},"retExtInfo":{},"time":1}"#.to_owned()
        }
    }

    fn fake_bybit(request: &str) -> String {
        if request_path(request).starts_with("/v5/market/time") {
            server_time_body()
        } else {
            r#"{"retCode":10001,"retMsg":"test","result":{},"retExtInfo":{},"time":1}"#.to_owned()
        }
    }

    fn paths(requests: &std::sync::Mutex<Vec<String>>) -> Vec<String> {
        requests
            .lock()
            .unwrap()
            .iter()
            .map(|r| request_path(r).split('?').next().unwrap().to_owned())
            .collect()
    }

    #[tokio::test]
    async fn get_is_resigned_and_retried_after_a_timestamp_error() {
        let (url, requests) = spawn_http_server(strict_bybit).await;
        let client = Client::new(Config::new(url).credentials("key", "secret")).unwrap();

        let params =
            GetOpenClosedOrdersParams::new(Category::Linear).with_symbol(String::from("BTCUSDT"));
        let result = client.get_open_closed_orders(&params).await;

        assert!(result.is_ok(), "{result:?}");
        assert_eq!(
            paths(&requests),
            [
                "/v5/order/realtime",
                "/v5/market/time",
                "/v5/order/realtime"
            ]
        );
        assert!((client.time_offset() - SERVER_AHEAD_MS as i64).abs() < 1000);
    }

    #[tokio::test]
    async fn post_is_resigned_and_retried_after_a_timestamp_error() {
        let (url, requests) = spawn_http_server(strict_bybit).await;
        let client = Client::new(Config::new(url).credentials("key", "secret")).unwrap();

        let request = SetLeverageRequest::new(Category::Linear, String::from("BTCUSDT"), 10.into());
        let result = client.set_leverage(&request).await;

        assert!(result.is_ok(), "{result:?}");
        assert_eq!(
            paths(&requests),
            [
                "/v5/position/set-leverage",
                "/v5/market/time",
                "/v5/position/set-leverage"
            ]
        );
    }

    #[tokio::test]
    async fn timestamp_errors_are_returned_when_resync_is_disabled() {
        let (url, requests) = spawn_http_server(strict_bybit).await;
        let config = Config::new(url)
            .credentials("key", "secret")
            .resync_time_on_timestamp_error(false);
        let client = Client::new(config).unwrap();

        let params =
            GetOpenClosedOrdersParams::new(Category::Linear).with_symbol(String::from("BTCUSDT"));
        let err = client.get_open_closed_orders(&params).await.unwrap_err();

        assert!(err.is_timestamp_error());
        assert_eq!(paths(&requests), ["/v5/order/realtime"]);
    }

    #[tokio::test]
    async fn signed_requests_use_the_synchronized_server_time() {
        let (url, requests) = spawn_http_server(fake_bybit).await;
        let client = Client::new(Config::new(url).credentials("key", "secret")).unwrap();

        let offset = client.sync_time().await.unwrap();
        let _ = client.get_api_key_information().await;

        let expected = SERVER_AHEAD_MS as i64;
        assert!((offset - expected).abs() < 1000, "offset {offset}");
        assert_eq!(client.time_offset(), offset);

        let head = requests.lock().unwrap().last().cloned().unwrap();
        let sent: i64 = head
            .lines()
            .find_map(|line| {
                let (name, value) = line.split_once(':')?;
                name.eq_ignore_ascii_case(HEADER_X_BAPI_TIMESTAMP)
                    .then(|| value.trim().parse().unwrap())
            })
            .expect("no X-BAPI-TIMESTAMP header");
        let skew = sent - (timestamp() as i64 + expected);
        assert!(
            skew.abs() < 1000,
            "signed timestamp is {skew} ms off the server clock"
        );
    }

    #[tokio::test]
    async fn clones_share_the_clock_offset_and_the_rate_limiter() {
        let (url, _) = spawn_http_server(fake_bybit).await;
        let config = Config::new(url).rate_limiter(RateLimiterConfig::uniform(0.0, 2));
        let client = Client::new(config).unwrap();
        let clone = client.clone();

        clone.sync_time().await.unwrap();
        assert_ne!(client.time_offset(), 0);
        assert_eq!(client.time_offset(), clone.time_offset());

        // The clone used one of the two tokens; the original gets the last one.
        client.get_server_time().await.unwrap();
        assert!(matches!(
            clone.get_server_time().await,
            Err(Error::RateLimitUnsatisfiable { .. })
        ));
    }

    #[tokio::test]
    async fn requests_go_through_the_configured_proxy() {
        fn answer_time(_: &str) -> String {
            server_time_body()
        }
        let (proxy, requests) = spawn_http_server(answer_time).await;
        // The host does not resolve: only the proxy can answer.
        let config = Config::new("http://bybit.invalid").proxy(proxy);
        let client = Client::new(config).unwrap();

        client.get_server_time().await.unwrap();

        let request_line = requests.lock().unwrap()[0]
            .lines()
            .next()
            .unwrap()
            .to_owned();
        assert_eq!(
            request_line,
            "GET http://bybit.invalid/v5/market/time HTTP/1.1"
        );
    }

    #[test]
    fn invalid_proxy_url_is_an_error() {
        let config = Config::new("http://bybit.invalid").proxy("not a url");

        assert!(Client::new(config).is_err());
    }

    #[tokio::test]
    async fn private_endpoint_without_credentials_returns_error() {
        let client = Client::new(Config::new("http://127.0.0.1:1")).unwrap();

        let err = client.get_api_key_information().await.unwrap_err();

        assert!(matches!(err, Error::MissingCredentials));
    }
}