dex-connector 3.2.3

connections to dexes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
#![cfg(feature = "lighter-sdk")]

// Lighter Protocol Order Type constants
const ORDER_TYPE_LIMIT: u32 = 0;
const ORDER_TYPE_IOC: u32 = 1;
const ORDER_TYPE_TRIGGER: u32 = 2;
// Note: Lighter reuses enum values for certain order-type/TIF combinations.

// Lighter Protocol Side constants (order direction, not position direction)
const SIDE_SELL: u32 = 0; // Sell order (close long positions, open short positions)
const SIDE_BUY: u32 = 1; // Buy order (close short positions, open long positions)

// Lighter Protocol Time-in-Force constants (aligned with Go SDK)
const TIF_IOC: u32 = 0; // Immediate-or-Cancel
const TIF_GTT: u32 = 1; // Good-Till-Time
const TIF_POST_ONLY: u32 = 2; // Post-Only (behaves like GTT but rejects immediate fills)

// Lighter Protocol scaling defaults (will be overridden by market metadata)
const DEFAULT_PRICE_DECIMALS: u32 = 1;
const DEFAULT_SIZE_DECIMALS: u32 = 5;
const MAX_DECIMAL_PRECISION: u32 = 9;

use crate::{
    dex_connector::{string_to_decimal, DexConnector},
    dex_request::{DexError, HttpMethod},
    dex_websocket::DexWebSocket,
    BalanceResponse, CanceledOrder, CanceledOrdersResponse, CombinedBalanceResponse,
    CreateOrderResponse, FilledOrder, FilledOrdersResponse, LastTrade, LastTradesResponse,
    OpenOrder, OpenOrdersResponse, OrderSide, TickerResponse, TpSl, TriggerOrderStyle,
};
use async_trait::async_trait;
use chrono::{DateTime, Duration as ChronoDuration, Utc};
use reqwest::Client;
use rust_decimal::Decimal;
use rust_decimal::{
    prelude::{FromStr, ToPrimitive},
    RoundingStrategy,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
    collections::HashMap,
    convert::TryFrom,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Mutex,
    },
    time::{Duration, Instant},
};
use tokio::sync::RwLock;
use tokio::task::JoinHandle;

/// Determine buy/sell direction for SL/TP orders based on position direction
/// Returns true for buy orders, false for sell orders
/// - Long position SL/TP = Sell order (close position) = false
/// - Short position SL/TP = Buy order (close position) = true
fn is_buy_for_tpsl(position_side: OrderSide) -> bool {
    matches!(position_side, OrderSide::Short)
}

struct MaintenanceInfo {
    next_start: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug)]
struct MarketInfo {
    canonical_symbol: String,
    market_id: u32,
    price_decimals: u32,
    size_decimals: u32,
}

#[derive(Default, Debug)]
struct MarketCache {
    by_symbol: HashMap<String, MarketInfo>,
    by_id: HashMap<u32, MarketInfo>,
}

// Priority message system for WebSocket sending
#[derive(Debug)]
enum OutboundMessage {
    Control(tokio_tungstenite::tungstenite::Message), // High priority: Pong, Close
}

impl OutboundMessage {
    fn into_message(self) -> tokio_tungstenite::tungstenite::Message {
        match self {
            OutboundMessage::Control(msg) => msg,
        }
    }

    fn is_pong(&self) -> bool {
        match self {
            OutboundMessage::Control(tokio_tungstenite::tungstenite::Message::Pong(_)) => true,
            _ => false,
        }
    }
}

fn normalize_symbol(symbol: &str) -> String {
    let upper = symbol.trim().to_ascii_uppercase();
    let mut normalized = upper
        .replace("-PERP", "")
        .replace("_PERP", "")
        .replace(".PERP", "")
        .replace("-USD", "")
        .replace("_USD", "")
        .replace("/USD", "")
        .replace("-USDC", "")
        .replace("_USDC", "")
        .replace("/USDC", "");
    if normalized.ends_with("-PERP") {
        normalized = normalized.trim_end_matches("-PERP").to_string();
    }
    normalized
}

// Cryptographic imports
#[cfg(feature = "lighter-sdk")]
use libc::{c_char, c_int, c_longlong};
use secp256k1::{Message, Secp256k1, SecretKey};
use sha3::{Digest, Keccak256};
#[cfg(feature = "lighter-sdk")]
use std::ffi::{CStr, CString};
use tokio::time::sleep;
use tokio_tungstenite;

// FFI bindings for Go shared library (only with lighter-sdk feature)
#[cfg(feature = "lighter-sdk")]
#[repr(C)]
pub struct StrOrErr {
    pub str: *mut c_char,
    pub err: *mut c_char,
}

#[cfg(feature = "lighter-sdk")]
extern "C" {
    fn CreateClient(
        url: *const c_char,
        private_key: *const c_char,
        chain_id: c_int,
        api_key_index: c_int,
        account_index: c_longlong,
    ) -> *mut c_char;

    fn CheckClient(api_key_index: c_int, account_index: c_longlong) -> *mut c_char;

    fn GetClientPubKey(api_key_index: c_int, account_index: c_longlong) -> *mut c_char;

    fn SignCreateOrder(
        market_index: c_int,
        client_order_index: c_longlong,
        base_amount: c_longlong,
        price: c_int,
        is_ask: c_int,
        order_type: c_int,
        time_in_force: c_int,
        reduce_only: c_int,
        trigger_price: c_int,
        order_expiry: c_longlong,
        nonce: c_longlong,
    ) -> StrOrErr;

    fn SignCancelOrder(market_index: c_int, order_index: c_longlong, nonce: c_longlong)
        -> StrOrErr;

    fn SignChangePubKey(new_pubkey: *const c_char, nonce: c_longlong) -> StrOrErr;

    fn SignMessageWithEVM(private_key: *const c_char, message: *const c_char) -> StrOrErr;
}

/// Global API call counter for monitoring Lighter Protocol rate limits
static API_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
static API_CALL_TRACKER: std::sync::LazyLock<Mutex<Vec<(Instant, String)>>> =
    std::sync::LazyLock::new(|| Mutex::new(Vec::new()));

/// Track and log API calls for rate limit monitoring
fn track_api_call(endpoint: &str, method: &str) {
    let call_count = API_CALL_COUNTER.fetch_add(1, Ordering::SeqCst) + 1;
    let now = Instant::now();

    // Clean old entries (older than 60 seconds)
    {
        let mut tracker = API_CALL_TRACKER.lock().unwrap();
        tracker.retain(|(time, _)| now.duration_since(*time) < Duration::from_secs(60));
        tracker.push((now, format!("{} {}", method, endpoint)));

        let recent_calls = tracker.len();
        log::info!(
            "[API_TRACKER] #{} {} {} | Recent calls (60s): {} | Rate: {:.1}/min",
            call_count,
            method,
            endpoint,
            recent_calls,
            recent_calls as f64
        );

        // Warn if approaching rate limit
        if recent_calls > 45 {
            log::warn!(
                "[API_TRACKER] ⚠️  Approaching rate limit: {}/60 calls in last 60s",
                recent_calls
            );
        }
    }
}

#[derive(Clone)]
pub struct LighterConnector {
    api_key_public: String,      // X-API-KEY header (from Lighter UI)
    api_key_index: u32,          // api_key_index query param
    api_private_key_hex: String, // API private key for signing (40-byte)
    #[cfg(feature = "lighter-sdk")]
    evm_wallet_private_key: Option<String>, // EVM wallet private key for API key registration
    account_index: u32,          // account_index query param
    base_url: String,
    websocket_url: String,
    _l1_address: String, // derived from wallet for logging purposes
    client: Client,
    filled_orders: Arc<RwLock<HashMap<String, Vec<FilledOrder>>>>,
    canceled_orders: Arc<RwLock<HashMap<String, Vec<CanceledOrder>>>>,
    // Cache for API key data to avoid repeated requests
    cached_server_pubkey: Arc<tokio::sync::RwLock<Option<(String, std::time::Instant)>>>,
    is_running: Arc<AtomicBool>,
    // Auto-cleanup management
    cleanup_started: Arc<AtomicBool>,
    cleanup_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
    _ws: Option<DexWebSocket>, // Reserved for future WebSocket implementation
    // WebSocket data storage
    current_price: Arc<RwLock<Option<(Decimal, u64)>>>, // (price, timestamp)
    current_volume: Arc<RwLock<Option<Decimal>>>,
    order_book: Arc<RwLock<Option<LighterOrderBook>>>,
    maintenance: Arc<RwLock<MaintenanceInfo>>,
    // WebSocket-based order tracking (no API calls)
    cached_open_orders: Arc<RwLock<HashMap<String, Vec<OpenOrder>>>>, // symbol -> orders
    // Connection epoch counter for race detection
    connection_epoch: Arc<AtomicU64>,
    // Market metadata cache for symbol↔market_id resolution
    market_cache: Arc<RwLock<MarketCache>>,
    // Symbols requested by caller (for order book subscription)
    tracked_symbols: Vec<String>,
}

#[derive(Deserialize, Debug, Clone)]
struct LighterOrderBook {
    bids: Vec<LighterOrderBookEntry>,
    asks: Vec<LighterOrderBookEntry>,
}

