ccxt-base 4.5.93

CCXT – CryptoCurrency eXchange Trading Library (Rust) – untyped engine (runtime, Value, REST/prediction Cores, WS infra)
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
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code

#![allow(unused, non_snake_case, clippy::all)]
use crate::Value;
use crate::get_value;
use crate::runtime::*;
// Base methods are now trait methods (review #1: static dispatch). Bring the
// traits into scope so `self.market(...)`, `self.safe_market(...)`,
// `self.load_markets(...)`, … on this Core resolve to the base defaults.
use crate::exchange_generated::ExchangeBase;
use crate::exchange::ExchangeRuntime;
// Dynamic `this[method](...)` re-entries are emitted as
// `self.call_dynamic_checked(...)` (blanket-impl'd on every Core) so an
// unresolvable name raises NotSupported instead of yielding a silent Null.
use crate::exchange::CallDynamicChecked;
use crate::pro::*;
use crate::prediction_exchange_generated::PredictionBase;
use crate::prediction_exchange::PredictionRuntime;


pub struct PolymarketCore {
    pub exchange: crate::prediction_exchange::PredictionExchange,
}

impl PolymarketCore {
    pub fn new(config: Option<crate::Value>) -> Self {
        let mut s = Self { exchange: crate::prediction_exchange::PredictionExchange::new(config) };
        s.init();
        s
    }

    pub fn init(&mut self) {
        let described = PolymarketCore::describe(self);
        self.initialize_properties(described);
        // compatibility for sandbox/testnet options in userConfig
        let user_config = self.userConfig.clone();
        <Self as crate::exchange_generated::ExchangeBase>::after_construct(self, &[user_config]);
    }

    /// Compatibility no-op. The old pointer-based dispatch needed a post-move
    /// `bind()`; static trait dispatch (review #1) needs no binding, so this
    /// just exists so callers that still call it keep compiling.
    #[inline]
    pub fn bind(&mut self) {}
}

impl crate::exchange::DerivedExchange for PolymarketCore {
    fn nonce(&self, ) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::nonce(self, )
    }
    fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::parse_ohlcv(self, ohlcv, &[market])
    }
    fn parse_balance(&self, response: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::parse_balance(self, response)
    }
    fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::parse_prediction_trade(self, trade, &[market])
    }
    fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::parse_prediction_order(self, order, &[market])
    }
    fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::parse_prediction_position(self, position, &[market])
    }
    fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::sign(self, path, &[api, method, params, headers, body])
    }
    fn handle_errors(&self, code: crate::Value, reason: crate::Value, url: crate::Value, method: crate::Value, headers: crate::Value, body: crate::Value, response: crate::Value, request_headers: crate::Value, request_body: crate::Value) -> crate::Value {
        // Forward to the inherent method on PolymarketCore.
        PolymarketCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
    }
}

