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
// 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 BinanceCore {
    pub exchange: crate::prediction_exchange::PredictionExchange,
}

impl BinanceCore {
    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 = BinanceCore::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 BinanceCore {
    fn nonce(&self, ) -> crate::Value {
        // Forward to the inherent method on BinanceCore.
        BinanceCore::nonce(self, )
    }
    fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
        // Forward to the inherent method on BinanceCore.
        BinanceCore::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 BinanceCore.
        BinanceCore::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 BinanceCore.
        BinanceCore::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 BinanceCore.
        BinanceCore::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 BinanceCore.
        BinanceCore::handle_errors(self, code, reason, url, method, headers, body, response, request_headers, request_body)
    }
}

impl crate::exchange_generated::ExchangeBase for BinanceCore {
    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 {
                "amount_to_precision" => self.amount_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "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,
                "complete_raw_topics" => self.complete_raw_topics(args.get(0).cloned().unwrap_or(crate::Value::Null)).await,
                "create_market_order_with_cost" => self.create_market_order_with_cost(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[3.min(args.len())..]).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,
                "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_events_by_query" => self.fetch_events_by_query(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args[2.min(args.len())..]).await,
                "fetch_markets" => self.fetch_markets(&args[..]).await,
                "fetch_my_trades" => self.fetch_my_trades(&args[..]).await,
                "fetch_open_orders" => self.fetch_open_orders(&args[..]).await,
                "fetch_order_book" => self.fetch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_orders" => self.fetch_orders(&args[..]).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_quote" => self.fetch_quote(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_raw_topic_detail" => self.fetch_raw_topic_detail(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).await,
                "fetch_raw_topics" => self.fetch_raw_topics(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]).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_wallet" => self.fetch_wallet(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)),
                "nonce" => self.nonce(),
                "parse_event" => self.parse_event(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "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())..]),
                "parse_topic_market" => self.parse_topic_market(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "price_to_precision" => self.price_to_precision(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "sign" => self.sign(args.get(0).cloned().unwrap_or(crate::Value::Null), &args[1.min(args.len())..]),
                // 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 BinanceCore {
    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 BinanceCore {
    type Target = crate::exchange::Exchange;
    fn deref(&self) -> &crate::exchange::Exchange { std::ops::Deref::deref(&self.exchange) }
}

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

impl BinanceCore {
    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("binance".into()));
        m.insert("name".to_string(), Value::Str("Binance".into()));
        m.insert("countries".to_string(), Value::from(vec![]));
        m.insert("rateLimit".to_string(), Value::Int(5));
        m.insert("version".to_string(), Value::Str("v1".into()));
        m.insert("certified".to_string(), Value::Bool(false));
        m.insert("pro".to_string(), Value::Bool(false));
        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("cancelOrder".to_string(), Value::Bool(true));
        m.insert("cancelOrders".to_string(), Value::Bool(true));
        m.insert("createMarketOrderWithCost".to_string(), Value::Bool(true));
        m.insert("createOrder".to_string(), Value::Bool(true));
        m.insert("fetchBalance".to_string(), Value::Bool(true));
        m.insert("fetchEvent".to_string(), Value::Bool(true));
        m.insert("fetchEvents".to_string(), Value::Bool(true));
        m.insert("fetchMarkets".to_string(), Value::Bool(true));
        m.insert("fetchMyTrades".to_string(), Value::Bool(true));
        m.insert("fetchOpenOrders".to_string(), Value::Bool(true));
        m.insert("fetchOrderBook".to_string(), Value::Bool(true));
        m.insert("fetchOrders".to_string(), Value::Bool(true));
        m.insert("fetchPosition".to_string(), Value::Bool(true));
        m.insert("fetchPositions".to_string(), Value::Bool(true));
        m.insert("fetchTicker".to_string(), Value::Bool(true));
        m.insert("fetchTickers".to_string(), Value::Bool(true));
        m.insert("prediction".to_string(), Value::Bool(true));
    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/e9419b93-ccb0-46aa-9bff-c883f096274b".into()));
        m.insert("api".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("sapi".to_string(), Value::Str("https://api.binance.com/sapi/v1/w3w/wallet/prediction".into()));
    m
}));
        m.insert("www".to_string(), Value::Str("https://www.binance.com/en/markets/prediction".into()));
        m.insert("doc".to_string(), Value::from(vec![Value::Str("https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading".into())]));
    m
}));
        m.insert("api".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("sapi".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        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("category/list".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("market/list".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("market/search".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("market/detail".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("order-book".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("order-book/last-trade-price".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("wallet/list".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("balance/payment-options".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("quota/limit/status".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("pnl/portfolio".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("pnl/query".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("position/list".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("position/filter".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("position/token".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("position/settled-history".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("order/list".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("order/history".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
    m
}));
        m.insert("post".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("trade/get-quote".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("trade/place-order-bundle".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
        m.insert("trade/batch-cancel".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("cost".to_string(), Value::Int(200));
    m
}));
    m
}));
    m
}));
    m
}));
    m
}));
        m.insert("requiredCredentials".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("apiKey".to_string(), Value::Bool(true));
        m.insert("secret".to_string(), Value::Bool(true));
    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::Float(0.02));
    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("-1003".to_string(), Value::Str("RateLimitExceeded".into()));
        m.insert("-1021".to_string(), Value::Str("InvalidNonce".into()));
        m.insert("-1022".to_string(), Value::Str("AuthenticationError".into()));
        m.insert("-1102".to_string(), Value::Str("BadRequest".into()));
        m.insert("-1121".to_string(), Value::Str("BadSymbol".into()));
        m.insert("-2008".to_string(), Value::Str("AuthenticationError".into()));
        m.insert("-2014".to_string(), Value::Str("AuthenticationError".into()));
        m.insert("-2015".to_string(), Value::Str("PermissionDenied".into()));
        m.insert("-2010".to_string(), Value::Str("InsufficientFunds".into()));
    m
}));
        m.insert("broad".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("insufficient balance".to_string(), Value::Str("InsufficientFunds".into()));
        m.insert("Order does not exist".to_string(), Value::Str("InvalidOrder".into()));
    m
}));
    m
}));
        m.insert("options".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("defaultVendor".to_string(), Value::Str("PREDICT_FUN".into()));
        m.insert("fetchOutcomeSearchLimit".to_string(), Value::Int(10));
        m.insert("maxFetchEventsResults".to_string(), Value::Int(25));
        m.insert("marketsPageLimit".to_string(), Value::Int(100));
        m.insert("maxFetchMarketsLimit".to_string(), Value::Int(200));
        m.insert("loadAllOutcomes".to_string(), Value::Bool(false));
        m.insert("allowUnscopedFetchEvents".to_string(), Value::Bool(true));
        m.insert("eventScopeParams".to_string(), Value::from(vec![Value::Str("l1Category".into()), Value::Str("l2Category".into())]));
    m
}));
    m
})]);

    Value::Null
}

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

    Value::Null
}