#[derive(Deserialize, Debug, Clone)]
struct LighterOrderBookEntry {
    price: String,
    size: String,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterAccountResponse {
    code: i32,
    total: i32,
    accounts: Vec<LighterAccountInfo>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterAccountInfo {
    account_index: i64,
    available_balance: String,
    collateral: String,
    total_asset_value: String,
    positions: Vec<LighterPosition>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterPosition {
    market_id: u8,
    symbol: String,
    position: String,
    sign: i8,
    open_order_count: u32,
    avg_entry_price: String,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterTradesResponse {
    code: i32,
    trades: Vec<LighterTrade>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterTrade {
    trade_id: u64,
    price: String,
    size: String,
    usd_amount: String,
    market_id: u8,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterExchangeStats {
    code: i32,
    order_book_stats: Vec<LighterOrderBookStats>,
    daily_usd_volume: f64,
    daily_trades_count: u32,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterOrderBookStats {
    symbol: String,
    last_trade_price: f64,
    daily_trades_count: u32,
    daily_base_token_volume: f64,
    daily_quote_token_volume: f64,
    daily_price_change: f64,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterFundingRates {
    code: i32,
    funding_rates: Vec<LighterFundingRate>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterFundingRate {
    market_id: u32,
    exchange: String,
    symbol: String,
    rate: f64,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterOrderBookDetailsResponse {
    code: i32,
    #[serde(rename = "order_book_details")]
    order_book_details: Vec<LighterOrderBookDetail>,
}

#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct LighterOrderBookDetail {
    market_id: u32,
    symbol: String,
    #[serde(rename = "supported_price_decimals")]
    supported_price_decimals: Option<u32>,
    #[serde(rename = "supported_size_decimals")]
    supported_size_decimals: Option<u32>,
}

#[allow(dead_code)]
#[derive(Deserialize, Debug)]
struct LighterNonceResponse {
    nonce: u64,
}

#[derive(Deserialize, Debug)]
struct ApiKeyInfo {
    #[serde(rename = "account_index")]
    #[allow(dead_code)]
    account_index: u32,
    #[serde(rename = "api_key_index")]
    #[allow(dead_code)]
    api_key_index: u32,
    #[allow(dead_code)]
    nonce: u32,
    #[serde(rename = "public_key")]
    public_key: String,
}

#[derive(Deserialize, Debug)]
struct ApiKeyResponse {
    #[allow(dead_code)]
    code: u32,
    #[serde(rename = "api_keys")]
    api_keys: Vec<ApiKeyInfo>,
}

#[allow(dead_code)]
#[derive(Deserialize, Debug)]
struct LighterOrderResponse {
    order_id: String,
    price: String,
    amount: String,
}

#[allow(dead_code)]
#[derive(Serialize, Debug)]
struct LighterTx {
    tx_type: String,
    ticker: String,
    amount: String,
    price: Option<String>,
    order_type: String,
    time_in_force: String,
}

#[allow(dead_code)]
#[derive(Serialize, Debug)]
struct LighterSignedEnvelope {
    sig: String,
    nonce: u64,
    tx: LighterTx,
}

// Lighter-specific cryptographic structures

impl LighterConnector {
    async fn refresh_market_cache(&self) -> Result<(), DexError> {
        let mut cache = MarketCache::default();
        let mut detail_decimals: HashMap<u32, (u32, u32)> = HashMap::new();

        match self.get_order_book_details().await {
            Ok(details) => {
                for detail in details.order_book_details {
                    let normalized = normalize_symbol(&detail.symbol);
                    if normalized.is_empty() {
                        continue;
                    }

                    let raw_price_decimals = detail.supported_price_decimals.unwrap_or_else(|| {
                        log::warn!(
                            "Missing supported_price_decimals for market_id={}, using default {}",
                            detail.market_id,
                            DEFAULT_PRICE_DECIMALS
                        );
                        DEFAULT_PRICE_DECIMALS
                    });
                    let price_decimals = raw_price_decimals.min(MAX_DECIMAL_PRECISION);
                    if price_decimals != raw_price_decimals {
                        log::warn!(
                            "supported_price_decimals {} for market_id={} exceeds max {}, clamping",
                            raw_price_decimals,
                            detail.market_id,
                            MAX_DECIMAL_PRECISION
                        );
                    }

                    let raw_size_decimals = detail.supported_size_decimals.unwrap_or_else(|| {
                        log::warn!(
                            "Missing supported_size_decimals for market_id={}, using default {}",
                            detail.market_id,
                            DEFAULT_SIZE_DECIMALS
                        );
                        DEFAULT_SIZE_DECIMALS
                    });
                    let size_decimals = raw_size_decimals.min(MAX_DECIMAL_PRECISION);
                    if size_decimals != raw_size_decimals {
                        log::warn!(
                            "supported_size_decimals {} for market_id={} exceeds max {}, clamping",
                            raw_size_decimals,
                            detail.market_id,
                            MAX_DECIMAL_PRECISION
                        );
                    }

                    detail_decimals.insert(detail.market_id, (price_decimals, size_decimals));

                    let info = MarketInfo {
                        canonical_symbol: normalized.clone(),
                        market_id: detail.market_id,
                        price_decimals,
                        size_decimals,
                    };

                    cache.by_symbol.insert(normalized.clone(), info.clone());
                    cache.by_id.insert(detail.market_id, info);
                }
            }
            Err(err) => {
                log::warn!(
                    "Failed to fetch order book details for market cache: {}. Falling back to funding rates only",
                    err
                );
            }
        }

        let funding = self.get_funding_rates().await?;

        for entry in funding.funding_rates {
            let normalized = normalize_symbol(&entry.symbol);
            if normalized.is_empty() {
                continue;
            }

            let (price_decimals, size_decimals) = detail_decimals
                .get(&entry.market_id)
                .copied()
                .unwrap_or((DEFAULT_PRICE_DECIMALS, DEFAULT_SIZE_DECIMALS));

            if !cache.by_symbol.contains_key(&normalized) {
                let info = MarketInfo {
                    canonical_symbol: normalized.clone(),
                    market_id: entry.market_id,
                    price_decimals,
                    size_decimals,
                };
                cache.by_symbol.insert(normalized.clone(), info.clone());
                cache.by_id.insert(entry.market_id, info);
            } else if !cache.by_id.contains_key(&entry.market_id) {
                if let Some(existing) = cache.by_symbol.get(&normalized) {
                    cache.by_id.insert(entry.market_id, existing.clone());
                }
            }
        }

        if cache.by_symbol.is_empty() {
            return Err(DexError::Other(
                "Unable to populate Lighter market metadata cache".to_string(),
            ));
        }

        *self.market_cache.write().await = cache;
        Ok(())
    }

    async fn resolve_market_info(&self, symbol: &str) -> Result<MarketInfo, DexError> {
        let normalized = normalize_symbol(symbol);
        {
            let cache = self.market_cache.read().await;
            if let Some(info) = cache.by_symbol.get(&normalized) {
                return Ok(info.clone());
            }
        }

        self.refresh_market_cache().await?;
        let cache = self.market_cache.read().await;
        cache
            .by_symbol
            .get(&normalized)
            .cloned()
            .ok_or_else(|| DexError::Other(format!("Unknown symbol: {}", symbol)))
    }

    /// Initialize Go client
    #[cfg(feature = "lighter-sdk")]
    async fn create_go_client(&self) -> Result<(), DexError> {
        unsafe {
            let url = CString::new(self.base_url.as_str())
                .map_err(|e| DexError::Other(format!("Invalid URL: {}", e)))?;

            // Use API private key directly (should be 40 bytes / 80 hex chars)
            let private_key_hex = self
                .api_private_key_hex
                .strip_prefix("0x")
                .unwrap_or(&self.api_private_key_hex);

            if private_key_hex.len() != 80 {
                return Err(DexError::Other(format!(
                    "API private key must be 40 bytes (80 hex chars), got: {}",
                    private_key_hex.len()
                )));
            }

            let private_key = CString::new(private_key_hex)
                .map_err(|e| DexError::Other(format!("Invalid private key: {}", e)))?;

            let result = CreateClient(
                url.as_ptr(),
                private_key.as_ptr(),
                304, // chain_id = 304 for mainnet (same as Python SDK)
                self.api_key_index as c_int,
                self.account_index as c_longlong,
            );

            if !result.is_null() {
                let error_cstr = CStr::from_ptr(result);
                let error_msg = error_cstr.to_string_lossy().to_string();
                libc::free(result as *mut libc::c_void);
                return Err(DexError::Other(format!(
                    "CreateClient error: {}",
                    error_msg
                )));
            }

            // Get the correct public key from the server
            let server_pubkey = match self.get_server_public_key().await {
                Ok(pubkey) => pubkey,
                Err(e) => {
                    log::error!("Failed to get server public key: {}", e);
                    return Err(e);
                }
            };

            // Get the public key derived by the Go shared library
            let go_pubkey_result = GetClientPubKey(
                self.api_key_index as c_int,
                self.account_index as c_longlong,
            );

            let go_derived_pubkey = if !go_pubkey_result.is_null() {
                let pubkey_cstr = CStr::from_ptr(go_pubkey_result);
                let pubkey_str = pubkey_cstr.to_string_lossy().to_string();
                libc::free(go_pubkey_result as *mut libc::c_void);
                Some(pubkey_str)
            } else {
                log::error!("Failed to get public key from Go client");
                None
            };

            // Compare Go-derived key with server key
            if let Some(go_key) = &go_derived_pubkey {
                let srv = server_pubkey
                    .to_lowercase()
                    .trim_start_matches("0x")
                    .to_string();
                let loc = go_key.to_lowercase().trim_start_matches("0x").to_string();

                if loc != srv {
                    log::debug!(
                        "API key mismatch detected (account={}, index={}). server={}…{} vs local={}…{} — will attempt ChangePubKey",
                        self.account_index,
                        self.api_key_index,
                        &srv[..8], &srv[srv.len()-8..],
                        &loc[..8], &loc[loc.len()-8..]
                    );
                } else {
                }
            }

            // Verify the API key is properly registered with Lighter
            let check_result = CheckClient(
                self.api_key_index as c_int,
                self.account_index as c_longlong,
            );

            if !check_result.is_null() {
                let error_cstr = CStr::from_ptr(check_result);
                let error_msg = error_cstr.to_string_lossy().to_string();
                libc::free(check_result as *mut libc::c_void);
                log::error!("API key validation failed: {}", error_msg);

                // Parse the error message to extract key details
                if error_msg.contains("ownPubKey:") && error_msg.contains("PublicKey:") {
                    if let Some(own_start) = error_msg.find("ownPubKey: ") {
                        if let Some(own_end) = error_msg[own_start + 11..].find(" ") {
                            let own_key = &error_msg[own_start + 11..own_start + 11 + own_end];
                            log::error!(
                                "  Our derived public key (first 8): {}",
                                &own_key[..std::cmp::min(8, own_key.len())]
                            );
                            log::error!(
                                "  Our derived public key (last 8): {}",
                                &own_key[std::cmp::max(0, own_key.len().saturating_sub(8))..]
                            );
                        }
                    }
                    if let Some(resp_start) = error_msg.find("PublicKey:") {
                        if let Some(resp_end) = error_msg[resp_start + 10..].find("}") {
                            let resp_key = &error_msg[resp_start + 10..resp_start + 10 + resp_end];
                            log::error!(
                                "  Server expected public key (first 8): {}",
                                &resp_key[..std::cmp::min(8, resp_key.len())]
                            );
                            log::error!(
                                "  Server expected public key (last 8): {}",
                                &resp_key[std::cmp::max(0, resp_key.len().saturating_sub(8))..]
                            );
                        }
                    }
                }

                // If we have the Go-derived public key and EVM wallet key, try to update the API key
                #[cfg(feature = "lighter-sdk")]
                if let (Some(_), Some(_)) = (&go_derived_pubkey, &self.evm_wallet_private_key) {
                    return Err(DexError::ApiKeyRegistrationRequired);
                } else {
                    return Err(DexError::Other(format!(
                        "API key validation failed: {}",
                        error_msg
                    )));
                }

                #[cfg(not(feature = "lighter-sdk"))]
                return Err(DexError::Other(format!(
                    "API key validation failed: {}",
                    error_msg
                )));
            }

            Ok(())
        }
    }

    /// Start auto-cleanup background task for filled orders
    /// Removes orders older than specified duration to prevent memory bloat
    pub fn start_auto_cleanup(&self, cleanup_interval_hours: u64) {
        if self.cleanup_started.swap(true, Ordering::SeqCst) {
            log::warn!("[AUTO_CLEANUP] already started; ignoring.");
            return;
        }

        log::info!(
            "[AUTO_CLEANUP] Starting background task (interval: {}h)",
            cleanup_interval_hours
        );

        let filled_orders = Arc::clone(&self.filled_orders);
        let canceled_orders = Arc::clone(&self.canceled_orders);
        let is_running = Arc::clone(&self.is_running);
        let cleanup_started = Arc::clone(&self.cleanup_started);
        let cleanup_handle = Arc::clone(&self.cleanup_handle);

        let handle = tokio::spawn(async move {
            let mut interval =
                tokio::time::interval(Duration::from_secs(cleanup_interval_hours * 3600));
            // Skip the first immediate tick to delay initial cleanup
            interval.tick().await;

            while is_running.load(Ordering::Relaxed) {
                interval.tick().await;

                let mut filled_removed = 0usize;
                let mut canceled_removed = 0usize;

                // Clean up filled orders - simple approach since FilledOrder doesn't have timestamp
                {
                    let mut filled = filled_orders.write().await;
                    for (symbol, orders) in filled.iter_mut() {
                        const KEEP_FILLED_PER_SYMBOL: usize = 50;
                        if orders.len() > KEEP_FILLED_PER_SYMBOL {
                            let remove_count = orders.len() - KEEP_FILLED_PER_SYMBOL;
                            // Assumes first elements are oldest (order insertion maintains chronological order)
                            orders.drain(0..remove_count);
                            filled_removed += remove_count;
                            log::debug!(
                                "🗑️ [AUTO_CLEANUP] Removed {} old filled orders for {} (kept {})",
                                remove_count,
                                symbol,
                                KEEP_FILLED_PER_SYMBOL
                            );
                        }
                    }
                    // Remove empty symbol entries
                    filled.retain(|_, orders| !orders.is_empty());
                }

                // Clean up canceled orders older than 24 hours
                {
                    let mut canceled = canceled_orders.write().await;
                    // NOTE: canceled_timestamp is seconds since epoch (not milliseconds)
                    let cutoff_secs = (Utc::now() - ChronoDuration::hours(24)).timestamp() as u64;

                    for (symbol, orders) in canceled.iter_mut() {
                        let initial_len = orders.len();
                        // Keep orders newer than 24 hours (timestamp > cutoff means newer)
                        orders.retain(|order| order.canceled_timestamp > cutoff_secs);
                        let removed = initial_len.saturating_sub(orders.len());
                        canceled_removed += removed;

                        if removed > 0 {
                            log::debug!(
                                "🗑️ [AUTO_CLEANUP] Removed {} old canceled orders for {}",
                                removed,
                                symbol
                            );
                        }
                    }
                    // Remove empty symbol entries
                    canceled.retain(|_, orders| !orders.is_empty());
                }

                let total_removed = filled_removed + canceled_removed;
                if total_removed > 0 {
                    log::info!(
                        "🗑️ [AUTO_CLEANUP] removed total={} (filled={}, canceled={})",
                        total_removed,
                        filled_removed,
                        canceled_removed
                    );
                }
            }

            // Cleanup on exit: reset state for potential restart
            cleanup_started.store(false, Ordering::SeqCst);
            let mut guard = cleanup_handle.lock().await;
            *guard = None;
            log::info!("🛑 [AUTO_CLEANUP] task exited, ready for restart");
        });

        // Store the handle using async context
        let cleanup_handle_for_storage = Arc::clone(&self.cleanup_handle);
        tokio::spawn(async move {
            let mut guard = cleanup_handle_for_storage.lock().await;
            *guard = Some(handle);
        });
    }

    /// Initialize Go client (disabled when lighter-sdk feature is not enabled)
    #[cfg(not(feature = "lighter-sdk"))]
    async fn create_go_client(&self) -> Result<(), DexError> {
        Err(DexError::Other(
            "Lighter Go SDK not available. Build with --features lighter-sdk to enable."
                .to_string(),
        ))
    }

    /// Call Go shared library to generate signature for CreateOrder transaction
    #[cfg(feature = "lighter-sdk")]
    async fn call_go_sign_create_order(
        &self,
        market_index: i32,
        client_order_index: i64,
        base_amount: i64,
        price: i32,
        is_ask: i32,
        order_type: i32,
        time_in_force: i32,
        reduce_only: i32,
        trigger_price: i32,
        order_expiry: i64,
        nonce: i64,
    ) -> Result<String, DexError> {
        // First create the client
        self.create_go_client().await?;

        unsafe {
            let result = SignCreateOrder(
                market_index,
                client_order_index,
                base_amount,
                price,
                is_ask,
                order_type,
                time_in_force,
                reduce_only,
                trigger_price,
                order_expiry,
                nonce,
            );

            if !result.err.is_null() {
                let error_cstr = CStr::from_ptr(result.err);
                let error_msg = error_cstr.to_string_lossy().to_string();
                libc::free(result.err as *mut libc::c_void);
                if !result.str.is_null() {
                    libc::free(result.str as *mut libc::c_void);
                }
                return Err(DexError::Other(format!("Go SDK error: {}", error_msg)));
            }

            if result.str.is_null() {
                return Err(DexError::Other("Go SDK returned null result".to_string()));
            }

            let result_cstr = CStr::from_ptr(result.str);
            let json_str = result_cstr.to_string_lossy().to_string();
            libc::free(result.str as *mut libc::c_void);

            Ok(json_str)
        }
    }

    /// Call Go shared library to generate signature (disabled when lighter-sdk feature is not enabled)
    #[cfg(not(feature = "lighter-sdk"))]
    async fn call_go_sign_create_order(
        &self,
        _market_index: i32,
        _client_order_index: i64,
        _base_amount: i64,
        _price: i32,
        _is_ask: i32,
        _order_type: i32,
        _time_in_force: i32,
        _reduce_only: i32,
        _trigger_price: i32,
        _order_expiry: i64,
        _nonce: i64,
    ) -> Result<String, DexError> {
        Err(DexError::Other(
            "Lighter Go SDK not available. Build with --features lighter-sdk to enable."
                .to_string(),
        ))
    }

    /// Call Go shared library to sign a cancel order transaction
    #[cfg(feature = "lighter-sdk")]
    async fn call_go_sign_cancel_order(
        &self,
        market_index: i32,
        order_index: i64,
        nonce: i64,
    ) -> Result<String, DexError> {
        self.create_go_client().await?;

        unsafe {
            let result = SignCancelOrder(market_index, order_index, nonce);

            if !result.err.is_null() {
                let error_cstr = CStr::from_ptr(result.err);
                let error_msg = error_cstr.to_string_lossy().to_string();
                libc::free(result.err as *mut libc::c_void);
                if !result.str.is_null() {
                    libc::free(result.str as *mut libc::c_void);
                }
                return Err(DexError::Other(format!("Go SDK error: {}", error_msg)));
            }

            if result.str.is_null() {
                return Err(DexError::Other(
                    "Go SDK returned null result for cancel order".to_string(),
                ));
            }

            let result_cstr = CStr::from_ptr(result.str);
            let json_str = result_cstr.to_string_lossy().to_string();
            libc::free(result.str as *mut libc::c_void);

            Ok(json_str)
        }
    }

    #[cfg(not(feature = "lighter-sdk"))]
    async fn call_go_sign_cancel_order(
        &self,
        _market_index: i32,
        _order_index: i64,
        _nonce: i64,
    ) -> Result<String, DexError> {
        Err(DexError::Other(
            "Lighter Go SDK not available. Build with --features lighter-sdk to enable."
                .to_string(),
        ))
    }

    #[cfg(feature = "lighter-sdk")]
    pub fn new(
        api_key_public: String,
        api_key_index: u32,
        api_private_key_hex: String,
        evm_wallet_private_key: Option<String>,
        account_index: u32,
        base_url: String,
        websocket_url: String,
        tracked_symbols: Vec<String>,
    ) -> Result<Self, DexError> {
        // For backward compatibility, derive L1 address for logging if possible
        let l1_address = "N/A".to_string(); // We don't need wallet address anymore

        log::debug!(
            "Creating LighterConnector with API key index: {}, account: {}",
            api_key_index,
            account_index
        );

        Ok(Self {
            api_key_public,
            api_key_index,
            api_private_key_hex,
            evm_wallet_private_key,
            account_index,
            base_url: base_url.clone(),
            websocket_url: websocket_url.clone(),
            _l1_address: l1_address,
            client: Client::new(),
            filled_orders: Arc::new(RwLock::new(HashMap::new())),
            canceled_orders: Arc::new(RwLock::new(HashMap::new())),
            cached_server_pubkey: Arc::new(tokio::sync::RwLock::new(None)),
            is_running: Arc::new(AtomicBool::new(false)),
            // Auto-cleanup management
            cleanup_started: Arc::new(AtomicBool::new(false)),
            cleanup_handle: Arc::new(tokio::sync::Mutex::new(None)),
            _ws: Some(DexWebSocket::new(websocket_url)),
            current_price: Arc::new(RwLock::new(None)),
            current_volume: Arc::new(RwLock::new(None)),
            order_book: Arc::new(RwLock::new(None)),
            maintenance: Arc::new(RwLock::new(MaintenanceInfo { next_start: None })),
            // WebSocket-based order tracking (no API calls)
            cached_open_orders: Arc::new(RwLock::new(HashMap::new())),
            // Connection epoch counter for race detection
            connection_epoch: Arc::new(AtomicU64::new(0)),
            market_cache: Arc::new(RwLock::new(MarketCache::default())),
            tracked_symbols,
        })
    }

    #[cfg(not(feature = "lighter-sdk"))]
    pub fn new(
        api_key_public: String,
        api_key_index: u32,
        api_private_key_hex: String,
        _evm_wallet_private_key: Option<String>,
        account_index: u32,
        base_url: String,
        websocket_url: String,
        tracked_symbols: Vec<String>,
    ) -> Result<Self, DexError> {
        // For backward compatibility, derive L1 address for logging if possible
        let l1_address = "N/A".to_string(); // We don't need wallet address anymore

        log::debug!(
            "Creating LighterConnector with API key index: {}, account: {}",
            api_key_index,
            account_index
        );

        Ok(Self {
            api_key_public,
            api_key_index,
            api_private_key_hex,
            account_index,
            base_url: base_url.clone(),
            websocket_url: websocket_url.clone(),
            _l1_address: l1_address,
            client: Client::new(),
            filled_orders: Arc::new(RwLock::new(HashMap::new())),
            canceled_orders: Arc::new(RwLock::new(HashMap::new())),
            cached_server_pubkey: Arc::new(tokio::sync::RwLock::new(None)),
            is_running: Arc::new(AtomicBool::new(false)),
            // Auto-cleanup management
            cleanup_started: Arc::new(AtomicBool::new(false)),
            cleanup_handle: Arc::new(tokio::sync::Mutex::new(None)),
            _ws: Some(DexWebSocket::new(websocket_url)),
            current_price: Arc::new(RwLock::new(None)),
            current_volume: Arc::new(RwLock::new(None)),
            order_book: Arc::new(RwLock::new(None)),
            maintenance: Arc::new(RwLock::new(MaintenanceInfo { next_start: None })),
            // WebSocket-based order tracking (no API calls)
            cached_open_orders: Arc::new(RwLock::new(HashMap::new())),
            // Connection epoch counter for race detection
            connection_epoch: Arc::new(AtomicU64::new(0)),
            market_cache: Arc::new(RwLock::new(MarketCache::default())),
            tracked_symbols,
        })
    }

    /// Get server public key with caching to reduce API calls
    async fn get_server_public_key_cached(&self) -> Result<String, DexError> {
        // Check cache first (valid for 5 minutes)
        {
            let cache = self.cached_server_pubkey.read().await;
            if let Some((pubkey, timestamp)) = &*cache {
                if timestamp.elapsed() < std::time::Duration::from_secs(300) {
                    log::debug!("[API_CACHE] Using cached server public key, no API call needed");
                    return Ok(pubkey.clone());
                }
            }
        }

        // Cache miss or expired - fetch from API
        let endpoint = format!(
            "/api/v1/apikeys?account_index={}&api_key_index={}",
            self.account_index, self.api_key_index
        );
        log::debug!("Getting server public key from: {}", endpoint);
        let response: ApiKeyResponse = self
            .make_request(&endpoint, crate::dex_request::HttpMethod::Get, None)
            .await?;

        if response.api_keys.is_empty() {
            return Err(DexError::Other("No API keys found on server".to_string()));
        }

        let server_pubkey = response.api_keys[0].public_key.clone();

        // Update cache
        {
            let mut cache = self.cached_server_pubkey.write().await;
            *cache = Some((server_pubkey.clone(), std::time::Instant::now()));
        }

        Ok(server_pubkey)
    }

    async fn create_order_native_with_type(
        &self,
        market_id: u32,
        side: u32,
        tif: u32,
        base_amount: u64,
        price: u64,
        client_order_id: Option<String>,
        order_type: u32,
        reduce_only: bool,
        expiry_secs: Option<u64>,
    ) -> Result<CreateOrderResponse, DexError> {
        let timestamp = chrono::Utc::now().timestamp_millis() as u64;
        let _client_id = client_order_id.unwrap_or_else(|| format!("rust-native-{}", timestamp));
        let nonce = self.get_nonce().await?;

        let (price_scale, size_scale, price_decimals, size_decimals) = {
            let cache = self.market_cache.read().await;
            if let Some(info) = cache.by_id.get(&market_id) {
                (
                    Self::ten_pow(info.price_decimals),
                    Self::ten_pow(info.size_decimals),
                    info.price_decimals.min(MAX_DECIMAL_PRECISION),
                    info.size_decimals.min(MAX_DECIMAL_PRECISION),
                )
            } else {
                (
                    Self::ten_pow(DEFAULT_PRICE_DECIMALS),
                    Self::ten_pow(DEFAULT_SIZE_DECIMALS),
                    DEFAULT_PRICE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                    DEFAULT_SIZE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                )
            }
        };

        let approx_price = if price_scale > 0 {
            price as f64 / price_scale as f64
        } else {
            price as f64
        };

        let approx_size = if size_scale > 0 {
            base_amount as f64 / size_scale as f64
        } else {
            base_amount as f64
        };

        log::debug!(
            "Creating native order: market_id={}, side={}, base_amount={}, price={}, approx_price={}, approx_size={}, price_decimals={}, size_decimals={}",
            market_id,
            side,
            base_amount,
            price,
            approx_price,
            approx_size,
            price_decimals,
            size_decimals
        );

        // Use timestamp as unique client_order_index instead of hardcoded value
        let client_order_index = timestamp; // Use unique timestamp for each order
        let order_type_param = order_type as u64; // Use passed order type
        let time_in_force = tif as u64; // Use passed time in force
        let reduce_only_param = if reduce_only { 1u64 } else { 0u64 };
        let trigger_price = 0u64; // no trigger
                                  // For market or immediate TIF orders, use 0 (NilOrderExpiry). For GTC orders, use future timestamp
        let is_immediate_tif = time_in_force == u64::from(TIF_IOC);
        let order_expiry = if order_type == ORDER_TYPE_IOC || is_immediate_tif {
            0i64 // NilOrderExpiry for immediate-or-cancel / fill-or-kill orders
        } else {
            // For GTC limit orders, use passed expiry_secs or default to 24 hours
            let expiry_duration_ms = if let Some(expiry_secs) = expiry_secs {
                expiry_secs * 1000 // Convert seconds to milliseconds
            } else {
                24 * 60 * 60 * 1000 // Default 24 hours in milliseconds
            };

            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_millis() as i64;
            now_ms + (expiry_duration_ms as i64)
        };

        // Use actual parameters passed to function instead of hardcoded test values
        let actual_market_id = market_id as u64;
        let actual_base_amount = base_amount;
        let actual_price = price;
        let actual_side = side as u64;

        let _tx_data = [
            actual_market_id,    // market_index - actual parameter
            client_order_index,  // client_order_index
            actual_base_amount,  // base_amount - actual parameter
            actual_price,        // price - actual parameter
            actual_side,         // is_ask - actual parameter
            order_type_param,    // order_type
            time_in_force,       // time_in_force
            reduce_only_param,   // reduce_only
            trigger_price,       // trigger_price
            order_expiry as u64, // order_expiry
            nonce,               // nonce - use actual API nonce
        ];

        // Extract private key bytes (40 bytes for Goldilocks quintic extension)
        let private_key_hex = self
            .api_private_key_hex
            .strip_prefix("0x")
            .unwrap_or(&self.api_private_key_hex);
        let private_key_bytes = hex::decode(private_key_hex)
            .map_err(|e| DexError::Other(format!("Invalid private key hex: {}", e)))?;

        // Lighter uses 40-byte private keys for Goldilocks quintic extension
        let mut key_bytes = [0u8; 40];
        let copy_len = std::cmp::min(private_key_bytes.len(), 40);
        key_bytes[..copy_len].copy_from_slice(&private_key_bytes[..copy_len]);

        // Call Go shared library to generate signature dynamically
        let go_result = self
            .call_go_sign_create_order(
                actual_market_id as i32,
                client_order_index as i64,
                actual_base_amount as i64,
                actual_price as i32,
                actual_side as i32,
                order_type_param as i32,
                time_in_force as i32,
                reduce_only_param as i32,
                trigger_price as i32,
                order_expiry as i64,
                nonce as i64,
            )
            .await?;

        log::debug!("=== GO SDK RESULT ===");
        log::debug!("Go SDK JSON: {}", go_result);

        // Use the exact JSON from Go SDK - it already contains everything correctly

        // Use the complete transaction JSON from Go SDK directly
        let tx_info = go_result;

        // Send to Lighter API using application/x-www-form-urlencoded format (same as Go SDK)
        let form_data = format!(
            "tx_type=14&tx_info={}&price_protection=false",
            urlencoding::encode(&tx_info)
        );

        log::debug!("=== REQUEST DEBUG ===");
        log::debug!("Timestamp: {}", timestamp);
        log::debug!("TX Info JSON: {}", tx_info);
        log::debug!("Form data: {}", form_data);

        track_api_call("POST /api/v1/sendTx", "POST");

        // Use form-urlencoded format same as Go SDK, without X-API-KEY header
        let response = self
            .client
            .post(&format!("{}/api/v1/sendTx", self.base_url))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(form_data)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("HTTP request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        log::debug!(
            "Native order response: HTTP {}, Body: {}",
            status,
            response_text
        );

        if status.is_success() {
            log::debug!("Native order submitted successfully!");
            // Use client_order_index as order_id for tracking
            let order_id = client_order_index.to_string();

            log::debug!(
                "Created order: order_id={}, client_order_index={}, side={}, size={}",
                order_id,
                client_order_index,
                side,
                i64::try_from(base_amount)
                    .ok()
                    .map(|b| Decimal::new(b, size_decimals))
                    .unwrap_or_else(|| Decimal::ZERO)
            );

            Ok(CreateOrderResponse {
                order_id,
                ordered_price: i64::try_from(price)
                    .ok()
                    .map(|p| Decimal::new(p, price_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
                ordered_size: i64::try_from(base_amount)
                    .ok()
                    .map(|b| Decimal::new(b, size_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
            })
        } else {
            Err(DexError::Other(format!(
                "Order failed: HTTP {}, {}",
                status, response_text
            )))
        }
    }

    async fn create_order_native_with_trigger(
        &self,
        market_id: u32,
        side: u32,
        tif: u32,
        base_amount: u64,
        price: u64,
        trigger_price: u64,
        client_order_id: Option<String>,
        order_type: u32,
        reduce_only: bool,
        expiry_secs: Option<u64>,
    ) -> Result<CreateOrderResponse, DexError> {
        let timestamp = chrono::Utc::now().timestamp_millis() as u64;
        let _client_id = client_order_id.unwrap_or_else(|| format!("rust-trigger-{}", timestamp));
        let nonce = self.get_nonce().await?;

        let (price_scale, size_scale, price_decimals, size_decimals) = {
            let cache = self.market_cache.read().await;
            if let Some(info) = cache.by_id.get(&market_id) {
                (
                    Self::ten_pow(info.price_decimals),
                    Self::ten_pow(info.size_decimals),
                    info.price_decimals.min(MAX_DECIMAL_PRECISION),
                    info.size_decimals.min(MAX_DECIMAL_PRECISION),
                )
            } else {
                (
                    Self::ten_pow(DEFAULT_PRICE_DECIMALS),
                    Self::ten_pow(DEFAULT_SIZE_DECIMALS),
                    DEFAULT_PRICE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                    DEFAULT_SIZE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                )
            }
        };

        let approx_price = if price_scale > 0 {
            price as f64 / price_scale as f64
        } else {
            price as f64
        };
        let approx_trigger = if price_scale > 0 {
            trigger_price as f64 / price_scale as f64
        } else {
            trigger_price as f64
        };
        let approx_size = if size_scale > 0 {
            base_amount as f64 / size_scale as f64
        } else {
            base_amount as f64
        };

        log::debug!(
            "Creating trigger order: market_id={}, side={}, base_amount={}, price={}, trigger_price={}, order_type={}, approx_price={}, approx_trigger={}, approx_size={}",
            market_id,
            side,
            base_amount,
            price,
            trigger_price,
            order_type,
            approx_price,
            approx_trigger,
            approx_size
        );

        let client_order_index = timestamp;
        let order_type_param = order_type as u64;
        let time_in_force = tif as u64;
        let reduce_only_param = if reduce_only { 1u64 } else { 0u64 };
        let trigger_price_param = trigger_price;

        // For trigger orders, use passed expiry_secs or default to 28 days
        let order_expiry = if order_type == ORDER_TYPE_TRIGGER
            || order_type == 4
            || order_type == 3
            || order_type == 5
        {
            // Use passed expiry_secs or default to 28 days for trigger orders
            let expiry_duration_ms = if let Some(expiry_secs) = expiry_secs {
                // Minimum 60 seconds for trigger orders as Go SDK requires MinOrderExpiry >= 1
                let min_expiry_secs = 60;
                std::cmp::max(min_expiry_secs, expiry_secs) * 1000
            } else {
                28 * 24 * 60 * 60 * 1000 // Default 28 days in milliseconds
            };
            (chrono::Utc::now().timestamp_millis() as u64 + expiry_duration_ms) as i64
        } else {
            // For regular orders, use passed expiry_secs or default
            let expiry_duration_ms = if let Some(expiry_secs) = expiry_secs {
                expiry_secs * 1000
            } else {
                24 * 60 * 60 * 1000 // Default 24 hours in milliseconds
            };
            (chrono::Utc::now().timestamp_millis() as u64 + expiry_duration_ms) as i64
        };

        let actual_market_id = market_id as u64;
        let actual_base_amount = base_amount;
        let actual_price = price;
        let actual_side = side as u64;

        // Extract private key bytes
        let private_key_hex = self
            .api_private_key_hex
            .strip_prefix("0x")
            .unwrap_or(&self.api_private_key_hex);
        let private_key_bytes = hex::decode(private_key_hex)
            .map_err(|e| DexError::Other(format!("Invalid private key hex: {}", e)))?;

        let mut key_bytes = [0u8; 40];
        let copy_len = std::cmp::min(private_key_bytes.len(), 40);
        key_bytes[..copy_len].copy_from_slice(&private_key_bytes[..copy_len]);

        // Call Go shared library for trigger order signature
        let go_result = self
            .call_go_sign_create_order(
                actual_market_id as i32,
                client_order_index as i64,
                actual_base_amount as i64,
                actual_price as i32,
                actual_side as i32,
                order_type_param as i32,
                time_in_force as i32,
                reduce_only_param as i32,
                trigger_price_param as i32,
                order_expiry,
                nonce as i64,
            )
            .await;

        let signature = match go_result {
            Ok(sig) => sig,
            Err(e) => {
                log::error!("Failed to sign trigger order via Go SDK: {}", e);
                return Err(DexError::Other(format!(
                    "Signature generation failed: {}",
                    e
                )));
            }
        };

        // Use same form-urlencoded format as regular orders
        let form_data = format!(
            "tx_type=14&tx_info={}&price_protection=false",
            urlencoding::encode(&signature)
        );

        log::debug!("Trigger order form data: {}", form_data);

        let client = &self.client;
        let url = format!("{}/api/v1/sendTx", self.base_url);

        let response = client
            .post(&url)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(form_data)
            .send()
            .await
            .map_err(|e| DexError::Other(e.to_string()))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(e.to_string()))?;

        log::debug!("Trigger order response: HTTP {}, {}", status, response_text);

        if status.is_success() {
            let order_id = format!("trigger-{}-{}", timestamp, market_id);
            log::info!(
                "✅ [TRIGGER_ORDER] Successfully created trigger order: {} (type={}, trigger_price={})",
                order_id,
                order_type,
                trigger_price_param
            );

            Ok(CreateOrderResponse {
                order_id,
                ordered_price: i64::try_from(price)
                    .ok()
                    .map(|p| Decimal::new(p, price_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
                ordered_size: i64::try_from(base_amount)
                    .ok()
                    .map(|b| Decimal::new(b, size_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
            })
        } else {
            Err(DexError::Other(format!(
                "Trigger order failed: HTTP {}, {}",
                status, response_text
            )))
        }
    }

    #[allow(dead_code)]
    async fn send_order_via_sdk(
        &self,
        market_id: u32,
        side: u32,
        tif: u32,
        base_amount: u64,
        price: u64,
        client_order_id: Option<String>,
    ) -> Result<CreateOrderResponse, DexError> {
        let timestamp = chrono::Utc::now().timestamp_millis() as u64;
        let client_id = client_order_id.unwrap_or_else(|| format!("rust-order-{}", timestamp));

        let (price_decimals, size_decimals) = {
            let cache = self.market_cache.read().await;
            if let Some(info) = cache.by_id.get(&market_id) {
                (
                    info.price_decimals.min(MAX_DECIMAL_PRECISION),
                    info.size_decimals.min(MAX_DECIMAL_PRECISION),
                )
            } else {
                (
                    DEFAULT_PRICE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                    DEFAULT_SIZE_DECIMALS.min(MAX_DECIMAL_PRECISION),
                )
            }
        };
        let price_scale = Self::ten_pow(price_decimals);
        let size_scale = Self::ten_pow(size_decimals);

        let approx_price = if price_scale > 0 {
            price as f64 / price_scale as f64
        } else {
            price as f64
        };
        let approx_size = if size_scale > 0 {
            base_amount as f64 / size_scale as f64
        } else {
            base_amount as f64
        };

        log::debug!(
            "Delegating order to Python SDK: market_id={}, side={}, base_amount={}, price={}, approx_price={}, approx_size={}",
            market_id,
            side,
            base_amount,
            price,
            approx_price,
            approx_size
        );

        let output = std::process::Command::new("./venv/bin/python")
            .arg("sdk_send_order.py")
            .arg(&format!("--market-id={}", market_id))
            .arg(&format!("--side={}", side))
            .arg(&format!("--tif={}", tif))
            .arg(&format!("--base-amt={}", base_amount))
            .arg(&format!("--price={}", price))
            .arg(&format!("--client-id={}", client_id))
            .env("LIGHTER_ACCOUNT_INDEX", &self.account_index.to_string())
            .env("LIGHTER_API_KEY_INDEX", &self.api_key_index.to_string())
            .env("LIGHTER_PRIVATE_API_KEY", &self.api_private_key_hex)
            .current_dir(".")
            .output()
            .map_err(|e| DexError::Other(format!("Failed to execute SDK script: {}", e)))?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        if !output.status.success() {
            log::error!("SDK delegation failed. stderr: {}", stderr);
            return Err(DexError::Other(format!("SDK execution failed: {}", stderr)));
        }

        if !stderr.is_empty() {
            log::warn!("SDK delegation warnings: {}", stderr);
        }

        // Parse JSON response
        let response: serde_json::Value = serde_json::from_str(&stdout)
            .map_err(|e| DexError::Other(format!("Failed to parse SDK response: {}", e)))?;

        if let Some(true) = response.get("success").and_then(|v| v.as_bool()) {
            log::debug!("Order successfully sent via SDK");

            let order_id = response
                .get("tx_hash")
                .and_then(|v| v.as_str())
                .unwrap_or(&client_id)
                .to_string();

            Ok(CreateOrderResponse {
                order_id,
                ordered_price: i64::try_from(price)
                    .ok()
                    .map(|p| Decimal::new(p, price_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
                ordered_size: i64::try_from(base_amount)
                    .ok()
                    .map(|b| Decimal::new(b, size_decimals))
                    .unwrap_or_else(|| Decimal::ZERO),
            })
        } else if let Some(error) = response.get("error") {
            log::error!("SDK order failed: {}", error);
            Err(DexError::Other(format!("SDK order error: {}", error)))
        } else {
            Err(DexError::Other(
                "Unexpected SDK response format".to_string(),
            ))
        }
    }

    #[allow(dead_code)]
    async fn get_nonce(&self) -> Result<u64, DexError> {
        self.get_nonce_with_key(&self.api_key_public).await
    }

    async fn get_nonce_with_key(&self, api_key: &str) -> Result<u64, DexError> {
        let url = format!(
            "{}/api/v1/nextNonce?account_index={}&api_key_index={}",
            self.base_url, self.account_index, self.api_key_index
        );

        log::debug!("Getting nonce from: {}", url);
        log::debug!("Using API key: {}", api_key);

        // Track API call
        track_api_call("/api/v1/nextNonce", "GET");

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", api_key)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Failed to get nonce: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let error_body = response
                .text()
                .await
                .unwrap_or_else(|_| "Failed to read error response".to_string());
            log::error!(
                "Nonce request failed: HTTP {}, Body: {}",
                status,
                error_body
            );
            return Err(DexError::Other(format!(
                "Failed to get nonce: HTTP {}, Body: {}",
                status, error_body
            )));
        }

        let nonce_response: LighterNonceResponse = response
            .json()
            .await
            .map_err(|e| DexError::Other(format!("Failed to parse nonce response: {}", e)))?;

        Ok(nonce_response.nonce)
    }

    #[allow(dead_code)]
    async fn discover_account_index(&self) -> Result<u32, DexError> {
        // For now, just return the configured account_index
        // In production, this could query the API to find the correct index
        Ok(self.account_index)
    }

    async fn get_server_public_key(&self) -> Result<String, DexError> {
        // Use cached version to reduce API calls
        self.get_server_public_key_cached().await
    }

    async fn make_request<T>(
        &self,
        endpoint: &str,
        method: HttpMethod,
        body: Option<&str>,
    ) -> Result<T, DexError>
    where
        T: for<'de> serde::Deserialize<'de>,
    {
        // Track API call
        let method_str = match method {
            HttpMethod::Get => "GET",
            HttpMethod::Post => "POST",
            HttpMethod::Put => "PUT",
            HttpMethod::Delete => "DELETE",
        };
        track_api_call(endpoint, method_str);

        let url = format!("{}{}", self.base_url, endpoint);

        let mut request = match method {
            HttpMethod::Get => self.client.get(&url),
            HttpMethod::Post => self.client.post(&url),
            HttpMethod::Put => self.client.put(&url),
            HttpMethod::Delete => self.client.delete(&url),
        };

        request = request.header("X-API-KEY", &self.api_key_public);

        if let Some(body_content) = body {
            request = request
                .header("Content-Type", "application/json")
                .body(body_content.to_string());
        }

        let response = request
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        if !status.is_success() {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            return Err(DexError::Other(format!("HTTP {}: {}", status, error_text)));
        }

        response
            .json()
            .await
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))
    }

    #[cfg(feature = "lighter-sdk")]
    async fn register_api_key(
        &self,
        evm_private_key: &str,
        go_public_key: &str,
        server_public_key: &str,
    ) -> Result<(), String> {
        log::debug!(
            "Attempting ChangePubKey: server='{}' -> local='{}'",
            server_public_key,
            go_public_key
        );

        // Get next nonce using server-registered public key (not our new key)
        let nonce = self
            .get_nonce_with_key(server_public_key)
            .await
            .map_err(|e| format!("Failed to get nonce: {:?}", e))?;
        log::debug!("Got nonce for ChangePubKey: {}", nonce);

        // Use the Go-derived public key
        let new_pubkey = if go_public_key.starts_with("0x") {
            go_public_key.to_string()
        } else {
            format!("0x{}", go_public_key)
        };
        log::debug!("New public key to register: {}", new_pubkey);

        // Use SignChangePubKey from the lighter-go library
        let sign_result = unsafe {
            SignChangePubKey(
                std::ffi::CString::new(new_pubkey.clone()).unwrap().as_ptr(),
                nonce as c_longlong,
            )
        };

        // Check if signing was successful
        if !sign_result.err.is_null() {
            let error_msg = unsafe { std::ffi::CStr::from_ptr(sign_result.err).to_string_lossy() };
            return Err(format!("Failed to sign ChangePubKey: {}", error_msg));
        }

        let tx_info_str = unsafe { std::ffi::CStr::from_ptr(sign_result.str).to_string_lossy() };
        log::debug!("SignChangePubKey result: {}", tx_info_str);

        // Parse the tx_info JSON and extract MessageToSign
        let mut tx_info: serde_json::Value = serde_json::from_str(&tx_info_str)
            .map_err(|e| format!("Failed to parse tx_info: {}", e))?;

        let message_to_sign = tx_info["MessageToSign"]
            .as_str()
            .ok_or("MessageToSign not found in tx_info")?
            .to_string();
        log::debug!("MessageToSign: {}", message_to_sign);

        // Remove MessageToSign from tx_info as per Python SDK implementation
        tx_info.as_object_mut().unwrap().remove("MessageToSign");

        // Sign the message with EVM key using lighter-go SignMessageWithEVM
        let evm_signature =
            self.sign_message_with_lighter_go_evm(evm_private_key, &message_to_sign)?;
        log::debug!("EVM signature: {}", evm_signature);

        // Compare expected vs actual L1 address for debugging
        if let Ok(recovered_addr) =
            self.recover_address_from_signature(&message_to_sign, &evm_signature)
        {
            if let Ok(expected_addr) = self.get_account_l1_address().await {
                log::debug!("L1 Address Comparison:");
                log::debug!(
                    "  Expected (account {}): {}",
                    self.account_index,
                    expected_addr
                );
                log::debug!("  Recovered from EVM sig: {}", recovered_addr);
                if expected_addr.to_lowercase() == recovered_addr.to_lowercase() {
                    log::debug!("  ✓ Addresses match - signature should be valid");
                } else {
                    log::error!("  ✗ Addresses MISMATCH - signature will fail validation");
                    log::error!("  This explains the L1 signature failure (code 21504)");
                }
            } else {
                log::warn!("Could not retrieve expected L1 address for comparison");
            }
        }

        // Add L1Sig field with the EVM signature (Python SDK uses L1Sig, not evmSignature)
        tx_info["L1Sig"] = serde_json::Value::String(evm_signature);

        // Send the ChangePubKey request
        let response = self.send_change_api_key_request(&tx_info.to_string()).await;

        match response {
            Ok(_v) => {
                let srv_short = &server_public_key[..8];
                let srv_end = &server_public_key[server_public_key.len() - 8..];
                let new_short = &new_pubkey.trim_start_matches("0x")[..8];
                let new_end_start = new_pubkey.len().saturating_sub(10); // account for "0x"
                let new_end = &new_pubkey[new_end_start..];

                log::debug!(
                    "ChangePubKey succeeded (account={}, index={}). Server public key updated from {}…{} to {}…{}",
                    self.account_index,
                    self.api_key_index,
                    srv_short, srv_end,
                    new_short, new_end
                );
                Ok(())
            }
            Err(e) => {
                let srv_short = &server_public_key[..8];
                let srv_end = &server_public_key[server_public_key.len() - 8..];

                log::error!(
                    "ChangePubKey failed (account={}, index={}) -> {}. Server key remains {}…{}",
                    self.account_index,
                    self.api_key_index,
                    e,
                    srv_short,
                    srv_end
                );
                Err(e)
            }
        }
    }

    #[cfg(not(feature = "lighter-sdk"))]
    async fn register_api_key(
        &self,
        _evm_private_key: &str,
        _go_public_key: &str,
        _server_public_key: &str,
    ) -> Result<(), String> {
        Err("API key registration requires lighter-sdk feature".to_string())
    }

    #[cfg(feature = "lighter-sdk")]
    fn sign_message_with_lighter_go_evm(
        &self,
        evm_private_key: &str,
        message: &str,
    ) -> Result<String, String> {
        log::debug!("Using lighter-go SignMessageWithEVM for EVM signature");

        let private_key_cstr = std::ffi::CString::new(evm_private_key)
            .map_err(|e| format!("Failed to create CString for private key: {}", e))?;
        let message_cstr = std::ffi::CString::new(message)
            .map_err(|e| format!("Failed to create CString for message: {}", e))?;

        let sign_result =
            unsafe { SignMessageWithEVM(private_key_cstr.as_ptr(), message_cstr.as_ptr()) };

        if !sign_result.err.is_null() {
            let error_msg = unsafe { std::ffi::CStr::from_ptr(sign_result.err).to_string_lossy() };
            return Err(format!("EVM signature failed: {}", error_msg));
        }

        let signature = unsafe { std::ffi::CStr::from_ptr(sign_result.str).to_string_lossy() };

        // Ensure 0x prefix is present (Lighter expects 0x-prefixed signatures)
        let signature_with_prefix = if signature.starts_with("0x") {
            signature.to_string()
        } else {
            format!("0x{}", signature)
        };

        // Check if v value needs to be adjusted from {0,1} to {27,28}
        if signature_with_prefix.len() == 132 {
            // "0x" + 130 hex chars = 132
            let mut sig_bytes = hex::decode(&signature_with_prefix[2..])
                .map_err(|e| format!("Failed to decode signature hex: {}", e))?;

            if sig_bytes.len() == 65 {
                // Check if v is 0 or 1, and convert to 27 or 28
                if sig_bytes[64] == 0 {
                    log::debug!("Converting v from 0 to 27");
                    sig_bytes[64] = 27;
                } else if sig_bytes[64] == 1 {
                    log::debug!("Converting v from 1 to 28");
                    sig_bytes[64] = 28;
                }

                let corrected_signature = format!("0x{}", hex::encode(sig_bytes));
                log::debug!("EVM signature v-corrected: {}", corrected_signature);

                // Log recovered address for debugging
                if let Ok(recovered_addr) =
                    self.recover_address_from_signature(message, &corrected_signature)
                {
                    log::debug!("EVM signature recovery check - Address: {}", recovered_addr);
                } else {
                    log::warn!("Failed to recover address from EVM signature for verification");
                }

                return Ok(corrected_signature);
            }
        }

        Ok(signature_with_prefix)
    }

    #[cfg(not(feature = "lighter-sdk"))]
    fn sign_message_with_lighter_go_evm(
        &self,
        _evm_private_key: &str,
        _message: &str,
    ) -> Result<String, String> {
        Err("EVM signing with lighter-go requires lighter-sdk feature".to_string())
    }

    /// Get account details to find the L1 address for this account
    async fn get_account_l1_address(&self) -> Result<String, DexError> {
        let url = format!(
            "{}/api/v1/account?account_index={}",
            self.base_url, self.account_index
        );
        log::debug!("Getting account details from: {}", url);

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Failed to get account details: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        log::debug!(
            "Account details response: HTTP {}, Body: {}",
            status,
            response_text
        );

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        // Parse the response to extract L1 address
        let account_data: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse account response: {}", e)))?;

        // Look for l1Address field
        if let Some(l1_address) = account_data.get("l1Address").and_then(|v| v.as_str()) {
            Ok(l1_address.to_string())
        } else {
            Err(DexError::Other(
                "l1Address not found in account response".to_string(),
            ))
        }
    }

    /// Recover the EVM address from a signature for debugging purposes
    fn recover_address_from_signature(
        &self,
        message: &str,
        signature: &str,
    ) -> Result<String, String> {
        // Remove 0x prefix if present
        let signature_hex = signature.strip_prefix("0x").unwrap_or(signature);

        // Decode the signature
        let signature_bytes = hex::decode(signature_hex)
            .map_err(|e| format!("Failed to decode signature hex: {}", e))?;

        if signature_bytes.len() != 65 {
            return Err(format!(
                "Invalid signature length: {} (expected 65)",
                signature_bytes.len()
            ));
        }

        // Split signature into r, s, v components
        let _r = &signature_bytes[0..32];
        let _s = &signature_bytes[32..64];
        let v = signature_bytes[64];

        // Convert v to recovery id (0 or 1)
        let recovery_id = match v {
            27 => 0,
            28 => 1,
            0 | 1 => v, // Already in correct format
            _ => return Err(format!("Invalid v value: {}", v)),
        };

        // Create the message hash (EIP-191 personal_sign format)
        let prefix = format!("\x19Ethereum Signed Message:\n{}", message.len());
        let mut hasher = Keccak256::new();
        hasher.update(prefix.as_bytes());
        hasher.update(message.as_bytes());
        let message_hash = hasher.finalize();

        // Create secp256k1 objects
        let secp = Secp256k1::new();
        let message_obj = Message::from_digest_slice(&message_hash)
            .map_err(|e| format!("Invalid message hash: {}", e))?;

        // Create recoverable signature
        let recoverable_sig = secp256k1::ecdsa::RecoverableSignature::from_compact(
            &signature_bytes[0..64],
            secp256k1::ecdsa::RecoveryId::from_i32(recovery_id as i32)
                .map_err(|e| format!("Invalid recovery id: {}", e))?,
        )
        .map_err(|e| format!("Failed to create recoverable signature: {}", e))?;

        // Recover the public key
        let public_key = secp
            .recover_ecdsa(&message_obj, &recoverable_sig)
            .map_err(|e| format!("Failed to recover public key: {}", e))?;

        // Convert public key to address
        let public_key_bytes = public_key.serialize_uncompressed();
        let mut hasher = Keccak256::new();
        hasher.update(&public_key_bytes[1..]); // Skip the 0x04 prefix
        let hash = hasher.finalize();

        // Take the last 20 bytes and format as address
        let address = format!("0x{}", hex::encode(&hash[12..]));

        Ok(address)
    }

    fn _unused_sign_with_evm_key(
        &self,
        evm_private_key: &str,
        message: &str,
    ) -> Result<String, String> {
        // Parse the private key - try base64 first, then hex
        let private_key_bytes = if evm_private_key.contains("=")
            || evm_private_key.contains("+")
            || evm_private_key.contains("/")
        {
            // Looks like base64
            use base64::Engine;
            base64::engine::general_purpose::STANDARD
                .decode(evm_private_key)
                .map_err(|e| format!("Failed to decode private key base64: {}", e))?
        } else {
            // Try hex format
            let private_key_hex = if evm_private_key.starts_with("0x") {
                &evm_private_key[2..]
            } else {
                evm_private_key
            };

            hex::decode(private_key_hex)
                .map_err(|e| format!("Failed to decode private key hex: {}", e))?
        };

        if private_key_bytes.len() != 32 {
            return Err("Private key must be 32 bytes".to_string());
        }

        let secret_key = SecretKey::from_slice(&private_key_bytes)
            .map_err(|e| format!("Failed to create secret key: {}", e))?;

        // Create EIP-191 prefixed message hash
        let prefix = format!("\x19Ethereum Signed Message:\n{}", message.len());
        let full_message = format!("{}{}", prefix, message);

        let mut hasher = Keccak256::new();
        hasher.update(full_message.as_bytes());
        let message_hash = hasher.finalize();

        // Sign the message
        let secp = Secp256k1::new();
        let message_obj = Message::from_digest_slice(&message_hash)
            .map_err(|e| format!("Failed to create message: {}", e))?;

        let signature = secp.sign_ecdsa_recoverable(&message_obj, &secret_key);
        let (recovery_id, compact_sig) = signature.serialize_compact();

        // Construct 65-byte signature: [r(32) | s(32) | v(1)]
        // For EVM signatures, v = recovery_id + 27
        let mut signature_bytes = [0u8; 65];
        signature_bytes[0..64].copy_from_slice(&compact_sig);
        signature_bytes[64] = (recovery_id.to_i32() + 27) as u8; // v = recovery_id + 27

        // Encode as hex
        Ok(hex::encode(signature_bytes))
    }

    async fn send_change_api_key_request(
        &self,
        tx_info: &str,
    ) -> Result<serde_json::Value, String> {
        let base_url = self.base_url.trim_end_matches('/');
        let url = format!("{}/api/v1/sendTx", base_url);

        let form_data = [
            ("tx_type", "8"), // TX_TYPE_CHANGE_PUB_KEY = 8 (correct value from Go SDK)
            ("tx_info", tx_info),
        ];

        log::debug!("Sending change API key request to: {}", url);
        log::debug!("Form data: {:?}", form_data);

        track_api_call("POST /api/v1/sendTx (change_api_key)", "POST");

        let response = self
            .client
            .post(&url)
            .form(&form_data)
            .send()
            .await
            .map_err(|e| format!("Failed to send request: {}", e))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;

        log::debug!(
            "Change API key response: HTTP {}, Body: {}",
            status,
            response_text
        );

        if !status.is_success() {
            return Err(format!("HTTP {}: {}", status, response_text));
        }

        serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response JSON: {}", e))
    }
}

#[async_trait]
impl DexConnector for LighterConnector {
    async fn start(&self) -> Result<(), DexError> {
        self.is_running.store(true, Ordering::SeqCst);
        log::debug!(
            "Lighter connector started with WebSocket: {}",
            self.websocket_url
        );

        // Initialize the Go client and validate API key
        #[cfg(feature = "lighter-sdk")]
        {
            match self.create_go_client().await {
                Ok(()) => {}
                Err(DexError::ApiKeyRegistrationRequired) => {
                    #[cfg(feature = "lighter-sdk")]
                    if let Some(evm_key) = &self.evm_wallet_private_key {
                        // Get Go-derived public key for registration
                        let go_pubkey_result = unsafe {
                            GetClientPubKey(
                                self.api_key_index as c_int,
                                self.account_index as c_longlong,
                            )
                        };

                        if !go_pubkey_result.is_null() {
                            let pubkey_cstr = unsafe { CStr::from_ptr(go_pubkey_result) };
                            let go_key = pubkey_cstr.to_string_lossy().to_string();
                            unsafe { libc::free(go_pubkey_result as *mut libc::c_void) };

                            log::debug!("API key registration required. Attempting to register...");

                            // Get server public key for ChangePubKey
                            let server_pubkey =
                                self.get_server_public_key().await.map_err(|e| {
                                    DexError::Other(format!(
                                        "Failed to get server public key: {}",
                                        e
                                    ))
                                })?;

                            self.register_api_key(evm_key, &go_key, &server_pubkey)
                                .await
                                .map_err(|e| {
                                    DexError::Other(format!("API key registration failed: {}", e))
                                })?;

                            // Retry validation after registration
                            self.create_go_client().await?;
                        } else {
                            log::error!("Failed to get Go-derived public key for registration");
                            return Err(DexError::Other(
                                "Cannot get Go-derived public key".to_string(),
                            ));
                        }
                    } else {
                        return Err(DexError::ApiKeyRegistrationRequired);
                    }

                    #[cfg(not(feature = "lighter-sdk"))]
                    return Err(DexError::ApiKeyRegistrationRequired);
                }
                Err(e) => return Err(e),
            }
        }

        // Start WebSocket connection
        self.start_websocket().await?;

        // Start auto-cleanup background task (every 6 hours)
        self.start_auto_cleanup(6);
        log::info!("🗑️ [AUTO_CLEANUP] Started background cleanup task (every 6 hours)");

        Ok(())
    }

    async fn stop(&self) -> Result<(), DexError> {
        self.is_running.store(false, Ordering::SeqCst);

        // Optionally abort cleanup task for immediate shutdown
        if let Some(handle) = self.cleanup_handle.lock().await.take() {
            handle.abort();
            self.cleanup_started.store(false, Ordering::SeqCst);
            log::debug!("🛑 [AUTO_CLEANUP] task forcibly aborted on stop");
        }

        log::debug!("Lighter connector stopped");
        Ok(())
    }

    async fn restart(&self, _max_retries: i32) -> Result<(), DexError> {
        self.stop().await?;
        sleep(Duration::from_secs(1)).await;
        self.start().await
    }

    async fn set_leverage(&self, _symbol: &str, _leverage: u32) -> Result<(), DexError> {
        log::warn!("Leverage setting not implemented for Lighter");
        Ok(())
    }

    async fn get_ticker(
        &self,
        symbol: &str,
        test_price: Option<Decimal>,
    ) -> Result<TickerResponse, DexError> {
        if let Some(price) = test_price {
            let min_tick = Self::calculate_min_tick(price, DEFAULT_PRICE_DECIMALS, false);
            return Ok(TickerResponse {
                symbol: symbol.to_string(),
                price,
                min_tick: Some(min_tick),
                min_order: None,
                volume: Some(Decimal::ZERO),
                num_trades: None,
                open_interest: None,
                funding_rate: None,
                oracle_price: None,
            });
        }

        let market_info = self.resolve_market_info(symbol).await?;
        let canonical_symbol = market_info.canonical_symbol.clone();

        // Get statistics data from API
        let stats_data = self.get_exchange_stats().await.ok();
        let funding_data = self.get_funding_rates().await.ok();

        // Try to get price from WebSocket first, but check if it's recent
        if let Some((ws_price, price_timestamp)) = *self.current_price.read().await {
            let current_time = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs();

            // Check if WebSocket price is stale (older than 30 seconds)
            let price_age = current_time.saturating_sub(price_timestamp);
            if price_age > 30 {
                log::warn!(
                    "WebSocket price is stale ({}s old), falling back to REST API",
                    price_age
                );
                // Fall through to REST API fallback below
            } else {
                let min_tick =
                    Self::calculate_min_tick(ws_price, market_info.price_decimals, false);

                let (volume, num_trades) = if let Some(stats) = &stats_data {
                    if let Some(market_stats) = stats
                        .order_book_stats
                        .iter()
                        .find(|s| normalize_symbol(&s.symbol) == canonical_symbol)
                    {
                        (
                            Some(
                                Decimal::from_f64_retain(market_stats.daily_base_token_volume)
                                    .unwrap_or(Decimal::ZERO),
                            ),
                            Some(market_stats.daily_trades_count as u64),
                        )
                    } else {
                        (Some(Decimal::ZERO), None)
                    }
                } else {
                    (Some(Decimal::ZERO), None)
                };

                let funding_rate = if let Some(funding) = &funding_data {
                    funding
                        .funding_rates
                        .iter()
                        .find(|f| normalize_symbol(&f.symbol) == canonical_symbol)
                        .and_then(|f| Decimal::from_f64_retain(f.rate))
                } else {
                    None
                };

                log::trace!(
                    "Using WebSocket price with API stats: price={}, volume={:?}, trades={:?}",
                    ws_price,
                    volume,
                    num_trades
                );

                return Ok(TickerResponse {
                    symbol: symbol.to_string(),
                    price: ws_price,
                    min_tick: Some(min_tick),
                    min_order: None,
                    volume,
                    num_trades,
                    open_interest: None,
                    funding_rate,
                    oracle_price: None,
                });
            }
        }

        // Fallback to REST API if WebSocket data is not available
        log::warn!("WebSocket data not available, falling back to REST API");

        // Get market_id for the symbol
        let market_id = market_info.market_id;

        // Query recent trades to get current price and volume
        let endpoint = format!("/api/v1/recentTrades?market_id={}&limit=100", market_id);

        // Debug the raw response first
        let url = format!("{}{}", self.base_url, endpoint);
        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        log::debug!(
            "Trades API response (status: {}): {}",
            status,
            response_text
        );

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        let trades_response: LighterTradesResponse = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))?;

        let price = if let Some(trade) = trades_response.trades.first() {
            string_to_decimal(Some(trade.price.clone()))?
        } else {
            // Fallback to default if no trades found
            Decimal::new(50000, 0)
        };

        let min_tick = Self::calculate_min_tick(price, market_info.price_decimals, false);

        // Get funding rate
        let funding_rate = if let Some(funding) = &funding_data {
            funding
                .funding_rates
                .iter()
                .find(|f| normalize_symbol(&f.symbol) == canonical_symbol)
                .and_then(|f| Decimal::from_f64_retain(f.rate))
        } else {
            None
        };

        // Use stats data if available, otherwise fallback to trades data
        let (volume, num_trades) = if let Some(stats) = &stats_data {
            if let Some(market_stats) = stats
                .order_book_stats
                .iter()
                .find(|s| normalize_symbol(&s.symbol) == canonical_symbol)
            {
                (
                    Some(
                        Decimal::from_f64_retain(market_stats.daily_base_token_volume)
                            .unwrap_or(Decimal::ZERO),
                    ),
                    Some(market_stats.daily_trades_count as u64),
                )
            } else {
                // Fallback to trades data
                let volume = trades_response
                    .trades
                    .iter()
                    .map(|trade| string_to_decimal(Some(trade.size.clone())))
                    .collect::<Result<Vec<_>, _>>()?
                    .iter()
                    .sum();
                (Some(volume), Some(trades_response.trades.len() as u64))
            }
        } else {
            // Fallback to trades data
            let volume = trades_response
                .trades
                .iter()
                .map(|trade| string_to_decimal(Some(trade.size.clone())))
                .collect::<Result<Vec<_>, _>>()?
                .iter()
                .sum();
            (Some(volume), Some(trades_response.trades.len() as u64))
        };

        Ok(TickerResponse {
            symbol: symbol.to_string(),
            price,
            min_tick: Some(min_tick),
            min_order: None,
            volume,
            num_trades,
            open_interest: None,
            funding_rate,
            oracle_price: None,
        })
    }

    async fn get_filled_orders(&self, symbol: &str) -> Result<FilledOrdersResponse, DexError> {
        let orders = self.filled_orders.read().await;
        let normalized = normalize_symbol(symbol);
        let symbol_orders = orders
            .get(symbol)
            .or_else(|| orders.get(&normalized))
            .cloned()
            .unwrap_or_default();

        Ok(FilledOrdersResponse {
            orders: symbol_orders,
        })
    }

    async fn get_canceled_orders(&self, symbol: &str) -> Result<CanceledOrdersResponse, DexError> {
        let orders = self.canceled_orders.read().await;
        let symbol_orders = orders.get(symbol).cloned().unwrap_or_default();

        Ok(CanceledOrdersResponse {
            orders: symbol_orders,
        })
    }

    async fn get_balance(&self, symbol: Option<&str>) -> Result<BalanceResponse, DexError> {
        let endpoint = format!("/api/v1/account?by=index&value={}", self.account_index);

        // First, get the raw response text for debugging
        let url = format!("{}{}", self.base_url, endpoint);
        log::info!(
            "get_balance called for symbol: {:?}, requesting URL: {}",
            symbol,
            url
        );

        // Track API call
        track_api_call(&endpoint, "GET");

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        log::info!(
            "Account API response (status: {}): {}",
            status,
            response_text
        );

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        let account_response: LighterAccountResponse = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))?;

        if account_response.accounts.is_empty() {
            return Err(DexError::Other("No account found".to_string()));
        }

        let account = &account_response.accounts[0];

        // Debug log account information
        log::info!("Account balance info:");
        log::info!("  - Account Index: {}", account.account_index);
        log::info!("  - Available Balance: {} USD", account.available_balance);
        log::info!("  - Collateral: {} USD", account.collateral);
        log::info!("  - Total Asset Value: {} USD", account.total_asset_value);
        log::info!("  - Positions count: {}", account.positions.len());

        // Debug log all positions
        for (i, position) in account.positions.iter().enumerate() {
            log::info!(
                "  Position [{}]: market_id={}, symbol={}, position={}, sign={}",
                i,
                position.market_id,
                position.symbol,
                position.position,
                position.sign
            );
        }

        // If symbol is specified, look for that specific token position
        if let Some(token_symbol) = symbol {
            log::trace!("Looking for position with symbol: {}", token_symbol);

            // Find position for the specific token
            for position in &account.positions {
                if position.symbol == token_symbol {
                    log::trace!(
                        "✓ Found position for {}: {} (sign: {})",
                        token_symbol,
                        position.position,
                        position.sign
                    );
                    let position_decimal = string_to_decimal(Some(position.position.clone()))?;
                    let entry_price = string_to_decimal(Some(position.avg_entry_price.clone()))?;
                    return Ok(BalanceResponse {
                        equity: position_decimal,
                        balance: position_decimal,
                        position_entry_price: Some(entry_price),
                        position_sign: Some(position.sign.into()),
                    });
                }
            }

            // If token not found in positions, return zero
            log::trace!("✗ No position found for {}, returning zero", token_symbol);
            return Ok(BalanceResponse {
                equity: rust_decimal::Decimal::ZERO,
                balance: rust_decimal::Decimal::ZERO,
                position_entry_price: None,
                position_sign: None,
            });
        }

        // If no symbol specified, return account-level balances (USD)
        log::trace!("No symbol specified, returning account-level USD balances");
        let total_asset_value = string_to_decimal(Some(account.total_asset_value.clone()))?;
        let available_balance = string_to_decimal(Some(account.available_balance.clone()))?;

        log::info!(
            "Account balances: total_asset_value={}, available_balance={}",
            total_asset_value,
            available_balance
        );

        Ok(BalanceResponse {
            equity: total_asset_value,  // Total account value in USD
            balance: available_balance, // Available balance in USD
            position_entry_price: None, // Account-level call doesn't have position info
            position_sign: None,
        })
    }

    async fn get_combined_balance(&self) -> Result<CombinedBalanceResponse, DexError> {
        let endpoint = format!("/api/v1/account?by=index&value={}", self.account_index);
        let url = format!("{}{}", self.base_url, endpoint);

        log::info!("get_combined_balance called, requesting URL: {}", url);

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        let account_response: LighterAccountResponse = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))?;

        if account_response.accounts.is_empty() {
            return Err(DexError::Other("No account found".to_string()));
        }

        let account = &account_response.accounts[0];

        // Extract USD balance
        let usd_balance = string_to_decimal(Some(account.available_balance.clone()))?;

        // Extract all token balances
        let mut token_balances = std::collections::HashMap::new();
        for position in &account.positions {
            let position_decimal = string_to_decimal(Some(position.position.clone()))?;
            let entry_price = string_to_decimal(Some(position.avg_entry_price.clone()))?;

            token_balances.insert(
                position.symbol.clone(),
                BalanceResponse {
                    equity: position_decimal,
                    balance: position_decimal,
                    position_entry_price: Some(entry_price),
                    position_sign: Some(position.sign.into()),
                },
            );
        }

        log::debug!(
            "Combined balance: USD={}, tokens={} positions",
            usd_balance,
            token_balances.len()
        );

        Ok(CombinedBalanceResponse {
            usd_balance,
            token_balances,
        })
    }

    async fn get_open_orders(&self, symbol: &str) -> Result<OpenOrdersResponse, DexError> {
        log::debug!(
            "[WS_ORDER_TRACKING] get_open_orders called for symbol: {} (WebSocket-only)",
            symbol
        );

        // Return WebSocket-tracked orders only (no API fallback)
        let orders_guard = self.cached_open_orders.read().await;
        let orders = orders_guard.get(symbol).cloned().unwrap_or_default();

        log::debug!(
            "[WS_ORDER_TRACKING] Returning {} orders for {} from WebSocket tracking",
            orders.len(),
            symbol
        );

        Ok(OpenOrdersResponse { orders })
    }

    async fn get_last_trades(&self, symbol: &str) -> Result<LastTradesResponse, DexError> {
        // Get market_id for the symbol
        let market_id = self.resolve_market_info(symbol).await?.market_id;

        // Query recent trades
        let endpoint = format!("/api/v1/recentTrades?market_id={}&limit=10", market_id);

        let url = format!("{}{}", self.base_url, endpoint);
        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        log::debug!(
            "Last trades API response (status: {}): {}",
            status,
            response_text
        );

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        let trades_response: LighterTradesResponse = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))?;

        let trades = trades_response
            .trades
            .into_iter()
            .map(|t| LastTrade {
                price: string_to_decimal(Some(t.price)).unwrap_or_default(),
            })
            .collect();

        Ok(LastTradesResponse { trades })
    }

    async fn clear_filled_order(&self, symbol: &str, trade_id: &str) -> Result<(), DexError> {
        let mut filled_orders = self.filled_orders.write().await;
        if let Some(orders) = filled_orders.get_mut(symbol) {
            let initial_len = orders.len();
            orders.retain(|order| order.trade_id != trade_id);
            if orders.len() < initial_len {
                log::debug!(
                    "🗑️ [CLEAR_FILL] Removed trade_id {} for {}",
                    trade_id,
                    symbol
                );
                Ok(())
            } else {
                Err(DexError::Other(format!(
                    "Trade ID {} not found for symbol {}",
                    trade_id, symbol
                )))
            }
        } else {
            Err(DexError::Other(format!(
                "No filled orders found for symbol {}",
                symbol
            )))
        }
    }

    async fn clear_all_filled_orders(&self) -> Result<(), DexError> {
        let mut filled_orders = self.filled_orders.write().await;
        let total_cleared = filled_orders.values().map(|v| v.len()).sum::<usize>();
        filled_orders.clear();
        log::info!(
            "🗑️ [CLEAR_ALL_FILLS] Cleared {} filled orders across all symbols",
            total_cleared
        );
        Ok(())
    }

    async fn clear_canceled_order(&self, _symbol: &str, _order_id: &str) -> Result<(), DexError> {
        Err(DexError::Other(
            "clear_canceled_order not supported for Lighter - canceled orders are streamed via WebSocket only".to_string()
        ))
    }

    async fn clear_all_canceled_orders(&self) -> Result<(), DexError> {
        Err(DexError::Other(
            "clear_all_canceled_orders not supported for Lighter - canceled orders are streamed via WebSocket only".to_string()
        ))
    }

    async fn create_order(
        &self,
        symbol: &str,
        size: Decimal,
        side: OrderSide,
        price: Option<Decimal>,
        _spread: Option<i64>,
        expiry_secs: Option<u64>,
    ) -> Result<CreateOrderResponse, DexError> {
        // Resolve market metadata for symbol
        let market_info = self.resolve_market_info(symbol).await?;
        let market_id = market_info.market_id;

        // Convert side: Long=0(BUY), Short=1(SELL) for Lighter API
        let side_value = match side {
            OrderSide::Long => 0,
            OrderSide::Short => 1,
        };

        // Convert time-in-force: 0=IOC, 1=GTT, 2=PostOnly
        // Use spread parameter to specify TIF when negative values:
        // spread >= 0: normal spread adjustment
        // spread = -1: Request IOC (degraded to GTT on Lighter)
        // spread = -2: Post-only order
        let default_tif = TIF_GTT;

        let price_decimals = market_info.price_decimals;
        let size_decimals = market_info.size_decimals;

        // Convert amounts to Lighter's scaled integers using market metadata
        let size_abs = size.abs();
        let mut base_amount = Self::scale_decimal_to_u64(
            size_abs,
            size_decimals,
            RoundingStrategy::ToZero,
            "base amount",
        )?;

        if base_amount == 0 && size_abs > Decimal::ZERO {
            log::debug!(
                "Rounded base amount to zero for size {} (decimals {}), forcing minimum base_amount=1",
                size_abs,
                size_decimals
            );
            base_amount = 1;
        }

        let (price_value, order_type, tif) = if let Some(p) = price {
            // Handle spread parameter: negative values for TIF, positive for price adjustment
            let (final_price, order_tif) = if let Some(spread_ticks) = _spread {
                if spread_ticks < 0 {
                    // Negative spread values specify TIF
                    let tif_value = match spread_ticks {
                        -1 => TIF_GTT,       // Treat IOC override as resting GTT on Lighter
                        -2 => TIF_POST_ONLY, // Post-only (resting limit)
                        _ => {
                            log::warn!("Invalid TIF spread value: {}, using GTT", spread_ticks);
                            default_tif
                        }
                    };
                    (p, tif_value) // No price adjustment for TIF orders
                } else {
                    // Positive spread values adjust price (original behavior)
                    let tick_decimals = price_decimals.min(MAX_DECIMAL_PRECISION);
                    if tick_decimals != price_decimals {
                        log::warn!(
                            "Price decimals {} exceed supported max {}, clamping for spread adjustment",
                            price_decimals,
                            MAX_DECIMAL_PRECISION
                        );
                    }
                    let tick_size = Decimal::new(1, tick_decimals);
                    let spread_amount = Decimal::from(spread_ticks) * tick_size;
                    (p + spread_amount, default_tif)
                }
            } else {
                (p, default_tif)
            };

            // Limit order
            let price_u32 = Self::scale_decimal_to_u32(
                final_price,
                price_decimals,
                RoundingStrategy::MidpointAwayFromZero,
                "price",
            )?;
            let price_val = u64::from(price_u32);

            let tif_name = match order_tif {
                v if v == TIF_IOC => "IOC",
                v if v == TIF_GTT => "GTT",
                v if v == TIF_POST_ONLY => "POST_ONLY",
                _ => "UNKNOWN",
            };

            log::debug!("Creating limit order: side={}, original_price={}, spread_param={:?}, final_price={}, TIF={} ({}), scaled_price={}, size={}, scaled_base_amount={}",
                side_value, p, _spread, final_price, order_tif, tif_name, price_val, size_abs, base_amount);
            (price_val, ORDER_TYPE_LIMIT, order_tif)
        } else {
            // Market order - get current price and set protection price
            let ticker = self.get_ticker(symbol, None).await?;
            let current_price = ticker.price;

            // Set protection price with large buffer for market orders
            let protection_price = if side_value == 1 {
                // SELL
                current_price * Decimal::new(800, 3) // 20% below market (protection price)
            } else {
                // BUY
                current_price * Decimal::new(1200, 3) // 20% above market (protection price)
            };

            let price_u32 = Self::scale_decimal_to_u32(
                protection_price,
                price_decimals,
                RoundingStrategy::MidpointAwayFromZero,
                "protection price",
            )?;
            let price_val = u64::from(price_u32);

            log::debug!(
                "Market order: current_price={}, protection_price={}, side={}, price_decimals={}, size_decimals={}",
                current_price,
                protection_price,
                side_value,
                price_decimals,
                size_decimals
            );

            (price_val, ORDER_TYPE_IOC, TIF_IOC) // Market orders use IOC semantics
        };

        // Use native Rust implementation for Lighter signatures
        let result = self
            .create_order_native_with_type(
                market_id,
                side_value,
                tif,
                base_amount,
                price_value,
                None,
                order_type,
                false,
                expiry_secs,
            )
            .await;

        // Update order tracking if order creation was successful
        if let Ok(ref response) = result {
            let actual_price = price.unwrap_or(Decimal::ZERO);
            self.update_order_tracking_after_create(
                symbol,
                &response.order_id,
                side,
                size,
                actual_price,
            )
            .await;
        }

        result
    }

    async fn create_advanced_trigger_order(
        &self,
        symbol: &str,
        size: Decimal,
        side: OrderSide,
        trigger_px: Decimal,
        limit_px: Option<Decimal>,
        order_style: TriggerOrderStyle,
        slippage_bps: Option<u32>,
        tpsl: TpSl,
        reduce_only: bool,
        expiry_secs: Option<u64>,
    ) -> Result<CreateOrderResponse, DexError> {
        log::info!(
            "🎯 [ADVANCED_TRIGGER_ORDER] Creating {} order for {}: style={:?}, trigger={}, limit={:?}, slippage_bps={:?}",
            match tpsl { TpSl::Sl => "stop loss", TpSl::Tp => "take profit" },
            symbol,
            order_style,
            trigger_px,
            limit_px,
            slippage_bps
        );

        let market_info = self.resolve_market_info(symbol).await?;
        let market_id = market_info.market_id;

        let side_value = if is_buy_for_tpsl(side) {
            SIDE_BUY
        } else {
            SIDE_SELL
        };

        let (is_market, final_limit_price, order_type) = match order_style {
            TriggerOrderStyle::Market => {
                let order_type = match tpsl {
                    TpSl::Sl => 2, // StopLossOrder
                    TpSl::Tp => 4, // TakeProfitOrder
                };
                (true, trigger_px, order_type)
            }
            TriggerOrderStyle::MarketWithSlippageControl => {
                if let Some(slippage) = slippage_bps {
                    let slippage_factor = Decimal::new(slippage as i64, 4);
                    // "Market equivalent with slippage control" means we prioritize execution over price
                    // Always adjust towards the WORSE direction for guaranteed execution
                    let adjusted_price = match (side, tpsl) {
                        (OrderSide::Long, TpSl::Sl) => {
                            // Long Stop Loss (sell): worse price for selling = lower price
                            trigger_px * (Decimal::ONE - slippage_factor)
                        }
                        (OrderSide::Short, TpSl::Sl) => {
                            // Short Stop Loss (buy): worse price for buying = higher price
                            trigger_px * (Decimal::ONE + slippage_factor)
                        }
                        (OrderSide::Long, TpSl::Tp) => {
                            // Long Take Profit executed as market (sell): worse price = lower price
                            trigger_px * (Decimal::ONE - slippage_factor)
                        }
                        (OrderSide::Short, TpSl::Tp) => {
                            // Short Take Profit executed as market (buy): worse price = higher price
                            trigger_px * (Decimal::ONE + slippage_factor)
                        }
                    };
                    let order_type = match tpsl {
                        TpSl::Sl => 3, // StopLossLimitOrder with slippage control
                        TpSl::Tp => 5, // TakeProfitLimitOrder with slippage control
                    };
                    (false, adjusted_price, order_type)
                } else {
                    // Fallback to pure market
                    let order_type = match tpsl {
                        TpSl::Sl => 2,
                        TpSl::Tp => 4,
                    };
                    (true, trigger_px, order_type)
                }
            }
            TriggerOrderStyle::Limit => {
                let limit_price = limit_px.ok_or_else(|| {
                    DexError::Other("limit_px required for Limit order style".into())
                })?;

                // Validate limit price vs trigger price for the order type
                // The validation should be based on order execution direction, not position side
                match (side, tpsl) {
                    (OrderSide::Long, TpSl::Sl) => {
                        // Buy stop loss: limit should be >= trigger (worse price for buying)
                        if limit_price < trigger_px {
                            return Err(DexError::Other(
                                "For Buy Stop Loss, limit_px must be >= trigger_px".into(),
                            ));
                        }
                    }
                    (OrderSide::Short, TpSl::Sl) => {
                        // Sell stop loss: limit should be <= trigger (worse price for selling)
                        if limit_price > trigger_px {
                            return Err(DexError::Other(
                                "For Sell Stop Loss, limit_px must be <= trigger_px".into(),
                            ));
                        }
                    }
                    (OrderSide::Long, TpSl::Tp) => {
                        // Buy take profit: limit should be <= trigger (better price for buying)
                        if limit_price > trigger_px {
                            return Err(DexError::Other(
                                "For Buy Take Profit, limit_px must be <= trigger_px".into(),
                            ));
                        }
                    }
                    (OrderSide::Short, TpSl::Tp) => {
                        // Sell take profit: limit should be >= trigger (better price for selling)
                        if limit_price < trigger_px {
                            return Err(DexError::Other(
                                "For Sell Take Profit, limit_px must be >= trigger_px".into(),
                            ));
                        }
                    }
                }

                let order_type = match tpsl {
                    TpSl::Sl => 3, // StopLossLimitOrder
                    TpSl::Tp => 5, // TakeProfitLimitOrder
                };
                (false, limit_price, order_type)
            }
        };

        // Convert to native units with proper error handling
        let size_abs = size.abs();
        let mut base_amount = Self::scale_decimal_to_u64(
            size_abs,
            market_info.size_decimals,
            RoundingStrategy::ToZero,
            "trigger order base amount",
        )?;
        if base_amount == 0 && size_abs > Decimal::ZERO {
            log::debug!(
                "Rounded trigger order base amount to zero for size {}, forcing minimum base_amount=1",
                size_abs
            );
            base_amount = 1;
        }

        let trigger_price_native = u64::from(Self::scale_decimal_to_u32(
            trigger_px,
            market_info.price_decimals,
            RoundingStrategy::MidpointAwayFromZero,
            "trigger price",
        )?);

        let execution_price_native = if is_market {
            0 // Market orders: server ignores execution_price, use 0 for clarity
        } else {
            u64::from(Self::scale_decimal_to_u32(
                final_limit_price,
                market_info.price_decimals,
                RoundingStrategy::MidpointAwayFromZero,
                "execution price",
            )?)
        };

        // Set TimeInForce based on order type (using global protocol constants)
        let time_in_force = if is_market { TIF_IOC } else { TIF_GTT };

        log::debug!(
            "Creating trigger order: market_id={}, side={}, base_amount={}, price={}, trigger_price={}, order_type={}",
            market_id, side_value, base_amount, execution_price_native, trigger_price_native, order_type
        );

        self.create_order_native_with_trigger(
            market_id,
            side_value,
            time_in_force,
            base_amount,
            execution_price_native,
            trigger_price_native,
            None,
            order_type,
            reduce_only,
            expiry_secs,
        )
        .await
    }

    async fn cancel_order(&self, symbol: &str, order_id: &str) -> Result<(), DexError> {
        let market_info = self.resolve_market_info(symbol).await?;

        let order_index = match order_id.parse::<i64>() {
            Ok(idx) => idx,
            Err(_) => {
                log::warn!(
                    "[CANCEL_ORDER] Unable to parse order_id '{}' as numeric index. Skipping cancel request.",
                    order_id
                );
                return Ok(());
            }
        };

        let nonce = self.get_nonce().await? as i64;
        let tx_json = self
            .call_go_sign_cancel_order(market_info.market_id as i32, order_index, nonce)
            .await?;

        let form_data = format!(
            "tx_type=15&tx_info={}&price_protection=false",
            urlencoding::encode(&tx_json)
        );

        track_api_call("POST /api/v1/sendTx (cancel_order)", "POST");

        let response = self
            .client
            .post(&format!("{}/api/v1/sendTx", self.base_url))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .body(form_data)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("HTTP request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "Cancel order failed: HTTP {}, {}",
                status, response_text
            )));
        }

        self.update_order_tracking_after_cancel(symbol, order_id)
            .await;

        log::info!(
            "[CANCEL_ORDER] Successfully cancelled order {} for {}",
            order_id,
            symbol
        );

        Ok(())
    }

    async fn cancel_all_orders(&self, symbol: Option<String>) -> Result<(), DexError> {
        let targets: Vec<(String, Vec<String>)> = {
            let orders_guard = self.cached_open_orders.read().await;
            match symbol {
                Some(sym) => {
                    let ids = orders_guard
                        .get(&sym)
                        .map(|orders| orders.iter().map(|o| o.order_id.clone()).collect())
                        .unwrap_or_default();
                    vec![(sym, ids)]
                }
                None => orders_guard
                    .iter()
                    .map(|(sym, orders)| {
                        (
                            sym.clone(),
                            orders.iter().map(|o| o.order_id.clone()).collect(),
                        )
                    })
                    .collect(),
            }
        };

        let mut last_err: Option<DexError> = None;
        for (sym, ids) in targets {
            for order_id in ids {
                if let Err(e) = self.cancel_order(&sym, &order_id).await {
                    log::error!(
                        "[CANCEL_ORDER] Failed to cancel order {} for {}: {}",
                        order_id,
                        sym,
                        e
                    );
                    last_err = Some(e);
                }
            }
        }

        if let Some(err) = last_err {
            Err(err)
        } else {
            Ok(())
        }
    }

    async fn cancel_orders(
        &self,
        symbol: Option<String>,
        order_ids: Vec<String>,
    ) -> Result<(), DexError> {
        let symbol = match symbol {
            Some(sym) => sym,
            None => {
                return Err(DexError::Other(
                    "cancel_orders requires a symbol on Lighter".to_string(),
                ))
            }
        };

        if order_ids.is_empty() {
            return Ok(());
        }

        let mut last_err: Option<DexError> = None;
        for order_id in order_ids {
            if let Err(e) = self.cancel_order(&symbol, &order_id).await {
                log::error!(
                    "[CANCEL_ORDER] Failed to cancel order {} for {}: {}",
                    order_id,
                    symbol,
                    e
                );
                last_err = Some(e);
            }
        }

        if let Some(err) = last_err {
            Err(err)
        } else {
            Ok(())
        }
    }

    async fn close_all_positions(&self, _symbol: Option<String>) -> Result<(), DexError> {
        // Get current account info to check positions
        let endpoint = format!("/api/v1/account?by=index&value={}", self.account_index);

        let url = format!("{}{}", self.base_url, endpoint);
        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Request failed: {}", e)))?;

        let status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| DexError::Other(format!("Failed to read response: {}", e)))?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "HTTP {}: {}",
                status, response_text
            )));
        }