impl crate::exchange_generated::ExchangeBase for PolymarketCore {
    fn call_dynamic<'a>(&'a mut self, method: &'a str, args: Vec<crate::Value>)
        -> std::pin::Pin<Box<dyn std::future::Future<Output = crate::Value> + Send + 'a>>
    {
        Box::pin(async move {
            match method {
                "build_clob_order_body" => self.build_clob_order_body(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
                "cancel_all_orders" => self.cancel_all_orders(&args[..]).await,
                "cancel_order" => self.cancel_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "cancel_orders" => self.cancel_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "create_api_key" => self.create_api_key(&args[..]).await,
                "create_market_buy_order_with_cost" => self.create_market_buy_order_with_cost(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
                "create_or_derive_api_key" => self.create_or_derive_api_key(&args[..]).await,
                "create_order" => self.create_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]).await,
                "create_orders" => self.create_orders(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "derive_api_key" => self.derive_api_key(&args[..]).await,
                "fetch_balance" => self.fetch_balance(&args[..]).await,
                "fetch_event" => self.fetch_event(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_events" => self.fetch_events(&args[..]).await,
                "fetch_markets" => self.fetch_markets(&args[..]).await,
                "fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
                "fetch_ohlcv" => self.fetch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_open_interest" => self.fetch_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
                "fetch_order" => self.fetch_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_order_trades" => self.fetch_order_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_outcome" => self.fetch_outcome(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
                "fetch_outcomes" => self.fetch_outcomes(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
                "fetch_position" => self.fetch_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_positions" => self.fetch_positions(&args[..]).await,
                "fetch_raw_events_by_search" => self.fetch_raw_events_by_search(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_raw_events_list" => self.fetch_raw_events_list(&args[..]).await,
                "fetch_status" => self.fetch_status(&args[..]).await,
                "fetch_ticker" => self.fetch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_tickers" => self.fetch_tickers(&args[..]).await,
                "fetch_time" => self.fetch_time(&args[..]).await,
                "fetch_trades" => self.fetch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_trading_fee" => self.fetch_trading_fee(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "handle_errors" => self.handle_errors(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), args.get(4).cloned().unwrap_or(crate::Value::Null),
                    args.get(5).cloned().unwrap_or(crate::Value::Null), args.get(6).cloned().unwrap_or(crate::Value::Null), args.get(7).cloned().unwrap_or(crate::Value::Null), args.get(8).cloned().unwrap_or(crate::Value::Null)),
                "handle_list_message" => { self.handle_list_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
                "handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
                "handle_text_message" => { self.handle_text_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
                "load_api_credentials" => self.load_api_credentials().await,
                "nonce" => self.nonce(),
                "parse_balance" => self.parse_balance(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "parse_event_to_markets" => self.parse_event_to_markets(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "parse_events" => self.parse_events(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "parse_ohlcv" => self.parse_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "parse_poly_timestamp" => self.parse_poly_timestamp(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "parse_prediction_open_interest" => self.parse_prediction_open_interest(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "parse_prediction_order" => self.parse_prediction_order(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "parse_prediction_position" => self.parse_prediction_position(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "parse_prediction_ticker" => self.parse_prediction_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "parse_prediction_trade" => self.parse_prediction_trade(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "ping" => self.ping(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "polymarket_order_raw_amounts" => self.polymarket_order_raw_amounts(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), args.get(2).cloned().unwrap_or(crate::Value::Null), args.get(3).cloned().unwrap_or(crate::Value::Null), &args[4.min(args.len())..]),
                "set_api_credentials" => self.set_api_credentials(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                "sign_hash" => self.sign_hash(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "sign_message" => self.sign_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "subscribe_user_channel" => self.subscribe_user_channel(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "watch_my_trades" => self.watch_my_trades(&args[..]).await,
                "watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "watch_orders" => self.watch_orders(&args[..]).await,
                "watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                // Prediction Core: fall through to prediction base methods (then Exchange base).
                _ => self.call_dynamic_prediction_base(method, args).await,
            }
        })
    }
}

impl crate::prediction_exchange_generated::PredictionBase for PolymarketCore {
    fn pred(&self) -> &crate::prediction_exchange::PredictionExchange { &self.exchange }
    fn pred_mut(&mut self) -> &mut crate::prediction_exchange::PredictionExchange { &mut self.exchange }
}

impl std::ops::Deref for PolymarketCore {
    type Target = crate::exchange::Exchange;
    fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}

impl std::ops::DerefMut for PolymarketCore {
    fn deref_mut(&mut self) -> &mut crate::exchange::Exchange { std::ops::DerefMut::deref_mut(&mut self.exchange) }
}

impl PolymarketCore {
    pub fn describe(&self) -> Value {
        return self.deep_extend(self.super_describe(), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), Value::Str("polymarket".into()));
        m.insert("name".to_string(), Value::Str("Polymarket".into()));
        m.insert("countries".to_string(), Value::from(vec![Value::Str("US".into())]));
        m.insert("rateLimit".to_string(), Value::Int(100));
        m.insert("certified".to_string(), Value::Bool(false));
        m.insert("pro".to_string(), Value::Bool(true));
        m.insert("streaming".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("ping".to_string(), Value::Null.clone());
        m.insert("keepAlive".to_string(), Value::Int(10000));
    m
}));
        m.insert("has".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("CORS".to_string(), Value::Null);
        m.insert("spot".to_string(), Value::Bool(false));
        m.insert("margin".to_string(), Value::Bool(false));
        m.insert("swap".to_string(), Value::Bool(false));
        m.insert("future".to_string(), Value::Bool(false));
        m.insert("option".to_string(), Value::Bool(false));
        m.insert("cancelAllOrders".to_string(), Value::Bool(true));
        m.insert("cancelOrder".to_string(), Value::Bool(true));
        m.insert("cancelOrders".to_string(), Value::Bool(true));
        m.insert("createMarketBuyOrderWithCost".to_string(), Value::Bool(true));
        m.insert("createOrder".to_string(), Value::Bool(true));
        m.insert("createOrders".to_string(), Value::Bool(true));
        m.insert("fetchBalance".to_string(), Value::Bool(true));
        m.insert("fetchCurrencies".to_string(), Value::Bool(false));
        m.insert("fetchDeposits".to_string(), Value::Bool(false));
        m.insert("fetchEvent".to_string(), Value::Bool(true));
        m.insert("fetchEvents".to_string(), Value::Bool(true));
        m.insert("fetchLedger".to_string(), Value::Bool(false));
        m.insert("fetchMarkets".to_string(), Value::Bool(true));
        m.insert("fetchMyTrades".to_string(), Value::Bool(true));
        m.insert("fetchOHLCV".to_string(), Value::Bool(true));
        m.insert("fetchOpenInterest".to_string(), Value::Bool(true));
        m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
        m.insert("fetchOrder".to_string(), Value::Bool(true));
        m.insert("fetchOrderBook".to_string(), Value::Bool(true));
        m.insert("fetchOrderTrades".to_string(), Value::Bool(true));
        m.insert("fetchPosition".to_string(), Value::Bool(true));
        m.insert("fetchPositions".to_string(), Value::Bool(true));
        m.insert("fetchStatus".to_string(), Value::Bool(true));
        m.insert("fetchTicker".to_string(), Value::Bool(true));
        m.insert("fetchTickers".to_string(), Value::Bool(true));
        m.insert("fetchTime".to_string(), Value::Bool(true));
        m.insert("fetchTrades".to_string(), Value::Bool(true));
        m.insert("fetchTradingFee".to_string(), Value::Bool(true));
        m.insert("fetchWithdrawals".to_string(), Value::Bool(false));
        m.insert("prediction".to_string(), Value::Bool(true));
        m.insert("watchMyTrades".to_string(), Value::Bool(true));
        m.insert("watchOrderBook".to_string(), Value::Bool(true));
        m.insert("watchOrders".to_string(), Value::Bool(true));
        m.insert("watchTicker".to_string(), Value::Bool(true));
        m.insert("watchTrades".to_string(), Value::Bool(true));
    m
}));
        m.insert("timeframes".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("1m".to_string(), Value::Str("1".into()));
        m.insert("5m".to_string(), Value::Str("5".into()));
        m.insert("1h".to_string(), Value::Str("60".into()));
        m.insert("6h".to_string(), Value::Str("360".into()));
        m.insert("1d".to_string(), Value::Str("1440".into()));
    m
}));
        m.insert("urls".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("logo".to_string(), Value::Str("https://github.com/user-attachments/assets/89e1a2c4-a682-44e7-ad50-9fb15b534437".into()));
        m.insert("api".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("gamma".to_string(), Value::Str("https://gamma-api.polymarket.com".into()));
        m.insert("clob".to_string(), Value::Str("https://clob.polymarket.com".into()));
        m.insert("data".to_string(), Value::Str("https://data-api.polymarket.com".into()));
        m.insert("ws".to_string(), Value::Str("wss://ws-subscriptions-clob.polymarket.com/ws/market".into()));
        m.insert("wsUser".to_string(), Value::Str("wss://ws-subscriptions-clob.polymarket.com/ws/user".into()));
    m
}));
        m.insert("www".to_string(), Value::Str("https://polymarket.com".into()));
        m.insert("doc".to_string(), Value::from(vec![Value::Str("https://docs.polymarket.com".into())]));
        m.insert("fees".to_string(), Value::Str("https://docs.polymarket.com/#fees".into()));
    m
}));
        m.insert("api".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("gamma".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("public".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("get".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("status".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("comments".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("comments/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("comments/user_address/{user_address}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/creators".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/creators/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/keyset".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/pagination".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/results".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/slug/{slug}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/{id}/comments/count".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/{id}/tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("events/{id}/tweet-count".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/keyset".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/slug/{slug}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/{id}/description".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/{id}/tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("profiles/user_address/{user_address}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("public-profile".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("public-search".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("series".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("series-summary/slug/{slug}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("series-summary/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("series/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("series/{id}/comments/count".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("sports".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("sports/market-types".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/slug/{slug}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/slug/{slug}/related-tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/slug/{slug}/related-tags/tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/{id}/related-tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tags/{id}/related-tags/tags".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("teams".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("teams/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
        m.insert("post".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("markets/abridged".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/information".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
    m
}));
        m.insert("clob".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("public".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("get".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("book".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("books".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("builder/trades".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("clob-markets/{condition_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("fee-rate".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("fee-rate/{token_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("last-trade-price".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("last-trades-prices".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets-by-token/{token_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/live-activity/{condition_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("midpoint".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("midpoints".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("neg-risk".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("neg-risk/{token_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("price".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("prices".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("prices-history".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rebates/current".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/markets/current".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/markets/multi".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/markets/{condition_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("sampling-markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("sampling-simplified-markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("simplified-markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("spread".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tick-size".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("tick-size/{token_id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("time".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
        m.insert("post".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("batch-prices-history".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("books".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("last-trades-prices".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("markets/live-activity".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("midpoints".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("prices".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("spreads".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
        m.insert("private".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("get".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("auth/api-keys".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("auth/ban-status/closed-only".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("auth/builder-api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("auth/derive-api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("balance-allowance".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("balance-allowance/update".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("data/order/{id}".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("data/orders".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("data/trades".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("notifications".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("order-scoring".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("orders-scoring".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/user".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/user/markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/user/percentages".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("rewards/user/total".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
        m.insert("post".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("auth/api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("auth/builder-api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("heartbeats".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("order".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("orders".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/heartbeats".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
        m.insert("delete".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("auth/api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("auth/builder-api-key".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("cancel-all".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("cancel-market-orders".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("notifications".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("order".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("orders".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
    m
}));
        m.insert("data".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("public".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("get".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("activity".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("closed-positions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("holders".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("live-volume".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("oi".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("other".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("positions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("revisions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("traded".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("trades".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/accounting/snapshot".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/activity/combos".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/builders/leaderboard".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/builders/volume".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/leaderboard".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/market-positions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/positions/combos".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("value".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
    m
}));
        m.insert("combos".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("public".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("get".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("v1/rfq/combo-markets".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
        m.insert("private".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("post".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("v1/maker/confirmations".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/maker/quotes".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
        m.insert("v1/maker/quotes/cancel".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(1));
    m
}));
    m
}));
    m
}));
    m
}));
    m
}));
        m.insert("exceptions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("exact".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("not enough balance / allowance".to_string(), Value::Str("InsufficientFunds".into()));
        m.insert("invalid signature".to_string(), Value::Str("AuthenticationError".into()));
        m.insert("api key not found".to_string(), Value::Str("AuthenticationError".into()));
    m
}));
        m.insert("broad".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("No orderbook exists".to_string(), Value::Str("BadSymbol".into()));
        m.insert("invalid clob token ids".to_string(), Value::Str("BadSymbol".into()));
        m.insert("not enough balance".to_string(), Value::Str("InsufficientFunds".into()));
        m.insert("allowance".to_string(), Value::Str("InsufficientFunds".into()));
        m.insert("invalid amount".to_string(), Value::Str("InvalidOrder".into()));
        m.insert("invalid price".to_string(), Value::Str("InvalidOrder".into()));
        m.insert("minimum tick size".to_string(), Value::Str("InvalidOrder".into()));
        m.insert("no orders found to match".to_string(), Value::Str("OrderNotFillable".into()));
        m.insert("could not be fully filled".to_string(), Value::Str("OrderNotFillable".into()));
        m.insert("geoblocked".to_string(), Value::Str("PermissionDenied".into()));
        m.insert("restricted jurisdiction".to_string(), Value::Str("PermissionDenied".into()));
        m.insert("Unauthorized".to_string(), Value::Str("AuthenticationError".into()));
    m
}));
    m
}));
        m.insert("requiredCredentials".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("apiKey".to_string(), Value::Bool(false));
        m.insert("secret".to_string(), Value::Bool(false));
        m.insert("password".to_string(), Value::Bool(false));
        m.insert("privateKey".to_string(), Value::Bool(false));
        m.insert("walletAddress".to_string(), Value::Bool(false));
    m
}));
        m.insert("fees".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("trading".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("tierBased".to_string(), Value::Bool(false));
        m.insert("percentage".to_string(), Value::Bool(true));
        m.insert("maker".to_string(), Value::Int(0));
        m.insert("taker".to_string(), Value::Int(0));
    m
}));
    m
}));
        m.insert("options".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("defaultFetchEventsLimit".to_string(), Value::Int(100));
        m.insert("eventsPageSize".to_string(), Value::Int(100));
        m.insert("fetchMarketsLimit".to_string(), Value::Int(200));
        m.insert("maxFetchEventsLimit".to_string(), Value::Int(500));
        m.insert("defaultEventStatus".to_string(), Value::Str("active".into()));
        m.insert("maxPricesHistoryWindow".to_string(), Value::Int(1296000));
        m.insert("chainId".to_string(), Value::Int(137));
        m.insert("ctfExchangeName".to_string(), Value::Str("Polymarket CTF Exchange".into()));
        m.insert("ctfExchangeVersion".to_string(), Value::Str("2".into()));
        m.insert("exchangeAddress".to_string(), Value::Str("0xE111180000d2663C0091e4f400237545B87B996B".into()));
        m.insert("negRiskExchangeAddress".to_string(), Value::Str("0xe2222d279d744050d28e00520010520000310F59".into()));
        m.insert("builder".to_string(), Value::Str("0xea409de8b037bb6ac664b6d12d6831b03cb04a37".into()));
        m.insert("builderFee".to_string(), Value::Bool(true));
        m.insert("feeRate".to_string(), Value::Int(0));
    m
}));
    m
})]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchMarkets
 * @description retrieves data on all markets for polymarket, each prediction market becomes one market with its outcome tokens listed under the outcomes key
 * @see https://docs.polymarket.com/api-reference/events/list-events
 * @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
 * @param {object} [params] extra exchange-specific parameters
 * @param {string} [params.query] a single search term used to filter the fetched events
 * @param {string[]} [params.queries] multiple search terms (alternative to query)
 * @param {string[]} [params.tags] filter events by tag — human-readable labels ("Fed Rates") or slugs ("fed-rates") both work; multiple tags match ANY (one gamma listing per tag, unioned)
 * @param {string} [params.status] 'active', 'closed' or 'all', the status of the events to fetch, defaults to 'active'
 * @param {int} [params.limit] max number of events to fetch when no query is given (defaults to options.fetchMarketsLimit, 200); the listing is ordered by 24h volume so the most active markets come first — outcomes on lower-volume markets are resolvable on demand by their token id (fetchOutcome)
 * @returns {object[]} an array of objects representing market data
 */
    pub async fn fetch_markets(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut queries: Value = self.parse_search_queries(&[params.clone()]);
        let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
        let mut queriesLength: f64 = ((queries.len() as i64) as f64);
        let mut rawEvents: Value = Value::from(vec![]);
        if queriesLength > ((0i64) as f64) {
            rawEvents = self.fetch_raw_events_by_search(queries, &[rest.clone()]).await;
        }  else {
            rawEvents = self.fetch_raw_events_list(&[rest]).await;
        }
        let mut flatMarkets: Vec<Value> = Vec::new();
        let mut eventsDict: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        {
                        let mut rei: i64 = 0;
            let mut __for_first_1407: bool = true;
            while { if !__for_first_1407 { rei += 1; } __for_first_1407 = false; rei < (rawEvents.len() as i64) } {
            let mut rawEvent: Value = rawEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(rei as usize).cloned().unwrap_or(Value::Null);
            let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(rawEvent.clone()).as_array().cloned().unwrap_or_default();
            {
                                let mut mi: i64 = 0;
                let mut __for_first_1406: bool = true;
                while { if !__for_first_1406 { mi += 1; } __for_first_1406 = false; mi < (ccxtMarkets.len() as i64) } {
                flatMarkets.push(ccxtMarkets.get(mi as usize).cloned().unwrap_or(Value::Null));
            }
            }
            let mut parsedEvent: indexmap::IndexMap<String, Value> = self.parse_event(rawEvent.clone()).as_map().cloned().unwrap_or_default();
            let mut eventSlug: Option<String> = self.safe_string_k_opt(rawEvent, "slug", &[]);
            if (eventSlug.is_some()) && (eventSlug.as_deref() != Some("")) {
                let mut eventKey: Value = self.shorten_slug(eventSlug.map(Value::from).unwrap_or(Value::Null));
                if let Value::Dict(__d) = &mut eventsDict { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&eventKey), Value::Map(parsedEvent)); }
            }
        }
        }
        self.exchange.events = eventsDict.clone();
        return Value::from(flatMarkets);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#fetchRawEventsBySearch
 * @description fetches raw gamma event objects matching the given search terms, paginating through all result pages
 * @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
 * @param {string[]} queries search terms
 * @param {object} [params] extra exchange-specific parameters
 * @param {int} [params.limit] page size per search query, defaults to 50
 * @returns {object[]} an array of raw gamma event objects
 */
    pub async fn fetch_raw_events_by_search(&mut self, mut queries: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let __queries_empty = Vec::new();
        let queries = queries.as_array().unwrap_or(&__queries_empty);
        let mut resultLimit: Value = self.safe_integer_k(params.clone(), "limit", &[]);
        // fixed page size (gamma's limit_per_type). do NOT tie it to `limit`: that made a small
        // limit fan out into many tiny-page requests (limit:1 -> ~one request per matching event).
        // tunable per-call via params.searchPageSize, else the exchange option, else 100
        let mut optionPageSize: Value = self.safe_integer_k(self.options.clone(), "searchPageSize", &[Value::Int(100)]);
        let mut pageSize: Value = self.safe_integer_k(params.clone(), "searchPageSize", &[optionPageSize]);
        // map the unified sort/status onto the gamma search params
        let mut sort: Option<String> = self.safe_string_k(params.clone(), "sort", &[]).as_str().map(str::to_owned);
        let mut sortParam: String = "volume".to_string();
        if (sort.as_deref() == Some("liquidity")) {
            sortParam = "liquidity".to_string();
        }  else if (sort.as_deref() == Some("newest")) {
            sortParam = "startDate".to_string();
        }
        let mut status: Option<String> = self.safe_string_k(params.clone(), "status", &[Value::Str("active".into())]).as_str().map(str::to_owned);
        let mut eventsStatus: Value = Value::Str("active".into());
        if (status.as_deref() == Some("closed")) || (status.as_deref() == Some("inactive")) {
            eventsStatus = Value::Str("closed".into());
        }  else if (status.as_deref() == Some("all")) {
            eventsStatus = Value::Null;
        }
        let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("status".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("searchPageSize".into()), Value::Str("maxSearchPages".into())]), &[]);
        let mut seen: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut rawEvents: Vec<Value> = Vec::new();
        {
                        let mut qi: Value = Value::Int(0);
            let mut __for_first_1414: bool = true;
            while { if !__for_first_1414 { if let Value::Int(n) = &mut qi { *n += 1; } } __for_first_1414 = false; qi.as_f64().unwrap_or(f64::NAN) < ((queries.len() as i64) as f64) } {
            let mut q: Value = queries.get((qi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            let mut baseRequest: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                    m.insert("q".to_string(), q);
                    m.insert("limit_per_type".to_string(), pageSize.clone());
                    m.insert("sort".to_string(), Value::from(sortParam.clone()));
                    m.insert("ascending".to_string(), Value::Bool(false));
                m
            });
            if (eventsStatus != Value::Null) {
                baseRequest.insert("events_status".into(), eventsStatus.clone());
            }
            let mut firstRequest: Value = Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("page".to_string(), Value::Int(1));
                m
            });
            let __ws_arg_0 = self.extend(firstRequest.clone(), &[Value::Map(baseRequest.clone())]);
            firstRequest = self.extend(__ws_arg_0, &[rest.clone()]);
            let mut first: Value = self.gamma_public_get_public_search(&[firstRequest]).await;
            let mut firstEvents: Vec<Value> = self.safe_list_k(first.clone(), "events", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
            let mut firstEventsLength: Value = Value::Int(firstEvents.len() as i64);
            let mut pagination: Value = self.safe_dict_k(first, "pagination", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            let mut totalResults: Value = self.safe_integer_k(pagination, "totalResults", &[firstEventsLength]);
            let mut totalPages: Value = self.parse_to_int(((match ((totalResults).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null));
            // only page as far as `limit` needs (applyEventFetchParams slices to it afterwards);
            // with no limit, cap the fan-out at options.maxSearchPages so a broad query stays bounded
            if (resultLimit != Value::Null) {
                let mut limitPages: Value = self.parse_to_int(((match ((resultLimit).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null));
                if limitPages.as_f64().unwrap_or(f64::NAN) < totalPages.as_f64().unwrap_or(f64::NAN) {
                    totalPages = limitPages;
                }
            }  else {
                let mut optionMaxPages: Value = self.safe_integer_k(self.options.clone(), "maxSearchPages", &[Value::Int(5)]);
                let mut maxSearchPages: Value = self.safe_integer_k(params.clone(), "maxSearchPages", &[optionMaxPages]);
                if maxSearchPages.as_f64().unwrap_or(f64::NAN) < totalPages.as_f64().unwrap_or(f64::NAN) {
                    totalPages = maxSearchPages;
                }
            }
            let mut remainingPages: Vec<Value> = Vec::new();
            {
                                let mut p: Value = Value::Int(2);
                let mut __for_first_1408: bool = true;
                while { if !__for_first_1408 { if let Value::Int(n) = &mut p { *n += 1; } } __for_first_1408 = false; p.as_f64().unwrap_or(f64::NAN) <= totalPages.as_f64().unwrap_or(f64::NAN) } {
                remainingPages.push(p.clone());
            }
            }
            let mut restPromises: Value = Value::from(vec![]);
            {
                                let mut pi: Value = Value::Int(0);
                let mut __for_first_1409: bool = true;
                while { if !__for_first_1409 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1409 = false; pi.as_f64().unwrap_or(f64::NAN) < ((remainingPages.len() as i64) as f64) } {
                let mut pageRequest: Value = Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("page".to_string(), remainingPages.get((pi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
                    m
                });
                let __ws_arg_1 = self.extend(pageRequest.clone(), &[Value::Map(baseRequest.clone())]);
                pageRequest = self.extend(__ws_arg_1, &[rest.clone()]);
                if let Value::Arr(__a) = &mut restPromises { std::sync::Arc::make_mut(__a).push(self.gamma_public_get_public_search(&[pageRequest]).await); }
            }
            }
            let mut restResponses: Vec<Value> = promise_all(&restPromises).await.as_array().cloned().unwrap_or_default();
            let mut allEvents: Vec<Value> = Vec::new();
            {
                                let mut fi: i64 = 0;
                let mut __for_first_1410: bool = true;
                while { if !__for_first_1410 { fi += 1; } __for_first_1410 = false; fi < (firstEvents.len() as i64) } {
                allEvents.push(firstEvents.get(fi as usize).cloned().unwrap_or(Value::Null));
            }
            }
            {
                                let mut ri: i64 = 0;
                let mut __for_first_1412: bool = true;
                while { if !__for_first_1412 { ri += 1; } __for_first_1412 = false; ri < (restResponses.len() as i64) } {
                let mut pageEvents: Vec<Value> = self.safe_list_k(restResponses.get(ri as usize).cloned().unwrap_or(Value::Null), "events", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
                {
                                        let mut ei: i64 = 0;
                    let mut __for_first_1411: bool = true;
                    while { if !__for_first_1411 { ei += 1; } __for_first_1411 = false; ei < (pageEvents.len() as i64) } {
                    allEvents.push(pageEvents.get(ei as usize).cloned().unwrap_or(Value::Null));
                }
                }
            }
            }
            {
                                let mut ei: Value = Value::Int(0);
                let mut __for_first_1413: bool = true;
                while { if !__for_first_1413 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1413 = false; ei.as_f64().unwrap_or(f64::NAN) < ((allEvents.len() as i64) as f64) } {
                let mut rawEvent: Value = allEvents.get((ei).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
                let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
                if ((eventId.is_some()) && (eventId.as_deref() != Some(""))) && !(matches!((&seen, &eventId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                    if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(eventId.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
                    rawEvents.push(rawEvent);
                }
            }
            }
        }
        }
        return Value::from(rawEvents);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#tagToSlug
 * @description converts a human-readable tag label into gamma's slug form, "Fed Rates" -> "fed-rates"; lowercase alphanumeric runs joined by single dashes, so a tag already in slug form passes through unchanged
 * @param {string} tag the tag label or slug
 * @returns {string} the gamma tag slug
 */
    pub fn tag_to_slug(&self, mut tag: Value) -> Option<String> {
        let mut lower: String = tag.as_str().map(str::to_lowercase).unwrap_or_default();
        let mut allowed: String = "abcdefghijklmnopqrstuvwxyz0123456789".to_string();
        let mut chars: Vec<Value> = self.string_to_chars_array(Value::from(lower.clone())).as_array().cloned().unwrap_or_default();
        let mut slug: Value = Value::Str("".into());
        let mut pendingSep: bool = false;
        {
                        let mut i: i64 = 0;
            let mut __for_first_1415: bool = true;
            while { if !__for_first_1415 { i += 1; } __for_first_1415 = false; i < (chars.len() as i64) } {
            let mut ch: Value = chars.get(i as usize).cloned().unwrap_or(Value::Null);
            if Value::Int(Some(allowed.as_str()).zip(ch.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
                if pendingSep && (slug.as_str() != Some("")) {
                    slug = Value::Str(format!("{}{}", slug, Value::Str("-".into())).into());
                }
                slug = Value::Str(format!("{}{}", slug, ch).into());
                pendingSep = false;
            }  else {
                pendingSep = true;
            }
        }
        }
        if (slug.as_str() == Some("")) {
            return Value::from(lower).as_str().map(str::to_owned);
        }
        return slug.as_str().map(str::to_owned);
}

/*
 * @ignore
 * @method
 * @name polymarket#fetchRawEventsList
 * @description fetches raw gamma event objects from the events listing endpoint, paginating in parallel
 * @see https://docs.polymarket.com/api-reference/events/list-events
 * @param {object} [params] extra exchange-specific parameters
 * @param {string} [params.status] 'active', 'closed' or 'all', defaults to options.defaultEventStatus
 * @param {int} [params.limit] max number of events to fetch (default options.fetchMarketsLimit); the listing is ordered by 24h volume so the most active markets come first
 * @returns {object[]} an array of raw gamma event objects
 */
    pub async fn fetch_raw_events_list(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        // gamma hard-caps each response at 100 events regardless of the requested limit, so the
        // page size must be that cap or pagination never advances (the > check below stays false)
        let mut pageSize: Value = self.safe_integer_k(self.options.clone(), "eventsPageSize", &[Value::Int(100)]);
        // scope the listing: without a search query loadMarkets would otherwise dump every
        // active event (tens of thousands of markets). Cap to `limit` events (most-traded first).
        let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("fetchMarketsLimit".into()), &[Value::Int(200)])]);
        let mut maxPages: Value = ((match ((limit).as_f64(), (pageSize).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null })).as_f64().map(|__x| Value::Float(__x.ceil())).unwrap_or(Value::Null);
        let mut status: Option<String> = self.safe_string_k(params.clone(), "status", &[self.safe_string(self.options.clone(), Value::Str("defaultEventStatus".into()), &[Value::Str("active".into())])]).as_str().map(str::to_owned);
        // sort maps to the gamma `order` field; 'volume' is the default ranking
        let mut sort: Option<String> = self.safe_string_k(params.clone(), "sort", &[]).as_str().map(str::to_owned);
        let mut order: String = "volume".to_string();
        if (sort.as_deref() == Some("liquidity")) {
            order = "liquidity".to_string();
        }  else if (sort.as_deref() == Some("newest")) {
            order = "startDate".to_string();
        }
        let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("status".into()), Value::Str("limit".into()), Value::Str("sort".into()), Value::Str("searchIn".into()), Value::Str("eventId".into()), Value::Str("slug".into()), Value::Str("query".into()), Value::Str("queries".into()), Value::Str("tags".into())]), &[]);
        let mut baseRequest: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("limit".to_string(), pageSize.clone());
                m.insert("order".to_string(), Value::from(order.clone()));
                m.insert("ascending".to_string(), Value::Bool(false));
            m
        });
        baseRequest = self.extend(baseRequest.clone(), &[rest]);
        // push requested tags server-side (gamma accepts one tag_slug per request) so a tags-only
        // fetchEvents returns the tagged events rather than filtering the top-volume listing down
        // to nothing; multiple tags run one listing per tag, unioned and deduped by event id
        let mut requestedTags: Value = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]);
        let mut requestedTagsLength: f64 = ((requestedTags.len() as i64) as f64);
        if requestedTagsLength > ((1i64) as f64) {
            let mut seen: Value = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
            let mut unioned: Vec<Value> = Vec::new();
            {
                                let mut ti: Value = Value::Int(0);
                let mut __for_first_1417: bool = true;
                while { if !__for_first_1417 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1417 = false; ti.as_f64().unwrap_or(f64::NAN) < requestedTagsLength } {
                let mut singleTagParams: Value = self.extend(Value::Map({
                    let mut m = indexmap::IndexMap::new();
                    m
                }), &[params.clone()]);
                add_element_to_object(&mut singleTagParams, &Value::Str("tags".into()), Value::from(vec![requestedTags.as_array().and_then(|__arr| match &ti { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null)]));
                let mut tagEvents: Value = Box::pin(self.fetch_raw_events_list(&[singleTagParams])).await;
                {
                                        let mut ei: i64 = 0;
                    let mut __for_first_1416: bool = true;
                    while { if !__for_first_1416 { ei += 1; } __for_first_1416 = false; ei < (tagEvents.len() as i64) } {
                    let mut rawEvent: Value = tagEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(ei as usize).cloned().unwrap_or(Value::Null);
                    let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
                    if (eventId.is_some()) && !(matches!((&seen, &eventId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                        if let Value::Dict(__d) = &mut seen { std::sync::Arc::make_mut(__d).insert(eventId.as_deref().unwrap_or("null").to_string(), Value::Bool(true)); }
                        unioned.push(rawEvent);
                    }
                }
                }
            }
            }
            return Value::from(unioned);
        }
        if requestedTagsLength > ((0i64) as f64) {
            // gamma matches tag_slug case-insensitively but only in slug form ("fed-rates"),
            // so human-readable labels ("Fed Rates") must be slugified first
            add_element_to_object(&mut baseRequest, &Value::Str("tag_slug".into()), self.tag_to_slug(self.safe_string(requestedTags, Value::Int(0), &[])).map(Value::from).unwrap_or(Value::Null));
        }
        if (status.as_deref() == Some("active")) {
            add_element_to_object(&mut baseRequest, &Value::Str("active".into()), Value::Bool(true));
            add_element_to_object(&mut baseRequest, &Value::Str("closed".into()), Value::Bool(false));
        }  else if (status.as_deref() == Some("closed")) || (status.as_deref() == Some("inactive")) {
            add_element_to_object(&mut baseRequest, &Value::Str("active".into()), Value::Bool(false));
            add_element_to_object(&mut baseRequest, &Value::Str("closed".into()), Value::Bool(true));
        }
        // 'all' — no active/closed filter
        // fetch page 1 first; if full, fire remaining pages in parallel
        let mut firstPageRequest: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("offset".to_string(), Value::Int(0));
            m
        });
        firstPageRequest = self.extend(firstPageRequest.clone(), &[baseRequest.clone()]);
        let mut firstPageResponse: Value = self.gamma_public_get_events(&[firstPageRequest]).await;
        let mut firstPageIsArray: bool = matches!(&firstPageResponse, Value::Arr(_));
        let mut firstPage: Value = (if (firstPageIsArray) { firstPageResponse } else { Value::from(vec![]) });
        let mut firstPageLength: f64 = ((firstPage.len() as i64) as f64);
        let mut allRawEvents: Vec<Value> = Vec::new();
        {
                        let mut fi: Value = Value::Int(0);
            let mut __for_first_1418: bool = true;
            while { if !__for_first_1418 { if let Value::Int(n) = &mut fi { *n += 1; } } __for_first_1418 = false; fi.as_f64().unwrap_or(f64::NAN) < firstPageLength } {
            allRawEvents.push(firstPage.as_array().and_then(|__arr| match &fi { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null));
        }
        }
        if firstPageLength >= pageSize.as_f64().unwrap_or(f64::NAN) {
            let mut offsets: Vec<Value> = Vec::new();
            {
                                let mut p: Value = Value::Int(1);
                let mut __for_first_1419: bool = true;
                while { if !__for_first_1419 { if let Value::Int(n) = &mut p { *n += 1; } } __for_first_1419 = false; maxPages.as_f64().unwrap_or(f64::NAN) > p.as_f64().unwrap_or(f64::NAN) } {
                offsets.push((match (&(p), &(pageSize)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null }));
            }
            }
            let mut restPromises: Vec<Value> = Vec::new();
            {
                                let mut oi: Value = Value::Int(0);
                let mut __for_first_1420: bool = true;
                while { if !__for_first_1420 { if let Value::Int(n) = &mut oi { *n += 1; } } __for_first_1420 = false; oi.as_f64().unwrap_or(f64::NAN) < ((offsets.len() as i64) as f64) } {
                let mut pageRequest: Value = Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("offset".to_string(), offsets.get((oi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
                    m
                });
                pageRequest = self.extend(pageRequest.clone(), &[baseRequest.clone()]);
                restPromises.push(self.gamma_public_get_events(&[pageRequest]).await);
            }
            }
            let mut restPages: Value = promise_all(&Value::from(restPromises)).await;
            {
                                let mut ri: i64 = 0;
                let mut __for_first_1422: bool = true;
                while { if !__for_first_1422 { ri += 1; } __for_first_1422 = false; ri < (restPages.len() as i64) } {
                let mut page: Vec<Value> = self.safe_list(restPages.clone(), Value::Int(ri), &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
                let mut pageLength: f64 = ((page.len() as i64) as f64);
                {
                                        let mut pi: Value = Value::Int(0);
                    let mut __for_first_1421: bool = true;
                    while { if !__for_first_1421 { if let Value::Int(n) = &mut pi { *n += 1; } } __for_first_1421 = false; pi.as_f64().unwrap_or(f64::NAN) < pageLength } {
                    allRawEvents.push(page.get(pi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
                }
                }
            }
            }
        }
        let mut allRawEventsLength: f64 = ((allRawEvents.len() as i64) as f64);
        if allRawEventsLength > limit.as_f64().unwrap_or(f64::NAN) {
            return self.array_slice(Value::from(allRawEvents), Value::Int(0), &[limit]);
        }
        return Value::from(allRawEvents);

    Value::Null
}

    pub fn parse_event_to_markets(&self, mut event: Value) -> Value {
        let __event_empty = indexmap::IndexMap::new();
        let event = event.as_map().unwrap_or(&__event_empty);
        let mut eventSlug: Value = (match event.get("slug") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => (match event.get("id") { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s.clone()),
            Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }) });
        let mut rawMarkets: Vec<Value> = (match event.get("markets") { Some(__v) if matches!(__v, Value::Arr(_)) => __v.clone(), _ => Value::from(vec![]) }).as_array().cloned().unwrap_or_default();
        let mut result: Vec<Value> = Vec::new();
        {
                        let mut mi: i64 = 0;
            let mut __for_first_1424: bool = true;
            while { if !__for_first_1424 { mi += 1; } __for_first_1424 = false; mi < (rawMarkets.len() as i64) } {
            let mut market: Value = rawMarkets.get(mi as usize).cloned().unwrap_or(Value::Null);
            let mut conditionId: Value = self.safe_string_k(market.clone(), "conditionId", &[]);
            let mut marketId: Value = self.safe_string_k(market.clone(), "id", &[]);
            let mut marketSlug: Value = self.safe_string_k(market.clone(), "slug", &[conditionId.clone()]);
            let mut active: bool = self.safe_bool_k_opt(market.clone(), "active", &[Value::Bool(false)]).unwrap_or(false);
            let mut closed: bool = self.safe_bool_k_opt(market.clone(), "closed", &[Value::Bool(false)]).unwrap_or(false);
            // resolution: a closed/uma-resolved market settles each outcome price to 0 or 1
            let mut marketResolved: Value = Value::Bool(closed || (self.safe_string_lower_k(market.clone(), "umaResolutionStatus", &[]).as_str() == Some("resolved")));
            let mut resolvedOutcome: Value = Value::Null;
            // gamma exposes the order-book tick as orderPriceMinTickSize; minimumTickSize is the clob alias
            let mut tickSize: Value = self.safe_number2(market.clone(), Value::Str("orderPriceMinTickSize".into()), Value::Str("minimumTickSize".into()), &[Value::Float(0.01)]);
            // real per-market min order size (shares) and price tick — don't hardcode 1 / 0.01..0.99
            let mut orderMinSize: Value = self.safe_number_k(market.clone(), "orderMinSize", &[Value::Int(1)]);
            let mut priceMax: Value = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &self.number_to_string(tickSize.clone())), &[]);
            let mut negRisk: bool = self.safe_bool_k_opt(market.clone(), "negRisk", &[Value::Bool(false)]).unwrap_or(false);
            let mut endDate: Value = self.safe_string_k(market.clone(), "endDate", &[self.safe_string(market.clone(), Value::Str("end_date_iso".into()), &[])]);
            // Gamma API returns these arrays as JSON-encoded strings
            let mut outcomeLabels: Value = Value::from(vec![]);
            let mut clobTokenIds: Value = Value::from(vec![]);
            let mut outcomePrices: Value = Value::from(vec![]);
            let mut parsedOutcomes: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("outcomes".into()), &[Value::Str("[]".into())]));
            let mut parsedTokenIds: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("clobTokenIds".into()), &[Value::Str("[]".into())]));
            let mut parsedPrices: Value = self.parse_json_value(self.safe_string(market.clone(), Value::Str("outcomePrices".into()), &[Value::Str("[]".into())]));
            let mut parsedOutcomesLength: Value = Value::Null;
            if (parsedOutcomes != Value::Null) {
                parsedOutcomesLength = Value::Int(parsedOutcomes.len() as i64);
            }
            let mut parsedTokenIdsLength: Value = Value::Null;
            if (parsedTokenIds != Value::Null) {
                parsedTokenIdsLength = Value::Int(parsedTokenIds.len() as i64);
            }
            let mut parsedPricesLength: Value = Value::Null;
            if (parsedPrices != Value::Null) {
                parsedPricesLength = Value::Int(parsedPrices.len() as i64);
            }
            if (parsedOutcomes != Value::Null) && (parsedOutcomesLength != Value::Null) {
                outcomeLabels = parsedOutcomes;
            }
            if (parsedTokenIds != Value::Null) && (parsedTokenIdsLength != Value::Null) {
                clobTokenIds = parsedTokenIds;
            }
            if (parsedPrices != Value::Null) && (parsedPricesLength != Value::Null) {
                outcomePrices = parsedPrices;
            }
            let mut outcomeLabelsLength: f64 = ((outcomeLabels.len() as i64) as f64);
            let mut clobTokenIdsLength: f64 = ((clobTokenIds.len() as i64) as f64);
            if (outcomeLabelsLength == 0.0) || (clobTokenIdsLength == 0.0) {
                continue;
            }
            // Market outcome (no outcome suffix)
            let mut marketSymbol: Value = self.slug_to_market_symbol(eventSlug.clone(), marketSlug.clone());
            // Build outcomes array
            let mut outcomes: Vec<Value> = Vec::new();
            {
                                let mut oi: i64 = 0;
                let mut __for_first_1423: bool = true;
                while { if !__for_first_1423 { oi += 1; } __for_first_1423 = false; oi < (outcomeLabels.len() as i64) } {
                let mut outcomeLabel: Value = outcomeLabels.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
                let mut clobTokenId: Value = clobTokenIds.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null);
                let mut outcomePrice: Value = self.safe_number(outcomePrices.clone(), Value::Int(oi), &[]);
                if (clobTokenId == Value::Null) || (clobTokenId.as_str() == Some("")) {
                    continue;
                }
                let mut outcomeHandle: Value = self.slug_to_outcome_symbol(eventSlug.clone(), marketSlug.clone(), outcomeLabel.clone());
                let mut winnerRaw: Value = Value::Null;
                let mut settleFractionRaw: Value = Value::Null;
                if matches!(&marketResolved, Value::Bool(true)) && (outcomePrice != Value::Null) {
                    // a genuinely-settled polymarket outcome is at 1 (won) or 0 (lost). a market
                    // that is only closed-for-trading (not yet UMA-resolved) still has fractional
                    // prices — don't report a fractional mid as a final settleFraction; leave the
                    // outcome-level fields undefined until a decisive price exists
                    if outcomePrice.as_f64().unwrap_or(f64::NAN) >= (0.99) {
                        winnerRaw = Value::Bool(true);
                        settleFractionRaw = Value::Int(1);
                        resolvedOutcome = outcomeHandle.clone();
                    }  else if (0.01) >= outcomePrice.as_f64().unwrap_or(f64::NAN) {
                        winnerRaw = Value::Bool(false);
                        settleFractionRaw = Value::Int(0);
                    }
                }
                // effectively-final copies: Java emits the object literal below as an anonymous
                // inner class, which cannot capture a reassigned local
                let mut winner: Value = winnerRaw;
                let mut settleFraction: Value = settleFractionRaw;
                outcomes.push(Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("outcome".to_string(), outcomeHandle);
                        m.insert("outcomeId".to_string(), clobTokenId);
                        m.insert("market".to_string(), marketSymbol.clone());
                        m.insert("label".to_string(), outcomeLabel);
                        m.insert("price".to_string(), outcomePrice);
                        m.insert("active".to_string(), Value::Bool(active && (!(closed))));
                        m.insert("winner".to_string(), winner);
                        m.insert("settleFraction".to_string(), settleFraction);
                        m.insert("precision".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("amount".to_string(), tickSize.clone());
        m.insert("price".to_string(), tickSize.clone());
    m
}));
                        m.insert("negRisk".to_string(), Value::Bool(negRisk));
                        m.insert("info".to_string(), market.clone());
                    m
                }));
            }
            }
            let mut baseId: Value = (if (conditionId != Value::Null) { conditionId.clone() } else { marketId });
            let mut marketType: Value = (if (outcomeLabelsLength > ((2i64) as f64)) { Value::Str("categorical".into()) } else { Value::Str("binary".into()) });
            // effectively-final copy for the market object literal below (reassigned in the loop)
            let mut marketResolvedOutcome: Value = resolvedOutcome;
            result.push(Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("id".to_string(), conditionId);
                    m.insert("market".to_string(), marketSymbol);
                    m.insert("marketType".to_string(), marketType);
                    m.insert("executionModel".to_string(), Value::Str("clob".into()));
                    m.insert("collateral".to_string(), Value::Str("USDC".into()));
                    m.insert("base".to_string(), Value::Str("USDC".into()));
                    m.insert("quote".to_string(), Value::Str("USDC".into()));
                    m.insert("settle".to_string(), Value::Null);
                    m.insert("baseId".to_string(), baseId);
                    m.insert("quoteId".to_string(), Value::Str("USDC".into()));
                    m.insert("settleId".to_string(), Value::Null);
                    m.insert("type".to_string(), Value::Str("prediction".into()));
                    m.insert("spot".to_string(), Value::Bool(false));
                    m.insert("margin".to_string(), Value::Bool(false));
                    m.insert("swap".to_string(), Value::Bool(false));
                    m.insert("future".to_string(), Value::Bool(false));
                    m.insert("option".to_string(), Value::Bool(false));
                    m.insert("prediction".to_string(), Value::Bool(true));
                    m.insert("active".to_string(), Value::Bool(active && (!(closed))));
                    m.insert("resolved".to_string(), marketResolved);
                    m.insert("resolvedOutcome".to_string(), marketResolvedOutcome);
                    m.insert("contract".to_string(), Value::Bool(false));
                    m.insert("linear".to_string(), Value::Null);
                    m.insert("inverse".to_string(), Value::Null);
                    m.insert("contractSize".to_string(), Value::Null);
                    m.insert("expiry".to_string(), (if ((endDate != Value::Null) && (endDate.as_str() != Some(""))) { self.parse8601(endDate.clone()) } else { Value::Null }));
                    m.insert("expiryDatetime".to_string(), endDate);
                    m.insert("strike".to_string(), Value::Null);
                    m.insert("optionType".to_string(), Value::Null);
                    m.insert("taker".to_string(), Value::Int(0));
                    m.insert("maker".to_string(), Value::Int(0));
                    m.insert("percentage".to_string(), Value::Bool(true));
                    m.insert("tierBased".to_string(), Value::Bool(false));
                    m.insert("feeSide".to_string(), Value::Str("get".into()));
                    m.insert("precision".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("amount".to_string(), tickSize.clone());
        m.insert("price".to_string(), tickSize.clone());
    m
}));
                    m.insert("limits".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("leverage".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("min".to_string(), Value::Int(1));
        m.insert("max".to_string(), Value::Int(1));
    m
}));
        m.insert("amount".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("min".to_string(), orderMinSize);
        m.insert("max".to_string(), Value::Null);
    m
}));
        m.insert("price".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("min".to_string(), tickSize);
        m.insert("max".to_string(), priceMax);
    m
}));
        m.insert("cost".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("min".to_string(), Value::Null);
        m.insert("max".to_string(), Value::Null);
    m
}));
    m
}));
                    m.insert("outcomes".to_string(), Value::from(outcomes));
                    m.insert("info".to_string(), market);
                    m.insert("created".to_string(), Value::Null);
                m
            }));
        }
        }
        return Value::from(result);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#fetchOutcome
 * @description resolves a single outcome by its CLOB token id in one request, so a cache miss
 * (a bare token id, or a valid outcome on a market outside the top-volume cold cache) recovers
 * instead of throwing BadSymbol. an outcome HANDLE ("MARKET:LABEL") carries no token id, so it
 * falls back to the base bulk load
 * @param {string} outcomeSymbol the outcome token id or handle
 * @returns {object} the resolved outcome object
 */
    pub async fn fetch_outcome(&mut self, mut outcomeSymbol: Value) -> Value {
        // a bare CLOB token id has no ':' (an outcome handle is always "MARKET:LABEL") and no
        // searchable words — outcomeSearchQuery returns undefined only for id-like inputs, so
        // word-bearing junk like 'BTC/USDT' skips the gamma by-id lookup (which 422s on
        // non-ids) and falls through to the search path and its local BadSymbol below.
        // absence must be `< 0` — the php transpiler maps that to `=== false`, while a literal
        // `=== -1` passes through and never matches mb_strpos's false return
        if (!outcomeSymbol.as_str().unwrap_or("").contains(":")) && (self.outcome_search_query(outcomeSymbol.clone()) == Value::Null) {
            let mut response: Value = self.gamma_public_get_markets(&[Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("clob_token_ids".to_string(), outcomeSymbol.clone());
                m
            })]).await;
            let mut rawMarkets: Value = (if (response != Value::Null) { response } else { Value::from(vec![]) });
            let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
            if rawMarketsLength > ((0i64) as f64) {
                if (self.markets.clone() == Value::Null) {
                    { let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
                }
                let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("markets".to_string(), rawMarkets);
                    m
                })).as_array().cloned().unwrap_or_default();
                let mut ccxtMarketsLength: f64 = ((ccxtMarkets.len() as i64) as f64);
                {
                                        let mut i: Value = Value::Int(0);
                    let mut __for_first_1425: bool = true;
                    while { if !__for_first_1425 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1425 = false; i.as_f64().unwrap_or(f64::NAN) < ccxtMarketsLength } {
                    let mut mkt: Value = ccxtMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
                    if (mkt == Value::Null) {
                        panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcome() could not resolve mkt".into()))));
                    }
                    add_element_to_object(&mut self.markets, &mkt.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), mkt.clone());
                }
                }
                self.populate_outcomes();
                if (self.safe_dict(self.exchange.outcomes_by_id.clone(), outcomeSymbol.clone(), &[]) != Value::Null) {
                    return self.safe_dict(self.exchange.outcomes_by_id.clone(), outcomeSymbol.clone(), &[]);
                }
            }
        }
        return self.super_fetch_outcome(outcomeSymbol).await;

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#fetchOutcomes
 * @description resolves several uncached outcomes at once — bare CLOB token ids are batched into gamma markets requests (repeated clob_token_ids params, 50 per request to keep the URL bounded); handle-shaped symbols fall back to the single fetch and its search path
 * @see https://docs.polymarket.com/api-reference/markets/list-markets
 * @param {string[]} outcomeSymbols outcome token ids or handles
 * @returns {object} the outcome cache
 */
    pub async fn fetch_outcomes(&mut self, mut outcomeSymbols: Value) -> Value {
        let __outcomeSymbols_empty = Vec::new();
        let outcomeSymbols = outcomeSymbols.as_array().unwrap_or(&__outcomeSymbols_empty);
        let mut tokenIds: Value = Value::from(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1426: bool = true;
            while { if !__for_first_1426 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1426 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
            let mut outcomeSymbol: Value = outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            // only id-like symbols (no ':', no searchable words) belong in the by-id batch —
            // see the same gate in fetchOutcome. absence must be `< 0` — the php transpiler
            // maps that to `=== false`, while a literal `=== -1` passes through and never
            // matches mb_strpos's false return
            if (!outcomeSymbol.as_str().unwrap_or("").contains(":")) && (self.outcome_search_query(outcomeSymbol.clone()) == Value::Null) {
                if let Value::Arr(__a) = &mut tokenIds { std::sync::Arc::make_mut(__a).push(outcomeSymbol); }
            }
        }
        }
        let mut tokenIdsLength: Value = Value::Int(tokenIds.len() as i64);
        if tokenIdsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
            if (self.markets.clone() == Value::Null) {
                { let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
            }
            // token ids are ~78 chars each, so cap the batch to keep the URL under common limits
            let mut chunkSize: Option<i64> = self.safe_integer_k(self.options.clone(), "fetchOutcomesBatchSize", &[Value::Int(50)]).as_i64();
            let mut startIndex: Value = Value::Int(0);
            while startIndex.as_f64().unwrap_or(f64::NAN) < tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
                let mut endIndex: Value = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
                if endIndex.as_f64().unwrap_or(f64::NAN) > tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
                    endIndex = tokenIdsLength.clone();
                }
                let mut chunk: Vec<Value> = Vec::new();
                {
                                        let mut i: Value = startIndex.clone();
                    let mut __for_first_1427: bool = true;
                    while { if !__for_first_1427 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
                        } __for_first_1427 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
                    chunk.push(get_value(&tokenIds, &i));
                }
                }
                // gamma matches repeated clob_token_ids params — comma-joined ids are rejected
                // with a validation error, so the list rides through urlencodeWithArrayRepeat
                let mut response: Value = self.gamma_public_get_markets(&[Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("clob_token_ids".to_string(), Value::from(chunk));
                        m.insert("limit".to_string(), Value::from(chunkSize));
                    m
                })]).await;
                let mut rawMarkets: Value = (if (response != Value::Null) { response } else { Value::from(vec![]) });
                let mut ccxtMarkets: Vec<Value> = self.parse_event_to_markets(Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("markets".to_string(), rawMarkets);
                    m
                })).as_array().cloned().unwrap_or_default();
                {
                                        let mut i: i64 = 0;
                    let mut __for_first_1428: bool = true;
                    while { if !__for_first_1428 { i += 1; } __for_first_1428 = false; i < (ccxtMarkets.len() as i64) } {
                    let mut mkt: Value = ccxtMarkets.get(i as usize).cloned().unwrap_or(Value::Null);
                    if (mkt == Value::Null) {
                        panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchOutcomes() could not resolve mkt".into()))));
                    }
                    add_element_to_object(&mut self.markets, &mkt.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), mkt.clone());
                }
                }
                startIndex = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
            }
            self.populate_outcomes();
        }
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1429: bool = true;
            while { if !__for_first_1429 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1429 = false; i.as_f64().unwrap_or(f64::NAN) < ((outcomeSymbols.len() as i64) as f64) } {
            if !(self.has_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).as_bool() == Some(true)) {
                self.fetch_outcome(outcomeSymbols.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)).await;
            }
        }
        }
        return self.exchange.outcomes.clone();

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchTicker
 * @description fetches the current mid-price and best bid/ask for a single outcome token
 * @see https://docs.polymarket.com/api-reference/data/get-midpoint-price
 * @see https://docs.polymarket.com/api-reference/market-data/get-order-book
 * @see https://docs.polymarket.com/api-reference/data/get-last-trade-price
 * @param {string} outcome unified outcome like TRUMP_DANCE_TODAY_997:YES or an outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
 */
    pub async fn fetch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
        let mut promises: Value = Value::from(vec![self.clob_public_get_midpoint(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
    m
})]).await, self.clob_public_get_book(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("token_id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
    m
})]).await, self.clob_public_get_last_trade_price(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
    m
})]).await]);
        let midpointResponsebookResponselastTradeResponseVariable: Vec<Value> = promise_all(&promises).await.as_array().cloned().unwrap_or_default();
        let mut midpointResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(0).cloned().unwrap_or(Value::Null);
        let mut bookResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(1).cloned().unwrap_or(Value::Null);
        let mut lastTradeResponse: Value = midpointResponsebookResponselastTradeResponseVariable.get(2).cloned().unwrap_or(Value::Null);
        let mut response: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("midpoint".to_string(), midpointResponse);
                m.insert("book".to_string(), bookResponse);
                m.insert("lastTrade".to_string(), lastTradeResponse);
            m
        });
        return self.parse_prediction_ticker(Value::Map(response), &[outcomeObj]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchTickers
 * @description fetches tickers for multiple outcome tokens at once using the batched CLOB book, midpoint and last-trade-price endpoints (200 per request trio)
 * @see https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body
 * @see https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-request-body
 * @see https://docs.polymarket.com/api-reference/data/get-last-trades-prices
 * @param {string[]} outcomes unified outcomes or outcome token ids — required: polymarket has no endpoint returning all tickers at once, so an unscoped call is not supported
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a dictionary of [prediction ticker structures](https://docs.ccxt.com/#/?id=prediction-ticker-structure) indexed by outcome
 */
    pub async fn fetch_tickers(&mut self, optional_args: &[Value]) -> Value {
        let mut outcomes = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if (outcomes == Value::Null) {
            panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" fetchTickers() requires an outcomes argument — the venue has no all-tickers endpoint; pass the outcome handles or token ids to fetch (discover them via fetchEvents ())".into()))));
        }
        // batch-resolve the uncached outcomes (one gamma request per 50 token ids)
        self.load_outcomes(&[outcomes.clone()]).await;
        let mut targets: Vec<Value> = Vec::new();
        {
                        let mut oi: i64 = 0;
            let mut __for_first_1430: bool = true;
            while { if !__for_first_1430 { oi += 1; } __for_first_1430 = false; oi < (outcomes.len() as i64) } {
            targets.push(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(oi as usize).cloned().unwrap_or(Value::Null));
        }
        }
        let mut outcomesByTokenId: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut tokenIds: Value = Value::from(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1431: bool = true;
            while { if !__for_first_1431 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1431 = false; i.as_f64().unwrap_or(f64::NAN) < ((targets.len() as i64) as f64) } {
            let mut outcomeObj: Value = self.outcome(targets.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
            let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
            if (tokenId.is_some()) && !(matches!((&outcomesByTokenId, &tokenId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                if let Value::Dict(__d) = &mut outcomesByTokenId { std::sync::Arc::make_mut(__d).insert(tokenId.as_deref().unwrap_or("null").to_string(), outcomeObj.clone()); }
                if let Value::Arr(__a) = &mut tokenIds { std::sync::Arc::make_mut(__a).push(tokenId.map(Value::from).unwrap_or(Value::Null)); }
            }
        }
        }
        let mut chunkSize: Option<i64> = self.safe_integer_k(self.options.clone(), "fetchTickersBatchSize", &[Value::Int(200)]).as_i64();
        let mut result: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut tokenIdsLength: Value = Value::Int(tokenIds.len() as i64);
        let mut startIndex: Value = Value::Int(0);
        while startIndex.as_f64().unwrap_or(f64::NAN) < tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
            let mut endIndex: Value = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
            if endIndex.as_f64().unwrap_or(f64::NAN) > tokenIdsLength.as_f64().unwrap_or(f64::NAN) {
                endIndex = tokenIdsLength.clone();
            }
            let mut bookParams: Vec<Value> = Vec::new();
            {
                                let mut i: Value = startIndex.clone();
                let mut __for_first_1432: bool = true;
                while { if !__for_first_1432 { i = (match (&(i), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x + y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 + *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x + *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x + y), _ => Value::Null });
                    } __for_first_1432 = false; i.as_f64().unwrap_or(f64::NAN) < endIndex.as_f64().unwrap_or(f64::NAN) } {
                bookParams.push(Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("token_id".to_string(), get_value(&tokenIds, &i));
                    m
                }));
            }
            }
            let mut promises: Value = Value::from(vec![self.clob_public_post_books(&[Value::from(bookParams.clone())]).await, self.clob_public_post_midpoints(&[Value::from(bookParams.clone())]).await, self.clob_public_post_last_trades_prices(&[Value::from(bookParams)]).await]);
            let mut responses: Vec<Value> = promise_all(&promises).await.as_array().cloned().unwrap_or_default();
            let mut booksResponse: Value = responses.get(0).cloned().unwrap_or(Value::Null);
            let mut midpoints: Value = responses.get(1).cloned().unwrap_or(Value::Null);
            let mut lastTradesResponse: Value = responses.get(2).cloned().unwrap_or(Value::Null);
            let mut booksIsArray: bool = matches!(&booksResponse, Value::Arr(_));
            let mut books: Value = (if (booksIsArray) { booksResponse } else { Value::from(vec![]) });
            let mut lastTradesIsArray: bool = matches!(&lastTradesResponse, Value::Arr(_));
            let mut lastTrades: Value = (if (lastTradesIsArray) { lastTradesResponse } else { Value::from(vec![]) });
            let mut lastTradesByTokenId: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                m
            });
            let mut lastTradesLength: f64 = ((lastTrades.len() as i64) as f64);
            {
                                let mut li: Value = Value::Int(0);
                let mut __for_first_1433: bool = true;
                while { if !__for_first_1433 { if let Value::Int(n) = &mut li { *n += 1; } } __for_first_1433 = false; li.as_f64().unwrap_or(f64::NAN) < lastTradesLength } {
                let mut lastTradeEntry: Value = lastTrades.as_array().and_then(|__arr| match &li { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
                let mut lastTradeTokenId: Option<String> = self.safe_string_k_opt(lastTradeEntry.clone(), "token_id", &[]);
                if (lastTradeTokenId.is_some()) {
                    lastTradesByTokenId.insert(lastTradeTokenId.as_deref().unwrap_or("null").to_string(), lastTradeEntry);
                }
            }
            }
            let mut booksLength: f64 = ((books.len() as i64) as f64);
            {
                                let mut i: Value = Value::Int(0);
                let mut __for_first_1434: bool = true;
                while { if !__for_first_1434 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1434 = false; i.as_f64().unwrap_or(f64::NAN) < booksLength } {
                let mut book: Value = books.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
                let mut tokenId: Value = self.safe_string_k(book.clone(), "asset_id", &[]);
                if (tokenId == Value::Null) || !(matches!((&outcomesByTokenId, &tokenId), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                    continue;
                }
                let mut outcomeObj: Value = (if let (Some(__m), Some(__k)) = (outcomesByTokenId.as_map(), tokenId.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
                let mut mid: Option<String> = self.safe_string_opt(midpoints.clone(), tokenId.clone(), &[]);
                let mut tickerInput: indexmap::IndexMap<String, Value> = ({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("midpoint".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("mid".to_string(), mid.map(Value::from).unwrap_or(Value::Null));
    m
}));
                        m.insert("book".to_string(), book);
                        m.insert("lastTrade".to_string(), self.safe_dict(Value::Map(lastTradesByTokenId.clone()), tokenId.clone(), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]));
                    m
                });
                let mut ticker: Value = self.parse_prediction_ticker(Value::Map(tickerInput), &[outcomeObj]);
                let mut symbolKey: Value = self.safe_string_k(ticker.clone(), "outcome", &[tokenId]);
                result.insert(crate::runtime::stringify_param(&symbolKey), ticker);
            }
            }
            startIndex = self.sum(&[startIndex.clone(), Value::from(chunkSize)]);
        }
        return Value::Map(result);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parsePredictionTicker
 * @description parses a combined midpoint + order book response into a unified ticker object
 * @param {object} ticker a dict with midpoint and book entries
 * @param {object} [market] the outcome object the ticker belongs to
 * @returns {object} a [prediction ticker structure](https://docs.ccxt.com/#/?id=prediction-ticker-structure)
 */
    pub fn parse_prediction_ticker(&self, mut ticker: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        //
        //     {
        //         "midpoint": {
        //             "mid": "0.9985"
        //         },
        //         "book": {
        //             "market": "0x2d55f622bc12e23dc1f1bb4db8360c28c92155f9376bf73953c0756ee1387b2f",
        //             "asset_id": "16718041887881762329859205887704087070587186248220606272297433440108449709696",
        //             "timestamp": "1777344471023",
        //             "hash": "11aa0feabec970de83b04a2c0d50a7639e144f43",
        //             "bids": [
        //                 {
        //                     "price": "0.45",
        //                     "size": "100"
        //                 },
        //             ],
        //             "asks": [
        //                 {
        //                     "price": "0.46",
        //                     "size": "150"
        //                 },
        //             ],
        //             "min_order_size": "5",
        //             "tick_size": "0.001",
        //             "neg_risk": false,
        //             "last_trade_price": "0.998"
        //         },
        //         "lastTrade": {
        //             "price": "0.46",
        //             "side": "BUY"
        //         }
        //     }
        //
        let mut midpointData: Value = self.safe_dict_k(ticker.clone(), "midpoint", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut bookData: Value = self.safe_dict_k(ticker.clone(), "book", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut mid: Value = self.safe_number_k(midpointData, "mid", &[]);
        let mut bids: Value = self.safe_list_k(bookData.clone(), "bids", &[Value::from(vec![])]);
        let mut asks: Value = self.safe_list_k(bookData.clone(), "asks", &[Value::from(vec![])]);
        let mut bidsLength: Value = Value::Int(bids.len() as i64);
        let mut asksLength: Value = Value::Int(asks.len() as i64);
        // the CLOB book endpoint returns levels sorted away from the touch (bids ascending, asks descending), so the best level is the last entry
        let mut bestBid: Value = (if (bidsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) { bids.as_array().and_then(|__arr| match &((match (&(bidsLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x),
            Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null) } else { Value::Null });
        let mut bestAsk: Value = (if (asksLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) { asks.as_array().and_then(|__arr| match &((match (&(asksLength), &(Value::Int(1))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x),
            Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })) { Value::Int(__n) if *__n >= 0 => __arr.get(*__n as usize), _ => None }).cloned().unwrap_or(Value::Null) } else { Value::Null });
        // book.last_trade_price is market-level and denominated in whichever token traded last —
        // on the complementary token it is the OTHER side's price, so only the per-token
        // last-trade-price endpoint value is usable here; that endpoint reports "0" for a
        // never-traded token, which also falls back to the mid
        let mut lastTradeData: Value = self.safe_dict_k(ticker.clone(), "lastTrade", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut last: Value = self.safe_number_k(lastTradeData, "price", &[]);
        if (last == Value::Null) || (last.as_f64() == Some(0.0)) {
            last = mid.clone();
        }
        let mut outcome: Value = self.safe_outcome_symbol(Value::Null, &[market.clone()]);
        let mut timestamp: Option<i64> = self.safe_integer_k(bookData, "timestamp", &[]).as_i64();
        let mut quoteVolume: Value = Value::Null;
        if (market != Value::Null) {
            quoteVolume = self.safe_number2(market.as_map().and_then(|__m| __m.get("info")).cloned().unwrap_or(Value::Null), Value::Str("volume24hr".into()), Value::Str("volume".into()), &[]);
        }
        return self.safe_prediction_ticker(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("outcome".to_string(), outcome);
        m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
        m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
        m.insert("timestamp".to_string(), Value::from(timestamp));
        m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
        m.insert("high".to_string(), Value::Null);
        m.insert("low".to_string(), Value::Null);
        m.insert("bid".to_string(), self.safe_number_k(bestBid.clone(), "price", &[]));
        m.insert("bidVolume".to_string(), self.safe_number_k(bestBid, "size", &[]));
        m.insert("ask".to_string(), self.safe_number_k(bestAsk.clone(), "price", &[]));
        m.insert("askVolume".to_string(), self.safe_number_k(bestAsk, "size", &[]));
        m.insert("vwap".to_string(), Value::Null);
        m.insert("open".to_string(), Value::Null);
        m.insert("close".to_string(), last.clone());
        m.insert("last".to_string(), last);
        m.insert("previousClose".to_string(), Value::Null);
        m.insert("change".to_string(), Value::Null);
        m.insert("percentage".to_string(), Value::Null);
        m.insert("average".to_string(), mid);
        m.insert("baseVolume".to_string(), Value::Null);
        m.insert("quoteVolume".to_string(), quoteVolume);
        m.insert("info".to_string(), ticker);
    m
}), &[market]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOrderBook
 * @description fetches the CLOB order book for a single outcome token
 * @see https://docs.polymarket.com/api-reference/market-data/get-order-book
 * @param {string} outcome unified outcome or outcome token id
 * @param {int} [limit] not used by polymarket fetchOrderBook
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction order book structure](https://docs.ccxt.com/#/?id=prediction-order-book-structure)
 */
    pub async fn fetch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut limit = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
        let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
            m
        });
        let __ws_arg_2 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_public_get_book(&[__ws_arg_2]).await;
        //
        //     {
        //         "market": "0x42d42b30124ed2d93800358dfd1d48253114e4d58cff15cb765cd0c69956555f",
        //         "asset_id": "53471586309106256293075593293890793127405137223521910882276033765569397092350",
        //         "timestamp": "1777541385018",
        //         "hash": "bfb61f58dab4055d956eb5e758dbc9101c9a4e6c",
        //         "bids": [
        //             { "price": "0.001", "size": "3147.19" },
        //             { "price": "0.002", "size": "1432.11" }
        //         ],
        //         "asks": [
        //             { "price": "0.999", "size": "73.68" },
        //             { "price": "0.998", "size": "7" }
        //         ],
        //         "min_order_size": "5",
        //         "tick_size": "0.001",
        //         "neg_risk": false,
        //         "last_trade_price": "0.002"
        //     }
        //
        let mut timestamp: Value = self.safe_integer_k(response.clone(), "timestamp", &[]);
        let mut orderbook: Value = self.parse_order_book(response, self.safe_outcome_symbol(outcome, &[outcomeObj.clone()]), &[timestamp, Value::Str("bids".into()), Value::Str("asks".into()), Value::Str("price".into()), Value::Str("size".into())]);
        return self.safe_prediction_order_book(orderbook, &[outcomeObj]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOHLCV
 * @description fetches price history ticks for a single outcome token and buckets them client-side into OHLCV candles, snapping tick timestamps to the candle boundary
 * @see https://docs.polymarket.com/api-reference/markets/get-prices-history
 * @param {string} outcome unified outcome or outcome token id
 * @param {string} timeframe the length of time each candle represents
 * @param {int} [since] timestamp in ms of the earliest candle to fetch
 * @param {int} [limit] the maximum number of candles to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {int[][]} a list of candles ordered as timestamp, open, high, low, close, volume
 */
    pub async fn fetch_ohlcv(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".into()));
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if !(matches!((&self.timeframes, &timeframe), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
            // hoisted keys list: chaining join onto Object.keys breaks the python transpiler
            let mut supportedKeys: Value = Value::Array(self.timeframes.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default());
            panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOHLCV() unsupported timeframe ".into())).into()), timeframe).into()), Value::Str(", supported timeframes are ".into())).into()),
                Value::Str(supportedKeys.as_array().map(|__a| __a.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(", ")).unwrap_or_default().into()))));
        }
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj, "outcomeId", &[]);
        let mut fidelityMin: Value = self.safe_integer(self.timeframes.clone(), timeframe, &[Value::Int(1)]); // fidelity in minutes
        let mut nowS: Value = self.seconds();
        let mut startS: Value = Value::Null;
        let mut endS: Value = nowS.clone();
        if (since != Value::Null) {
            startS = self.parse_to_int((match ((since).as_f64(), (Value::Int(1000)).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }));
            if (limit != Value::Null) {
                let mut endBound: Value = self.sum(&[startS.clone(), (match (&((match (&(limit), &(fidelityMin)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y),
                    _ => Value::Null })), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })]);
                endS = (if (endBound.as_f64().unwrap_or(f64::NAN) < nowS.as_f64().unwrap_or(f64::NAN)) { endBound } else { nowS.clone() });
            }
        }  else {
            let mut barCount: Value = (if (limit != Value::Null) { limit.clone() } else { Value::Int(100) });
            startS = (match (&(nowS), &(((match (&((match (&(barCount), &(fidelityMin)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })),
                &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })))) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y),
                (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
        }
        // the venue rejects startTs/endTs spans over 15 days ("interval is too long")
        // regardless of fidelity, so clamp the window to the cap: keep the requested
        // `since` anchor (oldest chunk first, consistent with since/limit paging),
        // or the most recent window when no `since` was given
        let mut maxWindow: Value = self.safe_integer_k(self.options.clone(), "maxPricesHistoryWindow", &[Value::Int(1296000)]);
        if ((match (&(endS), &(startS)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null })).as_f64().unwrap_or(f64::NAN) > maxWindow.as_f64().unwrap_or(f64::NAN) {
            if (since != Value::Null) {
                endS = self.sum(&[startS.clone(), maxWindow.clone()]);
            }  else {
                startS = (match (&(endS), &(maxWindow)) { (Value::Int(x), Value::Int(y)) => Value::Int(x - y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 - *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x - *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x - y), _ => Value::Null });
            }
        }
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("market".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
                m.insert("fidelity".to_string(), fidelityMin.clone());
                m.insert("startTs".to_string(), startS);
                m.insert("endTs".to_string(), endS);
            m
        });
        let __ws_arg_3 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_public_get_prices_history(&[__ws_arg_3]).await;
        //
        //     {
        //         "history": [
        //             { "t": "1776043119", "p": "0.265" },
        //         ]
        //     }
        //
        let mut history: Value = self.safe_list_k(response, "history", &[Value::from(vec![])]);
        // Client-side bucket aggregation: snap each tick to its candle boundary and
        // build open/high/low/close/volume. Assumes history is sorted ascending by time.
        let mut resolutionMs: Value = (match (&((match (&(fidelityMin), &(Value::Int(60))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null })),
            &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
        let mut buckets: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        {
                        let mut i: i64 = 0;
            let mut __for_first_1435: bool = true;
            while { if !__for_first_1435 { i += 1; } __for_first_1435 = false; i < (history.len() as i64) } {
            let mut item: Value = self.safe_dict(history.clone(), Value::Int(i), &[]);
            let mut t: Value = self.safe_integer_k(item.clone(), "t", &[]);
            let mut price: Value = self.safe_number_k(item.clone(), "p", &[]);
            if (t == Value::Null) || (price == Value::Null) {
                continue;
            }
            let mut rawMs: Value = (match (&(t), &(Value::Int(1000))) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
            let mut snappedMs: Value = (match (&(self.parse_to_int((match ((rawMs).as_f64(), (resolutionMs).as_f64()) { (Some(x), Some(y)) if y != 0.0 => Value::Float(x / y), _ => Value::Null }))), &(resolutionMs)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x),
                Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
            // the venue supplies no candle volume ({t, p} ticks only) — leave it undefined
            // rather than fabricating a 0, probing s/v in case the field ever appears
            let mut vol: Value = self.safe_number_k(item.clone(), "s", &[]);
            if (vol == Value::Null) {
                vol = self.safe_number_k(item, "v", &[]);
            }
            let mut bucketKey: Value = Value::Str(format!("{}", snappedMs).into());
            if !(matches!((&buckets, &bucketKey), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                if let Value::Dict(__d) = &mut buckets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&bucketKey), Value::from(vec![snappedMs, price.clone(), price.clone(), price.clone(), price.clone(), vol.clone()])); }
            }  else {
                let mut candle: Value = self.safe_list(buckets.clone(), bucketKey.clone(), &[Value::from(vec![])]);
                { let __be_tmp = crate::runtime::Math::max(&get_value(&candle, &Value::Int(2)), &price); add_element_to_object(&mut candle, &Value::Int(2), __be_tmp); }; // high
                { let __be_tmp = crate::runtime::Math::min(&get_value(&candle, &Value::Int(3)), &price); add_element_to_object(&mut candle, &Value::Int(3), __be_tmp); }; // low
                add_element_to_object(&mut candle, &Value::Int(4), price); // close (last tick wins)
                if (vol != Value::Null) {
                    let mut prevVol: Value = candle.as_array().and_then(|__arr| __arr.get(5)).cloned().unwrap_or(Value::Null);
                    add_element_to_object(&mut candle, &Value::Int(5), (if (prevVol == Value::Null) { vol.clone() } else { self.sum(&[prevVol, vol]) })); // volume
                }
                if let Value::Dict(__d) = &mut buckets { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&bucketKey), candle); }; // reassign after mutation, php arrays are value types
            }
        }
        }
        let mut bucketKeys: Vec<Value> = Value::Array(buckets.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
        let mut unsortedCandles: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1436: bool = true;
            while { if !__for_first_1436 { i += 1; } __for_first_1436 = false; i < (bucketKeys.len() as i64) } {
            unsortedCandles.push(buckets.as_map().and_then(|__m| bucketKeys.get(i as usize).cloned().unwrap_or(Value::Null).as_str().and_then(|__k| __m.get(__k))).cloned().unwrap_or(Value::Null));
        }
        }
        let mut candles: Value = self.sort_by(Value::from(unsortedCandles), Value::Int(0), &[]);
        let mut candlesLength: f64 = ((candles.len() as i64) as f64);
        if (limit != Value::Null) && (candlesLength > limit.as_f64().unwrap_or(f64::NAN)) {
            return self.array_slice(candles.clone(), (match &(limit) { Value::Int(x) => Value::Int(-x), Value::Float(x) => Value::Float(-x), _ => Value::Null }), &[]);
        }
        return candles;

    Value::Null
}

    pub fn parse_ohlcv(&self, mut ohlcv: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        // Unused: fetchOHLCV performs client-side bucket aggregation directly.
        //
        //     {
        //         "t": "1776043119",
        //         "p": "0.265"
        //     }
        //
        let mut price: Value = self.safe_number_k(ohlcv.clone(), "p", &[]);
        return Value::from(vec![self.safe_timestamp_k(ohlcv, "t", &[]), price.clone(), price.clone(), price.clone(), price.clone(), Value::Null]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchTime
 * @description fetches the current timestamp from the CLOB server
 * @see https://docs.polymarket.com/api-reference/data/get-server-time
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {int} the current server time in milliseconds
 */
    pub async fn fetch_time(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut response: Value = self.clob_public_get_time(&[params]).await;
        //
        //     1781273248
        //
        let mut result: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("serverTime".to_string(), response);
            m
        });
        return self.safe_timestamp_k(Value::Map(result), "serverTime", &[]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchStatus
 * @description fetches the gamma API health status
 * @see https://docs.polymarket.com/api-reference/events/list-events
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [status structure](https://docs.ccxt.com/#/?id=exchange-status-structure)
 */
    pub async fn fetch_status(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut response: Value = self.gamma_public_get_status(&[params]).await;
        //
        //     OK
        //
        let mut ok: bool = (response.as_str() == Some("OK")) || (response.as_str() == Some("ok"));
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("status".to_string(), (if ok { Value::Str("ok".into()) } else { Value::Str("maintenance".into()) }));
        m.insert("updated".to_string(), Value::Null);
        m.insert("eta".to_string(), Value::Null);
        m.insert("url".to_string(), Value::Null);
        m.insert("info".to_string(), response);
    m
});

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOpenInterest
 * @description fetches the open interest of a prediction market outcome
 * @see https://docs.polymarket.com/api-reference/misc/get-open-interest
 * @param {string} outcome unified outcome or outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} an [open interest structure](https://docs.ccxt.com/#/?id=open-interest-structure)
 */
    pub async fn fetch_open_interest(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome.clone(), &[]).await;
        let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut conditionId: Option<String> = self.safe_string_k_opt(outcomeInfo, "conditionId", &[]);
        if (conditionId.is_none()) {
            panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchOpenInterest() requires outcome.info.conditionId for ".into())).into()), outcome)));
        }
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("market".to_string(), conditionId.map(Value::from).unwrap_or(Value::Null));
            m
        });
        let __ws_arg_4 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.data_public_get_oi(&[__ws_arg_4]).await;
        //
        //     [ { "market": "0x7976b8...92", "value": 4925662.470476 } ]
        //
        let mut first: Value = self.safe_dict(response, Value::Int(0), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        return self.parse_prediction_open_interest(first, &[outcomeObj]);

    Value::Null
}

    pub fn parse_prediction_open_interest(&self, mut interest: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        //
        //     { "market": "0x7976b8...92", "value": 4925662.470476 }
        //
        let mut openInterest: Value = self.safe_open_interest(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("symbol".to_string(), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
        m.insert("openInterestAmount".to_string(), Value::Null);
        m.insert("openInterestValue".to_string(), self.safe_number_k(interest.clone(), "value", &[]));
        m.insert("baseVolume".to_string(), Value::Null);
        m.insert("quoteVolume".to_string(), Value::Null);
        m.insert("timestamp".to_string(), Value::Null);
        m.insert("datetime".to_string(), Value::Null);
        m.insert("info".to_string(), interest);
    m
}), &[market.clone()]);
        add_element_to_object(&mut openInterest, &Value::Str("outcome".into()), self.safe_outcome_symbol(Value::Null, &[market.clone()]));
        add_element_to_object(&mut openInterest, &Value::Str("outcomeId".into()), self.safe_string_k(market.clone(), "outcomeId", &[]));
        add_element_to_object(&mut openInterest, &Value::Str("market".into()), self.safe_string_k(market, "market", &[]));
        remove(&mut openInterest, &Value::Str("symbol".into()));
        return openInterest;

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchTradingFee
 * @description fetches the base fee rate for a prediction market outcome token
 * @see https://docs.polymarket.com/api-reference/market-data/get-fee-rate
 * @param {string} outcome unified outcome or outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [fee structure](https://docs.ccxt.com/#/?id=fee-structure)
 */
    pub async fn fetch_trading_fee(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("token_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
            m
        });
        let __ws_arg_5 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_public_get_fee_rate(&[__ws_arg_5]).await;
        //
        //     { "base_fee": 30 }   // base fee in basis points
        //
        let mut baseFeeBps: Option<String> = self.safe_string_k_opt(response.clone(), "base_fee", &[]);
        let mut rate: Value = (if (baseFeeBps.is_some()) { self.parse_number(crate::precise::Precise::stringDiv(&baseFeeBps.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("10000".into())), &[]) } else { Value::Null });
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("info".to_string(), response);
        m.insert("outcome".to_string(), self.safe_outcome_symbol(Value::Null, &[outcomeObj.clone()]));
        m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
        m.insert("maker".to_string(), rate.clone());
        m.insert("taker".to_string(), rate);
        m.insert("percentage".to_string(), Value::Bool(true));
        m.insert("tierBased".to_string(), Value::Bool(false));
    m
});

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchTrades
 * @description fetches public trade history for a single outcome token from the data API
 * @see https://docs.polymarket.com/api-reference/core/get-trades-for-a-user-or-markets
 * @param {string} outcome unified outcome or outcome token id
 * @param {int} [since] not used by polymarket fetchTrades
 * @param {int} [limit] the maximum number of trades to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
 */
    pub async fn fetch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
        let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj, "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut conditionId: Option<String> = self.safe_string_k_opt(outcomeInfo, "conditionId", &[]);
        if (conditionId.is_none()) {
            panic!("{}", crate::exchange_errors::bad_request(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" fetchTrades() requires outcome.info.conditionId for an outcome ".into())).into()), tokenId)));
        }
        // the endpoint filters by market conditionId (which spans BOTH outcome tokens), then we narrow
        // to the requested token client-side below. applying the user's `limit` to this request and
        // THEN filtering can return 0 rows on an active outcome (if the top `limit` market trades are
        // all the other token). over-fetch a large page here; the user's `limit` is applied AFTER the
        // token filter by parsePredictionTrades
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("market".to_string(), conditionId.clone().map(Value::from).unwrap_or(Value::Null));
            m
        });
        request.insert("limit".into(), self.safe_integer_k(self.options.clone(), "tradesPageSize", &[Value::Int(500)]));
        let __ws_arg_6 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.data_public_get_trades(&[__ws_arg_6]).await;
        let mut rawTrades: Value = (if (matches!(&response, Value::Arr(_))) { response.clone() } else { self.safe_list_k(response, "data", &[Value::from(vec![])]) });
        let mut filteredTrades: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1437: bool = true;
            while { if !__for_first_1437 { i += 1; } __for_first_1437 = false; i < (rawTrades.len() as i64) } {
            let mut trade: Value = rawTrades.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
            let mut tradeAsset: Value = self.safe_string_k(trade.clone(), "asset", &[]);
            if (tradeAsset == tokenId) {
                filteredTrades.push(trade);
            }
        }
        }
        return self.parse_prediction_trades(Value::from(filteredTrades), &[Value::Null, since, limit]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchMyTrades
 * @description fetches the authenticated user's trade history from the CLOB, optionally filtered by outcome token
 * @see https://docs.polymarket.com/api-reference/trade/get-trades
 * @param {string} [outcome] unified outcome or outcome token id
 * @param {int} [since] the earliest time in ms to fetch trades for
 * @param {int} [limit] the maximum number of trades to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
 */
    pub async fn fetch_my_trades(&mut self, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            outcomeObj = self.load_outcome(outcome, &[]).await;
            request.insert("asset_id".into(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
        }
        let __ws_arg_7 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_private_get_data_trades(&[__ws_arg_7]).await;
        let mut rawTrades: Value = (if (matches!(&response, Value::Arr(_))) { response.clone() } else { self.safe_list_k(response, "data", &[Value::from(vec![])]) });
        return self.parse_prediction_trades(rawTrades, &[outcomeObj, since, limit]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOrderTrades
 * @description fetches all the trades made from a single order
 * @see https://docs.polymarket.com/api-reference/trade/get-trades
 * @param {string} id the order id
 * @param {string} [outcome] unified outcome or outcome token id to narrow the lookup
 * @param {int} [since] the earliest time in ms to fetch trades for
 * @param {int} [limit] the maximum number of trades to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
 */
    pub async fn fetch_order_trades(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        // the /data/trades endpoint has no order filter, so fetch the user's trades and keep
        // the ones where this order was the taker or one of the matched makers
        let mut trades: Value = self.fetch_my_trades(&[outcome, Value::Null, Value::Null, params]).await;
        let mut result: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1439: bool = true;
            while { if !__for_first_1439 { i += 1; } __for_first_1439 = false; i < (trades.len() as i64) } {
            let mut trade: Value = trades.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
            let mut info: Value = self.safe_dict_k(trade.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            let mut belongs: bool = (self.safe_string_k(trade.clone(), "order", &[]).as_str() == id.as_str()) || (self.safe_string_k(info.clone(), "taker_order_id", &[]).as_str() == id.as_str());
            let mut makerOrders: Value = self.safe_list_k(info, "maker_orders", &[Value::from(vec![])]);
            {
                                let mut j: i64 = 0;
                let mut __for_first_1438: bool = true;
                while { if !__for_first_1438 { j += 1; } __for_first_1438 = false; j < (makerOrders.len() as i64) } {
                let mut makerOrder: Value = self.safe_dict(makerOrders.clone(), Value::Int(j), &[]);
                if (self.safe_string_k(makerOrder, "order_id", &[]).as_str() == id.as_str()) {
                    belongs = true;
                }
            }
            }
            if belongs {
                result.push(trade);
            }
        }
        }
        return self.filter_by_since_limit(Value::from(result), &[since, limit]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parsePredictionTrade
 * @description parses a raw data API trade object into a unified trade object
 * @param {object} trade the raw trade object
 * @param {object} [market] the outcome object the trade belongs to
 * @returns {object} a [prediction trade structure](https://docs.ccxt.com/#/?id=prediction-trade-structure)
 */
    pub fn parse_prediction_trade(&self, mut trade: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        // public data-api trades use 'asset'/'orderId'/'transactionHash'/'timestamp';
        // the private CLOB /data/trades use 'asset_id'/'taker_order_id'/'transaction_hash'/'match_time'
        let mut id: Option<String> = self.safe_string_n_opt(trade.clone(), Value::from(vec![Value::Str("transactionHash".into()), Value::Str("transaction_hash".into()), Value::Str("id".into())]), &[]);
        let mut timestamp: Value = self.safe_integer_product_k(trade.clone(), "timestamp", Value::Int(1000), &[]);
        if (timestamp == Value::Null) {
            timestamp = self.safe_integer_product_k(trade.clone(), "match_time", Value::Int(1000), &[]);
        }
        let mut price: Value = self.safe_number_k(trade.clone(), "price", &[]);
        let mut amount: Value = self.safe_number_k(trade.clone(), "size", &[]);
        let mut rawSide: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "side", &[]);
        let mut side: Value = Value::Null;
        if (rawSide.as_deref() == Some("buy")) || (rawSide.as_deref() == Some("sell")) {
            side = rawSide.map(Value::from).unwrap_or(Value::Null);
        }
        let mut assetId: Option<String> = self.safe_string2_opt(trade.clone(), Value::Str("asset".into()), Value::Str("asset_id".into()), &[]);
        let mut mkt: Value = Value::Null;
        if (market != Value::Null) {
            mkt = market;
        }  else {
            mkt = self.safe_outcome(assetId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
        }
        let mut outcome: Value = self.safe_outcome_symbol(Value::Null, &[mkt.clone()]);
        let mut rawTakerOrMaker: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "trader_side", &[]);
        let mut takerOrMaker: Value = Value::Null;
        if (rawTakerOrMaker.as_deref() == Some("taker")) || (rawTakerOrMaker.as_deref() == Some("maker")) {
            takerOrMaker = rawTakerOrMaker.map(Value::from).unwrap_or(Value::Null);
        }
        let mut feeRateBps: Option<String> = self.safe_string_k_opt(trade.clone(), "fee_rate_bps", &[]);
        let mut fee: Value = Value::Null;
        if (feeRateBps.is_some()) {
            fee = Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("currency".to_string(), Value::Str("USDC".into()));
                    m.insert("rate".to_string(), self.parse_number(crate::precise::Precise::stringDiv(&feeRateBps.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("10000".into())), &[]));
                m
            });
        }
        return self.safe_prediction_trade(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
        m.insert("info".to_string(), trade.clone());
        m.insert("timestamp".to_string(), timestamp.clone());
        m.insert("datetime".to_string(), self.iso8601(timestamp));
        m.insert("outcome".to_string(), outcome);
        m.insert("outcomeId".to_string(), assetId.map(Value::from).unwrap_or(Value::Null));
        m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
        m.insert("order".to_string(), self.safe_string2(trade, Value::Str("orderId".into()), Value::Str("taker_order_id".into()), &[]));
        m.insert("type".to_string(), Value::Null);
        m.insert("side".to_string(), side);
        m.insert("takerOrMaker".to_string(), takerOrMaker);
        m.insert("price".to_string(), price);
        m.insert("amount".to_string(), amount);
        m.insert("cost".to_string(), Value::Null);
        m.insert("fee".to_string(), fee);
    m
}), &[mkt]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchBalance
 * @description fetches the USDC collateral balance available for trading on the CLOB
 * @see https://docs.polymarket.com/api-reference/trade/get-balance-allowance
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {int} [params.signatureType] 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet); defaults to options.signatureType
 * @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
 */
    pub async fn fetch_balance(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        // the collateral balance is tied to the signature type / funder that holds the USDC
        let mut signatureType: Value = self.safe_integer2(params.clone(), Value::Str("signatureType".into()), Value::Str("signature_type".into()), &[self.safe_integer_k(self.options.clone(), "signatureType", &[Value::Int(3)])]);
        let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("signatureType".into()), Value::Str("signature_type".into())]), &[]);
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("asset_type".to_string(), Value::Str("COLLATERAL".into()));
                m.insert("signature_type".to_string(), signatureType);
            m
        });
        let __ws_arg_8 = self.extend(Value::Map(request), &[rest]);
        let mut response: Value = self.clob_private_get_balance_allowance(&[__ws_arg_8]).await;
        return self.parse_balance(response);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parseBalance
 * @description parses a balance-allowance response into a balances object with a USDC entry
 * @param {object} response the raw balance-allowance response
 * @returns {object} a [balance structure](https://docs.ccxt.com/#/?id=balance-structure)
 */
    pub fn parse_balance(&self, mut response: Value) -> Value {
        let mut result: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("info".to_string(), response.clone());
            m
        });
        // 'balance' is the raw USDC collateral in 6-decimal units (e.g. "8992211" = 8.992211 USDC)
        let mut raw: Option<String> = self.safe_string_k_opt(response, "balance", &[]);
        let mut total: Value = Value::Null;
        if (raw.is_some()) {
            total = self.parse_number(crate::precise::Precise::stringDiv(&raw.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1000000".into())), &[]);
        }
        result.insert("USDC".into(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("free".to_string(), total.clone());
        m.insert("used".to_string(), Value::Null);
        m.insert("total".to_string(), total);
    m
}));
        return self.safe_balance(Value::Map(result));

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchPositions
 * @description fetches open outcome token positions for the wallet from the data API
 * @see https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user
 * @param {string[]} [outcomes] unified outcomes to filter by
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction position structures](https://docs.ccxt.com/#/?id=prediction-position-structure)
 */
    pub async fn fetch_positions(&mut self, optional_args: &[Value]) -> Value {
        let mut outcomes = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomesLength: i64 = 0;
        if (outcomes != Value::Null) {
            outcomesLength = outcomes.len() as i64;
            self.load_outcomes(&[outcomes.clone()]).await;
        }
        // no bulk warm-up on the unfiltered path: the positions request is self-contained and
        // labels resolve cache-only via safeOutcome (raw token ids when the cache is cold)
        if (self.walletAddress.clone() == Value::Null) {
            panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" walletAddress is required to fetchPositions".into()))));
        }
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("user".to_string(), self.walletAddress.clone());
            m
        });
        let __ws_arg_9 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.data_public_get_positions(&[__ws_arg_9]).await;
        let mut positions: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
        // parse without the base outcome filter (it resolves standard markets, not outcome tokens),
        // then filter by the requested outcomes' token ids ourselves
        if (((outcomesLength as f64) == 0.0)) {
            return self.parse_prediction_positions(positions.clone(), &[]);
        }
        let mut parsed: Vec<Value> = self.parse_prediction_positions(positions, &[]).as_array().cloned().unwrap_or_default();
        let mut wantedIds: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        if (outcomes == Value::Null) {
            panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchPositions() missing outcomes".into()))));
        }
        {
                        let mut i: i64 = 0;
            let mut __for_first_1440: bool = true;
            while { if !__for_first_1440 { i += 1; } __for_first_1440 = false; i < (outcomes.len() as i64) } {
            let mut outcomeObj: Value = self.outcome(outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null));
            add_element_to_object(&mut wantedIds, &outcomeObj.as_map().and_then(|__m| __m.get("outcomeId")).cloned().unwrap_or(Value::Null), Value::Bool(true));
        }
        }
        let mut result: Value = Value::from(vec![]);
        {
                        let mut i: i64 = 0;
            let mut __for_first_1441: bool = true;
            while { if !__for_first_1441 { i += 1; } __for_first_1441 = false; i < (parsed.len() as i64) } {
            let mut position: Value = parsed.get(i as usize).cloned().unwrap_or(Value::Null);
            let mut info: Value = self.safe_dict_k(position.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            let mut assetId: Option<String> = self.safe_string_k_opt(info, "asset", &[]);
            if (assetId.is_some()) && (matches!((&wantedIds, &assetId.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(position); }
            }
        }
        }
        return result;

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchPosition
 * @description fetches the open position for a single outcome token
 * @see https://docs.polymarket.com/api-reference/core/get-current-positions-for-a-user
 * @param {string} outcome unified outcome or outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
 */
    pub async fn fetch_position(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut positions: Value = self.fetch_positions(&[Value::from(vec![outcome]), params]).await;
        return self.safe_dict(positions, Value::Int(0), &[]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parsePredictionPosition
 * @description parses a raw data API position object into a unified position object
 * @param {object} position the raw position object
 * @param {object} [market] the outcome object the position belongs to
 * @returns {object} a [prediction position structure](https://docs.ccxt.com/#/?id=prediction-position-structure)
 */
    pub fn parse_prediction_position(&self, mut position: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        let mut tokenId: Option<String> = self.safe_string_k_opt(position.clone(), "asset", &[]);
        let mut marketData: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
        let mut size: Value = self.safe_number_k(position.clone(), "size", &[]);
        let mut entryPrice: Value = self.safe_number_k(position.clone(), "avgPrice", &[]);
        let mut curPrice: Value = self.safe_number_k(position.clone(), "currentPrice", &[]);
        let mut notional: Value = Value::Null;
        if (size != Value::Null) && (curPrice != Value::Null) {
            notional = (match (&(size), &(curPrice)) { (Value::Int(x), Value::Int(y)) => Value::Int(x * y), (Value::Int(x), Value::Float(y)) => Value::Float(*x as f64 * *y), (Value::Float(x), Value::Int(y)) => Value::Float(*x * *y as f64), (Value::Float(x), Value::Float(y)) => Value::Float(x * y), _ => Value::Null });
        }
        return self.safe_prediction_position(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_string_k(position.clone(), "id", &[]));
        m.insert("outcome".to_string(), self.safe_string_k(marketData.clone(), "outcome", &[]));
        m.insert("outcomeId".to_string(), self.safe_string_k(marketData.clone(), "outcomeId", &[]));
        m.insert("market".to_string(), self.safe_string_k(marketData.clone(), "market", &[]));
        m.insert("label".to_string(), self.safe_string_k(marketData.clone(), "label", &[]));
        m.insert("event".to_string(), self.safe_string_k(marketData, "event", &[]));
        m.insert("timestamp".to_string(), Value::Null);
        m.insert("datetime".to_string(), Value::Null);
        m.insert("contracts".to_string(), size);
        m.insert("contractSize".to_string(), Value::Int(1));
        m.insert("side".to_string(), Value::Str("long".into()));
        m.insert("notional".to_string(), notional);
        m.insert("leverage".to_string(), Value::Int(1));
        m.insert("unrealizedPnl".to_string(), Value::Null);
        m.insert("realizedPnl".to_string(), self.safe_number_k(position.clone(), "realizedPnl", &[]));
        m.insert("collateral".to_string(), Value::Null);
        m.insert("entryPrice".to_string(), entryPrice);
        m.insert("markPrice".to_string(), curPrice);
        m.insert("liquidationPrice".to_string(), Value::Null);
        m.insert("hedged".to_string(), Value::Bool(false));
        m.insert("maintenanceMargin".to_string(), Value::Null);
        m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
        m.insert("initialMargin".to_string(), Value::Null);
        m.insert("initialMarginPercentage".to_string(), Value::Null);
        m.insert("marginRatio".to_string(), Value::Null);
        m.insert("marginMode".to_string(), Value::Str("cross".into()));
        m.insert("marginType".to_string(), Value::Str("cross".into()));
        m.insert("percentage".to_string(), Value::Null);
        m.insert("info".to_string(), position);
    m
}));

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOpenOrders
 * @description fetches open resting orders for the authenticated user, optionally filtered by outcome token
 * @see https://docs.polymarket.com/api-reference/trade/get-user-orders
 * @param {string} [outcome] unified outcome or outcome token id
 * @param {int} [since] not used by polymarket fetchOpenOrders
 * @param {int} [limit] the maximum number of orders to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn fetch_open_orders(&mut self, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            outcomeObj = self.load_outcome(outcome, &[]).await;
            request.insert("asset_id".into(), self.safe_string_k(outcomeObj.clone(), "outcomeId", &[]));
        }
        let __ws_arg_10 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_private_get_data_orders(&[__ws_arg_10]).await;
        let mut orders: Value = self.safe_list_k(response, "data", &[Value::from(vec![])]);
        return self.parse_prediction_orders(orders, &[outcomeObj, since, limit]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchOrder
 * @description fetches a single order by id from the CLOB private data endpoint
 * @see https://docs.polymarket.com/api-reference/trade/get-single-order-by-id
 * @param {string} id the order id
 * @param {string} [outcome] unified outcome or outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn fetch_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        // the request only needs the order id; the outcome is a labelling hint, so resolve it from
        // cache (no network) — fetchOrder stays a single request even on a cold cache.
        self.load_api_credentials().await;
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), id);
            m
        });
        let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_private_get_data_order_id(&[__ws_arg_11]).await;
        return self.parse_prediction_order(response, &[]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parsePredictionOrder
 * @description parses a raw CLOB order object into a unified order object
 * @param {object} order the raw order object
 * @param {object} [market] the outcome object the order belongs to
 * @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub fn parse_prediction_order(&self, mut order: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        //
        // {
        //     "errorMsg":"",
        //     "orderID":"0xdf6c53273ad44ab208323c8dde43f04304852c89d55df57efaca8e40caf2f363",
        //     "takingAmount":"",
        //     "makingAmount":"",
        //     "status":"live",
        //     "success":true
        // }
        // fetchOrder/fetchOpenOrders return 'id'; the createOrder POST response returns 'orderID'
        let mut id: Option<String> = self.safe_string2_opt(order.clone(), Value::Str("id".into()), Value::Str("orderID".into()), &[]);
        let mut tokenId: Option<String> = self.safe_string_k_opt(order.clone(), "asset_id", &[]);
        let mut mkt: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[market]);
        // REST returns 'status'; the user-websocket order event carries lifecycle in 'type'
        let mut status: Value = self.parse_order_status(self.safe_string2(order.clone(), Value::Str("status".into()), Value::Str("type".into()), &[])).map(Value::from).unwrap_or(Value::Null);
        let mut side: Option<String> = self.safe_string_lower_k_opt(order.clone(), "side", &[]);
        let mut price: Value = self.safe_number_k(order.clone(), "price", &[]);
        let mut amount: Value = self.safe_number_k(order.clone(), "original_size", &[]);
        let mut filled: Value = self.safe_number_k(order.clone(), "size_matched", &[Value::Int(0)]);
        let mut ts: Value = self.safe_integer_product_k(order.clone(), "created_at", Value::Int(1000), &[]);
        return self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), id.map(Value::from).unwrap_or(Value::Null));
        m.insert("clientOrderId".to_string(), Value::Null);
        m.insert("info".to_string(), order.clone());
        m.insert("timestamp".to_string(), ts.clone());
        m.insert("datetime".to_string(), self.iso8601(ts));
        m.insert("lastTradeTimestamp".to_string(), Value::Null);
        m.insert("status".to_string(), status);
        m.insert("outcome".to_string(), mkt.as_map().and_then(|__m| __m.get("outcome")).cloned().unwrap_or(Value::Null));
        m.insert("outcomeId".to_string(), self.safe_string_k(mkt.clone(), "outcomeId", &[]));
        m.insert("label".to_string(), self.safe_string_k(mkt.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(mkt.clone(), "market", &[]));
        m.insert("type".to_string(), Value::Str("limit".into()));
        m.insert("timeInForce".to_string(), self.safe_string_k(order.clone(), "time_in_force", &[Value::Str("GTC".into())]));
        m.insert("postOnly".to_string(), self.safe_bool_k(order, "postOnly", &[]));
        m.insert("side".to_string(), side.map(Value::from).unwrap_or(Value::Null));
        m.insert("price".to_string(), price);
        m.insert("stopPrice".to_string(), Value::Null);
        m.insert("triggerPrice".to_string(), Value::Null);
        m.insert("average".to_string(), Value::Null);
        m.insert("amount".to_string(), amount);
        m.insert("cost".to_string(), Value::Null);
        m.insert("filled".to_string(), filled);
        m.insert("remaining".to_string(), Value::Null);
        m.insert("fee".to_string(), Value::Null);
        m.insert("trades".to_string(), Value::from(vec![]));
    m
}), &[mkt]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parseOrderStatus
 * @description maps a polymarket order status string to the unified status vocabulary
 * @param {string} status the raw polymarket order status
 * @returns {string} a unified order status
 */
    pub fn parse_order_status(&self, mut status: Value) -> Option<String> {
        let mut statuses: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("live".to_string(), Value::Str("open".into()));
                m.insert("matched".to_string(), Value::Str("closed".into()));
                m.insert("cancelled".to_string(), Value::Str("canceled".into()));
                m.insert("delayed".to_string(), Value::Str("open".into()));
                m.insert("placement".to_string(), Value::Str("open".into()));
                m.insert("update".to_string(), Value::Str("open".into()));
                m.insert("cancellation".to_string(), Value::Str("canceled".into()));
            m
        });
        // the REST data endpoints return upper-case statuses (LIVE, MATCHED, CANCELLED) while the
        // user websocket sends lower-case lifecycle types — lower-case before the lookup so both map
        let mut normalized: Value = self.safe_string_lower(Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("status".to_string(), status);
            m
        }), Value::Str("status".into()), &[]);
        return self.safe_string(Value::Map(statuses), normalized.clone(), &[normalized.clone()]).as_str().map(str::to_owned);
}