/*
 * @method
 * @name binance#fetchMarkets
 * @description fetches binance prediction markets; with a query it resolves the query via the search endpoint and returns the matched topics' markets, otherwise it pages the market listing
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.query] a single search query resolved against the market search endpoint
 * @param {string[]} [params.queries] multiple search queries (alternative to query)
 * @param {string} [params.l1Category] filter the listing by a level-1 category id (see the category/list endpoint)
 * @param {string} [params.l2Category] filter the listing by a level-2 category id
 * @param {int} [params.limit] for an unscoped listing (no query), the max number of topics to collect (defaults to options.maxFetchMarketsLimit, 200)
 * @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: Vec<Value> = self.parse_search_queries(&[params.clone()]).as_array().cloned().unwrap_or_default();
        let mut queriesLength: f64 = ((queries.len() as i64) as f64);
        if queriesLength > ((0i64) as f64) {
            let mut eventParams: Value = self.omit(params.clone(), Value::from(vec![Value::Str("limit".into())]), &[]);
            let mut events: Value = self.fetch_events(&[eventParams]).await;
            let mut eventsLength: f64 = ((events.len() as i64) as f64);
            let mut queryMarkets: Vec<Value> = Vec::new();
            {
                                let mut ei: Value = Value::Int(0);
                let mut __for_first_1210: bool = true;
                while { if !__for_first_1210 { if let Value::Int(n) = &mut ei { *n += 1; } } __for_first_1210 = false; ei.as_f64().unwrap_or(f64::NAN) < eventsLength } {
                let mut eventMarkets: Value = self.safe_list(events.as_array().and_then(|__arr| match &ei { 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), Value::Str("markets".into()), &[Value::from(vec![])]);
                let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
                {
                                        let mut mi: Value = Value::Int(0);
                    let mut __for_first_1209: bool = true;
                    while { if !__for_first_1209 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1209 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
                    queryMarkets.push(eventMarkets.as_array().and_then(|__arr| match &mi { 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));
                }
                }
            }
            }
            return Value::from(queryMarkets);
        }
        let mut maxMarkets: Value = self.safe_integer_k(params.clone(), "limit", &[self.safe_integer(self.options.clone(), Value::Str("maxFetchMarketsLimit".into()), &[Value::Int(200)])]);
        let mut rest: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into()), Value::Str("limit".into())]), &[]);
        let mut rawTopics: Vec<Value> = self.fetch_raw_topics(maxMarkets, &[rest]).await.as_array().cloned().unwrap_or_default();
        let mut parsedEvents: Vec<Value> = Vec::new();
        let mut flatMarkets: Vec<Value> = Vec::new();
        let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1212: bool = true;
            while { if !__for_first_1212 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1212 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
            let mut parsedEvent: Value = self.parse_event(rawTopics.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
            parsedEvents.push(parsedEvent.clone());
            let mut eventMarkets: Value = self.safe_list_k(parsedEvent, "markets", &[Value::from(vec![])]);
            let mut eventMarketsLength: f64 = ((eventMarkets.len() as i64) as f64);
            {
                                let mut mi: Value = Value::Int(0);
                let mut __for_first_1211: bool = true;
                while { if !__for_first_1211 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1211 = false; mi.as_f64().unwrap_or(f64::NAN) < eventMarketsLength } {
                flatMarkets.push(eventMarkets.as_array().and_then(|__arr| match &mi { 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));
            }
            }
        }
        }
        self.set_events(Value::from(parsedEvents));
        return Value::from(flatMarkets);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#fetchRawTopics
 * @description pages the market/list endpoint and returns up to `maxTopics` raw market topics
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#list-prediction-markets
 * @param {int} maxTopics stop collecting once this many topics are gathered
 * @param {object} [rest] extra params forwarded verbatim to the listing endpoint (l1Category, l2Category, sortBy, orderBy)
 * @returns {object[]} raw market topic objects
 */
    pub async fn fetch_raw_topics(&mut self, mut maxTopics: Value, optional_args: &[Value]) -> Value {
        let mut rest = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut maxTopicsOption: Value = self.safe_integer_k(self.options.clone(), "maxFetchMarketsLimit", &[Value::Int(200)]);
        let mut maxTopicsResolved: Value = self.parse_to_int(maxTopicsOption);
        if (maxTopics != Value::Null) {
            maxTopicsResolved = self.parse_to_int(maxTopics);
        }
        let mut pageLimitOption: Value = self.safe_integer_k(self.options.clone(), "marketsPageLimit", &[Value::Int(100)]);
        let mut pageLimit: Value = self.parse_to_int(Value::Int(100));
        if pageLimitOption.as_f64().unwrap_or(f64::NAN) < ((100i64) as f64) {
            pageLimit = self.parse_to_int(pageLimitOption);
        }
        let mut collected: Vec<Value> = Vec::new();
        let mut offset: Value = Value::Int(0);
        loop {
            let mut collectedLength: Value = Value::Int(collected.len() as i64);
            let mut remaining: Value = (match (&(maxTopicsResolved), &(collectedLength)) { (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 reqLimit: Value = (if (remaining.as_f64().unwrap_or(f64::NAN) < pageLimit.as_f64().unwrap_or(f64::NAN)) { remaining } else { pageLimit.clone() });
            if reqLimit.as_f64().unwrap_or(f64::NAN) <= ((0i64) as f64) {
                break;
            }
            let mut request: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                    m.insert("offset".to_string(), offset.clone());
                    m.insert("limit".to_string(), reqLimit.clone());
                m
            });
            let __ws_arg_0 = self.extend(Value::Map(request), &[rest.clone()]);
            let mut response: Value = self.sapi_private_get_market_list(&[__ws_arg_0]).await;
            //
            //     {
            //         "marketTopics": [
            //             {
            //                 "marketTopicId": 4229564,
            //                 "vendor": "PREDICT_FUN",
            //                 "chainId": "56",
            //                 "slug": "btc-price-1h-up-or-down",
            //                 "title": "BTC Price 1h Up or Down?",
            //                 "question": "Will BTC price go UP?",
            //                 "topicType": "FLAT",
            //                 "chartType": "CRYPTO_UP_DOWN",
            //                 "symbol": "BTCUSDT",
            //                 "participantCount": 3420,
            //                 "collateral": "USDT",
            //                 "feeRateBps": 200,
            //                 "slippageBps": 1200,
            //                 "tradeVolume": "158234.56",
            //                 "liquidity": "45000.00",
            //                 "publishedAt": 1748100000000,
            //                 "startDate": 1748131200000,
            //                 "endDate": 1748134800000,
            //                 "status": "REGISTERED",
            //                 "markets": []
            //             }
            //         ],
            //         "total": 128,
            //         "offset": 0,
            //         "limit": 20,
            //         "hasMore": true
            //     }
            //
            let mut pageTopics: Vec<Value> = self.safe_list_k(response.clone(), "marketTopics", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
            let mut pageTopicsLength: Value = Value::Int(pageTopics.len() as i64);
            {
                                let mut i: Value = Value::Int(0);
                let mut __for_first_1213: bool = true;
                while { if !__for_first_1213 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1213 = false; i.as_f64().unwrap_or(f64::NAN) < pageTopicsLength.as_f64().unwrap_or(f64::NAN) } {
                collected.push(pageTopics.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
            }
            }
            let mut hasMore: bool = self.safe_bool_k_opt(response, "hasMore", &[Value::Bool(false)]).unwrap_or(false);
            if (!(hasMore)) || (pageTopicsLength.as_f64().unwrap_or(f64::NAN) < reqLimit.as_f64().unwrap_or(f64::NAN)) {
                break;
            }
            offset = self.sum(&[offset.clone(), pageTopicsLength]);
        }
        return Value::from(collected);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#fetchRawTopicDetail
 * @description fetches a single raw market topic (with nested markets and outcome tokens) by its id
 * @param {string} topicId the marketTopicId
 * @param {object} [params] extra params forwarded verbatim to the detail endpoint
 * @returns {object} the raw market topic object
 */
    pub async fn fetch_raw_topic_detail(&mut self, mut topicId: 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: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("marketTopicId".to_string(), topicId);
            m
        });
        let __ws_arg_1 = self.extend(Value::Map(request), &[params]);
        return self.sapi_private_get_market_detail(&[__ws_arg_1]).await;

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#completeRawTopics
 * @description ensures each raw topic carries fully-populated nested markets (with outcome token ids), fetching the topic detail when the listing/search payload omitted them
 * @param {object[]} rawTopics raw market topic objects
 * @returns {object[]} raw market topic objects with usable nested markets
 */
    pub async fn complete_raw_topics(&mut self, mut rawTopics: Value) -> Value {
        let __rawTopics_empty = Vec::new();
        let rawTopics = rawTopics.as_array().unwrap_or(&__rawTopics_empty);
        let mut result: Vec<Value> = Vec::new();
        let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1214: bool = true;
            while { if !__for_first_1214 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1214 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
            let mut rawTopic: Value = rawTopics.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            let mut rawMarkets: Value = self.safe_list_k(rawTopic.clone(), "markets", &[Value::from(vec![])]);
            let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
            let mut hasOutcomes: bool = false;
            if rawMarketsLength > ((0i64) as f64) {
                let mut firstMarket: Value = self.safe_dict(rawMarkets, Value::Int(0), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
                let mut firstOutcomes: Vec<Value> = self.safe_list_k(firstMarket, "outcomes", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
                let mut firstOutcomesLength: f64 = ((firstOutcomes.len() as i64) as f64);
                hasOutcomes = firstOutcomesLength > ((0i64) as f64);
            }
            if hasOutcomes {
                result.push(rawTopic.clone());
            }  else {
                let mut topicId: Option<String> = self.safe_string_k_opt(rawTopic, "marketTopicId", &[]);
                if (topicId.is_some()) {
                    let mut detail: Value = self.fetch_raw_topic_detail(topicId.map(Value::from).unwrap_or(Value::Null), &[]).await;
                    result.push(detail);
                }
            }
        }
        }
        return Value::from(result);

    Value::Null
}

/*
 * @method
 * @name binance#fetchEvents
 * @description fetches prediction-market events (market topics); the call must be scoped by query/queries/tags, eventId, or an l1Category/l2Category listing filter
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.query] a free-text search resolved against the semantic market search endpoint
 * @param {string[]} [params.queries] multiple free-text searches (alternative to query)
 * @param {string[]} [params.tags] treated as additional free-text searches (binance has no tag taxonomy)
 * @param {string} [params.eventId] a marketTopicId, fetched directly via the detail endpoint
 * @param {string} [params.l1Category] scope the listing server-side by a level-1 category id
 * @param {string} [params.l2Category] scope the listing server-side by a level-2 category id
 * @param {int} [params.limit] the maximum number of events to return
 * @param {string} [params.sort] 'volume' | 'liquidity' | 'newest' (client-side)
 * @param {string} [params.status] 'active' | 'closed' | 'all' (client-side)
 * @param {string} [params.sortBy] sort events by server side ('RECOMMENDED' | 'VOLUME' | 'PARTICIPANTS' | 'CREATED_TIME' | 'END_DATE'), works when no queries and eventId provided
 * @param {string} [params.orderBy] order events by server side ('ASC' | 'DESC'), works when no queries and eveitId provided
 * @returns {object[]} a list of [prediction event structures](https://docs.ccxt.com/#/?id=prediction-event-structure)
 */
    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
}));
        let mut allowUnscopedFetchEvents: bool = self.safe_bool_k_opt(self.options.clone(), "allowUnscopedFetchEvents", &[Value::Bool(false)]).unwrap_or(false);
        if !(allowUnscopedFetchEvents) {
            self.require_event_query(&[params.clone()]);
        }
        let mut queries: Vec<Value> = self.parse_search_queries(&[params.clone()]).as_array().cloned().unwrap_or_default();
        // binance has no tag taxonomy — resolve requested tags through the semantic search too
        let mut tags: Vec<Value> = self.safe_list_k(params.clone(), "tags", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
        let mut tagsLength: f64 = ((tags.len() as i64) as f64);
        let mut allQueries: Vec<Value> = Vec::new();
        {
                        let mut i: i64 = 0;
            let mut __for_first_1215: bool = true;
            while { if !__for_first_1215 { i += 1; } __for_first_1215 = false; i < (queries.len() as i64) } {
            allQueries.push(queries.get(i as usize).cloned().unwrap_or(Value::Null));
        }
        }
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1216: bool = true;
            while { if !__for_first_1216 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1216 = false; i.as_f64().unwrap_or(f64::NAN) < tagsLength } {
            allQueries.push(tags.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
        }
        }
        let mut allQueriesLength: f64 = ((allQueries.len() as i64) as f64);
        let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("query".into()), Value::Str("queries".into())]), &[]);
        // keys dropped before the client-side pass; a server-side sort also drops its own keys
        let mut postOmitKeys: Vec<Value> = vec![Value::Str("tags".into()), Value::Str("l1Category".into()), Value::Str("l2Category".into())];
        let mut userLimit: Value = self.safe_integer_k(paramsOmitted.clone(), "limit", &[]);
        let mut fetchCap: Value = self.safe_integer_k(self.options.clone(), "maxFetchEventsResults", &[Value::Int(100)]);
        if (userLimit != Value::Null) {
            fetchCap = userLimit;
        }
        let mut rest: Value = self.omit(paramsOmitted.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("tags".into()), Value::Str("l1Category".into()), Value::Str("l2Category".into())]), &[]);
        let mut eventId: Option<String> = self.safe_string_k_opt(paramsOmitted.clone(), "eventId", &[]);
        let mut l1Category: Option<String> = self.safe_string_k_opt(paramsOmitted.clone(), "l1Category", &[]);
        let mut l2Category: Option<String> = self.safe_string_k_opt(paramsOmitted.clone(), "l2Category", &[]);
        if (self.markets.clone() == Value::Null) {
            { let __t = self.create_safe_dictionary(&[]); self.markets = __t; }
        }
        let mut rawTopics: Value = Value::from(vec![]);
        if allQueriesLength > ((0i64) as f64) {
            rawTopics = self.fetch_events_by_query(Value::from(allQueries), fetchCap.clone(), &[rest.clone()]).await;
        }  else if (eventId.is_some()) {
            let mut detail: Value = self.fetch_raw_topic_detail(eventId.clone().map(Value::from).unwrap_or(Value::Null), &[rest.clone()]).await;
            rawTopics = Value::from(vec![detail]);
        }  else {
            let mut listingRequest: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                m
            });
            if (l1Category.is_some()) {
                listingRequest.insert("l1Category".into(), l1Category.clone().map(Value::from).unwrap_or(Value::Null));
            }
            if (l2Category.is_some()) {
                listingRequest.insert("l2Category".into(), l2Category.clone().map(Value::from).unwrap_or(Value::Null));
            }
            let mut sortBy: Value = self.safe_string_upper2(paramsOmitted.clone(), Value::Str("sortBy".into()), Value::Str("sort".into()), &[]);
            if (sortBy != Value::Null) {
                // map the unified sort values onto the server enum, one of RECOMMENDED,
                // VOLUME, PARTICIPANTS, CREATED_TIME or END_DATE — 'liquidity' has no
                // server-side equivalent and stays in params so the base
                // applyEventFetchParams sorts it client-side instead
                if (sortBy.as_str() == Some("NEWEST")) {
                    sortBy = Value::Str("CREATED_TIME".into());
                }  else if (sortBy.as_str() == Some("LIQUIDITY")) {
                    sortBy = Value::Null;
                }
                if (sortBy != Value::Null) {
                    listingRequest.insert("sortBy".into(), sortBy);
                    postOmitKeys.push(Value::Str("sort".into()));
                    postOmitKeys.push(Value::Str("sortBy".into()));
                }
            }
            let __ws_arg_2 = self.extend(Value::Map(listingRequest), &[rest]);
            let mut listed: Value = self.fetch_raw_topics(fetchCap, &[__ws_arg_2]).await;
            rawTopics = self.complete_raw_topics(listed).await;
        }
        let mut rawTopicsLength: f64 = ((rawTopics.len() as i64) as f64);
        let mut result: Vec<Value> = Vec::new();
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1218: bool = true;
            while { if !__for_first_1218 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1218 = false; i.as_f64().unwrap_or(f64::NAN) < rawTopicsLength } {
            let mut parsedEvent: Value = self.parse_event(rawTopics.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));
            result.push(parsedEvent.clone());
            let mut parsedMarkets: Vec<Value> = self.safe_list_k(parsedEvent, "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
            let mut parsedMarketsLength: f64 = ((parsedMarkets.len() as i64) as f64);
            {
                                let mut mi: Value = Value::Int(0);
                let mut __for_first_1217: bool = true;
                while { if !__for_first_1217 { if let Value::Int(n) = &mut mi { *n += 1; } } __for_first_1217 = false; mi.as_f64().unwrap_or(f64::NAN) < parsedMarketsLength } {
                let mut m: Value = parsedMarkets.get(mi.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
                // prediction market rows are keyed by the unified 'market' handle
                let mut handle: Option<String> = self.safe_string_k_opt(m.clone(), "market", &[]);
                if (handle.is_some()) {
                    if let Value::Dict(__d) = &mut self.markets { std::sync::Arc::make_mut(__d).insert(handle.as_deref().unwrap_or("null").to_string(), m); }
                }
            }
            }
        }
        }
        self.populate_outcomes();
        // scoping already happened server-side: the tag filter needs an event-level tags field
        // binance topics lack, and the query filter would drop semantic-search matches whose
        // title uses different words than the query
        let mut postParams: Value = self.omit(paramsOmitted, Value::from(postOmitKeys), &[]);
        return self.apply_event_fetch_params(Value::from(result), &[postParams, Value::from(vec![])]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#fetchEventsByQuery
 * @description resolves free-text queries through the semantic market search endpoint, then completes the matched topics with their outcome tokens
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#market-search
 * @param {string[]} queries free-text search strings
 * @param {int} [limit] max number of topics to fetch
 * @param {object} [rest] extra params forwarded verbatim to the search endpoint
 * @returns {object[]} raw market topic objects with usable nested markets
 */
    pub async fn fetch_events_by_query(&mut self, mut queries: Value, mut limit: Value, optional_args: &[Value]) -> Value {
        let mut rest = 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 seen: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut collected: Value = Value::from(vec![]);
        let mut queriesLength: f64 = ((queries.len() as i64) as f64);
        let mut limitValue: Value = self.parse_to_int(Value::Int(20));
        if (limit != Value::Null) {
            limitValue = self.parse_to_int(limit);
        }
        let mut limitResolved: Value = limitValue.clone();
        if limitValue.as_f64().unwrap_or(f64::NAN) > ((50i64) as f64) {
            limitResolved = self.parse_to_int(Value::Int(50));
        }
        {
                        let mut qi: Value = Value::Int(0);
            let mut __for_first_1220: bool = true;
            while { if !__for_first_1220 { if let Value::Int(n) = &mut qi { *n += 1; } } __for_first_1220 = false; qi.as_f64().unwrap_or(f64::NAN) < queriesLength } {
            let mut request: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                    m.insert("query".to_string(), queries.get((qi).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
                m
            });
            request.insert("topK".into(), limitResolved.clone());
            let __ws_arg_3 = self.extend(Value::Map(request), &[rest.clone()]);
            let mut response: Value = self.sapi_private_get_market_search(&[__ws_arg_3]).await;
            //
            //     [
            //         {
            //             "marketTopicId": 4229564,
            //             "vendor": "PREDICT_FUN",
            //             "slug": "btc-price-1h-up-or-down",
            //             "title": "BTC Price 1h Up or Down?",
            //             ...
            //             "markets": []
            //         }
            //     ]
            //
            let mut responseLength: f64 = ((response.len() as i64) as f64);
            {
                                let mut i: Value = Value::Int(0);
                let mut __for_first_1219: bool = true;
                while { if !__for_first_1219 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1219 = false; i.as_f64().unwrap_or(f64::NAN) < responseLength } {
                let mut rawTopic: Value = self.safe_dict(response.clone(), i.clone(), &[]);
                let mut topicId: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "marketTopicId", &[]);
                if (topicId.is_some()) {
                    let mut already: Option<String> = self.safe_string(Value::Map(seen.clone()), topicId.clone().map(Value::from).unwrap_or(Value::Null), &[]).as_str().map(str::to_owned);
                    if (already.is_none()) {
                        seen.insert(topicId.as_deref().unwrap_or("null").to_string(), topicId.map(Value::from).unwrap_or(Value::Null));
                        if let Value::Arr(__a) = &mut collected { std::sync::Arc::make_mut(__a).push(rawTopic); }
                    }
                }
            }
            }
        }
        }
        let mut capped: Value = collected.clone();
        let mut collectedLength: f64 = ((collected.len() as i64) as f64);
        if collectedLength > limitResolved.as_f64().unwrap_or(f64::NAN) {
            capped = self.array_slice(collected, Value::Int(0), &[limitResolved]);
        }
        return self.complete_raw_topics(capped).await;

    Value::Null
}