        let account_response: LighterAccountResponse = serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse response: {}", e)))?;

        if account_response.accounts.is_empty() {
            return Err(DexError::Other("No account found".to_string()));
        }

        let account = &account_response.accounts[0];

        // Check if there are any open positions (position != "0.00000")
        let mut has_positions = false;
        for position in &account.positions {
            if let Ok(pos_size) = position.position.parse::<f64>() {
                if pos_size.abs() > 0.0 {
                    // Close any position greater than 0
                    has_positions = true;
                    log::info!(
                        "Found open position: market_id={}, symbol={}, size={}",
                        position.market_id,
                        position.symbol,
                        position.position
                    );
                }
            }
        }

        if !has_positions {
            log::info!("No open positions found (threshold: > 0.0), nothing to close");
            // Log all positions for debugging
            for position in &account.positions {
                if let Ok(pos_size) = position.position.parse::<f64>() {
                    if pos_size.abs() > 0.0 {
                        log::debug!("Small position below threshold: market_id={}, symbol={}, size={} (abs: {})",
                                   position.market_id, position.symbol, position.position, pos_size.abs());
                    }
                }
            }
            return Ok(());
        }

        // Close each open position by placing market orders in opposite direction
        for position in &account.positions {
            if let Ok(pos_size) = position.position.parse::<f64>() {
                if pos_size.abs() > 0.0 {
                    log::info!(
                        "Closing position: market_id={}, symbol={}, size={}, sign={}",
                        position.market_id,
                        position.symbol,
                        position.position,
                        position.sign
                    );

                    // Determine order side (opposite to current position)
                    let order_side = if position.sign > 0 {
                        // Currently long, so sell to close
                        1 // Ask/Sell
                    } else {
                        // Currently short, so buy to close
                        0 // Bid/Buy
                    };

                    let market_id = position.market_id;
                    let market_info = match self.resolve_market_info(&position.symbol).await {
                        Ok(info) => info,
                        Err(err) => {
                            log::warn!(
                                "Failed to resolve market info for {} (market_id={}): {}. Skipping position close",
                                position.symbol,
                                market_id,
                                err
                            );
                            continue;
                        }
                    };

                    // Use rust_decimal for precise conversion to avoid floating point errors
                    let pos_decimal =
                        rust_decimal::Decimal::from_str(&position.position.replace('-', ""))
                            .unwrap_or_else(|_| {
                                // Fallback: convert to string first then parse
                                let pos_str = format!("{:.8}", pos_size.abs());
                                rust_decimal::Decimal::from_str(&pos_str)
                                    .unwrap_or(rust_decimal::Decimal::ZERO)
                            });
                    let mut base_amount = match Self::scale_decimal_to_u64(
                        pos_decimal,
                        market_info.size_decimals,
                        RoundingStrategy::ToZero,
                        "position base amount",
                    ) {
                        Ok(value) => value,
                        Err(err) => {
                            log::warn!(
                                "Failed to scale position size {} with {} decimals: {}. Falling back to default decimals {}",
                                pos_decimal,
                                market_info.size_decimals,
                                err,
                                DEFAULT_SIZE_DECIMALS
                            );
                            Self::scale_decimal_to_u64(
                                pos_decimal,
                                DEFAULT_SIZE_DECIMALS,
                                RoundingStrategy::ToZero,
                                "fallback position base amount",
                            )
                            .unwrap_or(0)
                        }
                    };

                    // Ensure minimum of 1 unit for very small positions
                    if base_amount == 0 && pos_size.abs() > 0.0 {
                        base_amount = 1;
                        log::debug!(
                            "Position too small for conversion, using minimum base_amount=1"
                        );
                    }

                    log::debug!(
                        "Converting position {} to base_amount: {} (original: {}, decimal: {})",
                        position.position,
                        base_amount,
                        pos_size,
                        pos_decimal
                    );

                    // Create reduce-only market order to close position (requires less margin)
                    log::info!(
                        "Placing reduce-only market order to close position: market_id={}, side={}, size={}",
                        market_id, order_side, pos_decimal
                    );

                    // Get current price for market order using ticker data
                    let ticker_price = match self.get_ticker(&position.symbol, None).await {
                        Ok(ticker) => ticker.price,
                        Err(e) => {
                            log::warn!(
                                "Failed to fetch ticker for {} while closing position: {}. Using fallback price",
                                position.symbol,
                                e
                            );
                            rust_decimal::Decimal::new(50000, 0)
                        }
                    };

                    let protection_price = if order_side == 1 {
                        // Sell: set low protection price
                        ticker_price * rust_decimal::Decimal::new(700, 3) // 30% below market
                    } else {
                        // Buy: set high protection price
                        ticker_price * rust_decimal::Decimal::new(1300, 3) // 30% above market
                    };

                    let current_price = match Self::scale_decimal_to_u32(
                        protection_price,
                        market_info.price_decimals,
                        RoundingStrategy::MidpointAwayFromZero,
                        "close-position protection price",
                    ) {
                        Ok(value) => u64::from(value),
                        Err(err) => {
                            log::warn!(
                                "Failed to scale protection price {} with {} decimals: {}. Using fallback 0",
                                protection_price,
                                market_info.price_decimals,
                                err
                            );
                            0
                        }
                    };

                    // Create reduce-only market order directly
                    match self
                        .create_order_native_with_type(
                            market_id as u32,
                            order_side as u32,
                            0, // IOC time in force
                            base_amount,
                            current_price,
                            None,
                            1,    // Market order type
                            true, // reduce_only=true for position closing (prevents overshooting)
                            None, // No expiry for position closing
                        )
                        .await
                    {
                        Ok(response) => {
                            log::info!(
                                "Successfully submitted reduce-only close order for {} position in market {}: Order ID {}",
                                position.symbol,
                                market_id,
                                response.order_id
                            );
                        }
                        Err(e) => {
                            log::error!("Failed to close position in market {}: {}", market_id, e);
                            return Err(e);
                        }
                    }
                }
            }
        }