/*
 * @method
 * @name polymarket#createOrder
 * @description places a limit or market order on the CLOB for the given outcome token
 * @see https://docs.polymarket.com/api-reference/trade/post-a-new-order
 * @param {string} outcome unified outcome or outcome token id
 * @param {string} type 'market' or 'limit'; market orders default to FOK and, when no price is given, use the outcome's current price as the marketable reference
 * @param {string} side 'buy' or 'sell'
 * @param {float} amount how many outcome tokens to trade
 * @param {float} [price] the price per outcome token between 0 and 1; required for limit orders, defaults to the outcome's current price for market orders
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.orderType] time-in-force override: 'GTC' (default for limit), 'FOK' (default for market), 'GTD' or 'FAK'
 * @param {int} [params.signatureType] 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet); defaults to options.signatureType
 * @param {string} [params.funder] the wallet that holds the USDC collateral; defaults to options.funder or the signing address
 * @param {string} [params.tickSize] the market tick size ('0.1'/'0.01'/'0.001'/'0.0001'); read from the outcome when omitted
 * @param {bool} [params.negRisk] whether the market is a neg-risk market; read from the outcome when omitted
 * @param {string} [params.salt] order salt; defaults to a strictly-increasing millisecond value (pin it for idempotent retries)
 * @param {string} [params.timestamp] order timestamp; defaults to the current time in ms
 * @param {string} [params.expiration] unix-seconds expiration for GTD orders; defaults to '0' (no expiry)
 * @param {string} [params.builderCode] builder wallet address or full bytes32 builder code attached to the order for attribution (zero fee — tracking only); defaults to options.builder
 * @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn create_order(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
        let mut price = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        self.load_outcome(outcome.clone(), &[]).await;
        let mut built: Value = self.build_clob_order_body(outcome, type_var, side, amount, &[price, params]);
        let mut response: Value = self.clob_private_post_order(&[self.safe_dict_k(built.clone(), "body", &[])]).await;
        // request echo first so the response's real orderID/status/success win on overlap
        let __ws_arg_12 = self.safe_dict_k(built.clone(), "request", &[]);
        let mut enriched: Value = self.extend(__ws_arg_12, &[response.clone()]);
        let mut order: Value = self.parse_prediction_order(enriched, &[self.safe_dict_k(built, "outcome", &[])]);
        if let Value::Dict(__rda) = &mut order { std::sync::Arc::make_mut(__rda).insert("info".to_string(), response); } // keep info the raw exchange response, not the request echo
        return order;

    Value::Null
}

/*
 * @method
 * @name polymarket#createOrders
 * @description places multiple orders on the CLOB in a single batched request
 * @see https://docs.polymarket.com/api-reference/trade/post-orders
 * @param {object[]} orders a list of order requests, each an object with outcome, type, side, amount, price and optional params (same params as createOrder)
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn create_orders(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        // buildClobOrderBody resolves outcomes synchronously from the cache, so batch-warm the
        // requested outcomes first (one gamma request for all uncached token ids)
        let mut orderOutcomes: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1442: bool = true;
            while { if !__for_first_1442 { i += 1; } __for_first_1442 = false; i < (orders.len() as i64) } {
            let mut o: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
            let mut __oc: Option<String> = self.safe_string_k_opt(o.clone(), "outcome", &[]);
            if (__oc.is_some()) {
                orderOutcomes.push(__oc.map(Value::from).unwrap_or(Value::Null));
            }
        }
        }
        self.load_outcomes(&[Value::from(orderOutcomes)]).await;
        let mut bodies: Vec<Value> = Vec::new();
        let mut outcomes: Vec<Value> = Vec::new();
        let mut requests: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1443: bool = true;
            while { if !__for_first_1443 { i += 1; } __for_first_1443 = false; i < (orders.len() as i64) } {
            let mut o: Value = self.safe_dict(orders.clone(), Value::Int(i), &[]);
            let mut orderParams: Value = self.safe_dict_k(o.clone(), "params", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            if (self.safe_string_k(orderParams.clone(), "salt", &[]) == Value::Null) {
                // a distinct salt per order so two identical orders don't collide, within a batch or across calls
                let mut orderSalt: Value = self.incrementing_nonce(); // hoisted to a named local: nesting the &mut self call inside numberToString breaks the Rust borrow checker
                let __ws_arg_13 = self.number_to_string(orderSalt);
                orderParams = self.extend(orderParams.clone(), &[Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("salt".to_string(), __ws_arg_13);
                    m
                })]);
            }
            let mut built: Value = self.build_clob_order_body(self.safe_string_k(o.clone(), "outcome", &[]), self.safe_string_k(o.clone(), "type", &[]), self.safe_string_k(o.clone(), "side", &[]), self.safe_number_k(o.clone(), "amount", &[]), &[self.safe_number_k(o, "price", &[]), orderParams]);
            bodies.push(self.safe_dict_k(built.clone(), "body", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]));
            outcomes.push(self.safe_dict_k(built.clone(), "outcome", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]));
            requests.push(self.safe_dict_k(built, "request", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]));
        }
        }
        let mut response: Value = self.clob_private_post_orders(&[Value::from(bodies)]).await;
        let mut result: Value = Value::from(vec![]);
        if (matches!(&response, Value::Arr(_))) {
            {
                                let mut i: Value = Value::Int(0);
                let mut __for_first_1444: bool = true;
                while { if !__for_first_1444 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1444 = false; i.as_f64().unwrap_or(f64::NAN) < ((response.len() as i64) as f64) } {
                // request echo first so the response's real orderID/status win on overlap
                let mut rawItem: Value = response.as_array().and_then(|__arr| match &i { Value::Int(__n) => __arr.get(*__n as usize), Value::Str(__s) => __s.parse::<usize>().ok().and_then(|__n| __arr.get(__n)), _ => None }).cloned().unwrap_or(Value::Null);
                let mut enriched: Value = self.extend(requests.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), &[rawItem.clone()]);
                let mut parsedItem: Value = self.parse_prediction_order(enriched, &[outcomes.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null)]);
                if let Value::Dict(__rda) = &mut parsedItem { std::sync::Arc::make_mut(__rda).insert("info".to_string(), rawItem); } // keep info the raw exchange response
                if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(parsedItem); }
            }
            }
        }  else {
            if let Value::Arr(__a) = &mut result { std::sync::Arc::make_mut(__a).push(self.parse_prediction_order(response, &[])); }
        }
        return result;

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#buildClobOrderBody
 * @description builds and signs a single CLOB order request body (shared by createOrder and createOrders)
 * @returns {object} an object with 'body' (the signed order request) and 'outcome' (the resolved outcome)
 */
    pub fn build_clob_order_body(&mut self, mut outcome: Value, mut type_var: Value, mut side: Value, mut amount: Value, optional_args: &[Value]) -> Value {
        let mut price = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        // pure builder, no network I/O — intentionally synchronous. a no-op async method
        // transpiles in php to a promise-typed wrapper around a body that returns a plain
        // dict, which throws a TypeError
        // outcome () validates the outcome against the loaded outcomes (built from events or markets)
        let mut outcomeObj: Value = self.outcome(outcome.clone());
        let mut tokenId: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "outcomeId", &[]);
        let mut sideStr: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
        let mut isMarket: bool = type_var.as_str() == Some("market");
        // CCXT type (limit/market) maps to a polymarket time-in-force: limit -> GTC, market -> FOK.
        // native override: params.orderType (GTC, GTD, FOK or FAK)
        let mut orderTypeStr: Value = self.safe_string_upper_k(params.clone(), "orderType", &[]);
        if (orderTypeStr == Value::Null) {
            // otherwise map the unified `timeInForce` onto polymarket's orderType vocabulary
            let mut unifiedTif: Option<String> = self.safe_string_upper_k(params.clone(), "timeInForce", &[]).as_str().map(str::to_owned);
            if (unifiedTif.as_deref() == Some("GTC")) {
                orderTypeStr = Value::Str("GTC".into());
            }  else if (unifiedTif.as_deref() == Some("FOK")) {
                orderTypeStr = Value::Str("FOK".into());
            }  else if (unifiedTif.as_deref() == Some("IOC")) {
                orderTypeStr = Value::Str("FAK".into()); // fill-and-kill == immediate-or-cancel
            }  else if (unifiedTif.as_deref() == Some("GTD")) {
                orderTypeStr = Value::Str("GTD".into());
            }
        }
        if (orderTypeStr == Value::Null) {
            orderTypeStr = (if isMarket { Value::Str("FOK".into()) } else { Value::Str("GTC".into()) });
        }
        let mut priceResolved: Value = price;
        if (priceResolved == Value::Null) {
            if !isMarket {
                panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() requires a price for limit orders".into()))));
            }
            // market order without an explicit price: use the outcome's current price as the marketable reference
            priceResolved = self.safe_number_k(outcomeObj.clone(), "price", &[]);
            if (priceResolved == Value::Null) {
                panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder() could not determine a price from the outcome, pass an explicit price".into()))));
            }
        }
        // tick size + neg-risk flag drive the rounding and the verifying contract; both are read from the
        // outcome object (set in parseMarket) and can be overridden via params to keep requests deterministic
        let mut outcomePrecision: Value = self.safe_dict_k(outcomeObj.clone(), "precision", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut tickSize: Value = self.safe_string_k(params.clone(), "tickSize", &[self.number_to_string(self.safe_number(outcomePrecision, Value::Str("price".into()), &[Value::Float(0.01)]))]);
        let mut negRisk: Value = self.safe_bool_k(params.clone(), "negRisk", &[self.safe_bool(outcomeObj.clone(), Value::Str("negRisk".into()), &[Value::Bool(false)])]);
        // maker-only: the CLOB rejects the order if it would immediately take
        let mut postOnly: bool = self.safe_bool_k_opt(params.clone(), "postOnly", &[Value::Bool(false)]).unwrap_or(false);
        // 0=EOA, 1=POLY_PROXY, 2=GNOSIS_SAFE, 3=POLY_1271 (deposit wallet, default); funder/maker holds the USDC
        let mut signatureType: Value = self.safe_integer2(params.clone(), Value::Str("signatureType".into()), Value::Str("signature_type".into()), &[self.safe_integer_k(self.options.clone(), "signatureType", &[Value::Int(3)])]);
        // the signer/owner is the EOA behind the privateKey; the funder/maker is the proxy or deposit wallet (walletAddress)
        let mut eoa: Value = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
        let mut funder: Value = self.eth_checksum_address(self.safe_string2(params.clone(), Value::Str("funder".into()), Value::Str("maker".into()), &[self.safe_string_k(self.options.clone(), "funder", &[self.walletAddress.clone()])])).map(Value::from).unwrap_or(Value::Null);
        // the salt defaults to a strictly-increasing millisecond value and the timestamp to the current time; both can be pinned via params for idempotency
        let mut defaultSalt: Value = self.incrementing_nonce(); // hoisted to a named local: nesting the &mut self call inside numberToString breaks the Rust borrow checker
        let mut salt: Value = self.safe_string_k(params.clone(), "salt", &[self.number_to_string(defaultSalt)]);
        let mut timestamp: Value = self.safe_string_k(params.clone(), "timestamp", &[self.number_to_string(self.milliseconds())]);
        // GTD (good-til-date) orders need a unix-seconds expiration; 0 means no expiry
        let mut expiration: Value = self.safe_string_k(params.clone(), "expiration", &[Value::Str("0".into())]);
        // a market buy can be sized by USDC cost instead of shares (see createMarketBuyOrderWithCost)
        let mut cost: Value = self.safe_number_k(params.clone(), "cost", &[]);
        let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("signatureType".into()), Value::Str("signature_type".into()), Value::Str("funder".into()), Value::Str("maker".into()), Value::Str("orderType".into()), Value::Str("timeInForce".into()), Value::Str("postOnly".into()), Value::Str("tickSize".into()), Value::Str("negRisk".into()),
            Value::Str("salt".into()), Value::Str("timestamp".into()), Value::Str("expiration".into()), Value::Str("cost".into()), Value::Str("builder".into()), Value::Str("builderCode".into())]), &[]);
        let mut amounts: Value = self.polymarket_order_raw_amounts(sideStr.clone(), amount.clone(), priceResolved.clone(), tickSize, &[cost.clone()]);
        let mut makerAmount: Option<String> = self.safe_string_k_opt(amounts.clone(), "makerAmount", &[]);
        let mut takerAmount: Option<String> = self.safe_string_k_opt(amounts, "takerAmount", &[]);
        let mut sideInt: Value = (if (sideStr.as_str() == Some("BUY")) { Value::Int(0) } else { Value::Int(1) });
        let mut bytes32Zero: String = "0x0000000000000000000000000000000000000000000000000000000000000000".to_string();
        // builder attribution: the order's bytes32 builder field packs the builder fee (bps,
        // upper 12 bytes) and the builder wallet (lower 20 bytes); when options.builderFee is
        // false the fee bytes stay zeroed, so orders are attributed for statistics only and
        // the user is not charged; a full 32-byte builder code is passed through unchanged
        let mut builderRaw: Value = self.safe_string_lower2(params, Value::Str("builder".into()), Value::Str("builderCode".into()), &[self.safe_string_lower_k(self.options.clone(), "builder", &[])]);
        let mut builderBytes32: Value = Value::from(bytes32Zero.clone());
        if (builderRaw != Value::Null) {
            let mut builderHex: Value = self.remove0x_prefix(builderRaw);
            if ((builderHex.len() as i64) as f64) <= ((40i64) as f64) {
                let mut builderFeeEnabled: bool = self.safe_bool_k_opt(self.options.clone(), "builderFee", &[Value::Bool(true)]).unwrap_or(true);
                let mut feeRate: Value = Value::Int(0);
                if builderFeeEnabled {
                    feeRate = self.safe_integer_k(self.options.clone(), "feeRate", &[Value::Int(0)]);
                }
                let mut feeHex: Value = self.int_to_base16(feeRate, &[]);
                feeHex = feeHex.as_str().map(|__s| Value::Str(format!("{:0>24}", __s).into())).unwrap_or(Value::Null);
                let mut addressHex: Value = builderHex.as_str().map(|__s| Value::Str(format!("{:0>40}", __s).into())).unwrap_or(Value::Null);
                let mut packedHex: Value = Value::Str(format!("{}{}", feeHex, addressHex).into());
                builderBytes32 = Value::Str(format!("{}{}", Value::Str("0x".into()), packedHex).into());
            }  else {
                let mut paddedHex: Value = builderHex.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
                builderBytes32 = Value::Str(format!("{}{}", Value::Str("0x".into()), paddedHex).into());
            }
        }
        // POLY_1271 (type 3): the order signer is the deposit wallet itself — the exchange calls
        // wallet.isValidSignature and the inner ERC-7739 domain's verifyingContract is the wallet (the EOA
        // still produces the signature and is checked on-chain as the wallet owner). Otherwise signer = EOA.
        let mut maker: Value = funder.clone();
        let mut signer: Value = eoa;
        if (signatureType.as_f64() == Some(3.0)) {
            signer = funder;
        }
        let mut message: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("salt".to_string(), salt.clone());
                m.insert("maker".to_string(), maker.clone());
                m.insert("signer".to_string(), signer.clone());
                m.insert("tokenId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
                m.insert("makerAmount".to_string(), makerAmount.clone().map(Value::from).unwrap_or(Value::Null));
                m.insert("takerAmount".to_string(), takerAmount.clone().map(Value::from).unwrap_or(Value::Null));
                m.insert("side".to_string(), sideInt);
                m.insert("signatureType".to_string(), signatureType.clone());
                m.insert("timestamp".to_string(), timestamp.clone());
                m.insert("metadata".to_string(), Value::from(bytes32Zero.clone()));
                m.insert("builder".to_string(), builderBytes32.clone());
            m
        });
        let mut exchangeV2: Value = self.safe_string_k(self.options.clone(), "exchangeAddress", &[Value::Str("0xE111180000d2663C0091e4f400237545B87B996B".into())]);
        let mut negRiskExchangeV2: Value = self.safe_string_k(self.options.clone(), "negRiskExchangeAddress", &[Value::Str("0xe2222d279d744050d28e00520010520000310F59".into())]);
        let mut exchangeAddress: Value = exchangeV2;
        if negRisk.as_bool() == Some(true) {
            exchangeAddress = negRiskExchangeV2;
        }
        let mut domainVersion: Value = self.safe_string_k(self.options.clone(), "ctfExchangeVersion", &[Value::Str("2".into())]);
        let mut signature: Value = self.sign_clob_order(Value::Map(message), exchangeAddress, domainVersion, signatureType.clone()).map(Value::from).unwrap_or(Value::Null);
        let mut owner: Value = self.safe_string_k(self.options.clone(), "l2ApiKey", &[self.apiKey.clone()]);
        let mut orderBody: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("deferExec".to_string(), Value::Bool(false));
                m.insert("postOnly".to_string(), Value::Bool(postOnly));
                m.insert("order".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("salt".to_string(), self.parse_to_int(salt));
        m.insert("maker".to_string(), maker);
        m.insert("signer".to_string(), signer);
        m.insert("taker".to_string(), Value::Str("0x0000000000000000000000000000000000000000".into()));
        m.insert("tokenId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("makerAmount".to_string(), makerAmount.map(Value::from).unwrap_or(Value::Null));
        m.insert("takerAmount".to_string(), takerAmount.map(Value::from).unwrap_or(Value::Null));
        m.insert("side".to_string(), sideStr.clone());
        m.insert("signatureType".to_string(), signatureType);
        m.insert("timestamp".to_string(), timestamp);
        m.insert("expiration".to_string(), expiration);
        m.insert("metadata".to_string(), Value::from(bytes32Zero));
        m.insert("builder".to_string(), builderBytes32);
        m.insert("signature".to_string(), signature);
    m
}));
                m.insert("owner".to_string(), owner);
                m.insert("orderType".to_string(), orderTypeStr.clone());
            m
        });
        // the CLOB create response only echoes {orderID, status}; carry the submitted terms
        // keyed as the fetchOrder response fields parsePredictionOrder reads, so createOrder can merge
        // them and return a fully-populated order instead of undefined side/price/amount
        let mut requestEcho: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("side".to_string(), sideStr);
                m.insert("price".to_string(), priceResolved);
                m.insert("asset_id".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
                m.insert("time_in_force".to_string(), orderTypeStr);
                m.insert("postOnly".to_string(), Value::Bool(postOnly));
            m
        });
        if (cost == Value::Null) {
            // a cost-sized market buy specifies spend, not shares — leave size to the fill
            requestEcho.insert("original_size".into(), amount);
        }
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("body".to_string(), self.extend(rest, &[Value::Map(orderBody)]));
        m.insert("outcome".to_string(), outcomeObj);
        m.insert("request".to_string(), Value::Map(requestEcho));
    m
});

    Value::Null
}