/*
 * @method
 * @name binance#fetchEvent
 * @description fetches a single prediction-market event (market topic) by its marketTopicId
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data
 * @param {string} id the marketTopicId
 * @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 __ws_arg_4 = self.extend(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("eventId".to_string(), id);
    m
}), &[params]);
        let mut events: Value = self.fetch_events(&[__ws_arg_4]).await;
        return self.safe_dict(events, Value::Int(0), &[]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parseEvent
 * @description parses a raw binance market topic (with nested markets) into the unified event shape
 * @param {object} rawTopic the raw market topic object
 * @returns {object} an event structure
 */
    pub fn parse_event(&self, mut rawTopic: Value) -> Value {
        //
        //     {
        //         "marketTopicId": 4229564,
        //         "vendor": "PREDICT_FUN",
        //         "chainId": "56",
        //         "slug": "btc-price-1h-up-or-down",
        //         "title": "BTC Price 1h Up or Down?",
        //         "question": "Will BTC price go UP?",
        //         "description": "Resolves YES if BTC spot price is higher than the starting price.",
        //         "imageUrl": "https://...",
        //         "topicType": "FLAT",
        //         "chartType": "CRYPTO_UP_DOWN",
        //         "symbol": "BTCUSDT",
        //         "variantData": { "type": "CRYPTO_UP_DOWN", "startPrice": "67890.12", "endPrice": null },
        //         "participantCount": 3420,
        //         "collateral": "USDT",
        //         "feeRateBps": 200,
        //         "slippageBps": 1200,
        //         "tradeVolume": "158234.56",
        //         "liquidity": "45000.00",
        //         "publishedAt": 1748100000000,
        //         "startDate": 1748131200000,
        //         "endDate": 1748134800000,
        //         "status": "REGISTERED",
        //         "timeline": [ ... ],
        //         "markets": [ { "marketId": 5567895, "title": "UP", "outcomes": [ ... ] } ]
        //     }
        //
        let mut rawMarkets: Vec<Value> = self.safe_list_k(rawTopic.clone(), "markets", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
        let mut marketsList: Vec<Value> = Vec::new();
        let mut anyActive: Value = Value::Bool(false);
        let mut rawMarketsLength: f64 = ((rawMarkets.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1221: bool = true;
            while { if !__for_first_1221 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1221 = false; i.as_f64().unwrap_or(f64::NAN) < rawMarketsLength } {
            let mut parsed: Value = self.parse_topic_market(rawMarkets.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null), rawTopic.clone());
            marketsList.push(parsed.clone());
            if matches!(self.safe_bool_k(parsed, "active", &[Value::Bool(false)]), Value::Bool(true)) {
                anyActive = Value::Bool(true);
            }
        }
        }
        let mut topicId: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "marketTopicId", &[]);
        let mut slug: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "slug", &[]);
        let mut title: Option<String> = self.safe_string_k_opt(rawTopic.clone(), "title", &[]);
        let mut endDate: Option<i64> = self.safe_integer_k(rawTopic.clone(), "endDate", &[]).as_i64();
        let mut created: Option<i64> = self.safe_integer2(rawTopic.clone(), Value::Str("publishedAt".into()), Value::Str("startDate".into()), &[]).as_i64();
        let mut status: Option<String> = self.safe_string_k(rawTopic.clone(), "status", &[]).as_str().map(str::to_owned);
        let mut active: Value = anyActive;
        if (rawMarketsLength == 0.0) {
            active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
        }
        let mut resolved: Value = Value::Null;
        if (status.is_some()) {
            resolved = Value::Bool((status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED")));
        }
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), topicId.map(Value::from).unwrap_or(Value::Null));
        m.insert("slug".to_string(), slug.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("event".to_string(), (if (slug.is_some()) { self.shorten_slug(slug.map(Value::from).unwrap_or(Value::Null)) } else { Value::Null }));
        m.insert("title".to_string(), title.map(Value::from).unwrap_or(Value::Null));
        m.insert("description".to_string(), self.safe_string_k(rawTopic.clone(), "description", &[]));
        m.insert("markets".to_string(), Value::from(marketsList));
        m.insert("active".to_string(), active);
        m.insert("volume".to_string(), self.safe_number_k(rawTopic.clone(), "tradeVolume", &[]));
        m.insert("liquidity".to_string(), self.safe_number_k(rawTopic.clone(), "liquidity", &[]));
        m.insert("url".to_string(), Value::Null);
        m.insert("image".to_string(), self.safe_string_k(rawTopic.clone(), "imageUrl", &[]));
        m.insert("created".to_string(), Value::from(created));
        m.insert("createdDatetime".to_string(), self.iso8601(Value::from(created)));
        m.insert("end".to_string(), Value::from(endDate));
        m.insert("endDatetime".to_string(), self.iso8601(Value::from(endDate)));
        m.insert("category".to_string(), self.safe_string_k(rawTopic.clone(), "chartType", &[]));
        m.insert("resolved".to_string(), resolved);
        m.insert("info".to_string(), rawTopic);
    m
});

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parseTopicMarket
 * @description parses one nested market of a market topic into the unified market shape, building its outcome tokens
 * @param {object} rawMarket the nested market object
 * @param {object} rawTopic the enclosing raw market topic (carries slug/vendor/fees/dates)
 * @returns {object} a market structure
 */
    pub fn parse_topic_market(&self, mut rawMarket: Value, mut rawTopic: Value) -> Value {
        let __rawTopic_empty = indexmap::IndexMap::new();
        let rawTopic = rawTopic.as_map().unwrap_or(&__rawTopic_empty);
        //
        //     {
        //         "marketId": 5567895,
        //         "externalId": "ext_001",
        //         "title": "UP",
        //         "question": "Will BTC go UP?",
        //         "description": "Resolves YES if BTC price increases.",
        //         "conditionId": "0xabc123",
        //         "status": "REGISTERED",
        //         "tradingStatus": "OPEN",
        //         "tradeVolume": "90000.00",
        //         "liquidity": "25000.00",
        //         "decimalPrecision": 2,
        //         "outcomes": [
        //             { "name": "YES", "price": "0.52", "chance": "0.52", "index": 0, "tokenId": "112233" }
        //         ]
        //     }
        //
        let mut marketId: Option<String> = self.safe_string_k_opt(rawMarket.clone(), "marketId", &[]);
        let mut topicId: Value = (match rawTopic.get("marketTopicId") { 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 topicSlug: Value = (match rawTopic.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()), _ => Value::Null });
        let mut vendor: Value = (match rawTopic.get("vendor") { 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 collateral: Value = (match rawTopic.get("collateral") { 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::Str("USDT".into()) });
        let mut title: Value = self.safe_string_k(rawMarket.clone(), "title", &[marketId.clone().map(Value::from).unwrap_or(Value::Null)]);
        let mut marketSymbol: Value = self.slug_to_market_symbol(topicSlug.clone(), title.clone());
        let mut tradingStatus: Option<String> = self.safe_string_k(rawMarket.clone(), "tradingStatus", &[]).as_str().map(str::to_owned);
        let mut status: Option<String> = self.safe_string_k(rawMarket.clone(), "status", &[]).as_str().map(str::to_owned);
        let mut active: Value = (Value::Bool(tradingStatus.as_deref() == Some("OPEN")));
        if (tradingStatus.is_none()) {
            active = Value::Bool((status.as_deref() == Some("REGISTERED")) || (status.as_deref() == Some("OPEN")));
        }
        let mut resolved: bool = (status.as_deref() == Some("RESOLVED")) || (status.as_deref() == Some("SETTLED"));
        let mut endDate: Value = (match rawTopic.get("endDate") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null });
        let mut feeRateBps: Value = (match rawTopic.get("feeRateBps") { 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::Str("200".into()) });
        let mut feeRate: Value = self.parse_number(crate::precise::Precise::stringDiv(&feeRateBps, &Value::Str("10000".into())), &[]);
        let mut decimalPrecision: Value = self.safe_string_k(rawMarket.clone(), "decimalPrecision", &[Value::Str("2".into())]);
        let mut pricePrecision: Value = self.parse_number(self.parse_precision(&[decimalPrecision]), &[]);
        let mut precision: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("amount".to_string(), Value::Float(0.01));
                m.insert("price".to_string(), pricePrecision);
            m
        });
        let mut volume: Value = self.safe_number_k(rawMarket.clone(), "tradeVolume", &[]);
        let mut liquidity: Value = self.safe_number_k(rawMarket.clone(), "liquidity", &[]);
        let mut rawOutcomes: Value = self.safe_list_k(rawMarket.clone(), "outcomes", &[Value::from(vec![])]);
        let mut outcomes: Vec<Value> = Vec::new();
        let mut resolvedOutcomeRaw: Value = Value::Null;
        let mut rawOutcomesLength: f64 = ((rawOutcomes.len() as i64) as f64);
        {
                        let mut oi: Value = Value::Int(0);
            let mut __for_first_1222: bool = true;
            while { if !__for_first_1222 { if let Value::Int(n) = &mut oi { *n += 1; } } __for_first_1222 = false; oi.as_f64().unwrap_or(f64::NAN) < rawOutcomesLength } {
            let mut rawOutcome: Value = self.safe_dict(rawOutcomes.clone(), oi.clone(), &[]);
            let mut label: Option<String> = self.safe_string_upper_k_opt(rawOutcome.clone(), "name", &[]);
            let mut tokenId: Option<String> = self.safe_string_k_opt(rawOutcome.clone(), "tokenId", &[]);
            let mut outcomeHandle: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", marketSymbol, Value::Str(":".into())).into()), label.clone().map(Value::from).unwrap_or(Value::Null)).into());
            let mut price: Option<String> = self.safe_string_k_opt(rawOutcome.clone(), "price", &[]);
            let mut winnerRaw: Value = Value::Null;
            let mut settleFractionRaw: Value = Value::Null;
            if resolved && (price.is_some()) {
                winnerRaw = crate::precise::Precise::stringEq(&price.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("1".into()));
                settleFractionRaw = (if (winnerRaw).as_bool() == Some(true) { Value::Int(1) } else { Value::Int(0) });
                if winnerRaw.as_bool() == Some(true) {
                    resolvedOutcomeRaw = outcomeHandle.clone();
                }
            }
            let mut winner: Value = winnerRaw;
            let mut settleFraction: Value = settleFractionRaw;
            outcomes.push(Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("id".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
                    m.insert("outcomeId".to_string(), tokenId.clone().map(Value::from).unwrap_or(Value::Null));
                    m.insert("outcome".to_string(), outcomeHandle);
                    m.insert("market".to_string(), marketSymbol.clone());
                    m.insert("label".to_string(), label.clone().map(Value::from).unwrap_or(Value::Null));
                    m.insert("price".to_string(), self.parse_number(price.clone().map(Value::from).unwrap_or(Value::Null), &[]));
                    m.insert("active".to_string(), active.clone());
                    m.insert("winner".to_string(), winner);
                    m.insert("settleFraction".to_string(), settleFraction);
                    m.insert("precision".to_string(), Value::Map(precision.clone()));
                    m.insert("info".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("tokenId".to_string(), tokenId.map(Value::from).unwrap_or(Value::Null));
        m.insert("marketId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("marketTopicId".to_string(), topicId.clone());
        m.insert("vendor".to_string(), vendor.clone());
        m.insert("chainId".to_string(), (match rawTopic.get("chainId") { 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 }));
        m.insert("slug".to_string(), topicSlug.clone());
        m.insert("marketTitle".to_string(), title.clone());
        m.insert("outcomeLabel".to_string(), label.map(Value::from).unwrap_or(Value::Null));
        m.insert("index".to_string(), self.safe_string_k(rawOutcome.clone(), "index", &[]));
        m.insert("price".to_string(), price.map(Value::from).unwrap_or(Value::Null));
        m.insert("chance".to_string(), self.safe_string_k(rawOutcome, "chance", &[]));
        m.insert("collateral".to_string(), collateral.clone());
        m.insert("feeRateBps".to_string(), feeRateBps.clone());
        m.insert("slippageBps".to_string(), (match rawTopic.get("slippageBps") { 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 }));
        m.insert("conditionId".to_string(), self.safe_string_k(rawMarket.clone(), "conditionId", &[]));
        m.insert("externalId".to_string(), self.safe_string_k(rawMarket.clone(), "externalId", &[]));
    m
}));
                m
            }));
        }
        }
        let mut resolvedOutcome: Value = resolvedOutcomeRaw;
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("market".to_string(), marketSymbol);
        m.insert("base".to_string(), collateral.clone());
        m.insert("quote".to_string(), collateral.clone());
        m.insert("settle".to_string(), Value::Null);
        m.insert("baseId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
        m.insert("quoteId".to_string(), collateral.clone());
        m.insert("settleId".to_string(), Value::Null);
        m.insert("type".to_string(), Value::Str("prediction".into()));
        m.insert("marketType".to_string(), Value::Str("binary".into()));
        m.insert("executionModel".to_string(), Value::Str("clob".into()));
        m.insert("collateral".to_string(), collateral);
        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(), active);
        m.insert("resolved".to_string(), Value::Bool(resolved));
        m.insert("resolvedOutcome".to_string(), resolvedOutcome);
        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(), endDate.clone());
        m.insert("expiryDatetime".to_string(), self.iso8601(endDate));
        m.insert("strike".to_string(), Value::Null);
        m.insert("optionType".to_string(), Value::Null);
        m.insert("taker".to_string(), feeRate);
        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(precision));
        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(), Value::Null);
        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(), Value::Float(0.01));
        m.insert("max".to_string(), Value::Float(0.99));
    m
}));
        m.insert("cost".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("min".to_string(), Value::Float(1.5));
        m.insert("max".to_string(), Value::Null);
    m
}));
    m
}));
        m.insert("outcomes".to_string(), Value::from(outcomes));
        m.insert("info".to_string(), self.extend(rawMarket, &[Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("marketTopicId".to_string(), topicId);
        m.insert("vendor".to_string(), vendor);
        m.insert("slug".to_string(), topicSlug);
        m.insert("volume".to_string(), volume);
        m.insert("liquidity".to_string(), liquidity);
    m
})]));
        m.insert("created".to_string(), (match rawTopic.get("publishedAt") { Some(Value::Int(__n)) => Value::Int(*__n), Some(Value::Float(__f)) => Value::Int(*__f as i64), Some(Value::Str(__s)) => match __s.parse::<i64>() { Ok(__n) => Value::Int(__n), Err(_) => match __s.parse::<f64>() { Ok(__f) if __f.is_finite() => Value::Int(__f as i64), _ => Value::Null } }, _ => Value::Null }));
    m
});

    Value::Null
}

