binance-async-api 0.2.4

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

use serde::{
    Deserialize,
    Serialize,
};
use serde_repr::{
    Deserialize_repr,
    Serialize_repr,
};
use url::Url;
use reqwest::Method;

use crate::{
    streams::BinanceStream,
    requests::{
        Request,
        ApiKeyHeaderRequest,
        SignedRequest,
        BinanceErrorMsg,
    },
    model::{
        Side,
        BookLevel,
        SelfTradePreventionMode,
        utils::{
            treat_error_as_none,
            serialize_bool_as_str,
            serialize_opt_bool_as_str,
        },
    },
};


#[derive(Debug, Clone, Deserialize)]
pub struct AggTradeEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "a")]
    pub id: usize,
    #[serde(rename = "p")]
    pub price: String,
    #[serde(rename = "q")]
    pub qty: String,
    #[serde(rename = "f")]
    pub first_trade_id: usize,
    #[serde(rename = "l")]
    pub last_trade_id: usize,
    #[serde(rename = "T")]
    pub trade_time: usize,
    #[serde(rename = "m")]
    pub buyer_is_maker: bool,
}

#[derive(Debug, Clone, Copy)]
pub struct AggTradeStream<'a> {
    pub symbol: &'a str,
}

impl<'a> BinanceStream for AggTradeStream<'a> {
    type Event = AggTradeEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@aggTrade", ws_base_url, self.symbol.to_lowercase()))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct MarkPriceEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "p")]
    pub mark_price: String,
    #[serde(rename = "i")]
    pub index_price: String,
    #[serde(rename = "P")]
    pub estimated_settelment_price: String,
    #[serde(rename = "r")]
    pub funding_fee_rate: String,
    #[serde(rename = "T")]
    pub next_funding_time: usize,
}

#[derive(Debug, Clone, Copy)]
#[allow(non_camel_case_types)]
pub enum MarkPriceStreamUpdateSpeed {
    ms1000,
    ms3000,
}

#[derive(Debug, Clone, Copy)]
pub struct MarkPriceStream<'a> {
    pub symbol: &'a str,
    pub update_speed: MarkPriceStreamUpdateSpeed,
}

impl<'a> BinanceStream for MarkPriceStream<'a> {
    type Event = MarkPriceEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let update_speed_str = match self.update_speed {
            MarkPriceStreamUpdateSpeed::ms1000 => "@1s",
            MarkPriceStreamUpdateSpeed::ms3000 => "",
        };
        Url::from_str(&format!("{}/ws/{}@markPrice{}", ws_base_url, self.symbol.to_lowercase(), update_speed_str))
    }
}

#[derive(Debug, Clone, Copy)]
pub struct AllMarkPricesStream {
    pub update_speed: MarkPriceStreamUpdateSpeed,
}

impl BinanceStream for AllMarkPricesStream {
    type Event = Vec<MarkPriceEvent>;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let update_speed_str = match self.update_speed {
            MarkPriceStreamUpdateSpeed::ms1000 => "@1s",
            MarkPriceStreamUpdateSpeed::ms3000 => "",
        };
        Url::from_str(&format!("{}/ws/!markPrice@arr{}", ws_base_url, update_speed_str))
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
pub enum KlineInterval {
    #[serde(rename = "1s")]
    m1,
    #[serde(rename = "1s")]
    m3,
    #[serde(rename = "1s")]
    m5,
    #[serde(rename = "1s")]
    m15,
    #[serde(rename = "1s")]
    m30,
    #[serde(rename = "1s")]
    h1,
    #[serde(rename = "1s")]
    h2,
    #[serde(rename = "1s")]
    h4,
    #[serde(rename = "1s")]
    h6,
    #[serde(rename = "1s")]
    h8,
    #[serde(rename = "1s")]
    h12,
    #[serde(rename = "1s")]
    d1,
    #[serde(rename = "1s")]
    d3,
    #[serde(rename = "1s")]
    w1,
    #[serde(rename = "1s")]
    M1,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KlineUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "k")]
    pub kline_update: KlineUpdate,
}

#[derive(Debug, Clone, Deserialize)]
pub struct KlineUpdate {
    #[serde(rename = "t")]
    pub open_time: usize,
    #[serde(rename = "T")]
    pub close_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "i")]
    pub interval: KlineInterval,
    #[serde(rename = "f")]
    pub first_trade_id: usize,
    #[serde(rename = "L")]
    pub last_trade_id: usize,
    #[serde(rename = "o")]
    pub open_price: String,
    #[serde(rename = "c")]
    pub close_price: String,
    #[serde(rename = "h")]
    pub high_price: String,
    #[serde(rename = "l")]
    pub low_price: String,
    #[serde(rename = "v")]
    pub base_asset_volume: String,
    #[serde(rename = "n")]
    pub trade_count: usize,
    #[serde(rename = "x")]
    pub is_closed: bool,
    #[serde(rename = "q")]
    pub quote_asset_volume: String,
    #[serde(rename = "V")]
    pub taker_buy_base_asset_volume: String,
    #[serde(rename = "Q")]
    pub taker_buy_quote_asset_volume: String,
}

#[derive(Debug, Clone, Copy)]
pub struct KlineUpdateStream<'a> {
    pub symbol: &'a str,
    pub interval: KlineInterval,
}

impl<'a> BinanceStream for KlineUpdateStream<'a> {
    type Event = KlineUpdateEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let interval_str = match self.interval {
            KlineInterval::m1 => "1m",
            KlineInterval::m3 => "3m",
            KlineInterval::m5 => "5m",
            KlineInterval::m15 => "15m",
            KlineInterval::m30 => "30m",
            KlineInterval::h1 => "1h",
            KlineInterval::h2 => "2h",
            KlineInterval::h4 => "4h",
            KlineInterval::h6 => "6h",
            KlineInterval::h8 => "8h",
            KlineInterval::h12 => "12h",
            KlineInterval::d1 => "1d",
            KlineInterval::d3 => "3d",
            KlineInterval::w1 => "1w",
            KlineInterval::M1 => "1M",
        };
        Url::from_str(&format!("{}/ws/{}@kline_{}", ws_base_url, self.symbol.to_lowercase(), interval_str))
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ContractType {
    Perpetual,
    CurrentMonth,
    NextMonth,
    CurrentQuarter,
    NextQuarter,
    PerpetualDelivering,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContinuousContractKlineUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "ps")]
    pub pair: String,
    #[serde(rename = "ct")]
    pub contract_type: ContractType,
    #[serde(rename = "k")]
    pub kline_update: ContinuousContractKlineUpdate,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContinuousContractKlineUpdate {
    #[serde(rename = "t")]
    pub open_time: usize,
    #[serde(rename = "T")]
    pub close_time: usize,
    #[serde(rename = "i")]
    pub interval: KlineInterval,
    #[serde(rename = "f")]
    pub first_trade_id: usize,
    #[serde(rename = "L")]
    pub last_trade_id: usize,
    #[serde(rename = "o")]
    pub open_price: String,
    #[serde(rename = "c")]
    pub close_price: String,
    #[serde(rename = "h")]
    pub high_price: String,
    #[serde(rename = "l")]
    pub low_price: String,
    #[serde(rename = "v")]
    pub base_asset_volume: String,
    #[serde(rename = "n")]
    pub trade_count: usize,
    #[serde(rename = "x")]
    pub is_closed: bool,
    #[serde(rename = "q")]
    pub quote_asset_volume: String,
    #[serde(rename = "V")]
    pub taker_buy_base_asset_volume: String,
    #[serde(rename = "Q")]
    pub taker_buy_quote_asset_volume: String,
}

#[derive(Debug, Clone, Copy)]
pub struct ContinuousContractKlineUpdateStream<'a> {
    pub pair: &'a str,
    pub contract_type: ContractType,
    pub interval: KlineInterval,
}