/*
 * @method
 * @name polymarket#createMarketBuyOrderWithCost
 * @description places a market buy order sized by USDC cost (how much to spend) rather than shares
 * @see https://docs.polymarket.com/api-reference/trade/post-a-new-order
 * @param {string} outcome unified outcome or outcome token id
 * @param {float} cost the amount of USDC to spend
 * @param {object} [params] extra parameters specific to the exchange API endpoint (see createOrder)
 * @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn create_market_buy_order_with_cost(&mut self, mut outcome: Value, mut cost: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut request: Value = self.extend(params, &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("cost".to_string(), cost.clone());
            m
        })]);
        return self.create_order(outcome, Value::Str("market".into()), Value::Str("buy".into()), cost, &[Value::Null, request]).await;

    Value::Null
}

    pub fn polymarket_order_raw_amounts(&self, mut side: Value, mut size: Value, mut price: Value, mut tickSize: Value, optional_args: &[Value]) -> Value {
        let mut cost = get_arg(optional_args, 0, Value::Null);
        let mut configs: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("0.1".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("price".to_string(), Value::Int(1));
        m.insert("size".to_string(), Value::Int(2));
        m.insert("amount".to_string(), Value::Int(3));
    m
}));
                m.insert("0.01".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("price".to_string(), Value::Int(2));
        m.insert("size".to_string(), Value::Int(2));
        m.insert("amount".to_string(), Value::Int(4));
    m
}));
                m.insert("0.001".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("price".to_string(), Value::Int(3));
        m.insert("size".to_string(), Value::Int(2));
        m.insert("amount".to_string(), Value::Int(5));
    m
}));
                m.insert("0.0001".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("price".to_string(), Value::Int(4));
        m.insert("size".to_string(), Value::Int(2));
        m.insert("amount".to_string(), Value::Int(6));
    m
}));
            m
        });
        let mut cfg: Value = self.safe_dict(Value::Map(configs.clone()), tickSize, &[self.safe_dict_k(Value::Map(configs), "0.01", &[])]);
        let mut priceDecimals: Value = self.safe_integer_k(cfg.clone(), "price", &[]);
        let mut sizeDecimals: Value = self.safe_integer_k(cfg.clone(), "size", &[]);
        let mut amountDecimals: Value = self.safe_integer_k(cfg, "amount", &[]);
        let mut priceStr: Value = self.number_to_string(price);
        let mut rawPrice: Value = self.decimal_to_precision(priceStr, Value::Int(crate::runtime::ROUND), priceDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        let mut makerRaw: Value = Value::Null;
        let mut takerRaw: Value = Value::Null;
        if (cost != Value::Null) && (side.as_str() == Some("BUY")) {
            // cost-sized market buy: maker pays `cost` USDC, taker receives cost/price shares.
            // truncate the shares so the implied price (cost/shares) stays >= the limit, otherwise
            // a marketable FOK would round just under the ask and fail to cross
            let mut costStr: Value = self.number_to_string(cost);
            makerRaw = self.decimal_to_precision(costStr, Value::Int(crate::runtime::TRUNCATE), sizeDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
            takerRaw = self.decimal_to_precision(crate::precise::Precise::stringDiv(&makerRaw, &rawPrice), Value::Int(crate::runtime::TRUNCATE), amountDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        }  else if (side.as_str() == Some("BUY")) {
            let mut sizeStr: Value = self.number_to_string(size.clone());
            takerRaw = self.decimal_to_precision(sizeStr.clone(), Value::Int(crate::runtime::TRUNCATE), sizeDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
            makerRaw = self.decimal_to_precision(crate::precise::Precise::stringMul(&takerRaw, &rawPrice), Value::Int(crate::runtime::ROUND), amountDecimals.clone(), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        }  else {
            let mut sizeStr: Value = self.number_to_string(size);
            makerRaw = self.decimal_to_precision(sizeStr, Value::Int(crate::runtime::TRUNCATE), sizeDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
            takerRaw = self.decimal_to_precision(crate::precise::Precise::stringMul(&makerRaw, &rawPrice), Value::Int(crate::runtime::ROUND), amountDecimals, &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        }
        // scale to collateral units (USDC has 6 decimals; shares are also scaled by 1e6)
        let mut makerAmount: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&makerRaw, &Value::Str("1000000".into())), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        let mut takerAmount: Value = self.decimal_to_precision(crate::precise::Precise::stringMul(&takerRaw, &Value::Str("1000000".into())), Value::Int(crate::runtime::TRUNCATE), Value::Int(0), &[Value::Int(crate::runtime::DECIMAL_PLACES)]);
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("makerAmount".to_string(), makerAmount);
        m.insert("takerAmount".to_string(), takerAmount);
    m
});

    Value::Null
}

    pub fn sign_clob_order(&self, mut message: Value, mut exchangeAddress: Value, mut domainVersion: Value, mut sigType: Value) -> Option<String> {
        // param is sigType, not signatureType: the php regex transpiler would rewrite the
        // substring "signatureType" inside the orderTypeString literal below into the local
        // var '$signatureType', corrupting the EIP-712 type hash
        // chainIdValue, not chainId: the php regex transpiler would rewrite the substring "chainId"
        // inside the 'EIP712Domain(...uint256 chainId,...)' literal below to the local var '$chainId',
        // corrupting the domain type hash
        let mut chainIdValue: Option<i64> = self.safe_integer_k(self.options.clone(), "chainId", &[Value::Int(137)]).as_i64();
        let mut domainName: Value = self.safe_string_k(self.options.clone(), "ctfExchangeName", &[Value::Str("Polymarket CTF Exchange".into())]);
        let mut orderTypeString: Value = Value::Str("Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)".into());
        let mut orderStruct: Value = Value::from(vec![Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("salt".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("maker".into()));
        m.insert("type".to_string(), Value::Str("address".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("signer".into()));
        m.insert("type".to_string(), Value::Str("address".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("tokenId".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("makerAmount".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("takerAmount".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("side".into()));
        m.insert("type".to_string(), Value::Str("uint8".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("signatureType".into()));
        m.insert("type".to_string(), Value::Str("uint8".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("timestamp".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("metadata".into()));
        m.insert("type".to_string(), Value::Str("bytes32".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("builder".into()));
        m.insert("type".to_string(), Value::Str("bytes32".into()));
    m
})]);
        let mut orderDomain: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("name".to_string(), domainName.clone());
                m.insert("version".to_string(), domainVersion.clone());
                m.insert("chainId".to_string(), Value::from(chainIdValue));
                m.insert("verifyingContract".to_string(), exchangeAddress.clone());
            m
        });
        // parseToInt: php types the number param as float, and 3.0 !== 3 (int) is true under
        // strict comparison, which would always wrongly select the EOA path
        if (self.parse_to_int(sigType).as_f64() != Some(3.0)) {
            // standard EOA EIP-712 order signature
            let mut encoded: Value = self.eth_encode_structured_data(Value::Map(orderDomain.clone()), Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("Order".to_string(), orderStruct.clone());
                m
            }), message.clone());
            let mut eoaSig: indexmap::IndexMap<String, Value> = self.sign_message(encoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
            // lowercase: intToBase16 emits uppercase hex in some target languages, but the
            // signature is case-insensitive bytes and the rest of the hex is lowercase
            let mut eoaSignature: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(eoaSig.get("r").cloned().unwrap_or(Value::Null))).into()), self.remove0x_prefix(eoaSig.get("s").cloned().unwrap_or(Value::Null))).into()), self.int_to_base16(eoaSig.get("v").cloned().unwrap_or(Value::Null), &[])).into());
            return (if let Some(__s) = eoaSignature.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str().map(str::to_owned);
        }
        // POLY_1271 — ERC-7739 wrapped signature validated on-chain by the deposit wallet.
        // ethAbiEncode needs portable value types: bytes32 as binary, uint256 as bigint
        // raw hex/decimal strings encode in ethers/JS but throw in the python/php codecs
        let mut orderTypeHash: Value = self.hash(self.encode(orderTypeString.clone()), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
        let mut contentsData: Value = self.eth_abi_encode(Value::from(vec![Value::Str("bytes32".into()), Value::Str("uint256".into()), Value::Str("address".into()), Value::Str("address".into()), Value::Str("uint256".into()), Value::Str("uint256".into()), Value::Str("uint256".into()), Value::Str("uint8".into()), Value::Str("uint8".into()),
            Value::Str("uint256".into()), Value::Str("bytes32".into()), Value::Str("bytes32".into())]), Value::from(vec![orderTypeHash, self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("salt")).cloned().unwrap_or(Value::Null)), message.as_map().and_then(|__m| __m.get("maker")).cloned().unwrap_or(Value::Null),
            message.as_map().and_then(|__m| __m.get("signer")).cloned().unwrap_or(Value::Null), self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("tokenId")).cloned().unwrap_or(Value::Null)), self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("makerAmount")).cloned().unwrap_or(Value::Null)),
            self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("takerAmount")).cloned().unwrap_or(Value::Null)), message.as_map().and_then(|__m| __m.get("side")).cloned().unwrap_or(Value::Null), message.as_map().and_then(|__m| __m.get("signatureType")).cloned().unwrap_or(Value::Null),
            self.convert_to_big_int(message.as_map().and_then(|__m| __m.get("timestamp")).cloned().unwrap_or(Value::Null)), self.base16_to_binary(self.remove0x_prefix(message.as_map().and_then(|__m| __m.get("metadata")).cloned().unwrap_or(Value::Null)), &[]), self.base16_to_binary(self.remove0x_prefix(message.as_map().and_then(|__m| __m.get("builder")).cloned().unwrap_or(Value::Null)), &[])]));
        let mut contentsHash: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(contentsData, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
        let mut domainTypeHash: Value = self.hash(self.encode(Value::Str("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)".into())), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
        let mut nameHash: Value = self.hash(self.encode(domainName), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
        let mut versionHash: Value = self.hash(self.encode(domainVersion), Value::Str("keccak".into()), &[Value::Str("binary".into())]);
        let mut appDomainData: Value = self.eth_abi_encode(Value::from(vec![Value::Str("bytes32".into()), Value::Str("bytes32".into()), Value::Str("bytes32".into()), Value::Str("uint256".into()), Value::Str("address".into())]), Value::from(vec![domainTypeHash, nameHash, versionHash, self.convert_to_big_int(self.number_to_string(Value::from(chainIdValue))), exchangeAddress]));
        let mut appDomainSep: Value = Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(appDomainData, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into());
        let mut typedDataSignStruct: Value = Value::from(vec![Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("contents".into()));
        m.insert("type".to_string(), Value::Str("Order".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("name".into()));
        m.insert("type".to_string(), Value::Str("string".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("version".into()));
        m.insert("type".to_string(), Value::Str("string".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("chainId".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("verifyingContract".into()));
        m.insert("type".to_string(), Value::Str("address".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("salt".into()));
        m.insert("type".to_string(), Value::Str("bytes32".into()));
    m
})]);
        let mut bytes32Zero: String = "0x0000000000000000000000000000000000000000000000000000000000000000".to_string();
        let mut innerValue: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("contents".to_string(), message.clone());
                m.insert("name".to_string(), Value::Str("DepositWallet".into()));
                m.insert("version".to_string(), Value::Str("1".into()));
                m.insert("chainId".to_string(), Value::from(chainIdValue));
                m.insert("verifyingContract".to_string(), message.as_map().and_then(|__m| __m.get("signer")).cloned().unwrap_or(Value::Null));
                m.insert("salt".to_string(), Value::from(bytes32Zero));
            m
        });
        let mut innerEncoded: Value = self.eth_encode_structured_data(Value::Map(orderDomain), Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("TypedDataSign".to_string(), typedDataSignStruct);
                m.insert("Order".to_string(), orderStruct);
            m
        }), Value::Map(innerValue));
        let mut innerSigObj: indexmap::IndexMap<String, Value> = self.sign_message(innerEncoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
        let mut innerSig: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.remove0x_prefix(self.safe_string(Value::Map(innerSigObj.clone()), Value::Str("r".into()), &[])), self.remove0x_prefix(self.safe_string(Value::Map(innerSigObj.clone()), Value::Str("s".into()), &[]))).into()), self.int_to_base16(innerSigObj.get("v").cloned().unwrap_or(Value::Null), &[])).into());
        // innerSig(65) || appDomainSep(32) || contentsHash(32) || contentsType || uint16_BE(len)
        // orderTypeString.length is used inline (not via a `const n = str.length;` statement) so the
        // php transpiler emits strlen() — the standalone statement form wrongly becomes count() (array)
        let mut ctLenHex: Value = self.int_to_base16(Value::Int(orderTypeString.len() as i64), &[]);
        // assign before padStart so the PHP transpiler's str_pad regex (which only matches a
        // simple identifier) picks it up instead of leaking a padStart() function call
        let mut lenHex: Value = ctLenHex.as_str().map(|__s| Value::Str(format!("{:0>4}", __s).into())).unwrap_or(Value::Null);
        let mut orderTypeStringHex: Value = self.binary_to_base16(self.encode(orderTypeString), &[]);
        let mut wrappedSignature: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), innerSig).into()), self.remove0x_prefix(appDomainSep)).into()), self.remove0x_prefix(contentsHash)).into()), orderTypeStringHex).into()), lenHex).into());
        return (if let Some(__s) = wrappedSignature.as_str() { Value::Str(__s.to_lowercase().into()) } else { Value::Null }).as_str().map(str::to_owned);
}

/*
 * @method
 * @name polymarket#cancelOrder
 * @description cancels a single open order by id on the CLOB
 * @see https://docs.polymarket.com/api-reference/trade/cancel-single-order
 * @param {string} id the order id
 * @param {string} [outcome] unified outcome or outcome token id
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction order structure](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn cancel_order(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        // cancelling by id needs no market data, so events do not have to be loaded first
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("orderID".to_string(), id.clone());
            m
        });
        let __ws_arg_14 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.clob_private_delete_order(&[__ws_arg_14]).await;
        // the DELETE endpoint returns { canceled: [id], not_canceled: { id: reason } } with no order
        // fields, so report the cancellation outcome explicitly rather than parsing an empty order
        let mut notCanceled: Value = self.safe_dict_k(response.clone(), "not_canceled", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut failureReason: Option<String> = self.safe_string(notCanceled, id.clone(), &[]).as_str().map(str::to_owned);
        let mut status: String = "open".to_string();
        if (failureReason.is_none()) {
            status = "canceled".to_string();
        }
        return self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), id);
        m.insert("status".to_string(), Value::from(status));
        m.insert("info".to_string(), response);
    m
}), &[]);

    Value::Null
}

/*
 * @method
 * @name polymarket#cancelOrders
 * @description cancels multiple open orders by id on the CLOB in a single request
 * @see https://docs.polymarket.com/api-reference/trade/cancel-orders
 * @param {string[]} ids the order ids to cancel
 * @param {string} [outcome] not used by polymarket cancelOrders
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn cancel_orders(&mut self, mut ids: Value, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        // the request body is the bare array of order ids (DELETE /orders), so params are not merged
        let mut response: Value = self.clob_private_delete_orders(&[ids]).await;
        let mut canceled: Value = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]);
        let mut orders: Value = Value::from(vec![]);
        {
                        let mut i: i64 = 0;
            let mut __for_first_1445: bool = true;
            while { if !__for_first_1445 { i += 1; } __for_first_1445 = false; i < (canceled.len() as i64) } {
            if let Value::Arr(__a) = &mut orders { std::sync::Arc::make_mut(__a).push(self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_string(canceled.clone(), Value::Int(i), &[]));
        m.insert("status".to_string(), Value::Str("canceled".into()));
        m.insert("info".to_string(), response.clone());
    m
}), &[])); }
        }
        }
        return orders;

    Value::Null
}

/*
 * @method
 * @name polymarket#cancelAllOrders
 * @description cancels all open orders on the CLOB, optionally scoped to one outcome token
 * @see https://docs.polymarket.com/api-reference/trade/cancel-all-orders
 * @see https://docs.polymarket.com/api-reference/trade/cancel-market-orders
 * @param {string} [outcome] unified outcome or outcome token id; when given only that outcome's orders are cancelled
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn cancel_all_orders(&mut self, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        let mut response: Value = Value::Null;
        if (outcome != Value::Null) {
            // scope to a single outcome token via DELETE /cancel-market-orders { asset_id }
            let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
            let mut request: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                    m.insert("asset_id".to_string(), self.safe_string_k(outcomeObj, "outcomeId", &[]));
                m
            });
            let __ws_arg_15 = self.extend(Value::Map(request), &[params.clone()]);
            response = self.clob_private_delete_cancel_market_orders(&[__ws_arg_15]).await;
        }  else {
            // cancel every open order via DELETE /cancel-all (no body, no market data needed)
            response = self.clob_private_delete_cancel_all(&[params]).await;
        }
        let mut canceled: Value = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]);
        let mut orders: Value = Value::from(vec![]);
        {
                        let mut i: i64 = 0;
            let mut __for_first_1446: bool = true;
            while { if !__for_first_1446 { i += 1; } __for_first_1446 = false; i < (canceled.len() as i64) } {
            if let Value::Arr(__a) = &mut orders { std::sync::Arc::make_mut(__a).push(self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_string(canceled.clone(), Value::Int(i), &[]));
        m.insert("status".to_string(), Value::Str("canceled".into()));
        m.insert("info".to_string(), response.clone());
    m
}), &[])); }
        }
        }
        return orders;

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchEvents
 * @description fetches prediction-market events matching the given scope (query/queries/tags/eventId/slug — required) and caches their markets and outcomes on the instance; for an unscoped top-volume browse use fetchMarkets ()
 * @see https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles
 * @see https://docs.polymarket.com/api-reference/events/list-events
 * @param {object} [params] extra exchange-specific parameters
 * @param {string} [params.query] a single keyword search term
 * @param {string[]} [params.queries] multiple search terms (alternative to query)
 * @param {string[]} [params.tags] filter events by tag — human-readable labels ("Fed Rates") or slugs ("fed-rates") both work; multiple tags match ANY (one gamma listing per tag, unioned and deduped)
 * @param {int} [params.limit] max number of events to return
 * @param {string} [params.sort] 'volume' (default), 'liquidity' or 'newest' — mapped to the gamma order field
 * @param {string} [params.status] 'active' (default), 'inactive', 'closed' or 'all' ('inactive' and 'closed' are interchangeable)
 * @param {string} [params.searchIn] when searching, restrict the match to 'title' (default), 'description' or 'both'
 * @param {string} [params.eventId] direct lookup by event id (short-circuits the listing/search)
 * @param {string} [params.slug] direct lookup by event slug
 * @param {int} [params.searchPageSize] search page size (gamma limit_per_type, default 100); lower it to shrink the download when a small limit is enough, higher to over-fetch before client-side status/title filtering
 * @param {int} [params.maxSearchPages] max search pages to fetch when no limit is given (default 5), bounding a broad query
 * @returns {object[]} an array of event structures
 */
    pub async fn fetch_events(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.require_event_query(&[params.clone()]);
        let mut requestedEventId: Option<String> = self.safe_string_k_opt(params.clone(), "eventId", &[]);
        let mut requestedSlug: Option<String> = self.safe_string_k_opt(params.clone(), "slug", &[]);
        let mut queries: Value = self.parse_search_queries(&[params.clone()]);
        let mut rest: Value = self.omit(params.clone(), Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("eventId".into()), Value::Str("slug".into())]), &[]);
        if (queries == Value::Null) {
            panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() missing queries".into()))));
        }
        let mut queriesLength: f64 = ((queries.len() as i64) as f64);
        let mut rawEvents: Value = Value::from(vec![]);
        if (requestedEventId.is_some()) || (requestedSlug.is_some()) {
            // direct lookup by event id or slug via the events endpoint (returns a list)
            let mut lookup: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                m
            });
            if (requestedEventId.is_some()) {
                lookup.insert("id".into(), requestedEventId.clone().map(Value::from).unwrap_or(Value::Null));
            }  else {
                lookup.insert("slug".into(), requestedSlug.clone().map(Value::from).unwrap_or(Value::Null));
            }
            let mut response: Value = self.gamma_public_get_events(&[Value::Map(lookup)]).await;
            let mut responseIsArray: bool = matches!(&response, Value::Arr(_));
            rawEvents = (if (responseIsArray) { response } else { Value::from(vec![]) });
        }  else if queriesLength > ((0i64) as f64) {
            rawEvents = self.fetch_raw_events_by_search(queries.clone(), &[rest.clone()]).await;
        }  else {
            rawEvents = self.fetch_raw_events_list(&[rest]).await;
        }
        // Parse and merge into class-level caches
        if (self.exchange.events.clone() == Value::Null) {
            self.exchange.events = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
        }
        if (self.markets.clone() == Value::Null) {
            { let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
        }
        let mut result: Vec<Value> = Vec::new();
        {
                        let mut rei: i64 = 0;
            let mut __for_first_1448: bool = true;
            while { if !__for_first_1448 { rei += 1; } __for_first_1448 = false; rei < (rawEvents.len() as i64) } {
            let mut rawEvent: Value = rawEvents.as_array().map(Vec::as_slice).unwrap_or_default().get(rei as usize).cloned().unwrap_or(Value::Null);
            let mut eventForParsing: Value = rawEvent.clone();
            let mut ccxtMarkets: Value = self.parse_event_to_markets(eventForParsing.clone());
            let mut ccxtMarketsLength: f64 = ((ccxtMarkets.len() as i64) as f64);
            if (ccxtMarketsLength == 0.0) {
                // search results may omit the nested markets, fall back to the detail endpoint
                let mut eventId: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "id", &[]);
                let mut rawEventSlug: Option<String> = self.safe_string_k_opt(rawEvent, "slug", &[]);
                let mut detailedEvent: Value = Value::Null;
                if (eventId.is_some()) {
                    detailedEvent = self.gamma_public_get_events_id(&[Value::Map({
                        let mut m = indexmap::IndexMap::new();
                            m.insert("id".to_string(), eventId.map(Value::from).unwrap_or(Value::Null));
                        m
                    })]).await;
                }  else if (rawEventSlug.is_some()) {
                    detailedEvent = self.gamma_public_get_events_slug_slug(&[Value::Map({
                        let mut m = indexmap::IndexMap::new();
                            m.insert("slug".to_string(), rawEventSlug.map(Value::from).unwrap_or(Value::Null));
                        m
                    })]).await;
                }
                if (detailedEvent != Value::Null) {
                    eventForParsing = self.safe_value_k(detailedEvent.clone(), "event", &[detailedEvent.clone()]);
                    ccxtMarkets = self.parse_event_to_markets(eventForParsing.clone());
                }
            }
            {
                                let mut mi: i64 = 0;
                let mut __for_first_1447: bool = true;
                while { if !__for_first_1447 { mi += 1; } __for_first_1447 = false; mi < (ccxtMarkets.len() as i64) } {
                let mut m: Value = ccxtMarkets.as_array().map(Vec::as_slice).unwrap_or_default().get(mi as usize).cloned().unwrap_or(Value::Null);
                if (m == Value::Null) {
                    panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" fetchEvents() missing m".into()))));
                }
                add_element_to_object(&mut self.markets, &m.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null), m.clone());
            }
            }
            let mut parsedEvent: Value = self.parse_event(eventForParsing);
            result.push(parsedEvent);
        }
        }
        // populateOutcomes rebuilds the outcome cache from the markets registered above; the
        // shared applyEventFetchParams then caches (setEvents) and applies the unified
        // eventId/slug/status/tags/searchIn/sort/limit filters, so all five venues behave the same
        self.populate_outcomes();
        let mut effectiveParams: Value = params.clone();
        if queriesLength > ((0i64) as f64) {
            // the gamma search endpoint is fuzzy, so default to refining by active status and a
            // title match (the caller can override); the other venues search exactly and need no
            // such default. inject the defaults as explicit params so the shared pipeline stays
            // the single behaviour definition
            effectiveParams = self.extend(Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            }), &[params.clone()]);
            add_element_to_object(&mut effectiveParams, &Value::Str("status".into()), self.safe_string_k(params.clone(), "status", &[Value::Str("active".into())]));
            add_element_to_object(&mut effectiveParams, &Value::Str("searchIn".into()), self.safe_string_k(params, "searchIn", &[Value::Str("title".into())]));
        }
        return self.apply_event_fetch_params(Value::from(result), &[effectiveParams, queries]);

    Value::Null
}