/*
 * @method
 * @name binance#fetchTicker
 * @description fetches the last trade price for a single prediction outcome
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-last-trade-price
 * @param {string} outcome unified outcome handle like BTC_PRICE_1H_UP_DOWN_UP: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=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
}));
        self.load_outcome(outcome.clone(), &[]).await;
        let mut outcomeObj: Value = self.outcome(outcome.clone());
        let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("marketId".to_string(), self.safe_string_k(info, "marketId", &[]));
            m
        });
        let __ws_arg_5 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.sapi_private_get_order_book_last_trade_price(&[__ws_arg_5]).await;
        return self.parse_prediction_ticker(response, &[outcomeObj]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parsePredictionTicker
 * @description parses a last-trade-price response into a unified ticker object; the venue quotes the market's primary (YES) token, so a NO outcome mirrors as 1 - price
 * @param {object} raw the raw last-trade-price object
 * @param {object} [market] the outcome object the ticker belongs to
 * @returns {object} a [ticker structure](https://docs.ccxt.com/#/?id=ticker-structure)
 */
    pub fn parse_prediction_ticker(&self, mut raw: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        //
        //     { "marketId": 5567895, "lastTradePrice": "0.52" }
        //
        let mut marketAny: Value = market.clone();
        let mut outcomeObj: Value = self.safe_outcome(self.safe_string_k(marketAny.clone(), "outcome", &[]), &[marketAny]);
        // the venue quotes the market's primary token (outcome index 0, e.g. YES or UP),
        // any other outcome of a binary market mirrors as 1 - price
        let mut outcomeInfo: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut outcomeIndex: Option<String> = self.safe_string_k(outcomeInfo, "index", &[]).as_str().map(str::to_owned);
        let mut isMirrored: bool = false;
        if (outcomeIndex.is_some()) {
            isMirrored = outcomeIndex.as_deref() != Some("0");
        }  else {
            let mut label: Option<String> = self.safe_string_upper_k(outcomeObj.clone(), "label", &[Value::Str("YES".into())]).as_str().map(str::to_owned);
            isMirrored = (label.as_deref() == Some("NO")) || (label.as_deref() == Some("DOWN"));
        }
        let mut lastString: Option<String> = self.safe_string_k_opt(raw.clone(), "lastTradePrice", &[]);
        let mut last: Value = Value::Null;
        if (lastString.is_some()) {
            if isMirrored {
                last = self.parse_number(crate::precise::Precise::stringSub(&Value::Str("1".into()), &lastString.clone().map(Value::from).unwrap_or(Value::Null)), &[]);
            }  else {
                last = self.parse_number(lastString.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(), self.safe_string_k(outcomeObj.clone(), "outcome", &[]));
        m.insert("outcomeId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
        m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
        m.insert("timestamp".to_string(), Value::Null);
        m.insert("datetime".to_string(), Value::Null);
        m.insert("high".to_string(), Value::Null);
        m.insert("low".to_string(), Value::Null);
        m.insert("bid".to_string(), Value::Null);
        m.insert("bidVolume".to_string(), Value::Null);
        m.insert("ask".to_string(), Value::Null);
        m.insert("askVolume".to_string(), Value::Null);
        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(), Value::Null);
        m.insert("baseVolume".to_string(), Value::Null);
        m.insert("quoteVolume".to_string(), Value::Null);
        m.insert("info".to_string(), raw);
    m
}), &[market]);

    Value::Null
}

/*
 * @method
 * @name binance#fetchTickers
 * @description fetches last trade prices for multiple outcomes, one request per distinct underlying market
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-last-trade-price
 * @param {string[]} outcomes unified outcomes — required: the venue has no all-tickers endpoint
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a dictionary of prediction [ticker structures](https://docs.ccxt.com/#/?id=ticker-structure)
 */
    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 to fetch (discover them via fetchEvents ())".into()))));
        }
        self.load_outcomes(&[outcomes.clone()]).await;
        let mut responsesByMarketId: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut result: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut outcomesLength: f64 = ((outcomes.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1223: bool = true;
            while { if !__for_first_1223 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1223 = false; i.as_f64().unwrap_or(f64::NAN) < outcomesLength } {
            let mut outcomeObj: Value = self.outcome(outcomes.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 info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
            let mut marketId: Option<String> = self.safe_string_k_opt(info, "marketId", &[]);
            if (marketId.is_none()) {
                continue;
            }
            let mut response: Value = self.safe_dict(Value::Map(responsesByMarketId.clone()), marketId.clone().map(Value::from).unwrap_or(Value::Null), &[]);
            if (response == Value::Null) {
                let mut request: indexmap::IndexMap<String, Value> = ({
                    let mut m = indexmap::IndexMap::new();
                        m.insert("marketId".to_string(), marketId.clone().map(Value::from).unwrap_or(Value::Null));
                    m
                });
                let __ws_arg_6 = self.extend(Value::Map(request), &[params.clone()]);
                response = self.sapi_private_get_order_book_last_trade_price(&[__ws_arg_6]).await;
                responsesByMarketId.insert(marketId.as_deref().unwrap_or("null").to_string(), response.clone());
            }
            let mut ticker: Value = self.parse_prediction_ticker(response, &[outcomeObj]);
            let mut symbolKey: Value = self.safe_string_k(ticker.clone(), "outcome", &[outcomes.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)]);
            result.insert(crate::runtime::stringify_param(&symbolKey), ticker);
        }
        }
        return Value::Map(result);

    Value::Null
}

