ccxt-pro 4.5.78

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


pub struct GateCore {
    pub parent: crate::exchanges::gate::GateCore,
}

impl GateCore {
    pub fn new(config: Option<crate::Value>) -> Self {
        let mut s = Self { parent: crate::exchanges::gate::GateCore::new(config) };
        s.init();
        s
    }

    pub fn init(&mut self) {
        let described = GateCore::describe(self);
        self.initialize_properties(described);
        <Self as crate::exchange_generated::ExchangeBase>::after_construct(self);
    }

    /// 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 GateCore {
    fn nonce(&self, ) -> crate::Value {
        crate::exchange::DerivedExchange::nonce(&self.parent)
    }
    fn parse_ticker(&self, ticker: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_ticker(&self.parent, ticker, market)
    }
    fn parse_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_trade(&self.parent, trade, market)
    }
    fn parse_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_order(&self.parent, order, market)
    }
    fn parse_market(&self, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_market(&self.parent, market)
    }
    fn parse_ohlcv(&self, ohlcv: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_ohlcv(&self.parent, ohlcv, market)
    }
    fn parse_order_book(&self, ob: crate::Value, symbol: crate::Value, ts: crate::Value, bk: crate::Value, ak: crate::Value, pk: crate::Value, ak2: crate::Value, ck: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_order_book(&self.parent, ob, symbol, ts, bk, ak, pk, ak2, ck)
    }
    fn parse_balance(&self, response: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_balance(&self.parent, response)
    }
    fn parse_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_position(&self.parent, position, market)
    }
    fn parse_funding_rate(&self, rate: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_funding_rate(&self.parent, rate, market)
    }
    fn parse_deposit(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_deposit(&self.parent, tx, currency)
    }
    fn parse_deposit_address(&self, depositAddress: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_deposit_address(&self.parent, depositAddress, currency)
    }
    fn parse_last_price(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_last_price(&self.parent, entry, market)
    }
    fn parse_withdrawal(&self, tx: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_withdrawal(&self.parent, tx, currency)
    }
    fn parse_ledger_entry(&self, entry: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_ledger_entry(&self.parent, entry, currency)
    }
    fn parse_transfer(&self, transfer: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_transfer(&self.parent, transfer, currency)
    }
    fn parse_currency(&self, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_currency(&self.parent, currency)
    }
    fn parse_bid_ask(&self, bidask: crate::Value, price_key: crate::Value, amount_key: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_bid_ask(&self.parent, bidask, price_key, amount_key, market)
    }
    fn parse_open_interest(&self, interest: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_open_interest(&self.parent, interest, market)
    }
    fn parse_liquidation(&self, liquidation: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_liquidation(&self.parent, liquidation, market)
    }
    fn parse_funding_rate_history(&self, entry: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_funding_rate_history(&self.parent, entry, market)
    }
    fn parse_margin_modification(&self, data: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_margin_modification(&self.parent, data, market)
    }
    fn parse_account(&self, account: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_account(&self.parent, account)
    }
    fn parse_my_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_my_trade(&self.parent, trade, market)
    }
    fn parse_transaction(&self, transaction: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_transaction(&self.parent, transaction, currency)
    }
    fn parse_borrow_interest(&self, info: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_borrow_interest(&self.parent, info, market)
    }
    fn parse_adl_rank(&self, info: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_adl_rank(&self.parent, info, market)
    }
    fn parse_income(&self, info: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_income(&self.parent, info, market)
    }
    fn parse_greeks(&self, greeks: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_greeks(&self.parent, greeks, market)
    }
    fn parse_margin_mode(&self, margin_mode: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_margin_mode(&self.parent, margin_mode, market)
    }
    fn parse_conversion(&self, conversion: crate::Value, from_currency: crate::Value, to_currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_conversion(&self.parent, conversion, from_currency, to_currency)
    }
    fn parse_borrow_rate(&self, info: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_borrow_rate(&self.parent, info, currency)
    }
    fn parse_leverage(&self, leverage: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_leverage(&self.parent, leverage, market)
    }
    fn parse_market_leverage_tiers(&self, info: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_market_leverage_tiers(&self.parent, info, market)
    }
    fn parse_deposit_withdraw_fee(&self, fee: crate::Value, currency: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_deposit_withdraw_fee(&self.parent, fee, currency)
    }
    fn parse_prediction_trade(&self, trade: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_prediction_trade(&self.parent, trade, market)
    }
    fn parse_prediction_order(&self, order: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_prediction_order(&self.parent, order, market)
    }
    fn parse_prediction_position(&self, position: crate::Value, market: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::parse_prediction_position(&self.parent, position, market)
    }
    fn create_expired_option_market(&self, symbol: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::create_expired_option_market(&self.parent, symbol)
    }
    fn sign(&self, path: crate::Value, api: crate::Value, method: crate::Value, params: crate::Value, headers: crate::Value, body: crate::Value) -> crate::Value {
        crate::exchange::DerivedExchange::sign(&self.parent, 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 {
        crate::exchange::DerivedExchange::handle_errors(&self.parent, code, reason, url, method, headers, body, response, request_headers, request_body)
    }
}

impl crate::exchange_generated::ExchangeBase for GateCore {
    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 {
                "authenticate" => self.authenticate(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)).await,
                "cancel_all_orders_ws" => self.cancel_all_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "cancel_order_ws" => self.cancel_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "create_order_ws" => self.create_order_ws(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..).unwrap_or(&[]).to_vec()[..]).await,
                "create_orders_ws" => self.create_orders_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "describe_data" => self.describe_data(),
                "edit_order_ws" => self.edit_order_ws(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..).unwrap_or(&[]).to_vec()[..]).await,
                "fetch_closed_orders_ws" => self.fetch_closed_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "fetch_open_orders_ws" => self.fetch_open_orders_ws(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "fetch_order_ws" => self.fetch_order_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "fetch_orders_by_status_ws" => self.fetch_orders_by_status_ws(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "get_market_type_by_url" => self.get_market_type_by_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "get_type_by_market" => self.get_type_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "get_url_by_market" => self.get_url_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
                "get_url_by_market_type" => self.get_url_by_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
                "handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
                "handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
                "load_positions_snapshot" => self.load_positions_snapshot(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)).await,
                "parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
                "request_id" => self.request_id(),
                "request_private" => self.request_private(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..).unwrap_or(&[]).to_vec()[..]).await,
                "subscribe_private" => self.subscribe_private(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..).unwrap_or(&[]).to_vec()[..]).await,
                "subscribe_public" => self.subscribe_public(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..).unwrap_or(&[]).to_vec()[..]).await,
                "subscribe_public_multiple" => self.subscribe_public_multiple(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..).unwrap_or(&[]).to_vec()[..]).await,
                "subscribe_watch_tickers_and_bids_asks" => self.subscribe_watch_tickers_and_bids_asks(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "un_subscribe_public_multiple" => self.un_subscribe_public_multiple(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..).unwrap_or(&[]).to_vec()[..]).await,
                "un_watch_order_book" => self.un_watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "un_watch_trades" => self.un_watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "un_watch_trades_for_symbols" => self.un_watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_balance" => self.watch_balance(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_bids_asks" => self.watch_bids_asks(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_my_liquidations" => self.watch_my_liquidations(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_my_liquidations_for_symbols" => self.watch_my_liquidations_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_my_trades" => self.watch_my_trades(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_ohlcv" => self.watch_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_order_book" => self.watch_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_orders" => self.watch_orders(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_positions" => self.watch_positions(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_ticker" => self.watch_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_tickers" => self.watch_tickers(&args.get(0..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_trades" => self.watch_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                "watch_trades_for_symbols" => self.watch_trades_for_symbols(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]).await,
                // Go-style inheritance: an un-overridden method dispatches to the parent core.
                _ => crate::exchange_generated::ExchangeBase::call_dynamic(&mut self.parent, method, args).await,
            }
        })
    }
}
impl GateCore {
    /// Synchronous WS handler dispatch — routes a handler-name string (from the
    /// venue's handle_message dispatch table) to the real handler method.
    #[allow(dead_code, unreachable_patterns, clippy::all)]
    pub fn dispatch_ws_handler(&mut self, __name: &crate::Value, args: &[crate::Value]) -> crate::Value {
        let __n = match __name { crate::Value::Str(s) => s.as_str(), _ => return crate::Value::Null };
        match __n {
            "authenticate" => { crate::exchange_stubs::enqueue_spawn("authenticate", args.to_vec()); crate::Value::Null },
            "cancel_all_orders_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_all_orders_ws", args.to_vec()); crate::Value::Null },
            "cancel_order_ws" => { crate::exchange_stubs::enqueue_spawn("cancel_order_ws", args.to_vec()); crate::Value::Null },
            "create_order_ws" => { crate::exchange_stubs::enqueue_spawn("create_order_ws", args.to_vec()); crate::Value::Null },
            "create_orders_ws" => { crate::exchange_stubs::enqueue_spawn("create_orders_ws", args.to_vec()); crate::Value::Null },
            "describe_data" => self.describe_data(),
            "edit_order_ws" => { crate::exchange_stubs::enqueue_spawn("edit_order_ws", args.to_vec()); crate::Value::Null },
            "fetch_closed_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_closed_orders_ws", args.to_vec()); crate::Value::Null },
            "fetch_open_orders_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_open_orders_ws", args.to_vec()); crate::Value::Null },
            "fetch_order_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_order_ws", args.to_vec()); crate::Value::Null },
            "fetch_orders_by_status_ws" => { crate::exchange_stubs::enqueue_spawn("fetch_orders_by_status_ws", args.to_vec()); crate::Value::Null },
            "get_cache_index" => self.get_cache_index(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
            "get_market_type_by_url" => self.get_market_type_by_url(args.get(0).cloned().unwrap_or(crate::Value::Null)),
            "get_type_by_market" => self.get_type_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
            "get_url_by_market" => self.get_url_by_market(args.get(0).cloned().unwrap_or(crate::Value::Null)),
            "get_url_by_market_type" => self.get_url_by_market_type(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
            "handle_authentication_message" => { self.handle_authentication_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_balance" => { self.handle_balance(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_balance_subscription" => { self.handle_balance_subscription(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]); crate::Value::Null },
            "handle_bid_ask" => { self.handle_bid_ask(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_bid_asks" => { self.handle_bid_asks(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_delta" => { self.handle_delta(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_error_message" => self.handle_error_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)),
            "handle_liquidation" => { self.handle_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_message" => { self.handle_message(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_my_trades" => { self.handle_my_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_new_spot_order_book" => { self.handle_new_spot_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_ohlcv" => { self.handle_ohlcv(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_order" => { self.handle_order(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_order_book" => { self.handle_order_book(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_order_book_subscription" => { self.handle_order_book_subscription(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)); crate::Value::Null },
            "handle_positions" => { self.handle_positions(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_subscription_status" => { self.handle_subscription_status(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_ticker" => { self.handle_ticker(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_ticker_and_bid_ask" => { self.handle_ticker_and_bid_ask(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)); crate::Value::Null },
            "handle_trades" => { self.handle_trades(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "handle_un_subscribe" => { self.handle_un_subscribe(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null)); crate::Value::Null },
            "load_positions_snapshot" => { crate::exchange_stubs::enqueue_spawn("load_positions_snapshot", args.to_vec()); crate::Value::Null },
            "parse_ws_liquidation" => self.parse_ws_liquidation(args.get(0).cloned().unwrap_or(crate::Value::Null), &args.get(1..).unwrap_or(&[]).to_vec()[..]),
            "request_id" => self.request_id(),
            "request_private" => { crate::exchange_stubs::enqueue_spawn("request_private", args.to_vec()); crate::Value::Null },
            "set_positions_cache" => { self.set_positions_cache(args.get(0).cloned().unwrap_or(crate::Value::Null), args.get(1).cloned().unwrap_or(crate::Value::Null), &args.get(2..).unwrap_or(&[]).to_vec()[..]); crate::Value::Null },
            "subscribe_private" => { crate::exchange_stubs::enqueue_spawn("subscribe_private", args.to_vec()); crate::Value::Null },
            "subscribe_public" => { crate::exchange_stubs::enqueue_spawn("subscribe_public", args.to_vec()); crate::Value::Null },
            "subscribe_public_multiple" => { crate::exchange_stubs::enqueue_spawn("subscribe_public_multiple", args.to_vec()); crate::Value::Null },
            "subscribe_watch_tickers_and_bids_asks" => { crate::exchange_stubs::enqueue_spawn("subscribe_watch_tickers_and_bids_asks", args.to_vec()); crate::Value::Null },
            "un_subscribe_public_multiple" => { crate::exchange_stubs::enqueue_spawn("un_subscribe_public_multiple", args.to_vec()); crate::Value::Null },
            "un_watch_order_book" => { crate::exchange_stubs::enqueue_spawn("un_watch_order_book", args.to_vec()); crate::Value::Null },
            "un_watch_trades" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades", args.to_vec()); crate::Value::Null },
            "un_watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("un_watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
            "watch_balance" => { crate::exchange_stubs::enqueue_spawn("watch_balance", args.to_vec()); crate::Value::Null },
            "watch_bids_asks" => { crate::exchange_stubs::enqueue_spawn("watch_bids_asks", args.to_vec()); crate::Value::Null },
            "watch_my_liquidations" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations", args.to_vec()); crate::Value::Null },
            "watch_my_liquidations_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_my_liquidations_for_symbols", args.to_vec()); crate::Value::Null },
            "watch_my_trades" => { crate::exchange_stubs::enqueue_spawn("watch_my_trades", args.to_vec()); crate::Value::Null },
            "watch_ohlcv" => { crate::exchange_stubs::enqueue_spawn("watch_ohlcv", args.to_vec()); crate::Value::Null },
            "watch_order_book" => { crate::exchange_stubs::enqueue_spawn("watch_order_book", args.to_vec()); crate::Value::Null },
            "watch_orders" => { crate::exchange_stubs::enqueue_spawn("watch_orders", args.to_vec()); crate::Value::Null },
            "watch_positions" => { crate::exchange_stubs::enqueue_spawn("watch_positions", args.to_vec()); crate::Value::Null },
            "watch_ticker" => { crate::exchange_stubs::enqueue_spawn("watch_ticker", args.to_vec()); crate::Value::Null },
            "watch_tickers" => { crate::exchange_stubs::enqueue_spawn("watch_tickers", args.to_vec()); crate::Value::Null },
            "watch_trades" => { crate::exchange_stubs::enqueue_spawn("watch_trades", args.to_vec()); crate::Value::Null },
            "watch_trades_for_symbols" => { crate::exchange_stubs::enqueue_spawn("watch_trades_for_symbols", args.to_vec()); crate::Value::Null },
            _ => crate::Value::Null,
        }
    }
}

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

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

impl GateCore {
    pub fn describe(&self) -> Value {
        let mut superDescribe: Value = self.parent.describe();
        return self.deep_extend(superDescribe.clone(), &[self.describe_data()]);

    Value::Null
}

    pub fn describe_data(&self) -> Value {
        return Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("has".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("ws".to_string(), Value::Bool(true));
        m.insert("cancelAllOrdersWs".to_string(), Value::Bool(true));
        m.insert("cancelOrderWs".to_string(), Value::Bool(true));
        m.insert("createMarketBuyOrderWithCostWs".to_string(), Value::Bool(true));
        m.insert("createMarketOrderWs".to_string(), Value::Bool(true));
        m.insert("createMarketOrderWithCostWs".to_string(), Value::Bool(false));
        m.insert("createMarketSellOrderWithCostWs".to_string(), Value::Bool(false));
        m.insert("createOrderWs".to_string(), Value::Bool(true));
        m.insert("createOrdersWs".to_string(), Value::Bool(true));
        m.insert("createPostOnlyOrderWs".to_string(), Value::Bool(true));
        m.insert("createReduceOnlyOrderWs".to_string(), Value::Bool(true));
        m.insert("createStopLimitOrderWs".to_string(), Value::Bool(true));
        m.insert("createStopLossOrderWs".to_string(), Value::Bool(true));
        m.insert("createStopMarketOrderWs".to_string(), Value::Bool(false));
        m.insert("createStopOrderWs".to_string(), Value::Bool(true));
        m.insert("createTakeProfitOrderWs".to_string(), Value::Bool(true));
        m.insert("createTriggerOrderWs".to_string(), Value::Bool(true));
        m.insert("editOrderWs".to_string(), Value::Bool(true));
        m.insert("fetchOrderWs".to_string(), Value::Bool(true));
        m.insert("fetchOrdersWs".to_string(), Value::Bool(false));
        m.insert("fetchOpenOrdersWs".to_string(), Value::Bool(true));
        m.insert("fetchClosedOrdersWs".to_string(), Value::Bool(true));
        m.insert("watchOrderBook".to_string(), Value::Bool(true));
        m.insert("watchBidsAsks".to_string(), Value::Bool(true));
        m.insert("watchTicker".to_string(), Value::Bool(true));
        m.insert("watchTickers".to_string(), Value::Bool(true));
        m.insert("watchTrades".to_string(), Value::Bool(true));
        m.insert("watchTradesForSymbols".to_string(), Value::Bool(true));
        m.insert("watchMyTrades".to_string(), Value::Bool(true));
        m.insert("watchOHLCV".to_string(), Value::Bool(true));
        m.insert("watchBalance".to_string(), Value::Bool(true));
        m.insert("watchOrders".to_string(), Value::Bool(true));
        m.insert("watchLiquidations".to_string(), Value::Bool(false));
        m.insert("watchLiquidationsForSymbols".to_string(), Value::Bool(false));
        m.insert("watchMyLiquidations".to_string(), Value::Bool(true));
        m.insert("watchMyLiquidationsForSymbols".to_string(), Value::Bool(true));
        m.insert("watchPositions".to_string(), Value::Bool(true));
        m.insert("unWatchTicker".to_string(), Value::Bool(false));
        m.insert("unWatchTickers".to_string(), Value::Bool(false));
        m.insert("unWatchOHLCV".to_string(), Value::Bool(false));
        m.insert("unWatchOHLCVForSymbols".to_string(), Value::Bool(false));
        m.insert("unWatchOrderBook".to_string(), Value::Bool(true));
        m.insert("unWatchOrderBookForSymbols".to_string(), Value::Bool(false));
        m.insert("unWatchTrades".to_string(), Value::Bool(true));
        m.insert("unWatchTradesForSymbols".to_string(), Value::Bool(true));
        m.insert("unWatchMyTrades".to_string(), Value::Bool(false));
        m.insert("unWatchOrders".to_string(), Value::Bool(false));
        m.insert("unWatchPositions".to_string(), Value::Bool(false));
        m.insert("unWatchMarkPrices".to_string(), Value::Bool(false));
        m.insert("unWatchMarkPrice".to_string(), Value::Bool(false));
    m
}));
        m.insert("urls".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("api".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("ws".to_string(), Value::Str("wss://ws.gate.io/v4".to_string()));
        m.insert("spot".to_string(), Value::Str("wss://api.gateio.ws/ws/v4/".to_string()));
        m.insert("swap".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/btc".to_string()));
    m
}));
        m.insert("future".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/delivery/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://fx-ws.gateio.ws/v4/ws/delivery/btc".to_string()));
    m
}));
        m.insert("option".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://op-ws.gateio.live/v4/ws/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://op-ws.gateio.live/v4/ws/btc".to_string()));
    m
}));
    m
}));
        m.insert("test".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("swap".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/futures/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/btc".to_string()));
    m
}));
        m.insert("future".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/btc".to_string()));
    m
}));
        m.insert("option".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("usdt".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/options/usdt".to_string()));
        m.insert("btc".to_string(), Value::Str("wss://ws-testnet.gate.com/v4/ws/options/btc".to_string()));
    m
}));
    m
}));
    m
}));
        m.insert("options".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("tradesLimit".to_string(), Value::Int(1000));
        m.insert("OHLCVLimit".to_string(), Value::Int(1000));
        m.insert("watchTradesSubscriptions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        m.insert("watchTickerSubscriptions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        m.insert("watchOrderBookSubscriptions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        m.insert("watchTicker".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("name".to_string(), Value::Str("tickers".to_string()));
    m
}));
        m.insert("watchOrderBook".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("snapshotDelay".to_string(), Value::Int(10));
        m.insert("snapshotMaxRetries".to_string(), Value::Int(3));
        m.insert("checksum".to_string(), Value::Bool(true));
    m
}));
        m.insert("watchBalance".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("settle".to_string(), Value::Str("usdt".to_string()));
        m.insert("spot".to_string(), Value::Str("spot.balances".to_string()));
    m
}));
        m.insert("watchPositions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("fetchPositionsSnapshot".to_string(), Value::Bool(true));
        m.insert("awaitPositionsSnapshot".to_string(), Value::Bool(true));
    m
}));
    m
}));
        m.insert("exceptions".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("ws".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("1".to_string(), Value::Str("BadRequest".to_string()).clone());
        m.insert("2".to_string(), Value::Str("BadRequest".to_string()).clone());
        m.insert("4".to_string(), Value::Str("AuthenticationError".to_string()).clone());
        m.insert("6".to_string(), Value::Str("AuthenticationError".to_string()).clone());
        m.insert("11".to_string(), Value::Str("AuthenticationError".to_string()).clone());
    m
}));
        m.insert("broad".to_string(), Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
    m
}));
    m
}));
    m
});

    Value::Null
}