/*
 * @method
 * @name polymarket#fetchEvent
 * @description fetches a single prediction-market event by its id or slug
 * @see https://docs.polymarket.com/api-reference/events/get-event-by-id
 * @see https://docs.polymarket.com/api-reference/events/get-event-by-slug
 * @param {string} id the event id (numeric) or slug
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [prediction event structure](https://docs.ccxt.com/#/?id=prediction-event-structure)
 */
    pub async fn fetch_event(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut response: Value = Value::Null;
        if id.as_str().unwrap_or("").contains("-") {
            let __ws_arg_16 = self.extend(Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("slug".to_string(), id.clone());
                m
            }), &[params.clone()]);
            response = self.gamma_public_get_events_slug_slug(&[__ws_arg_16]).await;
        }  else {
            let __ws_arg_17 = self.extend(Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("id".to_string(), id);
                m
            }), &[params]);
            response = self.gamma_public_get_events_id(&[__ws_arg_17]).await;
        }
        let mut eventForParsing: Value = self.safe_dict_k(response.clone(), "event", &[response.clone()]);
        if (eventForParsing == Value::Null) {
            eventForParsing = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
        }
        let mut event: Value = self.parse_event(eventForParsing);
        self.index_event_outcomes(event.clone());
        return event;

    Value::Null
}

    pub fn parse_event(&self, mut rawEvent: Value) -> Value {
        // {
        //     "id": "73113",
        //     "ticker": "ukraine-agrees-not-to-join-nato-before-2027",
        //     "slug": "ukraine-agrees-not-to-join-nato-before-2027",
        //     "title": "Ukraine agrees not to join NATO before 2027? ",
        //     "description": "This market will resolve to \\"Yes\\" if Ukraine publicly agrees not to join NATO by December 31, 2026, 11:59 PM ET. Otherwise, this market will resolve to “No”.\\n\\nAn official pledge by Ukraine not to join NATO will qualify for a “Yes” resolution whether as a unilateral announcement or part of an agreement with the Russian Federation.\\n\\nAny agreement or pledge made before the resolution date of this market will qualify, regardless of if/when the agreement goes into effect.\\n\\nAn agreement by Ukraine not to join NATO for any amount of time will count (e.g. If Ukraine not to join NATO for 10 years this will qualify).\\n\\nAn agreement by Ukraine not to join NATO as a precondition of a more comprehensive peace process or deal will qualify, even if the agreement is not finalized or part of a formalized peace deal. The September 8, 1995 “Agreed Basic Principles” between Bosnia and Yugoslavia which recognized the borders and sovereignty of Bosnia and Herzegovina, and was later formalized through the Dayton Peace Agreement is an example of a qualifying agreement. \\n\\nThe primary resolution source for this market will be an official announcement by the Ukraine, however an overwhelming consensus of credible reporting confirming a qualifying agreement has been reached will also count.",
        //     "resolutionSource": "",
        //     "startDate": "2025-11-05T17:00:57.200353Z",
        //     "creationDate": "2025-11-05T17:00:57.20035Z",
        //     "endDate": "2026-12-31T00:00:00Z",
        //     "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/ukraine-agrees-not-to-join-nato-before-july-vKEDpScXuAtt.jpg",
        //     "icon": "https://polymarket-upload.s3.us-east-2.amazonaws.com/ukraine-agrees-not-to-join-nato-before-july-vKEDpScXuAtt.jpg",
        //     "active": true,
        //     "closed": false,
        //     "archived": false,
        //     "new": false,
        //     "featured": false,
        //     "restricted": true,
        //     "liquidity": "22010.6659",
        //     "openInterest": "0",
        //     "createdAt": "2025-11-04T19:27:23.246129Z",
        //     "updatedAt": "2026-03-14T14:38:21.25643Z",
        //     "competitive": "0.9538344143456696",
        //     "enableOrderBook": true,
        //     "liquidityClob": "22010.6659",
        //     "commentCount": "0",
        //     "markets": [],
        //     "tags": [
        //         {
        //             "id": "101970",
        //             "label": "World",
        //             "slug": "world",
        //             "forceShow": false,
        //             "createdAt": "2025-03-19T23:36:08.498099Z",
        //             "updatedAt": "2026-03-09T22:25:02.420693Z",
        //             "requiresTranslation": false
        //         },
        //         {
        //             "id": "270",
        //             "label": "putin",
        //             "slug": "putin",
        //             "publishedAt": "2023-11-02 21:46:19.507+00",
        //             "createdAt": "2023-11-02T21:46:19.528Z",
        //             "updatedAt": "2026-03-09T22:29:44.08742Z",
        //             "requiresTranslation": false
        //         }
        //     ],
        //     "cyom": false,
        //     "showAllOutcomes": true,
        //     "showMarketImages": true,
        //     "enableNegRisk": false,
        //     "automaticallyActive": true,
        //     "seriesSlug": "ukraine-not-nato",
        //     "negRiskAugmented": false,
        //     "cumulativeMarkets": false,
        //     "pendingDeployment": false,
        //     "deploying": false,
        //     "requiresTranslation": false
        // }
        let mut marketsList: Value = self.parse_event_to_markets(rawEvent.clone());
        let mut slug: Option<String> = self.safe_string_k_opt(rawEvent.clone(), "slug", &[]);
        // gamma events use camelCase keys (createdAt/endDate/image/updatedAt/closed);
        // the snake_case fallbacks cover older payload shapes
        let mut createdAt: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("createdAt".into()), Value::Str("created_date_iso".into()), &[]);
        let mut endDate: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("endDate".into()), Value::Str("end_date_iso".into()), &[]);
        let mut updatedAt: Option<String> = self.safe_string2_opt(rawEvent.clone(), Value::Str("updatedAt".into()), Value::Str("last_updated_date_iso".into()), &[]);
        let mut rawActive: Option<bool> = self.safe_bool_k_opt(rawEvent.clone(), "active", &[]);
        let mut closed: bool = self.safe_bool_k_opt(rawEvent.clone(), "closed", &[Value::Bool(false)]).unwrap_or(false);
        let mut active: Value = Value::Null;
        if (rawActive.is_some()) {
            active = Value::Bool(rawActive == Some(true) && (!(closed)));
        }
        // surface gamma's tag objects as a top-level string[] so the unified `tags` filter
        // — filterEventsByTags reads event['tags'], not event.info.tags — can actually match.
        // prefer the human-readable label ("Fed Rates") over the slug — matching is
        // normalized (normalizeTagKey), so the display form is free to be the friendly one
        let mut rawTags: Vec<Value> = self.safe_list_k(rawEvent.clone(), "tags", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
        let mut rawTagsLength: f64 = ((rawTags.len() as i64) as f64);
        let mut parsedTags: Vec<Value> = Vec::new();
        {
                        let mut ti: Value = Value::Int(0);
            let mut __for_first_1449: bool = true;
            while { if !__for_first_1449 { if let Value::Int(n) = &mut ti { *n += 1; } } __for_first_1449 = false; ti.as_f64().unwrap_or(f64::NAN) < rawTagsLength } {
            let mut tagLabel: Option<String> = self.safe_string2_opt(rawTags.get(ti.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), Value::Str("label".into()), Value::Str("slug".into()), &[]);
            if (tagLabel.is_some()) {
                parsedTags.push(tagLabel.map(Value::from).unwrap_or(Value::Null));
            }
        }
        }
        let __ws_arg_18 = self.safe_string_k(rawEvent.clone(), "id", &[]);
        let __ws_arg_19 = self.shorten_slug(slug.clone().map(Value::from).unwrap_or(Value::Null));
        let __ws_arg_20 = self.safe_string_k(rawEvent.clone(), "title", &[]);
        let __ws_arg_21 = self.safe_string_k(rawEvent.clone(), "url", &[]);
        let __ws_arg_22 = self.safe_string2(rawEvent.clone(), Value::Str("image".into()), Value::Str("image_url".into()), &[]);
        let __ws_arg_23 = self.parse8601(createdAt.clone().map(Value::from).unwrap_or(Value::Null));
        let __ws_arg_24 = self.parse8601(endDate.clone().map(Value::from).unwrap_or(Value::Null));
        let __ws_arg_25 = self.safe_string_k(rawEvent.clone(), "category", &[]);
        let __ws_arg_26 = self.parse8601(updatedAt.clone().map(Value::from).unwrap_or(Value::Null));
        let __ws_arg_27 = self.safe_string2(rawEvent.clone(), Value::Str("resolutionSource".into()), Value::Str("resolution_source".into()), &[]);
        let __ws_arg_28 = self.safe_bool2(rawEvent.clone(), Value::Str("closed".into()), Value::Str("resolved".into()), &[]);
        return self.extend(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), __ws_arg_18);
        m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("event".to_string(), (if ((slug.is_some()) && (slug.as_deref() != Some(""))) { __ws_arg_19 } else { Value::Null }));
        m.insert("title".to_string(), __ws_arg_20);
        m.insert("tags".to_string(), Value::from(parsedTags));
        m.insert("markets".to_string(), marketsList);
        m.insert("active".to_string(), active);
        m.insert("url".to_string(), __ws_arg_21);
        m.insert("image".to_string(), __ws_arg_22);
        m.insert("created".to_string(), __ws_arg_23);
        m.insert("createdDatetime".to_string(), createdAt.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("end".to_string(), __ws_arg_24);
        m.insert("endDatetime".to_string(), endDate.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("category".to_string(), __ws_arg_25);
        m.insert("lastUpdatedAt".to_string(), __ws_arg_26);
        m.insert("lastUpdatedAtDatetime".to_string(), updatedAt.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("resolutionSource".to_string(), __ws_arg_27);
        m.insert("resolved".to_string(), __ws_arg_28);
        m.insert("info".to_string(), rawEvent);
    m
}), &[]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#parseEvents
 * @description parses an array of raw gamma event objects into unified event objects
 * @param {object[]} rawEvents the raw gamma event objects
 * @returns {object[]} a list of event structures
 */
    pub fn parse_events(&self, mut rawEvents: Value) -> Value {
        let __rawEvents_empty = Vec::new();
        let rawEvents = rawEvents.as_array().unwrap_or(&__rawEvents_empty);
        let mut result: Vec<Value> = Vec::new();
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1450: bool = true;
            while { if !__for_first_1450 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1450 = false; i.as_f64().unwrap_or(f64::NAN) < ((rawEvents.len() as i64) as f64) } {
            let mut rawEvent: Value = rawEvents.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            result.push(self.parse_event(rawEvent));
        }
        }
        return Value::from(result);

    Value::Null
}

    pub fn handle_errors(&self, mut code: Value, mut reason: Value, mut url: Value, mut method: Value, mut headers: Value, mut body: Value, mut response: Value, mut requestHeaders: Value, mut requestBody: Value) -> Value {
        // the CLOB api returns { "error": "..." } (and createOrder variants use "errorMsg");
        // map the known messages so callers can distinguish a dead book or a rejected order
        // from a transport outage (the base otherwise maps a bare 404 to a retryable error)
        if (response == Value::Null) {
            return Value::Null;
        }
        let mut errorMessage: Option<String> = self.safe_string2_opt(response, Value::Str("error".into()), Value::Str("errorMsg".into()), &[]);
        if (errorMessage.is_some()) {
            let mut feedback: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), body).into());
            self.throw_exactly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("exact")).cloned().unwrap_or(Value::Null), errorMessage.clone().map(Value::from).unwrap_or(Value::Null), feedback.clone());
            self.throw_broadly_matched_exception(self.exceptions.as_map().and_then(|__m| __m.get("broad")).cloned().unwrap_or(Value::Null), errorMessage.map(Value::from).unwrap_or(Value::Null), feedback);
        }
        return Value::Null;

    Value::Null
}

    pub fn nonce(&self) -> Value {
        return self.milliseconds();

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#sign
 * @description builds the request url and attaches HMAC-SHA256 authentication headers for private endpoints
 * @param {string} path the endpoint path
 * @param {string[]} api the api group and access level
 * @param {string} method the http method
 * @param {object} params the request parameters
 * @returns {object} a dict with url, method, body and headers
 */
    pub fn sign(&self, mut path: Value, optional_args: &[Value]) -> Value {
        let mut api = get_arg(optional_args, 0, Value::from(vec![Value::Str("gamma".into())]));
        let mut method = get_arg(optional_args, 1, Value::Str("GET".into()));
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let __api_empty = Vec::new();
        let api = api.as_array().unwrap_or(&__api_empty);
        let mut apiGroup: Value = api.get(0).cloned().unwrap_or(Value::Null);
        let mut access: Option<String> = api.get(1).and_then(Value::as_str).map(str::to_owned);
        let mut baseUrls: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null);
        let mut baseUrl: Value = self.safe_string(baseUrls.clone(), apiGroup, &[baseUrls.as_map().and_then(|__m| __m.get("gamma")).cloned().unwrap_or(Value::Null)]);
        let mut url: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", baseUrl, Value::Str("/".into())).into()), self.implode_params(path.clone(), params.clone())).into());
        // an empty params container must not become a body: in PHP an empty array is
        // indistinguishable from an empty dict, so a bare Array.isArray check would json it to "[]"
        let mut isArrayBody: bool = false;
        if (matches!(&params, Value::Arr(_))) {
            let mut paramsList: Value = params.clone();
            let mut paramsListLength: f64 = ((paramsList.len() as i64) as f64);
            isArrayBody = paramsListLength > ((0i64) as f64);
        }
        let mut query: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        if !(isArrayBody) {
            query = self.omit(params.clone(), self.extract_params(path.clone()), &[]);
        }
        let mut bodyValue: Value = Value::Null;
        if (method.as_str() == Some("GET")) {
            // array-valued params must repeat the key (gamma's clob_token_ids rejects
            // comma-joined ids); scalar-only queries keep the plain encoder — the repeat
            // encoder capitalizes booleans ("False") under the C# base
            let mut hasArrayParam: bool = false;
            let mut queryKeys: Value = object_keys(&query);
            {
                                let mut i: i64 = 0;
                let mut __for_first_1451: bool = true;
                while { if !__for_first_1451 { i += 1; } __for_first_1451 = false; i < (queryKeys.len() as i64) } {
                if (matches!(&get_value(&query, &queryKeys.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null)), Value::Arr(_))) {
                    hasArrayParam = true;
                }
            }
            }
            let mut querystring: Value = Value::Null;
            if hasArrayParam {
                querystring = self.urlencode_with_array_repeat(query.clone());
            }  else {
                querystring = self.urlencode(query.clone(), &[]);
            }
            if (querystring.as_str() != Some("")) {
                url = Value::Str(format!("{}{}", url, Value::Str(format!("{}{}", Value::Str("?".into()), querystring).into())).into());
            }
        }  else if isArrayBody {
            bodyValue = json_stringify(&params);
        }  else {
            let mut queryKeys: Value = object_keys(&query);
            let mut queryKeysLength: f64 = ((queryKeys.len() as i64) as f64);
            if queryKeysLength > ((0i64) as f64) {
                bodyValue = json_stringify(&query);
            }
        }
        let mut headerDefaults: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut headersValue: Value = self.extend(Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("Accept".to_string(), Value::Str("application/json".into()));
                m.insert("Content-Type".to_string(), Value::Str("application/json".into()));
            m
        }), &[Value::Map(headerDefaults)]);
        if (access.as_deref() == Some("private")) {
            // 'auth/derive-api-key' is built by concatenation so the substring "api" sits at a
            // string-literal boundary: the php regex transpiler rewrites a bare "api" flanked by
            // '-' into the local var '$api' (it only skips quote/slash-adjacent matches), which
            // would corrupt the literal to 'auth/derive-$api-key' and break this check
            let mut deriveApiKeyPath: Value = Value::Str(format!("{}{}", Value::Str("auth/derive-".into()), Value::Str("api-key".into())).into());
            let mut isL1Auth: bool = (path.as_str() == Some("auth/api-key")) || (path.as_str() == deriveApiKeyPath.as_str()) || (path.as_str() == Some("auth/api-keys"));
            if isL1Auth {
                // L1 (private-key / EIP-712) auth used to create or derive the L2 api credentials
                if (self.privateKey.clone() == Value::Null) {
                    panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" ".into())).into()), path).into()), Value::Str(" requires a privateKey".into()))));
                }
                // the L1 signer/owner is the EOA behind the privateKey (walletAddress is the proxy/deposit wallet, not the signer)
                let mut address: Value = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
                let mut timestamp: Value = Value::Str(format!("{}", self.seconds()).into());
                let mut nonce: Value = self.safe_integer_k(params.clone(), "nonce", &[Value::Int(0)]);
                let mut l1signature: Value = self.sign_clob_auth(address.clone(), timestamp.clone(), nonce.clone()).map(Value::from).unwrap_or(Value::Null);
                let __ws_arg_29 = self.number_to_string(nonce);
                headersValue = self.extend(headersValue.clone(), &[Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("POLY_ADDRESS".to_string(), address.clone());
                        m.insert("POLY_SIGNATURE".to_string(), l1signature);
                        m.insert("POLY_TIMESTAMP".to_string(), timestamp.clone());
                        m.insert("POLY_NONCE".to_string(), __ws_arg_29);
                    m
                })]);
            }  else {
                // L2 credentials: provided directly (apiKey/secret/password) or derived from
                // the privateKey and cached in options (see setApiCredentials/loadApiCredentials)
                // prefer the derived creds (owned by the privateKey's EOA) over any externally supplied ones
                let mut apiKey: Value = self.safe_string_k(self.options.clone(), "l2ApiKey", &[self.apiKey.clone()]);
                let mut secret: Value = self.safe_string_k(self.options.clone(), "l2Secret", &[self.secret.clone()]);
                let mut passphrase: Value = self.safe_string_k(self.options.clone(), "l2Passphrase", &[self.password.clone()]);
                // POLY_ADDRESS is the api-key owner = the signer EOA (derived from the privateKey when present)
                let mut address: Value = Value::Null;
                if (self.privateKey.clone() != Value::Null) {
                    address = self.eth_checksum_address(self.eth_get_address_from_private_key(self.privateKey.clone(), &[])).map(Value::from).unwrap_or(Value::Null);
                }  else {
                    address = self.walletAddress.clone();
                }
                let mut timestamp: Value = Value::Str(format!("{}", self.seconds()).into());
                // the L2 HMAC signs only the request path (no query string), matching
                // @polymarket/clob-client — query params are sent separately, not signed
                let mut requestPath: Value = Value::Str(format!("{}{}", Value::Str("/".into()), self.implode_params(path, params)).into());
                let mut auth: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", timestamp, method).into()), requestPath).into());
                if (bodyValue != Value::Null) {
                    auth = Value::Str(format!("{}{}", auth, bodyValue).into());
                }
                // the L2 api secret is base64url-encoded; decode it to raw bytes for the HMAC key.
                // unchained replaceAll: the php transpiler only converts the outermost .replaceAll
                // in a chain, leaving the inner call as an (invalid) method call
                let mut plusSecret: Value = secret.as_str().map(|__s| Value::Str(__s.replace("-", "+").into())).unwrap_or_else(|| secret.clone());
                let mut normalizedSecret: Value = plusSecret.as_str().map(|__s| Value::Str(__s.replace("_", "/").into())).unwrap_or_else(|| plusSecret.clone());
                let mut secretBytes: Value = self.base64_to_binary(normalizedSecret, &[]);
                let mut signature: Value = self.hmac(self.encode(auth), secretBytes, Value::Str("sha256".into()), &[Value::Str("base64".into())]);
                // url-safe base64, preserving '=' padding (matches the reference client)
                signature = signature.as_str().map(|__s| Value::Str(__s.replace("+", "-").into())).unwrap_or_else(|| signature.clone());
                signature = signature.as_str().map(|__s| Value::Str(__s.replace("/", "_").into())).unwrap_or_else(|| signature.clone());
                headersValue = self.extend(headersValue.clone(), &[Value::Map({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("POLY_ADDRESS".to_string(), address);
                        m.insert("POLY_API_KEY".to_string(), apiKey);
                        m.insert("POLY_PASSPHRASE".to_string(), passphrase);
                        m.insert("POLY_SIGNATURE".to_string(), signature);
                        m.insert("POLY_TIMESTAMP".to_string(), timestamp);
                    m
                })]);
            }
        }
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("url".to_string(), url);
        m.insert("method".to_string(), method);
        m.insert("body".to_string(), bodyValue);
        m.insert("headers".to_string(), headersValue);
    m
});

    Value::Null
}

    pub fn hash_message(&self, mut message: Value) -> Option<String> {
        return Value::Str(format!("{}{}", Value::Str("0x".into()), self.hash(message, Value::Str("keccak".into()), &[Value::Str("hex".into())])).into()).as_str().map(str::to_owned);
}

    pub fn eth_checksum_address(&self, mut address: Value) -> Option<String> {
        // EIP-55 mixed-case checksum; the CLOB compares the order signer to the api-key owner
        // case-sensitively and stores addresses checksummed, so every address we send must be checksummed
        let mut cleaned: Value = (self.remove0x_prefix(address)).as_str().map(|__s| Value::Str(__s.to_lowercase().into())).unwrap_or(Value::Null);
        let mut hashHex: Value = self.hash(self.encode(cleaned.clone()), Value::Str("keccak".into()), &[Value::Str("hex".into())]);
        let mut addrChars: Vec<Value> = self.string_to_chars_array(cleaned).as_array().cloned().unwrap_or_default();
        let mut hashChars: Vec<Value> = self.string_to_chars_array(hashHex).as_array().cloned().unwrap_or_default();
        let mut upperNibbles: String = "89abcdef".to_string();
        let mut result: Value = Value::Str("".into());
        {
                        let mut i: i64 = 0;
            let mut __for_first_1452: bool = true;
            while { if !__for_first_1452 { i += 1; } __for_first_1452 = false; i < (addrChars.len() as i64) } {
            let mut ch: Value = addrChars.get(i as usize).cloned().unwrap_or(Value::Null);
            let mut hashCh: Value = hashChars.get(i as usize).cloned().unwrap_or(Value::Null);
            if Value::Int(Some(upperNibbles.as_str()).zip(hashCh.as_str()).and_then(|(__s, __n)| __s.find(__n)).map(|__i| __i as i64).unwrap_or(-1)).as_f64().unwrap_or(f64::NAN) >= ((0i64) as f64) {
                result = Value::Str(format!("{}{}", result, (if let Some(__s) = ch.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null })).into());
            }  else {
                result = Value::Str(format!("{}{}", result, ch).into());
            }
        }
        }
        return Value::Str(format!("{}{}", Value::Str("0x".into()), result).into()).as_str().map(str::to_owned);
}

    pub fn sign_hash(&self, mut hash: Value, mut privateKey: Value) -> Value {
        let mut signature: Value = ecdsa(hash.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null),
            privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null), Value::Str("secp256k1".into()), Value::Null);
        // assign before padStart so the PHP str_pad regex matches (it only handles a bare identifier)
        let mut rRaw: Value = signature.as_map().and_then(|__m| __m.get("r")).cloned().unwrap_or(Value::Null);
        let mut sRaw: Value = signature.as_map().and_then(|__m| __m.get("s")).cloned().unwrap_or(Value::Null);
        let mut r: Value = rRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
        let mut s: Value = sRaw.as_str().map(|__s| Value::Str(format!("{:0>64}", __s).into())).unwrap_or(Value::Null);
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("r".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), r).into()));
        m.insert("s".to_string(), Value::Str(format!("{}{}", Value::Str("0x".into()), s).into()));
        m.insert("v".to_string(), self.sum(&[Value::Int(27), signature.as_map().and_then(|__m| __m.get("v")).cloned().unwrap_or(Value::Null)]));
    m
});

    Value::Null
}

    pub fn sign_message(&self, mut message: Value, mut privateKey: Value) -> Value {
        return self.sign_hash(self.hash_message(message).map(Value::from).unwrap_or(Value::Null), privateKey.as_str().map(|__s| { let __c: Vec<char> = __s.chars().collect(); let __l = __c.len() as i64; let __i = (__l - 64).max(0); let __j = __l; if __i <= __j { __c[__i as usize..__j as usize].iter().collect::<String>() } else { String::new() } }).map(Value::from).unwrap_or(Value::Null));

    Value::Null
}

    pub fn sign_clob_auth(&self, mut address: Value, mut timestamp: Value, mut nonce: Value) -> Option<String> {
        // EIP-712 ClobAuth signature used for L1 auth (creating/deriving L2 api credentials)
        let mut domain: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("name".to_string(), Value::Str("ClobAuthDomain".into()));
                m.insert("version".to_string(), Value::Str("1".into()));
                m.insert("chainId".to_string(), Value::Int(137));
            m
        });
        let mut messageTypes: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("ClobAuth".to_string(), Value::from(vec![Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("address".into()));
        m.insert("type".to_string(), Value::Str("address".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("timestamp".into()));
        m.insert("type".to_string(), Value::Str("string".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("nonce".into()));
        m.insert("type".to_string(), Value::Str("uint256".into()));
    m
}), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("message".into()));
        m.insert("type".to_string(), Value::Str("string".into()));
    m
})]));
            m
        });
        let mut messageData: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("address".to_string(), address);
                m.insert("timestamp".to_string(), timestamp);
                m.insert("nonce".to_string(), nonce);
                m.insert("message".to_string(), Value::Str("This message attests that I control the given wallet".into()));
            m
        });
        let mut encoded: Value = self.eth_encode_structured_data(Value::Map(domain), Value::Map(messageTypes), Value::Map(messageData));
        let mut sig: indexmap::IndexMap<String, Value> = self.sign_message(encoded, self.privateKey.clone()).as_map().cloned().unwrap_or_default();
        return Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("0x".into()), self.remove0x_prefix(sig.get("r").cloned().unwrap_or(Value::Null))).into()), self.remove0x_prefix(sig.get("s").cloned().unwrap_or(Value::Null))).into()), self.int_to_base16(sig.get("v").cloned().unwrap_or(Value::Null), &[])).into()).as_str().map(str::to_owned);
}