        log::info!("All position close orders submitted successfully");
        Ok(())
    }

    async fn clear_last_trades(&self, _symbol: &str) -> Result<(), DexError> {
        Ok(())
    }

    async fn is_upcoming_maintenance(&self, hours_ahead: i64) -> bool {
        let info = self.maintenance.read().await;
        if let Some(start) = info.next_start {
            let now = Utc::now();
            if now < start && (start - now) <= ChronoDuration::hours(hours_ahead) {
                return true;
            }
        }
        false
    }

    async fn sign_evm_65b(&self, message: &str) -> Result<String, DexError> {
        use ethers::signers::{LocalWallet, Signer};
        use std::str::FromStr;

        let private_key = self
            .evm_wallet_private_key
            .as_ref()
            .ok_or_else(|| DexError::Other("EVM wallet private key not set".to_string()))?;
        let cleaned_key = private_key.strip_prefix("0x").unwrap_or(private_key);
        let wallet = LocalWallet::from_str(cleaned_key)
            .map_err(|e| DexError::Other(format!("Invalid private key: {}", e)))?;

        let signature = wallet
            .sign_message(message.as_bytes())
            .await
            .map_err(|e| DexError::Other(format!("Signing failed: {}", e)))?;

        Ok(format!("0x{}", signature))
    }

    async fn sign_evm_65b_with_eip191(&self, message: &str) -> Result<String, DexError> {
        // EIP-191 adds the prefix "\x19Ethereum Signed Message:\n" + message.len() + message
        let prefixed = format!("\x19Ethereum Signed Message:\n{}{}", message.len(), message);
        self.sign_evm_65b(&prefixed).await
    }
}