/*
 * @method
 * @name gate#createOrderWs
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-place
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-place
 * @description Create an order on the exchange
 * @param {string} symbol Unified CCXT market symbol
 * @param {string} type 'limit' or 'market' *"market" is contract only*
 * @param {string} side 'buy' or 'sell'
 * @param {float} amount the amount of currency to trade
 * @param {float} [price] *ignored in "market" orders* the price at which the order is to be fulfilled at in units of the quote currency
 * @param {object} [params]  extra parameters specific to the exchange API endpoint
 * @param {float} [params.stopPrice] The price at which a trigger order is triggered at
 * @param {string} [params.timeInForce] "GTC", "IOC", or "PO"
 * @param {float} [params.stopLossPrice] The price at which a stop loss order is triggered at
 * @param {float} [params.takeProfitPrice] The price at which a take profit order is triggered at
 * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used
 * @param {int} [params.iceberg] Amount to display for the iceberg order, Null or 0 for normal orders, Set to -1 to hide the order completely
 * @param {string} [params.text] User defined information
 * @param {string} [params.account] *spot and margin only* "spot", "margin" or "cross_margin"
 * @param {bool} [params.auto_borrow] *margin only* Used in margin or cross margin trading to allow automatic loan of insufficient amount if balance is not enough
 * @param {string} [params.settle] *contract only* Unified Currency Code for settle currency
 * @param {bool} [params.reduceOnly] *contract only* Indicates if this order is to reduce the size of a position
 * @param {bool} [params.close] *contract only* Set as true to close the position, with size set to 0
 * @param {bool} [params.auto_size] *contract only* Set side to close dual-mode position, close_long closes the long side, while close_short the short one, size also needs to be set to 0
 * @param {int} [params.price_type] *contract only* 0 latest deal price, 1 mark price, 2 index price
 * @param {float} [params.cost] *spot market buy only* the quote quantity that can be used as an alternative for the amount
 * @returns {object|undefined} [An order structure]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn create_order_ws(&mut self, mut symbol: 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = self.market(symbol.clone());
        symbol = get_value(&market, &Value::Str("symbol".to_string()));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_place".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        add_element_to_object(&mut params, &Value::Str("textIsRequired".to_string()), Value::Bool(true));
        let mut request: Value = self.parent.create_order_request(symbol.clone(), type_var.clone(), side.clone(), amount.clone(), &[price.clone(), params.clone()]);
        self.authenticate(url.clone(), messageType.clone()).await;
        let mut rawOrder: Value = self.request_private(url.clone(), request.clone(), channel.clone(), &[]).await;
        let mut order: Value = self.parse_order(rawOrder.clone(), &[market.clone()]);
        return order;

    Value::Null
}

/*
 * @method
 * @name gate#createOrdersWs
 * @description create a list of trade orders
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-batch-place
 * @param {Array} orders list of orders to create, each object should contain the parameters required by createOrder, namely symbol, type, side, amount, price and params
 * @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_orders_ws(&mut self, mut orders: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut request: Value = self.parent.create_orders_request(orders.clone(), &[params.clone()]);
        let mut firstOrder: Value = get_value(&orders, &Value::Int(0));
        let mut market: Value = self.market(get_value(&firstOrder, &Value::Str("symbol".to_string())));
        if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
            panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" createOrdersWs is not supported for swap markets".to_string()))));
        }
        // todo add swap support
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_batch_place".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        self.authenticate(url.clone(), messageType.clone()).await;
        let mut rawOrders: Value = self.request_private(url.clone(), request.clone(), channel.clone(), &[]).await;
        return self.parse_orders(rawOrders.clone(), &[market.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#cancelAllOrdersWs
 * @description cancel all open orders
 * @see https://www.gate.com/docs/developers/futures/ws/en/#cancel-matched-open-orders
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel-all-with-specified-currency-pair
 * @param {string} symbol unified market symbol, only orders in the market of this symbol are cancelled when symbol is not undefined
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.channel] the channel to use, defaults to spot.order_cancel_cp or futures.order_cancel_cp
 * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn cancel_all_orders_ws(&mut self, optional_args: &[Value]) -> Value {
        let mut symbol = 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 is_equal(&symbol, &Value::Null) {
            panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" cancelAllOrdersWs() requires a symbol argument".to_string()))));
        }
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = ternary(is_true(&(is_equal(&symbol, &Value::Null))), Value::Null, self.market(symbol.clone()));
        let mut trigger: Value = self.safe_bool2(params.clone(), Value::Str("stop".to_string()), Value::Str("trigger".to_string()), &[]);
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_cancel_cp".to_string()));
        { let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("cancelAllOrdersWs".to_string()), Value::Str("channel".to_string()), &[channel.clone()]); channel = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut url: Value = self.get_url_by_market(market.clone());
        params = self.omit(params.clone(), Value::List(vec![Value::Str("stop".to_string()), Value::Str("trigger".to_string())]), &[]);
        let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("cancelAllOrders".to_string()), &[market.clone(), params.clone()]);
        let mut type_var: Value = get_value(&type_varqueryVariable, &Value::Int(0));
        let mut query: Value = get_value(&type_varqueryVariable, &Value::Int(1));
        let mut requestrequestParamsVariable = ternary(is_true(&(is_equal(&type_var, &Value::Str("spot".to_string())))), self.parent.multi_order_spot_prepare_request(&[market.clone(), trigger.clone(), query.clone()]), self.parent.prepare_request(&[market.clone(), type_var.clone(), query.clone()]));
        let mut request: Value = get_value(&requestrequestParamsVariable, &Value::Int(0));
        let mut requestParams: Value = get_value(&requestrequestParamsVariable, &Value::Int(1));
        self.authenticate(url.clone(), messageType.clone()).await;
        let __ws_arg_0 = self.extend(request.clone(), &[requestParams.clone()]);
        let mut rawOrders: Value = self.request_private(url.clone(), __ws_arg_0, channel.clone(), &[]).await;
        return self.parse_orders(rawOrders.clone(), &[market.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#cancelOrderWs
 * @description Cancels an open order
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-cancel
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-cancel
 * @param {string} id Order id
 * @param {string} symbol Unified market symbol
 * @param {object} [params] Parameters specified by the exchange api
 * @param {bool} [params.trigger] True if the order to be cancelled is a trigger order
 * @returns An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn cancel_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut symbol = 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 is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = ternary(is_true(&(is_equal(&symbol, &Value::Null))), Value::Null, self.market(symbol.clone()));
        let mut trigger: Value = self.safe_value_n(params.clone(), Value::List(vec![Value::Str("is_stop_order".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string())]), &[Value::Bool(false)]);
        params = self.omit(params.clone(), Value::List(vec![Value::Str("is_stop_order".to_string()), Value::Str("stop".to_string()), Value::Str("trigger".to_string())]), &[]);
        let mut type_varqueryVariable = self.handle_market_type_and_params(Value::Str("cancelOrder".to_string()), &[market.clone(), params.clone()]);
        let mut type_var: Value = get_value(&type_varqueryVariable, &Value::Int(0));
        let mut query: Value = get_value(&type_varqueryVariable, &Value::Int(1));
        let mut requestrequestParamsVariable = ternary(is_true(&(is_equal(&type_var, &Value::Str("spot".to_string())) || is_equal(&type_var, &Value::Str("margin".to_string())))), self.parent.spot_order_prepare_request(&[market.clone(), trigger.clone(), query.clone()]), self.parent.prepare_request(&[market.clone(), type_var.clone(), query.clone()]));
        let mut request: Value = get_value(&requestrequestParamsVariable, &Value::Int(0));
        let mut requestParams: Value = get_value(&requestrequestParamsVariable, &Value::Int(1));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_cancel".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        self.authenticate(url.clone(), messageType.clone()).await;
        add_element_to_object(&mut request, &Value::Str("order_id".to_string()), to_string_val(&id));
        let __ws_arg_1 = self.extend(request.clone(), &[requestParams.clone()]);
        let mut res: Value = self.request_private(url.clone(), __ws_arg_1, channel.clone(), &[]).await;
        return self.parse_order(res.clone(), &[market.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#editOrderWs
 * @description edit a trade order, gate currently only supports the modification of the price or amount fields
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-amend
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-amend
 * @param {string} id order id
 * @param {string} symbol unified symbol of the market to create an order in
 * @param {string} type 'market' or 'limit'
 * @param {string} side 'buy' or 'sell'
 * @param {float} amount how much of the currency you want to trade in units of the base currency
 * @param {float} [price] the price at which the order is to be fulfilled, in units of the quote currency, ignored in market orders
 * @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 edit_order_ws(&mut self, mut id: Value, mut symbol: Value, mut type_var: Value, mut side: Value, optional_args: &[Value]) -> Value {
        let mut amount = get_arg(optional_args, 0, Value::Null);
        let mut price = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = self.market(symbol.clone());
        let mut extendedRequest: Value = self.parent.edit_order_request(id.clone(), symbol.clone(), type_var.clone(), side.clone(), &[amount.clone(), price.clone(), params.clone()]);
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_amend".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        self.authenticate(url.clone(), messageType.clone()).await;
        let mut rawOrder: Value = self.request_private(url.clone(), extendedRequest.clone(), channel.clone(), &[]).await;
        return self.parse_order(rawOrder.clone(), &[market.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#fetchOrderWs
 * @description Retrieves information on an order
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-status
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-status
 * @param {string} id Order id
 * @param {string} symbol Unified market symbol, *required for spot and margin*
 * @param {object} [params] Parameters specified by the exchange api
 * @param {bool} [params.trigger] True if the order being fetched is a trigger order
 * @param {string} [params.marginMode] 'cross' or 'isolated' - marginMode for margin trading if not provided this.options['defaultMarginMode'] is used
 * @param {string} [params.type] 'spot', 'swap', or 'future', if not provided this.options['defaultMarginMode'] is used
 * @param {string} [params.settle] 'btc' or 'usdt' - settle currency for perpetual swap and future - market settle currency is used if symbol !== undefined, default="usdt" for swap and "btc" for future
 * @returns An [order structure]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn fetch_order_ws(&mut self, mut id: Value, optional_args: &[Value]) -> Value {
        let mut symbol = 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 is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = ternary(is_true(&(is_equal(&symbol, &Value::Null))), Value::Null, self.market(symbol.clone()));
        let mut requestrequestParamsVariable = self.parent.fetch_order_request(id.clone(), &[symbol.clone(), params.clone()]);
        let mut request: Value = get_value(&requestrequestParamsVariable, &Value::Int(0));
        let mut requestParams: Value = get_value(&requestrequestParamsVariable, &Value::Int(1));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_status".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        self.authenticate(url.clone(), messageType.clone()).await;
        let __ws_arg_2 = self.extend(request.clone(), &[requestParams.clone()]);
        let mut rawOrder: Value = self.request_private(url.clone(), __ws_arg_2, channel.clone(), &[]).await;
        return self.parse_order(rawOrder.clone(), &[market.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#fetchOpenOrdersWs
 * @description fetch all unfilled currently open orders
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
 * @param {string} symbol unified market symbol
 * @param {int} [since] the earliest time in ms to fetch open orders for
 * @param {int} [limit] the maximum number of  open orders structures to retrieve
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn fetch_open_orders_ws(&mut self, optional_args: &[Value]) -> Value {
        let mut symbol = 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
}));
        return self.fetch_orders_by_status_ws(Value::Str("open".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;

    Value::Null
}

/*
 * @method
 * @name gate#fetchClosedOrdersWs
 * @description fetches information on multiple closed orders made by the user
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
 * @param {string} symbol unified market symbol of the market orders were made in
 * @param {int} [since] the earliest time in ms to fetch orders for
 * @param {int} [limit] the maximum number of order structures to retrieve
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {Order[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn fetch_closed_orders_ws(&mut self, optional_args: &[Value]) -> Value {
        let mut symbol = 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
}));
        return self.fetch_orders_by_status_ws(Value::Str("finished".to_string()), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]).await;

    Value::Null
}

/*
 * @method
 * @name gate#fetchOrdersWs
 * @see https://www.gate.io/docs/developers/futures/ws/en/#order-list
 * @description fetches information on multiple orders made by the user by status
 * @param {string} status requested order status
 * @param {string} symbol unified market symbol of the market orders were made in
 * @param {int|undefined} [since] the earliest time in ms to fetch orders for
 * @param {int|undefined} [limit] the maximum number of order structures to retrieve
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {int} [params.orderId] order id to begin at
 * @param {int} [params.limit] the maximum number of order structures to retrieve
 * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn fetch_orders_by_status_ws(&mut self, mut status: Value, optional_args: &[Value]) -> Value {
        let mut symbol = 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = Value::Null;
        if !is_equal(&symbol, &Value::Null) {
            market = self.market(symbol.clone());
            symbol = get_value(&market, &Value::Str("symbol".to_string()));
            if !is_equal(&get_value(&market, &Value::Str("swap".to_string())), &Value::Bool(true)) {
                panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" fetchOrdersByStatusWs is only supported by swap markets. Use rest API for other markets".to_string()))));
            }
        }
        let mut requestrequestParamsVariable = self.parent.prepare_orders_by_status_request(status.clone(), &[symbol.clone(), since.clone(), limit.clone(), params.clone()]);
        let mut request: Value = get_value(&requestrequestParamsVariable, &Value::Int(0));
        let mut requestParams: Value = get_value(&requestrequestParamsVariable, &Value::Int(1));
        let mut newRequest: Value = self.omit(request.clone(), Value::List(vec![Value::Str("settle".to_string())]), &[]);
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".order_list".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        self.authenticate(url.clone(), messageType.clone()).await;
        let __ws_arg_3 = self.extend(newRequest.clone(), &[requestParams.clone()]);
        let mut rawOrders: Value = self.request_private(url.clone(), __ws_arg_3, channel.clone(), &[]).await;
        let mut orders: Value = self.parse_orders(rawOrders.clone(), &[market.clone()]);
        return self.filter_by_symbol_since_limit(orders.clone(), &[symbol.clone(), since.clone(), limit.clone()]);

    Value::Null
}

/*
 * @method
 * @name gate#watchOrderBook
 * @description watches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-channel
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#order-book-v2-api
 * @see https://www.gate.com/docs/developers/futures/ws/en/#order-book-api
 * @see https://www.gate.com/docs/developers/futures/ws/en/#order-book-v2-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#order-book-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#order-book-channel
 * @param {string} symbol unified symbol of the market to fetch the order book for
 * @param {int} [limit] the maximum amount of order book entries to return
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} an [order book structure]{@link https://docs.ccxt.com/?id=order-book-structure}
 */
    pub async fn watch_order_book(&mut self, mut symbol: 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = self.market(symbol.clone());
        symbol = get_value(&market, &Value::Str("symbol".to_string()));
        let mut marketId: Value = get_value(&market, &Value::Str("id".to_string()));
        let mut url: Value = self.get_url_by_market(market.clone());
        let mut isEuUrl: bool = is_greater_than_or_equal(&get_index_of(&url, &Value::Str("gateeu".to_string())), &Value::Int(0));
        let mut isNonEuSpot: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))) && !is_true(&isEuUrl);
        let mut intervalDefault: Value = ternary(is_true(&isNonEuSpot), Value::Str("50".to_string()), Value::Str("100ms".to_string()));
        let mut intervalqueryVariable = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".to_string()), Value::Str("interval".to_string()), &[intervalDefault.clone()]);
        let mut interval: Value = get_value(&intervalqueryVariable, &Value::Int(0));
        let mut query: Value = get_value(&intervalqueryVariable, &Value::Int(1));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut messageHash: Value = add(&add(&Value::Str("orderbook".to_string()), &Value::Str(":".to_string())), &symbol);
        if is_equal(&limit, &Value::Null) {
            limit = ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))), Value::Int(50), Value::Int(100)); // max 100 atm
            if is_equal(&messageType, &Value::Str("options".to_string())) {
                limit = Value::Int(50); // max 50 for options
            }
        }
        let mut payload: Value = Value::List(vec![]);
        let mut channel: Value = Value::Str("".to_string());
        if is_true(&isEuUrl) {
            channel = Value::Str("spot.order_book_update".to_string());
            payload = Value::List(vec![marketId.clone(), interval.clone()]);
        }  else if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
            channel = Value::Str("spot.obu".to_string());
            let mut finalInterval: Value = interval.clone();
            if is_equal(&limit, &Value::Int(400)) {
                finalInterval = Value::Str("400".to_string());
            }
            payload = Value::List(vec![add(&add(&add(&Value::Str("ob.".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(".".to_string())), &finalInterval)]);
        }  else {
            channel = add(&messageType, &Value::Str(".order_book_update".to_string()));
            payload = Value::List(vec![marketId.clone(), interval.clone()]);
            let mut stringLimit: Value = to_string_val(&limit);
            append_to_array(&mut payload, stringLimit.clone());
        }
        let mut subscription: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("symbol".to_string(), symbol.clone());
                m.insert("limit".to_string(), limit.clone());
            m
        });
        let mut orderbook: Value = self.subscribe_public(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), &[query.clone(), subscription.clone()]).await;
        return orderbook.limit();

    Value::Null
}