/*
 * @method
 * @name polymarket#deriveApiKey
 * @description derives the L2 api credentials (apiKey, secret, passphrase) deterministically from the wallet private key
 * @see https://docs.polymarket.com/developers/CLOB/authentication
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {int} [params.nonce] the nonce used to derive the credentials, defaults to 0
 * @returns {object} the api credentials { apiKey, secret, passphrase }
 */
    pub async fn derive_api_key(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut response: Value = self.clob_private_get_auth_derive_api_key(&[params]).await;
        return self.set_api_credentials(response);

    Value::Null
}

/*
 * @method
 * @name polymarket#createApiKey
 * @description creates new L2 api credentials (apiKey, secret, passphrase) for the wallet private key
 * @see https://docs.polymarket.com/developers/CLOB/authentication
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {int} [params.nonce] the nonce used to create the credentials, defaults to 0
 * @returns {object} the api credentials { apiKey, secret, passphrase }
 */
    pub async fn create_api_key(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut response: Value = self.clob_private_post_auth_api_key(&[params]).await;
        return self.set_api_credentials(response);

    Value::Null
}

/*
 * @method
 * @name polymarket#createOrDeriveApiKey
 * @description derives the existing L2 api credentials for the wallet private key, creating them if none exist yet
 * @see https://docs.polymarket.com/developers/CLOB/authentication
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} the api credentials { apiKey, secret, passphrase }
 */
    pub async fn create_or_derive_api_key(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut creds: Value = Value::Null;
        let _try_result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
            creds = self.derive_api_key(&[params.clone()]).await;
         #[allow(unreachable_code)] { Value::Null }})).await;
if _try_result.is_err() {
            creds = self.create_api_key(&[params]).await;
        }
        if (creds == Value::Null) {
            panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" createOrDeriveApiKey() returned no credentials".into()))));
        }
        return creds;

    Value::Null
}

    pub fn set_api_credentials(&self, mut response: Value) -> Value {
        //
        //     { "apiKey": "...", "secret": "...", "passphrase": "..." }
        //
        let mut creds: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("apiKey".to_string(), self.safe_string2(response.clone(), Value::Str("apiKey".into()), Value::Str("key".into()), &[]));
                m.insert("secret".to_string(), self.safe_string_k(response.clone(), "secret", &[]));
                m.insert("passphrase".to_string(), self.safe_string_k(response, "passphrase", &[]));
            m
        });
        // cache in options rather than the typed apiKey/secret/password fields so the
        // assignment is valid in the struct-based languages (C#/Go/Java)
        if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2ApiKey".into(), creds.get("apiKey").cloned().unwrap_or(Value::Null)); }
        if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2Secret".into(), creds.get("secret").cloned().unwrap_or(Value::Null)); }
        if let Value::Dict(__d) = &mut self.options.clone() { std::sync::Arc::make_mut(__d).insert("l2Passphrase".into(), creds.get("passphrase").cloned().unwrap_or(Value::Null)); }
        return Value::Map(creds);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name polymarket#loadApiCredentials
 * @description ensures L2 api credentials are available for private requests — uses the provided apiKey/secret/password when present, otherwise derives them from the privateKey
 */
    pub async fn load_api_credentials(&mut self) -> Value {
        // the order signer / L2 POLY_ADDRESS is always the EOA behind the privateKey, so the L2 api key MUST
        // belong to that same EOA — derive it from the privateKey rather than trusting externally supplied
        // creds that may have been issued to a different wallet
        if (self.privateKey.clone() != Value::Null) {
            let mut alreadyDerived: Option<String> = self.safe_string_k(self.options.clone(), "l2ApiKey", &[]).as_str().map(str::to_owned);
            if (alreadyDerived.is_none()) {
                self.create_or_derive_api_key(&[]).await;
            }
            return Value::Null;
        }
        let mut apiKey: Value = (if (self.apiKey.clone() != Value::Null) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "l2ApiKey", &[]) });
        let mut secret: Value = Value::Null;
        if (self.secret.clone() != Value::Null) {
            secret = self.secret.clone();
        }  else {
            secret = self.safe_string_k(self.options.clone(), "l2Secret", &[]);
        }
        let mut passphrase: Value = (if (self.password.clone() != Value::Null) { self.password.clone() } else { self.safe_string_k(self.options.clone(), "l2Passphrase", &[]) });
        let mut hasL2: bool = (apiKey != Value::Null) && (secret != Value::Null) && (passphrase != Value::Null);
        if hasL2 {
            return Value::Null;
        }
        panic!("{}", crate::exchange_errors::authentication_error(format!("{}{}", self.id.clone(), Value::Str(" requires L2 api credentials (apiKey, secret, password) or a privateKey to derive them".into()))));

    Value::Null
}

    pub fn ping(&self, mut client: Value) -> Value {
        return Value::Str("PING".into());

    Value::Null
}

    pub fn handle_text_message(&self, mut client: Value, mut message: Value) {
        // Polymarket keeps the ws alive with text PING/PONG (not protocol ping-pong frames), so the
        // client's onPong never fires; refresh client.lastPong here on the "PONG" reply, otherwise the
        // base keepalive treats the connection as stale and times it out after maxPingPongMisses.
        crate::set_value(&mut client, &Value::Str("lastPong".into()), self.milliseconds());
}

    pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
        self.handle_message_event(client, message);
}

    pub fn handle_list_message(&mut self, mut client: Value, mut message: Value) {
        let __message_empty = Vec::new();
        let message = message.as_array().unwrap_or(&__message_empty);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1453: bool = true;
            while { if !__for_first_1453 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1453 = false; i.as_f64().unwrap_or(f64::NAN) < ((message.len() as i64) as f64) } {
            let mut event: Value = message.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            if (event == Value::Null) || (event == Value::Null) || (!matches!(&event, Value::Dict(_))) {
                continue;
            }
            self.handle_message_event(client.clone(), event);
        }
        }
}

    pub fn handle_message_event(&mut self, mut client: Value, mut event: Value) {
        let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
        let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
        let mut eventType: Option<String> = (match __pro_message.get("event_type").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }).as_str().map(str::to_owned);
        if (eventType.as_deref() == Some("book")) {
            self.handle_order_book_snapshot(client.clone(), event.clone());
        }  else if (eventType.as_deref() == Some("price_change")) {
            self.handle_order_book_delta(client.clone(), event.clone());
        }  else if (eventType.as_deref() == Some("last_trade_price")) {
            self.handle_trade(client.clone(), event.clone());
        }  else if (eventType.as_deref() == Some("order")) {
            self.handle_order(client.clone(), event.clone());
        }  else if (eventType.as_deref() == Some("trade")) {
            self.handle_my_trade(client, event);
        }
}

    pub fn handle_order_book_snapshot(&self, mut client: Value, mut event: Value) {
        let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
        let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
        let mut tokenId: Option<String> = match __pro_message.get("asset_id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
        let mut outcome: Value = self.token_id_to_symbol(tokenId.clone().map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
        if (outcome == Value::Null) {
            return;
        }
        if !(matches!((&self.orderbooks, &outcome), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
            let mut seededBook: Value = self.order_book(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            if let Value::Dict(__d) = &mut self.orderbooks.clone() { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), seededBook); }
        }
        let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
        let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event, "timestamp", &[]));
        let mut rawBids: Value = (match __pro_message.get("bids").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
        let mut rawAsks: Value = (match __pro_message.get("asks").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
        let mut bids: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1454: bool = true;
            while { if !__for_first_1454 { i += 1; } __for_first_1454 = false; i < (rawBids.len() as i64) } {
            let mut b: Value = self.safe_dict(rawBids.clone(), Value::Int(i), &[]);
            bids.push(Value::from(vec![self.safe_number_k(b.clone(), "price", &[]), self.safe_number_k(b, "size", &[])]));
        }
        }
        let mut asks: Vec<Value> = Vec::new();
        {
                        let mut j: i64 = 0;
            let mut __for_first_1455: bool = true;
            while { if !__for_first_1455 { j += 1; } __for_first_1455 = false; j < (rawAsks.len() as i64) } {
            let mut a: Value = self.safe_dict(rawAsks.clone(), Value::Int(j), &[]);
            asks.push(Value::from(vec![self.safe_number_k(a.clone(), "price", &[]), self.safe_number_k(a, "size", &[])]));
        }
        }
        let mut outcomeObj: Value = self.safe_outcome(outcome.clone(), &[]);
        orderbook.reset(Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("bids".to_string(), Value::from(bids));
                m.insert("asks".to_string(), Value::from(asks));
                m.insert("timestamp".to_string(), timestamp.clone());
                m.insert("datetime".to_string(), self.iso8601(timestamp));
                m.insert("outcome".to_string(), outcome.clone());
                m.insert("outcomeId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
                m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
            m
        }));
        client.resolve(&[orderbook.clone(), Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcome).into())]);
        client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcome).into())]);
}

    pub fn handle_order_book_delta(&self, mut client: Value, mut event: Value) {
        let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
        let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
        let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event, "timestamp", &[]));
        let mut changes: Value = (match __pro_message.get("price_changes").cloned() { Some(__v) if matches!(__v, Value::Arr(_)) => __v, _ => Value::from(vec![]) });
        let mut updated: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        {
                        let mut i: i64 = 0;
            let mut __for_first_1456: bool = true;
            while { if !__for_first_1456 { i += 1; } __for_first_1456 = false; i < (changes.len() as i64) } {
            let mut change: Value = self.safe_dict(changes.clone(), Value::Int(i), &[]);
            let mut tokenId: Option<String> = self.safe_string_k_opt(change.clone(), "asset_id", &[]);
            let mut outcome: Value = self.token_id_to_symbol(tokenId.map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
            if (outcome == Value::Null) || !(matches!((&self.orderbooks, &outcome), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                continue;
            }
            let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
            let mut price: Value = self.safe_number_k(change.clone(), "price", &[]);
            let mut size: Value = self.safe_number_k(change.clone(), "size", &[]);
            let mut isBuy: bool = self.safe_string_upper_k(change, "side", &[Value::Str("".into())]).as_str() == Some("BUY");
            let mut side: Value = (if isBuy { orderbook.book_field("bids") } else { orderbook.book_field("asks") });
            // storeArray([price, size]) inserts/updates or removes (size=0) the level
            let mut sideRef: Value = side;
            sideRef.store_array(Value::from(vec![price, size]));
            orderbook.set_book_meta("timestamp", timestamp.clone());
            orderbook.set_book_meta("datetime", self.iso8601(timestamp.clone()));
            if let Value::Dict(__d) = &mut updated { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), Value::Bool(true)); }
        }
        }
        let mut updatedSymbols: Vec<Value> = Value::Array(updated.as_map().map(|__m| __m.keys().map(|__k| Value::Str(__k.clone().into())).collect()).unwrap_or_default()).as_array().cloned().unwrap_or_default();
        {
                        let mut k: i64 = 0;
            let mut __for_first_1457: bool = true;
            while { if !__for_first_1457 { k += 1; } __for_first_1457 = false; k < (updatedSymbols.len() as i64) } {
            let mut outcome: Value = updatedSymbols.get(k as usize).cloned().unwrap_or(Value::Null);
            let mut orderbook: Value = (if let (Some(__m), Some(__k)) = (self.orderbooks.as_map(), outcome.as_str()) { __m.get(__k).cloned().unwrap_or(Value::Null) } else { Value::Null });
            client.resolve(&[orderbook.clone(), Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcome).into())]);
            client.resolve(&[orderbook, Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcome).into())]);
        }
        }
}

    pub fn handle_trade(&mut self, mut client: Value, mut event: Value) {
        let __pro_message_arc: std::sync::Arc<indexmap::IndexMap<String, Value>> = (if let Value::Dict(__d) = &event { __d.clone() } else { std::sync::Arc::new(indexmap::IndexMap::new()) });
        let __pro_message: &indexmap::IndexMap<String, Value> = &__pro_message_arc;
        let mut tokenId: Option<String> = match __pro_message.get("asset_id").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Some(__s.to_string()), Some(Value::Int(__n)) => Some(__n.to_string()), Some(Value::Float(__f)) => Some(__f.to_string()), _ => None };
        let mut outcome: Value = self.token_id_to_symbol(tokenId.clone().map(Value::from).unwrap_or(Value::Null)).map(Value::from).unwrap_or(Value::Null);
        if (outcome == Value::Null) {
            return;
        }
        let mut timestamp: Value = self.parse_poly_timestamp(self.safe_string_k(event.clone(), "timestamp", &[]));
        let mut price: Value = (match __pro_message.get("price").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null });
        let mut amount: Value = (match __pro_message.get("size").cloned() { Some(Value::Float(__f)) => Value::Float(__f), Some(Value::Int(__n)) => Value::Float(__n as f64), Some(Value::Str(__s)) if !__s.is_empty() => match __s.parse::<f64>() { Ok(__f) => Value::Float(__f), Err(_) => Value::Null }, _ => Value::Null });
        let mut market: Value = self.safe_outcome(tokenId.map(Value::from).unwrap_or(Value::Null), &[]);
        let mut trade: Value = self.safe_prediction_trade(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), (match __pro_message.get("transaction_hash").cloned() { Some(Value::Str(__s)) if !__s.is_empty() => Value::Str(__s), Some(Value::Int(__n)) => Value::Str(__n.to_string().into()), Some(Value::Float(__f)) => Value::Str(__f.to_string().into()), _ => Value::Null }));
        m.insert("info".to_string(), event.clone());
        m.insert("timestamp".to_string(), timestamp.clone());
        m.insert("datetime".to_string(), self.iso8601(timestamp));
        m.insert("outcome".to_string(), outcome.clone());
        m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
        m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
        m.insert("order".to_string(), Value::Null);
        m.insert("type".to_string(), Value::Null);
        m.insert("side".to_string(), self.safe_string_lower_k(event, "side", &[]));
        m.insert("takerOrMaker".to_string(), Value::Str("taker".into()));
        m.insert("price".to_string(), price);
        m.insert("amount".to_string(), amount);
        m.insert("cost".to_string(), Value::Null);
        m.insert("fee".to_string(), Value::Null);
    m
}), &[market]);
        if (self.trades.clone() == Value::Null) {
            self.trades = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
        }
        let mut stored: Value = self.safe_value(self.trades.clone(), outcome.clone(), &[]);
        if (stored == Value::Null) {
            let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
            stored = ArrayCache::new(limit);
            if let Value::Dict(__d) = &mut self.trades { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&outcome), stored.clone()); }
        }
        stored.append(trade);
        client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("trades::".into()), outcome).into())]);
}