/*
 * @method
 * @name binance#fetchOrderBook
 * @description fetches the order book for a single prediction outcome token
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/market-data#query-order-book
 * @param {string} outcome unified outcome handle, or an outcome token id
 * @param {int} [limit] not used by binance fetchOrderBook
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a prediction [order book structure](https://docs.ccxt.com/#/?id=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
}));
        self.load_outcome(outcome.clone(), &[]).await;
        let mut outcomeObj: Value = self.outcome(outcome.clone());
        let mut info: Value = self.safe_dict_k(outcomeObj.clone(), "info", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("vendor".to_string(), self.safe_string_k(info.clone(), "vendor", &[self.safe_string(self.options.clone(), Value::Str("defaultVendor".into()), &[])]));
                m.insert("marketId".to_string(), self.safe_string_k(info, "marketId", &[]));
                m.insert("tokenId".to_string(), self.safe_string2(outcomeObj.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
            m
        });
        let __ws_arg_7 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.sapi_private_get_order_book(&[__ws_arg_7]).await;
        //
        //     {
        //         "outcome": "YES",
        //         "tokenId": "112233",
        //         "timestamp": 1748131800000,
        //         "bids": [ { "price": "0.51", "size": "5000.00" } ],
        //         "asks": [ { "price": "0.52", "size": "3000.00" } ]
        //     }
        //
        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 binance#fetchBalance
 * @description query for balance and get the amount of funds available for trading or funds locked in orders
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/wallet#query-payment-option-balances
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.type] 'CeDefi', 'FUNDING', or 'SPOT'
 * @returns {object} a [balance structure]{@link 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
}));
        let type_varparamsTypeVariable: Vec<Value> = self.handle_option_string_and_params(params, Value::Str("fetchBalance".into()), Value::Str("type".into()), &[Value::Str("SPOT".into())]).as_array().cloned().unwrap_or_default();
        let mut type_var: Value = type_varparamsTypeVariable.get(0).cloned().unwrap_or(Value::Null);
        let mut paramsType: Value = type_varparamsTypeVariable.get(1).cloned().unwrap_or(Value::Null);
        let mut response: Value = self.sapi_private_get_balance_payment_options(&[paramsType]).await;
        //
        // {
        //     "items": [
        //         {
        //             "accountType": "SPOT",
        //             "availableBalanceDisplay": "1000.00",
        //             "enabled": true
        //         }
        //     ]
        // }
        //
        let mut result: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("info".to_string(), response.clone());
            m
        });
        let mut balances: Value = self.safe_list_k(response, "items", &[Value::from(vec![])]);
        {
                        let mut i: i64 = 0;
            let mut __for_first_1224: bool = true;
            while { if !__for_first_1224 { i += 1; } __for_first_1224 = false; i < (balances.len() as i64) } {
            let mut balance: Value = self.safe_dict(balances.clone(), Value::Int(i), &[]);
            let mut accountType: Option<String> = self.safe_string_k_opt(balance.clone(), "accountType", &[]);
            if (accountType.as_deref() == type_var.as_str()) {
                let mut free: Option<String> = self.safe_string_k_opt(balance, "availableBalanceDisplay", &[]);
                let mut account: indexmap::IndexMap<String, Value> = self.account().as_map().cloned().unwrap_or_default();
                account.insert("free".into(), free.map(Value::from).unwrap_or(Value::Null));
                result.insert("USDT".into(), Value::Map(account));
            }
        }
        }
        return self.safe_balance(Value::Map(result));

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parsePredictionOrder
 * @description parses a raw binance prediction order object into a unified order object
 * @param {object} order the raw order object
 * @param {object} [outcomeObj] the ourtome 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 outcomeObj = get_arg(optional_args, 0, Value::Null);
        //
        // {
        //     "orderId": "54124",
        //     "vendorOrderId": "0x1234abcd...",
        //     "vendor": "PREDICT_FUN",
        //     "marketTopicId": 4229564,
        //     "slug": "btc-price-1h-up-or-down",
        //     "marketTopicTitle": "BTC Price 1h Up or Down?",
        //     "marketId": 5567895,
        //     "marketTitle": "UP",
        //     "outcome": "YES",
        //     "outcomeIndex": 0,
        //     "status": "OPENING",
        //     "side": "BUY",
        //     "orderType": "LIMIT",
        //     "createTime": 1748131500000,
        //     "modifyTime": 1748131500000,
        //     "makerUsdtAmount": "1.00",
        //     "makerShareQty": "2000.00",
        //     "filledUsdtAmount": "0.00",
        //     "filledShareQty": "0.00",
        //     "fillPercentage": "0.00",
        //     "price": "0.50",
        //     "marketProviderFee": "0.02",
        //     "networkFee": "0.000001"
        // }
        //
        let mut status: Value = self.parse_order_status(self.safe_string_k(order.clone(), "status", &[])).map(Value::from).unwrap_or(Value::Null);
        let mut outcomeObjResolved: Value = outcomeObj;
        if (outcomeObjResolved == Value::Null) {
            let mut marketId: Option<String> = self.safe_string_k_opt(order.clone(), "marketId", &[]);
            let outcome: String = self.safe_string_upper_k_opt(order.clone(), "outcome", &[]).unwrap_or_default();
            let mut market: Value = self.safe_market(&[marketId.clone().map(Value::from).unwrap_or(Value::Null)]);
            let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
            if (outcomeName == Value::Null) {
                outcomeName = marketId.map(Value::from).unwrap_or(Value::Null);
            }
            outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
            outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
        }
        let mut side: Option<String> = self.safe_string_lower_k_opt(order.clone(), "side", &[]);
        let mut timestamp: Option<i64> = self.safe_integer_k(order.clone(), "createTime", &[]).as_i64();
        return self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_string_k(order.clone(), "orderId", &[]));
        m.insert("clientOrderId".to_string(), Value::Null);
        m.insert("info".to_string(), order.clone());
        m.insert("timestamp".to_string(), Value::from(timestamp));
        m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
        m.insert("lastTradeTimestamp".to_string(), Value::Null);
        m.insert("status".to_string(), status);
        m.insert("outcome".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "outcome", &[]));
        m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "id", &[]));
        m.insert("label".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "market", &[]));
        m.insert("type".to_string(), self.safe_string_lower_k(order.clone(), "orderType", &[]));
        m.insert("timeInForce".to_string(), Value::Null);
        m.insert("postOnly".to_string(), Value::Null);
        m.insert("reduceOnly".to_string(), Value::Null);
        m.insert("side".to_string(), side.map(Value::from).unwrap_or(Value::Null));
        m.insert("price".to_string(), self.safe_number_k(order, "price", &[]));
        m.insert("triggerPrice".to_string(), Value::Null);
        m.insert("amount".to_string(), Value::Null);
        m.insert("cost".to_string(), Value::Null);
        m.insert("average".to_string(), Value::Null);
        m.insert("filled".to_string(), Value::Null);
        m.insert("remaining".to_string(), Value::Null);
        m.insert("fee".to_string(), Value::Null);
        m.insert("trades".to_string(), Value::from(vec![]));
    m
}), &[outcomeObjResolved]);

    Value::Null
}

    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("OPENING".to_string(), Value::Str("open".into()));
                m.insert("FILLED".to_string(), Value::Str("closed".into()));
            m
        });
        if (status == Value::Null) {
            return None;
        }
        if (status.as_str().unwrap_or("").ends_with("Rejected")) {
            return Value::Str("rejected".into()).as_str().map(str::to_owned);
        }
        if (status.as_str().unwrap_or("").ends_with("Canceled")) {
            return Value::Str("canceled".into()).as_str().map(str::to_owned);
        }
        return self.safe_string(Value::Map(statuses), status.clone(), &[status.clone()]).as_str().map(str::to_owned);
}

/*
 * @method
 * @name binance#fetchOpenOrders
 * @description fetches currently open orders for the user
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-active-orders
 * @param {string} [outcome] filter by outcome
 * @param {int} [since] only return orders updated since this timestamp in ms
 * @param {int} [limit] max number of orders to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.tradeSide] Filter by trade side. Enum: BUY, SELL
 * @param {string} [params.l1Category] Filter by level-1 category
 * @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
 * @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
}));
        let mut paginate: Value = Value::Bool(false);
        let mut paramsPaginate: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        { let __destr_tmp: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchOpenOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default(); paginate = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
        let maxEntriesPerRequestparamsMaxEntriesPerRequestVariable: Vec<Value> = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchOpenOrders".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]).as_array().cloned().unwrap_or_default();
        let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(0).cloned().unwrap_or(Value::Null);
        let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(1).cloned().unwrap_or(Value::Null);
        let mut pageKey: String = "ccxtPageKey".to_string();
        if paginate.as_bool() == Some(true) {
            return self.fetch_paginated_call_incremental(Value::Str("fetchOpenOrders".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), Value::from(pageKey.clone()), maxEntriesPerRequest.clone()]).await;
        }
        let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), Value::from(pageKey), &[Value::Int(1)])), &(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 });
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (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 })]);
        if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
            request.insert("offset".into(), offSet);
        }
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            self.load_outcome(outcome.clone(), &[]).await;
            outcomeObj = self.outcome(outcome.clone());
            let mut market: indexmap::IndexMap<String, Value> = self.market(outcomeObj.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null)).as_map().cloned().unwrap_or_default();
            request.insert("marketId".into(), market.get("id").cloned().unwrap_or(Value::Null));
        }
        if (limit != Value::Null) {
            request.insert("limit".into(), limit.clone());
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOpenOrders".into()), &[paramsMaxEntriesPerRequest.clone()]).await;
        request.insert("walletAddress".into(), self.safe_string_k(wallet, "walletAddress", &[]));
        let __ws_arg_8 = self.extend(Value::Map(request), &[paramsMaxEntriesPerRequest]);
        let mut response: Value = self.sapi_private_get_order_list(&[__ws_arg_8]).await;
        //
        // {
        //     "total": 2,
        //     "offset": 0,
        //     "limit": 20,
        //     "orders": [
        //         {
        //             "orderId": "54124",
        //             "vendorOrderId": "0x1234abcd...",
        //             "vendor": "PREDICT_FUN",
        //             "marketTopicId": 4229564,
        //             "slug": "btc-price-1h-up-or-down",
        //             "marketTopicTitle": "BTC Price 1h Up or Down?",
        //             "marketId": 5567895,
        //             "marketTitle": "UP",
        //             "outcome": "YES",
        //             "outcomeIndex": 0,
        //             "status": "OPENING",
        //             "side": "BUY",
        //             "orderType": "LIMIT",
        //             "createTime": 1748131500000,
        //             "modifyTime": 1748131500000,
        //             "makerUsdtAmount": "1.00",
        //             "makerShareQty": "2000.00",
        //             "filledUsdtAmount": "0.00",
        //             "filledShareQty": "0.00",
        //             "fillPercentage": "0.00",
        //             "price": "0.50",
        //             "marketProviderFee": "0.02",
        //             "networkFee": "0.000001"
        //         }
        //     ]
        // }
        //
        let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
        let mut parsedOrders: Value = self.parse_prediction_orders(orders, &[outcomeObj, since.clone()]);
        return self.filter_by_outcome_since_limit(parsedOrders, &[outcome, since, limit]);

    Value::Null
}

/*
 * @method
 * @name binance#fetchOrders
 * @description fetches all historical orders for the user
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-order-history
 * @param {string} [outcome] filter by outcome
 * @param {int} [since] only return orders updated since this timestamp in ms
 * @param {int} [limit] max number of orders to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.orderType] Filter by order type. Enum: MARKET, LIMIT
 * @param {string} [params.l1Category] Filter by level-1 category
 * @param {string} [params.status] Filter by order status
 * @param {string} [params.until] end timestamp in ms
 * @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-structure)
 */
    pub async fn fetch_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
}));
        let mut paginate: Value = Value::Bool(false);
        let mut paramsPaginate: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        { let __destr_tmp: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchOrders".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default(); paginate = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
        let maxEntriesPerRequestparamsMaxEntriesPerRequestVariable: Vec<Value> = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchOrders".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]).as_array().cloned().unwrap_or_default();
        let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(0).cloned().unwrap_or(Value::Null);
        let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(1).cloned().unwrap_or(Value::Null);
        let mut pageKey: String = "ccxtPageKey".to_string();
        if paginate.as_bool() == Some(true) {
            return self.fetch_paginated_call_incremental(Value::Str("fetchOrders".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), Value::from(pageKey.clone()), maxEntriesPerRequest.clone()]).await;
        }
        let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), Value::from(pageKey), &[Value::Int(1)])), &(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 });
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (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 })]);
        if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
            request.insert("offset".into(), offSet);
        }
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            self.load_outcome(outcome.clone(), &[]).await;
            outcomeObj = self.outcome(outcome.clone());
        }
        if (limit != Value::Null) {
            request.insert("limit".into(), limit.clone());
        }
        if (since != Value::Null) {
            request.insert("startDate".into(), self.yyyymmdd(since.clone(), &[]));
        }
        let mut until: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "until", &[]);
        let mut paramsOmitted: Value = self.omit(paramsMaxEntriesPerRequest, Value::Str("until".into()), &[]);
        if (until != Value::Null) {
            request.insert("endDate".into(), self.yyyymmdd(until, &[]));
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOrders".into()), &[paramsOmitted.clone()]).await;
        request.insert("walletAddress".into(), self.safe_string_k(wallet, "walletAddress", &[]));
        let __ws_arg_9 = self.extend(Value::Map(request), &[paramsOmitted]);
        let mut response: Value = self.sapi_private_get_order_history(&[__ws_arg_9]).await;
        //
        // {
        //     "total": 15,
        //     "offset": 0,
        //     "limit": 20,
        //     "orders": [
        //         {
        //             "orderId": "54100",
        //             "vendorOrderId": "0xabcd5678...",
        //             "vendor": "PREDICT_FUN",
        //             "marketTopicId": 4229500,
        //             "slug": "btc-price-1h-up-or-down-prev",
        //             "marketTopicTitle": "BTC Price 1h Up or Down?",
        //             "marketId": 5567800,
        //             "marketTitle": "UP",
        //             "outcome": "YES",
        //             "outcomeIndex": 0,
        //             "status": "CLOSED",
        //             "side": "BUY",
        //             "orderType": "MARKET",
        //             "createTime": 1748045100000,
        //             "modifyTime": 1748045101000,
        //             "terminalTime": 1748045101000,
        //             "makerUsdtAmount": "1.00",
        //             "makerShareQty": "1923.07",
        //             "filledUsdtAmount": "1.00",
        //             "filledShareQty": "1923.07",
        //             "fillPercentage": "1.00",
        //             "price": "0.52",
        //             "marketProviderFee": "0.02",
        //             "networkFee": "0.000001"
        //         }
        //     ]
        // }
        //
        let mut orders: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
        let mut parsedOrders: Value = self.parse_prediction_orders(orders, &[outcomeObj, since.clone()]);
        return self.filter_by_outcome_since_limit(parsedOrders, &[outcome, since, limit]);

    Value::Null
}