/*
 * @method
 * @name gate#unWatchOrderBook
 * @description unWatches information on open orders with bid (buy) and ask (sell) prices, volumes and other data
 * @param {string} symbol unified symbol of the market to fetch the order book for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} A dictionary of [order book structures]{@link https://docs.ccxt.com/?id=order-book-structure}
 */
    pub async fn un_watch_order_book(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = self.market(symbol.clone());
        let mut url: Value = self.get_url_by_market(market.clone());
        symbol = get_value(&market, &Value::Str("symbol".to_string()));
        let mut marketId: Value = get_value(&market, &Value::Str("id".to_string()));
        let mut isEuUrl: bool = is_greater_than_or_equal(&get_index_of(&url, &Value::Str("gateeu".to_string())), &Value::Int(0));
        let mut isNonEuSpot: bool = is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))) && !is_true(&isEuUrl);
        let mut intervalDefault: Value = ternary(is_true(&isNonEuSpot), Value::Str("50".to_string()), Value::Str("100ms".to_string()));
        let mut interval: Value = intervalDefault.clone();
        { let __destr_tmp = self.handle_option_and_params(params.clone(), Value::Str("watchOrderBook".to_string()), Value::Str("interval".to_string()), &[interval.clone()]); interval = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut limit: Value = self.safe_integer_k(params.clone(), "limit", &[]);
        if is_equal(&limit, &Value::Null) {
            limit = ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)))), Value::Int(50), Value::Int(100)); // max 100 atm
            if is_equal(&messageType, &Value::Str("options".to_string())) {
                limit = Value::Int(50); // max 50 for options
            }
        }
        let mut payload: Value = Value::List(vec![]);
        let mut channel: Value = Value::Str("".to_string());
        if is_true(&isEuUrl) {
            channel = Value::Str("spot.order_book_update".to_string());
            payload = Value::List(vec![marketId.clone(), interval.clone()]);
        }  else if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
            channel = Value::Str("spot.obu".to_string());
            let mut finalInterval: Value = interval.clone();
            if is_equal(&limit, &Value::Int(400)) {
                finalInterval = Value::Str("400".to_string());
            }
            payload = Value::List(vec![add(&add(&add(&Value::Str("ob.".to_string()), &get_value(&market, &Value::Str("id".to_string()))), &Value::Str(".".to_string())), &finalInterval)]);
        }  else {
            channel = add(&messageType, &Value::Str(".order_book_update".to_string()));
            payload = Value::List(vec![marketId.clone(), interval.clone()]);
            let mut stringLimit: Value = to_string_val(&limit);
            append_to_array(&mut payload, stringLimit.clone());
        }
        let mut subMessageHash: Value = add(&add(&Value::Str("orderbook".to_string()), &Value::Str(":".to_string())), &symbol);
        let mut messageHash: Value = add(&add(&Value::Str("unsubscribe:orderbook".to_string()), &Value::Str(":".to_string())), &symbol);
        return self.un_subscribe_public_multiple(url.clone(), Value::Str("orderbook".to_string()), Value::List(vec![symbol.clone()]), Value::List(vec![messageHash.clone()]), Value::List(vec![subMessageHash.clone()]), payload.clone(), channel.clone(), &[params.clone()]).await;

    Value::Null
}

    pub fn handle_order_book_subscription(&mut self, mut client: Value, mut message: Value, mut subscription: Value) {
        let mut symbol: Value = self.safe_string_k(subscription.clone(), "symbol", &[]);
        let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
        if !is_equal(&symbol, &Value::Null) {
            { let __be_tmp = self.order_book(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}), limit.clone()]); add_element_to_object(&mut self.orderbooks, &symbol, __be_tmp); };
        }
}

    pub fn handle_new_spot_order_book(&mut self, mut client: Value, mut message: Value) {
        //
        //   {
        //      "channel":"spot.obu",
        //      "result":{
        //         "t":1777275365213,
        //         "full":true,
        //         "s":"ob.XRP_USDT.50",
        //         "u":9649549324,
        //         "b":[
        //            [
        //               "1.414",
        //               "1397.899"
        //            ]
        //         ],
        //         "a":[
        //            [
        //               "1.415",
        //               "17344.926"
        //            ]
        //         ]
        //      },
        //      "time_ms":1777275365214,
        //      "event":"update"
        //   }
        let mut result: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        })]);
        let mut full: Value = self.safe_bool_k(result.clone(), "full", &[Value::Bool(false)]);
        let mut marketIdWithPrefix: Value = self.safe_string_k(result.clone(), "s", &[]);
        if is_equal(&marketIdWithPrefix, &Value::Null) {
            return;
        }
        let mut marketIdParts: Value = split(&marketIdWithPrefix, &Value::Str(".".to_string()));
        let mut marketId: Value = self.safe_string(marketIdParts.clone(), Value::Int(1), &[]);
        let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Str("_".to_string()), Value::Str("spot".to_string())]);
        let mut messageHash: Value = add(&Value::Str("orderbook:".to_string()), &symbol);
        if is_equal(&self.safe_value(self.orderbooks.clone(), symbol.clone(), &[]), &Value::Null) {
            { let __be_tmp = self.order_book(&[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}), Value::Int(1000)]); add_element_to_object(&mut self.orderbooks, &symbol, __be_tmp); };
        }
        let mut orderbook: Value = get_value(&self.orderbooks, &symbol);
        if is_equal(&full, &Value::Bool(true)) {
            let mut snapshopt: Value = self.parse_order_book(result.clone(), symbol.clone(), &[Value::Null, Value::Str("b".to_string()), Value::Str("a".to_string())]);
            add_element_to_object(&mut snapshopt, &Value::Str("nonce".to_string()), self.safe_integer_k(result.clone(), "u", &[]));
            add_element_to_object(&mut snapshopt, &Value::Str("timestamp".to_string()), self.safe_integer_k(result.clone(), "t", &[]));
            orderbook.reset(snapshopt.clone());
        }  else {
            let mut nonce: Value = self.safe_integer_k(orderbook.clone(), "nonce", &[]);
            let mut deltaStart: Value = self.safe_integer_k(result.clone(), "u", &[]);
            if is_true(&(is_equal(&nonce, &Value::Null))) || is_true(&(is_true(&(!is_equal(&deltaStart, &Value::Null))) && is_true(&(is_greater_than_or_equal(&nonce, &deltaStart))))) {
                return;
            }
            self.handle_delta(orderbook.clone(), result.clone());
        }
        client.resolve(&[orderbook.clone(), messageHash.clone()]);
}

    pub fn handle_order_book(&mut self, mut client: Value, mut message: Value) {
        //
        // spot
        //
        //     {
        //         "time": 1650189272,
        //         "channel": "spot.order_book_update",
        //         "event": "update",
        //         "result": {
        //             "t": 1650189272515,
        //             "e": "depthUpdate",
        //             "E": 1650189272,
        //             "s": "GMT_USDT",
        //             "U": 140595902,
        //             "u": 140595902,
        //             "b": [
        //                 [ '2.51518', "228.119" ],
        //                 [ '2.50587', "1510.11" ],
        //                 [ '2.49944', "67.6" ],
        //             ],
        //             "a": [
        //                 [ '2.5182', "4.199" ],
        //                 [ "2.51926", "1874" ],
        //                 [ '2.53528', "96.529" ],
        //             ]
        //         }
        //     }
        //
        // swap
        //
        //     {
        //         "id": null,
        //         "time": 1650188898,
        //         "channel": "futures.order_book_update",
        //         "event": "update",
        //         "error": null,
        //         "result": {
        //             "t": 1650188898938,
        //             "s": "GMT_USDT",
        //             "U": 1577718307,
        //             "u": 1577719254,
        //             "b": [
        //                 { p: "2.5178", s: 0 },
        //                 { p: "2.5179", s: 0 },
        //                 { p: "2.518", s: 0 },
        //             ],
        //             "a": [
        //                 { p: "2.52", s: 0 },
        //                 { p: "2.5201", s: 0 },
        //                 { p: "2.5203", s: 0 },
        //             ]
        //         }
        //     }
        //
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
        if is_equal(&channel, &Value::Str("spot.obu".to_string())) {
            self.handle_new_spot_order_book(client.clone(), message.clone());
            return;
        }
        let mut channelParts: Value = split(&channel, &Value::Str(".".to_string()));
        let mut rawMarketType: Value = self.safe_string(channelParts.clone(), Value::Int(0), &[]);
        let mut isSpot: bool = is_equal(&rawMarketType, &Value::Str("spot".to_string()));
        let mut marketType: Value = ternary(is_true(&isSpot), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
        let mut delta: Value = self.safe_value_k(message.clone(), "result", &[]);
        let mut deltaStart: Value = self.safe_integer_k(delta.clone(), "U", &[]);
        let mut deltaEnd: Value = self.safe_integer_k(delta.clone(), "u", &[]);
        let mut marketId: Value = self.safe_string_k(delta.clone(), "s", &[]);
        let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Str("_".to_string()), marketType.clone()]);
        let mut messageHash: Value = add(&Value::Str("orderbook:".to_string()), &symbol);
        let mut storedOrderBook: Value = self.safe_value(self.orderbooks.clone(), symbol.clone(), &[self.order_book(&[Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        })])]);
        let mut nonce: Value = self.safe_integer_k(storedOrderBook.clone(), "nonce", &[]);
        if is_equal(&nonce, &Value::Null) {
            let mut cacheLength: Value = Value::Int(0);
            if !is_equal(&storedOrderBook, &Value::Null) {
                cacheLength = get_array_length(&get_value(&storedOrderBook, &Value::Str("cache".to_string())));
            }
            let mut snapshotDelay: Value = self.handle_option(Value::Str("watchOrderBook".to_string()), Value::Str("snapshotDelay".to_string()), &[Value::Int(10)]);
            let mut waitAmount: Value = ternary(is_true(&isSpot), snapshotDelay.clone(), Value::Int(0));
            if is_equal(&cacheLength, &waitAmount) {
                // max limit is 100
                let mut subscription: Value = get_value(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash);
                let mut limit: Value = self.safe_integer_k(subscription.clone(), "limit", &[]);
                self.spawn(&[Value::Str("load_order_book".to_string()).clone(), client.clone(), messageHash.clone(), symbol.clone(), limit.clone(), Value::Map({
                    let mut m = indexmap::IndexMap::new();
                    m
                })]); // needed for c#, number of args needs to match
            }
            crate::runtime::append_to_object_array(&mut storedOrderBook, &Value::Str("cache".to_string()), delta.clone());
            return;
        }  else if is_true(&(!is_equal(&deltaEnd, &Value::Null))) && is_true(&(is_greater_than_or_equal(&nonce, &deltaEnd))) {
            return;
        }  else if is_true(&(!is_equal(&deltaStart, &Value::Null))) && is_true(&(is_greater_than_or_equal(&nonce, &subtract(&deltaStart, &Value::Int(1))))) {
            self.handle_delta(storedOrderBook.clone(), delta.clone());
        }  else {
            remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash);
            remove(&mut self.orderbooks, &symbol);
            let mut checksum: Value = self.handle_option(Value::Str("watchOrderBook".to_string()), Value::Str("checksum".to_string()), &[Value::Bool(true)]);
            if is_equal(&checksum, &Value::Bool(true)) {
                let mut error = Value::from(crate::exchange_errors::checksum_error(add(&add(&self.id, &Value::Str(" ".to_string())), &self.orderbook_checksum_message(symbol.clone()))));
                client.reject(&[Value::from(error.clone()), messageHash.clone()]);
            }
        }
        client.resolve(&[storedOrderBook.clone(), messageHash.clone()]);
}

    pub fn get_cache_index(&self, mut orderBook: Value, mut cache: Value) -> Value {
        let mut nonce: Value = self.safe_integer_k(orderBook.clone(), "nonce", &[]);
        let mut firstDelta: Value = get_value(&cache, &Value::Int(0));
        let mut firstDeltaStart: Value = self.safe_integer_k(firstDelta.clone(), "U", &[]);
        if is_true(&(!is_equal(&nonce, &Value::Null))) && is_true(&(!is_equal(&firstDeltaStart, &Value::Null))) && is_true(&(is_less_than(&nonce, &firstDeltaStart))) {
            return negate(&Value::Int(1));
        }
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_332: bool = true;
            while { if !__for_first_332 { i = add(&i, &Value::Int(1)); } __for_first_332 = false; is_less_than(&i, &get_array_length(&cache)) } {
            let mut delta: Value = get_value(&cache, &i);
            let mut delta: Value = get_value(&cache, &i);
            let mut deltaStart: Value = self.safe_integer_k(delta.clone(), "U", &[]);
            let mut deltaEnd: Value = self.safe_integer_k(delta.clone(), "u", &[]);
            if is_true(&(!is_equal(&nonce, &Value::Null))) && is_true(&(!is_equal(&deltaStart, &Value::Null))) && is_true(&(!is_equal(&deltaEnd, &Value::Null))) && is_true(&(is_greater_than_or_equal(&nonce, &subtract(&deltaStart, &Value::Int(1))))) && is_true(&(is_less_than(&nonce, &deltaEnd))) {
                return i;
            }
        }
        }
        return get_array_length(&cache);

    Value::Null
}

    pub fn handle_bid_asks(&self, mut bookSide: Value, mut bidAsks: Value) {
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_333: bool = true;
            while { if !__for_first_333 { i = add(&i, &Value::Int(1)); } __for_first_333 = false; is_less_than(&i, &get_array_length(&bidAsks)) } {
            let mut bidAsk: Value = get_value(&bidAsks, &i);
            let mut bidAsk: Value = get_value(&bidAsks, &i);
            if is_true(&Value::Bool(is_array(&bidAsk))) {
                bookSide.store_array(self.parse_order_book_bid_ask(bidAsk.clone(), &[]));
            }  else {
                let mut price: Value = self.safe_float_k(bidAsk.clone(), "p", &[]);
                let mut amount: Value = self.safe_float_k(bidAsk.clone(), "s", &[]);
                bookSide.store(price.clone(), amount.clone());
            }
        }
        }
}

    pub fn handle_delta(&self, mut orderbook: Value, mut delta: Value) {
        let mut timestamp: Value = self.safe_integer_k(delta.clone(), "t", &[]);
        add_element_to_object(&mut orderbook, &Value::Str("timestamp".to_string()), timestamp.clone());
        add_element_to_object(&mut orderbook, &Value::Str("datetime".to_string()), self.iso8601(timestamp.clone()));
        add_element_to_object(&mut orderbook, &Value::Str("nonce".to_string()), self.safe_integer_k(delta.clone(), "u", &[]));
        let mut bids: Value = self.safe_value_k(delta.clone(), "b", &[Value::List(vec![])]);
        let mut asks: Value = self.safe_value_k(delta.clone(), "a", &[Value::List(vec![])]);
        let mut storedBids: Value = get_value(&orderbook, &Value::Str("bids".to_string()));
        let mut storedAsks: Value = get_value(&orderbook, &Value::Str("asks".to_string()));
        self.handle_bid_asks(storedBids.clone(), bids.clone());
        self.handle_bid_asks(storedAsks.clone(), asks.clone());
}