/*
 * @method
 * @name polymarket#watchOrderBook
 * @description streams live order-book updates for a single Polymarket outcome token
 * @param {string} outcome unified outcome (e.g. "TRUMP_WINS_2028:YES") or an outcome token id
 * @param {int} [limit] optional depth limit applied after resolving
 * @param {object} [params] extra params (currently unused)
 * @returns {object} a [prediction order book structure]{@link https://docs.ccxt.com/#/?id=prediction-order-book-structure}
 */
    pub async fn watch_order_book(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut limit = get_arg(optional_args, 0, Value::Null);
        let mut params = get_arg(optional_args, 1, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
        let outcomeValue: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
        let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("orderbook::".into()), outcomeValue).into());
        let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
        let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
                m.insert("type".to_string(), Value::Str("market".into()));
            m
        });
        let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
        let mut orderbook: Value = self.watch(url, messageHash, &[Value::Map(subscribeMsg), subscribeHash]).await;
        return orderbook.limit();

    Value::Null
}

/*
 * @method
 * @name polymarket#watchTrades
 * @description streams live fills for a single Polymarket outcome token
 * @param {string} outcome unified outcome
 * @param {int} [since] optional unix timestamp (ms) lower bound
 * @param {int} [limit] optional max number of trades to return
 * @param {object} [params] extra params (unused)
 * @returns {object[]} a list of [prediction trade structures]{@link https://docs.ccxt.com/#/?id=prediction-trade-structure}
 */
    pub async fn watch_trades(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
        let outcomeValue: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
        let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("trades::".into()), outcomeValue).into());
        let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
        let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
                m.insert("type".to_string(), Value::Str("market".into()));
            m
        });
        let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
        let mut trades: Value = self.watch(url, messageHash, &[Value::Map(subscribeMsg), subscribeHash]).await;
        return self.filter_by_since_limit(trades, &[since, limit, Value::Str("timestamp".into()), Value::Bool(true)]);

    Value::Null
}