impl<'a> BinanceStream for ContinuousContractKlineUpdateStream<'a> {
    type Event = ContinuousContractKlineUpdateEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let interval_str = match self.interval {
            KlineInterval::m1 => "1m",
            KlineInterval::m3 => "3m",
            KlineInterval::m5 => "5m",
            KlineInterval::m15 => "15m",
            KlineInterval::m30 => "30m",
            KlineInterval::h1 => "1h",
            KlineInterval::h2 => "2h",
            KlineInterval::h4 => "4h",
            KlineInterval::h6 => "6h",
            KlineInterval::h8 => "8h",
            KlineInterval::h12 => "12h",
            KlineInterval::d1 => "1d",
            KlineInterval::d3 => "3d",
            KlineInterval::w1 => "1w",
            KlineInterval::M1 => "1M",
        };
        let contract_type_str = match self.contract_type {
            ContractType::Perpetual => "perpetual",
            ContractType::CurrentMonth => "current_month",
            ContractType::NextMonth => "next_month",
            ContractType::CurrentQuarter => "current_quarter",
            ContractType::NextQuarter => "next_quarter",
            ContractType::PerpetualDelivering => "perpetual_delivering"
        };
        Url::from_str(&format!("{}/ws/{}_{}@continuousKline_{}", ws_base_url, self.pair.to_lowercase(), contract_type_str, interval_str))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct MiniTickerEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "c")]
    pub close_price: String,
    #[serde(rename = "o")]
    pub open_price: String,
    #[serde(rename = "h")]
    pub high_price: String,
    #[serde(rename = "l")]
    pub low_price: String,
    #[serde(rename = "v")]
    pub base_asset_volume: String,
    #[serde(rename = "q")]
    pub quote_asset_volume: String,
}

#[derive(Debug, Clone, Copy)]
pub struct MiniTickerStream<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy)]
pub struct AllMiniTickersStream;

impl<'a> BinanceStream for MiniTickerStream<'a> {
    type Event = MiniTickerEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@miniTicker", ws_base_url, self.symbol.to_lowercase()))
    }
}

impl BinanceStream for AllMiniTickersStream {
    type Event = Vec<MiniTickerEvent>;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!miniTicker@arr", ws_base_url))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct TickerEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "p")]
    pub price_change: String,
    #[serde(rename = "P")]
    pub price_change_percent: String,
    #[serde(rename = "w")]
    pub volume_weighted_avg_price: String,
    #[serde(rename = "c")]
    pub last_price: String,
    #[serde(rename = "Q")]
    pub last_qty: String,
    #[serde(rename = "o")]
    pub open_price: String,
    #[serde(rename = "h")]
    pub high_price: String,
    #[serde(rename = "l")]
    pub low_price: String,
    #[serde(rename = "v")]
    pub base_asset_volume: String,
    #[serde(rename = "q")]
    pub quote_asset_volume: String,
    #[serde(rename = "O")]
    pub open_time: usize,
    #[serde(rename = "C")]
    pub close_time: usize,
    #[serde(rename = "F")]
    pub first_trade_id: usize,
    #[serde(rename = "L")]
    pub last_trade_id: usize,
    #[serde(rename = "n")]
    pub trade_count: usize,
}

#[derive(Debug, Clone, Copy)]
pub struct TickerStream<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy)]
pub struct AllTickersStream;

impl<'a> BinanceStream for TickerStream<'a> {
    type Event = TickerEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@ticker", ws_base_url, self.symbol.to_lowercase()))
    }
}

impl BinanceStream for AllTickersStream {
    type Event = Vec<TickerEvent>;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!ticker@arr", ws_base_url))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct BookTickerEvent {
    #[serde(rename = "u")]
    pub order_book_update_id: usize,
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "b")]
    pub best_bid_price: String,
    #[serde(rename = "B")]
    pub best_bid_qty: String,
    #[serde(rename = "a")]
    pub best_ask_price: String,
    #[serde(rename = "A")]
    pub best_ask_qty: String,
}

#[derive(Debug, Clone, Copy)]
pub struct BookTickerStream<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy)]
pub struct AllBookTickersStream;

impl<'a> BinanceStream for BookTickerStream<'a> {
    type Event = BookTickerEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@bookTicker", ws_base_url, self.symbol.to_lowercase()))
    }
}

impl BinanceStream for AllBookTickersStream {
    type Event = BookTickerEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!bookTicker", ws_base_url))
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderType {
    Limit,
    Market,
    Stop,
    StopMarket,
    TakeProfit,
    TakeProfitMarket,
    TrailingStopMarket,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum TimeInForce {
    #[serde(rename = "GTC")]
    GoodTillCancel,
    #[serde(rename = "IOC")]
    ImmediateOrCancel,
    #[serde(rename = "FOK")]
    FillOrKill,
    #[serde(rename = "GTX")]
    GoodTillCrossing,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderStatus {
    New,
    PartiallyFilled,
    Filled,
    Canceled,
    Rejected,
    Expired,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LiquidationOrderEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "o")]
    pub liquidation_order: LiquidationOrder,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LiquidationOrder {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "S")]
    pub side: Side,
    #[serde(rename = "o")]
    pub order_type: OrderType,
    #[serde(rename = "f")]
    pub time_in_force: TimeInForce,
    #[serde(rename = "q")]
    pub orig_qty: String,
    #[serde(rename = "p")]
    pub price: String,
    #[serde(rename = "ap")]
    pub avg_price: String,
    #[serde(rename = "X")]
    pub status: OrderStatus,
    #[serde(rename = "l")]
    pub last_filled_qty: String,
    #[serde(rename = "z")]
    pub cumulative_filled_qty: String,
    #[serde(rename = "T")]
    pub order_trade_time: usize,
}

#[derive(Debug, Clone, Copy)]
pub struct LiquidationOrderStream<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy)]
pub struct AllLiquidationOrdersStream;

impl<'a> BinanceStream for LiquidationOrderStream<'a> {
    type Event = LiquidationOrderEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@forceOrder", ws_base_url, self.symbol.to_lowercase()))
    }
}

impl BinanceStream for AllLiquidationOrdersStream {
    type Event = LiquidationOrderEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!forceOrder@arr", ws_base_url))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct PartialDepthEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "U")]
    pub first_update_id: usize,
    #[serde(rename = "u")]
    pub final_update_id: usize,
    #[serde(rename = "pu")]
    pub last_event_final_update_id: usize,
    #[serde(rename = "b")]
    pub bids: Vec<BookLevel>,
    #[serde(rename = "a")]
    pub asks: Vec<BookLevel>,
}

#[derive(Debug, Clone, Copy)]
#[allow(non_camel_case_types)]
pub enum PartialDepthStreamUpdateSpeed {
    ms100,
    ms250,
    ms500,
}

#[derive(Debug, Clone, Copy)]
#[allow(non_camel_case_types)]
pub enum PartialDepthStreamLevels {
    l5,
    l10,
    l20,
}

#[derive(Debug, Clone, Copy)]
pub struct PartialDepthStream<'a> {
    pub symbol: &'a str,
    pub update_speed: PartialDepthStreamUpdateSpeed,
    pub levels: PartialDepthStreamLevels,
}