/*
 * @method
 * @name gate#watchTicker
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api
 * @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
 * @param {string} symbol unified symbol of the market to fetch the ticker for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
 */
    pub async fn watch_ticker(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = self.market(symbol.clone());
        symbol = get_value(&market, &Value::Str("symbol".to_string()));
        add_element_to_object(&mut params, &Value::Str("callerMethodName".to_string()), Value::Str("watchTicker".to_string()));
        let mut result: Value = self.watch_tickers(&[Value::List(vec![symbol.clone()]), params.clone()]).await;
        return self.safe_value(result.clone(), symbol.clone(), &[]);

    Value::Null
}

/*
 * @method
 * @name gate#watchTickers
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#tickers-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#tickers-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#tickers-api
 * @description watches a price ticker, a statistical calculation with the information calculated over the past 24 hours for all markets of a specific list
 * @param {string[]} symbols unified symbol of the market to fetch the ticker for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
 */
    pub async fn watch_tickers(&mut self, optional_args: &[Value]) -> Value {
        let mut symbols = 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 __ws_arg_4 = self.extend(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("method".to_string(), Value::Str("tickers".to_string()));
    m
}), &[params.clone()]);
        return self.subscribe_watch_tickers_and_bids_asks(&[symbols.clone(), Value::Str("watchTickers".to_string()), __ws_arg_4]).await;

    Value::Null
}

    pub fn handle_ticker(&mut self, mut client: Value, mut message: Value) {
        //
        //    {
        //        "time": 1649326221,
        //        "channel": "spot.tickers",
        //        "event": "update",
        //        "result": {
        //          "currency_pair": "BTC_USDT",
        //          "last": "43444.82",
        //          "lowest_ask": "43444.82",
        //          "highest_bid": "43444.81",
        //          "change_percentage": "-4.0036",
        //          "base_volume": "5182.5412425462",
        //          "quote_volume": "227267634.93123952",
        //          "high_24h": "47698",
        //          "low_24h": "42721.03"
        //        }
        //    }
        //
        self.handle_ticker_and_bid_ask(Value::Str("ticker".to_string()), client.clone(), message.clone());
}

/*
 * @method
 * @name gate#watchBidsAsks
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#best-bid-or-ask-price
 * @see https://www.gate.io/docs/developers/apiv4/ws/en/#order-book-channel
 * @see https://www.gate.com/docs/developers/options/ws/en/#best-bid-or-ask-price
 * @description watches best bid & ask for symbols
 * @param {string[]} symbols unified symbol of the market to fetch the ticker for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [ticker structure]{@link https://docs.ccxt.com/?id=ticker-structure}
 */
    pub async fn watch_bids_asks(&mut self, optional_args: &[Value]) -> Value {
        let mut symbols = 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 __ws_arg_5 = self.extend(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("method".to_string(), Value::Str("book_ticker".to_string()));
    m
}), &[params.clone()]);
        return self.subscribe_watch_tickers_and_bids_asks(&[symbols.clone(), Value::Str("watchBidsAsks".to_string()), __ws_arg_5]).await;

    Value::Null
}

    pub fn handle_bid_ask(&mut self, mut client: Value, mut message: Value) {
        //
        //    {
        //        "time": 1671363004,
        //        "time_ms": 1671363004235,
        //        "channel": "spot.book_ticker",
        //        "event": "update",
        //        "result": {
        //          "t": 1671363004228,
        //          "u": 9793320464,
        //          "s": "BTC_USDT",
        //          "b": "16716.8",
        //          "B": "0.0134",
        //          "a": "16716.9",
        //          "A": "0.0353"
        //        }
        //    }
        //
        self.handle_ticker_and_bid_ask(Value::Str("bidask".to_string()), client.clone(), message.clone());
}

    pub async fn subscribe_watch_tickers_and_bids_asks(&mut self, optional_args: &[Value]) -> Value {
        let mut symbols = get_arg(optional_args, 0, Value::Null);
        let mut callerMethodName = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        { let __destr_tmp = self.handle_param_string(params.clone(), Value::Str("callerMethodName".to_string()), &[callerMethodName.clone()]); callerMethodName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(false)]);
        let mut market: Value = self.market(get_value(&symbols, &Value::Int(0)));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
        let mut channelName: Value = Value::Null;
        { let __destr_tmp = self.handle_option_and_params(params.clone(), callerMethodName.clone(), Value::Str("method".to_string()), &[]); channelName = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut url: Value = self.get_url_by_market(market.clone());
        let mut channel: Value = add(&add(&messageType, &Value::Str(".".to_string())), &channelName);
        if is_equal(&callerMethodName, &Value::Null) {
            panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires a callerMethodName argument".to_string()))));
        }
        let mut isWatchTickers: bool = is_greater_than_or_equal(&get_index_of(&callerMethodName, &Value::Str("watchTicker".to_string())), &Value::Int(0));
        let mut prefix: Value = ternary(is_true(&isWatchTickers), Value::Str("ticker".to_string()), Value::Str("bidask".to_string()));
        let mut messageHashes: Value = Value::List(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_334: bool = true;
            while { if !__for_first_334 { i = add(&i, &Value::Int(1)); } __for_first_334 = false; is_less_than(&i, &get_array_length(&symbols)) } {
            let mut symbol: Value = get_value(&symbols, &i);
            let mut symbol: Value = get_value(&symbols, &i);
            append_to_array(&mut messageHashes, add(&add(&prefix, &Value::Str(":".to_string())), &symbol));
        }
        }
        let mut tickerOrBidAsk: Value = self.subscribe_public_multiple(url.clone(), messageHashes.clone(), marketIds.clone(), channel.clone(), &[params.clone()]).await;
        if is_true(&self.newUpdates) {
            let mut items: Value = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
            add_element_to_object(&mut items, &get_value(&tickerOrBidAsk, &Value::Str("symbol".to_string())), tickerOrBidAsk.clone());
            return items;
        }
        let mut result: Value = ternary(is_true(&isWatchTickers), self.tickers.clone(), self.bidsasks.clone());
        return self.filter_by_array(result.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(true)]);

    Value::Null
}

    pub fn handle_ticker_and_bid_ask(&mut self, mut objectName: Value, mut client: Value, mut message: Value) {
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
        let mut parts: Value = split(&channel, &Value::Str(".".to_string()));
        let mut rawMarketType: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
        let mut marketType: Value = ternary(is_true(&(is_equal(&rawMarketType, &Value::Str("futures".to_string())))), Value::Str("contract".to_string()), Value::Str("spot".to_string()));
        let mut result: Value = self.safe_value_k(message.clone(), "result", &[]);
        let mut results: Value = Value::List(vec![]);
        if is_true(&Value::Bool(is_array(&result))) {
            results = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
        }  else {
            let mut rawTicker: Value = self.safe_dict_k(message.clone(), "result", &[Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            })]);
            results = Value::List(vec![rawTicker.clone()]);
        }
        let mut isTicker: bool = is_equal(&objectName, &Value::Str("ticker".to_string())); // whether ticker or bid-ask
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_335: bool = true;
            while { if !__for_first_335 { i = add(&i, &Value::Int(1)); } __for_first_335 = false; is_less_than(&i, &get_array_length(&results)) } {
            let mut rawTicker: Value = get_value(&results, &i);
            let mut rawTicker: Value = get_value(&results, &i);
            let mut marketId: Value = self.safe_string_k(rawTicker.clone(), "s", &[]);
            let mut market: Value = self.safe_market(&[marketId.clone(), Value::Null, Value::Str("_".to_string()), marketType.clone()]);
            let mut parsedItem: Value = self.parse_ticker(rawTicker.clone(), &[market.clone()]);
            let mut symbol: Value = get_value(&parsedItem, &Value::Str("symbol".to_string()));
            if is_true(&isTicker) {
                if !is_equal(&symbol, &Value::Null) {
                    add_element_to_object(&mut self.tickers, &symbol, parsedItem.clone());
                }
            }  else {
                if !is_equal(&symbol, &Value::Null) {
                    add_element_to_object(&mut self.bidsasks, &symbol, parsedItem.clone());
                }
            }
            let mut messageHash: Value = add(&add(&objectName, &Value::Str(":".to_string())), &symbol);
            client.resolve(&[parsedItem.clone(), messageHash.clone()]);
        }
        }
}

/*
 * @method
 * @name gate#watchTrades
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#trades-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel
 * @description get the list of most recent trades for a particular symbol
 * @param {string} symbol unified symbol of the market to fetch trades for
 * @param {int} [since] timestamp in ms of the earliest trade to fetch
 * @param {int} [limit] the maximum amount of trades to fetch
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
 */
    pub async fn watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        return self.watch_trades_for_symbols(Value::List(vec![symbol.clone()]), &[since.clone(), limit.clone(), params.clone()]).await;

    Value::Null
}

/*
 * @method
 * @name gate#watchTradesForSymbols
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#public-trades-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#trades-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#trades-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#public-contract-trades-channel
 * @description get the list of most recent trades for a particular symbol
 * @param {string[]} symbols unified symbol of the market to fetch trades for
 * @param {int} [since] timestamp in ms of the earliest trade to fetch
 * @param {int} [limit] the maximum amount of trades to fetch
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
 */
    pub async fn watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        symbols = self.market_symbols(&[symbols.clone()]);
        let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
        let mut market: Value = self.market(get_value(&symbols, &Value::Int(0)));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".trades".to_string()));
        let mut messageHashes: Value = Value::List(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_336: bool = true;
            while { if !__for_first_336 { i = add(&i, &Value::Int(1)); } __for_first_336 = false; is_less_than(&i, &get_array_length(&symbols)) } {
            let mut symbol: Value = get_value(&symbols, &i);
            let mut symbol: Value = get_value(&symbols, &i);
            append_to_array(&mut messageHashes, add(&Value::Str("trades:".to_string()), &symbol));
        }
        }
        let mut url: Value = self.get_url_by_market(market.clone());
        let mut trades: Value = self.subscribe_public_multiple(url.clone(), messageHashes.clone(), marketIds.clone(), channel.clone(), &[params.clone()]).await;
        if is_true(&self.newUpdates) {
            let mut first: Value = self.safe_value(trades.clone(), Value::Int(0), &[]);
            let mut tradeSymbol: Value = self.safe_string_k(first.clone(), "symbol", &[]);
            limit = trades.get_limit(tradeSymbol.clone(), limit.clone());
        }
        return self.filter_by_since_limit(trades.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);

    Value::Null
}

/*
 * @method
 * @name gate#unWatchTradesForSymbols
 * @description get the list of most recent trades for a particular symbol
 * @param {string[]} symbols unified symbol of the market to fetch trades for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
 */
    pub async fn un_watch_trades_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        symbols = self.market_symbols(&[symbols.clone()]);
        let mut marketIds: Value = self.market_ids(&[symbols.clone()]);
        let mut market: Value = self.market(get_value(&symbols, &Value::Int(0)));
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".trades".to_string()));
        let mut subMessageHashes: Value = Value::List(vec![]);
        let mut messageHashes: Value = Value::List(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_337: bool = true;
            while { if !__for_first_337 { i = add(&i, &Value::Int(1)); } __for_first_337 = false; is_less_than(&i, &get_array_length(&symbols)) } {
            let mut symbol: Value = get_value(&symbols, &i);
            let mut symbol: Value = get_value(&symbols, &i);
            append_to_array(&mut subMessageHashes, add(&Value::Str("trades:".to_string()), &symbol));
            append_to_array(&mut messageHashes, add(&Value::Str("unsubscribe:trades:".to_string()), &symbol));
        }
        }
        let mut url: Value = self.get_url_by_market(market.clone());
        return self.un_subscribe_public_multiple(url.clone(), Value::Str("trades".to_string()), symbols.clone(), messageHashes.clone(), subMessageHashes.clone(), marketIds.clone(), channel.clone(), &[params.clone()]).await;

    Value::Null
}

/*
 * @method
 * @name gate#unWatchTrades
 * @description get the list of most recent trades for a particular symbol
 * @param {string} symbol unified symbol of the market to fetch trades for
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=public-trades}
 */
    pub async fn un_watch_trades(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        return self.un_watch_trades_for_symbols(Value::List(vec![symbol.clone()]), &[params.clone()]).await;

    Value::Null
}

    pub fn handle_trades(&mut self, mut client: Value, mut message: Value) {
        //
        // {
        //     "time": 1648725035,
        //     "channel": "spot.trades",
        //     "event": "update",
        //     "result": [{
        //       "id": 3130257995,
        //       "create_time": 1648725035,
        //       "create_time_ms": "1648725035923.0",
        //       "side": "sell",
        //       "currency_pair": "LTC_USDT",
        //       "amount": "0.0116",
        //       "price": "130.11"
        //     }]
        // }
        //
        let mut result: Value = self.safe_value_k(message.clone(), "result", &[]);
        if !is_true(&Value::Bool(is_array(&result))) {
            result = Value::List(vec![result.clone()]);
        }
        let mut parsedTrades: Value = self.parse_trades(result.clone(), &[]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_338: bool = true;
            while { if !__for_first_338 { i = add(&i, &Value::Int(1)); } __for_first_338 = false; is_less_than(&i, &get_array_length(&parsedTrades)) } {
            let mut trade: Value = get_value(&parsedTrades, &i);
            let mut trade: Value = get_value(&parsedTrades, &i);
            let mut symbol: Value = get_value(&trade, &Value::Str("symbol".to_string()));
            let mut cachedTrades: Value = self.safe_value(self.trades.clone(), symbol.clone(), &[]);
            if is_equal(&cachedTrades, &Value::Null) {
                let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
                cachedTrades = ArrayCache::new(limit.clone());
                if !is_equal(&symbol, &Value::Null) {
                    add_element_to_object(&mut self.trades, &symbol, cachedTrades.clone());
                }
            }
            cachedTrades.append(trade.clone());
            let mut hash: Value = add(&Value::Str("trades:".to_string()), &symbol);
            client.resolve(&[cachedTrades.clone(), hash.clone()]);
        }
        }
}