/*
 * @method
 * @name binance#fetchPositions
 * @description fetches the user's outcome positions; outcome positions are spot token balances under the "+<encoding>" coin form (size and entry notional), the value/entry/mark price/pnl are computed from the current mid prices
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/position#query-positions
 * @param {string[]} [outcomes] filter by outcome ids or outcomes
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.tab] Position status tab. Values from PositionQueryType. Default ONGOING
 * @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
}));
        self.load_outcomes(&[]).await;
        let mut requestedOutcomeSymbols: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        if (outcomes != Value::Null) {
            {
                                let mut i: i64 = 0;
                let mut __for_first_1225: bool = true;
                while { if !__for_first_1225 { i += 1; } __for_first_1225 = false; i < (outcomes.len() as i64) } {
                let mut requested: Value = outcomes.as_array().map(Vec::as_slice).unwrap_or_default().get(i as usize).cloned().unwrap_or(Value::Null);
                let mut requestedOutcomeObj: Value = self.safe_outcome(requested.clone(), &[]);
                let mut requestedOutcome: Value = self.safe_string_k(requestedOutcomeObj, "outcome", &[requested]);
                if let Value::Dict(__d) = &mut requestedOutcomeSymbols { std::sync::Arc::make_mut(__d).insert(crate::runtime::stringify_param(&requestedOutcome), Value::Bool(true)); }
            }
            }
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("fetchPositions".into()), &[params.clone()]).await;
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("walletAddress".to_string(), self.safe_string_k(wallet, "walletAddress", &[]));
            m
        });
        let __ws_arg_10 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.sapi_private_get_position_list(&[__ws_arg_10]).await;
        //
        // {
        //     "summary": {
        //         "totalValue": "1523.45",
        //         "positionValue": "523.45",
        //         "walletBalance": "1000.00",
        //         "totalClaimableAmount": "50.00",
        //         "todayRealizedPnl": "15.30",
        //         "todayRealizedPnlPercent": "3.10",
        //         "todayTotalCost": "493.55"
        //     },
        //     "counts": {
        //         "ongoingCount": 3,
        //         "endedCount": 12,
        //         "pendingClaimCount": 1
        //     },
        //     "positions": [
        //         {
        //             "positionId": 1001,
        //             "vendor": "PREDICT_FUN",
        //             "chainId": "56",
        //             "tokenId": "112233",
        //             "collateralSymbol": "USDT",
        //             "topicType": "FLAT",
        //             "marketTopicId": 4229564,
        //             "marketId": 5567895,
        //             "marketTopicTitle": "BTC Price 1h Up or Down?",
        //             "marketTitle": "UP",
        //             "outcomeName": "YES",
        //             "outcomeIndex": 0,
        //             "shares": "1923.07",
        //             "avgPrice": "0.52",
        //             "totalCost": "1.00",
        //             "value": "1.06",
        //             "currentPrice": "0.55",
        //             "toWin": "1923.07",
        //             "positionStatus": "OPEN",
        //             "canClaim": false,
        //             "endDate": 1748134800000,
        //             "unrealizedPnl": "0.06",
        //             "unrealizedPnlPercent": "6.00",
        //             "realizedPnl": "0.00",
        //             "pnl": "0.06",
        //             "createdTime": 1748131500000,
        //             "updatedTime": 1748132000000
        //         }
        //     ]
        // }
        //
        let mut data: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
        if (outcomes == Value::Null) {
            return self.parse_prediction_positions(data.clone(), &[]);
        }
        let mut positions: Vec<Value> = self.parse_prediction_positions(data, &[]).as_array().cloned().unwrap_or_default();
        let mut filtered: Vec<Value> = Vec::new();
        let mut positionsLength: f64 = ((positions.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1226: bool = true;
            while { if !__for_first_1226 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1226 = false; i.as_f64().unwrap_or(f64::NAN) < positionsLength } {
            let mut position: Value = positions.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            let mut positionOutcome: Option<String> = self.safe_string_k_opt(position.clone(), "outcome", &[]);
            if (positionOutcome.is_some()) && (matches!((&requestedOutcomeSymbols, &positionOutcome.clone().map(Value::from).unwrap_or(Value::Null)), (Value::Dict(__d), Value::Str(__k)) if __d.contains_key(__k.as_ref()))) {
                filtered.push(position);
            }
        }
        }
        return Value::from(filtered);

    Value::Null
}

/*
 * @method
 * @name binance#fetchPosition
 * @description fetch data on an open position
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/position#query-positions-by-filter
 * @param {string} [outcome] filter by outcome
 * @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_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 request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            self.load_outcome(outcome.clone(), &[]).await;
            outcomeObj = self.outcome(outcome.clone());
            let mut market: indexmap::IndexMap<String, Value> = self.market(outcomeObj.as_map().and_then(|__m| __m.get("market")).cloned().unwrap_or(Value::Null)).as_map().cloned().unwrap_or_default();
            request.insert("marketTopicId".into(), crate::value::get_value_k(&market.get("info").cloned().unwrap_or(Value::Null), "marketTopicId"));
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("fetchOrders".into()), &[params.clone()]).await;
        request.insert("walletAddress".into(), self.safe_string_k(wallet, "walletAddress", &[]));
        let __ws_arg_11 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.sapi_private_get_position_filter(&[__ws_arg_11]).await;
        //
        //
        let mut positions: Value = self.safe_list_k(response, "positions", &[Value::from(vec![])]);
        let mut parsedPositions: Value = self.parse_prediction_positions(positions, &[]);
        let mut filteredPositions: Value = self.filter_by_outcome_since_limit(parsedPositions, &[outcome, Value::Null, Value::Null]);
        return self.safe_dict(filteredPositions, Value::Int(0), &[]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parsePredictionPosition
 * @description parses a spot balance entry for an outcome token into a unified position object
 * @param {object} position the raw balance entry
 * @param {object} [outcomeObj] the ourtome 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 outcomeObj = get_arg(optional_args, 0, Value::Null);
        let mut outcomeObjResolved: Value = outcomeObj;
        if (outcomeObjResolved == Value::Null) {
            let mut marketId: Option<String> = self.safe_string_k_opt(position.clone(), "marketId", &[]);
            let outcome: String = self.safe_string_upper_k_opt(position.clone(), "outcomeName", &[]).unwrap_or_default();
            let mut market: Value = self.safe_market(&[marketId.clone().map(Value::from).unwrap_or(Value::Null)]);
            let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
            if (outcomeName == Value::Null) {
                outcomeName = marketId.map(Value::from).unwrap_or(Value::Null);
            }
            outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
            outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
        }
        let mut timestamp: Option<i64> = self.safe_integer_k(position.clone(), "createdTime", &[]).as_i64();
        let mut totalCost: Value = self.parse_number(self.safe_string_k(position.clone(), "totalCost", &[]), &[]);
        return self.safe_prediction_position(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_integer_k(position.clone(), "positionId", &[]));
        m.insert("outcome".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "outcome", &[]));
        m.insert("outcomeId".to_string(), self.safe_string2(outcomeObjResolved.clone(), Value::Str("outcomeId".into()), Value::Str("id".into()), &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved, "market", &[]));
        m.insert("timestamp".to_string(), Value::from(timestamp));
        m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
        m.insert("isolated".to_string(), Value::Bool(false));
        m.insert("hedged".to_string(), Value::Null);
        m.insert("side".to_string(), Value::Str("long".into()));
        m.insert("contracts".to_string(), Value::Null);
        m.insert("contractSize".to_string(), self.parse_number(self.safe_string_k(position.clone(), "shares", &[]), &[]));
        m.insert("entryPrice".to_string(), self.parse_number(self.safe_string_k(position.clone(), "avgPrice", &[]), &[]));
        m.insert("markPrice".to_string(), Value::Null);
        m.insert("notional".to_string(), self.parse_number(self.safe_string_k(position.clone(), "value", &[]), &[]));
        m.insert("leverage".to_string(), Value::Null);
        m.insert("collateral".to_string(), totalCost.clone());
        m.insert("initialMargin".to_string(), totalCost);
        m.insert("maintenanceMargin".to_string(), Value::Null);
        m.insert("initialMarginPercentage".to_string(), Value::Null);
        m.insert("maintenanceMarginPercentage".to_string(), Value::Null);
        m.insert("unrealizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealizedPnl", &[]), &[]));
        m.insert("realizedPnl".to_string(), self.parse_number(self.safe_string_k(position.clone(), "realizedPnl", &[]), &[]));
        m.insert("liquidationPrice".to_string(), Value::Null);
        m.insert("marginRatio".to_string(), Value::Null);
        m.insert("marginMode".to_string(), Value::Str("cross".into()));
        m.insert("percentage".to_string(), self.parse_number(self.safe_string_k(position.clone(), "unrealizedPnlPercent", &[]), &[]));
        m.insert("info".to_string(), position);
    m
}));

    Value::Null
}

/*
 * @method
 * @name binance#fetchMyTrades
 * @description fetch all trades made by the user
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#query-order-history
 * @param {string} [outcome] filter by outcome
 * @param {int} [since] only return orders updated since this timestamp in ms
 * @param {int} [limit] max number of orders to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.orderType] Filter by order type. Enum: MARKET, LIMIT
 * @param {string} [params.l1Category] Filter by level-1 category
 * @param {string} [params.status] Filter by order status
 * @param {string} [params.until] end timestamp in ms
 * @param {boolean} [params.paginate] *spot only* default false, when true will automatically paginate by calling this endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
 * @returns {object[]} a list of [prediction order structures](https://docs.ccxt.com/#/?id=prediction-order-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
}));
        let mut paginate: Value = Value::Bool(false);
        let mut paramsPaginate: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        { let __destr_tmp: Vec<Value> = self.handle_option_bool_and_params(params, Value::Str("fetchMyTrades".into()), Value::Str("paginate".into()), &[Value::Bool(false)]).as_array().cloned().unwrap_or_default(); paginate = __destr_tmp.get(0).cloned().unwrap_or(Value::Null); paramsPaginate = __destr_tmp.get(1).cloned().unwrap_or(Value::Null); }
        let maxEntriesPerRequestparamsMaxEntriesPerRequestVariable: Vec<Value> = self.handle_option_integer_and_params(paramsPaginate, Value::Str("fetchMyTrades".into()), Value::Str("maxEntriesPerRequest".into()), &[Value::Int(100)]).as_array().cloned().unwrap_or_default();
        let mut maxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(0).cloned().unwrap_or(Value::Null);
        let mut paramsMaxEntriesPerRequest: Value = maxEntriesPerRequestparamsMaxEntriesPerRequestVariable.get(1).cloned().unwrap_or(Value::Null);
        let mut pageKey: String = "ccxtPageKey".to_string();
        if paginate.as_bool() == Some(true) {
            return self.fetch_paginated_call_incremental(Value::Str("fetchMyTrades".into()), &[outcome.clone(), since.clone(), limit.clone(), paramsMaxEntriesPerRequest.clone(), Value::from(pageKey.clone()), maxEntriesPerRequest.clone()]).await;
        }
        let mut page: Value = (match (&(self.safe_integer(paramsMaxEntriesPerRequest.clone(), Value::from(pageKey), &[Value::Int(1)])), &(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 });
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("status".to_string(), Value::Str("FILLED".into()));
            m
        });
        let mut offSet: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "offset", &[(match (&(page), &(maxEntriesPerRequest)) { (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 })]);
        if offSet.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64) {
            request.insert("offset".into(), offSet);
        }
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            self.load_outcome(outcome.clone(), &[]).await;
            outcomeObj = self.outcome(outcome.clone());
        }
        if (limit != Value::Null) {
            request.insert("limit".into(), limit.clone());
        }
        if (since != Value::Null) {
            request.insert("startDate".into(), self.yyyymmdd(since.clone(), &[]));
        }
        let mut until: Value = self.safe_integer_k(paramsMaxEntriesPerRequest.clone(), "until", &[]);
        let mut paramsOmitted: Value = self.omit(paramsMaxEntriesPerRequest, Value::Str("until".into()), &[]);
        if (until != Value::Null) {
            request.insert("endDate".into(), self.yyyymmdd(until, &[]));
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("fetchMyTrades".into()), &[paramsOmitted.clone()]).await;
        request.insert("walletAddress".into(), self.safe_string_k(wallet, "walletAddress", &[]));
        let __ws_arg_12 = self.extend(Value::Map(request), &[paramsOmitted]);
        let mut response: Value = self.sapi_private_get_order_history(&[__ws_arg_12]).await;
        //
        // {
        //     "total": 15,
        //     "offset": 0,
        //     "limit": 20,
        //     "orders": [
        //         {
        //             "orderId": "54100",
        //             "vendorOrderId": "0xabcd5678...",
        //             "vendor": "PREDICT_FUN",
        //             "marketTopicId": 4229500,
        //             "slug": "btc-price-1h-up-or-down-prev",
        //             "marketTopicTitle": "BTC Price 1h Up or Down?",
        //             "marketId": 5567800,
        //             "marketTitle": "UP",
        //             "outcome": "YES",
        //             "outcomeIndex": 0,
        //             "status": "CLOSED",
        //             "side": "BUY",
        //             "orderType": "MARKET",
        //             "createTime": 1748045100000,
        //             "modifyTime": 1748045101000,
        //             "terminalTime": 1748045101000,
        //             "makerUsdtAmount": "1.00",
        //             "makerShareQty": "1923.07",
        //             "filledUsdtAmount": "1.00",
        //             "filledShareQty": "1923.07",
        //             "fillPercentage": "1.00",
        //             "price": "0.52",
        //             "marketProviderFee": "0.02",
        //             "networkFee": "0.000001"
        //         }
        //     ]
        // }
        //
        let mut trades: Value = self.safe_list_k(response, "orders", &[Value::from(vec![])]);
        let mut parsedTrades: Value = self.parse_prediction_trades(trades, &[outcomeObj]);
        return self.filter_by_outcome_since_limit(parsedTrades, &[outcome, since, limit]);

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#parsePredictionTrade
 * @description parses a single binance fill into a unified trade object
 * @param {object} trade the raw fill object
 * @param {object} [outcomeObj] the outcome 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 outcomeObj = get_arg(optional_args, 0, Value::Null);
        //
        // {
        //     "orderId": "54124",
        //     "vendorOrderId": "0x1234abcd...",
        //     "vendor": "PREDICT_FUN",
        //     "marketTopicId": 4229564,
        //     "slug": "btc-price-1h-up-or-down",
        //     "marketTopicTitle": "BTC Price 1h Up or Down?",
        //     "marketId": 5567895,
        //     "marketTitle": "UP",
        //     "outcome": "YES",
        //     "outcomeIndex": 0,
        //     "status": "OPENING",
        //     "side": "BUY",
        //     "orderType": "LIMIT",
        //     "createTime": 1748131500000,
        //     "modifyTime": 1748131500000,
        //     "makerUsdtAmount": "1.00",
        //     "makerShareQty": "2000.00",
        //     "filledUsdtAmount": "0.00",
        //     "filledShareQty": "0.00",
        //     "fillPercentage": "0.00",
        //     "price": "0.50",
        //     "marketProviderFee": "0.02",
        //     "networkFee": "0.000001"
        // }
        //
        let mut outcomeObjResolved: Value = outcomeObj;
        if (outcomeObjResolved == Value::Null) {
            let mut marketId: Option<String> = self.safe_string_k_opt(trade.clone(), "marketId", &[]);
            let outcome: String = self.safe_string_upper_k_opt(trade.clone(), "outcome", &[]).unwrap_or_default();
            let mut market: Value = self.safe_market(&[marketId.clone().map(Value::from).unwrap_or(Value::Null)]);
            let mut outcomeName: Value = self.safe_string_k(market, "market", &[]);
            if (outcomeName == Value::Null) {
                outcomeName = marketId.map(Value::from).unwrap_or(Value::Null);
            }
            outcomeName = Value::Str(format!("{}{}", outcomeName, Value::Str(format!("{}{}", Value::Str(":".into()), outcome).into())).into());
            outcomeObjResolved = self.safe_outcome(outcomeName, &[]);
        }
        let mut timestamp: Option<i64> = self.safe_integer_k(trade.clone(), "createTime", &[]).as_i64();
        let mut filled: Option<String> = self.safe_string_k_opt(trade.clone(), "filledShareQty", &[]);
        let mut cost: Option<String> = self.safe_string_k_opt(trade.clone(), "filledUsdtAmount", &[]);
        let mut price: Option<String> = self.safe_string_k_opt(trade.clone(), "price", &[]);
        let mut orderType: Option<String> = self.safe_string_lower_k_opt(trade.clone(), "orderType", &[]);
        let mut fee: Value = Value::Null;
        if (orderType.as_deref() == Some("market")) && (cost.is_some()) && (price.is_some()) && (filled.is_some()) {
            // buys pay cost above price*filled, sells receive proceeds net of the fee —
            // either way the fee is the absolute difference
            let mut feeCost: Value = crate::precise::Precise::stringAbs(&crate::precise::Precise::stringSub(&cost.clone().map(Value::from).unwrap_or(Value::Null), &crate::precise::Precise::stringMul(&price.clone().map(Value::from).unwrap_or(Value::Null), &filled.clone().map(Value::from).unwrap_or(Value::Null))));
            fee = Value::Map({
                let mut m = indexmap::IndexMap::new();
                    m.insert("currency".to_string(), Value::Str("USDT".into()));
                    m.insert("cost".to_string(), self.parse_number(feeCost, &[]));
                m
            });
        }
        return self.safe_prediction_trade(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), Value::Null);
        m.insert("info".to_string(), trade.clone());
        m.insert("timestamp".to_string(), Value::from(timestamp));
        m.insert("datetime".to_string(), self.iso8601(Value::from(timestamp)));
        m.insert("outcome".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "outcome", &[]));
        m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "id", &[]));
        m.insert("label".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObjResolved.clone(), "market", &[]));
        m.insert("order".to_string(), self.safe_string_k(trade.clone(), "orderId", &[]));
        m.insert("type".to_string(), orderType.map(Value::from).unwrap_or(Value::Null));
        m.insert("side".to_string(), self.safe_string_lower_k(trade.clone(), "side", &[]));
        m.insert("takerOrMaker".to_string(), Value::Null);
        m.insert("price".to_string(), price.map(Value::from).unwrap_or(Value::Null));
        m.insert("amount".to_string(), self.safe_string_k(trade, "makerShareQty", &[]));
        m.insert("cost".to_string(), cost.map(Value::from).unwrap_or(Value::Null));
        m.insert("fee".to_string(), fee);
    m
}), &[outcomeObjResolved]);

    Value::Null
}

/*
 * @method
 * @name binance#fetchWallet
 * @description fetch wallet for user and save the one match the walletAddress user provided
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/wallet#list-prediction-wallets
 * @param {string} [methodName] method name
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a wallet
 */
    pub async fn fetch_wallet(&mut self, mut methodName: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if (self.safe_dict_k(self.options.clone(), "wallet", &[]) != Value::Null) {
            return self.safe_dict_k(self.options.clone(), "wallet", &[]);
        }
        let mut walletAddress: Value = self.handle_option_string_and_params(params, methodName, Value::Str("walletAddress".into()), &[self.walletAddress.clone()]).as_array().and_then(|__arr| __arr.get(0)).cloned().unwrap_or(Value::Null);
        let mut response: Value = self.sapi_private_get_wallet_list(&[]).await;
        //
        // {
        //     "wallets": [
        //         {
        //             "walletAddress": "0x12e32db8817e292508c34111cbc4b23340df542c",
        //             "walletId": "5b5c1ec3be4e4416a5872b21c1ca5d20",
        //             "registeredTime": 1748000000000
        //         }
        //     ]
        // }
        //
        let mut wallets: Value = self.safe_list_k(response, "wallets", &[Value::from(vec![])]);
        if (walletAddress == Value::Null) {
            { let __be_tmp = self.safe_dict(wallets.clone(), Value::Int(0), &[]); if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wallet".into(), __be_tmp); } }
            return self.safe_dict_k(self.options.clone(), "wallet", &[]);
        }
        let mut walletLength: f64 = ((wallets.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1227: bool = true;
            while { if !__for_first_1227 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1227 = false; i.as_f64().unwrap_or(f64::NAN) < walletLength } {
            let mut w: Value = self.safe_string(wallets.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), Value::Str("walletAddress".into()), &[Value::Str("".into())]);
            if (w.as_str() == walletAddress.as_str()) {
                if let Value::Dict(__d) = &mut self.options { std::sync::Arc::make_mut(__d).insert("wallet".into(), wallets.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)); }
                return self.safe_dict_k(self.options.clone(), "wallet", &[]);
            }
        }
        }
        panic!("{}", crate::exchange_errors::not_supported(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str("fetchWallet could'n find wallet ".into())).into()), walletAddress)));

    Value::Null
}

