nautilus-hyperliquid 0.55.0

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

//! Provides the HTTP client integration for the [Hyperliquid](https://hyperliquid.xyz/) REST API.
//!
//! This module defines and implements a [`HyperliquidHttpClient`] for sending requests to various
//! Hyperliquid endpoints. It handles request signing (when credentials are provided), constructs
//! valid HTTP requests using the [`HttpClient`], and parses the responses back into structured
//! data or an [`Error`].

use std::{
    collections::HashMap,
    env,
    num::NonZeroU32,
    sync::{Arc, LazyLock},
    time::Duration,
};

use ahash::AHashMap;
use anyhow::Context;
use nautilus_core::{
    AtomicMap, UUID4, UnixNanos,
    consts::NAUTILUS_USER_AGENT,
    time::{AtomicTime, get_atomic_clock_realtime},
};
use nautilus_model::{
    data::{Bar, BarType},
    enums::{
        AccountType, BarAggregation, CurrencyType, OrderSide, OrderStatus, OrderType, TimeInForce,
        TriggerType,
    },
    events::AccountState,
    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
    instruments::{CurrencyPair, Instrument, InstrumentAny},
    orders::{Order, OrderAny},
    reports::{FillReport, OrderStatusReport, PositionStatusReport},
    types::{AccountBalance, Currency, Money, Price, Quantity},
};
use nautilus_network::{
    http::{HttpClient, HttpClientError, HttpResponse, Method, USER_AGENT},
    ratelimiter::quota::Quota,
};
use rust_decimal::Decimal;
use serde_json::Value;
use ustr::Ustr;

use crate::{
    common::{
        consts::{HYPERLIQUID_VENUE, NAUTILUS_BUILDER_ADDRESS, exchange_url, info_url},
        credential::{Secrets, VaultAddress},
        enums::{
            HyperliquidBarInterval, HyperliquidOrderStatus as HyperliquidOrderStatusEnum,
            HyperliquidProductType,
        },
        parse::{
            bar_type_to_interval, clamp_price_to_precision, derive_limit_from_trigger,
            extract_inner_error, normalize_price, order_to_hyperliquid_request_with_asset,
            round_to_sig_figs, time_in_force_to_hyperliquid_tif,
        },
    },
    data::candle_to_bar,
    http::{
        error::{Error, Result},
        models::{
            ClearinghouseState, Cloid, HyperliquidCandleSnapshot, HyperliquidExchangeRequest,
            HyperliquidExchangeResponse, HyperliquidExecAction, HyperliquidExecBuilderFee,
            HyperliquidExecCancelByCloidRequest, HyperliquidExecCancelOrderRequest,
            HyperliquidExecGrouping, HyperliquidExecLimitParams, HyperliquidExecModifyOrderRequest,
            HyperliquidExecOrderKind, HyperliquidExecOrderResponseData, HyperliquidExecOrderStatus,
            HyperliquidExecPlaceOrderRequest, HyperliquidExecTif, HyperliquidExecTpSl,
            HyperliquidExecTriggerParams, HyperliquidFills, HyperliquidL2Book, HyperliquidMeta,
            HyperliquidOrderStatus, PerpMeta, PerpMetaAndCtxs, RESPONSE_STATUS_OK, SpotMeta,
            SpotMetaAndCtxs,
        },
        parse::{
            HyperliquidInstrumentDef, instruments_from_defs_owned, parse_fill_report,
            parse_order_status_report_from_basic, parse_perp_instruments,
            parse_position_status_report, parse_spot_instruments,
        },
        query::{ExchangeAction, InfoRequest},
        rate_limits::{
            RateLimitSnapshot, WeightedLimiter, backoff_full_jitter, exchange_weight,
            info_base_weight, info_extra_weight,
        },
    },
    signing::{
        HyperliquidActionType, HyperliquidEip712Signer, NonceManager, SignRequest, types::SignerId,
    },
    websocket::messages::WsBasicOrderData,
};

// https://hyperliquid.xyz/docs/api#rate-limits
pub static HYPERLIQUID_REST_QUOTA: LazyLock<Quota> =
    LazyLock::new(|| Quota::per_minute(NonZeroU32::new(1200).unwrap()));

/// Provides a raw HTTP client for low-level Hyperliquid REST API operations.
///
/// This client handles HTTP infrastructure, request signing, and raw API calls
/// that closely match Hyperliquid endpoint specifications.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.core.nautilus_pyo3.hyperliquid",
        from_py_object
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.hyperliquid")
)]
pub struct HyperliquidRawHttpClient {
    client: HttpClient,
    is_testnet: bool,
    base_info: String,
    base_exchange: String,
    signer: Option<HyperliquidEip712Signer>,
    nonce_manager: Option<Arc<NonceManager>>,
    vault_address: Option<VaultAddress>,
    rest_limiter: Arc<WeightedLimiter>,
    rate_limit_backoff_base: Duration,
    rate_limit_backoff_cap: Duration,
    rate_limit_max_attempts_info: u32,
}

impl HyperliquidRawHttpClient {
    /// Creates a new [`HyperliquidRawHttpClient`] for public endpoints only.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new(
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> std::result::Result<Self, HttpClientError> {
        Ok(Self {
            client: HttpClient::new(
                Self::default_headers(),
                vec![],
                vec![],
                Some(*HYPERLIQUID_REST_QUOTA),
                Some(timeout_secs),
                proxy_url,
            )?,
            is_testnet,
            base_info: info_url(is_testnet).to_string(),
            base_exchange: exchange_url(is_testnet).to_string(),
            signer: None,
            nonce_manager: None,
            vault_address: None,
            rest_limiter: Arc::new(WeightedLimiter::per_minute(1200)),
            rate_limit_backoff_base: Duration::from_millis(125),
            rate_limit_backoff_cap: Duration::from_secs(5),
            rate_limit_max_attempts_info: 3,
        })
    }

    /// Creates a new [`HyperliquidRawHttpClient`] configured with credentials
    /// for authenticated requests.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn with_credentials(
        secrets: &Secrets,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> std::result::Result<Self, HttpClientError> {
        let signer = HyperliquidEip712Signer::new(secrets.private_key.clone());
        let nonce_manager = Arc::new(NonceManager::new());

        Ok(Self {
            client: HttpClient::new(
                Self::default_headers(),
                vec![],
                vec![],
                Some(*HYPERLIQUID_REST_QUOTA),
                Some(timeout_secs),
                proxy_url,
            )?,
            is_testnet: secrets.is_testnet,
            base_info: info_url(secrets.is_testnet).to_string(),
            base_exchange: exchange_url(secrets.is_testnet).to_string(),
            signer: Some(signer),
            nonce_manager: Some(nonce_manager),
            vault_address: secrets.vault_address,
            rest_limiter: Arc::new(WeightedLimiter::per_minute(1200)),
            rate_limit_backoff_base: Duration::from_millis(125),
            rate_limit_backoff_cap: Duration::from_secs(5),
            rate_limit_max_attempts_info: 3,
        })
    }

    /// Overrides the base info URL (for testing with mock servers).
    pub fn set_base_info_url(&mut self, url: String) {
        self.base_info = url;
    }

    /// Overrides the base exchange URL (for testing with mock servers).
    pub fn set_base_exchange_url(&mut self, url: String) {
        self.base_exchange = url;
    }