/*
 * @method
 * @name gate#watchOHLCV
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#candlesticks-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#candlesticks-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#candlesticks-api
 * @description watches historical candlestick data containing the open, high, low, and close price, and the volume of a market
 * @param {string} symbol unified symbol of the market to fetch OHLCV data for
 * @param {string} timeframe the length of time each candle represents
 * @param {int} [since] timestamp in ms of the earliest candle to fetch
 * @param {int} [limit] the maximum amount of candles to fetch
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {int[][]} A list of candles ordered as timestamp, open, high, low, close, volume
 */
    pub async fn watch_ohlcv(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut timeframe = get_arg(optional_args, 0, Value::Str("1m".to_string()));
        let mut since = get_arg(optional_args, 1, Value::Null);
        let mut limit = get_arg(optional_args, 2, Value::Null);
        let mut params = get_arg(optional_args, 3, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        // todo add options support
        let mut market: Value = self.market(symbol.clone());
        symbol = get_value(&market, &Value::Str("symbol".to_string()));
        let mut marketId: Value = get_value(&market, &Value::Str("id".to_string()));
        let mut interval: Value = self.safe_string(self.timeframes.clone(), timeframe.clone(), &[timeframe.clone()]);
        let mut messageType: Value = self.get_type_by_market(market.clone());
        let mut channel: Value = add(&messageType, &Value::Str(".candlesticks".to_string()));
        let mut messageHash: Value = add(&add(&add(&Value::Str("candles:".to_string()), &interval), &Value::Str(":".to_string())), &get_value(&market, &Value::Str("symbol".to_string())));
        let mut url: Value = self.get_url_by_market(market.clone());
        let mut payload: Value = Value::List(vec![interval.clone(), marketId.clone()]);
        let mut ohlcv: Value = self.subscribe_public(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), &[params.clone()]).await;
        if is_true(&self.newUpdates) {
            limit = ohlcv.get_limit(symbol.clone(), limit.clone());
        }
        return self.filter_by_since_limit(ohlcv.clone(), &[since.clone(), limit.clone(), Value::Int(0), Value::Bool(true)]);

    Value::Null
}

    pub fn handle_ohlcv(&mut self, mut client: Value, mut message: Value) {
        //
        // {
        //     "time": 1606292600,
        //     "channel": "spot.candlesticks",
        //     "event": "update",
        //     "result": {
        //       "t": "1606292580", // total volume
        //       "v": "2362.32035", // volume
        //       "c": "19128.1", // close
        //       "h": "19128.1", // high
        //       "l": "19128.1", // low
        //       "o": "19128.1", // open
        //       "n": "1m_BTC_USDT" // sub
        //     }
        //   }
        //
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
        let mut channelParts: Value = split(&channel, &Value::Str(".".to_string()));
        let mut rawMarketType: Value = self.safe_string(channelParts.clone(), Value::Int(0), &[]);
        let mut marketType: Value = ternary(is_true(&(is_equal(&rawMarketType, &Value::Str("spot".to_string())))), Value::Str("spot".to_string()), Value::Str("contract".to_string()));
        let mut result: Value = self.safe_value_k(message.clone(), "result", &[]);
        if !is_true(&Value::Bool(is_array(&result))) {
            result = Value::List(vec![result.clone()]);
        }
        let mut marketIds: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_339: bool = true;
            while { if !__for_first_339 { i = add(&i, &Value::Int(1)); } __for_first_339 = false; is_less_than(&i, &get_array_length(&result)) } {
            let mut ohlcv: Value = get_value(&result, &i);
            let mut ohlcv: Value = get_value(&result, &i);
            let mut subscription: Value = self.safe_string_k(ohlcv.clone(), "n", &[Value::Str("".to_string())]);
            let mut parts: Value = split(&subscription, &Value::Str("_".to_string()));
            let mut timeframeId: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
            let mut timeframe: Value = self.find_timeframe(timeframeId.clone(), &[]);
            let mut prefix: Value = add(&timeframe, &Value::Str("_".to_string()));
            let mut marketId: Value = replace_str(&subscription, &prefix, &Value::Str("".to_string()));
            let mut symbol: Value = self.safe_symbol(marketId.clone(), &[Value::Null, Value::Str("_".to_string()), marketType.clone()]);
            let mut parsed: Value = self.parse_ohlcv(ohlcv.clone(), &[]);
            { let __be_tmp = self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
})]); add_element_to_object(&mut self.ohlcvs, &symbol, __be_tmp); };
            let mut stored: Value = self.safe_value(self.safe_value(self.ohlcvs.clone(), symbol.clone(), &[]), timeframe.clone(), &[]);
            if is_equal(&stored, &Value::Null) {
                let mut limit: Value = self.safe_integer_k(self.options.clone(), "OHLCVLimit", &[Value::Int(1000)]);
                stored = ArrayCacheByTimestamp::new(limit.clone());
                if !is_equal(&symbol, &Value::Null) && !is_equal(&timeframe, &Value::Null) {
                    add_element_to_object(get_value_mut(unsafe { crate::runtime::coerce_value_to_mut(&self.ohlcvs) }, &symbol), &timeframe, stored.clone());
                }
            }
            stored.append(parsed.clone());
            add_element_to_object(&mut marketIds, &symbol, timeframe.clone());
        }
        }
        let mut keys: Value = object_keys(&marketIds);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_340: bool = true;
            while { if !__for_first_340 { i = add(&i, &Value::Int(1)); } __for_first_340 = false; is_less_than(&i, &get_array_length(&keys)) } {
            let mut symbol: Value = get_value(&keys, &i);
            let mut symbol: Value = get_value(&keys, &i);
            let mut timeframe: Value = get_value(&marketIds, &symbol);
            let mut timeframe: Value = get_value(&marketIds, &symbol);
            let mut interval: Value = self.find_timeframe(timeframe.clone(), &[]);
            let mut hash: Value = add(&add(&add(&add(&Value::Str("candles".to_string()), &Value::Str(":".to_string())), &interval), &Value::Str(":".to_string())), &symbol);
            let mut stored: Value = self.safe_value(get_value(&self.ohlcvs, &symbol), interval.clone(), &[]);
            client.resolve(&[stored.clone(), hash.clone()]);
        }
        }
}

/*
 * @method
 * @name gate#watchMyTrades
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#user-trades-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#user-trades-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#user-trades-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#user-trades-channel
 * @description watches information on multiple trades made by the user
 * @param {string} symbol unified market symbol of the market trades were made in
 * @param {int} [since] the earliest time in ms to fetch trades for
 * @param {int} [limit] the maximum number of trade structures to retrieve
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [trade structures]{@link https://docs.ccxt.com/?id=trade-structure}
 */
    pub async fn watch_my_trades(&mut self, optional_args: &[Value]) -> Value {
        let mut symbol = 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut subType: Value = Value::Null;
        let mut type_var: Value = Value::Null;
        let mut marketId: Value = add(&Value::Str("!".to_string()), &Value::Str("all".to_string()));
        let mut market: Value = Value::Null;
        if !is_equal(&symbol, &Value::Null) {
            market = self.market(symbol.clone());
            marketId = get_value(&market, &Value::Str("id".to_string()));
        }
        { let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchMyTrades".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        { let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchMyTrades".to_string()), &[market.clone(), params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut messageType: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("spot".to_string(), Value::Str("spot".to_string()));
                m.insert("margin".to_string(), Value::Str("spot".to_string()));
                m.insert("future".to_string(), Value::Str("futures".to_string()));
                m.insert("swap".to_string(), Value::Str("futures".to_string()));
                m.insert("option".to_string(), Value::Str("options".to_string()));
            m
        })]);
        let mut channel: Value = add(&messageType, &Value::Str(".usertrades".to_string()));
        let mut messageHash: Value = Value::Str("myTrades".to_string());
        if !is_equal(&symbol, &Value::Null) {
            messageHash = add(&messageHash, &add(&Value::Str(":".to_string()), &symbol));
        }
        let mut isInverse: Value = Value::Bool(is_equal(&subType, &Value::Str("inverse".to_string())));
        let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse.clone()]);
        let mut payload: Value = Value::List(vec![marketId.clone()]);
        // uid required for non spot markets
        let mut requiresUid: Value = Value::Bool(!is_equal(&type_var, &Value::Str("spot".to_string())));
        let mut trades: Value = self.subscribe_private(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), params.clone(), &[requiresUid.clone()]).await;
        if is_true(&self.newUpdates) {
            limit = trades.get_limit(symbol.clone(), limit.clone());
        }
        return self.filter_by_symbol_since_limit(trades.clone(), &[symbol.clone(), since.clone(), limit.clone(), Value::Bool(true)]);

    Value::Null
}

    pub fn handle_my_trades(&mut self, mut client: Value, mut message: Value) {
        //
        // {
        //     "time": 1543205083,
        //     "channel": "futures.usertrades",
        //     "event": "update",
        //     "error": null,
        //     "result": [
        //       {
        //         "id": "3335259",
        //         "create_time": 1628736848,
        //         "create_time_ms": 1628736848321,
        //         "contract": "BTC_USD",
        //         "order_id": "4872460",
        //         "size": 1,
        //         "price": "40000.4",
        //         "role": "maker"
        //       }
        //     ]
        // }
        //
        let mut result: Value = self.safe_value_k(message.clone(), "result", &[Value::List(vec![])]);
        let mut tradesLength: Value = get_array_length(&result);
        if is_equal(&tradesLength, &Value::Int(0)) {
            return;
        }
        let mut cachedTrades: Value = self.myTrades.clone();
        if is_equal(&cachedTrades, &Value::Null) {
            let mut limit: Value = self.safe_integer_k(self.options.clone(), "tradesLimit", &[Value::Int(1000)]);
            cachedTrades = ArrayCacheBySymbolById::new(limit.clone());
            self.myTrades = cachedTrades.clone();
        }
        let mut parsed: Value = self.parse_trades(result.clone(), &[]);
        let mut marketIds: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_341: bool = true;
            while { if !__for_first_341 { i = add(&i, &Value::Int(1)); } __for_first_341 = false; is_less_than(&i, &get_array_length(&parsed)) } {
            let mut trade: Value = get_value(&parsed, &i);
            let mut trade: Value = get_value(&parsed, &i);
            cachedTrades.append(trade.clone());
            let mut symbol: Value = get_value(&trade, &Value::Str("symbol".to_string()));
            if !is_equal(&symbol, &Value::Null) {
                add_element_to_object(&mut marketIds, &symbol, Value::Bool(true));
            }
        }
        }
        let mut keys: Value = object_keys(&marketIds);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_342: bool = true;
            while { if !__for_first_342 { i = add(&i, &Value::Int(1)); } __for_first_342 = false; is_less_than(&i, &get_array_length(&keys)) } {
            let mut market: Value = get_value(&keys, &i);
            let mut market: Value = get_value(&keys, &i);
            let mut hash: Value = add(&Value::Str("myTrades:".to_string()), &market);
            client.resolve(&[cachedTrades.clone(), hash.clone()]);
        }
        }
        client.resolve(&[cachedTrades.clone(), Value::Str("myTrades".to_string())]);
}

/*
 * @method
 * @name gate#watchBalance
 * @description watch balance and get the amount of funds available for trading or funds locked in orders
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#spot-balance-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#balances-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#balances-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#balances-channel
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @returns {object} a [balance structure]{@link https://docs.ccxt.com/?id=balance-structure}
 */
    pub async fn watch_balance(&mut self, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut type_var: Value = Value::Null;
        let mut subType: Value = Value::Null;
        { let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchBalance".to_string()), &[Value::Null, params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        { let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchBalance".to_string()), &[Value::Null, params.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); params = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut isInverse: Value = Value::Bool(is_equal(&subType, &Value::Str("inverse".to_string())));
        let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse.clone()]);
        let mut requiresUid: Value = Value::Bool(!is_equal(&type_var, &Value::Str("spot".to_string())));
        let mut channelType: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("spot".to_string(), Value::Str("spot".to_string()));
                m.insert("margin".to_string(), Value::Str("spot".to_string()));
                m.insert("future".to_string(), Value::Str("futures".to_string()));
                m.insert("swap".to_string(), Value::Str("futures".to_string()));
                m.insert("option".to_string(), Value::Str("options".to_string()));
            m
        })]);
        // todo: add correct margin support
        let mut channel: Value = add(&channelType, &Value::Str(".balances".to_string()));
        let mut messageHash: Value = add(&type_var, &Value::Str(".balance".to_string()));
        return self.subscribe_private(url.clone(), messageHash.clone(), Value::Null, channel.clone(), params.clone(), &[requiresUid.clone()]).await;

    Value::Null
}

    pub fn handle_balance(&mut self, mut client: Value, mut message: Value) {
        //
        // spot order fill
        //     {
        //         "time": 1653664351,
        //         "time_ms": 1605248616763,
        //         "channel": "spot.balances",
        //         "event": "update",
        //         "result": [
        //             {
        //                 "timestamp": "1667556323",
        //                 "timestamp_ms": "1667556323730",
        //                 "user": "1000001",
        //                 "currency": "USDT",
        //                 "change": "0",
        //                 "total": "222244.3827652",
        //                 "available": "222244.3827",
        //                 "freeze": "5",
        //                 "freeze_change": "5.000000",
        //                 "change_type": "order-create"
        //             }
        //         ]
        //     }
        //
        // account transfer
        //
        //    {
        //        "id": null,
        //        "time": 1653665088,
        //        "channel": "futures.balances",
        //        "event": "update",
        //        "error": null,
        //        "result": [
        //          {
        //            "balance": 25.035008537,
        //            "change": 25,
        //            "text": "-",
        //            "time": 1653665088,
        //            "time_ms": 1653665088286,
        //            "type": "dnw",
        //            "user": "10406147"
        //          }
        //        ]
        //   }
        //
        // swap order fill
        //   {
        //       "id": null,
        //       "time": 1653665311,
        //       "channel": "futures.balances",
        //       "event": "update",
        //       "error": null,
        //       "result": [
        //         {
        //           "balance": 20.031873037,
        //           "change": -0.0031355,
        //           "text": "LTC_USDT:165551103273",
        //           "time": 1653665311,
        //           "time_ms": 1653665311437,
        //           "type": "fee",
        //           "user": "10406147"
        //         }
        //       ]
        //   }
        //
        let mut result: Value = self.safe_value_k(message.clone(), "result", &[Value::List(vec![])]);
        add_element_to_object(&mut self.balance, &Value::Str("info".to_string()), result.clone());
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_343: bool = true;
            while { if !__for_first_343 { i = add(&i, &Value::Int(1)); } __for_first_343 = false; is_less_than(&i, &get_array_length(&result)) } {
            let mut rawBalance: Value = get_value(&result, &i);
            let mut rawBalance: Value = get_value(&result, &i);
            let mut account: Value = self.account();
            let mut currencyId: Value = self.safe_string_k(rawBalance.clone(), "currency", &[Value::Str("USDT".to_string())]); // when not present it is USDT
            let mut code: Value = self.safe_currency_code(currencyId.clone(), &[]);
            let mut timestamp: Value = self.safe_integer2(rawBalance.clone(), Value::Str("time_ms".to_string()), Value::Str("timestamp_ms".to_string()), &[]);
            add_element_to_object(&mut self.balance, &Value::Str("timestamp".to_string()), timestamp.clone());
            { let __be_tmp = self.iso8601(timestamp.clone()); add_element_to_object(&mut self.balance, &Value::Str("datetime".to_string()), __be_tmp); };
            add_element_to_object(&mut account, &Value::Str("used".to_string()), self.safe_string_k(rawBalance.clone(), "freeze", &[]));
            add_element_to_object(&mut account, &Value::Str("free".to_string()), self.safe_string_k(rawBalance.clone(), "available", &[]));
            add_element_to_object(&mut account, &Value::Str("total".to_string()), self.safe_string2(rawBalance.clone(), Value::Str("total".to_string()), Value::Str("balance".to_string()), &[]));
            if !is_equal(&code, &Value::Null) {
                add_element_to_object(&mut self.balance, &code, account.clone());
            }
        }
        }
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
        let mut parts: Value = split(&channel, &Value::Str(".".to_string()));
        let mut rawType: Value = self.safe_string(parts.clone(), Value::Int(0), &[]);
        let mut channelType: Value = self.get_supported_mapping(rawType.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("spot".to_string(), Value::Str("spot".to_string()));
                m.insert("futures".to_string(), Value::Str("swap".to_string()));
                m.insert("options".to_string(), Value::Str("option".to_string()));
            m
        })]);
        let mut messageHash: Value = add(&channelType, &Value::Str(".balance".to_string()));
        { let __t = self.safe_balance(self.balance.clone()); self.balance = __t; }
        client.resolve(&[self.balance.clone(), messageHash.clone()]);
}