impl<'a> BinanceStream for PartialDepthStream<'a> {
    type Event = PartialDepthEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let levels_str = match self.levels {
            PartialDepthStreamLevels::l5 => "5",
            PartialDepthStreamLevels::l10 => "10",
            PartialDepthStreamLevels::l20 => "20",
        };
        let update_speed_str = match self.update_speed {
            PartialDepthStreamUpdateSpeed::ms100 => "@100ms",
            PartialDepthStreamUpdateSpeed::ms250 => "",
            PartialDepthStreamUpdateSpeed::ms500 => "@500ms",
        };
        Url::from_str(&format!("{}/ws/{}@depth{}{}", ws_base_url, self.symbol.to_lowercase(), levels_str, update_speed_str))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct DiffDepthEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "U")]
    pub first_update_id: usize,
    #[serde(rename = "u")]
    pub final_update_id: usize,
    #[serde(rename = "pu")]
    pub last_event_final_update_id: usize,
    #[serde(rename = "b")]
    pub bid_updates: Vec<BookLevel>,
    #[serde(rename = "a")]
    pub ask_updates: Vec<BookLevel>,
}

#[derive(Debug, Clone, Copy)]
#[allow(non_camel_case_types)]
pub enum DiffDepthStreamUpdateSpeed {
    ms100,
    ms250,
    ms500,
}

#[derive(Debug, Clone, Copy)]
pub struct DiffDepthStream<'a> {
    pub symbol: &'a str,
    pub update_speed: DiffDepthStreamUpdateSpeed,
}

impl<'a> BinanceStream for DiffDepthStream<'a> {
    type Event = DiffDepthEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        let update_speed_str = match self.update_speed {
            DiffDepthStreamUpdateSpeed::ms100 => "@100ms",
            DiffDepthStreamUpdateSpeed::ms250 => "",
            DiffDepthStreamUpdateSpeed::ms500 => "@500ms",
        };
        Url::from_str(&format!("{}/ws/{}@depth{}", ws_base_url, self.symbol.to_lowercase(), update_speed_str))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct CompositeIndexEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "p")]
    pub price: String,
    #[serde(rename = "C")]
    pub c: String,
    #[serde(rename = "c", default = "Vec::new")]
    pub composition: Vec<Composite>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct Composite {
    #[serde(rename = "b")]
    pub base_asset: String,
    #[serde(rename = "q")]
    pub quote_asset: String,
    #[serde(rename = "w")]
    pub qty_weight: String,
    #[serde(rename = "W")]
    pub percentage_weight: String,
    #[serde(rename = "i")]
    pub index_price: String,
}

#[derive(Debug, Clone, Copy)]
pub struct CompositeIndexStream<'a> {
    pub symbol: &'a str,
}

impl<'a> BinanceStream for CompositeIndexStream<'a> {
    type Event = CompositeIndexEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@compositeIndex", ws_base_url, self.symbol.to_lowercase()))
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ContractStatus {
    PendingTrading,
    Trading,
    PreDelivering,
    Delivering,
    Delivered,
    PreSettle,
    Settling,
    Close,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ContractInfoEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "ps")]
    pub pair: String,
    #[serde(rename = "ct")]
    pub contract_type: ContractType,
    #[serde(rename = "dt")]
    pub delivery_time: usize,
    #[serde(rename = "ot")]
    pub onboard_time: usize,
    #[serde(rename = "cs")]
    pub contract_status: ContractStatus,
    #[serde(rename = "bks")]
    pub notional_brackets: Vec<NotionalBracket>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct NotionalBracket {
    #[serde(rename = "bs")]
    pub id: usize,
    #[serde(rename = "bnf")]
    pub floor: String,
    #[serde(rename = "bnc")]
    pub cap: String,
    #[serde(rename = "mmr")]
    pub maintenance_ratio: String,
    #[serde(rename = "cf")]
    pub auxiliary_number: String,
    #[serde(rename = "mi")]
    pub min_leverage: usize,
    #[serde(rename = "ma")]
    pub max_leverage: usize,
}

#[derive(Debug, Clone, Copy)]
pub struct ContractInfoStream;

impl BinanceStream for ContractInfoStream {
    type Event = ContractInfoEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!contractInfo", ws_base_url))
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct AssetIndexUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "i")]
    pub index_price: String,
    #[serde(rename = "b")]
    pub bid_buffer: String,
    #[serde(rename = "a")]
    pub ask_buffer: String,
    #[serde(rename = "B")]
    pub bid_rate: String,
    #[serde(rename = "A")]
    pub ask_rate: String,
    #[serde(rename = "q")]
    pub auto_exchange_bid_buffer: String,
    #[serde(rename = "g")]
    pub auto_exchange_ask_buffer: String,
    #[serde(rename = "Q")]
    pub auto_exchange_bid_rate: String,
    #[serde(rename = "G")]
    pub auto_exchange_ask_rate: String,
}

#[derive(Debug, Clone, Copy)]
pub struct AssetIndexUpdateStream<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy)]
pub struct AllAssetIndexUpdatesStream;

impl<'a> BinanceStream for AssetIndexUpdateStream<'a> {
    type Event = AssetIndexUpdateEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}@assetIndex", ws_base_url, self.symbol.to_lowercase()))
    }
}

impl BinanceStream for AllAssetIndexUpdatesStream {
    type Event = Vec<AssetIndexUpdateEvent>;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/!assetIndex@arr", ws_base_url))
    }
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct PingRequest;

#[derive(Debug, Clone, Deserialize)]
pub struct PingResponse { }

impl Request for PingRequest {
    type Response = PingResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ping";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct ServerTimeRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerTimeResponse {
    pub server_time: usize,
}

impl Request for ServerTimeRequest {
    type Response = ServerTimeResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/time";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct ExchangeInfoRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExchangeInfoResponse {
    pub exchange_filters: Vec<ExchangeFilter>,
    pub rate_limits: Vec<RateLimit>,
    pub server_time: usize,
    #[serde(rename = "symbols")]
    pub markets: Vec<Market>,
}

impl Request for ExchangeInfoRequest {
    type Response = ExchangeInfoResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/exchangeInfo";
}