/*
 * @method
 * @name polymarket#watchTicker
 * @description streams a synthetic ticker derived from order-book snapshots and deltas (mid = (bid + ask) / 2)
 * @param {string} outcome unified outcome
 * @param {object} [params] extra params (unused)
 * @returns {object} a [prediction ticker structure]{@link https://docs.ccxt.com/#/?id=prediction-ticker-structure}
 */
    pub async fn watch_ticker(&mut self, mut outcome: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut outcomeObj: Value = self.load_outcome(outcome, &[]).await;
        let mut tokenId: Value = self.safe_string_k(outcomeObj.clone(), "outcomeId", &[Value::Str("".into())]);
        let mut outcomeValue: Option<String> = self.safe_string_k_opt(outcomeObj, "outcome", &[]);
        if (outcomeValue.is_none()) {
            panic!("{}", crate::exchange_errors::exchange_error(format!("{}{}", self.id.clone(), Value::Str(" watchTicker() missing outcome".into()))));
        }
        let mut messageHash: Value = Value::Str(format!("{}{}", Value::Str("ticker::".into()), outcomeValue.clone().map(Value::from).unwrap_or(Value::Null)).into());
        let mut subscribeHash: Value = Value::Str(format!("{}{}", Value::Str("subscribe::".into()), tokenId).into());
        let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("assets_ids".to_string(), Value::from(vec![tokenId]));
                m.insert("type".to_string(), Value::Str("market".into()));
            m
        });
        if !(matches!((&self.orderbooks, &outcomeValue.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
            let mut seededBook: Value = self.order_book(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            if (outcomeValue.is_some()) {
                if let Value::Dict(__d) = &mut self.orderbooks { std::sync::Arc::make_mut(__d).insert(outcomeValue.as_deref().unwrap_or("null").to_string(), seededBook); }
            }
        }
        let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("ws")).cloned().unwrap_or(Value::Null);
        let mut orderbook: Value = self.watch(url, messageHash, &[Value::Map(subscribeMsg), subscribeHash]).await;
        let mut bids: Value = crate::value::get_value_k(&orderbook, "bids");
        let mut asks: Value = crate::value::get_value_k(&orderbook, "asks");
        let mut bestBid: Value = Value::Null;
        let mut bestBidVolume: Value = Value::Null;
        let mut bidsLength: Value = Value::Int(0);
        if (bids != Value::Null) {
            bidsLength = get_array_length(&bids);
        }
        if (bids != Value::Null) && (bidsLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
            bestBid = get_value(&get_value(&bids, &Value::Int(0)), &Value::Int(0));
            bestBidVolume = get_value(&get_value(&bids, &Value::Int(0)), &Value::Int(1));
        }
        let mut bestAsk: Value = Value::Null;
        let mut bestAskVolume: Value = Value::Null;
        let mut asksLength: Value = Value::Int(0);
        if (asks != Value::Null) {
            asksLength = get_array_length(&asks);
        }
        if (asks != Value::Null) && (asksLength.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
            bestAsk = get_value(&get_value(&asks, &Value::Int(0)), &Value::Int(0));
            bestAskVolume = get_value(&get_value(&asks, &Value::Int(0)), &Value::Int(1));
        }
        let mut mid: Value = Value::Null;
        if (bestBid != Value::Null) && (bestAsk != Value::Null) {
            let mut sum: Value = crate::precise::Precise::stringAdd(&self.number_to_string(bestBid.clone()), &self.number_to_string(bestAsk.clone()));
            mid = self.parse_number(crate::precise::Precise::stringDiv(&sum, &Value::Str("2".into())), &[]);
        }  else if (bestBid != Value::Null) {
            mid = bestBid.clone();
        }  else {
            mid = bestAsk.clone();
        }
        let mut market: Value = self.safe_outcome(outcomeValue.clone().map(Value::from).unwrap_or(Value::Null), &[]);
        return self.safe_prediction_ticker(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("outcome".to_string(), outcomeValue.map(Value::from).unwrap_or(Value::Null));
        m.insert("outcomeId".to_string(), self.safe_string_k(market.clone(), "outcomeId", &[]));
        m.insert("label".to_string(), self.safe_string_k(market.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(market.clone(), "market", &[]));
        m.insert("timestamp".to_string(), crate::value::get_value_k(&orderbook, "timestamp"));
        m.insert("datetime".to_string(), crate::value::get_value_k(&orderbook, "datetime"));
        m.insert("high".to_string(), Value::Null);
        m.insert("low".to_string(), Value::Null);
        m.insert("bid".to_string(), bestBid);
        m.insert("bidVolume".to_string(), bestBidVolume);
        m.insert("ask".to_string(), bestAsk);
        m.insert("askVolume".to_string(), bestAskVolume);
        m.insert("vwap".to_string(), Value::Null);
        m.insert("open".to_string(), Value::Null);
        m.insert("close".to_string(), mid.clone());
        m.insert("last".to_string(), mid.clone());
        m.insert("previousClose".to_string(), Value::Null);
        m.insert("change".to_string(), Value::Null);
        m.insert("percentage".to_string(), Value::Null);
        m.insert("average".to_string(), mid);
        m.insert("baseVolume".to_string(), Value::Null);
        m.insert("quoteVolume".to_string(), Value::Null);
        m.insert("info".to_string(), orderbook);
    m
}), &[market]);

    Value::Null
}

/*
 * @method
 * @name polymarket#watchOrders
 * @description watches the authenticated user's order updates over the CLOB user websocket channel
 * @see https://docs.polymarket.com/developers/CLOB/websocket/user-channel
 * @param {string} [outcome] unified outcome to filter the stream to one market
 * @param {int} [since] the earliest time in ms to return orders for
 * @param {int} [limit] the maximum number of orders to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        let mut messageHash: Value = Value::Str("orders".into());
        let mut outcomeResolved: Value = outcome;
        if (outcomeResolved != Value::Null) {
            let mut outcomeObj: Value = self.load_outcome(outcomeResolved.clone(), &[]).await;
            outcomeResolved = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
            let outcomeName: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
            messageHash = Value::Str(format!("{}{}", Value::Str("orders::".into()), outcomeName).into());
        }
        let mut orders: Value = self.subscribe_user_channel(messageHash, &[params]).await;
        let mut limitResolved: Value = limit;
        if self.newUpdates.as_bool() == Some(true) {
            limitResolved = orders.get_limit(outcomeResolved.clone(), limitResolved.clone());
        }
        return self.filter_by_outcome_since_limit(orders, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);

    Value::Null
}

/*
 * @method
 * @name polymarket#watchMyTrades
 * @description watches the authenticated user's trade fills over the CLOB user websocket channel
 * @see https://docs.polymarket.com/developers/CLOB/websocket/user-channel
 * @param {string} [outcome] unified outcome to filter the stream to one market
 * @param {int} [since] the earliest time in ms to return trades for
 * @param {int} [limit] the maximum number of trades to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [prediction trade structures](https://docs.ccxt.com/#/?id=prediction-trade-structure)
 */
    pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
        let mut outcome = get_arg(optional_args, 0, Value::Null);
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        self.load_api_credentials().await;
        let mut messageHash: Value = Value::Str("myTrades".into());
        let mut outcomeResolved: Value = outcome;
        if (outcomeResolved != Value::Null) {
            let mut outcomeObj: Value = self.load_outcome(outcomeResolved.clone(), &[]).await;
            outcomeResolved = self.safe_string_k(outcomeObj.clone(), "outcome", &[]);
            let outcomeName: String = self.safe_string_k_opt(outcomeObj, "outcome", &[Value::Str("".into())]).unwrap_or_default();
            messageHash = Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcomeName).into());
        }
        let mut trades: Value = self.subscribe_user_channel(messageHash, &[params]).await;
        let mut limitResolved: Value = limit;
        if self.newUpdates.as_bool() == Some(true) {
            limitResolved = trades.get_limit(outcomeResolved.clone(), limitResolved.clone());
        }
        return self.filter_by_outcome_since_limit(trades, &[outcomeResolved, since, limitResolved, Value::Bool(true)]);

    Value::Null
}

    pub async fn subscribe_user_channel(&mut self, mut messageHash: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        // the user channel authenticates inside the subscribe frame, not via HMAC headers
        let mut apiKey: Value = (if (self.apiKey.clone() != Value::Null) { self.apiKey.clone() } else { self.safe_string_k(self.options.clone(), "l2ApiKey", &[]) });
        let mut secret: Value = Value::Null;
        if (self.secret.clone() != Value::Null) {
            secret = self.secret.clone();
        }  else {
            secret = self.safe_string_k(self.options.clone(), "l2Secret", &[]);
        }
        let mut passphrase: Value = (if (self.password.clone() != Value::Null) { self.password.clone() } else { self.safe_string_k(self.options.clone(), "l2Passphrase", &[]) });
        let mut auth: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("apiKey".to_string(), apiKey);
                m.insert("secret".to_string(), secret);
                m.insert("passphrase".to_string(), passphrase);
            m
        });
        // an empty markets list subscribes to every market the user is active in
        let mut subscribeMsg: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("auth".to_string(), Value::Map(auth));
                m.insert("markets".to_string(), Value::from(vec![]));
                m.insert("type".to_string(), Value::Str("user".into()));
            m
        });
        let mut url: Value = self.urls.as_map().and_then(|__m| __m.get("api")).cloned().unwrap_or(Value::Null).as_map().and_then(|__m| __m.get("wsUser")).cloned().unwrap_or(Value::Null);
        let mut subscribeHash: String = "user".to_string();
        let __ws_arg_30 = self.extend(Value::Map(subscribeMsg), &[params]);
        return self.watch(url, messageHash, &[__ws_arg_30, Value::from(subscribeHash)]).await;

    Value::Null
}

    pub fn handle_order(&mut self, mut client: Value, mut event: Value) {
        if (self.orders.clone() == Value::Null) {
            let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
            self.orders = ArrayCacheByOutcomeById::new(limit);
        }
        let mut stored: Value = self.orders.clone();
        let mut parsed: Value = self.parse_prediction_order(event, &[]);
        stored.append(parsed.clone());
        client.resolve(&[stored.clone(), Value::Str("orders".into())]);
        let mut outcome: Option<String> = self.safe_string_k_opt(parsed, "outcome", &[]);
        if (outcome.is_some()) {
            client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("orders::".into()), outcome.map(Value::from).unwrap_or(Value::Null)).into())]);
        }
}

    pub fn handle_my_trade(&mut self, mut client: Value, mut event: Value) {
        if (self.myTrades.clone() == Value::Null) {
            let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
            self.myTrades = ArrayCacheByOutcomeById::new(limit);
        }
        let mut stored: Value = self.myTrades.clone();
        let mut parsed: Value = self.parse_prediction_trade(event, &[]);
        stored.append(parsed.clone());
        client.resolve(&[stored.clone(), Value::Str("myTrades".into())]);
        let mut outcome: Option<String> = self.safe_string_k_opt(parsed, "outcome", &[]);
        if (outcome.is_some()) {
            client.resolve(&[stored, Value::Str(format!("{}{}", Value::Str("myTrades::".into()), outcome.map(Value::from).unwrap_or(Value::Null)).into())]);
        }
}

    pub fn token_id_to_symbol(&self, mut tokenId: Value) -> Option<String> {
        if (tokenId == Value::Null) || (tokenId.as_str() == Some("")) {
            return None;
        }
        // outcome tokens are keyed in outcomes_by_id (populated by fetchEvents/loadMarkets);
        // fall back to markets_by_id for the standard market lookup
        let mut outcomeObj: Value = self.safe_dict(self.exchange.outcomes_by_id.clone(), tokenId.clone(), &[]);
        if (outcomeObj != Value::Null) {
            return self.safe_string_k(outcomeObj, "outcome", &[]).as_str().map(str::to_owned);
        }
        // safe dict/string access: a bare marketsById[tokenId] / market['market'] is undefined in JS
        // but raises KeyError in Python when the token isn't a market id (the ws trade path hits this)
        let mut market: Value = self.safe_dict(self.markets_by_id.clone(), tokenId, &[]);
        return self.safe_string2(market, Value::Str("market".into()), Value::Str("symbol".into()), &[]).as_str().map(str::to_owned);
}

    pub fn parse_poly_timestamp(&self, mut raw: Value) -> Value {
        if (raw == Value::Null) {
            return Value::Null;
        }
        return self.parse_to_int(raw);

    Value::Null
}
}