/*
 * @method
 * @name gate#watchPositions
 * @see https://www.gate.io/docs/developers/futures/ws/en/#positions-subscription
 * @see https://www.gate.io/docs/developers/delivery/ws/en/#positions-subscription
 * @see https://www.gate.io/docs/developers/options/ws/en/#positions-channel
 * @description watch all open positions
 * @param {string[]} [symbols] list of unified market symbols to watch positions for
 * @param {int} [since] the earliest time in ms to fetch positions for
 * @param {int} [limit] the maximum number of positions to retrieve
 * @param {object} params extra parameters specific to the exchange API endpoint
 * @returns {object[]} a list of [position structure]{@link https://docs.ccxt.com/en/latest/manual.html#position-structure}
 */
    pub async fn watch_positions(&mut self, optional_args: &[Value]) -> Value {
        let mut symbols = 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = Value::Null;
        symbols = self.market_symbols(&[symbols.clone()]);
        let mut payload: Value = Value::List(vec![add(&Value::Str("!".to_string()), &Value::Str("all".to_string()))]);
        if !is_true(&self.is_empty(symbols.clone())) {
            market = self.get_market_from_symbols(&[symbols.clone()]);
        }
        let mut type_var: Value = Value::Null;
        let mut query: Value = Value::Null;
        { let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchPositions".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        if is_equal(&type_var, &Value::Str("spot".to_string())) {
            type_var = Value::Str("swap".to_string());
        }
        let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("future".to_string(), Value::Str("futures".to_string()));
                m.insert("swap".to_string(), Value::Str("futures".to_string()));
                m.insert("option".to_string(), Value::Str("options".to_string()));
            m
        })]);
        let mut messageHash: Value = add(&type_var, &Value::Str(":positions".to_string()));
        if !is_true(&self.is_empty(symbols.clone())) {
            if is_equal(&symbols, &Value::Null) {
                panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" watchPositions() symbols is required".to_string()))));
            }
            messageHash = add(&messageHash, &add(&Value::Str("::".to_string()), &join(&symbols, &Value::Str(",".to_string()))));
        }
        let mut channel: Value = add(&typeId, &Value::Str(".positions".to_string()));
        let mut subType: Value = Value::Null;
        { let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchPositions".to_string()), &[market.clone(), query.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut isInverse: Value = Value::Bool(is_equal(&subType, &Value::Str("inverse".to_string())));
        let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse.clone()]);
        let mut client: Value = self.client(&[url.clone()]);
        self.set_positions_cache(client.clone(), type_var.clone(), &[symbols.clone()]);
        let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("fetchPositionsSnapshot".to_string()), &[Value::Bool(true)]);
        let mut awaitPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("awaitPositionsSnapshot".to_string()), &[Value::Bool(true)]);
        let mut cache: Value = self.safe_value(self.positions.clone(), type_var.clone(), &[]);
        if is_true(&(is_equal(&fetchPositionsSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&awaitPositionsSnapshot, &Value::Bool(true)))) && is_true(&(is_equal(&cache, &Value::Null))) {
            return crate::exchange_stubs::ws_await_flight(&client.future(&[add(&type_var, &Value::Str(":fetchPositionsSnapshot".to_string()))])).await;
        }
        let mut positions: Value = self.subscribe_private(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), query.clone(), &[Value::Bool(true)]).await;
        if is_true(&self.newUpdates) {
            return positions;
        }
        return self.filter_by_symbols_since_limit(self.safe_value(self.positions.clone(), type_var.clone(), &[]), &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);

    Value::Null
}

    pub fn set_positions_cache(&mut self, mut client: Value, mut type_var: Value, optional_args: &[Value]) {
        let mut symbols = get_arg(optional_args, 0, Value::Null);
        if is_equal(&self.positions, &Value::Null) {
            self.positions = Value::Map({
                let mut m = indexmap::IndexMap::new();
                m
            });
        }
        if is_true(&Value::Bool(in_op(&self.positions, &type_var))) {
            return;
        }
        let mut fetchPositionsSnapshot: Value = self.handle_option(Value::Str("watchPositions".to_string()), Value::Str("fetchPositionsSnapshot".to_string()), &[Value::Bool(false)]);
        if is_equal(&fetchPositionsSnapshot, &Value::Bool(true)) {
            let mut messageHash: Value = add(&type_var, &Value::Str(":fetchPositionsSnapshot".to_string()));
            if !is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash)))) {
                client.future(&[messageHash.clone()]);
                self.spawn(&[Value::Str("load_positions_snapshot".to_string()).clone(), client.clone(), messageHash.clone(), type_var.clone()]);
            }
        }  else {
            add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
        }
}

    pub async fn load_positions_snapshot(&mut self, mut client: Value, mut messageHash: Value, mut type_var: Value) -> Value {
        let mut positions: Value = self.fetch_positions(&[Value::Null, Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("type".to_string(), type_var.clone());
            m
        })]).await;
        add_element_to_object(&mut self.positions, &type_var, ArrayCacheBySymbolBySide::new(Value::Null));
        let mut cache: Value = get_value(&self.positions, &type_var);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_344: bool = true;
            while { if !__for_first_344 { i = add(&i, &Value::Int(1)); } __for_first_344 = false; is_less_than(&i, &get_array_length(&positions)) } {
            let mut position: Value = get_value(&positions, &i);
            let mut position: Value = get_value(&positions, &i);
            let mut contracts: Value = self.safe_number_k(position.clone(), "contracts", &[Value::Int(0)]);
            if is_true(&(!is_equal(&contracts, &Value::Null))) && is_true(&(is_greater_than(&contracts, &Value::Int(0)))) {
                cache.append(position.clone());
            }
        }
        }
        // don't remove the future from the .futures cache
        if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("futures".to_string())), &messageHash))) {
            let mut future: Value = get_value(&get_value(&client, &Value::Str("futures".to_string())), &messageHash);
            future.resolve(&[cache.clone()]);
            client.resolve(&[cache.clone(), add(&type_var, &Value::Str(":position".to_string()))]);
        }

    Value::Null
}

    pub fn handle_positions(&self, mut client: Value, mut message: Value) {
        //
        //    {
        //        time: 1693158497,
        //        time_ms: 1693158497204,
        //        channel: 'futures.positions',
        //        event: 'update',
        //        result: [{
        //            contract: 'XRP_USDT',
        //            cross_leverage_limit: 0,
        //            entry_price: 0.5253,
        //            history_pnl: 0,
        //            history_point: 0,
        //            last_close_pnl: 0,
        //            leverage: 0,
        //            leverage_max: 50,
        //            liq_price: 0.0361,
        //            maintenance_rate: 0.01,
        //            margin: 4.89609962852,
        //            mode: 'single',
        //            realised_pnl: -0.0026265,
        //            realised_point: 0,
        //            risk_limit: 500000,
        //            size: 1,
        //            time: 1693158497,
        //            time_ms: 1693158497195,
        //            update_id: 1,
        //            user: '10444586'
        //        }]
        //    }
        //
        let mut type_var: Value = self.get_market_type_by_url(get_value(&client, &Value::Str("url".to_string())));
        let mut data: Value = self.safe_value_k(message.clone(), "result", &[Value::List(vec![])]);
        let mut cache: Value = get_value(&self.positions, &type_var);
        let mut newPositions: Value = Value::List(vec![]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_345: bool = true;
            while { if !__for_first_345 { i = add(&i, &Value::Int(1)); } __for_first_345 = false; is_less_than(&i, &get_array_length(&data)) } {
            let mut rawPosition: Value = get_value(&data, &i);
            let mut rawPosition: Value = get_value(&data, &i);
            let mut position: Value = self.parse_position(rawPosition.clone(), &[]);
            let mut symbol: Value = self.safe_string_k(position.clone(), "symbol", &[]);
            let mut side: Value = self.safe_string_k(position.clone(), "side", &[]);
            // Control when position is closed no side is returned
            if is_equal(&side, &Value::Null) {
                let mut prevLongPosition: Value = self.safe_dict(cache.clone(), add(&symbol, &Value::Str("long".to_string())), &[]);
                if !is_equal(&prevLongPosition, &Value::Null) {
                    add_element_to_object(&mut position, &Value::Str("side".to_string()), get_value(&prevLongPosition, &Value::Str("side".to_string())));
                    append_to_array(&mut newPositions, position.clone());
                    cache.append(position.clone());
                }
                let mut prevShortPosition: Value = self.safe_dict(cache.clone(), add(&symbol, &Value::Str("short".to_string())), &[]);
                if !is_equal(&prevShortPosition, &Value::Null) {
                    add_element_to_object(&mut position, &Value::Str("side".to_string()), get_value(&prevShortPosition, &Value::Str("side".to_string())));
                    append_to_array(&mut newPositions, position.clone());
                    cache.append(position.clone());
                }
                // if no prev position is found, default to long
                if is_equal(&prevLongPosition, &Value::Null) && is_equal(&prevShortPosition, &Value::Null) {
                    add_element_to_object(&mut position, &Value::Str("side".to_string()), Value::Str("long".to_string()));
                    append_to_array(&mut newPositions, position.clone());
                    cache.append(position.clone());
                }
            }  else {
                append_to_array(&mut newPositions, position.clone());
                cache.append(position.clone());
            }
        }
        }
        let mut messageHashes: Value = self.find_message_hashes(client.clone(), add(&type_var, &Value::Str(":positions::".to_string())));
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_346: bool = true;
            while { if !__for_first_346 { i = add(&i, &Value::Int(1)); } __for_first_346 = false; is_less_than(&i, &get_array_length(&messageHashes)) } {
            let mut messageHash: Value = get_value(&messageHashes, &i);
            let mut messageHash: Value = get_value(&messageHashes, &i);
            let mut parts: Value = split(&messageHash, &Value::Str("::".to_string()));
            let mut symbolsString: Value = get_value(&parts, &Value::Int(1));
            let mut symbols: Value = split(&symbolsString, &Value::Str(",".to_string()));
            let mut positions: Value = self.filter_by_array(newPositions.clone(), Value::Str("symbol".to_string()), &[symbols.clone(), Value::Bool(false)]);
            if !is_true(&self.is_empty(positions.clone())) {
                client.resolve(&[positions.clone(), messageHash.clone()]);
            }
        }
        }
        client.resolve(&[newPositions.clone(), add(&type_var, &Value::Str(":positions".to_string()))]);
}

/*
 * @method
 * @name gate#watchOrders
 * @description watches information on multiple orders made by the user
 * @see https://www.gate.com/docs/developers/apiv4/ws/en/#orders-channel
 * @see https://www.gate.com/docs/developers/futures/ws/en/#orders-api
 * @see https://www.gate.com/docs/developers/delivery/ws/en/#orders-api
 * @see https://www.gate.com/docs/developers/options/ws/en/#orders-channel
 * @param {string} symbol unified market symbol of the market orders were made in
 * @param {int} [since] the earliest time in ms to fetch orders for
 * @param {int} [limit] the maximum number of order structures to retrieve
 * @param {object} [params] extra parameters specific to the exchange API endpoint
 * @param {string} [params.type] spot, margin, swap, future, or option. Required if listening to all symbols.
 * @param {boolean} [params.isInverse] if future, listen to inverse or linear contracts
 * @param {boolean} [params.trigger] set to true to watch trigger orders, spot.priceorders and futures.autoorders channels, see https://github.com/ccxt/ccxt/issues/27202
 * @param {boolean} [params.stop] alias of params.trigger
 * @returns {object[]} a list of [order structures]{@link https://docs.ccxt.com/?id=order-structure}
 */
    pub async fn watch_orders(&mut self, optional_args: &[Value]) -> Value {
        let mut symbol = 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
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        let mut market: Value = Value::Null;
        if !is_equal(&symbol, &Value::Null) {
            let mut marketResolved: Value = self.market(symbol.clone());
            market = marketResolved.clone();
            symbol = get_value(&market, &Value::Str("symbol".to_string()));
        }
        let mut type_var: Value = Value::Null;
        let mut query: Value = Value::Null;
        { let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchOrders".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("spot".to_string(), Value::Str("spot".to_string()));
                m.insert("margin".to_string(), Value::Str("spot".to_string()));
                m.insert("future".to_string(), Value::Str("futures".to_string()));
                m.insert("swap".to_string(), Value::Str("futures".to_string()));
                m.insert("option".to_string(), Value::Str("options".to_string()));
            m
        })]);
        let mut isTrigger: Value = Value::Bool(false);
        { let __destr_tmp = self.handle_param_bool2(query.clone(), Value::Str("trigger".to_string()), Value::Str("stop".to_string()), &[Value::Bool(false)]); isTrigger = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        if is_true(&(is_equal(&isTrigger, &Value::Bool(true)))) && is_true(&(is_equal(&typeId, &Value::Str("options".to_string())))) {
            panic!("{}", crate::exchange_errors::not_supported(add(&self.id, &Value::Str(" watchOrders() does not support trigger orders for options, see https://github.com/ccxt/ccxt/issues/27202".to_string()))));
        }
        // gate pushes trigger orders on dedicated channels, spot.priceorders and futures.autoorders,
        // see https://github.com/ccxt/ccxt/issues/27202
        let mut suffix: Value = Value::Str(".orders".to_string());
        if is_equal(&isTrigger, &Value::Bool(true)) {
            suffix = ternary(is_true(&(is_equal(&typeId, &Value::Str("spot".to_string())))), Value::Str(".priceorders".to_string()), Value::Str(".autoorders".to_string()));
        }
        let mut channel: Value = add(&typeId, &suffix);
        let mut messageHash: Value = ternary(is_true(&(is_equal(&isTrigger, &Value::Bool(true)))), Value::Str("triggerOrders".to_string()), Value::Str("orders".to_string()));
        let mut payload: Value = Value::List(vec![add(&Value::Str("!".to_string()), &Value::Str("all".to_string()))]);
        if !is_equal(&market, &Value::Null) {
            messageHash = add(&messageHash, &add(&Value::Str(":".to_string()), &get_value(&market, &Value::Str("id".to_string()))));
            let mut mid: Value = get_value(&market, &Value::Str("id".to_string()));
            if !is_equal(&mid, &Value::Null) {
                payload = Value::List(vec![mid.clone()]);
            }
        }
        let mut subType: Value = Value::Null;
        { let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchOrders".to_string()), &[market.clone(), query.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut isInverse: Value = Value::Bool(is_equal(&subType, &Value::Str("inverse".to_string())));
        let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse.clone()]);
        // uid required for non spot markets
        let mut requiresUid: Value = Value::Bool(!is_equal(&type_var, &Value::Str("spot".to_string())));
        let mut orders: Value = self.subscribe_private(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), query.clone(), &[requiresUid.clone()]).await;
        if is_true(&self.newUpdates) {
            limit = orders.get_limit(symbol.clone(), limit.clone());
        }
        return self.filter_by_since_limit(orders.clone(), &[since.clone(), limit.clone(), Value::Str("timestamp".to_string()), Value::Bool(true)]);

    Value::Null
}

    pub fn handle_order(&mut self, mut client: Value, mut message: Value) {
        //
        //     {
        //         "time": 1774613210,
        //         "time_ms": 1774613210392,
        //         "channel": "spot.orders",
        //         "event": "update",
        //         "result": [
        //             {
        //                 "id": "1036717689726",
        //                 "text": "apiv4",
        //                 "create_time": "1774613210",
        //                 "update_time": "1774613210",
        //                 "currency_pair": "BTC_USDT",
        //                 "type": "limit",
        //                 "account": "unified",
        //                 "side": "buy",
        //                 "amount": "0.1",
        //                 "price": "200",
        //                 "time_in_force": "gtc",
        //                 "left": "0.1",
        //                 "filled_amount": "0",
        //                 "filled_total": "0",
        //                 "avg_deal_price": "0",
        //                 "fee": "0",
        //                 "fee_currency": "BTC",
        //                 "point_fee": "0",
        //                 "gt_fee": "0",
        //                 "rebated_fee": "0",
        //                 "rebated_fee_currency": "BTC",
        //                 "create_time_ms": "1774613210391",
        //                 "update_time_ms": "1774613210391",
        //                 "user": 10406147,
        //                 "event": "put",
        //                 "stp_id": 0,
        //                 "stp_act": "-",
        //                 "finish_as": "open",
        //                 "biz_info": "ch:ccxt",
        //                 "amend_text": "-"
        //             }
        //         ]
        //     }
        //
        let mut orders: Value = self.safe_value_k(message.clone(), "result", &[Value::List(vec![])]);
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[Value::Str("".to_string())]);
        let mut isTrigger: bool = is_true(&(is_greater_than_or_equal(&get_index_of(&channel, &Value::Str("autoorders".to_string())), &Value::Int(0)))) || is_true(&(is_greater_than_or_equal(&get_index_of(&channel, &Value::Str("priceorders".to_string())), &Value::Int(0))));
        let mut hashPrefix: Value = ternary(is_true(&isTrigger), Value::Str("triggerOrders".to_string()), Value::Str("orders".to_string()));
        let mut limit: Value = self.safe_integer_k(self.options.clone(), "ordersLimit", &[Value::Int(1000)]);
        if is_equal(&self.orders, &Value::Null) {
            self.orders = ArrayCacheBySymbolById::new(limit.clone());
            self.triggerOrders = ArrayCacheBySymbolById::new(limit.clone());
        }
        let mut stored: Value = ternary(is_true(&isTrigger), self.triggerOrders.clone(), self.orders.clone());
        let mut marketIds: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
        let mut parsedOrders: Value = self.parse_orders(orders.clone(), &[]);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_347: bool = true;
            while { if !__for_first_347 { i = add(&i, &Value::Int(1)); } __for_first_347 = false; is_less_than(&i, &get_array_length(&parsedOrders)) } {
            let mut parsed: Value = get_value(&parsedOrders, &i);
            let mut parsed: Value = get_value(&parsedOrders, &i);
            // inject order status
            let mut info: Value = self.safe_value_k(parsed.clone(), "info", &[]);
            let mut event: Value = self.safe_string_k(info.clone(), "event", &[]);
            if is_equal(&event, &Value::Str("put".to_string())) || is_equal(&event, &Value::Str("update".to_string())) {
                add_element_to_object(&mut parsed, &Value::Str("status".to_string()), Value::Str("open".to_string()));
            }  else if is_equal(&event, &Value::Str("finish".to_string())) {
                let mut status: Value = self.safe_string_k(parsed.clone(), "status", &[]);
                if is_equal(&status, &Value::Null) {
                    let mut left: Value = self.safe_integer_k(info.clone(), "left", &[]);
                    add_element_to_object(&mut parsed, &Value::Str("status".to_string()), ternary(is_true(&(is_equal(&left, &Value::Int(0)))), Value::Str("closed".to_string()), Value::Str("canceled".to_string())));
                }
            }
            stored.append(parsed.clone());
            let mut symbol: Value = get_value(&parsed, &Value::Str("symbol".to_string()));
            let mut market: Value = self.market(symbol.clone());
            if !is_equal(&get_value(&market, &Value::Str("id".to_string())), &Value::Null) {
                add_element_to_object(&mut marketIds, &get_value(&market, &Value::Str("id".to_string())), Value::Bool(true));
            }
        }
        }
        let mut keys: Value = object_keys(&marketIds);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_348: bool = true;
            while { if !__for_first_348 { i = add(&i, &Value::Int(1)); } __for_first_348 = false; is_less_than(&i, &get_array_length(&keys)) } {
            let mut messageHash: Value = add(&add(&hashPrefix, &Value::Str(":".to_string())), &get_value(&keys, &i));
            client.resolve(&[stored.clone(), messageHash.clone()]);
        }
        }
        client.resolve(&[stored.clone(), hashPrefix.clone()]);
}

/*
 * @method
 * @name gate#watchMyLiquidations
 * @description watch the public liquidations of a trading pair
 * @see https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
 * @see https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
 * @see https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel
 * @param {string} symbol unified CCXT market symbol
 * @param {int} [since] the earliest time in ms to fetch liquidations for
 * @param {int} [limit] the maximum number of liquidation structures to retrieve
 * @param {object} [params] exchange specific parameters for the bitmex api endpoint
 * @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure}
 */
    pub async fn watch_my_liquidations(&mut self, mut symbol: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        return self.watch_my_liquidations_for_symbols(Value::List(vec![symbol.clone()]), &[since.clone(), limit.clone(), params.clone()]).await;

    Value::Null
}