    /// Creates an authenticated client from environment variables for the specified network.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if required environment variables are not set.
    pub fn from_env(is_testnet: bool) -> Result<Self> {
        let secrets = Secrets::from_env(is_testnet)
            .map_err(|e| Error::auth(format!("missing credentials in environment: {e}")))?;
        Self::with_credentials(&secrets, 60, None)
            .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))
    }

    /// Creates a new [`HyperliquidRawHttpClient`] configured with explicit credentials.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the private key is invalid or cannot be parsed.
    pub fn from_credentials(
        private_key: &str,
        vault_address: Option<&str>,
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> Result<Self> {
        let secrets = Secrets::from_private_key(private_key, vault_address, is_testnet)
            .map_err(|e| Error::auth(format!("invalid credentials: {e}")))?;
        Self::with_credentials(&secrets, timeout_secs, proxy_url)
            .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))
    }

    /// Configure rate limiting parameters (chainable).
    #[must_use]
    pub fn with_rate_limits(mut self) -> Self {
        self.rest_limiter = Arc::new(WeightedLimiter::per_minute(1200));
        self.rate_limit_backoff_base = Duration::from_millis(125);
        self.rate_limit_backoff_cap = Duration::from_secs(5);
        self.rate_limit_max_attempts_info = 3;
        self
    }

    /// Returns whether this client is configured for testnet.
    #[must_use]
    pub fn is_testnet(&self) -> bool {
        self.is_testnet
    }

    /// Gets the user address derived from the private key (if client has credentials).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the client has no signer configured.
    pub fn get_user_address(&self) -> Result<String> {
        self.signer
            .as_ref()
            .ok_or_else(|| Error::auth("No signer configured"))?
            .address()
    }

    /// Returns `true` if a vault address is configured.
    #[must_use]
    pub fn has_vault_address(&self) -> bool {
        self.vault_address.is_some()
    }

    /// Gets the account address for queries: vault address if configured,
    /// otherwise the user (EOA) address.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the client has no signer configured.
    pub fn get_account_address(&self) -> Result<String> {
        if let Some(vault) = &self.vault_address {
            Ok(vault.to_hex())
        } else {
            self.get_user_address()
        }
    }

    fn default_headers() -> HashMap<String, String> {
        HashMap::from([
            (USER_AGENT.to_string(), NAUTILUS_USER_AGENT.to_string()),
            ("Content-Type".to_string(), "application/json".to_string()),
        ])
    }

    fn signer_id(&self) -> SignerId {
        SignerId("hyperliquid:default".into())
    }

    fn parse_retry_after_simple(&self, headers: &HashMap<String, String>) -> Option<u64> {
        let retry_after = headers.get("retry-after")?;
        retry_after.parse::<u64>().ok().map(|s| s * 1000) // convert seconds to ms
    }

    /// Get metadata about available markets.
    pub async fn info_meta(&self) -> Result<HyperliquidMeta> {
        let request = InfoRequest::meta();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get complete spot metadata (tokens and pairs).
    pub async fn get_spot_meta(&self) -> Result<SpotMeta> {
        let request = InfoRequest::spot_meta();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get perpetuals metadata with asset contexts (for price precision refinement).
    pub async fn get_perp_meta_and_ctxs(&self) -> Result<PerpMetaAndCtxs> {
        let request = InfoRequest::meta_and_asset_ctxs();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get spot metadata with asset contexts (for price precision refinement).
    pub async fn get_spot_meta_and_ctxs(&self) -> Result<SpotMetaAndCtxs> {
        let request = InfoRequest::spot_meta_and_asset_ctxs();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    pub(crate) async fn load_perp_meta(&self) -> Result<PerpMeta> {
        let request = InfoRequest::meta();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get metadata for all perp dexes (standard + HIP-3).
    pub(crate) async fn load_all_perp_metas(&self) -> Result<Vec<PerpMeta>> {
        let request = InfoRequest::all_perp_metas();
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get L2 order book for a coin.
    pub async fn info_l2_book(&self, coin: &str) -> Result<HyperliquidL2Book> {
        let request = InfoRequest::l2_book(coin);
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get user fills (trading history).
    pub async fn info_user_fills(&self, user: &str) -> Result<HyperliquidFills> {
        let request = InfoRequest::user_fills(user);
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get order status for a user.
    pub async fn info_order_status(&self, user: &str, oid: u64) -> Result<HyperliquidOrderStatus> {
        let request = InfoRequest::order_status(user, oid);
        let response = self.send_info_request(&request).await?;
        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Get all open orders for a user.
    pub async fn info_open_orders(&self, user: &str) -> Result<Value> {
        let request = InfoRequest::open_orders(user);
        self.send_info_request(&request).await
    }

    /// Get frontend open orders (includes more detail) for a user.
    pub async fn info_frontend_open_orders(&self, user: &str) -> Result<Value> {
        let request = InfoRequest::frontend_open_orders(user);
        self.send_info_request(&request).await
    }

    /// Get clearinghouse state (balances, positions, margin) for a user.
    pub async fn info_clearinghouse_state(&self, user: &str) -> Result<Value> {
        let request = InfoRequest::clearinghouse_state(user);
        self.send_info_request(&request).await
    }

    /// Get user fee schedule and effective rates.
    pub async fn info_user_fees(&self, user: &str) -> Result<Value> {
        let request = InfoRequest::user_fees(user);
        self.send_info_request(&request).await
    }

    /// Get candle/bar data for a coin.
    pub async fn info_candle_snapshot(
        &self,
        coin: &str,
        interval: HyperliquidBarInterval,
        start_time: u64,
        end_time: u64,
    ) -> Result<HyperliquidCandleSnapshot> {
        let request = InfoRequest::candle_snapshot(coin, interval, start_time, end_time);
        let response = self.send_info_request(&request).await?;

        log::trace!(
            "Candle snapshot raw response (len={}): {:?}",
            response.as_array().map_or(0, |a| a.len()),
            response
        );

        serde_json::from_value(response).map_err(Error::Serde)
    }

    /// Generic info request method that returns raw JSON (useful for new endpoints and testing).
    pub async fn send_info_request_raw(&self, request: &InfoRequest) -> Result<Value> {
        self.send_info_request(request).await
    }

    async fn send_info_request(&self, request: &InfoRequest) -> Result<Value> {
        let base_w = info_base_weight(request);
        self.rest_limiter.acquire(base_w).await;

        let mut attempt = 0u32;
        loop {
            let response = self.http_roundtrip_info(request).await?;

            if response.status.is_success() {
                // decode once to count items, then materialize T
                let val: Value = serde_json::from_slice(&response.body).map_err(Error::Serde)?;
                let extra = info_extra_weight(request, &val);
                if extra > 0 {
                    self.rest_limiter.debit_extra(extra).await;
                    log::debug!(
                        "Info debited extra weight: endpoint={request:?}, base_w={base_w}, extra={extra}"
                    );
                }
                return Ok(val);
            }

            // 429 → respect Retry-After; else jittered backoff. Retry Info only.
            if response.status.as_u16() == 429 {
                if attempt >= self.rate_limit_max_attempts_info {
                    let ra = self.parse_retry_after_simple(&response.headers);
                    return Err(Error::rate_limit("info", base_w, ra));
                }
                let delay = self
                    .parse_retry_after_simple(&response.headers)
                    .map_or_else(
                        || {
                            backoff_full_jitter(
                                attempt,
                                self.rate_limit_backoff_base,
                                self.rate_limit_backoff_cap,
                            )
                        },
                        Duration::from_millis,
                    );
                log::warn!(
                    "429 Too Many Requests; backing off: endpoint={request:?}, attempt={attempt}, wait_ms={:?}",
                    delay.as_millis()
                );
                attempt += 1;
                tokio::time::sleep(delay).await;
                // tiny re-acquire to avoid stampede exactly on minute boundary
                self.rest_limiter.acquire(1).await;
                continue;
            }

            // transient 5xx: treat like retryable Info (bounded)
            if (response.status.is_server_error() || response.status.as_u16() == 408)
                && attempt < self.rate_limit_max_attempts_info
            {
                let delay = backoff_full_jitter(
                    attempt,
                    self.rate_limit_backoff_base,
                    self.rate_limit_backoff_cap,
                );
                log::warn!(
                    "Transient error; retrying: endpoint={request:?}, attempt={attempt}, status={:?}, wait_ms={:?}",
                    response.status.as_u16(),
                    delay.as_millis()
                );
                attempt += 1;
                tokio::time::sleep(delay).await;
                continue;
            }

            // non-retryable or exhausted
            let error_body = String::from_utf8_lossy(&response.body);
            return Err(Error::http(
                response.status.as_u16(),
                error_body.to_string(),
            ));
        }
    }

    async fn http_roundtrip_info(&self, request: &InfoRequest) -> Result<HttpResponse> {
        let url = &self.base_info;
        let body = serde_json::to_value(request).map_err(Error::Serde)?;
        let body_bytes = serde_json::to_string(&body)
            .map_err(Error::Serde)?
            .into_bytes();

        self.client
            .request(
                Method::POST,
                url.clone(),
                None,
                None,
                Some(body_bytes),
                None,
                None,
            )
            .await
            .map_err(Error::from_http_client)
    }

    /// Send a signed action to the exchange.
    pub async fn post_action(
        &self,
        action: &ExchangeAction,
    ) -> Result<HyperliquidExchangeResponse> {
        let w = exchange_weight(action);
        self.rest_limiter.acquire(w).await;

        let signer = self
            .signer
            .as_ref()
            .ok_or_else(|| Error::auth("credentials required for exchange operations"))?;

        let nonce_manager = self
            .nonce_manager
            .as_ref()
            .ok_or_else(|| Error::auth("nonce manager missing"))?;

        let signer_id = self.signer_id();
        let time_nonce = nonce_manager.next(signer_id)?;

        let action_value = serde_json::to_value(action)
            .context("serialize exchange action")
            .map_err(|e| Error::bad_request(e.to_string()))?;

        // Serialize the original action struct with MessagePack for L1 signing
        let action_bytes = rmp_serde::to_vec_named(action)
            .context("serialize action with MessagePack")
            .map_err(|e| Error::bad_request(e.to_string()))?;

        let sign_request = SignRequest {
            action: action_value.clone(),
            action_bytes: Some(action_bytes),
            time_nonce,
            action_type: HyperliquidActionType::L1,
            is_testnet: self.is_testnet,
            vault_address: self.vault_address.as_ref().map(|v| v.to_hex()),
        };

        let sig = signer.sign(&sign_request)?.signature;

        let nonce_u64 = time_nonce.as_millis() as u64;

        let request = if let Some(vault) = self.vault_address {
            HyperliquidExchangeRequest::with_vault(
                action.clone(),
                nonce_u64,
                &sig,
                vault.to_string(),
            )
            .map_err(|e| Error::bad_request(format!("Failed to create request: {e}")))?
        } else {
            HyperliquidExchangeRequest::new(action.clone(), nonce_u64, &sig)
                .map_err(|e| Error::bad_request(format!("Failed to create request: {e}")))?
        };

        let response = self.http_roundtrip_exchange(&request).await?;

        if response.status.is_success() {
            let parsed_response: HyperliquidExchangeResponse =
                serde_json::from_slice(&response.body).map_err(Error::Serde)?;

            // Check if the response contains an error status
            match &parsed_response {
                HyperliquidExchangeResponse::Status {
                    status,
                    response: response_data,
                } if status == "err" => {
                    let error_msg = response_data
                        .as_str()
                        .map_or_else(|| response_data.to_string(), |s| s.to_string());
                    log::error!("Hyperliquid API returned error: {error_msg}");
                    Err(Error::bad_request(format!("API error: {error_msg}")))
                }
                HyperliquidExchangeResponse::Error { error } => {
                    log::error!("Hyperliquid API returned error: {error}");
                    Err(Error::bad_request(format!("API error: {error}")))
                }
                _ => Ok(parsed_response),
            }
        } else if response.status.as_u16() == 429 {
            let ra = self.parse_retry_after_simple(&response.headers);
            Err(Error::rate_limit("exchange", w, ra))
        } else {
            let error_body = String::from_utf8_lossy(&response.body);
            log::error!(
                "Exchange API error (status {}): {}",
                response.status.as_u16(),
                error_body
            );
            Err(Error::http(
                response.status.as_u16(),
                error_body.to_string(),
            ))
        }
    }

    /// Send a signed action to the exchange using the typed HyperliquidExecAction enum.
    ///
    /// This is the preferred method for placing orders as it uses properly typed
    /// structures that match Hyperliquid's API expectations exactly.
    pub async fn post_action_exec(
        &self,
        action: &HyperliquidExecAction,
    ) -> Result<HyperliquidExchangeResponse> {
        let w = match action {
            HyperliquidExecAction::Order { orders, .. } => 1 + (orders.len() as u32 / 40),
            HyperliquidExecAction::Cancel { cancels } => 1 + (cancels.len() as u32 / 40),
            HyperliquidExecAction::CancelByCloid { cancels } => 1 + (cancels.len() as u32 / 40),
            HyperliquidExecAction::BatchModify { modifies } => 1 + (modifies.len() as u32 / 40),
            _ => 1,
        };
        self.rest_limiter.acquire(w).await;

        let signer = self
            .signer
            .as_ref()
            .ok_or_else(|| Error::auth("credentials required for exchange operations"))?;

        let nonce_manager = self
            .nonce_manager
            .as_ref()
            .ok_or_else(|| Error::auth("nonce manager missing"))?;

        let signer_id = self.signer_id();
        let time_nonce = nonce_manager.next(signer_id)?;
        // No need to validate - next() guarantees a valid, unused nonce

        let action_value = serde_json::to_value(action)
            .context("serialize exchange action")
            .map_err(|e| Error::bad_request(e.to_string()))?;

        // Serialize the original action struct with MessagePack for L1 signing
        let action_bytes = rmp_serde::to_vec_named(action)
            .context("serialize action with MessagePack")
            .map_err(|e| Error::bad_request(e.to_string()))?;

        let sig = signer
            .sign(&SignRequest {
                action: action_value.clone(),
                action_bytes: Some(action_bytes),
                time_nonce,
                action_type: HyperliquidActionType::L1,
                is_testnet: self.is_testnet,
                vault_address: self.vault_address.as_ref().map(|v| v.to_hex()),
            })?
            .signature;

        let request = if let Some(vault) = self.vault_address {
            HyperliquidExchangeRequest::with_vault(
                action.clone(),
                time_nonce.as_millis() as u64,
                &sig,
                vault.to_string(),
            )
            .map_err(|e| Error::bad_request(format!("Failed to create request: {e}")))?
        } else {
            HyperliquidExchangeRequest::new(action.clone(), time_nonce.as_millis() as u64, &sig)
                .map_err(|e| Error::bad_request(format!("Failed to create request: {e}")))?
        };

        let response = self.http_roundtrip_exchange(&request).await?;

        if response.status.is_success() {
            let parsed_response: HyperliquidExchangeResponse =
                serde_json::from_slice(&response.body).map_err(Error::Serde)?;

            // Check if the response contains an error status
            match &parsed_response {
                HyperliquidExchangeResponse::Status {
                    status,
                    response: response_data,
                } if status == "err" => {
                    let error_msg = response_data
                        .as_str()
                        .map_or_else(|| response_data.to_string(), |s| s.to_string());
                    log::error!("Hyperliquid API returned error: {error_msg}");
                    Err(Error::bad_request(format!("API error: {error_msg}")))
                }
                HyperliquidExchangeResponse::Error { error } => {
                    log::error!("Hyperliquid API returned error: {error}");
                    Err(Error::bad_request(format!("API error: {error}")))
                }
                _ => Ok(parsed_response),
            }
        } else if response.status.as_u16() == 429 {
            let ra = self.parse_retry_after_simple(&response.headers);
            Err(Error::rate_limit("exchange", w, ra))
        } else {
            let error_body = String::from_utf8_lossy(&response.body);
            Err(Error::http(
                response.status.as_u16(),
                error_body.to_string(),
            ))
        }
    }

    /// Submit a single order to the Hyperliquid exchange.
    ///
    pub async fn rest_limiter_snapshot(&self) -> RateLimitSnapshot {
        self.rest_limiter.snapshot().await
    }
    async fn http_roundtrip_exchange<T>(
        &self,
        request: &HyperliquidExchangeRequest<T>,
    ) -> Result<HttpResponse>
    where
        T: serde::Serialize,
    {
        let url = &self.base_exchange;
        let body = serde_json::to_string(&request).map_err(Error::Serde)?;
        let body_bytes = body.into_bytes();

        let response = self
            .client
            .request(
                Method::POST,
                url.clone(),
                None,
                None,
                Some(body_bytes),
                None,
                None,
            )
            .await
            .map_err(Error::from_http_client)?;

        Ok(response)
    }
}

/// Provides a high-level HTTP client for the [Hyperliquid](https://hyperliquid.xyz/) REST API.
///
/// This domain client wraps [`HyperliquidRawHttpClient`] and provides methods that work
/// with Nautilus domain types. It maintains an instrument cache and handles conversions
/// between Hyperliquid API responses and Nautilus domain models.
#[derive(Debug, Clone)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.core.nautilus_pyo3.hyperliquid",
        from_py_object
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.hyperliquid")
)]
pub struct HyperliquidHttpClient {
    pub(crate) inner: Arc<HyperliquidRawHttpClient>,
    clock: &'static AtomicTime,
    instruments: Arc<AtomicMap<Ustr, InstrumentAny>>,
    instruments_by_coin: Arc<AtomicMap<(Ustr, HyperliquidProductType), InstrumentAny>>,
    /// Mapping from symbol to asset index for order submission.
    asset_indices: Arc<AtomicMap<Ustr, u32>>,
    /// Mapping from spot fill coin (`@{pair_index}`) to instrument symbol.
    spot_fill_coins: Arc<AtomicMap<Ustr, Ustr>>,
    account_id: Option<AccountId>,
    /// Optional override address for queries (agent wallet / API sub-key support).
    /// When set, used for balance queries, position reports, and WS subscriptions
    /// instead of the address derived from the private key.
    account_address: Option<String>,
    normalize_prices: bool,
}

impl Default for HyperliquidHttpClient {
    fn default() -> Self {
        Self::new(true, 60, None).expect("Failed to create default Hyperliquid HTTP client")
    }
}

impl HyperliquidHttpClient {
    /// Creates a new [`HyperliquidHttpClient`] for public endpoints only.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new(
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> std::result::Result<Self, HttpClientError> {
        let raw_client = HyperliquidRawHttpClient::new(is_testnet, timeout_secs, proxy_url)?;
        Ok(Self::from_raw(raw_client))
    }

    /// Creates a new [`HyperliquidHttpClient`] configured with a [`Secrets`] struct.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn with_secrets(
        secrets: &Secrets,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> std::result::Result<Self, HttpClientError> {
        let raw_client =
            HyperliquidRawHttpClient::with_credentials(secrets, timeout_secs, proxy_url)?;
        Ok(Self::from_raw(raw_client))
    }

    fn from_raw(raw_client: HyperliquidRawHttpClient) -> Self {
        Self {
            inner: Arc::new(raw_client),
            clock: get_atomic_clock_realtime(),
            instruments: Arc::new(AtomicMap::new()),
            instruments_by_coin: Arc::new(AtomicMap::new()),
            asset_indices: Arc::new(AtomicMap::new()),
            spot_fill_coins: Arc::new(AtomicMap::new()),
            account_id: None,
            account_address: None,
            normalize_prices: true,
        }
    }

    /// Overrides the base info URL (for testing with mock servers).
    ///
    /// # Panics
    ///
    /// Panics if the inner `Arc` has multiple references.
    pub fn set_base_info_url(&mut self, url: String) {
        Arc::get_mut(&mut self.inner)
            .expect("cannot override URL: Arc has multiple references")
            .set_base_info_url(url);
    }

    /// Overrides the base exchange URL (for testing with mock servers).
    ///
    /// # Panics
    ///
    /// Panics if the inner `Arc` has multiple references.
    pub fn set_base_exchange_url(&mut self, url: String) {
        Arc::get_mut(&mut self.inner)
            .expect("cannot override URL: Arc has multiple references")
            .set_base_exchange_url(url);
    }

    /// Creates an authenticated client from environment variables for the specified network.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if required environment variables are not set.
    pub fn from_env(is_testnet: bool) -> Result<Self> {
        let raw_client = HyperliquidRawHttpClient::from_env(is_testnet)?;
        Ok(Self {
            inner: Arc::new(raw_client),
            clock: get_atomic_clock_realtime(),
            instruments: Arc::new(AtomicMap::new()),
            instruments_by_coin: Arc::new(AtomicMap::new()),
            asset_indices: Arc::new(AtomicMap::new()),
            spot_fill_coins: Arc::new(AtomicMap::new()),
            account_id: None,
            account_address: None,
            normalize_prices: true,
        })
    }

    /// Creates a new [`HyperliquidHttpClient`] configured with credentials.
    ///
    /// If credentials are not provided, falls back to environment variables:
    /// - Testnet: `HYPERLIQUID_TESTNET_PK`, `HYPERLIQUID_TESTNET_VAULT`
    /// - Mainnet: `HYPERLIQUID_PK`, `HYPERLIQUID_VAULT`
    ///
    /// If no credentials are provided and no environment variables are set,
    /// creates an unauthenticated client for public endpoints only.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if credentials are invalid.
    pub fn with_credentials(
        private_key: Option<String>,
        vault_address: Option<String>,
        account_address: Option<String>,
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> Result<Self> {
        // Determine which env vars to use based on is_testnet
        let pk_env_var = if is_testnet {
            "HYPERLIQUID_TESTNET_PK"
        } else {
            "HYPERLIQUID_PK"
        };
        let vault_env_var = if is_testnet {
            "HYPERLIQUID_TESTNET_VAULT"
        } else {
            "HYPERLIQUID_VAULT"
        };

        // Resolve private key: explicit value -> env var -> None (unauthenticated)
        let resolved_pk = match private_key {
            Some(pk) => Some(pk),
            None => env::var(pk_env_var).ok(),
        };

        // Resolve vault address: explicit value -> env var -> None
        let resolved_vault = match vault_address {
            Some(vault) => Some(vault),
            None => env::var(vault_env_var).ok(),
        };

        // Resolve account address: explicit value -> env var -> None
        let resolved_account_address = match account_address {
            Some(addr) => Some(addr),
            None => env::var("HYPERLIQUID_ACCOUNT_ADDRESS").ok(),
        };

        match resolved_pk {
            Some(pk) => {
                let raw_client = HyperliquidRawHttpClient::from_credentials(
                    &pk,
                    resolved_vault.as_deref(),
                    is_testnet,
                    timeout_secs,
                    proxy_url,
                )?;
                Ok(Self {
                    inner: Arc::new(raw_client),
                    clock: get_atomic_clock_realtime(),
                    instruments: Arc::new(AtomicMap::new()),
                    instruments_by_coin: Arc::new(AtomicMap::new()),
                    asset_indices: Arc::new(AtomicMap::new()),
                    spot_fill_coins: Arc::new(AtomicMap::new()),
                    account_id: None,
                    account_address: resolved_account_address,
                    normalize_prices: true,
                })
            }
            None => {
                // No credentials available, create unauthenticated client
                Self::new(is_testnet, timeout_secs, proxy_url)
                    .map_err(|e| Error::auth(format!("Failed to create HTTP client: {e}")))
            }
        }
    }

    /// Creates a new [`HyperliquidHttpClient`] configured with explicit credentials.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the private key is invalid or cannot be parsed.
    pub fn from_credentials(
        private_key: &str,
        vault_address: Option<&str>,
        is_testnet: bool,
        timeout_secs: u64,
        proxy_url: Option<String>,
    ) -> Result<Self> {
        let raw_client = HyperliquidRawHttpClient::from_credentials(
            private_key,
            vault_address,
            is_testnet,
            timeout_secs,
            proxy_url,
        )?;
        Ok(Self {
            inner: Arc::new(raw_client),
            clock: get_atomic_clock_realtime(),
            instruments: Arc::new(AtomicMap::new()),
            instruments_by_coin: Arc::new(AtomicMap::new()),
            asset_indices: Arc::new(AtomicMap::new()),
            spot_fill_coins: Arc::new(AtomicMap::new()),
            account_id: None,
            account_address: None,
            normalize_prices: true,
        })
    }

    /// Returns whether this client is configured for testnet.
    #[must_use]
    pub fn is_testnet(&self) -> bool {
        self.inner.is_testnet()
    }

    /// Returns whether order price normalization is enabled.
    #[must_use]
    pub fn normalize_prices(&self) -> bool {
        self.normalize_prices
    }

    /// Sets whether to normalize order prices to 5 significant figures.
    pub fn set_normalize_prices(&mut self, value: bool) {
        self.normalize_prices = value;
    }

    /// Gets the user address derived from the private key (if client has credentials).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the client has no signer configured.
    pub fn get_user_address(&self) -> Result<String> {
        self.inner.get_user_address()
    }

    /// Returns `true` if a vault address is configured.
    #[must_use]
    pub fn has_vault_address(&self) -> bool {
        self.inner.has_vault_address()
    }

    /// Gets the account address for queries: account_address if configured
    /// (agent wallet), then vault address, otherwise the user (EOA) address.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Auth`] if the client has no signer configured and
    /// no account_address override is set.
    pub fn get_account_address(&self) -> Result<String> {
        if let Some(addr) = &self.account_address {
            return Ok(addr.clone());
        }
        self.inner.get_account_address()
    }

    /// Sets the account address override for queries (agent wallet support).
    pub fn set_account_address(&mut self, address: Option<String>) {
        self.account_address = address;
    }

    /// Caches a single instrument.
    ///
    /// This is required for parsing orders, fills, and positions into reports.
    /// Any existing instrument with the same symbol will be replaced.
    pub fn cache_instrument(&self, instrument: &InstrumentAny) {
        let full_symbol = instrument.symbol().inner();
        let coin = instrument.raw_symbol().inner();

        self.instruments.rcu(|m| {
            m.insert(full_symbol, instrument.clone());
            // HTTP responses only include coins, external code may lookup by coin
            m.insert(coin, instrument.clone());
        });

        // Composite key allows disambiguating same coin across PERP and SPOT
        if let Ok(product_type) = HyperliquidProductType::from_symbol(full_symbol.as_str()) {
            self.instruments_by_coin.rcu(|m| {
                m.insert((coin, product_type), instrument.clone());

                // Spot raw_symbols use @{pair_index} format (e.g., "@107") but
                // callers often extract the base currency from the symbol (e.g.,
                // "HYPE" from "HYPE-USDC-SPOT"), so also index by base name
                if coin.as_str().starts_with('@')
                    && let Some(base) = full_symbol.as_str().split('-').next()
                {
                    let base_ustr = Ustr::from(base);
                    if base_ustr != coin {
                        m.insert((base_ustr, product_type), instrument.clone());
                    }
                }
            });
        } else {
            log::warn!("Unable to determine product type for symbol: {full_symbol}");
        }
    }

    fn get_or_create_instrument(
        &self,
        coin: &Ustr,
        product_type: Option<HyperliquidProductType>,
    ) -> Option<InstrumentAny> {
        if let Some(pt) = product_type
            && let Some(instrument) = self.instruments_by_coin.load().get(&(*coin, pt))
        {
            return Some(instrument.clone());
        }

        // HTTP responses lack product type context, try PERP then SPOT
        if product_type.is_none() {
            let guard = self.instruments_by_coin.load();

            if let Some(instrument) = guard.get(&(*coin, HyperliquidProductType::Perp)) {
                return Some(instrument.clone());
            }

            if let Some(instrument) = guard.get(&(*coin, HyperliquidProductType::Spot)) {
                return Some(instrument.clone());
            }
        }

        // Spot fills use @{pair_index} format, translate to full symbol and look up
        if coin.as_str().starts_with('@')
            && let Some(symbol) = self.spot_fill_coins.load().get(coin)
        {
            // Look up by full symbol in instruments map (not instruments_by_coin
            // which uses raw_symbol)
            if let Some(instrument) = self.instruments.load().get(symbol) {
                return Some(instrument.clone());
            }
        }

        // Vault tokens aren't in standard API, create synthetic instruments
        if coin.as_str().starts_with("vntls:") {
            log::info!("Creating synthetic instrument for vault token: {coin}");

            let ts_event = self.clock.get_time_ns();

            // Create synthetic vault token instrument
            let symbol_str = format!("{coin}-USDC-SPOT");
            let symbol = Symbol::new(&symbol_str);
            let venue = *HYPERLIQUID_VENUE;
            let instrument_id = InstrumentId::new(symbol, venue);

            // Create currencies
            let base_currency = Currency::new(
                coin.as_str(),
                8, // precision
                0, // ISO code (not applicable)
                coin.as_str(),
                CurrencyType::Crypto,
            );

            let quote_currency = Currency::new(
                "USDC",
                6, // USDC standard precision
                0,
                "USDC",
                CurrencyType::Crypto,
            );

            let price_increment = Price::from("0.00000001");
            let size_increment = Quantity::from("0.00000001");

            let instrument = InstrumentAny::CurrencyPair(CurrencyPair::new(
                instrument_id,
                symbol,
                base_currency,
                quote_currency,
                8, // price_precision
                8, // size_precision
                price_increment,
                size_increment,
                None, // multiplier
                None, // lot_size
                None, // max_quantity
                None, // min_quantity
                None, // max_notional
                None, // min_notional
                None, // max_price
                None, // min_price
                None, // margin_init
                None, // margin_maint
                None, // maker_fee
                None, // taker_fee
                None, // info
                ts_event,
                ts_event,
            ));

            self.cache_instrument(&instrument);

            Some(instrument)
        } else {
            // For non-vault tokens, log warning and return None
            log::warn!("Instrument not found in cache: {coin}");
            None
        }
    }

    /// Set the account ID for this client.
    ///
    /// This is required for generating reports with the correct account ID.
    pub fn set_account_id(&mut self, account_id: AccountId) {
        self.account_id = Some(account_id);
    }

    /// Fetch and parse all instrument definitions, populating the asset indices cache.
    pub async fn request_instrument_defs(&self) -> Result<Vec<HyperliquidInstrumentDef>> {
        let mut defs: Vec<HyperliquidInstrumentDef> = Vec::new();

        // Load all perp dexes: index 0 = standard, index 1+ = HIP-3
        match self.inner.load_all_perp_metas().await {
            Ok(all_metas) => {
                for (dex_index, meta) in all_metas.iter().enumerate() {
                    let base = perp_dex_asset_index_base(dex_index);

                    match parse_perp_instruments(meta, base) {
                        Ok(perp_defs) => {
                            log::debug!(
                                "Loaded Hyperliquid perp defs: dex_index={dex_index}, count={}",
                                perp_defs.len(),
                            );
                            defs.extend(perp_defs);
                        }
                        Err(e) => {
                            log::warn!("Failed to parse perp instruments for dex {dex_index}: {e}");
                        }
                    }
                }
            }
            Err(e) => {
                log::warn!("Failed to load allPerpMetas, falling back to meta: {e}");
                match self.inner.load_perp_meta().await {
                    Ok(perp_meta) => match parse_perp_instruments(&perp_meta, 0) {
                        Ok(perp_defs) => {
                            log::debug!(
                                "Loaded Hyperliquid perp defs via fallback: count={}",
                                perp_defs.len(),
                            );
                            defs.extend(perp_defs);
                        }
                        Err(e) => {
                            log::warn!("Failed to parse perp instruments: {e}");
                        }
                    },
                    Err(e) => {
                        log::warn!("Failed to load Hyperliquid perp metadata: {e}");
                    }
                }
            }
        }

        match self.inner.get_spot_meta().await {
            Ok(spot_meta) => match parse_spot_instruments(&spot_meta) {
                Ok(spot_defs) => {
                    log::debug!(
                        "Loaded Hyperliquid spot definitions: count={}",
                        spot_defs.len(),
                    );
                    defs.extend(spot_defs);
                }
                Err(e) => {
                    log::warn!("Failed to parse Hyperliquid spot instruments: {e}");
                }
            },
            Err(e) => {
                log::warn!("Failed to load Hyperliquid spot metadata: {e}");
            }
        }

        // Populate asset indices for all instruments (including filtered HIP-3)
        self.asset_indices.rcu(|m| {
            for def in &defs {
                m.insert(def.symbol, def.asset_index);
            }
        });
        log::debug!(
            "Populated asset indices map (count={})",
            self.asset_indices.len()
        );

        Ok(defs)
    }

    /// Converts instrument definitions into Nautilus instruments.
    pub fn convert_defs(&self, defs: Vec<HyperliquidInstrumentDef>) -> Vec<InstrumentAny> {
        let ts_init = self.clock.get_time_ns();
        instruments_from_defs_owned(defs, ts_init)
    }

    /// Fetch and parse all available instrument definitions from Hyperliquid.
    pub async fn request_instruments(&self) -> Result<Vec<InstrumentAny>> {
        let defs = self.request_instrument_defs().await?;
        Ok(self.convert_defs(defs))
    }

    /// Get asset index for a symbol from the cached map.
    ///
    /// For perps: index in meta.universe (0, 1, 2, ...).
    /// For spot: 10_000 + index in spotMeta.universe.
    /// For HIP-3: 100_000 + dex_index * 10_000 + index in dex meta.universe.
    ///
    /// Returns `None` if the symbol is not found in the map.
    pub fn get_asset_index(&self, symbol: &str) -> Option<u32> {
        self.asset_indices.load().get(&Ustr::from(symbol)).copied()
    }

    /// Get the price precision for a cached instrument by symbol.
    pub fn get_price_precision(&self, symbol: &str) -> Option<u8> {
        self.instruments
            .load()
            .get(&Ustr::from(symbol))
            .map(|inst| inst.price_precision())
    }

    /// Get mapping from spot fill coin identifiers to instrument symbols.
    ///
    /// Hyperliquid WebSocket fills for spot use `@{pair_index}` format (e.g., `@107`),
    /// while instruments are identified by full symbols (e.g., `HYPE-USDC-SPOT`).
    /// This mapping allows looking up the instrument from a spot fill.
    ///
    /// This method also caches the mapping internally for use by fill parsing methods.
    #[must_use]
    pub fn get_spot_fill_coin_mapping(&self) -> AHashMap<Ustr, Ustr> {
        const SPOT_INDEX_OFFSET: u32 = 10_000;
        const BUILDER_PERP_OFFSET: u32 = 100_000;

        let guard = self.asset_indices.load();

        let mut mapping = AHashMap::new();
        for (symbol, &asset_index) in guard.iter() {
            // Spot instruments: asset_index in [10_000, 100_000)
            if (SPOT_INDEX_OFFSET..BUILDER_PERP_OFFSET).contains(&asset_index) {
                let pair_index = asset_index - SPOT_INDEX_OFFSET;
                let fill_coin = Ustr::from(&format!("@{pair_index}"));
                mapping.insert(fill_coin, *symbol);
            }
        }

        // Cache the mapping internally for fill parsing
        self.spot_fill_coins.store(mapping.clone());

        mapping
    }

    /// Get perpetuals metadata (internal helper).
    #[allow(dead_code)]
    pub(crate) async fn load_perp_meta(&self) -> Result<PerpMeta> {
        self.inner.load_perp_meta().await
    }

    /// Get metadata for all perp dexes (standard + HIP-3).
    #[allow(dead_code)]
    pub(crate) async fn load_all_perp_metas(&self) -> Result<Vec<PerpMeta>> {
        self.inner.load_all_perp_metas().await
    }

    /// Get spot metadata (internal helper).
    #[allow(dead_code)]
    pub(crate) async fn get_spot_meta(&self) -> Result<SpotMeta> {
        self.inner.get_spot_meta().await
    }

    /// Get L2 order book for a coin.
    pub async fn info_l2_book(&self, coin: &str) -> Result<HyperliquidL2Book> {
        self.inner.info_l2_book(coin).await
    }

    /// Get user fills (trading history).
    pub async fn info_user_fills(&self, user: &str) -> Result<HyperliquidFills> {
        self.inner.info_user_fills(user).await
    }

    /// Get order status for a user.
    pub async fn info_order_status(&self, user: &str, oid: u64) -> Result<HyperliquidOrderStatus> {
        self.inner.info_order_status(user, oid).await
    }

    /// Get all open orders for a user.
    pub async fn info_open_orders(&self, user: &str) -> Result<Value> {
        self.inner.info_open_orders(user).await
    }

    /// Get frontend open orders (includes more detail) for a user.
    pub async fn info_frontend_open_orders(&self, user: &str) -> Result<Value> {
        self.inner.info_frontend_open_orders(user).await
    }

    /// Get clearinghouse state (balances, positions, margin) for a user.
    pub async fn info_clearinghouse_state(&self, user: &str) -> Result<Value> {
        self.inner.info_clearinghouse_state(user).await
    }

    /// Get user fee schedule and effective rates.
    pub async fn info_user_fees(&self, user: &str) -> Result<Value> {
        self.inner.info_user_fees(user).await
    }

    /// Get candle/bar data for a coin.
    pub async fn info_candle_snapshot(
        &self,
        coin: &str,
        interval: HyperliquidBarInterval,
        start_time: u64,
        end_time: u64,
    ) -> Result<HyperliquidCandleSnapshot> {
        self.inner
            .info_candle_snapshot(coin, interval, start_time, end_time)
            .await
    }

    /// Post an action to the exchange endpoint (low-level delegation).
    pub async fn post_action(
        &self,
        action: &ExchangeAction,
    ) -> Result<HyperliquidExchangeResponse> {
        self.inner.post_action(action).await
    }

    /// Post an execution action (low-level delegation).
    pub async fn post_action_exec(
        &self,
        action: &HyperliquidExecAction,
    ) -> Result<HyperliquidExchangeResponse> {
        self.inner.post_action_exec(action).await
    }

    /// Get metadata about available markets (low-level delegation).
    pub async fn info_meta(&self) -> Result<HyperliquidMeta> {
        self.inner.info_meta().await
    }

    /// Cancel an order on the Hyperliquid exchange.
    ///
    /// Can cancel either by venue order ID or client order ID.
    /// At least one ID must be provided.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing, no order ID is provided,
    /// or the API returns an error.
    pub async fn cancel_order(
        &self,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: Option<VenueOrderId>,
    ) -> Result<()> {
        // Get asset ID from cached indices map
        let symbol = instrument_id.symbol.as_str();
        let asset_id = self.get_asset_index(symbol).ok_or_else(|| {
            Error::bad_request(format!(
                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
            ))
        })?;

        // Create cancel action based on which ID we have
        let action = if let Some(cloid) = client_order_id {
            // Hash the client order ID to CLOID (same as order submission)
            let cloid_hash = Cloid::from_client_order_id(cloid);
            let cancel_req = HyperliquidExecCancelByCloidRequest {
                asset: asset_id,
                cloid: cloid_hash,
            };
            HyperliquidExecAction::CancelByCloid {
                cancels: vec![cancel_req],
            }
        } else if let Some(oid) = venue_order_id {
            let oid_u64 = oid
                .as_str()
                .parse::<u64>()
                .map_err(|_| Error::bad_request("Invalid venue order ID format"))?;
            let cancel_req = HyperliquidExecCancelOrderRequest {
                asset: asset_id,
                oid: oid_u64,
            };
            HyperliquidExecAction::Cancel {
                cancels: vec![cancel_req],
            }
        } else {
            return Err(Error::bad_request(
                "Either client_order_id or venue_order_id must be provided",
            ));
        };

        // Submit cancellation
        let response = self.inner.post_action_exec(&action).await?;

        // Check response - only check for error status
        match response {
            ref r @ HyperliquidExchangeResponse::Status { .. } if r.is_ok() => Ok(()),
            HyperliquidExchangeResponse::Status {
                status,
                response: error_data,
            } => Err(Error::bad_request(format!(
                "Cancel order failed: status={status}, error={error_data}"
            ))),
            HyperliquidExchangeResponse::Error { error } => {
                Err(Error::bad_request(format!("Cancel order error: {error}")))
            }
        }
    }

    /// Modify an order on the Hyperliquid exchange.
    ///
    /// The HL modify API requires a full replacement order spec plus the
    /// venue order ID. The caller must provide all order fields.
    ///
    /// # Errors
    ///
    /// Returns an error if the asset index is not found, the venue order ID
    /// is invalid, or the API returns an error.
    #[allow(clippy::too_many_arguments)]
    pub async fn modify_order(
        &self,
        instrument_id: InstrumentId,
        venue_order_id: VenueOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        price: Price,
        quantity: Quantity,
        trigger_price: Option<Price>,
        reduce_only: bool,
        post_only: bool,
        time_in_force: TimeInForce,
        client_order_id: Option<ClientOrderId>,
    ) -> Result<()> {
        let symbol = instrument_id.symbol.as_str();
        let asset_id = self.get_asset_index(symbol).ok_or_else(|| {
            Error::bad_request(format!(
                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
            ))
        })?;

        let oid: u64 = venue_order_id
            .as_str()
            .parse()
            .map_err(|_| Error::bad_request("Invalid venue order ID format"))?;

        let is_buy = matches!(order_side, OrderSide::Buy);
        let decimals = self.get_price_precision(symbol).unwrap_or(2);

        let normalized_price = if self.normalize_prices {
            normalize_price(price.as_decimal(), decimals).normalize()
        } else {
            price.as_decimal().normalize()
        };

        let size = quantity.as_decimal().normalize();
        let cloid = client_order_id.map(Cloid::from_client_order_id);

        let kind = match order_type {
            OrderType::Market => HyperliquidExecOrderKind::Limit {
                limit: HyperliquidExecLimitParams {
                    tif: HyperliquidExecTif::Ioc,
                },
            },
            OrderType::Limit => {
                let tif = time_in_force_to_hyperliquid_tif(time_in_force, post_only)
                    .map_err(|e| Error::bad_request(format!("{e}")))?;
                HyperliquidExecOrderKind::Limit {
                    limit: HyperliquidExecLimitParams { tif },
                }
            }
            OrderType::StopMarket
            | OrderType::StopLimit
            | OrderType::MarketIfTouched
            | OrderType::LimitIfTouched => {
                if let Some(trig_px) = trigger_price {
                    let trigger_price_decimal = if self.normalize_prices {
                        normalize_price(trig_px.as_decimal(), decimals).normalize()
                    } else {
                        trig_px.as_decimal().normalize()
                    };
                    let tpsl = match order_type {
                        OrderType::StopMarket | OrderType::StopLimit => HyperliquidExecTpSl::Sl,
                        _ => HyperliquidExecTpSl::Tp,
                    };
                    let is_market = matches!(
                        order_type,
                        OrderType::StopMarket | OrderType::MarketIfTouched
                    );
                    HyperliquidExecOrderKind::Trigger {
                        trigger: HyperliquidExecTriggerParams {
                            is_market,
                            trigger_px: trigger_price_decimal,
                            tpsl,
                        },
                    }
                } else {
                    return Err(Error::bad_request("Trigger orders require a trigger price"));
                }
            }
            _ => {
                return Err(Error::bad_request(format!(
                    "Order type {order_type:?} not supported for modify"
                )));
            }
        };

        let order = HyperliquidExecPlaceOrderRequest {
            asset: asset_id,
            is_buy,
            price: normalized_price,
            size,
            reduce_only,
            kind,
            cloid,
        };

        let action = HyperliquidExecAction::Modify {
            modify: HyperliquidExecModifyOrderRequest { oid, order },
        };

        let response = self.inner.post_action_exec(&action).await?;

        match response {
            ref r @ HyperliquidExchangeResponse::Status { .. } if r.is_ok() => {
                if let Some(inner_error) = extract_inner_error(&response) {
                    Err(Error::bad_request(format!(
                        "Modify order rejected: {inner_error}",
                    )))
                } else {
                    Ok(())
                }
            }
            HyperliquidExchangeResponse::Status {
                status,
                response: error_data,
            } => Err(Error::bad_request(format!(
                "Modify order failed: status={status}, error={error_data}"
            ))),
            HyperliquidExchangeResponse::Error { error } => {
                Err(Error::bad_request(format!("Modify order error: {error}")))
            }
        }
    }

    /// Request order status reports for a user.
    ///
    /// Fetches open orders via `info_frontend_open_orders` and parses them into OrderStatusReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails or parsing fails.
    pub async fn request_order_status_reports(
        &self,
        user: &str,
        instrument_id: Option<InstrumentId>,
    ) -> Result<Vec<OrderStatusReport>> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
        let response = self.info_frontend_open_orders(user).await?;

        // Parse the JSON response into a vector of orders
        let orders: Vec<serde_json::Value> = serde_json::from_value(response)
            .map_err(|e| Error::bad_request(format!("Failed to parse orders: {e}")))?;

        let mut reports = Vec::new();
        let ts_init = self.clock.get_time_ns();

        for order_value in orders {
            // Parse the order data
            let order: WsBasicOrderData = match serde_json::from_value(order_value.clone()) {
                Ok(o) => o,
                Err(e) => {
                    log::warn!("Failed to parse order: {e}");
                    continue;
                }
            };

            // Get instrument from cache or create synthetic for vault tokens
            let instrument = match self.get_or_create_instrument(&order.coin, None) {
                Some(inst) => inst,
                None => continue, // Skip if instrument not found
            };

            // Filter by instrument_id if specified
            if let Some(filter_id) = instrument_id
                && instrument.id() != filter_id
            {
                continue;
            }

            // Determine status from order data - orders from frontend_open_orders are open
            let status = HyperliquidOrderStatusEnum::Open;

            // Parse to OrderStatusReport
            match parse_order_status_report_from_basic(
                &order,
                &status,
                &instrument,
                account_id,
                ts_init,
            ) {
                Ok(report) => reports.push(report),
                Err(e) => log::error!("Failed to parse order status report: {e}"),
            }
        }

        Ok(reports)
    }

    /// Request a single order status report by venue order ID.
    ///
    /// Queries `info_frontend_open_orders` and filters for the given oid so the
    /// result includes trigger metadata (trigger_px, tpsl, trailing_stop, etc.).
    /// Falls back to `info_order_status` when the order is no longer open.
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails or parsing fails.
    pub async fn request_order_status_report(
        &self,
        user: &str,
        oid: u64,
    ) -> Result<Option<OrderStatusReport>> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;

        let ts_init = self.clock.get_time_ns();

        // Try open orders first (returns full WsBasicOrderData with trigger fields)
        let response = self.info_frontend_open_orders(user).await?;
        let orders: Vec<WsBasicOrderData> = match serde_json::from_value(response) {
            Ok(v) => v,
            Err(e) => {
                log::warn!("Failed to parse frontend open orders response: {e}");
                Vec::new()
            }
        };

        if let Some(order) = orders.into_iter().find(|o| o.oid == oid) {
            let instrument = match self.get_or_create_instrument(&order.coin, None) {
                Some(inst) => inst,
                None => return Ok(None),
            };

            let status = if order.trigger_activated == Some(true) {
                HyperliquidOrderStatusEnum::Triggered
            } else {
                HyperliquidOrderStatusEnum::Open
            };

            return match parse_order_status_report_from_basic(
                &order,
                &status,
                &instrument,
                account_id,
                ts_init,
            ) {
                Ok(report) => Ok(Some(report)),
                Err(e) => {
                    log::error!("Failed to parse order status report for oid {oid}: {e}");
                    Ok(None)
                }
            };
        }

        // Order not in open set: query by oid (returns limited HyperliquidOrderInfo)
        let response = self.info_order_status(user, oid).await?;
        let entry = match response.statuses.into_iter().next() {
            Some(e) => e,
            None => return Ok(None),
        };

        let instrument = match self.get_or_create_instrument(&entry.order.coin, None) {
            Some(inst) => inst,
            None => return Ok(None),
        };

        // The info_order_status endpoint returns limited HyperliquidOrderInfo
        // without trigger fields (trigger_px, tpsl, is_market, trailing_stop).
        // Closed trigger orders will report as Limit type. This is an exchange
        // API limitation: trigger metadata is only available on open orders.
        let basic = WsBasicOrderData {
            coin: entry.order.coin,
            side: entry.order.side,
            limit_px: entry.order.limit_px,
            sz: entry.order.sz,
            oid: entry.order.oid,
            timestamp: entry.order.timestamp,
            orig_sz: entry.order.orig_sz,
            cloid: None,
            trigger_px: None,
            is_market: None,
            tpsl: None,
            trigger_activated: None,
            trailing_stop: None,
        };

        match parse_order_status_report_from_basic(
            &basic,
            &entry.status,
            &instrument,
            account_id,
            ts_init,
        ) {
            Ok(mut report) => {
                // Use status_timestamp for ts_last when available (more accurate
                // than the order creation timestamp for filled/canceled orders)
                if entry.status_timestamp > 0 {
                    report.ts_last = UnixNanos::from(entry.status_timestamp * 1_000_000);
                }
                Ok(Some(report))
            }
            Err(e) => {
                log::error!("Failed to parse order status report for oid {oid}: {e}");
                Ok(None)
            }
        }
    }

    /// Request a single order status report by client order ID.
    ///
    /// Searches `info_frontend_open_orders` for an order whose cloid matches the
    /// keccak256 hash of the given client order ID. Only finds open orders.
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails or parsing fails.
    pub async fn request_order_status_report_by_client_order_id(
        &self,
        user: &str,
        client_order_id: &ClientOrderId,
    ) -> Result<Option<OrderStatusReport>> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;

        let ts_init = self.clock.get_time_ns();

        let cloid_hex = Cloid::from_client_order_id(*client_order_id).to_hex();

        let response = self.info_frontend_open_orders(user).await?;
        let orders: Vec<WsBasicOrderData> = match serde_json::from_value(response) {
            Ok(v) => v,
            Err(e) => {
                log::warn!("Failed to parse frontend open orders response: {e}");
                return Ok(None);
            }
        };

        let order = match orders
            .into_iter()
            .find(|o| o.cloid.as_ref().is_some_and(|c| c == &cloid_hex))
        {
            Some(o) => o,
            None => return Ok(None),
        };

        let instrument = match self.get_or_create_instrument(&order.coin, None) {
            Some(inst) => inst,
            None => return Ok(None),
        };

        let status = if order.trigger_activated == Some(true) {
            HyperliquidOrderStatusEnum::Triggered
        } else {
            HyperliquidOrderStatusEnum::Open
        };

        match parse_order_status_report_from_basic(
            &order,
            &status,
            &instrument,
            account_id,
            ts_init,
        ) {
            Ok(mut report) => {
                report.client_order_id = Some(*client_order_id);
                Ok(Some(report))
            }
            Err(e) => {
                log::error!("Failed to parse order status report for cloid {cloid_hex}: {e}");
                Ok(None)
            }
        }
    }

    /// Request fill reports for a user.
    ///
    /// Fetches user fills via `info_user_fills` and parses them into FillReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails or parsing fails.
    ///
    /// Returns an error if `account_id` is not set on the client.
    pub async fn request_fill_reports(
        &self,
        user: &str,
        instrument_id: Option<InstrumentId>,
    ) -> Result<Vec<FillReport>> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
        let fills_response = self.info_user_fills(user).await?;

        let mut reports = Vec::new();
        let ts_init = self.clock.get_time_ns();

        for fill in fills_response {
            // Get instrument from cache or create synthetic for vault tokens
            let instrument = match self.get_or_create_instrument(&fill.coin, None) {
                Some(inst) => inst,
                None => continue, // Skip if instrument not found
            };

            // Filter by instrument_id if specified
            if let Some(filter_id) = instrument_id
                && instrument.id() != filter_id
            {
                continue;
            }

            // Parse to FillReport
            match parse_fill_report(&fill, &instrument, account_id, ts_init) {
                Ok(report) => reports.push(report),
                Err(e) => log::error!("Failed to parse fill report: {e}"),
            }
        }

        Ok(reports)
    }

    /// Request position status reports for a user.
    ///
    /// Fetches clearinghouse state via `info_clearinghouse_state` and parses positions into PositionStatusReports.
    /// This method requires instruments to be added to the client cache via `cache_instrument()`.
    ///
    /// For vault tokens (starting with "vntls:") that are not in the cache, synthetic instruments
    /// will be created automatically.
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails or parsing fails.
    ///
    /// Returns an error if `account_id` has not been set on the client.
    pub async fn request_position_status_reports(
        &self,
        user: &str,
        instrument_id: Option<InstrumentId>,
    ) -> Result<Vec<PositionStatusReport>> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
        let state_response = self.info_clearinghouse_state(user).await?;

        // Extract asset positions from the clearinghouse state
        let asset_positions: Vec<serde_json::Value> = state_response
            .get("assetPositions")
            .and_then(|v| v.as_array())
            .ok_or_else(|| Error::bad_request("assetPositions not found in clearinghouse state"))?
            .clone();

        let mut reports = Vec::new();
        let ts_init = self.clock.get_time_ns();

        for position_value in asset_positions {
            // Extract coin from position data
            let coin = position_value
                .get("position")
                .and_then(|p| p.get("coin"))
                .and_then(|c| c.as_str())
                .ok_or_else(|| Error::bad_request("coin not found in position"))?;

            // Get instrument from cache - convert &str to Ustr for lookup
            let coin_ustr = Ustr::from(coin);
            let instrument = match self.get_or_create_instrument(&coin_ustr, None) {
                Some(inst) => inst,
                None => continue, // Skip if instrument not found
            };

            // Filter by instrument_id if specified
            if let Some(filter_id) = instrument_id
                && instrument.id() != filter_id
            {
                continue;
            }

            // Parse to PositionStatusReport
            match parse_position_status_report(&position_value, &instrument, account_id, ts_init) {
                Ok(report) => reports.push(report),
                Err(e) => log::error!("Failed to parse position status report: {e}"),
            }
        }

        Ok(reports)
    }

    /// Request account state (balances and margins) for a user.
    ///
    /// Fetches clearinghouse state from Hyperliquid API and converts it to `AccountState`.
    ///
    /// # Errors
    ///
    /// Returns an error if `account_id` is not set or the API request fails.
    pub async fn request_account_state(&self, user: &str) -> Result<AccountState> {
        let account_id = self
            .account_id
            .ok_or_else(|| Error::bad_request("Account ID not set"))?;
        let state_response = self.info_clearinghouse_state(user).await?;
        let ts_init = self.clock.get_time_ns();

        log::trace!("Clearinghouse state response: {state_response}");

        // Parse clearinghouse state
        let state: ClearinghouseState =
            serde_json::from_value(state_response.clone()).map_err(|e| {
                log::error!("Failed to parse clearinghouse state: {e}");
                log::debug!("Raw response: {state_response}");
                Error::bad_request(format!("Failed to parse clearinghouse state: {e}"))
            })?;

        // Create USDC currency for balances
        let usdc = Currency::new("USDC", 6, 0, "0.000001", CurrencyType::Crypto);

        // Build balances using Decimal arithmetic for precision
        let balances = if let Some(margin) = &state.cross_margin_summary {
            let mut total = margin.total_raw_usd.max(Decimal::ZERO);
            let free = state.withdrawable.unwrap_or(total).max(Decimal::ZERO);

            // Ensure total >= free (withdrawable may include spot balances not in total_raw_usd)
            if free > total {
                log::debug!("Adjusting total ({total}) to match withdrawable ({free})");
                total = free;
            }

            let locked = (total - free).max(Decimal::ZERO);

            vec![AccountBalance::new(
                Money::from_decimal(total, usdc).map_err(|e| Error::decode(e.to_string()))?,
                Money::from_decimal(locked, usdc).map_err(|e| Error::decode(e.to_string()))?,
                Money::from_decimal(free, usdc).map_err(|e| Error::decode(e.to_string()))?,
            )]
        } else {
            // No margin summary, use withdrawable if available
            let free = state
                .withdrawable
                .unwrap_or(Decimal::ZERO)
                .max(Decimal::ZERO);

            vec![AccountBalance::new(
                Money::from_decimal(free, usdc).map_err(|e| Error::decode(e.to_string()))?,
                Money::zero(usdc),
                Money::from_decimal(free, usdc).map_err(|e| Error::decode(e.to_string()))?,
            )]
        };

        Ok(AccountState::new(
            account_id,
            AccountType::Margin,
            balances,
            vec![], // Margins can be added later if needed
            true,   // reported
            UUID4::new(),
            ts_init,
            ts_init,
            None,
        ))
    }

    /// Request historical bars for an instrument.
    ///
    /// Fetches candle data from the Hyperliquid API and converts it to Nautilus bars.
    /// Incomplete bars (where end_timestamp >= current time) are filtered out.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The instrument is not found in cache.
    /// - The bar aggregation is unsupported by Hyperliquid.
    /// - The API request fails.
    /// - Parsing fails.
    ///
    /// # References
    ///
    /// <https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint#candles-snapshot>
    pub async fn request_bars(
        &self,
        bar_type: BarType,
        start: Option<chrono::DateTime<chrono::Utc>>,
        end: Option<chrono::DateTime<chrono::Utc>>,
        limit: Option<u32>,
    ) -> Result<Vec<Bar>> {
        let instrument_id = bar_type.instrument_id();
        let symbol = instrument_id.symbol;

        let product_type = HyperliquidProductType::from_symbol(symbol.as_str()).ok();

        // Extract base currency for lookup, then use raw_symbol for the API call
        let base = Ustr::from(
            symbol
                .as_str()
                .split('-')
                .next()
                .ok_or_else(|| Error::bad_request("Invalid instrument symbol"))?,
        );

        let instrument = self
            .get_or_create_instrument(&base, product_type)
            .ok_or_else(|| {
                Error::bad_request(format!("Instrument not found in cache: {instrument_id}"))
            })?;

        // Use raw_symbol which has the correct Hyperliquid API format:
        // - Perps: base currency (e.g., "BTC")
        // - Spot PURR: slash format (e.g., "PURR/USDC")
        // - Spot others: @{index} format (e.g., "@107")
        let coin = instrument.raw_symbol().inner();

        let price_precision = instrument.price_precision();
        let size_precision = instrument.size_precision();

        let interval =
            bar_type_to_interval(&bar_type).map_err(|e| Error::bad_request(e.to_string()))?;

        // Hyperliquid uses millisecond timestamps
        let now = chrono::Utc::now();
        let end_time = end.unwrap_or(now).timestamp_millis() as u64;
        let start_time = if let Some(start) = start {
            start.timestamp_millis() as u64
        } else {
            // Default to 1000 bars before end_time
            let spec = bar_type.spec();
            let step_ms = match spec.aggregation {
                BarAggregation::Minute => spec.step.get() as u64 * 60_000,
                BarAggregation::Hour => spec.step.get() as u64 * 3_600_000,
                BarAggregation::Day => spec.step.get() as u64 * 86_400_000,
                BarAggregation::Week => spec.step.get() as u64 * 604_800_000,
                BarAggregation::Month => spec.step.get() as u64 * 2_592_000_000,
                _ => 60_000,
            };
            end_time.saturating_sub(1000 * step_ms)
        };

        let candles = self
            .info_candle_snapshot(coin.as_str(), interval, start_time, end_time)
            .await?;

        // Filter out incomplete bars where end_timestamp >= current time
        let now_ms = now.timestamp_millis() as u64;

        let mut bars: Vec<Bar> = candles
            .iter()
            .filter(|candle| candle.end_timestamp < now_ms)
            .enumerate()
            .filter_map(|(i, candle)| {
                candle_to_bar(candle, bar_type, price_precision, size_precision)
                    .map_err(|e| {
                        log::error!("Failed to convert candle {i} to bar: {candle:?} error: {e}");
                        e
                    })
                    .ok()
            })
            .collect();

        // 0 means no limit
        if let Some(limit) = limit
            && limit > 0
            && bars.len() > limit as usize
        {
            bars.truncate(limit as usize);
        }

        log::debug!(
            "Received {} bars for {} (filtered {} incomplete)",
            bars.len(),
            bar_type,
            candles.len() - bars.len()
        );
        Ok(bars)
    }

    /// Submits an order to the exchange.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing, order validation fails, serialization fails,
    /// or the API returns an error.
    #[allow(clippy::too_many_arguments)]
    pub async fn submit_order(
        &self,
        instrument_id: InstrumentId,
        client_order_id: ClientOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: TimeInForce,
        price: Option<Price>,
        trigger_price: Option<Price>,
        post_only: bool,
        reduce_only: bool,
    ) -> Result<OrderStatusReport> {
        let symbol = instrument_id.symbol.as_str();
        let asset = self.get_asset_index(symbol).ok_or_else(|| {
            Error::bad_request(format!(
                "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
            ))
        })?;

        let is_buy = matches!(order_side, OrderSide::Buy);
        let price_precision = self.get_price_precision(symbol).unwrap_or(2);

        let price_decimal = match price {
            Some(px) if self.normalize_prices => {
                normalize_price(px.as_decimal(), price_precision).normalize()
            }
            Some(px) => px.as_decimal().normalize(),
            None if matches!(order_type, OrderType::Market) => Decimal::ZERO,
            None if matches!(
                order_type,
                OrderType::StopMarket | OrderType::MarketIfTouched
            ) =>
            {
                match trigger_price {
                    Some(tp) => {
                        let derived =
                            derive_limit_from_trigger(tp.as_decimal().normalize(), is_buy);
                        let sig_rounded = round_to_sig_figs(derived, 5);
                        clamp_price_to_precision(sig_rounded, price_precision, is_buy).normalize()
                    }
                    None => Decimal::ZERO,
                }
            }
            None => return Err(Error::bad_request("Limit orders require a price")),
        };

        let size_decimal = quantity.as_decimal().normalize();

        let kind = match order_type {
            OrderType::Market => HyperliquidExecOrderKind::Limit {
                limit: HyperliquidExecLimitParams {
                    tif: HyperliquidExecTif::Ioc,
                },
            },
            OrderType::Limit => {
                let tif = if post_only {
                    HyperliquidExecTif::Alo
                } else {
                    match time_in_force {
                        TimeInForce::Gtc => HyperliquidExecTif::Gtc,
                        TimeInForce::Ioc => HyperliquidExecTif::Ioc,
                        TimeInForce::Fok
                        | TimeInForce::Day
                        | TimeInForce::Gtd
                        | TimeInForce::AtTheOpen
                        | TimeInForce::AtTheClose => {
                            return Err(Error::bad_request(format!(
                                "Time in force {time_in_force:?} not supported"
                            )));
                        }
                    }
                };
                HyperliquidExecOrderKind::Limit {
                    limit: HyperliquidExecLimitParams { tif },
                }
            }
            OrderType::StopMarket
            | OrderType::StopLimit
            | OrderType::MarketIfTouched
            | OrderType::LimitIfTouched => {
                if let Some(trig_px) = trigger_price {
                    let trigger_price_decimal = if self.normalize_prices {
                        normalize_price(trig_px.as_decimal(), price_precision).normalize()
                    } else {
                        trig_px.as_decimal().normalize()
                    };

                    // Determine TP/SL type based on order type
                    // StopMarket/StopLimit are always Sl (protective stops)
                    // MarketIfTouched/LimitIfTouched are always Tp (profit-taking/entry)
                    let tpsl = match order_type {
                        OrderType::StopMarket | OrderType::StopLimit => HyperliquidExecTpSl::Sl,
                        OrderType::MarketIfTouched | OrderType::LimitIfTouched => {
                            HyperliquidExecTpSl::Tp
                        }
                        _ => unreachable!(),
                    };

                    let is_market = matches!(
                        order_type,
                        OrderType::StopMarket | OrderType::MarketIfTouched
                    );

                    HyperliquidExecOrderKind::Trigger {
                        trigger: HyperliquidExecTriggerParams {
                            is_market,
                            trigger_px: trigger_price_decimal,
                            tpsl,
                        },
                    }
                } else {
                    return Err(Error::bad_request("Trigger orders require a trigger price"));
                }
            }
            _ => {
                return Err(Error::bad_request(format!(
                    "Order type {order_type:?} not supported"
                )));
            }
        };

        let hyperliquid_order = HyperliquidExecPlaceOrderRequest {
            asset,
            is_buy,
            price: price_decimal,
            size: size_decimal,
            reduce_only,
            kind,
            cloid: Some(Cloid::from_client_order_id(client_order_id)),
        };

        let builder = if self.has_vault_address() {
            None
        } else {
            Some(HyperliquidExecBuilderFee {
                address: NAUTILUS_BUILDER_ADDRESS.to_string(),
                fee_tenths_bp: 0,
            })
        };

        let action = HyperliquidExecAction::Order {
            orders: vec![hyperliquid_order],
            grouping: HyperliquidExecGrouping::Na,
            builder,
        };

        let response = self.inner.post_action_exec(&action).await?;

        match response {
            HyperliquidExchangeResponse::Status {
                status,
                response: response_data,
            } if status == RESPONSE_STATUS_OK => {
                let data_value = if let Some(data) = response_data.get("data") {
                    data.clone()
                } else {
                    response_data
                };

                let order_response: HyperliquidExecOrderResponseData =
                    serde_json::from_value(data_value).map_err(|e| {
                        Error::bad_request(format!("Failed to parse order response: {e}"))
                    })?;

                let order_status = order_response
                    .statuses
                    .first()
                    .ok_or_else(|| Error::bad_request("No order status in response"))?;

                let symbol_str = instrument_id.symbol.as_str();
                let product_type = HyperliquidProductType::from_symbol(symbol_str).ok();

                // Extract base coin from symbol (first segment before '-')
                let asset_str = symbol_str.split('-').next().unwrap_or(symbol_str);
                let instrument = self
                    .get_or_create_instrument(&Ustr::from(asset_str), product_type)
                    .ok_or_else(|| {
                        Error::bad_request(format!("Instrument not found for {asset_str}"))
                    })?;

                let account_id = self
                    .account_id
                    .ok_or_else(|| Error::bad_request("Account ID not set"))?;
                let ts_init = self.clock.get_time_ns();

                match order_status {
                    HyperliquidExecOrderStatus::Resting { resting } => Ok(self
                        .create_order_status_report(
                            instrument_id,
                            Some(client_order_id),
                            VenueOrderId::new(resting.oid.to_string()),
                            order_side,
                            order_type,
                            quantity,
                            time_in_force,
                            price,
                            trigger_price,
                            OrderStatus::Accepted,
                            Quantity::new(0.0, instrument.size_precision()),
                            &instrument,
                            account_id,
                            ts_init,
                        )),
                    HyperliquidExecOrderStatus::Filled { filled } => {
                        let filled_qty = Quantity::new(
                            filled.total_sz.to_string().parse::<f64>().unwrap_or(0.0),
                            instrument.size_precision(),
                        );
                        Ok(self.create_order_status_report(
                            instrument_id,
                            Some(client_order_id),
                            VenueOrderId::new(filled.oid.to_string()),
                            order_side,
                            order_type,
                            quantity,
                            time_in_force,
                            price,
                            trigger_price,
                            OrderStatus::Filled,
                            filled_qty,
                            &instrument,
                            account_id,
                            ts_init,
                        ))
                    }
                    HyperliquidExecOrderStatus::Error { error } => {
                        Err(Error::bad_request(format!("Order rejected: {error}")))
                    }
                }
            }
            HyperliquidExchangeResponse::Error { error } => Err(Error::bad_request(format!(
                "Order submission failed: {error}"
            ))),
            _ => Err(Error::bad_request("Unexpected response format")),
        }
    }

    /// Submit an order using an OrderAny object.
    ///
    /// This is a convenience method that wraps submit_order.
    pub async fn submit_order_from_order_any(&self, order: &OrderAny) -> Result<OrderStatusReport> {
        self.submit_order(
            order.instrument_id(),
            order.client_order_id(),
            order.order_side(),
            order.order_type(),
            order.quantity(),
            order.time_in_force(),
            order.price(),
            order.trigger_price(),
            order.is_post_only(),
            order.is_reduce_only(),
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    fn create_order_status_report(
        &self,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: VenueOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: TimeInForce,
        price: Option<Price>,
        trigger_price: Option<Price>,
        order_status: OrderStatus,
        filled_qty: Quantity,
        _instrument: &InstrumentAny,
        account_id: AccountId,
        ts_init: UnixNanos,
    ) -> OrderStatusReport {
        let ts_accepted = self.clock.get_time_ns();
        let ts_last = ts_accepted;
        let report_id = UUID4::new();

        let mut report = OrderStatusReport::new(
            account_id,
            instrument_id,
            client_order_id,
            venue_order_id,
            order_side,
            order_type,
            time_in_force,
            order_status,
            quantity,
            filled_qty,
            ts_accepted,
            ts_last,
            ts_init,
            Some(report_id),
        );

        if let Some(px) = price {
            report = report.with_price(px);
        }

        if let Some(trig_px) = trigger_price {
            report = report
                .with_trigger_price(trig_px)
                .with_trigger_type(TriggerType::Default);
        }

        report
    }

    /// Submit multiple orders to the Hyperliquid exchange in a single request.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing, order validation fails, serialization fails,
    /// or the API returns an error.
    pub async fn submit_orders(&self, orders: &[&OrderAny]) -> Result<Vec<OrderStatusReport>> {
        // Convert orders using asset indices from the cached map
        let mut hyperliquid_orders = Vec::with_capacity(orders.len());

        for order in orders {
            let instrument_id = order.instrument_id();
            let symbol = instrument_id.symbol.as_str();
            let asset = self.get_asset_index(symbol).ok_or_else(|| {
                Error::bad_request(format!(
                    "Asset index not found for symbol: {symbol}. Ensure instruments are loaded."
                ))
            })?;
            let price_decimals = self.get_price_precision(symbol).unwrap_or(2);
            let request = order_to_hyperliquid_request_with_asset(
                order,
                asset,
                price_decimals,
                self.normalize_prices,
            )
            .map_err(|e| Error::bad_request(format!("Failed to convert order: {e}")))?;
            hyperliquid_orders.push(request);
        }

        let builder = if self.has_vault_address() {
            None
        } else {
            Some(HyperliquidExecBuilderFee {
                address: NAUTILUS_BUILDER_ADDRESS.to_string(),
                fee_tenths_bp: 0,
            })
        };

        let action = HyperliquidExecAction::Order {
            orders: hyperliquid_orders,
            grouping: HyperliquidExecGrouping::Na,
            builder,
        };

        // Submit to exchange using the typed exec endpoint
        let response = self.inner.post_action_exec(&action).await?;

        // Parse the response to extract order statuses
        match response {
            HyperliquidExchangeResponse::Status {
                status,
                response: response_data,
            } if status == RESPONSE_STATUS_OK => {
                // Extract the 'data' field from the response if it exists (new format)
                // Otherwise use response_data directly (old format)
                let data_value = if let Some(data) = response_data.get("data") {
                    data.clone()
                } else {
                    response_data
                };

                // Parse the response data to extract order statuses
                let order_response: HyperliquidExecOrderResponseData =
                    serde_json::from_value(data_value).map_err(|e| {
                        Error::bad_request(format!("Failed to parse order response: {e}"))
                    })?;

                let account_id = self
                    .account_id
                    .ok_or_else(|| Error::bad_request("Account ID not set"))?;
                let ts_init = self.clock.get_time_ns();

                // Validate we have the same number of statuses as orders submitted
                if order_response.statuses.len() != orders.len() {
                    return Err(Error::bad_request(format!(
                        "Mismatch between submitted orders ({}) and response statuses ({})",
                        orders.len(),
                        order_response.statuses.len()
                    )));
                }

                let mut reports = Vec::new();

                // Create OrderStatusReport for each order
                for (order, order_status) in orders.iter().zip(order_response.statuses.iter()) {
                    // Extract asset from instrument symbol
                    let instrument_id = order.instrument_id();
                    let symbol = instrument_id.symbol.as_str();
                    let product_type = HyperliquidProductType::from_symbol(symbol).ok();

                    // Extract base coin from symbol (first segment before '-')
                    let asset = symbol.split('-').next().unwrap_or(symbol);
                    let instrument = self
                        .get_or_create_instrument(&Ustr::from(asset), product_type)
                        .ok_or_else(|| {
                            Error::bad_request(format!("Instrument not found for {asset}"))
                        })?;

                    // Create OrderStatusReport based on the order status
                    let report = match order_status {
                        HyperliquidExecOrderStatus::Resting { resting } => {
                            // Order is resting on the order book
                            self.create_order_status_report(
                                order.instrument_id(),
                                Some(order.client_order_id()),
                                VenueOrderId::new(resting.oid.to_string()),
                                order.order_side(),
                                order.order_type(),
                                order.quantity(),
                                order.time_in_force(),
                                order.price(),
                                order.trigger_price(),
                                OrderStatus::Accepted,
                                Quantity::new(0.0, instrument.size_precision()),
                                &instrument,
                                account_id,
                                ts_init,
                            )
                        }
                        HyperliquidExecOrderStatus::Filled { filled } => {
                            // Order was filled immediately
                            let filled_qty = Quantity::new(
                                filled.total_sz.to_string().parse::<f64>().unwrap_or(0.0),
                                instrument.size_precision(),
                            );
                            self.create_order_status_report(
                                order.instrument_id(),
                                Some(order.client_order_id()),
                                VenueOrderId::new(filled.oid.to_string()),
                                order.order_side(),
                                order.order_type(),
                                order.quantity(),
                                order.time_in_force(),
                                order.price(),
                                order.trigger_price(),
                                OrderStatus::Filled,
                                filled_qty,
                                &instrument,
                                account_id,
                                ts_init,
                            )
                        }
                        HyperliquidExecOrderStatus::Error { error } => {
                            return Err(Error::bad_request(format!(
                                "Order {} rejected: {error}",
                                order.client_order_id()
                            )));
                        }
                    };

                    reports.push(report);
                }

                Ok(reports)
            }
            HyperliquidExchangeResponse::Error { error } => Err(Error::bad_request(format!(
                "Order submission failed: {error}"
            ))),
            _ => Err(Error::bad_request("Unexpected response format")),
        }
    }
}

/// Returns the asset index base for a perp dex.
///
/// Standard perps (dex 0) start at 0. HIP-3 dexes start at
/// 100_000 + dex_index * 10_000.
fn perp_dex_asset_index_base(dex_index: usize) -> u32 {
    if dex_index == 0 {
        0
    } else {
        100_000 + dex_index as u32 * 10_000
    }
}

#[cfg(test)]
mod tests {
    use nautilus_core::{MUTEX_POISONED, time::get_atomic_clock_realtime};
    use nautilus_model::{
        currencies::CURRENCY_MAP,
        enums::CurrencyType,
        identifiers::{InstrumentId, Symbol},
        instruments::{CurrencyPair, Instrument, InstrumentAny},
        types::{Currency, Price, Quantity},
    };
    use rstest::rstest;
    use ustr::Ustr;

    use super::HyperliquidHttpClient;
    use crate::{
        common::{consts::HYPERLIQUID_VENUE, enums::HyperliquidProductType},
        http::query::InfoRequest,
    };

    #[rstest]
    fn stable_json_roundtrips() {
        let v = serde_json::json!({"type":"l2Book","coin":"BTC"});
        let s = serde_json::to_string(&v).unwrap();
        // Parse back to ensure JSON structure is correct, regardless of field order
        let parsed: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(parsed["type"], "l2Book");
        assert_eq!(parsed["coin"], "BTC");
        assert_eq!(parsed, v);
    }

    #[rstest]
    fn info_pretty_shape() {
        let r = InfoRequest::l2_book("BTC");
        let val = serde_json::to_value(&r).unwrap();
        let pretty = serde_json::to_string_pretty(&val).unwrap();
        assert!(pretty.contains("\"type\": \"l2Book\""));
        assert!(pretty.contains("\"coin\": \"BTC\""));
    }

    #[rstest]
    fn test_cache_instrument_by_raw_symbol() {
        let client = HyperliquidHttpClient::new(true, 60, None).unwrap();

        // Create a test instrument with base currency "vntls:vCURSOR"
        let base_code = "vntls:vCURSOR";
        let quote_code = "USDC";

        // Register the custom currency
        {
            let mut currency_map = CURRENCY_MAP.lock().expect(MUTEX_POISONED);
            if !currency_map.contains_key(base_code) {
                currency_map.insert(
                    base_code.to_string(),
                    Currency::new(base_code, 8, 0, base_code, CurrencyType::Crypto),
                );
            }
        }

        let base_currency = Currency::new(base_code, 8, 0, base_code, CurrencyType::Crypto);
        let quote_currency = Currency::new(quote_code, 6, 0, quote_code, CurrencyType::Crypto);

        // Nautilus symbol is "vntls:vCURSOR-USDC-SPOT"
        let symbol = Symbol::new("vntls:vCURSOR-USDC-SPOT");
        let venue = *HYPERLIQUID_VENUE;
        let instrument_id = InstrumentId::new(symbol, venue);

        // raw_symbol is set to the base currency "vntls:vCURSOR" (see parse.rs)
        let raw_symbol = Symbol::new(base_code);

        let clock = get_atomic_clock_realtime();
        let ts = clock.get_time_ns();

        let instrument = InstrumentAny::CurrencyPair(CurrencyPair::new(
            instrument_id,
            raw_symbol,
            base_currency,
            quote_currency,
            8,
            8,
            Price::from("0.00000001"),
            Quantity::from("0.00000001"),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None, // taker_fee
            None, // info
            ts,
            ts,
        ));

        // Cache the instrument
        client.cache_instrument(&instrument);

        // Verify it can be looked up by full symbol
        let instruments = client.instruments.load();
        let by_full_symbol = instruments.get(&Ustr::from("vntls:vCURSOR-USDC-SPOT"));
        assert!(
            by_full_symbol.is_some(),
            "Instrument should be accessible by full symbol"
        );
        assert_eq!(by_full_symbol.unwrap().id(), instrument.id());

        // Verify it can be looked up by raw_symbol (coin) - backward compatibility
        let by_raw_symbol = instruments.get(&Ustr::from("vntls:vCURSOR"));
        assert!(
            by_raw_symbol.is_some(),
            "Instrument should be accessible by raw_symbol (Hyperliquid coin identifier)"
        );
        assert_eq!(by_raw_symbol.unwrap().id(), instrument.id());
        drop(instruments);

        // Verify it can be looked up by composite key (coin, product_type)
        let instruments_by_coin = client.instruments_by_coin.load();
        let by_coin =
            instruments_by_coin.get(&(Ustr::from("vntls:vCURSOR"), HyperliquidProductType::Spot));
        assert!(
            by_coin.is_some(),
            "Instrument should be accessible by coin and product type"
        );
        assert_eq!(by_coin.unwrap().id(), instrument.id());
        drop(instruments_by_coin);

        // Verify get_or_create_instrument works with product type
        let retrieved_with_type = client.get_or_create_instrument(
            &Ustr::from("vntls:vCURSOR"),
            Some(HyperliquidProductType::Spot),
        );
        assert!(retrieved_with_type.is_some());
        assert_eq!(retrieved_with_type.unwrap().id(), instrument.id());

        // Verify get_or_create_instrument works without product type (fallback)
        let retrieved_without_type =
            client.get_or_create_instrument(&Ustr::from("vntls:vCURSOR"), None);
        assert!(retrieved_without_type.is_some());
        assert_eq!(retrieved_without_type.unwrap().id(), instrument.id());
    }
}