/*
 * @method
 * @name binance#fetchQuote
 * @description request for quote from binance server
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#get-quote
 * @param {object} [request] request to the exchange API endpoint
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.chainId] Chain ID. Default 56 (BSC)
 * @param {integer} [params.feeRateBps] Fee rate in basis points. Default 200, range 1–10000
 * @param {string} [params.fundingSource] Funding source. Enum: MPC, CEX. Default MPC
 * @param {string} [params.fundTransferAmount] Auto-transfer amount before order (wei). Must be > 0 if provided
 * @returns {object} a quote
 */
    pub async fn fetch_quote(&mut self, mut request: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let __ws_arg_13 = self.extend(request, &[params]);
        let mut response: Value = self.sapi_private_post_trade_get_quote(&[__ws_arg_13]).await;
        return response;

    Value::Null
}

    pub fn price_to_precision(&self, mut outcome: Value, mut price: Value) -> Value {
        let mut market: Value = self.market(outcome);
        let mut prec: Value = self.safe_number(self.safe_dict_k(market, "precision", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]), Value::Str("price".into()), &[Value::Float(0.0001)]);
        let mut decimals: Value = Value::Int(4);
        if (prec != Value::Null) && (prec.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
            decimals = self.precision_from_string(self.number_to_string(prec));
        }
        return self.decimal_to_precision(price, Value::Int(crate::runtime::ROUND), decimals, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);

    Value::Null
}

    pub fn amount_to_precision(&self, mut outcome: Value, mut amount: Value) -> Value {
        let mut market: Value = self.market(outcome);
        let mut prec: Value = self.safe_number(self.safe_dict_k(market, "precision", &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]), Value::Str("amount".into()), &[Value::Float(0.01)]);
        let mut decimals: Value = Value::Int(2);
        if (prec != Value::Null) && (prec.as_f64().unwrap_or(f64::NAN) > ((0i64) as f64)) {
            decimals = self.precision_from_string(self.number_to_string(prec));
        }
        return self.decimal_to_precision(amount, Value::Int(crate::runtime::TRUNCATE), decimals, &[Value::Int(crate::runtime::DECIMAL_PLACES), self.paddingMode.clone()]);

    Value::Null
}