/*
 * @method
 * @name gate#watchMyLiquidationsForSymbols
 * @description watch the private liquidations of a trading pair
 * @see https://www.gate.io/docs/developers/futures/ws/en/#liquidates-api
 * @see https://www.gate.io/docs/developers/delivery/ws/en/#liquidates-api
 * @see https://www.gate.io/docs/developers/options/ws/en/#liquidates-channel
 * @param {string[]} symbols unified CCXT market symbols
 * @param {int} [since] the earliest time in ms to fetch liquidations for
 * @param {int} [limit] the maximum number of liquidation structures to retrieve
 * @param {object} [params] exchange specific parameters for the gate api endpoint
 * @returns {object} an array of [liquidation structures]{@link https://github.com/ccxt/ccxt/wiki/Manual#liquidation-structure}
 */
    pub async fn watch_my_liquidations_for_symbols(&mut self, mut symbols: Value, optional_args: &[Value]) -> Value {
        let mut since = get_arg(optional_args, 0, Value::Null);
        let mut limit = get_arg(optional_args, 1, Value::Null);
        let mut params = get_arg(optional_args, 2, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        if is_equal(&self.markets, &Value::Null) {
            self.load_markets(&[]).await;
        }
        symbols = self.market_symbols(&[symbols.clone(), Value::Null, Value::Bool(true), Value::Bool(true)]);
        let mut market: Value = self.get_market_from_symbols(&[symbols.clone()]);
        let mut type_var: Value = Value::Null;
        let mut query: Value = Value::Null;
        { let __destr_tmp = self.handle_market_type_and_params(Value::Str("watchMyLiquidationsForSymbols".to_string()), &[market.clone(), params.clone()]); type_var = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut typeId: Value = self.get_supported_mapping(type_var.clone(), &[Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("future".to_string(), Value::Str("futures".to_string()));
                m.insert("swap".to_string(), Value::Str("futures".to_string()));
                m.insert("option".to_string(), Value::Str("options".to_string()));
            m
        })]);
        let mut subType: Value = Value::Null;
        { let __destr_tmp = self.handle_sub_type_and_params(Value::Str("watchMyLiquidationsForSymbols".to_string()), &[market.clone(), query.clone()]); subType = get_value(&__destr_tmp, &Value::Int(0)); query = get_value(&__destr_tmp, &Value::Int(1)); }
        let mut isInverse: Value = Value::Bool(is_equal(&subType, &Value::Str("inverse".to_string())));
        let mut url: Value = self.get_url_by_market_type(type_var.clone(), &[isInverse.clone()]);
        let mut payload: Value = Value::List(vec![]);
        let mut messageHash: Value = Value::Str("".to_string());
        if is_true(&self.is_empty(symbols.clone())) {
            if !is_equal(&typeId, &Value::Str("futures".to_string())) && !is_true(&isInverse) {
                panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchMyLiquidationsForSymbols() does not support listening to all symbols, you must call watchMyLiquidations() instead for each symbol you wish to watch.".to_string()))));
            }
            messageHash = Value::Str("myLiquidations".to_string());
            append_to_array(&mut payload, Value::Str("!all".to_string()));
        }  else {
            let mut symbolsLength: Value = get_array_length(&symbols);
            if !is_equal(&symbolsLength, &Value::Int(1)) {
                panic!("{}", crate::exchange_errors::bad_request(add(&self.id, &Value::Str(" watchMyLiquidationsForSymbols() only allows one symbol at a time. To listen to several symbols call watchMyLiquidationsForSymbols() several times.".to_string()))));
            }
            messageHash = add(&Value::Str("myLiquidations::".to_string()), &get_value(&symbols, &Value::Int(0)));
            append_to_array(&mut payload, get_value(&market, &Value::Str("id".to_string())));
        }
        let mut channel: Value = add(&typeId, &Value::Str(".liquidates".to_string()));
        let mut newLiquidations: Value = self.subscribe_private(url.clone(), messageHash.clone(), payload.clone(), channel.clone(), query.clone(), &[Value::Bool(true)]).await;
        if is_true(&self.newUpdates) {
            return newLiquidations;
        }
        return self.filter_by_symbols_since_limit(self.liquidations.clone(), &[symbols.clone(), since.clone(), limit.clone(), Value::Bool(true)]);

    Value::Null
}

    pub fn handle_liquidation(&mut self, mut client: Value, mut message: Value) {
        //
        // future / delivery
        //     {
        //         "channel":"futures.liquidates",
        //         "event":"update",
        //         "time":1541505434,
        //         "time_ms":1541505434123,
        //         "result":[
        //            {
        //               "entry_price":209,
        //               "fill_price":215.1,
        //               "left":0,
        //               "leverage":0.0,
        //               "liq_price":213,
        //               "margin":0.007816722941,
        //               "mark_price":213,
        //               "order_id":4093362,
        //               "order_price":215.1,
        //               "size":-124,
        //               "time":1541486601,
        //               "time_ms":1541486601123,
        //               "contract":"BTC_USD",
        //               "user":"1040xxxx"
        //            }
        //         ]
        //     }
        // option
        //    {
        //        "channel":"options.liquidates",
        //        "event":"update",
        //        "time":1630654851,
        //        "result":[
        //           {
        //              "user":"1xxxx",
        //              "init_margin":1190,
        //              "maint_margin":1042.5,
        //              "order_margin":0,
        //              "time":1639051907,
        //              "time_ms":1639051907000
        //           }
        //        ]
        //    }
        //
        let mut rawLiquidations: Value = self.safe_list_k(message.clone(), "result", &[Value::List(vec![])]);
        let mut newLiquidations: Value = Value::List(vec![]);
        if is_equal(&self.liquidations, &Value::Null) {
            let mut limit: Value = self.safe_integer_k(self.options.clone(), "liquidationsLimit", &[Value::Int(1000)]);
            self.liquidations = ArrayCache::new(limit.clone());
        }
        let mut cache: Value = self.liquidations.clone();
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_349: bool = true;
            while { if !__for_first_349 { i = add(&i, &Value::Int(1)); } __for_first_349 = false; is_less_than(&i, &get_array_length(&rawLiquidations)) } {
            let mut rawLiquidation: Value = get_value(&rawLiquidations, &i);
            let mut rawLiquidation: Value = get_value(&rawLiquidations, &i);
            let mut liquidation: Value = self.parse_ws_liquidation(rawLiquidation.clone(), &[]);
            cache.append(liquidation.clone());
            let mut symbol: Value = self.safe_string_k(liquidation.clone(), "symbol", &[]);
            let mut symbolLiquidations: Value = self.safe_value(cache.clone(), symbol.clone(), &[Value::List(vec![])]);
            client.resolve(&[symbolLiquidations.clone(), add(&Value::Str("myLiquidations::".to_string()), &symbol)]);
        }
        }
        client.resolve(&[newLiquidations.clone(), Value::Str("myLiquidations".to_string())]);
}

    pub fn parse_ws_liquidation(&self, mut liquidation: Value, optional_args: &[Value]) -> Value {
        let mut market = get_arg(optional_args, 0, Value::Null);
        //
        // future / delivery
        //    {
        //        "entry_price": 209,
        //        "fill_price": 215.1,
        //        "left": 0,
        //        "leverage": 0.0,
        //        "liq_price": 213,
        //        "margin": 0.007816722941,
        //        "mark_price": 213,
        //        "order_id": 4093362,
        //        "order_price": 215.1,
        //        "size": -124,
        //        "time": 1541486601,
        //        "time_ms": 1541486601123,
        //        "contract": "BTC_USD",
        //        "user": "1040xxxx"
        //    }
        // option
        //    {
        //        "user": "1xxxx",
        //        "init_margin": 1190,
        //        "maint_margin": 1042.5,
        //        "order_margin": 0,
        //        "time": 1639051907,
        //        "time_ms": 1639051907000
        //    }
        //
        let mut marketId: Value = self.safe_string_k(liquidation.clone(), "contract", &[]);
        market = self.safe_market(&[marketId.clone(), market.clone()]);
        let mut timestamp: Value = self.safe_integer_k(liquidation.clone(), "time_ms", &[]);
        let mut originalSize: Value = self.safe_string_k(liquidation.clone(), "size", &[]);
        let mut left: Value = self.safe_string_k(liquidation.clone(), "left", &[]);
        let mut amount: Value = crate::precise::Precise::stringAbs(&crate::precise::Precise::stringSub(&originalSize, &left));
        return self.safe_liquidation(Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("info".to_string(), liquidation.clone());
        m.insert("symbol".to_string(), self.safe_symbol(marketId.clone(), &[market.clone()]));
        m.insert("contracts".to_string(), self.parse_number(amount.clone(), &[]));
        m.insert("contractSize".to_string(), self.safe_number_k(market.clone(), "contractSize", &[]));
        m.insert("price".to_string(), self.safe_number_k(liquidation.clone(), "fill_price", &[]));
        m.insert("baseValue".to_string(), Value::Null);
        m.insert("quoteValue".to_string(), Value::Null);
        m.insert("timestamp".to_string(), timestamp.clone());
        m.insert("datetime".to_string(), self.iso8601(timestamp.clone()));
    m
}), &[]);

    Value::Null
}

    pub fn handle_error_message(&self, mut client: Value, mut message: Value) -> Value {
        //
        //    {
        //        "time": 1647274664,
        //        "channel": "futures.orders",
        //        "event": "subscribe",
        //        "error": { code: 2, message: "unknown contract BTC_USDT_20220318" },
        //    }
        //    {
        //      "time": 1647276473,
        //      "channel": "futures.orders",
        //      "event": "subscribe",
        //      "error": {
        //        "code": 4,
        //        "message": "{"label":"INVALID_KEY","message":"Invalid key provided"}\n"
        //      },
        //      "result": null
        //    }
        //    {
        //       header: {
        //         response_time: '1718551891329',
        //         status: '400',
        //         channel: 'spot.order_place',
        //         event: 'api',
        //         client_id: '81.34.68.6-0xc16375e2c0',
        //         conn_id: '9539116e0e09678f'
        //       },
        //       data: { errs: { label: 'AUTHENTICATION_FAILED', message: 'Not login' } },
        //       request_id: '10406147'
        //     }
        //     {
        //         "time": 1739853211,
        //         "time_ms": 1739853211201,
        //         "id": 1,
        //         "conn_id": "62f2c1dabbe186d7",
        //         "trace_id": "cdb02a8c0b61086b2fe6f8fad2f98c54",
        //         "channel": "spot.trades",
        //         "event": "subscribe",
        //         "payload": [
        //             "LUNARLENS_USDT",
        //             "ETH_USDT"
        //         ],
        //         "error": {
        //             "code": 2,
        //             "message": "unknown currency pair: LUNARLENS_USDT"
        //         },
        //         "result": {
        //             "status": "fail"
        //         },
        //         "requestId": "cdb02a8c0b61086b2fe6f8fad2f98c54"
        //     }
        //
        let mut data: Value = self.safe_dict_k(message.clone(), "data", &[]);
        let mut errs: Value = self.safe_dict_k(data.clone(), "errs", &[]);
        let mut error: Value = self.safe_dict_k(message.clone(), "error", &[errs.clone()]);
        let mut code: Value = self.safe_string2(error.clone(), Value::Str("code".to_string()), Value::Str("label".to_string()), &[]);
        let mut id: Value = self.safe_string_n(message.clone(), Value::List(vec![Value::Str("id".to_string()), Value::Str("requestId".to_string()), Value::Str("request_id".to_string())]), &[]);
        if !is_equal(&error, &Value::Null) {
            let mut messageHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".to_string())), id.clone(), &[]);
            let _try_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.throw_exactly_matched_exception(get_value(&get_value(&self.exceptions, &Value::Str("ws".to_string())), &Value::Str("exact".to_string())), code.clone(), self.json(message.clone()));
                self.throw_exactly_matched_exception(get_value(&self.exceptions, &Value::Str("exact".to_string())), code.clone(), self.json(errs.clone()));
                let mut errorMessage: Value = self.safe_string_k(error.clone(), "message", &[self.safe_string(errs.clone(), Value::Str("message".to_string()), &[])]);
                self.throw_broadly_matched_exception(get_value(&get_value(&self.exceptions, &Value::Str("ws".to_string())), &Value::Str("broad".to_string())), errorMessage.clone(), self.json(message.clone()));
                panic!("{}", crate::exchange_errors::exchange_error(self.json(message.clone())));
             #[allow(unreachable_code)] { Value::Null }}));
if let Err(_try_err) = _try_result { let e: Value = panic_to_value(_try_err);
                client.reject(&[e.clone(), messageHash.clone()]);
                if is_true(&(!is_equal(&messageHash, &Value::Null))) && is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash)))) {
                    remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash);
                }
                // remove subscriptions for watchSymbols
                let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
                if is_true(&(!is_equal(&channel, &Value::Null))) && is_true(&(is_greater_than(&get_index_of(&channel, &Value::Str(".".to_string())), &Value::Int(0)))) {
                    let mut parsedChannel: Value = split(&channel, &Value::Str(".".to_string()));
                    let mut payload: Value = self.safe_list_k(message.clone(), "payload", &[Value::List(vec![])]);
                    {
                                                let mut i: Value = Value::Int(0);
                        let mut __for_first_350: bool = true;
                        while { if !__for_first_350 { i = add(&i, &Value::Int(1)); } __for_first_350 = false; is_less_than(&i, &get_array_length(&payload)) } {
                        let mut marketType: Value = ternary(is_equal(&get_value(&parsedChannel, &Value::Int(0)), &Value::Str("futures".to_string())), Value::Str("swap".to_string()), get_value(&parsedChannel, &Value::Int(0)));
                        let mut symbol: Value = self.safe_symbol(get_value(&payload, &i), &[Value::Null, Value::Str("_".to_string()), marketType.clone()]);
                        let mut messageHashSymbol: Value = add(&add(&get_value(&parsedChannel, &Value::Int(1)), &Value::Str(":".to_string())), &symbol);
                        if is_true(&(!is_equal(&messageHashSymbol, &Value::Null))) && is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHashSymbol)))) {
                            remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &messageHashSymbol);
                        }
                    }
                    }
                }
            }
            if is_true(&(!is_equal(&id, &Value::Null))) && is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &id)))) {
                remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &id);
            }
            return Value::Bool(true);
        }
        return Value::Bool(false);

    Value::Null
}

    pub fn handle_balance_subscription(&mut self, mut client: Value, mut message: Value, optional_args: &[Value]) {
        let mut subscription = get_arg(optional_args, 0, Value::Null);
        self.balance = Value::Map({
            let mut m = indexmap::IndexMap::new();
            m
        });
}

    pub fn handle_subscription_status(&mut self, mut client: Value, mut message: Value) {
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[]);
        let mut methods: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("balance".to_string(), Value::Str("handle_balance_subscription".to_string()).clone());
                m.insert("spot.order_book_update".to_string(), Value::Str("handle_order_book_subscription".to_string()).clone());
                m.insert("futures.order_book_update".to_string(), Value::Str("handle_order_book_subscription".to_string()).clone());
                m.insert("options.order_book_update".to_string(), Value::Str("handle_order_book_subscription".to_string()).clone());
            m
        });
        let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
        if is_equal(&id, &Value::Null) {
            return;
        }
        if is_true(&Value::Bool(in_op(&methods, &channel))) {
            let mut subscriptionHash: Value = self.safe_string(get_value(&client, &Value::Str("subscriptions".to_string())), id.clone(), &[]);
            let mut subscription: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), subscriptionHash.clone(), &[]);
            let mut method: Value = get_value(&methods, &channel);
            let mut method: Value = get_value(&methods, &channel);
            self.dispatch_ws_handler(&method, &[client.clone(), message.clone(), subscription.clone()]);
        }
        if is_true(&Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &id))) {
            if !is_equal(&id, &Value::Null) {
                remove(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &id);
            }
        }
}

    pub fn handle_un_subscribe(&mut self, mut client: Value, mut message: Value) {
        //
        // {
        //     "time":1725534679,
        //     "time_ms":1725534679786,
        //     "id":2,
        //     "conn_id":"fac539b443fd7002",
        //     "trace_id":"efe1d282b630b4aa266b84bee177791a",
        //     "channel":"spot.trades",
        //     "event":"unsubscribe",
        //     "payload":[
        //        "LTC_USDT"
        //     ],
        //     "result":{
        //        "status":"success"
        //     },
        //     "requestId":"efe1d282b630b4aa266b84bee177791a"
        // }
        //
        let mut id: Value = self.safe_string_k(message.clone(), "id", &[]);
        let mut keys: Value = object_keys(&get_value(&client, &Value::Str("subscriptions".to_string())));
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_352: bool = true;
            while { if !__for_first_352 { i = add(&i, &Value::Int(1)); } __for_first_352 = false; is_less_than(&i, &get_array_length(&keys)) } {
            let mut messageHash: Value = get_value(&keys, &i);
            let mut messageHash: Value = get_value(&keys, &i);
            if !is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash)))) {
                continue;
            }
            if is_true(&Value::Bool(starts_with(&messageHash, &Value::Str("unsubscribe".to_string())))) {
                let mut subscription: Value = get_value(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash);
                let mut subId: Value = self.safe_string_k(subscription.clone(), "id", &[]);
                if !is_equal(&id, &subId) {
                    continue;
                }
                let mut messageHashes: Value = self.safe_list_k(subscription.clone(), "messageHashes", &[Value::List(vec![])]);
                let mut subMessageHashes: Value = self.safe_list_k(subscription.clone(), "subMessageHashes", &[Value::List(vec![])]);
                {
                                        let mut j: Value = Value::Int(0);
                    let mut __for_first_351: bool = true;
                    while { if !__for_first_351 { j = add(&j, &Value::Int(1)); } __for_first_351 = false; is_less_than(&j, &get_array_length(&messageHashes)) } {
                    let mut unsubHash: Value = get_value(&messageHashes, &j);
                    let mut unsubHash: Value = get_value(&messageHashes, &j);
                    let mut subHash: Value = get_value(&subMessageHashes, &j);
                    let mut subHash: Value = get_value(&subMessageHashes, &j);
                    self.clean_unsubscription(client.clone(), subHash.clone(), unsubHash.clone(), &[]);
                }
                }
                self.clean_cache(subscription.clone());
            }
        }
        }
}

    pub fn handle_message(&mut self, mut client: Value, mut message: Value) {
        //
        // subscribe
        //    {
        //        "time": 1649062304,
        //        "id": 1649062303,
        //        "channel": "spot.candlesticks",
        //        "event": "subscribe",
        //        "result": { status: "success" }
        //    }
        //
        // candlestick
        //    {
        //        "time": 1649063328,
        //        "channel": "spot.candlesticks",
        //        "event": "update",
        //        "result": {
        //          "t": "1649063280",
        //          "v": "58932.23174896",
        //          "c": "45966.47",
        //          "h": "45997.24",
        //          "l": "45966.47",
        //          "o": "45975.18",
        //          "n": "1m_BTC_USDT",
        //          "a": "1.281699"
        //        }
        //     }
        //
        //  orders
        //   {
        //       "time": 1630654851,
        //       "channel": "options.orders", or futures.orders or spot.orders
        //       "event": "update",
        //       "result": [
        //          {
        //             "contract": "BTC_USDT-20211130-65000-C",
        //             "create_time": 1637897000,
        //               (...)
        //       ]
        //   }
        // orderbook
        //   {
        //       "time": 1649770525,
        //       "channel": "spot.order_book_update",
        //       "event": "update",
        //       "result": {
        //         "t": 1649770525653,
        //         "e": "depthUpdate",
        //         "E": 1649770525,
        //         "s": "LTC_USDT",
        //         "U": 2622525645,
        //         "u": 2622525665,
        //         "b": [
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array]
        //         ],
        //         "a": [
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array], [Array],
        //           [Array]
        //         ]
        //       }
        //     }
        //
        // balance update
        //
        //    {
        //        "time": 1653664351,
        //        "channel": "spot.balances",
        //        "event": "update",
        //        "result": [
        //          {
        //            "timestamp": "1653664351",
        //            "timestamp_ms": "1653664351017",
        //            "user": "10406147",
        //            "currency": "LTC",
        //            "change": "-0.0002000000000000",
        //            "total": "0.09986000000000000000",
        //            "available": "0.09986000000000000000"
        //          }
        //        ]
        //    }
        //
        if is_equal(&self.handle_error_message(client.clone(), message.clone()), &Value::Bool(true)) {
            return;
        }
        let mut event: Value = self.safe_string_k(message.clone(), "event", &[]);
        if is_equal(&event, &Value::Str("subscribe".to_string())) {
            self.handle_subscription_status(client.clone(), message.clone());
            return;
        }
        if is_equal(&event, &Value::Str("unsubscribe".to_string())) {
            self.handle_un_subscribe(client.clone(), message.clone());
            return;
        }
        let mut channel: Value = self.safe_string_k(message.clone(), "channel", &[Value::Str("".to_string())]);
        // after supporting more method we can create a mapping for this
        if is_equal(&channel, &Value::Str("spot.obu".to_string())) {
            self.handle_order_book(client.clone(), message.clone());
            return;
        }
        let mut channelParts: Value = split(&channel, &Value::Str(".".to_string()));
        let mut channelType: Value = self.safe_value(channelParts.clone(), Value::Int(1), &[]);
        let mut v4Methods: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("usertrades".to_string(), Value::Str("handle_my_trades".to_string()).clone());
                m.insert("candlesticks".to_string(), Value::Str("handle_ohlcv".to_string()).clone());
                m.insert("orders".to_string(), Value::Str("handle_order".to_string()).clone());
                m.insert("autoorders".to_string(), Value::Str("handle_order".to_string()).clone());
                m.insert("priceorders".to_string(), Value::Str("handle_order".to_string()).clone());
                m.insert("positions".to_string(), Value::Str("handle_positions".to_string()).clone());
                m.insert("tickers".to_string(), Value::Str("handle_ticker".to_string()).clone());
                m.insert("book_ticker".to_string(), Value::Str("handle_bid_ask".to_string()).clone());
                m.insert("trades".to_string(), Value::Str("handle_trades".to_string()).clone());
                m.insert("order_book_update".to_string(), Value::Str("handle_order_book".to_string()).clone());
                m.insert("balances".to_string(), Value::Str("handle_balance".to_string()).clone());
                m.insert("liquidates".to_string(), Value::Str("handle_liquidation".to_string()).clone());
            m
        });
        let mut method: Value = self.safe_value(v4Methods.clone(), channelType.clone(), &[]);
        if !is_equal(&method, &Value::Null) {
            self.dispatch_ws_handler(&method, &[client.clone(), message.clone()]);
        }
        let mut requestId: Value = self.safe_string_k(message.clone(), "request_id", &[]);
        if is_equal(&requestId, &Value::Str("authenticated".to_string())) {
            self.handle_authentication_message(client.clone(), message.clone());
            return;
        }
        if !is_equal(&requestId, &Value::Null) {
            let mut data: Value = self.safe_dict_k(message.clone(), "data", &[]);
            // use safeValue as result may be Array or an Object
            let mut result: Value = self.safe_value_k(data.clone(), "result", &[]);
            let mut ack: Value = self.safe_bool_k(message.clone(), "ack", &[]);
            if !is_equal(&ack, &Value::Bool(true)) {
                client.resolve(&[result.clone(), requestId.clone()]);
            }
        }
}

    pub fn get_url_by_market(&self, mut market: Value) -> Value {
        let mut baseUrl: Value = get_value(&get_value(&self.urls, &Value::Str("api".to_string())), &get_value(&market, &Value::Str("type".to_string())));
        if is_equal(&get_value(&market, &Value::Str("contract".to_string())), &Value::Bool(true)) {
            return ternary(is_true(&(is_equal(&get_value(&market, &Value::Str("linear".to_string())), &Value::Bool(true)))), get_value(&baseUrl, &Value::Str("usdt".to_string())), get_value(&baseUrl, &Value::Str("btc".to_string())));
        }  else {
            return baseUrl;
        }

    Value::Null
}

    pub fn get_type_by_market(&self, mut market: Value) -> Value {
        if is_equal(&market, &Value::Null) {
            return Value::Null;
        }
        if is_equal(&get_value(&market, &Value::Str("spot".to_string())), &Value::Bool(true)) {
            return Value::Str("spot".to_string());
        }  else if is_equal(&get_value(&market, &Value::Str("option".to_string())), &Value::Bool(true)) {
            return Value::Str("options".to_string());
        }  else {
            return Value::Str("futures".to_string());
        }

    Value::Null
}

    pub fn get_url_by_market_type(&self, mut type_var: Value, optional_args: &[Value]) -> Value {
        let mut isInverse = get_arg(optional_args, 0, Value::Bool(false));
        let mut api: Value = get_value(&self.urls, &Value::Str("api".to_string()));
        let mut url: Value = self.safe_value(api.clone(), type_var.clone(), &[]);
        if is_true(&(is_equal(&type_var, &Value::Str("swap".to_string())))) || is_true(&(is_equal(&type_var, &Value::Str("future".to_string())))) {
            return ternary(is_true(&isInverse), get_value(&url, &Value::Str("btc".to_string())), get_value(&url, &Value::Str("usdt".to_string())));
        }  else {
            return url;
        }

    Value::Null
}

    pub fn get_market_type_by_url(&self, mut url: Value) -> Value {
        let mut findBy: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("op-".to_string(), Value::Str("option".to_string()));
                m.insert("delivery".to_string(), Value::Str("future".to_string()));
                m.insert("fx".to_string(), Value::Str("swap".to_string()));
            m
        });
        let mut keys: Value = object_keys(&findBy);
        {
                        let mut i: Value = Value::Int(0);
            let mut __for_first_353: bool = true;
            while { if !__for_first_353 { i = add(&i, &Value::Int(1)); } __for_first_353 = false; is_less_than(&i, &get_array_length(&keys)) } {
            let mut key: Value = get_value(&keys, &i);
            let mut key: Value = get_value(&keys, &i);
            let mut value: Value = get_value(&findBy, &key);
            let mut value: Value = get_value(&findBy, &key);
            if is_greater_than_or_equal(&get_index_of(&url, &key), &Value::Int(0)) {
                return value;
            }
        }
        }
        return Value::Str("spot".to_string());

    Value::Null
}

    pub fn request_id(&mut self) -> Value {
        // their support said that reqid must be an int32, not documented
        self.lock_id(&[]);
        let mut reqid: Value = self.sum(&[self.safe_integer_k(self.options.clone(), "reqid", &[Value::Int(0)]), Value::Int(1)]);
        add_element_to_object(&mut self.options, &Value::Str("reqid".to_string()), reqid.clone());
        self.unlock_id(&[]);
        return reqid;

    Value::Null
}

    pub async fn subscribe_public(&mut self, mut url: Value, mut messageHash: Value, mut payload: Value, mut channel: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut subscription = get_arg(optional_args, 1, Value::Null);
        let mut requestId: Value = self.request_id();
        let mut time: Value = self.seconds();
        let mut request: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), requestId.clone());
                m.insert("time".to_string(), time.clone());
                m.insert("channel".to_string(), channel.clone());
                m.insert("event".to_string(), Value::Str("subscribe".to_string()));
                m.insert("payload".to_string(), payload.clone());
            m
        });
        if !is_equal(&subscription, &Value::Null) {
            let mut client: Value = self.client(&[url.clone()]);
            if !is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash)))) {
                let mut tempSubscriptionHash: Value = to_string_val(&requestId);
                add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &tempSubscriptionHash, messageHash.clone());
            }
        }
        let mut message: Value = self.extend(request.clone(), &[params.clone()]);
        return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), subscription.clone()]).await;

    Value::Null
}

    pub async fn subscribe_public_multiple(&mut self, mut url: Value, mut messageHashes: Value, mut payload: Value, mut channel: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut requestId: Value = self.request_id();
        let mut time: Value = self.seconds();
        let mut request: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), requestId.clone());
                m.insert("time".to_string(), time.clone());
                m.insert("channel".to_string(), channel.clone());
                m.insert("event".to_string(), Value::Str("subscribe".to_string()));
                m.insert("payload".to_string(), payload.clone());
            m
        });
        let mut message: Value = self.extend(request.clone(), &[params.clone()]);
        return self.watch_multiple(url.clone(), messageHashes.clone(), &[message.clone(), messageHashes.clone()]).await;

    Value::Null
}

    pub async fn un_subscribe_public_multiple(&mut self, mut url: Value, mut topic: Value, mut symbols: Value, mut messageHashes: Value, mut subMessageHashes: Value, mut payload: Value, mut channel: Value, optional_args: &[Value]) -> Value {
        let mut params = get_arg(optional_args, 0, Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}));
        let mut requestId: Value = self.request_id();
        let mut time: Value = self.seconds();
        let mut request: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), requestId.clone());
                m.insert("time".to_string(), time.clone());
                m.insert("channel".to_string(), channel.clone());
                m.insert("event".to_string(), Value::Str("unsubscribe".to_string()));
                m.insert("payload".to_string(), payload.clone());
            m
        });
        let mut sub: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), to_string_val(&requestId));
                m.insert("topic".to_string(), topic.clone());
                m.insert("unsubscribe".to_string(), Value::Bool(true));
                m.insert("messageHashes".to_string(), messageHashes.clone());
                m.insert("subMessageHashes".to_string(), subMessageHashes.clone());
                m.insert("symbols".to_string(), symbols.clone());
            m
        });
        let mut message: Value = self.extend(request.clone(), &[params.clone()]);
        return self.watch_multiple(url.clone(), messageHashes.clone(), &[message.clone(), messageHashes.clone(), sub.clone()]).await;

    Value::Null
}

    pub async fn authenticate(&mut self, mut url: Value, mut messageType: Value) -> Value {
        let mut channel: Value = add(&messageType, &Value::Str(".login".to_string()));
        let mut client: Value = self.client(&[url.clone()]);
        let mut messageHash: Value = Value::Str("authenticated".to_string());
        let mut future: Value = client.reusable_future(messageHash.clone());
        let mut authenticated: Value = self.safe_value(get_value(&client, &Value::Str("subscriptions".to_string())), messageHash.clone(), &[]);
        if is_equal(&authenticated, &Value::Null) {
            return self.request_private(url.clone(), Value::Map({
    let mut m = indexmap::IndexMap::new();
    m
}), channel.clone(), &[messageHash.clone()]).await;
        }
        return future;

    Value::Null
}

    pub fn handle_authentication_message(&self, mut client: Value, mut message: Value) {
        let mut messageHash: Value = Value::Str("authenticated".to_string());
        let mut future: Value = self.safe_value(get_value(&client, &Value::Str("futures".to_string())), messageHash.clone(), &[]);
        future.resolve(&[Value::Bool(true)]);
}

    pub async fn request_private(&mut self, mut url: Value, mut reqParams: Value, mut channel: Value, optional_args: &[Value]) -> Value {
        let mut requestId = get_arg(optional_args, 0, Value::Null);
        self.check_required_credentials(&[]);
        // uid is required for some subscriptions only so it's not a part of required credentials
        let mut event: Value = Value::Str("api".to_string());
        if is_equal(&requestId, &Value::Null) {
            let mut reqId: Value = self.request_id();
            requestId = to_string_val(&reqId);
        }
        let mut messageHash: Value = requestId.clone();
        let mut time: Value = self.seconds();
        // unfortunately, PHP demands double quotes for the escaped newline symbol
        let mut signatureString: Value = join(&Value::List(vec![event.clone(), channel.clone(), self.json(reqParams.clone()), to_string_val(&time)]), &Value::Str("\n".to_string())); // eslint-disable-line quotes
        let mut signature: Value = self.hmac(self.encode(signatureString.clone()), self.encode(self.secret.clone()), Value::Str("sha512".to_string()), &[Value::Str("hex".to_string())]);
        let mut payload: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("req_id".to_string(), requestId.clone());
                m.insert("timestamp".to_string(), to_string_val(&time));
                m.insert("api_key".to_string(), self.apiKey.clone());
                m.insert("signature".to_string(), signature.clone());
                m.insert("req_param".to_string(), reqParams.clone());
            m
        });
        if is_true(&(is_equal(&channel, &Value::Str("spot.order_place".to_string())))) || is_true(&(is_equal(&channel, &Value::Str("futures.order_place".to_string())))) {
            add_element_to_object(&mut payload, &Value::Str("req_header".to_string()), Value::Map({
    let mut m = indexmap::IndexMap::new();
        m.insert("X-Gate-Channel-Id".to_string(), Value::Str("ccxt".to_string()));
    m
}));
        }
        let mut request: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), requestId.clone());
                m.insert("time".to_string(), time.clone());
                m.insert("channel".to_string(), channel.clone());
                m.insert("event".to_string(), event.clone());
                m.insert("payload".to_string(), payload.clone());
            m
        });
        return self.watch(url.clone(), messageHash.clone(), &[request.clone(), messageHash.clone(), requestId.clone()]).await;

    Value::Null
}

    pub async fn subscribe_private(&mut self, mut url: Value, mut messageHash: Value, mut payload: Value, mut channel: Value, mut params: Value, optional_args: &[Value]) -> Value {
        let mut requiresUid = get_arg(optional_args, 0, Value::Bool(false));
        self.check_required_credentials(&[]);
        // uid is required for some subscriptions only so it's not a part of required credentials
        if is_true(&requiresUid) {
            if is_equal(&self.uid, &Value::Null) || is_equal(&get_array_length(&self.uid), &Value::Int(0)) {
                panic!("{}", crate::exchange_errors::arguments_required(add(&self.id, &Value::Str(" requires uid to subscribe".to_string()))));
            }
            let mut idArray: Value = Value::List(vec![self.uid.clone()]);
            if is_equal(&payload, &Value::Null) {
                payload = idArray.clone();
            }  else {
                payload = self.array_concat(idArray.clone(), payload.clone());
            }
        }
        let mut time: Value = self.seconds();
        let mut event: Value = Value::Str("subscribe".to_string());
        let mut signaturePayload: Value = add(&add(&add(&add(&add(&add(&add(&Value::Str("channel=".to_string()), &channel), &Value::Str("&".to_string())), &Value::Str("event=".to_string())), &event), &Value::Str("&".to_string())), &Value::Str("time=".to_string())), &to_string_val(&time));
        let mut signature: Value = self.hmac(self.encode(signaturePayload.clone()), self.encode(self.secret.clone()), Value::Str("sha512".to_string()), &[Value::Str("hex".to_string())]);
        let mut auth: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("method".to_string(), Value::Str("api_key".to_string()));
                m.insert("KEY".to_string(), self.apiKey.clone());
                m.insert("SIGN".to_string(), signature.clone());
            m
        });
        let mut requestId: Value = self.request_id();
        let mut request: Value = Value::Map({
            let mut m = indexmap::IndexMap::new();
                m.insert("id".to_string(), requestId.clone());
                m.insert("time".to_string(), time.clone());
                m.insert("channel".to_string(), channel.clone());
                m.insert("event".to_string(), event.clone());
                m.insert("auth".to_string(), auth.clone());
            m
        });
        if !is_equal(&payload, &Value::Null) {
            add_element_to_object(&mut request, &Value::Str("payload".to_string()), payload.clone());
        }
        let mut client: Value = self.client(&[url.clone()]);
        if !is_true(&(Value::Bool(in_op(&get_value(&client, &Value::Str("subscriptions".to_string())), &messageHash)))) {
            let mut tempSubscriptionHash: Value = to_string_val(&requestId);
            // in case of authenticationError we will throw
            add_element_to_object(&mut get_value(&client, &Value::Str("subscriptions".to_string())), &tempSubscriptionHash, messageHash.clone());
        }
        let mut message: Value = self.extend(request.clone(), &[params.clone()]);
        return self.watch(url.clone(), messageHash.clone(), &[message.clone(), messageHash.clone(), messageHash.clone()]).await;

    Value::Null
}
}