#[derive(Debug, Clone, Deserialize)]
pub enum ExchangeFilter {
    // No info about this on binance api docs
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RateLimit {
    pub rate_limit_type: RateLimitType,
    pub interval: RateLimitInterval,
    pub interval_num: usize,
    pub limit: usize,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RateLimitType {
    RequestWeight,
    Orders,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RateLimitInterval {
    Second,
    Minute,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Market {
    pub symbol: String,
    pub pair: String,
    #[serde(deserialize_with = "treat_error_as_none")]
    pub contract_type: Option<ContractType>,
    pub delivery_date: usize,
    pub onboard_date: usize,
    pub status: ContractStatus,
    pub maint_margin_percent: String,
    pub required_margin_percent: String,
    pub base_asset: String,
    pub quote_asset: String,
    pub margin_asset: String,
    pub price_precision: usize,
    #[serde(rename = "quantityPrecision")]
    pub qty_precision: usize,
    pub base_asset_precision: usize,
    #[serde(rename = "quotePrecision")]
    pub quote_asset_precision: usize,
    pub underlying_type: String, // No info on this
    pub underlying_sub_type: Vec<String>, // No info on this
    pub settle_plan: usize, // No info on this
    pub trigger_protect: String,
    pub filters: Vec<SymbolFilter>,
    pub liquidation_fee: String,
    pub market_take_bound: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "filterType", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SymbolFilter {
    #[serde(rename = "PRICE_FILTER", rename_all = "camelCase")]
    Price {
        #[serde(rename = "minPrice")]
        min: String,
        #[serde(rename = "maxPrice")]
        max: String,
        tick_size: String,
    },
    #[serde(rename_all = "camelCase")]
    LotSize {
        min_qty: String,
        max_qty: String,
        step_size: String,
    },
    #[serde(rename_all = "camelCase")]
    MarketLotSize {
        min_qty: String,
        max_qty: String,
        step_size: String,
    },
    MaxNumOrders {
        #[serde(rename = "limit")]
        max: usize,
    },
    MaxNumAlgoOrders {
        #[serde(rename = "limit")]
        max: usize,
    },
    #[serde(rename_all = "camelCase")]
    PercentPrice {
        multiplier_up: String,
        multiplier_down: String,
        #[serde(rename = "multiplierDecimal")]
        multiplier_precision: String,
    },
    #[serde(rename_all = "camelCase")]
    MinNotional {
        #[serde(rename = "notional")]
        min: String,
    },
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct OrderBookRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<OrderBookRequestLevels>,
}

#[derive(Debug, Clone, Copy, Serialize_repr)]
#[repr(usize)]
#[allow(non_camel_case_types)]
pub enum OrderBookRequestLevels {
    l5 = 5,
    l10 = 10,
    l20 = 20,
    l50 = 50,
    l100 = 100,
    l500 = 500,
    l1000 = 1000,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderBookResponse {
    pub last_update_id: usize,
    #[serde(rename = "E")]
    pub message_output_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    pub bids: Vec<BookLevel>,
    pub asks: Vec<BookLevel>,
}

impl<'a> Request for OrderBookRequest<'a> {
    type Response = OrderBookResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/depth";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct RecentTradesRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OldTradesRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_id: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TradeResponse {
    pub id: usize,
    pub price: String,
    pub qty: String,
    pub quote_qty: String,
    pub time: usize,
    pub is_buyer_maker: bool,
}

impl<'a> Request for RecentTradesRequest<'a> {
    type Response = Vec<TradeResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/trades";
}

impl<'a> ApiKeyHeaderRequest for OldTradesRequest<'a> {
    type Response = Vec<TradeResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/historicalTrades";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AggTradesRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
}

#[derive(Debug, Clone, Deserialize)]
pub struct AggTradeResponse {
    #[serde(rename = "a")]
    pub id: usize,
    #[serde(rename = "p")]
    pub price: String,
    #[serde(rename = "q")]
    pub qty: String,
    #[serde(rename = "f")]
    pub first_trade_id: usize,
    #[serde(rename = "l")]
    pub last_trade_id: usize,
    #[serde(rename = "T")]
    pub time: usize,
    #[serde(rename = "m")]
    pub is_buyer_maker: bool,
}

impl<'a> Request for AggTradesRequest<'a> {
    type Response = Vec<AggTradeResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/aggTrades";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KlinesRequest<'a> {
    pub symbol: &'a str,
    pub interval: KlineInterval,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1500
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ContinuousContractKlinesRequest<'a> {
    pub pair: &'a str,
    pub contract_type: ContractType,
    pub interval: KlineInterval,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1500
}

#[derive(Debug, Clone, Deserialize)]
pub struct KlineResponse {
    pub open_time: usize,
    pub open_price: String,
    pub high_price: String,
    pub low_price: String,
    pub close_price: String,
    pub base_asset_volume: String,
    pub close_time: usize,
    pub quote_asset_volmue: String,
    pub trade_count: usize,
    pub taker_buy_base_asset_volume: String,
    pub taker_buy_quote_asset_volume: String,
}

impl<'a> Request for KlinesRequest<'a> {
    type Response = Vec<KlineResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/klines";
}

impl<'a> Request for ContinuousContractKlinesRequest<'a> {
    type Response = Vec<KlineResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/continuousKlines";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexPriceKlinesRequest<'a> {
    pub pair: &'a str,
    pub interval: KlineInterval,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1500
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MarkPriceKlinesRequest<'a> {
    pub symbol: &'a str,
    pub interval: KlineInterval,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1500
}

#[derive(Debug, Clone, Deserialize)]
pub struct IndexKlineResponse {
    pub open_time: usize,
    pub open_price: String,
    pub high_price: String,
    pub low_price: String,
    pub close_price: String,
    pub close_time: usize,
}

impl<'a> Request for IndexPriceKlinesRequest<'a> {
    type Response = Vec<IndexKlineResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/indexPriceKlines";
}

impl<'a> Request for MarkPriceKlinesRequest<'a> {
    type Response = Vec<IndexKlineResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/markPriceKlines";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct MarkPriceRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct AllMarkPricesRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarkPriceResponse {
    pub symbol: String,
    pub mark_price: String,
    pub index_price: String,
    pub estimated_settle_price: String,
    pub last_funding_rate: String,
    pub next_funding_time: usize,
    pub interest_rate: String,
    pub time: usize,
}

impl<'a> Request for MarkPriceRequest<'a> {
    type Response = MarkPriceResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/premiumIndex";
}

impl Request for AllMarkPricesRequest {
    type Response = Vec<MarkPriceResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/premiumIndex";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FundingRateHistoryRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FundingRateHistoryResponse {
    pub symbol: String,
    pub funding_rate: String,
    pub funding_time: usize,
}

impl<'a> Request for FundingRateHistoryRequest<'a> {
    type Response = Vec<FundingRateHistoryResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/fundingRate";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct TickerRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct AllTickersRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TickerResponse {
    pub symbol: String,
    pub price_change: String,
    pub price_change_percent: String,
    #[serde(rename = "weightedAvgPrice")]
    pub volume_weighted_avg_price: String,
    pub last_price: String,
    pub last_qty: String,
    pub open_price: String,
    pub hight_price: String,
    pub low_price: String,
    #[serde(rename = "volume")]
    pub base_asset_volume: String,
    #[serde(rename = "quoteVolume")]
    pub quote_asset_volume: String,
    pub open_time: usize,
    pub close_time: usize,
    #[serde(rename = "firstId")]
    pub first_trade_id: usize,
    #[serde(rename = "lastId")]
    pub last_trade_id: usize,
    #[serde(rename = "count")]
    pub trade_count: usize,
}

impl<'a> Request for TickerRequest<'a> {
    type Response = TickerResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/24hr";
}

impl Request for AllTickersRequest {
    type Response = Vec<TickerResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/24hr";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct PriceTickerRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct AllPriceTickersRequest;

#[derive(Debug, Clone, Deserialize)]
pub struct PriceTickerResponse {
    pub symbol: String,
    pub price: String,
    pub time: usize,
}

impl<'a> Request for PriceTickerRequest<'a> {
    type Response = PriceTickerResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/price";
}

impl Request for AllPriceTickersRequest {
    type Response = Vec<PriceTickerResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/price";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct BookTickerRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct AllBookTickersRequest;

#[derive(Debug, Clone, Deserialize)]
pub struct BookTickerResponse {
    pub symbol: String,
    #[serde(rename = "bidPrice")]
    pub best_bid_price: String,
    #[serde(rename = "bidQty")]
    pub best_bid_qty: String,
    #[serde(rename = "askPrice")]
    pub best_ask_price: String,
    #[serde(rename = "askQty")]
    pub best_ask_qty: String,
    pub time: usize,
}

impl<'a> Request for BookTickerRequest<'a> {
    type Response = BookTickerResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/bookTicker";
}

impl Request for AllBookTickersRequest {
    type Response = Vec<BookTickerResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/ticker/bookTicker";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct OpenInterestRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenInterestResponse {
    pub open_interest: String,
    pub symbol: String,
    pub time: usize,
}

impl<'a> Request for OpenInterestRequest<'a> {
    type Response = OpenInterestResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/openInterest";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct OpenInterestStatisticsRequest<'a> {
    pub symbol: &'a str,
    pub period: FuturesStatisticsPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 500
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[allow(non_camel_case_types)]
pub enum FuturesStatisticsPeriod {
    #[serde(rename = "5m")]
    m5,
    #[serde(rename = "15m")]
    m15,
    #[serde(rename = "30m")]
    m30,
    #[serde(rename = "1h")]
    h1,
    #[serde(rename = "2h")]
    h2,
    #[serde(rename = "4h")]
    h4,
    #[serde(rename = "6h")]
    h6,
    #[serde(rename = "12h")]
    h12,
    #[serde(rename = "1d")]
    d1,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenInterestStatisticsResponse {
    pub symbol: String,
    pub sum_open_interest: String,
    pub sum_open_interest_value: String,
    pub timestamp: usize,
}

impl<'a> Request for OpenInterestStatisticsRequest<'a> {
    type Response = Vec<OpenInterestStatisticsResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/futures/data/openInterestHist";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct TopLongShortAccountRatioRequest<'a> {
    pub symbol: &'a str,
    pub period: FuturesStatisticsPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 500
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TopLongShortAccountRatioResponse {
    pub symbol: String,
    pub long_short_ratio: String,
    pub long_account: String,
    pub short_account: String,
    pub timestamp: usize,
}

impl<'a> Request for TopLongShortAccountRatioRequest<'a> {
    type Response = Vec<TopLongShortAccountRatioResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/futures/data/topLongShortAccountRatio";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct TopLongShortPositionRatioRequest<'a> {
    pub symbol: &'a str,
    pub period: FuturesStatisticsPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 500
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TopLongShortPositionRatioResponse {
    pub symbol: String,
    pub long_short_ratio: String,
    pub long_account: String,
    pub short_account: String,
    pub timestamp: usize,
}

impl<'a> Request for TopLongShortPositionRatioRequest<'a> {
    type Response = Vec<TopLongShortPositionRatioResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/futures/data/topLongShortPositionRatio";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct GlobalLongShortAccountRatioRequest<'a> {
    pub symbol: &'a str,
    pub period: FuturesStatisticsPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 500
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GlobalLongShortAccountRatioResponse {
    pub symbol: String,
    pub long_short_ratio: String,
    pub long_account: String,
    pub short_account: String,
    pub timestamp: usize,
}

impl<'a> Request for GlobalLongShortAccountRatioRequest<'a> {
    type Response = Vec<GlobalLongShortAccountRatioResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/futures/data/globalLongShortAccountRatio";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct TakerBuySellVolumeRequest<'a> {
    pub symbol: &'a str,
    pub period: FuturesStatisticsPeriod,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 500
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TakerBuySellVolumeResponse {
    pub buy_sell_ratio: String,
    pub buy_vol: String,
    pub sell_vol: String,
    pub timestamp: usize,
}

impl<'a> Request for TakerBuySellVolumeRequest<'a> {
    type Response = Vec<TakerBuySellVolumeResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/futures/data/globalLongShortAccountRatio";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HistoricalBlvtKlinesRequest<'a> {
    pub symbol: &'a str,
    pub interval: KlineInterval,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1500
}

#[derive(Debug, Clone, Deserialize)]
pub struct HistoricalBlvtKlineResponse {
    pub open_time: usize,
    pub open_price: String,
    pub high_price: String,
    pub low_price: String,
    pub close_price: String,
    pub real_leverage: String,
    pub close_time: usize,
    pub nav_update_count: usize,
}

impl<'a> Request for HistoricalBlvtKlinesRequest<'a> {
    type Response = Vec<HistoricalBlvtKlineResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/lvtKlines";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetIndexRequest<'a> {
    pub symbol: &'a str,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AllAssetIndexesRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetIndexResponse {
    pub symbol: String,
    pub time: usize,
    pub index: String,
    pub bid_buffer: String,
    pub ask_buffer: String,
    pub bid_rate: String,
    pub ask_rate: String,
    pub auto_exchange_bid_buffer: String,
    pub auto_exchange_ask_buffer: String,
    pub auto_exchange_bid_rate: String,
    pub auto_exchange_ask_rate: String,
}

impl<'a> Request for AssetIndexRequest<'a> {
    type Response = AssetIndexResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/assetIndex";
}

impl Request for AllAssetIndexesRequest {
    type Response = Vec<AssetIndexResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/assetIndex";
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct CreateListenKeyRequest;

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateListenKeyResponse {
    pub listen_key: String,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub struct KeepAliveListenKeyRequest;

#[derive(Debug, Clone, Deserialize)]
pub struct KeepAliveListenKeyResponse { }

#[derive(Debug, Clone, Copy, Serialize)]
pub struct CloseListenKeyRequest;

#[derive(Debug, Clone, Deserialize)]
pub struct CloseListenKeyResponse { }

impl ApiKeyHeaderRequest for CreateListenKeyRequest {
    type Response = CreateListenKeyResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/listenKey";
}

impl ApiKeyHeaderRequest for KeepAliveListenKeyRequest {
    type Response = KeepAliveListenKeyResponse;

    const METHOD: Method = Method::PUT;
    const ENDPOINT: &'static str = "/fapi/v1/listenKey";
}

impl ApiKeyHeaderRequest for CloseListenKeyRequest {
    type Response = CloseListenKeyResponse;

    const METHOD: Method = Method::DELETE;
    const ENDPOINT: &'static str = "/fapi/v1/listenKey";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangePositionModeRequest {
    #[serde(serialize_with = "serialize_bool_as_str")]
    pub dual_side_position: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChangePositionModeResponse { }

impl SignedRequest for ChangePositionModeRequest {
    type Response = ChangePositionModeResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/positionSide/dual";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPositionModeRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetPositionModeResponse {
    pub dual_side_position: bool,
}

impl SignedRequest for GetPositionModeRequest {
    type Response = GetPositionModeResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/positionSide/dual";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeMultiAssetModeRequest {
    #[serde(serialize_with = "serialize_bool_as_str")]
    pub multi_asset_margin: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChangeMultiAssetModeResponse { }

impl SignedRequest for ChangeMultiAssetModeRequest {
    type Response = ChangeMultiAssetModeResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/multiAssetsMargin";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetMultiAssetModeRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetMultiAssetModeResponse {
    pub multi_asset_margin: bool,
}

impl SignedRequest for GetMultiAssetModeRequest {
    type Response = GetMultiAssetModeResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/multiAssetsMargin";
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PositionSide {
    Both,
    Long,
    Short,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WorkingType {
    MarkPrice,
    ContractPrice,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TestNewOrderRequest<'a> {
    pub symbol: &'a str,
    pub side: Side,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position_side: Option<PositionSide>,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<TimeInForce>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "quantity")]
    pub qty: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub reduce_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "newClientOrderId")]
    pub client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub close_position: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activation_price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callback_rate: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_type: Option<WorkingType>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub price_protect: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub self_trade_prevention_mode: Option<SelfTradePreventionMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub good_till_date: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct TestNewOrderResponse { }

impl<'a> SignedRequest for TestNewOrderRequest<'a> {
    type Response = TestNewOrderResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/order/test";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderRequest<'a> {
    pub symbol: &'a str,
    pub side: Side,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position_side: Option<PositionSide>,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<TimeInForce>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "quantity")]
    pub qty: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub reduce_only: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "newClientOrderId")]
    pub client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub close_position: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activation_price: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callback_rate: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_type: Option<WorkingType>,
    #[serde(skip_serializing_if = "Option::is_none", serialize_with = "serialize_opt_bool_as_str")]
    pub price_protect: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub self_trade_prevention_mode: Option<SelfTradePreventionMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub good_till_date: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NewOrderResponse {
    pub client_order_id: String,
    #[serde(rename = "cumQty")]
    pub cummulative_qty: String,
    #[serde(rename = "cumQuote")]
    pub cummulative_quote_qty: String,
    pub executed_qty: String,
    pub order_id: usize,
    #[serde(rename = "avgPrice")]
    pub average_price: String,
    pub orig_qty: String,
    pub price: String,
    pub reduce_only: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub status: OrderStatus,
    pub stop_price: String,
    pub close_position: bool,
    pub symbol: String,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub activate_price: Option<String>,
    pub price_rate: Option<String>,
    pub update_time: usize,
    pub working_type: WorkingType,
    pub price_protect: bool,
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    pub good_till_date: usize,
}

impl SignedRequest for NewOrderRequest<'_> {
    type Response = NewOrderResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/order";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModifyOrderRequest<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orig_client_order_id: Option<usize>,
    pub symbol: &'a str,
    pub side: Side,
    #[serde(rename = "quantity")]
    pub qty: &'a str,
    pub price: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModifyOrderResponse {
    pub order_id: usize,
    pub symbol: String,
    pub pair: String,
    pub status: OrderStatus,
    pub client_order_id: String,
    pub price: String,
    #[serde(rename = "avgPrice")]
    pub average_price: String,
    pub orig_qty: String,
    pub executed_qty: String,
    #[serde(rename = "cumQty")]
    pub cummulative_qty: String,
    #[serde(rename = "cumBase")]
    pub cummulative_base_qty: String,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub reduce_only: bool,
    pub close_position: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub stop_price: String,
    pub working_type: WorkingType,
    pub price_protect: bool,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    pub good_till_date: usize,
    pub update_time: usize,
}

impl SignedRequest for ModifyOrderRequest<'_> {
    type Response = ModifyOrderResponse;

    const METHOD: Method = Method::PUT;
    const ENDPOINT: &'static str = "/fapi/v1/order";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewOrdersRequest<'a> {
    pub batch_orders: &'a [NewOrderRequest<'a>],
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

impl SignedRequest for NewOrdersRequest<'_> {
    type Response = Vec<Result<NewOrderResponse, BinanceErrorMsg>>;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/batchOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModifyOrdersRequest<'a> {
    pub batch_orders: &'a [ModifyOrderRequest<'a>],
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

impl SignedRequest for ModifyOrdersRequest<'_> {
    type Response = Vec<Result<ModifyOrderResponse, BinanceErrorMsg>>;

    const METHOD: Method = Method::PUT;
    const ENDPOINT: &'static str = "/fapi/v1/batchOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetOrderModifyHistoryRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orig_client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 100
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Modification {
    pub before: String,
    pub after: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderAmendment {
    pub price: Modification,
    pub orig_qty: Modification,
    pub count: usize,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetOrderModifyHistoryResponse {
    pub amendment_id: usize,
    pub symbol: String,
    pub pair: String,
    pub order_id: usize,
    pub client_order_id: String,
    pub time: usize,
    pub amendment: OrderAmendment,
}

impl SignedRequest for GetOrderModifyHistoryRequest<'_> {
    type Response = GetOrderModifyHistoryResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/orderAmendment";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryOrderRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orig_client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryOrderResponse {
    #[serde(rename = "avgPrice")]
    pub average_price: String,
    pub client_order_id: String,
    #[serde(rename = "cumQuote")]
    pub cummulative_quote_qty: String,
    pub executed_qty: String,
    pub order_id: usize,
    pub orig_qty: String,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub price: String,
    pub reduce_only: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub status: OrderStatus,
    pub stop_price: String,
    pub close_position: bool,
    pub symbol: String,
    pub time: usize,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub activate_price: Option<String>,
    pub price_rate: Option<String>,
    pub update_time: usize,
    pub working_type: WorkingType,
    pub price_protect: bool,
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    pub good_till_date: usize,
}

impl SignedRequest for QueryOrderRequest<'_> {
    type Response = QueryOrderResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/order";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrderRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orig_client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrderResponse {
    pub client_order_id: String,
    #[serde(rename = "cumQty")]
    pub cummulative_qty: String,
    #[serde(rename = "cumQuote")]
    pub cummulative_quote_qty: String,
    pub executed_qty: String,
    pub order_id: usize,
    pub orig_qty: String,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub price: String,
    pub reduce_only: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub status: OrderStatus,
    pub stop_price: String,
    pub close_position: bool,
    pub symbol: String,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub activate_price: Option<String>,
    pub price_rate: Option<String>,
    pub update_time: usize,
    pub working_type: WorkingType,
    pub price_protect: bool,
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    pub good_till_date: usize,
}

impl SignedRequest for CancelOrderRequest<'_> {
    type Response = CancelOrderResponse;

    const METHOD: Method = Method::DELETE;
    const ENDPOINT: &'static str = "/fapi/v1/order";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelAllOrdersRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct CancelAllOrdersResponse { }

impl SignedRequest for CancelAllOrdersRequest<'_> {
    type Response = CancelAllOrdersResponse;

    const METHOD: Method = Method::DELETE;
    const ENDPOINT: &'static str = "/fapi/v1/allOpenOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrdersRequest<'a> {
    pub symbol: &'a str,
    pub order_id_list: Option<&'a [usize]>, // len <= 10
    pub orig_client_order_id_list: Option<&'a [String]>, // len <= 10
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

impl SignedRequest for CancelOrdersRequest<'_> {
    type Response = Vec<Result<CancelOrderResponse, BinanceErrorMsg>>;

    const METHOD: Method = Method::DELETE;
    const ENDPOINT: &'static str = "/fapi/v1/batchOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelAllOrdersWithCountdownRequest<'a> {
    pub symbol: &'a str,
    pub countdown_time: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelAllOrdersWithCountdownResponse {
    pub symbol: String,
    pub countdown_time: String,
}

impl SignedRequest for CancelAllOrdersWithCountdownRequest<'_> {
    type Response = CancelAllOrdersWithCountdownResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/countdownCancelAll";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryOpenOrderRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub orig_client_order_id: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryOpenOrderResponse {
    #[serde(rename = "avgPrice")]
    pub average_price: String,
    pub client_order_id: String,
    #[serde(rename = "cumQuote")]
    pub cummulative_quote_qty: String,
    pub executed_qty: String,
    pub order_id: usize,
    pub orig_qty: String,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub price: String,
    pub reduce_only: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub status: OrderStatus,
    pub stop_price: String,
    pub close_position: bool,
    pub symbol: String,
    pub time: usize,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub activate_price: Option<String>,
    pub price_rate: Option<String>,
    pub update_time: usize,
    pub working_type: WorkingType,
    pub price_protect: bool,
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    pub good_till_date: usize,
}

impl SignedRequest for QueryOpenOrderRequest<'_> {
    type Response = QueryOpenOrderResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/openOrder";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryAllOpenOrdersRequest<'a> {
    pub symbol: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

impl SignedRequest for QueryAllOpenOrdersRequest<'_> {
    type Response = Vec<QueryOpenOrderResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/openOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct QueryAllOrdersRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none", rename = "orderId")]
    pub from_order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

impl SignedRequest for QueryAllOrdersRequest<'_> {
    type Response = Vec<QueryOrderResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/allOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BalancesRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BalanceResponse {
    pub account_alias: String,
    pub asset: String,
    pub balance: String,
    pub cross_wallet_balance: String,
    #[serde(rename = "crossUnPnl")]
    pub cross_unrealized_pnl: String,
    pub available_balance: String,
    pub max_withdraw_amount: String,
    pub margin_availble: bool,
    pub update_time: usize,
}

impl SignedRequest for BalancesRequest {
    type Response = BalanceResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v2/balance";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountInformationRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssetInformation {
    pub asset: String,
    pub wallet_balance: String,
    pub unrealized_profit: String,
    pub margin_balance: String,
    #[serde(rename = "maintMargin")]
    pub maintenance_margin: String,
    pub initial_margin: String,
    pub position_initial_margin: String,
    pub open_order_initial_margin: String,
    pub cross_wallet_balance: String,
    #[serde(rename = "crossUnPnl")]
    pub cross_unrealized_pnl: String,
    pub available_balance: String,
    pub max_withdraw_amount: String,
    pub margin_available: bool,
    pub update_time: usize,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionInformation {
    pub symbol: String,
    pub initial_margin: String,
    #[serde(rename = "maintMargin")]
    pub maintenance_margin: String,
    pub unrealized_profit: String,
    pub position_initial_margin: String,
    pub open_order_initial_margin: String,
    pub leverage: String,
    pub isolated: bool,
    pub entry_price: String,
    pub max_notional: String,
    pub bid_notional: String,
    pub ask_notional: String,
    pub position_side: PositionSide,
    #[serde(rename = "positionAmt")]
    pub position_amount: String,
    pub update_time: usize,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountInformationResponse {
    pub fee_tier: usize,
    pub can_trade: bool,
    pub can_deposit: bool,
    pub can_withdraw: bool,
    pub update_time: usize,
    pub multi_asset_margin: bool,
    #[serde(deserialize_with = "treat_error_as_none")]
    pub trade_group_id: Option<usize>,
    pub total_initial_margin: String,
    #[serde(rename = "totalMaintMargin")]
    pub total_maintenance_margin: String,
    pub total_wallet_balance: String,
    pub total_unrealized_profit: String,
    pub total_margin_balance: String,
    pub total_position_initial_margin: String,
    pub total_open_order_initial_margin: String,
    pub total_cross_wallet_balance: String,
    #[serde(rename = "totalCrossUnPnl")]
    pub total_cross_unrealized_pnl: String,
    pub available_balance: String,
    pub max_withdraw_amount: String,
    pub assets: Vec<AssetInformation>,
    pub positions: Vec<PositionInformation>,
}

impl SignedRequest for AccountInformationRequest {
    type Response = AccountInformationResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v2/account";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeLeverageRequest<'a> {
    pub symbol: &'a str,
    pub leverage: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeLeverageResponse {
    pub leverage: usize,
    pub max_notional_value: String,
    pub symbol: String,
}

impl SignedRequest for ChangeLeverageRequest<'_> {
    type Response = ChangeLeverageResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/leverage";
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MarginType {
    #[serde(alias = "isolated")]
    Isolated,
    #[serde(alias = "crossed")]
    Crossed,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangeMarginTypeRequest<'a> {
    pub symbol: &'a str,
    pub margin_type: MarginType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChangeMarginTypeResponse { }

impl SignedRequest for ChangeMarginTypeRequest<'_> {
    type Response = ChangeMarginTypeResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/marginType";
}

#[derive(Debug, Clone, Copy, Serialize_repr, Deserialize_repr)]
#[repr(usize)]
pub enum ModifiyPositionMarginType {
    Add = 1,
    Reduce = 2,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModifyIsolatedPositionMarginRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position_side: Option<PositionSide>,
    pub amount: &'a str,
    #[serde(rename = "type")]
    pub modifiy_position_margin_type: ModifiyPositionMarginType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
pub struct ModifyIsolatedPositionMarginResponse { }

impl SignedRequest for ModifyIsolatedPositionMarginRequest<'_> {
    type Response = ModifyIsolatedPositionMarginResponse;

    const METHOD: Method = Method::POST;
    const ENDPOINT: &'static str = "/fapi/v1/positionMargin";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionMarginChangeHistoryRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
    pub modifiy_position_margin_type: Option<ModifiyPositionMarginType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionMarginChange {
    pub symbol: String,
    #[serde(rename = "type")]
    pub modifiy_position_margin_type: ModifiyPositionMarginType,
    pub amount: String,
    pub asset: String,
    pub time: usize,
    pub position_side: PositionSide,
}

impl SignedRequest for PositionMarginChangeHistoryRequest<'_> {
    type Response = Vec<PositionMarginChange>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/positionMargin/history";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionResponse {
    pub entry_price: String,
    pub break_even_price: String,
    pub margin_type: MarginType,
    pub is_auto_add_margin: String,
    pub isolated_margin: String,
    pub leverage: String,
    pub liquidation_price: String,
    pub mark_price: String,
    pub max_notional_value: String,
    #[serde(rename = "positionAmt")]
    pub position_amount: String,
    pub notional: String,
    pub isolated_wallet: String,
    pub symbol: String,
    #[serde(rename = "unRealizedProfit")]
    pub unrealized_profit: String,
    pub position_side: PositionSide,
    pub update_time: usize,
}

impl SignedRequest for PositionRequest<'_> {
    type Response = Vec<PositionResponse>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v2/positionRisk";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountTradesRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_id: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 1000
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountTrade {
    pub buyer: bool,
    pub commission: String,
    pub commission_asset: String,
    pub id: usize,
    pub maker: bool,
    pub order_id: usize,
    pub price: String,
    pub qty: String,
    pub quote_qty: String,
    pub realized_pnl: String,
    pub side: Side,
    pub position_side: PositionSide,
    pub symbol: String,
    pub time: usize,
}

impl SignedRequest for AccountTradesRequest<'_> {
    type Response = Vec<AccountTrade>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/userTrades";
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum IncomeType {
    Transfer,
    WelcomeBonus,
    RealizedPNL,
    FundingFee,
    Commission,
    InsuranceClear,
    ReferralKickback,
    CommissionRebate,
    ApiRebate,
    ContestReward,
    CrossCollateralTransfer,
    OptionsPremiumFee,
    OptionsSettleProfit,
    InternalTransfer,
    AutoExchange,
    DeliveredSettlement,
    CoinSwapDeposit,
    CoinSwapWithdraw,
    PositionLimitIncreaseFee,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IncomeHistoryRequest<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub income_type: Option<IncomeType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Income {
    pub symbol: String,
    pub income_type: IncomeType,
    pub income: String,
    pub asset: String,
    pub time: usize,
    #[serde(rename = "tranId")]
    pub traansaction_id: String,
    pub trade_id: String,
}

impl SignedRequest for IncomeHistoryRequest<'_> {
    type Response = Vec<Income>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/income";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LeverageBracketsRequest<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LeverageBracket {
    pub bracket: usize,
    pub initial_leverage: usize,
    pub notional_cap: usize,
    pub notional_floor: usize,
    #[serde(rename = "maintMarginRatio")]
    pub maintenance_margin_ration: usize,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SymbolLeverageBrackets {
    pub symbol: String,
    pub brackets: Vec<LeverageBracket>,
}

impl SignedRequest for LeverageBracketsRequest<'_> {
    type Response = Vec<SymbolLeverageBrackets>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/leverageBracket";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AutoCloseType {
    Liquidation,
    Adl,
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserForceOrdersRequest<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_close_type: Option<AutoCloseType>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_time: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>, // <= 100
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserForceOrder {
    pub order_id: usize,
    pub symbol: String,
    pub status: OrderStatus,
    pub client_order_id: String,
    pub price: String,
    #[serde(rename = "avgPrice")]
    pub average_price: String,
    pub orig_qty: String,
    pub executed_qty: String,
    #[serde(rename = "cumQuote")]
    pub cummulative_quote_qty: String,
    pub time_in_force: TimeInForce,
    #[serde(rename = "type")]
    pub order_type: OrderType,
    pub reduce_only: bool,
    pub close_position: bool,
    pub side: Side,
    pub position_side: PositionSide,
    pub stop_price: String,
    pub working_type: WorkingType,
    #[serde(rename = "origType")]
    pub orig_order_type: OrderType,
    pub time: usize,
    pub update_time: usize,
}

impl SignedRequest for UserForceOrdersRequest<'_> {
    type Response = Vec<UserForceOrder>;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/forceOrders";
}

#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCommissionRateRequest<'a> {
    pub symbol: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recv_window: Option<usize>, // <= 60_000
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCommissionRateResponse {
    pub symbol: String,
    pub maker_commission_rate: String,
    pub taker_commission_rate: String,
}

impl SignedRequest for UserCommissionRateRequest<'_> {
    type Response = UserCommissionRateResponse;

    const METHOD: Method = Method::GET;
    const ENDPOINT: &'static str = "/fapi/v1/commissionRate";
}

#[derive(Debug, Clone, Deserialize)]
pub struct PositionMarginCall {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "ps")]
    pub position_side: PositionSide,
    #[serde(rename = "pa")]
    pub position_amount: String,
    #[serde(rename = "mt")]
    pub margin_type: MarginType,
    #[serde(rename = "iw")]
    pub isolated_wallet: Option<String>,
    #[serde(rename = "mp")]
    pub mark_price: String,
    #[serde(rename = "up")]
    pub unrealized_pnl: String,
    #[serde(rename = "mm")]
    pub required_maintenance_margin: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MarginCallEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "cw")]
    pub cross_wallet_balance: Option<String>,
    #[serde(rename = "p")]
    pub positions: Vec<PositionMarginCall>,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BalancePositionEventReason {
    Deposit,
    Withdraw,
    Order,
    FundingFee,
    WithdrawReject,
    Adjustment,
    InsuranceClear,
    AdminDeposit,
    AdminWithdraw,
    MarginTransfer,
    MarginTypeChange,
    AssetTransfer,
    OptionsPremiumFee,
    OptionsSettleProfit,
    AutoExchange,
    CoinSwapDeposit,
    CoinSwapWithdraw,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BalancePositionUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "a")]
    pub balance_position_update: BalancePositionUpdate,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BalancePositionUpdate {
    #[serde(rename = "m")]
    pub reason: BalancePositionEventReason,
    #[serde(rename = "B")]
    pub balance_updates: Vec<BalanceUpdate>,
    #[serde(rename = "P")]
    pub position_updates: Vec<PositionUpdate>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct BalanceUpdate {
    #[serde(rename = "a")]
    pub asset: String,
    #[serde(rename = "wb")]
    pub wallet_balance: String,
    #[serde(rename = "cw")]
    pub cross_wallet_balance: String,
    #[serde(rename = "bc")]
    pub balance_change: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct PositionUpdate {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "pa")]
    pub position_amount: String,
    #[serde(rename = "ep")]
    pub entry_price: String,
    #[serde(rename = "bep")]
    pub breakeven_price: String,
    #[serde(rename = "cr")]
    pub realized_pnl: String,
    #[serde(rename = "up")]
    pub unrealized_pnl: String,
    #[serde(rename = "mt")]
    pub margin_type: MarginType,
    #[serde(rename = "iw")]
    pub isolated_wallet: Option<String>,
    #[serde(rename = "ps")]
    pub position_side: PositionSide,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderExecutionType {
    New,
    Canceled,
    Calculated, // Liquidation Execution
    Expired,
    Trade,
    Amendment,
}

#[derive(Debug, Clone, Deserialize)]
pub struct OrderUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "o")]
    pub order_update: OrderUpdate,
}

#[derive(Debug, Clone, Deserialize)]
pub struct OrderUpdate {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "c")]
    pub client_order_id: String,
    #[serde(rename = "S")]
    pub side: Side,
    #[serde(rename = "o")]
    pub order_type: OrderType,
    #[serde(rename = "f")]
    pub time_in_force: TimeInForce,
    #[serde(rename = "q")]
    pub orig_qty: String,
    #[serde(rename = "p")]
    pub orig_price: String,
    #[serde(rename = "ap")]
    pub average_price: String,
    #[serde(rename = "sp")]
    pub stop_price: String,
    #[serde(rename = "x")]
    pub current_order_execution_type: OrderExecutionType,
    #[serde(rename = "X")]
    pub current_order_status: OrderStatus,
    #[serde(rename = "i")]
    pub order_id: usize,
    #[serde(rename = "l")]
    pub last_filled_qty: String,
    #[serde(rename = "z")]
    pub cummulative_filled_qty: String,
    #[serde(rename = "L")]
    pub last_fill_price: String,
    #[serde(rename = "N")]
    pub commission_asset: Option<String>,
    #[serde(rename = "n")]
    pub commission_amount: Option<String>,
    #[serde(rename = "T")]
    pub order_trade_time: usize,
    #[serde(rename = "t")]
    pub order_trade_id: usize,
    #[serde(rename = "b")]
    pub bid_notional: String,
    #[serde(rename = "a")]
    pub ask_notional: String,
    #[serde(rename = "m")]
    pub is_trade_maker: bool,
    #[serde(rename = "R")]
    pub is_reduce_only: bool,
    #[serde(rename = "wt")]
    pub stop_price_working_type: WorkingType,
    #[serde(rename = "ot")]
    pub orig_order_type: OrderType,
    #[serde(rename = "ps")]
    pub position_side: PositionSide,
    #[serde(rename = "cp")]
    pub close_position: bool,
    #[serde(rename = "AP")]
    pub activation_price: Option<String>,
    #[serde(rename = "cr")]
    pub callback_rate: Option<String>,
    #[serde(rename = "pP")]
    pub price_protection: bool,
    #[serde(rename = "rp")]
    pub trade_realized_profit: String,
    #[serde(rename = "V")]
    pub self_trade_prevention_mode: SelfTradePreventionMode,
    #[serde(rename = "gtd")]
    pub good_till_date: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct AccountConfigurationUpdateEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "ac")]
    pub leverage: Option<LeverageUpdate>,
    #[serde(rename = "ai")]
    pub multi_asset_mode: Option<MultiAssetModeUpdate>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct LeverageUpdate {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "l")]
    pub leverage: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MultiAssetModeUpdate {
    #[serde(rename = "j")]
    pub multi_asset_mode: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ConditionalOrderTriggerRejectEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "T")]
    pub transaction_time: usize,
    #[serde(rename = "or")]
    pub conditional_order_trigger_reject: ConditionalOrderTriggerReject,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ConditionalOrderTriggerReject {
    #[serde(rename = "s")]
    pub symbol: String,
    #[serde(rename = "i")]
    pub order_id: usize,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ListenKeyExpiredEvent {
    #[serde(rename = "E")]
    pub event_time: usize,
    #[serde(rename = "listenKey")]
    pub listen_key: String,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "e")]
pub enum UserStreamEvent {
    #[serde(rename = "MARGIN_CALL")]
    MarginCall(MarginCallEvent),
    #[serde(rename = "ACCOUNT_UPDATE")]
    BalancePositionUpdate(BalancePositionUpdateEvent),
    #[serde(rename = "ORDER_TRADE_UPDATE")]
    OrderUpdate(OrderUpdateEvent),
    #[serde(rename = "ACCOUNT_CONFIG_UPDATE")]
    AccountConfigurationUpdate(AccountConfigurationUpdateEvent),
    #[serde(rename = "CONDITIONAL_ORDER_TRIGGER_REJECT")]
    ConditionalOrderTriggerReject(ConditionalOrderTriggerRejectEvent),
    #[serde(rename = "listenKeyExpired")]
    ListenKeyExpired(ListenKeyExpiredEvent),
}

#[derive(Debug, Clone, Copy)]
pub struct UserStream<'a> {
    pub listen_key: &'a str,
}

impl<'a> BinanceStream for UserStream<'a> {
    type Event = UserStreamEvent;

    fn build_url(&self, ws_base_url: &str) -> Result<Url, url::ParseError> {
        Url::from_str(&format!("{}/ws/{}", ws_base_url, self.listen_key))
    }
}