/*
 * @method
 * @name binance#createOrder
 * @description creates a limit or market order for an outcome market
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#place-order
 * @param {string} outcome unified outcome
 * @param {string} type 'limit' or 'market'
 * @param {string} side 'buy' or 'sell'
 * @param {float} amount quantity of outcome tokens
 * @param {float} [price] limit price (0–1 range for prediction markets)
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.timeInForce] Must match orderType: FOK for MARKET, GTC for LIMIT
 * @param {string} [params.slippage] slippage for market orders (default 5%)
 * @param {string} [params.fundingSource] Funding source. Enum: MPC, CEX. Default MPC
 * @param {string} [params.fundTransferAmount] Auto-transfer amount before order (wei). Must be > 0 if provided
 * @param {string} [params.accountType] Payment account type. Enum: SPOT, FUNDING
 * @param {string} [params.feeRateBps] Payment account type. Enum: SPOT, FUNDING
 * @param {string} [params.cost] Buy prediction market with USDT cost, only for buy side
 * @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_outcome(outcome.clone(), &[]).await;
        let mut outcomeObj: Value = self.outcome(outcome.clone());
        // markets are keyed by the parent market outcome; the outcome handle ("MARKET:LABEL")
        // is not a market id, so resolve the market and price/amount precision via outcomeObj['market']
        let mut marketSymbol: Option<String> = self.safe_string_k_opt(outcomeObj.clone(), "market", &[]);
        let mut market: Value = self.market(marketSymbol.clone().map(Value::from).unwrap_or(Value::Null));
        let mut typeUpper: Value = (if let Some(__s) = type_var.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
        let mut sideUpper: Value = (if let Some(__s) = side.as_str() { Value::Str(__s.to_uppercase().into()) } else { Value::Null });
        let mut wallet: Value = self.fetch_wallet(Value::Str("createOrder".into()), &[params.clone()]).await;
        let mut defaultSlippage: Value = self.safe_string_k(self.options.clone(), "defaultSlippage", &[Value::Str("0.05".into())]);
        let mut slippage: Value = self.safe_string_k(params.clone(), "slippage", &[defaultSlippage]);
        let mut cost: Option<String> = self.safe_string_k_opt(params.clone(), "cost", &[]);
        let mut slippageBps: Value = self.parse_to_int(crate::precise::Precise::stringMul(&slippage, &Value::Str("10000".into())));
        let mut commonRequest: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("walletAddress".to_string(), self.safe_string_k(wallet.clone(), "walletAddress", &[]));
                m.insert("orderType".to_string(), typeUpper.clone());
                m.insert("slippageBps".to_string(), slippageBps);
            m
        });
        let mut amountStr: Value = self.number_to_string(amount.clone());
        let mut priceStr: Value = self.number_to_string(price.clone());
        let mut defaultTif: String = "FOK".to_string();
        if (typeUpper.as_str() == Some("LIMIT")) {
            if (price == Value::Null) {
                panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str("createOrder requires price for limit order".into()))));
            }
            commonRequest.insert("priceLimit".into(), self.price_to_precision(marketSymbol.clone().map(Value::from).unwrap_or(Value::Null), price.clone()));
            defaultTif = "GTC".to_string();
        }
        if (sideUpper.as_str() == Some("BUY")) {
            if (cost.is_some()) {
                amountStr = cost.map(Value::from).unwrap_or(Value::Null);
            }  else {
                // the amountIn represents USDT for buy order
                let mut feeRateBps: Value = self.safe_string_k(params.clone(), "feeRateBps", &[Value::Str("200".into())]);
                if (typeUpper.as_str() == Some("LIMIT")) {
                    feeRateBps = Value::Str("0".into());
                }  else {
                    if (price == Value::Null) {
                        panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", Value::Str(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" createOrder requires price for ".into())).into()), side).into()), Value::Str(" order".into()))));
                    }
                }
                let mut feeRate: Value = crate::precise::Precise::stringDiv(&feeRateBps, &Value::Str("10000".into()));
                let mut minPrice: Value = crate::precise::Precise::stringMin(&priceStr, &crate::precise::Precise::stringSub(&Value::Str("1".into()), &priceStr));
                let mut fee: Value = crate::precise::Precise::stringMul(&crate::precise::Precise::stringMul(&feeRate, &minPrice), &amountStr);
                amountStr = crate::precise::Precise::stringAdd(&crate::precise::Precise::stringMul(&amountStr, &priceStr), &fee);
            }
        }
        let mut timeInForce: Value = self.safe_string_upper_k(params.clone(), "timeInForce", &[Value::from(defaultTif)]);
        let mut accountType: Option<String> = self.safe_string_k_opt(params.clone(), "accountType", &[]);
        if (accountType.is_none()) {
            panic!("{}", crate::exchange_errors::arguments_required(format!("{}{}", self.id.clone(), Value::Str(" createOrder requires accountType (SPOT, FUNDING)".into()))));
        }
        let mut paramsOmitted: Value = self.omit(params, Value::from(vec![Value::Str("timeInForce".into()), Value::Str("accountType".into()), Value::Str("cost".into())]), &[]);
        let __ws_arg_14 = self.amount_to_precision(marketSymbol.map(Value::from).unwrap_or(Value::Null), amountStr);
        let mut quoteRequest: Value = self.extend(Value::Map(commonRequest.clone()), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("tokenId".to_string(), outcomeObj.as_map().and_then(|__m| __m.get("id")).cloned().unwrap_or(Value::Null));
                m.insert("side".to_string(), sideUpper);
                m.insert("amountIn".to_string(), crate::precise::Precise::stringMul(&__ws_arg_14, &Value::Str("1000000000000000000".into())));
            m
        })]);
        let mut quote: Value = self.fetch_quote(quoteRequest, &[paramsOmitted.clone()]).await;
        let mut quoteId: Option<String> = self.safe_string_k_opt(quote, "quoteId", &[]);
        let __ws_arg_15 = self.safe_string_k(wallet, "walletId", &[]);
        let mut orderRequest: Value = self.extend(Value::Map(commonRequest), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("walletId".to_string(), __ws_arg_15);
                m.insert("quoteId".to_string(), quoteId.map(Value::from).unwrap_or(Value::Null));
                m.insert("timeInForce".to_string(), timeInForce);
                m.insert("accountType".to_string(), accountType.map(Value::from).unwrap_or(Value::Null));
            m
        })]);
        let __ws_arg_16 = self.extend(orderRequest, &[paramsOmitted]);
        let mut response: Value = self.sapi_private_post_trade_place_order_bundle(&[__ws_arg_16]).await;
        return self.safe_prediction_order(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("id".to_string(), self.safe_string_k(response.clone(), "orderId", &[]));
        m.insert("clientOrderId".to_string(), Value::Null);
        m.insert("info".to_string(), response);
        m.insert("timestamp".to_string(), Value::Null);
        m.insert("datetime".to_string(), Value::Null);
        m.insert("status".to_string(), Value::Null);
        m.insert("outcome".to_string(), self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]));
        m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
        m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
        m.insert("market".to_string(), self.safe_string_k(outcomeObj, "market", &[]));
        m.insert("type".to_string(), type_var);
        m.insert("side".to_string(), side);
        m.insert("price".to_string(), price);
        m.insert("amount".to_string(), amount);
        m.insert("filled".to_string(), Value::Null);
        m.insert("remaining".to_string(), Value::Null);
        m.insert("cost".to_string(), Value::Null);
        m.insert("fee".to_string(), Value::Null);
        m.insert("trades".to_string(), Value::from(vec![]));
    m
}), &[market]);

    Value::Null
}

/*
 * @method
 * @name binance#createMarketOrderWithCost
 * @description create a market order by providing the symbol, side and cost
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#place-order
 * @param {string} symbol unified symbol of the market to create an order in
 * @param {string} side 'buy' or 'sell'
 * @param {float} cost how much you want to trade in units of the quote currency
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} an [order structure]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn create_market_order_with_cost(&mut self, mut symbol: Value, mut side: 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 req: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("cost".to_string(), cost.clone());
            m
        });
        let __ws_arg_17 = self.extend(Value::Map(req), &[params]);
        return self.create_order(symbol, Value::Str("market".into()), side, cost, &[Value::Null, __ws_arg_17]).await;

    Value::Null
}

/*
 * @method
 * @name binance#cancelOrder
 * @description cancels a single open order
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#batch-cancel-orders
 * @param {string} id order id
 * @param {string} [outcome] unified outcome
 * @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
}));
        let mut orders: Value = self.cancel_orders(Value::from(vec![id]), &[outcome, params]).await;
        let mut first: Value = self.safe_dict(orders, Value::Int(0), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]);
        return first;

    Value::Null
}

/*
 * @method
 * @name binance#cancelOrders
 * @description cancels multiple open orders
 * @see https://developers.binance.com/en/docs/catalog/web3-wallet-prediction-trading/api/rest-api/trade#batch-cancel-orders
 * @param {string[]} ids order ids
 * @param {string} [outcome] unified outcome (required)
 * @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
}));
        let __ids_empty = Vec::new();
        let ids = ids.as_array().unwrap_or(&__ids_empty);
        let mut outcomeObj: Value = Value::Null;
        if (outcome != Value::Null) {
            self.load_outcome(outcome.clone(), &[]).await;
            outcomeObj = self.outcome(outcome.clone());
        }
        let mut wallet: Value = self.fetch_wallet(Value::Str("cancelOrders".into()), &[params.clone()]).await;
        let mut request: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("walletAddress".to_string(), self.safe_string_k(wallet.clone(), "walletAddress", &[]));
                m.insert("walletId".to_string(), self.safe_string_k(wallet, "walletId", &[]));
            m
        });
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1228: bool = true;
            while { if !__for_first_1228 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1228 = false; i.as_f64().unwrap_or(f64::NAN) < ((ids.len() as i64) as f64) } {
            let mut key: Value = Value::Str(format!("{}{}", Value::Str(format!("{}{}", Value::Str("cancelInfoList[".into()), self.number_to_string(i.clone())).into()), Value::Str("].orderId".into())).into());
            request.insert(crate::runtime::stringify_param(&key), ids.get((i).as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null));
        }
        }
        let __ws_arg_18 = self.extend(Value::Map(request), &[params]);
        let mut response: Value = self.sapi_private_post_trade_batch_cancel(&[__ws_arg_18]).await;
        //
        // {
        //     "canceled": [
        //         "54124"
        //     ],
        //     "failed": [
        //         {
        //             "orderId": "54126",
        //             "reason": "ORDER_NOT_FOUND"
        //         }
        //     ]
        // }
        //
        let mut canceledOrders: Vec<Value> = self.safe_list_k(response.clone(), "canceled", &[Value::from(vec![])]).as_array().cloned().unwrap_or_default();
        let mut outcomeSymbol: Value = self.safe_string_k(outcomeObj.clone(), "outcome", &[outcome]);
        let mut failedOrders: Value = self.safe_list_k(response, "failed", &[Value::from(vec![])]);
        let mut failedOrdersLength: f64 = ((failedOrders.len() as i64) as f64);
        if failedOrdersLength > ((0i64) as f64) {
            let mut failedDetails: Vec<Value> = Vec::new();
            {
                                let mut i: Value = Value::Int(0);
                let mut __for_first_1229: bool = true;
                while { if !__for_first_1229 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1229 = false; i.as_f64().unwrap_or(f64::NAN) < failedOrdersLength } {
                let mut failedOrder: Value = self.safe_dict(failedOrders.clone(), i.clone(), &[]);
                let failedOrderId: String = self.safe_string_k_opt(failedOrder.clone(), "orderId", &[Value::Str("".into())]).unwrap_or_default();
                let failedReason: String = self.safe_string_k_opt(failedOrder, "reason", &[Value::Str("".into())]).unwrap_or_default();
                failedDetails.push(Value::Str(format!("{}{}", Value::Str(format!("{}{}", failedOrderId, Value::Str(": ".into())).into()), failedReason).into()));
            }
            }
            panic!("{}", crate::exchange_errors::order_not_found(format!("{}{}", Value::Str(format!("{}{}", self.id.clone(), Value::Str(" cancelOrders() failed for ".into())).into()), Value::Str(failedDetails.iter().map(|__v| __v.to_string()).collect::<Vec<String>>().join(", ").into()))));
        }
        let mut orders: Vec<Value> = Vec::new();
        let mut canceledOrdersLength: f64 = ((canceledOrders.len() as i64) as f64);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_1230: bool = true;
            while { if !__for_first_1230 { if let Value::Int(n) = &mut i { *n += 1; } } __for_first_1230 = false; i.as_f64().unwrap_or(f64::NAN) < canceledOrdersLength } {
            let mut status: Value = canceledOrders.get(i.as_i64().unwrap_or(-1) as usize).cloned().unwrap_or(Value::Null);
            let mut order: indexmap::IndexMap<String, Value> = ({
                let mut m = indexmap::IndexMap::new();
                    m.insert("id".to_string(), status.clone());
                    m.insert("clientOrderId".to_string(), Value::Null);
                    m.insert("info".to_string(), status);
                    m.insert("status".to_string(), Value::Str("canceled".into()));
                    m.insert("outcome".to_string(), outcomeSymbol.clone());
                    m.insert("outcomeId".to_string(), self.safe_string_k(outcomeObj.clone(), "id", &[]));
                    m.insert("label".to_string(), self.safe_string_k(outcomeObj.clone(), "label", &[]));
                    m.insert("market".to_string(), self.safe_string_k(outcomeObj.clone(), "market", &[]));
                    m.insert("timestamp".to_string(), Value::Null);
                    m.insert("datetime".to_string(), Value::Null);
                m
            });
            orders.push(self.safe_prediction_order(Value::Map(order), &[]));
        }
        }
        return Value::from(orders);

    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 {
        if (response == Value::Null) {
            return Value::Null;
        }
        let mut errorCode: Option<String> = self.safe_string_k_opt(response.clone(), "code", &[]);
        if (errorCode.is_some()) && crate::precise::Precise::stringLt(&errorCode.clone().map(Value::from).unwrap_or(Value::Null), &Value::Str("0".into())).as_bool() == Some(true) {
            let mut message: Value = self.safe_string_k(response, "msg", &[Value::Str("".into())]);
            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), errorCode.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), message, feedback.clone());
            panic!("{}", crate::exchange_errors::exchange_error(feedback));
        }
        return Value::Null;

    Value::Null
}

/*
 * @ignore
 * @method
 * @name binance#sign
 * @description builds the request URL and attaches the standard binance SAPI HMAC-SHA256 signature — every prediction endpoint is signed
 * @param {string} path the endpoint path
 * @param {string|string[]} [api] the api group and access level
 * @param {string} [method] HTTP method
 * @param {object} [params] request parameters
 * @returns {object} a dictionary 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("sapi".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 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("sapi")).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());
        let mut query: Value = self.omit(params, self.extract_params(path), &[]);
        self.check_required_credentials(&[]);
        let __ws_arg_19 = self.nonce();
        let mut extendedParams: Value = self.extend(Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("timestamp".to_string(), __ws_arg_19);
            m
        }), &[query]);
        let mut defaultRecvWindow: Value = self.safe_integer_k(self.options.clone(), "recvWindow", &[]);
        if (defaultRecvWindow != Value::Null) {
            add_element_to_object(&mut extendedParams, &Value::Str("recvWindow".into()), defaultRecvWindow);
        }
        let mut querystring: Value = self.urlencode_nested(extendedParams, &[]);
        querystring = querystring.as_str().map(|__s| Value::Str(__s.replace("%5B", "[").into())).unwrap_or_else(|| querystring.clone());
        querystring = querystring.as_str().map(|__s| Value::Str(__s.replace("%5D", "]").into())).unwrap_or_else(|| querystring.clone());
        let mut signature: Value = self.hmac(self.encode(querystring.clone()), self.encode(self.secret.clone()), Value::Str("sha256".into()), &[]);
        querystring = Value::Str(format!("{}{}", Value::Str(format!("{}{}", querystring, Value::Str("&signature=".into())).into()), signature).into());
        let mut headersValue: indexmap::IndexMap<String, Value> = ({
            let mut m = indexmap::IndexMap::new();
                m.insert("X-MBX-APIKEY".to_string(), self.apiKey.clone());
            m
        });
        let mut bodyValue: Value = Value::Null;
        if (method.as_str() == Some("GET")) || (method.as_str() == Some("DELETE")) {
            url = Value::Str(format!("{}{}", Value::Str(format!("{}{}", url, Value::Str("?".into())).into()), querystring).into());
        }  else {
            bodyValue = querystring;
            headersValue.insert("Content-Type".into(), Value::Str("application/x-www-form-urlencoded".into()));
        }
        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(), Value::Map(headersValue));
    m
});

    Value::Null
}
}