impl LighterConnector {
    /// Update order tracking after order creation
    async fn update_order_tracking_after_create(
        &self,
        symbol: &str,
        order_id: &str,
        side: OrderSide,
        size: Decimal,
        price: Decimal,
    ) {
        let mut orders_guard = self.cached_open_orders.write().await;
        let orders = orders_guard
            .entry(symbol.to_string())
            .or_insert_with(Vec::new);

        let new_order = OpenOrder {
            order_id: order_id.to_string(),
            symbol: symbol.to_string(),
            side,
            size,
            price,
            status: "open".to_string(),
        };

        orders.push(new_order);

        log::debug!(
            "[WS_ORDER_TRACKING] Added order {} to tracking for {} (total: {} orders)",
            order_id,
            symbol,
            orders.len()
        );
    }

    /// Update order tracking after order cancellation
    #[allow(dead_code)]
    async fn update_order_tracking_after_cancel(&self, symbol: &str, order_id: &str) {
        let mut orders_guard = self.cached_open_orders.write().await;
        if let Some(orders) = orders_guard.get_mut(symbol) {
            orders.retain(|order| order.order_id != order_id);
            log::debug!(
                "[WS_ORDER_TRACKING] Removed order {} from tracking for {} (remaining: {} orders)",
                order_id,
                symbol,
                orders.len()
            );
        }
    }
}

impl LighterConnector {
    async fn get_exchange_stats(&self) -> Result<LighterExchangeStats, DexError> {
        let url = format!("{}/api/v1/exchangeStats", self.base_url);

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Failed to get exchange stats: {}", e)))?;

        let status = response.status();
        let response_text = response.text().await.map_err(|e| {
            DexError::Other(format!("Failed to read exchange stats response: {}", e))
        })?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "Exchange stats HTTP {}: {}",
                status, response_text
            )));
        }

        log::trace!("Exchange stats response: {}", response_text);

        serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse exchange stats: {}", e)))
    }

    async fn get_order_book_details(&self) -> Result<LighterOrderBookDetailsResponse, DexError> {
        let url = format!("{}/api/v1/orderBookDetails", self.base_url);

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Failed to get order book details: {}", e)))?;

        let status = response.status();
        let response_text = response.text().await.map_err(|e| {
            DexError::Other(format!("Failed to read order book details response: {}", e))
        })?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "OrderBookDetails HTTP {}: {}",
                status, response_text
            )));
        }

        log::trace!("Order book details response: {}", response_text);

        serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse order book details: {}", e)))
    }

    async fn get_funding_rates(&self) -> Result<LighterFundingRates, DexError> {
        let url = format!("{}/api/v1/funding-rates", self.base_url);

        let response = self
            .client
            .get(&url)
            .header("X-API-KEY", &self.api_key_public)
            .send()
            .await
            .map_err(|e| DexError::Other(format!("Failed to get funding rates: {}", e)))?;

        let status = response.status();
        let response_text = response.text().await.map_err(|e| {
            DexError::Other(format!("Failed to read funding rates response: {}", e))
        })?;

        if !status.is_success() {
            return Err(DexError::Other(format!(
                "Funding rates HTTP {}: {}",
                status, response_text
            )));
        }

        log::trace!("Funding rates response: {}", response_text);

        serde_json::from_str(&response_text)
            .map_err(|e| DexError::Other(format!("Failed to parse funding rates: {}", e)))
    }

    async fn start_websocket(&self) -> Result<(), DexError> {
        let ws_url = self
            .websocket_url
            .replace("https://", "wss://")
            .replace("http://", "ws://");

        log::info!("Connecting to WebSocket: {}", ws_url);

        let ws = match self._ws.as_ref() {
            Some(ws) => ws,
            None => return Err(DexError::Other("WebSocket not initialized".to_string())),
        };

        let (_sink, _stream) = ws
            .connect()
            .await
            .map_err(|_| DexError::Other("Failed to connect to WebSocket".to_string()))?;

        let primary_market_id = if let Some(symbol) = self.tracked_symbols.first() {
            match self.resolve_market_info(symbol).await {
                Ok(info) => info.market_id,
                Err(e) => {
                    log::warn!(
                        "Failed to resolve primary symbol '{}' for WS order book subscription: {}. Falling back to market_id=1",
                        symbol,
                        e
                    );
                    1
                }
            }
        } else {
            1
        };

        // Clone necessary data for the WebSocket task
        let current_price = self.current_price.clone();
        let current_volume = self.current_volume.clone();
        let order_book = self.order_book.clone();
        let filled_orders = self.filled_orders.clone();
        let canceled_orders = self.canceled_orders.clone();
        let is_running = self.is_running.clone();
        let connection_epoch = self.connection_epoch.clone();
        let account_index = self.account_index;
        let market_cache = Arc::clone(&self.market_cache);
        let default_symbol = self
            .tracked_symbols
            .first()
            .cloned()
            .unwrap_or_else(|| "BTC".to_string());

        // Spawn WebSocket handler task with reconnection logic
        let ws_url_clone = ws_url.clone();
        tokio::spawn(async move {
            use rand::Rng;

            const BACKOFF_MAX_SECS: u64 = 60;
            const BACKOFF_BASE: f64 = 1.5;

            let mut reconnect_attempt = 0u32;
            let mut last_reconnect_time = std::time::SystemTime::now();

            async fn reconnect_backoff(attempt: u32) {
                let pow = BACKOFF_BASE.powi(attempt.min(12) as i32);
                let base_secs = (pow as f64).min(BACKOFF_MAX_SECS as f64);
                let jitter_ms: i64 = rand::thread_rng().gen_range(0..=250);
                let dur = std::time::Duration::from_secs_f64(base_secs)
                    + std::time::Duration::from_millis(jitter_ms as u64);

                log::debug!(
                    "Reconnect backoff: attempt={}, delay={:.1}s",
                    attempt,
                    dur.as_secs_f64()
                );
                tokio::time::sleep(dur).await;
            }

            loop {
                if !is_running.load(Ordering::SeqCst) {
                    log::info!("WebSocket task stopping due to is_running flag");
                    break;
                }

                // Reset attempt counter if enough time has passed since last reconnect
                let now = std::time::SystemTime::now();
                if let Ok(elapsed) = now.duration_since(last_reconnect_time) {
                    if elapsed.as_secs() > 300 {
                        // 5 minutes
                        reconnect_attempt = 0;
                        log::debug!("Reset reconnect attempt counter after successful period");
                    }
                }

                if reconnect_attempt > 0 {
                    reconnect_backoff(reconnect_attempt).await;
                }

                log::info!(
                    "Attempting WebSocket connection to: {} (attempt: {})",
                    ws_url_clone,
                    reconnect_attempt + 1
                );
                last_reconnect_time = now;

                // Try to establish connection with optimized configuration
                use tokio_tungstenite::tungstenite::protocol::WebSocketConfig;
                let mut config = WebSocketConfig::default();

                // Optimize WebSocket configuration for low latency
                config.max_message_size = Some(64 * 1024 * 1024); // 64MB
                config.max_frame_size = Some(16 * 1024 * 1024); // 16MB
                config.write_buffer_size = 128 * 1024; // 128KB write buffer
                config.max_write_buffer_size = 1024 * 1024; // 1MB max write buffer

                let connection_result = tokio_tungstenite::connect_async_with_config(
                    &ws_url_clone,
                    Some(config),
                    false,
                )
                .await;

                match connection_result {
                    Ok((mut ws_stream, _)) => {
                        // Increment connection epoch for race detection
                        let current_epoch = connection_epoch.fetch_add(1, Ordering::SeqCst) + 1;

                        // Extract connection information for logging
                        let (local_addr, peer_addr) = match ws_stream.get_ref() {
                            tokio_tungstenite::MaybeTlsStream::Rustls(tls_stream) => {
                                let tcp_stream = tls_stream.get_ref().0;

                                // Apply TCP optimizations for TLS connection
                                if let Err(e) = tcp_stream.set_nodelay(true) {
                                    log::warn!("Failed to set TCP_NODELAY on TLS: {}", e);
                                }

                                match (tcp_stream.local_addr(), tcp_stream.peer_addr()) {
                                    (Ok(local), Ok(peer)) => (local, peer),
                                    _ => {
                                        log::warn!(
                                            "Failed to get TLS socket addresses for epoch {}",
                                            current_epoch
                                        );
                                        ("0.0.0.0:0".parse().unwrap(), "0.0.0.0:0".parse().unwrap())
                                    }
                                }
                            }
                            tokio_tungstenite::MaybeTlsStream::Plain(tcp_stream) => {
                                if let Err(e) = tcp_stream.set_nodelay(true) {
                                    log::warn!("Failed to set TCP_NODELAY on plain WS: {}", e);
                                }
                                match (tcp_stream.local_addr(), tcp_stream.peer_addr()) {
                                    (Ok(local), Ok(peer)) => (local, peer),
                                    _ => {
                                        log::warn!(
                                            "Failed to get plain socket addresses for epoch {}",
                                            current_epoch
                                        );
                                        ("0.0.0.0:0".parse().unwrap(), "0.0.0.0:0".parse().unwrap())
                                    }
                                }
                            }
                            other => {
                                log::warn!(
                                    "Unsupported WebSocket stream type {:?} for epoch {}",
                                    other,
                                    current_epoch
                                );
                                ("0.0.0.0:0".parse().unwrap(), "0.0.0.0:0".parse().unwrap())
                            }
                        };

                        let epoch_prefix = format!("[{:03}]", current_epoch);

                        log::info!(
                            "{} WebSocket connected successfully: {} -> {}",
                            epoch_prefix,
                            local_addr,
                            peer_addr
                        );

                        // Determine primary market for order book subscription
                        let orderbook_market_id = primary_market_id;

                        // Send subscription messages
                        let subscribe_orderbook = serde_json::json!({
                            "type": "subscribe",
                            "channel": format!("order_book/{}", orderbook_market_id)
                        });

                        let subscribe_account = serde_json::json!({
                            "type": "subscribe",
                            "channel": format!("account_all/{}", account_index)
                        });

                        log::info!(
                            "🔗 [WS_DEBUG] Sending subscriptions - orderbook: {}, account: {}",
                            subscribe_orderbook,
                            subscribe_account
                        );

                        if let Err(e) = ws_stream
                            .send(tokio_tungstenite::tungstenite::Message::Text(
                                subscribe_orderbook.to_string(),
                            ))
                            .await
                        {
                            log::error!("Failed to send orderbook subscription: {}", e);
                            continue;
                        }

                        if let Err(e) = ws_stream
                            .send(tokio_tungstenite::tungstenite::Message::Text(
                                subscribe_account.to_string(),
                            ))
                            .await
                        {
                            log::error!("Failed to send account subscription: {}", e);
                            continue;
                        }

                        log::info!("WebSocket subscriptions sent successfully");

                        // Single-task pump architecture: no split(), unified read/write with select!
                        use futures::sink::SinkExt;
                        use futures::stream::StreamExt;

                        // Split stream for shared access but use channels for coordination
                        let (write, mut read) = ws_stream.split();

                        // Shared writer protected by Arc<Mutex>
                        let ws_writer_arc = Arc::new(tokio::sync::Mutex::new(write));
                        let ws_writer_for_reader = ws_writer_arc.clone();

                        // Control channel for high-priority messages (ping/pong)
                        let (tx_ctrl, mut rx_ctrl) =
                            tokio::sync::mpsc::channel::<OutboundMessage>(32);

                        // Create unified writer task with priority handling
                        let writer_is_running = is_running.clone();
                        let ws_writer_for_task = ws_writer_arc.clone();
                        let _writer_task = tokio::spawn(async move {
                            loop {
                                if !writer_is_running.load(Ordering::SeqCst) {
                                    break;
                                }

                                // Handle control messages
                                let (msg, _) = tokio::select! {
                                    // High priority channel (control messages like Pong)
                                    Some(msg) = rx_ctrl.recv() => (msg, true),
                                    else => break,
                                };

                                let send_start = std::time::Instant::now();
                                let is_pong = msg.is_pong();

                                // Use shared writer with short-lived lock
                                let mut ws_write = ws_writer_for_task.lock().await;
                                if let Err(e) = ws_write.send(msg.into_message()).await {
                                    log::error!("WebSocket send failed: {:?}", e);
                                    break;
                                }

                                let send_duration = send_start.elapsed();

                                if is_pong {
                                    let latency_ms = send_duration.as_millis();
                                    if latency_ms > 100 {
                                        log::warn!("High pong send latency: {}ms", latency_ms);
                                    }
                                }
                            }

                            log::debug!("WebSocket writer task terminated");
                        });

                        // Heartbeat strategy: application-layer ping-pong + control frame ping-pong
                        const IDLE_PING_SECS: u64 = 20; // Client ping interval
                        const PONG_TIMEOUT_SECS: u64 = 8; // Pong timeout (reduced from 10s)
                        const HEARTBEAT_CHECK_SECS: u64 = 5; // Check interval for heartbeat logic

                        fn get_pong_payload(ping_payload: &[u8]) -> Vec<u8> {
                            // Always echo for strict server compliance
                            ping_payload.to_vec()
                        }

                        use parking_lot::Mutex;
                        use std::sync::atomic::{AtomicBool, AtomicU64};
                        use std::time::{SystemTime, UNIX_EPOCH};

                        fn now_secs() -> u64 {
                            SystemTime::now()
                                .duration_since(UNIX_EPOCH)
                                .unwrap_or_default()
                                .as_secs()
                        }

                        let last_rx = std::sync::Arc::new(AtomicU64::new(now_secs()));
                        let last_tx = std::sync::Arc::new(AtomicU64::new(now_secs()));
                        let last_app_ping = std::sync::Arc::new(AtomicU64::new(now_secs()));
                        let last_server_ping = std::sync::Arc::new(AtomicU64::new(0));
                        let pending_client_ping = std::sync::Arc::new(AtomicBool::new(false));
                        let pending_app_pong = std::sync::Arc::new(AtomicBool::new(false));
                        let last_client_ping_payload =
                            std::sync::Arc::new(Mutex::new(Vec::<u8>::new()));

                        // Create ping/heartbeat task with priority channel access
                        let ping_is_running = is_running.clone();
                        let _ping_last_rx = last_rx.clone();
                        let ping_last_tx = last_tx.clone();
                        let ping_last_app_ping = last_app_ping.clone();
                        let _ping_last_server_ping = last_server_ping.clone();
                        let ping_pending_client_ping = pending_client_ping.clone();
                        let ping_pending_app_pong = pending_app_pong.clone();
                        let ping_last_client_ping_payload = last_client_ping_payload.clone();
                        let ping_tx_ctrl = tx_ctrl.clone();

                        let _ping_task = tokio::spawn(async move {
                            let mut heartbeat_interval = tokio::time::interval(
                                std::time::Duration::from_secs(HEARTBEAT_CHECK_SECS),
                            );
                            heartbeat_interval
                                .set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

                            loop {
                                tokio::select! {
                                    // Handle heartbeat check interval
                                    _ = heartbeat_interval.tick() => {
                                        if !ping_is_running.load(Ordering::SeqCst) {
                                            break;
                                        }

                                        let now = now_secs();
                                        let idle_tx = now.saturating_sub(ping_last_tx.load(Ordering::SeqCst));

                                        // Send client ping regularly (every 20s) regardless of server ping activity
                                        // This ensures server's ~120s client ping requirement is always satisfied
                                        if !ping_pending_client_ping.load(Ordering::SeqCst)
                                            && idle_tx >= IDLE_PING_SECS
                                        {
                                            // Send ping with timestamp payload for echo verification
                                            let payload: [u8; 8] = (now as u64).to_be_bytes();
                                            *ping_last_client_ping_payload.lock() = payload.to_vec();

                                            let ping_msg = OutboundMessage::Control(
                                                tokio_tungstenite::tungstenite::Message::Ping(payload.to_vec())
                                            );
                                            if let Err(e) = ping_tx_ctrl.send(ping_msg).await {
                                                log::warn!("Failed to send client ping: {:?}", e);
                                                break;
                                            }

                                            ping_pending_client_ping.store(true, Ordering::SeqCst);
                                            ping_last_tx.store(now, Ordering::SeqCst);
                                        }


                                        // Send application-layer ping (every 20s) for servers that require JSON ping-pong
                                        let idle_app_ping = now.saturating_sub(ping_last_app_ping.load(Ordering::SeqCst));
                                        if !ping_pending_app_pong.load(Ordering::SeqCst) && idle_app_ping >= IDLE_PING_SECS {
                                            // Send application-layer ping with timestamp
                                            let app_ping = serde_json::json!({
                                                "type": "ping",
                                                "ts": now
                                            });

                                            let ping_msg = OutboundMessage::Control(
                                                tokio_tungstenite::tungstenite::Message::Text(app_ping.to_string())
                                            );
                                            if let Err(e) = ping_tx_ctrl.send(ping_msg).await {
                                                log::warn!("Failed to send application-layer ping: {:?}", e);
                                                break;
                                            }

                                            ping_pending_app_pong.store(true, Ordering::SeqCst);
                                            ping_last_app_ping.store(now, Ordering::SeqCst);
                                        }

                                        // Check for control frame pong timeout
                                        if ping_pending_client_ping.load(Ordering::SeqCst) {
                                            let waited = now.saturating_sub(ping_last_tx.load(Ordering::SeqCst));
                                            if waited >= PONG_TIMEOUT_SECS {
                                                log::warn!("Control pong timeout ({}s), reconnecting", waited);
                                                let close_msg = OutboundMessage::Control(
                                                    tokio_tungstenite::tungstenite::Message::Close(None)
                                                );
                                                let _ = ping_tx_ctrl.send(close_msg).await;
                                                break;
                                            }
                                        }

                                        // Check for application-layer pong timeout
                                        if ping_pending_app_pong.load(Ordering::SeqCst) {
                                            let waited = now.saturating_sub(ping_last_app_ping.load(Ordering::SeqCst));
                                            if waited >= PONG_TIMEOUT_SECS {
                                                log::warn!("Application pong timeout ({}s), reconnecting", waited);
                                                let close_msg = OutboundMessage::Control(
                                                    tokio_tungstenite::tungstenite::Message::Close(None)
                                                );
                                                let _ = ping_tx_ctrl.send(close_msg).await;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            log::debug!("Heartbeat task ended");
                        });

                        // Handle messages in this connection with performance tracking
                        log::debug!("Starting WebSocket message handling loop");

                        while let Some(message) = read.next().await {
                            if !is_running.load(Ordering::SeqCst) {
                                log::info!("WebSocket stopping due to is_running flag");
                                break;
                            }

                            match message {
                                Ok(message) => match message {
                                    tokio_tungstenite::tungstenite::Message::Text(text) => {
                                        let msg_start = std::time::Instant::now();
                                        log::trace!("WebSocket text message: {}", text);

                                        // Update last received timestamp for any text message
                                        let now = now_secs();
                                        last_rx.store(now, Ordering::SeqCst);

                                        if let Ok(parsed) = serde_json::from_str::<Value>(&text) {
                                            // Check for application-layer ping/pong FIRST (before business logic)
                                            if let Some(msg_type) =
                                                parsed.get("type").and_then(|t| t.as_str())
                                            {
                                                if msg_type == "ping" {
                                                    // Immediate application-layer pong response
                                                    let mut pong =
                                                        serde_json::json!({"type": "pong"});

                                                    // Echo any timestamp/id fields as required by server
                                                    if let Some(ts) = parsed.get("ts") {
                                                        pong["ts"] = ts.clone();
                                                    }
                                                    if let Some(id) = parsed.get("id") {
                                                        pong["id"] = id.clone();
                                                    }
                                                    if let Some(nonce) = parsed.get("nonce") {
                                                        pong["nonce"] = nonce.clone();
                                                    }

                                                    // Send application-layer pong (NOT control frame pong)
                                                    if let Ok(mut ws_write) =
                                                        ws_writer_for_reader.try_lock()
                                                    {
                                                        if let Err(e) = ws_write.send(
                                                            tokio_tungstenite::tungstenite::Message::Text(pong.to_string())
                                                        ).await {
                                                            log::error!("Failed to send application-layer pong: {:?}", e);
                                                        } else {
                                                                        }
                                                    } else {
                                                    }

                                                    // Continue to next message (don't process ping as business data)
                                                    continue;
                                                } else if msg_type == "pong" {
                                                    // Application-layer pong received - clear pending state
                                                    pending_app_pong.store(false, Ordering::SeqCst);

                                                    // Continue to next message (don't process pong as business data)
                                                    continue;
                                                }
                                            }

                                            Self::handle_websocket_message(
                                                parsed,
                                                &current_price,
                                                &current_volume,
                                                &order_book,
                                                &filled_orders,
                                                &canceled_orders,
                                                account_index,
                                                &market_cache,
                                                default_symbol.as_str(),
                                            )
                                            .await;

                                            let total_duration = msg_start.elapsed();

                                            // Log slow messages only
                                            if total_duration.as_millis() > 10 {
                                                log::warn!(
                                                    "Slow message processing: {}ms (len={})",
                                                    total_duration.as_millis(),
                                                    text.len()
                                                );
                                            }
                                        } else {
                                            log::warn!(
                                                "Failed to parse WebSocket message as JSON: {}",
                                                text
                                            );
                                        }
                                    }
                                    tokio_tungstenite::tungstenite::Message::Ping(payload) => {
                                        // Server ping -> immediate manual pong response
                                        let now = now_secs();
                                        last_server_ping.store(now, Ordering::SeqCst);
                                        last_rx.store(now, Ordering::SeqCst);

                                        // Echo pong payload for server compliance
                                        let pong_payload = get_pong_payload(&payload);

                                        // Get current epoch for race detection logging
                                        let current_epoch = connection_epoch.load(Ordering::SeqCst);

                                        // Direct pong send - bypass writer task for immediate response
                                        if let Ok(mut ws_write) = ws_writer_for_reader.try_lock() {
                                            if let Err(e) = ws_write
                                                .send(
                                                    tokio_tungstenite::tungstenite::Message::Pong(
                                                        pong_payload.clone(),
                                                    ),
                                                )
                                                .await
                                            {
                                                log::error!("🚨 [CRITICAL] Failed to send pong directly: {:?}", e);
                                                break;
                                            }
                                            if let Err(e) =
                                                futures::SinkExt::flush(&mut *ws_write).await
                                            {
                                                log::error!("🚨 [CRITICAL] Failed to flush after pong: {:?}", e);
                                                break;
                                            }
                                            last_tx.store(now, Ordering::SeqCst);

                                            // Verify same connection epoch for race detection
                                            let pong_epoch =
                                                connection_epoch.load(Ordering::SeqCst);

                                            if pong_epoch != current_epoch {
                                                log::error!(
                                                    "Pong epoch mismatch: ping={} pong={}",
                                                    current_epoch,
                                                    pong_epoch
                                                );
                                            }
                                        } else {
                                            // Fallback to try_lock with retry for up to 200ms
                                            let mut pong_sent = false;
                                            for retry in 0..4 {
                                                tokio::time::sleep(
                                                    std::time::Duration::from_millis(50),
                                                )
                                                .await;
                                                if let Ok(mut ws_write) =
                                                    ws_writer_for_reader.try_lock()
                                                {
                                                    if let Err(e) = ws_write.send(tokio_tungstenite::tungstenite::Message::Pong(pong_payload.clone())).await {
                                                        log::error!("Failed to send pong on retry {}: {:?}", retry, e);
                                                        break;
                                                    }
                                                    if let Err(e) =
                                                        futures::SinkExt::flush(&mut *ws_write)
                                                            .await
                                                    {
                                                        log::error!("Failed to flush after pong retry {}: {:?}", retry, e);
                                                        break;
                                                    }
                                                    last_tx.store(now, Ordering::SeqCst);

                                                    pong_sent = true;
                                                    break;
                                                }
                                            }
                                            if !pong_sent {
                                                log::warn!("Pong timeout, closing connection");
                                                // Proactively close to trigger reconnect before server timeout
                                                let mut ws_write =
                                                    ws_writer_for_reader.lock().await;
                                                let _ = ws_write.close().await;
                                                break;
                                            }
                                        }
                                    }
                                    tokio_tungstenite::tungstenite::Message::Pong(payload) => {
                                        // Pong response - check if it matches our client ping
                                        let now = now_secs();
                                        last_rx.store(now, Ordering::SeqCst);

                                        let expected_payload =
                                            last_client_ping_payload.lock().clone();
                                        if !expected_payload.is_empty()
                                            && payload == expected_payload
                                        {
                                            pending_client_ping.store(false, Ordering::SeqCst);
                                        } else {
                                        }
                                    }
                                    tokio_tungstenite::tungstenite::Message::Close(frame) => {
                                        log::warn!("WebSocket close frame received: {:?}", frame);
                                        break;
                                    }
                                    tokio_tungstenite::tungstenite::Message::Binary(data) => {
                                        log::debug!(
                                            "Received binary WebSocket message: {} bytes",
                                            data.len()
                                        );
                                    }
                                    tokio_tungstenite::tungstenite::Message::Frame(_) => {
                                        log::trace!("Received raw WebSocket frame");
                                    }
                                },
                                Err(e) => {
                                    log::error!(
                                        "WebSocket error: {} (type: {:?}). Will attempt reconnection.",
                                        e, std::any::type_name_of_val(&e)
                                    );
                                    break; // Break inner loop to attempt reconnection
                                }
                            }
                        }

                        reconnect_attempt += 1;
                    }
                    Err(e) => {
                        reconnect_attempt += 1;

                        // Check for 429 Too Many Requests
                        let error_str = e.to_string();
                        if error_str.contains("429") || error_str.contains("Too Many Requests") {
                            log::error!(
                                "WebSocket connection failed with rate limit (429): {}. Attempt: {}. Using exponential backoff.",
                                e, reconnect_attempt
                            );
                        } else {
                            log::error!(
                                "Failed to connect to WebSocket: {}. Attempt: {}. Will retry with backoff.",
                                e, reconnect_attempt
                            );
                        }
                    }
                }
            }

            log::info!("WebSocket task ended");
        });

        Ok(())
    }

    async fn handle_websocket_message(
        message: Value,
        current_price: &Arc<RwLock<Option<(Decimal, u64)>>>,
        current_volume: &Arc<RwLock<Option<Decimal>>>,
        order_book: &Arc<RwLock<Option<LighterOrderBook>>>,
        filled_orders: &Arc<RwLock<HashMap<String, Vec<FilledOrder>>>>,
        canceled_orders: &Arc<RwLock<HashMap<String, Vec<CanceledOrder>>>>,
        account_index: u32,
        market_cache: &Arc<RwLock<MarketCache>>,
        default_symbol: &str,
    ) {
        let msg_type = message.get("type").and_then(|t| t.as_str()).unwrap_or("");

        match msg_type {
            "subscribed/order_book" | "update/order_book" => {
                if let Some(order_book_data) = message.get("order_book") {
                    if let Ok(ob) =
                        serde_json::from_value::<LighterOrderBook>(order_book_data.clone())
                    {
                        // Update current price from best bid/ask
                        if let (Some(best_bid), Some(best_ask)) = (ob.bids.first(), ob.asks.first())
                        {
                            if let (Ok(bid_price), Ok(ask_price)) = (
                                string_to_decimal(Some(best_bid.price.clone())),
                                string_to_decimal(Some(best_ask.price.clone())),
                            ) {
                                let mid_price = (bid_price + ask_price) / Decimal::from(2);
                                let timestamp = std::time::SystemTime::now()
                                    .duration_since(std::time::UNIX_EPOCH)
                                    .unwrap()
                                    .as_secs();
                                *current_price.write().await = Some((mid_price, timestamp));
                                log::trace!(
                                    "Updated price from WebSocket: {} at {}",
                                    mid_price,
                                    timestamp
                                );
                            }
                        }

                        // Calculate volume from order book
                        let total_volume: Decimal = ob
                            .bids
                            .iter()
                            .chain(ob.asks.iter())
                            .filter_map(|entry| string_to_decimal(Some(entry.size.clone())).ok())
                            .sum();
                        *current_volume.write().await = Some(total_volume);

                        *order_book.write().await = Some(ob);
                    }
                }
            }
            "subscribed/account_all" | "update/account_all" => {
                log::trace!(
                    "Received account message: type={}, message={:?}",
                    msg_type,
                    message
                );
                // Handle account updates (filled/canceled orders)
                // For Lighter DEX, the data is directly in the message, not in a 'data' field
                Self::handle_account_update(
                    &message,
                    filled_orders,
                    canceled_orders,
                    account_index as u64,
                    market_cache,
                    default_symbol,
                )
                .await;
            }
            _ => {
                log::trace!("Unhandled WebSocket message type: {}", msg_type);
            }
        }
    }

    async fn handle_account_update(
        data: &Value,
        filled_orders: &Arc<RwLock<HashMap<String, Vec<FilledOrder>>>>,
        canceled_orders: &Arc<RwLock<HashMap<String, Vec<CanceledOrder>>>>,
        account_id: u64,
        market_cache: &Arc<RwLock<MarketCache>>,
        default_symbol: &str,
    ) {
        log::trace!("handle_account_update called with data: {:?}", data);

        // Handle filled orders - try both 'fills' and 'trades' fields
        if let Some(fills) = data.get("fills").and_then(|f| f.as_array()) {
            log::info!(
                "✅ [FILL_DETECTION] Found {} fills in account update",
                fills.len()
            );
            let default_symbol = default_symbol.to_string();
            let mut filled_map = filled_orders.write().await;
            for fill in fills {
                log::debug!("🔍 [FILL_DETECTION] Processing fill: {:?}", fill);
                if let Ok(filled_order) = Self::parse_filled_order(fill, account_id) {
                    log::info!("✅ [FILL_DETECTION] Added filled order: order_id={}, size={:?}, value={:?}",
                              filled_order.order_id, filled_order.filled_size, filled_order.filled_value);
                    filled_map
                        .entry(default_symbol.clone())
                        .or_insert_with(Vec::new)
                        .push(filled_order);
                } else {
                    log::warn!("Failed to parse filled order: {:?}", fill);
                }
            }
        }

        // Process 'trades' field according to Lighter API specification
        if let Some(trades) = data.get("trades").and_then(|t| t.as_object()) {
            log::info!("✅ [FILL_DETECTION] Found trades object in account update");

            let mut pending_inserts: Vec<(String, FilledOrder)> = Vec::new();

            for (market_id, trade_array) in trades {
                let market_id_num = match market_id.parse::<u32>() {
                    Ok(id) => id,
                    Err(_) => {
                        log::warn!(
                            "[FILL_DETECTION] Unable to parse market_id '{}' as u32",
                            market_id
                        );
                        continue;
                    }
                };

                let market_symbol = {
                    let cache = market_cache.read().await;
                    cache
                        .by_id
                        .get(&market_id_num)
                        .map(|info| info.canonical_symbol.clone())
                };

                let market_symbol = match market_symbol {
                    Some(symbol) => symbol,
                    None => {
                        log::warn!(
                            "[FILL_DETECTION] Market cache missing entry for market_id {}",
                            market_id_num
                        );
                        continue;
                    }
                };

                if let Some(trades_array) = trade_array.as_array() {
                    for trade in trades_array {
                        if let (Some(ask_id), Some(bid_id), Some(size_str), Some(price_str)) = (
                            trade.get("ask_id").and_then(|v| v.as_u64()),
                            trade.get("bid_id").and_then(|v| v.as_u64()),
                            trade.get("size").and_then(|v| v.as_str()),
                            trade.get("price").and_then(|v| v.as_str()),
                        ) {
                            let order_id = if account_id == ask_id { ask_id } else { bid_id };

                            log::info!(
                                "✅ [FILL_DETECTION] Trade detected: order_id={}, size={}, price={}, market_id={}",
                                order_id, size_str, price_str, market_id_num
                            );

                            if let (Ok(size), Ok(price)) = (
                                size_str.parse::<rust_decimal::Decimal>(),
                                price_str.parse::<rust_decimal::Decimal>(),
                            ) {
                                let filled_order = FilledOrder {
                                    order_id: order_id.to_string(),
                                    is_rejected: false,
                                    trade_id: trade
                                        .get("trade_id")
                                        .and_then(|v| v.as_u64())
                                        .unwrap_or(0)
                                        .to_string(),
                                    filled_side: if account_id == ask_id {
                                        Some(OrderSide::Short)
                                    } else {
                                        Some(OrderSide::Long)
                                    },
                                    filled_size: Some(size),
                                    filled_value: Some(size * price),
                                    filled_fee: None,
                                };

                                pending_inserts.push((market_symbol.clone(), filled_order));
                                log::info!(
                                    "✅ [FILL_DETECTION] Added filled order from trade: order_id={}",
                                    order_id
                                );
                            }
                        }
                    }
                }
            }

            if !pending_inserts.is_empty() {
                let mut filled_map = filled_orders.write().await;
                for (symbol_key, filled_order) in pending_inserts {
                    filled_map
                        .entry(symbol_key)
                        .or_insert_with(Vec::new)
                        .push(filled_order);
                }
            }
        } else {
            log::trace!("No 'fills' array or 'trades' object found in account data");
        }

        // Handle canceled orders
        if let Some(cancels) = data.get("cancels").and_then(|c| c.as_array()) {
            let default_symbol = default_symbol.to_string();
            let mut canceled_map = canceled_orders.write().await;
            for cancel in cancels {
                if let Ok(canceled_order) = Self::parse_canceled_order(cancel) {
                    canceled_map
                        .entry(default_symbol.clone())
                        .or_insert_with(Vec::new)
                        .push(canceled_order);
                }
            }
        }
    }

    fn parse_filled_order(_data: &Value, _account_id: u64) -> Result<FilledOrder, DexError> {
        // Filled order tracking is not supported for Lighter DEX
        // MarketMake strategy will use timeout-based order management instead
        Err(DexError::Other(
            "Filled order tracking not supported for Lighter DEX".to_string(),
        ))
    }

    fn parse_canceled_order(data: &Value) -> Result<CanceledOrder, DexError> {
        // Parse canceled order from WebSocket data
        // This is a simplified implementation - adjust based on actual Lighter WebSocket format
        Ok(CanceledOrder {
            order_id: data
                .get("order_id")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            canceled_timestamp: data.get("timestamp").and_then(|v| v.as_u64()).unwrap_or(0),
        })
    }

    fn ten_pow(decimals: u32) -> u64 {
        let safe_decimals = decimals.min(MAX_DECIMAL_PRECISION);
        if safe_decimals != decimals {
            log::warn!(
                "Decimal precision {} exceeds supported max {}, clamping",
                decimals,
                MAX_DECIMAL_PRECISION
            );
        }
        10u64.pow(safe_decimals)
    }

    fn scale_decimal_to_u64(
        value: Decimal,
        decimals: u32,
        rounding: RoundingStrategy,
        context: &str,
    ) -> Result<u64, DexError> {
        let safe_decimals = decimals.min(MAX_DECIMAL_PRECISION);
        if safe_decimals != decimals {
            log::warn!(
                "{} decimals {} exceed supported max {}, clamping",
                context,
                decimals,
                MAX_DECIMAL_PRECISION
            );
        }

        let multiplier = Decimal::new(10i64.pow(safe_decimals), 0);
        let rounded = value.round_dp_with_strategy(safe_decimals, rounding);
        (rounded * multiplier).to_u64().ok_or_else(|| {
            DexError::Other(format!(
                "Invalid {} value {} after scaling to {} decimals",
                context, value, safe_decimals
            ))
        })
    }

    fn scale_decimal_to_u32(
        value: Decimal,
        decimals: u32,
        rounding: RoundingStrategy,
        context: &str,
    ) -> Result<u32, DexError> {
        let scaled = Self::scale_decimal_to_u64(value, decimals, rounding, context)?;
        if scaled > u64::from(u32::MAX) {
            return Err(DexError::Other(format!(
                "Scaled {} value {} exceeds u32 maximum",
                context, scaled
            )));
        }
        Ok(scaled as u32)
    }

    fn calculate_min_tick(price: Decimal, sz_decimals: u32, is_spot: bool) -> Decimal {
        let price_str = price.to_string();
        let integer_part = price_str.split('.').next().unwrap_or("");
        let integer_digits = if integer_part == "0" {
            0
        } else {
            integer_part.len()
        };

        let scale_by_sig: u32 = if integer_digits >= 5 {
            0
        } else {
            (5 - integer_digits) as u32
        };

        let max_decimals: u32 = if is_spot { 8u32 } else { 6u32 };
        let scale_by_dec: u32 = max_decimals.saturating_sub(sz_decimals);
        let scale: u32 = scale_by_sig.min(scale_by_dec);

        Decimal::new(1, scale)
    }
}

pub fn create_lighter_connector(
    api_key_public: String,
    api_key_index: u32,
    api_private_key_hex: String,
    evm_wallet_private_key: Option<String>,
    account_index: u32,
    base_url: String,
    websocket_url: String,
    tracked_symbols: Vec<String>,
) -> Result<Box<dyn DexConnector>, DexError> {
    let connector = LighterConnector::new(
        api_key_public,
        api_key_index,
        api_private_key_hex,
        evm_wallet_private_key,
        account_index,
        base_url,
        websocket_url,
        tracked_symbols,
    )?;
    Ok(Box::new(connector))
}

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

    #[tokio::test]
    async fn test_get_open_orders() {
        // Skip test if environment variables are not set
        let api_key_public = match env::var("LIGHTER_PLAIN_PUBLIC_API_KEY") {
            Ok(key) => key,
            Err(_) => {
                println!("Skipping test - LIGHTER_PLAIN_PUBLIC_API_KEY not set");
                return;
            }
        };

        let base_url = env::var("LIGHTER_BASE_URL")
            .unwrap_or_else(|_| "https://mainnet.zklighter.elliot.ai".to_string());

        let account_index = env::var("LIGHTER_ACCOUNT_INDEX")
            .unwrap_or_else(|_| "0".to_string())
            .parse::<u32>()
            .unwrap_or(0);

        // Create connector using the proper constructor
        let connector = match LighterConnector::new(
            api_key_public,
            0, // api_key_index
            "dummy_private_key".to_string(),
            None, // evm_wallet_private_key
            account_index,
            base_url,
            "dummy_websocket_url".to_string(),
        ) {
            Ok(c) => c,
            Err(e) => {
                println!("Failed to create connector: {}", e);
                return;
            }
        };

        // Test get_open_orders
        match connector.get_open_orders("BTC").await {
            Ok(response) => {
                println!(
                    "✅ get_open_orders success: {} orders found",
                    response.orders.len()
                );
                for (i, order) in response.orders.iter().enumerate() {
                    println!("  Order {}: {}", i, order.order_id);
                }
            }
            Err(e) => {
                println!("❌ get_open_orders failed: {}", e);
                panic!("get_open_orders test failed: {}", e);
            }
        }
    }
}