cexy 0.1.0-dev.16

Official Rust SDK for the CEXY.io exchange API (REST + WebSocket)
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
// Code generated by tools/generate.py from cexy-api-spec; DO NOT EDIT.

//! API models, generated from the shared OpenAPI document.

#![allow(clippy::doc_markdown, clippy::too_many_arguments)]

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::amount::Amount;
use crate::error::ErrorBody;

/// The id of the account a credential belongs to, and nothing else.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccountId {
    /// Account id: the same hex as the realtime `authenticated` reply's `user_id`.
    pub user_id: String,
}

/// An existing key. Never carries the secret.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApiKey {
    /// Permitted source addresses. Empty means unrestricted.
    #[serde(default)]
    pub allowed_ips: Vec<String>,
    /// When it was created.
    pub created_at: DateTime<Utc>,
    /// When it stops working.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
    /// Opaque key identifier, used to revoke it.
    pub id: String,
    /// The public key id, sent as `X-API-Key`.
    pub key_id: String,
    /// Human label.
    pub label: String,
    /// When it was last used, if ever.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_used_at: Option<DateTime<Utc>>,
    /// Its rate-limit tier: `default`, or `mm` for a market maker's key, which only the exchange sets.
    pub rate_tier: String,
    /// Whether it has been revoked.
    pub revoked: bool,
    /// Granted scopes.
    #[serde(default)]
    pub scopes: Vec<ApiScope>,
}

open_enum! {
    /// Scope attached to an API key.
    ///
    /// Scopes narrow what an API key may do. They apply to API keys only: a signed-in session carries none and is not limited by them.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    ApiScope {
        Read => "read",
        Trade => "trade",
    }
}

/// An asset's policy on one network.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AssetNetwork {
    /// Contract address or chain asset id, for a token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contract_address: Option<String>,
    /// Confirmations before a deposit is credited.
    pub deposit_confirmations: i32,
    /// Whether deposits are accepted.
    pub deposit_enabled: bool,
    /// `maintenance`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance: Option<MaintenanceState>,
    /// `max_withdrawal`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_withdrawal: Option<Amount>,
    /// What to call the memo field in a UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo_label: Option<String>,
    /// Whether a memo is mandatory.
    pub memo_required: bool,
    /// Whether the network uses a memo / destination tag.
    pub memo_supported: bool,
    /// `min_deposit`
    pub min_deposit: Amount,
    /// `min_withdrawal`
    pub min_withdrawal: Amount,
    /// Network code.
    pub network: String,
    /// Network display name.
    pub network_name: String,
    /// Operator note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notice: Option<String>,
    /// How the asset exists on this chain.
    pub token_kind: String,
    /// Decimal places a withdrawal amount is truncated to.
    pub withdrawal_decimals: i32,
    /// Whether withdrawals are accepted.
    pub withdrawal_enabled: bool,
    /// `withdrawal_fee`
    pub withdrawal_fee: Amount,
    /// Asset the withdrawal fee is charged in.
    pub withdrawal_fee_asset: String,
}

/// A tradable asset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Asset {
    /// Accounting precision: the decimal places the exchange records internally.
    ///
    /// Use this for arithmetic. For rendering, use `display_decimals`.
    pub decimals: i32,
    /// Decimal places to show in a user interface.
    ///
    /// Always less than or equal to `decimals`. Rounding for display is presentation only and must never be fed back into a request.
    pub display_decimals: i32,
    /// Identifier for a client-bundled icon, when no logo URL is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_key: Option<String>,
    /// Logo URL, when the operator has configured one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logo_url: Option<String>,
    /// How old this asset's price may be before it is refused, in seconds.
    ///
    /// The global default unless an operator set an override for this asset. Exposed beside the flag because the flag alone cannot explain itself: an asset that is not stale after a week and one that is not stale after an hour look identical without it.
    pub max_price_age_secs: i64,
    /// Display name.
    pub name: String,
    /// Networks this asset can be deposited to or withdrawn from.
    #[serde(default)]
    pub networks: Vec<AssetNetwork>,
    /// Operator note, e.g. why deposits are paused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notice: Option<String>,
    /// Uppercase ticker.
    pub symbol: String,
    /// Whether the asset may appear in markets.
    pub trading_enabled: bool,
    /// `usd_price`
    pub usd_price: Amount,
    /// Whether that price is too old to compute with.
    ///
    /// When true, the exchange refuses to derive anything from it: daily limits and auto-approval fail closed rather than guess, and a stored USD value is recorded as absent rather than as a confident wrong figure.
    pub usd_price_stale: bool,
    /// When that price was last set.
    ///
    /// Exposed because the price is typed in by an operator and refreshed by nothing — there is no feed. Without the timestamp a caller cannot tell a price set an hour ago from one set last month, and both look equally authoritative.
    pub usd_price_updated_at: DateTime<Utc>,
    /// Project website.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub website_url: Option<String>,
}

/// A balance in one asset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Balance {
    /// Asset symbol.
    pub asset: String,
    /// `available`
    pub available: Amount,
    /// Internal transfers to this account still held, soonest released first; empty when none. Their sum is part of `locked`. Shows at most 100.
    #[serde(default)]
    pub held_incoming: Vec<HeldIncoming>,
    /// `locked`
    pub locked: Amount,
    /// `pending`
    pub pending: Amount,
    /// This balance's sequence: it rises with every change to it, and `balance.updated` carries the same number as `data.sequence`. Apply an event only if its sequence is greater than the one this snapshot holds. 0 for a balance never touched.
    #[serde(default)]
    pub sequence: i64,
    /// `total`
    pub total: Amount,
}

/// One order of a batch: an order as for `POST /trading/orders`, without the symbol, and with `client_order_id` required.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchOrderItem {
    /// Your own identifier, unique per account. Required: a retry of the batch is answered `ALREADY_EXISTS` for every order it already placed, so nothing is placed twice.
    pub client_order_id: String,
    /// `price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<Amount>,
    /// `quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantity: Option<Amount>,
    /// `quote_quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_quantity: Option<Amount>,
    /// `side`
    pub side: OrderSide,
    /// `stop_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<Amount>,
    /// `time_in_force`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<TimeInForce>,
    /// `trigger_direction`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_direction: Option<TriggerDirection>,
    /// `type`
    pub r#type: OrderType,
}

/// Places up to 20 orders in one market (Phase 0 B2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchOrderRequest {
    /// The orders, 1 to 20, placed one after another in this order.
    #[serde(default)]
    pub orders: Vec<BatchOrderItem>,
    /// The market every order is placed in.
    pub symbol: String,
}

impl BatchOrderRequest {
    /// A request with the required fields (symbol); the optional ones are unset.
    pub fn new(symbol: impl Into<String>) -> Self {
        Self {
            symbol: symbol.into(),
            orders: Default::default(),
        }
    }
}

/// What a batch did: one result per order, in the order sent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchOrder {
    /// How many were refused.
    pub failed: i64,
    /// How many were accepted.
    pub placed: i64,
    /// One per order sent, in the same order.
    #[serde(default)]
    pub results: Vec<BatchOrderResult>,
}

/// One order's outcome in a batch: exactly one of `order` and `error` is set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchOrderResult {
    /// Its `client_order_id`, as sent.
    pub client_order_id: String,
    /// `error`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorBody>,
    /// Fills produced on entry, oldest first; empty when refused.
    #[serde(default)]
    pub fills: Vec<Fill>,
    /// Its position in the request, from 0.
    pub index: i64,
    /// `order`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order: Option<Order>,
}

/// Arms, re-arms or disarms the dead-man switch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelAllAfterRequest {
    /// One market's orders only. Omitted or `null`, the switch covers every market; an empty string is refused (400). A per-market switch and the all-markets switch are separate: each fires on its own.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    /// Milliseconds from now after which the open orders in scope are cancelled, unless the switch is armed again first: from 5000 to 600000. `0` disarms.
    pub timeout_ms: i64,
}

impl CancelAllAfterRequest {
    /// A request with the required fields (timeout_ms); the optional ones are unset.
    pub fn new(timeout_ms: i64) -> Self {
        Self {
            timeout_ms,
            symbol: None,
        }
    }
}

/// The dead-man switch, as just set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelAllAfter {
    /// Whether a deadline is now armed for this scope. `false` after a disarm.
    pub armed: bool,
    /// When the orders are cancelled unless armed again. `null` when disarmed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deadline: Option<DateTime<Utc>>,
    /// The server's time after the deadline was stored, to measure the deadline against.
    pub server_time: DateTime<Utc>,
    /// The market it covers, or `null` for every market.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    /// The timeout asked for, in milliseconds.
    pub timeout_ms: i64,
}

/// Cancels every open order, optionally within one market.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CancelAllRequest {
    /// Limit the cancellation to one market. Omitted or `null`, every market's open orders are cancelled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
}

/// What a bulk cancellation achieved.
///
/// Every order the call handled is in exactly one of `cancelled`, `already_closed` and `failed`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelAllResult {
    /// Orders that closed on their own (filled, rejected, cancelled elsewhere) before this call reached them. Nothing was done to them, and they are not failures.
    #[serde(default)]
    pub already_closed: Vec<String>,
    /// Orders cancelled.
    #[serde(default)]
    pub cancelled: Vec<String>,
    /// Orders that could not be cancelled in this call. Check `failures` for why, then refresh or call again.
    #[serde(default)]
    pub failed: Vec<String>,
    /// Why each order in `failed` could not be cancelled.
    #[serde(default)]
    pub failures: Vec<CancelFailure>,
    /// More open orders exist than one call handles (500). Call again.
    pub has_more: bool,
}

/// One order to cancel: exactly one of `order_id` and `client_order_id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBatchItem {
    /// Your identifier for it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
    /// The order's id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
}

/// Cancels up to 50 orders, each named by its id or by your own (Phase 0 B2).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBatchRequest {
    /// The orders, 1 to 50, cancelled one after another in this order.
    #[serde(default)]
    pub orders: Vec<CancelBatchItem>,
}

/// What a batch cancel did: one result per entry, in the order sent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBatch {
    /// How many were cancelled.
    pub cancelled: i64,
    /// How many were not.
    pub failed: i64,
    /// One per entry sent, in the same order.
    #[serde(default)]
    pub results: Vec<CancelBatchResult>,
}

/// One entry's outcome in a batch cancel: exactly one of `order` and `error` is set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelBatchResult {
    /// The client order id, as sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
    /// `error`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorBody>,
    /// Its position in the request, from 0.
    pub index: i64,
    /// `order`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order: Option<Order>,
    /// The order id, as sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub order_id: Option<String>,
}

/// Why one order could not be cancelled.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CancelFailure {
    /// The error code of the attempt, as in any error response: e.g. `MARKET_UNAVAILABLE` for an order whose market is restarting, or `CONCURRENT_MODIFICATION`.
    pub code: String,
    /// Its message.
    pub message: String,
    /// The order.
    pub order_id: String,
}

/// One candle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesCandle {
    /// `close`
    pub close: Amount,
    /// Close time, unix milliseconds.
    pub close_time: i64,
    /// `high`
    pub high: Amount,
    /// `low`
    pub low: Amount,
    /// `open`
    pub open: Amount,
    /// Open time, unix milliseconds.
    pub open_time: i64,
    /// Number of trades.
    pub trades: i64,
    /// `volume`
    pub volume: Amount,
}

open_enum! {
    /// Candle/kline intervals for market data.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    CandleInterval {
        M1 => "1m",
        M5 => "5m",
        M15 => "15m",
        M30 => "30m",
        H1 => "1h",
        H4 => "4h",
        D1 => "1d",
        W1 => "1w",
    }
}

/// An OHLCV bucket.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Candle {
    /// `close`
    pub close: Amount,
    /// `high`
    pub high: Amount,
    /// `low`
    pub low: Amount,
    /// `open`
    pub open: Amount,
    /// Bucket start.
    pub open_time: DateTime<Utc>,
    /// `quote_volume`
    pub quote_volume: Amount,
    /// Number of trades.
    pub trade_count: i64,
    /// `volume`
    pub volume: Amount,
}

/// A deposit address.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DepositAddress {
    /// The address to send to.
    pub address: String,
    /// Asset symbol.
    pub asset: String,
    /// When the address was issued.
    pub created_at: DateTime<Utc>,
    /// Confirmations before the deposit is credited.
    pub deposit_confirmations: i32,
    /// Memo / destination tag. **Required when present** — a deposit without it may be unrecoverable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    /// What to call the memo field in a UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo_label: Option<String>,
    /// `min_deposit`
    pub min_deposit: Amount,
    /// Network code.
    pub network: String,
}

/// Unique identifier of a deposit.
pub type DepositId = String;

/// A deposit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Deposit {
    /// Address that received it.
    pub address: String,
    /// `amount`
    pub amount: Amount,
    /// Asset symbol.
    pub asset: String,
    /// Confirmations observed.
    pub confirmations: i32,
    /// When it was credited.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credited_at: Option<DateTime<Utc>>,
    /// Explorer link, when the network has one configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub explorer_url: Option<String>,
    /// When it was first observed.
    pub first_seen_at: DateTime<Utc>,
    /// Deposit id.
    pub id: String,
    /// Memo, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    /// Network code.
    pub network: String,
    /// Operator note, e.g. why it was reversed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Position within the transaction. Distinguishes two outputs of one transaction.
    pub output_index: i32,
    /// Confirmations required to credit.
    pub required_confirmations: i32,
    /// `status`
    pub status: DepositStatus,
    /// Transaction hash.
    pub txid: String,
}

open_enum! {
    /// Lifecycle of an incoming blockchain deposit.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    DepositStatus {
        Detected => "detected",
        Credited => "credited",
        Reversed => "reversed",
        Orphaned => "orphaned",
        BelowMinimum => "below_minimum",
        UnderReview => "under_review",
        Internal => "internal",
    }
}

open_enum! {
    /// Stable, machine-readable error identifiers.
    ///
    /// Serialized as `SCREAMING_SNAKE_CASE`. Adding a variant is backwards-compatible; renaming or removing one is a breaking API change.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    ErrorCode {
        ValidationFailed => "VALIDATION_FAILED",
        MalformedRequest => "MALFORMED_REQUEST",
        InvalidCursor => "INVALID_CURSOR",
        PrecisionExceeded => "PRECISION_EXCEEDED",
        BelowMinimum => "BELOW_MINIMUM",
        AboveMaximum => "ABOVE_MAXIMUM",
        InvalidAddress => "INVALID_ADDRESS",
        MemoRequired => "MEMO_REQUIRED",
        Unauthenticated => "UNAUTHENTICATED",
        InvalidCredentials => "INVALID_CREDENTIALS",
        TokenExpired => "TOKEN_EXPIRED",
        SessionRevoked => "SESSION_REVOKED",
        TwoFactorRequired => "TWO_FACTOR_REQUIRED",
        TwoFactorInvalid => "TWO_FACTOR_INVALID",
        FreshTwoFactorRequired => "FRESH_TWO_FACTOR_REQUIRED",
        Forbidden => "FORBIDDEN",
        ApiKeyNotAllowed => "API_KEY_NOT_ALLOWED",
        KeyNotSignable => "KEY_NOT_SIGNABLE",
        SignatureExpired => "SIGNATURE_EXPIRED",
        NonceReused => "NONCE_REUSED",
        SignatureRequired => "SIGNATURE_REQUIRED",
        FuturesRestricted => "FUTURES_RESTRICTED",
        AccountFrozen => "ACCOUNT_FROZEN",
        AccountOnHold => "ACCOUNT_ON_HOLD",
        EmailNotVerified => "EMAIL_NOT_VERIFIED",
        RegionBlocked => "REGION_BLOCKED",
        JurisdictionBlocked => "JURISDICTION_BLOCKED",
        NotFound => "NOT_FOUND",
        MethodNotAllowed => "METHOD_NOT_ALLOWED",
        AlreadyExists => "ALREADY_EXISTS",
        InvalidState => "INVALID_STATE",
        IdempotencyKeyConflict => "IDEMPOTENCY_KEY_CONFLICT",
        WindowOpen => "WINDOW_OPEN",
        EvidenceContradicts => "EVIDENCE_CONTRADICTS",
        AmountMismatch => "AMOUNT_MISMATCH",
        ConcurrentModification => "CONCURRENT_MODIFICATION",
        DeadManNotArmed => "DEAD_MAN_NOT_ARMED",
        InsufficientFunds => "INSUFFICIENT_FUNDS",
        InsufficientFeeFunds => "INSUFFICIENT_FEE_FUNDS",
        MarketUnavailable => "MARKET_UNAVAILABLE",
        DepositDisabled => "DEPOSIT_DISABLED",
        WithdrawalDisabled => "WITHDRAWAL_DISABLED",
        SelfTradeBlocked => "SELF_TRADE_BLOCKED",
        LimitExceeded => "LIMIT_EXCEEDED",
        PriceUnavailable => "PRICE_UNAVAILABLE",
        RateLimited => "RATE_LIMITED",
        Internal => "INTERNAL",
        ServiceUnavailable => "SERVICE_UNAVAILABLE",
        UnderMaintenance => "UNDER_MAINTENANCE",
        EngineOverloaded => "ENGINE_OVERLOADED",
        /// The server answered with a redirect (3xx). The SDK never follows redirects, so
        /// credentials and orders are never re-sent to another URL. Set by the SDK; the API
        /// never sends it.
        UnexpectedRedirect => "UNEXPECTED_REDIRECT",
    }
}

/// Public exchange configuration.
///
/// Everything a frontend needs to render itself without a deploy: branding, limits, supported intervals, and whether the exchange is in maintenance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExchangeConfig {
    /// Candle intervals the API serves.
    #[serde(default)]
    pub candle_intervals: Vec<CandleInterval>,
    /// Default page size for paginated endpoints.
    pub default_page_size: i32,
    /// Whether registration verifies the email address with an emailed code before the authenticator step. Lets a signup form show the right number of steps up front.
    pub email_verification_required: bool,
    /// Feature flags a frontend may use to hide unavailable functionality.
    ///
    /// Presentation only. The backend enforces every rule independently.
    #[serde(default)]
    pub features: BTreeMap<String, bool>,
    /// Message to show while in maintenance.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maintenance_message: Option<String>,
    /// Whether the exchange is in maintenance mode.
    pub maintenance_mode: bool,
    /// Maximum page size.
    pub max_page_size: i32,
    /// Display name.
    pub name: String,
    /// `password_rules`
    pub password_rules: PasswordRules,
    /// Whether new registrations are accepted.
    pub registration_enabled: bool,
    /// Support contact.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub support_url: Option<String>,
    /// Seconds a verified two-factor code authorises sensitive actions for.
    pub two_factor_freshness_seconds: i64,
    /// Where to open the realtime connection, relative to this API's origin.
    pub websocket_path: String,
    /// The realtime protocol version this server speaks.
    pub websocket_protocol_version: i32,
}

/// Removes liquidity from a pool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExitPoolRequest {
    /// `shares`
    pub shares: Amount,
}

impl ExitPoolRequest {
    /// A request with the required fields (shares); the optional ones are unset.
    pub fn new(shares: Amount) -> Self {
        Self { shares }
    }
}

/// What an exit produced.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExitPoolResult {
    /// `base_returned`
    pub base_returned: Amount,
    /// `quote_returned`
    pub quote_returned: Amount,
    /// `shares_burned`
    pub shares_burned: Amount,
    /// `shares_held`
    pub shares_held: Amount,
}

/// A fee tier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FeeSchedule {
    /// Human label.
    pub label: String,
    /// Maker rate, as a percentage.
    pub maker_fee_percent: String,
    /// `min_30d_volume_usd`
    pub min_30d_volume_usd: Amount,
    /// Taker rate, as a percentage.
    pub taker_fee_percent: String,
    /// Tier index.
    pub tier: i32,
}

/// One fill.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesFill {
    /// `closed_pnl`
    pub closed_pnl: Amount,
    /// Coin.
    pub coin: String,
    /// The provider's description of the fill's effect (`Open Long`, `Close Short`, ...).
    pub direction: String,
    /// Our id for it.
    pub id: String,
    /// Our id for its order.
    pub order_id: String,
    /// `price`
    pub price: Amount,
    /// `buy` or `sell`.
    pub side: String,
    /// `size`
    pub size: Amount,
    /// Whether this fill took liquidity.
    pub taker: bool,
    /// When, unix milliseconds.
    pub time: i64,
}

/// One of the caller's executions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Fill {
    /// `fee`
    pub fee: Amount,
    /// Asset the fee was charged in.
    pub fee_asset: String,
    /// The caller's order.
    pub order_id: String,
    /// `price`
    pub price: Amount,
    /// `quantity`
    pub quantity: Amount,
    /// `quote_quantity`
    pub quote_quantity: Amount,
    /// `role`
    pub role: LiquidityRole,
    /// `side`
    pub side: OrderSide,
    /// Market symbol.
    pub symbol: String,
    /// When it executed.
    pub timestamp: DateTime<Utc>,
    /// Trade id.
    pub trade_id: String,
}

/// One funding payment.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Funding {
    /// `amount`
    pub amount: Amount,
    /// Coin.
    pub coin: String,
    /// `position_size`
    pub position_size: Amount,
    /// `rate`
    pub rate: Amount,
    /// When, unix milliseconds.
    pub time: i64,
}

/// A futures market's book.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesBook {
    /// When the provider last sent it.
    pub as_of: DateTime<Utc>,
    /// Asks, best first.
    #[serde(default)]
    pub asks: Vec<Level>,
    /// Bids, best first.
    #[serde(default)]
    pub bids: Vec<Level>,
    /// Coin.
    pub coin: String,
    /// The live feed is not healthy: the book may be out of date.
    pub stale: bool,
}

/// A futures market's candles.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesCandles {
    /// When read.
    pub as_of: DateTime<Utc>,
    /// Candles, oldest first.
    #[serde(default)]
    pub candles: Vec<FuturesCandle>,
    /// Coin.
    pub coin: String,
    /// Interval.
    pub interval: String,
    /// Older than it should be.
    pub stale: bool,
}

/// A page of the account's fills.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesFills {
    /// Newest first; fills sharing a millisecond in a fixed order. A page may be short of 100 and still be followed by more.
    #[serde(default)]
    pub fills: Vec<FuturesFill>,
    /// Whether the account has a futures account.
    pub has_account: bool,
    /// Pass as `cursor` for older fills, exactly as given; `null` at the end (30 days back). Opaque: it may carry more than a time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// A page of the account's funding payments.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesFunding {
    /// Newest first.
    #[serde(default)]
    pub funding: Vec<Funding>,
    /// Whether the account has a futures account.
    pub has_account: bool,
    /// Pass as `cursor` for older payments, exactly as given; `null` at the end (30 days back). Opaque.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// One futures market.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesMarket {
    /// When this data was read.
    pub as_of: DateTime<Utc>,
    /// `market`
    pub market: PerpMarket,
    /// Older than it should be.
    pub stale: bool,
}

/// Every listed futures market.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesMarkets {
    /// When this data was read from the futures provider.
    pub as_of: DateTime<Utc>,
    /// The markets, in the provider's order. Delisted markets are not included.
    #[serde(default)]
    pub markets: Vec<PerpMarket>,
    /// The data is older than it should be: the provider could not be read just now.
    pub stale: bool,
}

/// The account's open orders.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesOpenOrders {
    /// When read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub as_of: Option<DateTime<Utc>>,
    /// Whether the account has a futures account.
    pub has_account: bool,
    /// The open orders.
    #[serde(default)]
    pub orders: Vec<OpenOrder>,
    /// Older than it should be.
    pub stale: bool,
}

/// The account's positions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesPositions {
    /// When read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub as_of: Option<DateTime<Utc>>,
    /// Whether the account has a futures account. Without one, nothing else is meaningful.
    pub has_account: bool,
    /// `positions`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub positions: Option<Positions>,
    /// Older than it should be.
    pub stale: bool,
}

/// A futures market's recent public trades.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesTrades {
    /// Coin.
    pub coin: String,
    /// The live feed is not healthy, or was only just opened: trades may be missing.
    pub stale: bool,
    /// Newest first.
    #[serde(default)]
    pub trades: Vec<FuturesPublicTrade>,
}

/// Unique identifier of a futures collateral transfer.
pub type FuturesTransferId = String;

/// An internal transfer credited to `locked` and not yet available.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct HeldIncoming {
    /// `amount`
    pub amount: Amount,
    /// When it becomes available, unless an operator cancels it before then.
    pub available_at: DateTime<Utc>,
    /// The transfer.
    pub transfer_id: String,
}

/// Adds liquidity to a pool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JoinPoolRequest {
    /// `base_amount`
    pub base_amount: Amount,
    /// `max_ratio_deviation_percent`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_ratio_deviation_percent: Option<Amount>,
    /// `quote_amount`
    pub quote_amount: Amount,
}

impl JoinPoolRequest {
    /// A request with the required fields (base_amount, quote_amount); the optional ones are unset.
    pub fn new(base_amount: Amount, quote_amount: Amount) -> Self {
        Self {
            base_amount,
            quote_amount,
            max_ratio_deviation_percent: None,
        }
    }
}

/// What a join produced.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JoinPoolResult {
    /// `base_deposited`
    pub base_deposited: Amount,
    /// `quote_deposited`
    pub quote_deposited: Amount,
    /// `shares_held`
    pub shares_held: Amount,
    /// `shares_minted`
    pub shares_minted: Amount,
}

open_enum! {
    /// What a ledger entry records.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    LedgerEntryKind {
        Deposit => "deposit",
        DepositReversal => "deposit_reversal",
        WithdrawalDebit => "withdrawal_debit",
        WithdrawalFee => "withdrawal_fee",
        WithdrawalFeeReserve => "withdrawal_fee_reserve",
        WithdrawalRelease => "withdrawal_release",
        WithdrawalFeeRelease => "withdrawal_fee_release",
        OrderReserve => "order_reserve",
        WithdrawalReserve => "withdrawal_reserve",
        OrderRelease => "order_release",
        TradeDebit => "trade_debit",
        TradeCredit => "trade_credit",
        TradeFee => "trade_fee",
        TransferOut => "transfer_out",
        TransferIn => "transfer_in",
        TransferInHeld => "transfer_in_held",
        TransferRelease => "transfer_release",
        TransferReversal => "transfer_reversal",
        AdjustmentCredit => "adjustment_credit",
        AdjustmentDebit => "adjustment_debit",
        Rebate => "rebate",
        PoolJoin => "pool_join",
        PoolExit => "pool_exit",
        FuturesTransferReserve => "futures_transfer_reserve",
        FuturesTransferRelease => "futures_transfer_release",
        FuturesCollateralSent => "futures_collateral_sent",
        FuturesCollateralReturned => "futures_collateral_returned",
        WithdrawalRefund => "withdrawal_refund",
    }
}

/// One entry from the account's ledger.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerEntry {
    /// Asset symbol.
    pub asset: String,
    /// `available_after`
    pub available_after: Amount,
    /// `available_delta`
    pub available_delta: Amount,
    /// When it was applied.
    pub created_at: DateTime<Utc>,
    /// Entry id.
    pub id: String,
    /// `kind`
    pub kind: LedgerEntryKind,
    /// `locked_delta`
    pub locked_delta: Amount,
    /// `pending_delta`
    pub pending_delta: Amount,
    /// `reference`
    #[serde(default)]
    pub reference: LedgerReference,
    /// Position in this account's history for this asset.
    pub sequence: i64,
}

/// A blockchain deposit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceDeposit {
    /// `deposit_id`
    pub deposit_id: DepositId,
}

/// A withdrawal request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceWithdrawal {
    /// `withdrawal_id`
    pub withdrawal_id: WithdrawalId,
}

/// An order reservation or release.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceOrder {
    /// `order_id`
    pub order_id: OrderId,
}

/// A trade settlement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceTrade {
    /// `order_id`
    pub order_id: OrderId,
    /// `trade_id`
    pub trade_id: TradeId,
}

/// An internal transfer between accounts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceTransfer {
    /// `counterparty_user_id`
    pub counterparty_user_id: UserId,
    /// Shared reference linking both halves.
    pub transfer_ref: String,
}

/// A manual operator adjustment. Always accompanied by an audit event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceAdjustment {
    /// `operator_user_id`
    pub operator_user_id: UserId,
}

/// A liquidity pool join or exit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferencePool {
    /// `pool_id`
    pub pool_id: PoolId,
}

/// A movement of collateral to or from a futures account.
///
/// Every entry a transfer produces carries the same one, so the reservation, the release and the completion can be read back as one event — which is what an operator resolving an ambiguous transfer needs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceFuturesTransfer {
    /// `futures_transfer_id`
    pub futures_transfer_id: FuturesTransferId,
}

/// A system-originated credit with no user counterparty (rebate, promotion).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LedgerReferenceSystem {
    /// Short machine-readable cause.
    pub cause: String,
}

/// What caused a ledger entry: one kind of cause per variant, told apart by `type`.
///
/// Decoding never fails on a kind this SDK does not know yet (or a known kind with an
/// unexpected shape): it becomes [`LedgerReference::Unknown`] with the raw JSON.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LedgerReference {
    /// `type: "deposit"`
    Deposit(LedgerReferenceDeposit),
    /// `type: "withdrawal"`
    Withdrawal(LedgerReferenceWithdrawal),
    /// `type: "order"`
    Order(LedgerReferenceOrder),
    /// `type: "trade"`
    Trade(LedgerReferenceTrade),
    /// `type: "transfer"`
    Transfer(LedgerReferenceTransfer),
    /// `type: "adjustment"`
    Adjustment(LedgerReferenceAdjustment),
    /// `type: "pool"`
    Pool(LedgerReferencePool),
    /// `type: "futures_transfer"`
    FuturesTransfer(LedgerReferenceFuturesTransfer),
    /// `type: "system"`
    System(LedgerReferenceSystem),
    /// A kind this SDK does not know yet, kept as the raw JSON object.
    Unknown(serde_json::Value),
}

impl Default for LedgerReference {
    /// `Unknown(null)`: what a missing value decodes as.
    fn default() -> Self {
        Self::Unknown(serde_json::Value::Null)
    }
}

impl LedgerReference {
    /// The `type` tag of this value.
    pub fn kind(&self) -> &str {
        match self {
            Self::Deposit(_) => "deposit",
            Self::Withdrawal(_) => "withdrawal",
            Self::Order(_) => "order",
            Self::Trade(_) => "trade",
            Self::Transfer(_) => "transfer",
            Self::Adjustment(_) => "adjustment",
            Self::Pool(_) => "pool",
            Self::FuturesTransfer(_) => "futures_transfer",
            Self::System(_) => "system",
            Self::Unknown(v) => v.get("type").and_then(|t| t.as_str()).unwrap_or(""),
        }
    }
}

impl<'de> Deserialize<'de> for LedgerReference {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let v = serde_json::Value::deserialize(d)?;
        let parsed = match v.get("type").and_then(|t| t.as_str()) {
            Some("deposit") => serde_json::from_value(v.clone()).ok().map(Self::Deposit),
            Some("withdrawal") => serde_json::from_value(v.clone()).ok().map(Self::Withdrawal),
            Some("order") => serde_json::from_value(v.clone()).ok().map(Self::Order),
            Some("trade") => serde_json::from_value(v.clone()).ok().map(Self::Trade),
            Some("transfer") => serde_json::from_value(v.clone()).ok().map(Self::Transfer),
            Some("adjustment") => serde_json::from_value(v.clone()).ok().map(Self::Adjustment),
            Some("pool") => serde_json::from_value(v.clone()).ok().map(Self::Pool),
            Some("futures_transfer") => serde_json::from_value(v.clone())
                .ok()
                .map(Self::FuturesTransfer),
            Some("system") => serde_json::from_value(v.clone()).ok().map(Self::System),
            _ => None,
        };
        Ok(parsed.unwrap_or(Self::Unknown(v)))
    }
}

impl Serialize for LedgerReference {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let (tag, mut v) = match self {
            Self::Deposit(x) => (
                "deposit",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Withdrawal(x) => (
                "withdrawal",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Order(x) => (
                "order",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Trade(x) => (
                "trade",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Transfer(x) => (
                "transfer",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Adjustment(x) => (
                "adjustment",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Pool(x) => (
                "pool",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::FuturesTransfer(x) => (
                "futures_transfer",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::System(x) => (
                "system",
                serde_json::to_value(x).map_err(serde::ser::Error::custom)?,
            ),
            Self::Unknown(v) => return v.serialize(s),
        };
        if let serde_json::Value::Object(m) = &mut v {
            m.insert("type".to_owned(), serde_json::Value::String(tag.to_owned()));
        }
        v.serialize(s)
    }
}

/// One price level.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Level {
    /// `price`
    pub price: Amount,
    /// `size`
    pub size: Amount,
}

open_enum! {
    /// Whether a fill added liquidity (maker) or removed it (taker).
    ///
    /// The type is open: values added to the API later decode as `Other`.
    LiquidityRole {
        Maker => "maker",
        Taker => "taker",
    }
}

open_enum! {
    /// Machine-readable reasons a capability is unavailable.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    MaintenanceReason {
        ExchangeMaintenance => "exchange_maintenance",
        NetworkUnavailable => "network_unavailable",
        DepositsDisabled => "deposits_disabled",
        WithdrawalsDisabled => "withdrawals_disabled",
        AssetUnavailable => "asset_unavailable",
    }
}

/// Why a capability is currently unavailable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MaintenanceState {
    /// Operator-supplied explanation, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// `reason`
    pub reason: MaintenanceReason,
}

/// A tradable market and its current ticker.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Market {
    /// Base asset symbol.
    pub base_asset: String,
    /// `best_ask`
    pub best_ask: Amount,
    /// `best_bid`
    pub best_bid: Amount,
    /// `change_24h_percent`
    pub change_24h_percent: Amount,
    /// `high_24h`
    pub high_24h: Amount,
    /// `last_price`
    pub last_price: Amount,
    /// Time of the most recent trade.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_trade_at: Option<DateTime<Utc>>,
    /// `lot_size`
    pub lot_size: Amount,
    /// `low_24h`
    pub low_24h: Amount,
    /// `max_quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_quantity: Option<Amount>,
    /// `min_notional`
    pub min_notional: Amount,
    /// `min_quantity`
    pub min_quantity: Amount,
    /// Decimal places a price may carry.
    pub price_decimals: i32,
    /// Decimal places a quantity may carry.
    pub quantity_decimals: i32,
    /// Quote asset symbol.
    pub quote_asset: String,
    /// `quote_volume_24h`
    pub quote_volume_24h: Amount,
    /// `status`
    pub status: MarketStatus,
    /// Order types this market accepts.
    #[serde(default)]
    pub supported_order_types: Vec<OrderType>,
    /// Time-in-force options this market accepts.
    #[serde(default)]
    pub supported_time_in_force: Vec<TimeInForce>,
    /// `BASE/QUOTE`.
    pub symbol: String,
    /// `tick_size`
    pub tick_size: Amount,
    /// When trading opens, for a market not yet live.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trading_starts_at: Option<DateTime<Utc>>,
    /// `volume_24h`
    pub volume_24h: Amount,
}

open_enum! {
    /// Trading availability of a market.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    MarketStatus {
        Active => "active",
        Paused => "paused",
        SellOnly => "sell_only",
        PreTrading => "pre_trading",
        Delisted => "delisted",
    }
}

/// A blockchain network.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Network {
    /// Typical seconds between blocks, for estimating confirmation time.
    pub average_block_seconds: i32,
    /// Stable code.
    pub code: String,
    /// Whether deposits on this network are actually being detected.
    ///
    /// False means either half of the pipeline is down: the last scan pass failed — a refused block range, a rate limit, a node that answers but will not serve logs — or finality could not be established, so deposits are being held rather than credited.
    ///
    /// Deposits sent now will be credited late, whenever the chain recovers, rather than lost. This is the field a status page should use to say deposits are degraded; `reachable` only says the node replies, which it may well do while yielding nothing.
    pub deposits_operational: bool,
    /// Template for an address explorer link. `{address}` is substituted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub explorer_address_url_template: Option<String>,
    /// Template for a transaction explorer link. `{txid}` is substituted.
    ///
    /// Absent when the operator has configured none; render no link rather than guessing a URL.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub explorer_tx_url_template: Option<String>,
    /// Whether the network is operational.
    pub is_active: bool,
    /// Display name.
    pub name: String,
    /// Whether the node answers at all.
    ///
    /// Narrower than it sounds, and deliberately so: a reachable node can still be failing to yield deposits. Do not render this alone as "network up".
    pub reachable: bool,
}

open_enum! {
    /// What a notice is about.
    ///
    /// A closed enum so a client can render each kind deliberately — an icon, a colour, a link — rather than pattern-matching on prose that may be reworded.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    NotificationKind {
        DepositDetected => "deposit_detected",
        DepositCredited => "deposit_credited",
        WithdrawalRequested => "withdrawal_requested",
        WithdrawalSent => "withdrawal_sent",
        WithdrawalCompleted => "withdrawal_completed",
        WithdrawalFailed => "withdrawal_failed",
        OrderFilled => "order_filled",
        OrderClosed => "order_closed",
        Security => "security",
        ListingDecision => "listing_decision",
        Announcement => "announcement",
    }
}

/// An in-app notice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Notification {
    /// One or two sentences.
    pub body: String,
    /// When it was created.
    pub created_at: DateTime<Utc>,
    /// Notice id.
    pub id: String,
    /// `kind`
    pub kind: NotificationKind,
    /// Whether it has been read.
    pub read: bool,
    /// The referenced resource's opaque id, for linking.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<String>,
    /// What it refers to: `deposit`, `withdrawal`, `order`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_type: Option<String>,
    /// Short heading.
    pub title: String,
}

/// One open order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OpenOrder {
    /// Coin.
    pub coin: String,
    /// Our id for it, stable across reads.
    pub id: String,
    /// The order type as the provider names it (`Limit`, `Stop Market`, ...).
    pub order_type: String,
    /// `original_size`
    pub original_size: Amount,
    /// When placed, unix milliseconds.
    pub placed_at: i64,
    /// `price`
    pub price: Amount,
    /// Whether it may only reduce a position.
    pub reduce_only: bool,
    /// `buy` or `sell`.
    pub side: String,
    /// `size`
    pub size: Amount,
    /// `trigger_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_price: Option<Amount>,
}

/// One side of the order book, aggregated by price.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderBook {
    /// Asks, best first.
    #[serde(default)]
    pub asks: Vec<Vec<Amount>>,
    /// Bids, best first, as `[price, quantity]` pairs.
    #[serde(default)]
    pub bids: Vec<Vec<Amount>>,
    /// The realtime sequence this snapshot is current as of.
    ///
    /// Each `orderbook.update` on the `orderbook:{symbol}` websocket channel carries both sides of the top 50 levels in full (`data.full` is always `true`) and replaces the previous state; there are no deltas to buffer. Ignore an update whose `sequence` is at or below the one you hold. A gap only means a book was missed: the next update replaces it whole.
    pub sequence: i64,
    /// Market symbol.
    pub symbol: String,
    /// When this snapshot was taken.
    pub timestamp: DateTime<Utc>,
}

/// Unique identifier of an order.
pub type OrderId = String;

/// An order.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Order {
    /// `average_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub average_price: Option<Amount>,
    /// Your identifier, if you supplied one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
    /// When it reached a terminal state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closed_at: Option<DateTime<Utc>>,
    /// When it was placed.
    pub created_at: DateTime<Utc>,
    /// Asset the fees were charged in.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fee_asset: Option<String>,
    /// `fee_paid`
    pub fee_paid: Amount,
    /// `filled_quantity`
    pub filled_quantity: Amount,
    /// `filled_quote_quantity`
    pub filled_quote_quantity: Amount,
    /// Order id.
    pub id: String,
    /// `price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<Amount>,
    /// `quantity`
    pub quantity: Amount,
    /// `quote_quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_quantity: Option<Amount>,
    /// `remaining_quantity`
    pub remaining_quantity: Amount,
    /// `reserved_remaining`
    pub reserved_remaining: Amount,
    /// `side`
    pub side: OrderSide,
    /// `status`
    pub status: OrderStatus,
    /// Why the order was rejected or cancelled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status_reason: Option<String>,
    /// `stop_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<Amount>,
    /// Market symbol.
    pub symbol: String,
    /// `time_in_force`
    pub time_in_force: TimeInForce,
    /// `trigger_direction`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_direction: Option<TriggerDirection>,
    /// When the trigger fired, if it has.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub triggered_at: Option<DateTime<Utc>>,
    /// `type`
    pub r#type: OrderType,
    /// When it last changed.
    pub updated_at: DateTime<Utc>,
}

open_enum! {
    /// Which side of a market an order takes.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    OrderSide {
        Buy => "buy",
        Sell => "sell",
    }
}

open_enum! {
    /// Lifecycle of an order.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    OrderStatus {
        Pending => "pending",
        Open => "open",
        PartiallyFilled => "partially_filled",
        Filled => "filled",
        Cancelled => "cancelled",
        Rejected => "rejected",
        PendingTrigger => "pending_trigger",
        Expired => "expired",
    }
}

open_enum! {
    /// Order types the matching engine accepts.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    OrderType {
        Limit => "limit",
        Market => "market",
        StopLimit => "stop_limit",
        StopMarket => "stop_market",
    }
}

/// Password constraints, published so a form can validate locally.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PasswordRules {
    /// Whether the password may contain the account's email address.
    pub allows_email_substring: bool,
    /// A short description of any further rules, for display beside the input.
    pub description: String,
    /// Maximum length in characters.
    pub max_length: i64,
    /// Minimum length in characters.
    pub min_length: i64,
}

/// One listed perpetual market and its current figures.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PerpMarket {
    /// The provider's coin name, e.g. `BTC` or `kPEPE`.
    pub coin: String,
    /// `funding_rate`
    pub funding_rate: Amount,
    /// `mark_price`
    pub mark_price: Amount,
    /// The highest leverage allowed.
    pub max_leverage: i32,
    /// `mid_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mid_price: Option<Amount>,
    /// `open_interest`
    pub open_interest: Amount,
    /// `oracle_price`
    pub oracle_price: Amount,
    /// `price_24h_ago`
    pub price_24h_ago: Amount,
    /// Decimal places a size may have.
    pub size_decimals: i32,
    /// `volume_24h`
    pub volume_24h: Amount,
}

/// Places an order.
///
/// Set `client_order_id` to make a retry safe: it is unique per account, so a repeat is refused before any funds move, and `GET /trading/orders/by-client-id/{client_order_id}` recovers the outcome. `Idempotency-Key` is not honoured for orders.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlaceOrderRequest {
    /// Your own identifier. Unique per account.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_order_id: Option<String>,
    /// `price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<Amount>,
    /// `quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quantity: Option<Amount>,
    /// `quote_quantity`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub quote_quantity: Option<Amount>,
    /// `side`
    pub side: OrderSide,
    /// `stop_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stop_price: Option<Amount>,
    /// Market symbol.
    pub symbol: String,
    /// `time_in_force`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_in_force: Option<TimeInForce>,
    /// `trigger_direction`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_direction: Option<TriggerDirection>,
    /// `type`
    pub r#type: OrderType,
}

impl PlaceOrderRequest {
    /// A request with the required fields (symbol, side, type); the optional ones are unset.
    pub fn new(symbol: impl Into<String>, side: OrderSide, r#type: OrderType) -> Self {
        Self {
            symbol: symbol.into(),
            side,
            r#type,
            client_order_id: None,
            price: None,
            quantity: None,
            quote_quantity: None,
            stop_price: None,
            time_in_force: None,
            trigger_direction: None,
        }
    }
}

/// The result of placing an order, including anything it executed immediately.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PlaceOrderResponse {
    /// Fills produced on entry, oldest first.
    #[serde(default)]
    pub fills: Vec<Fill>,
    /// `order`
    pub order: Order,
}

/// Unique identifier of a liquidity pool.
pub type PoolId = String;

/// A pool as a client sees it.
///
/// Reserves are the custody account's balances, so they include liquidity currently locked in resting orders. `price` is the curve's mid, which sits between the pool's own best bid and ask by exactly its fee — it is not a traded price.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Pool {
    /// `base_reserve`
    pub base_reserve: Amount,
    /// When the pool was created.
    pub created_at: DateTime<Utc>,
    /// The pool's fee, in percent, priced into every quote it rests.
    pub fee_percent: String,
    /// Identifier.
    pub id: String,
    /// Ladder steps per side.
    pub ladder_steps: i32,
    /// `price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub price: Option<Amount>,
    /// `quote_reserve`
    pub quote_reserve: Amount,
    /// `shares_outstanding`
    pub shares_outstanding: Amount,
    /// `status`
    pub status: PoolStatus,
    /// Market the pool quotes.
    pub symbol: String,
}

open_enum! {
    /// Whether a pool quotes, and whether it accepts new liquidity.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    PoolStatus {
        Active => "active",
        Paused => "paused",
        Closing => "closing",
    }
}

/// One open position.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Position {
    /// Coin.
    pub coin: String,
    /// `entry_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry_price: Option<Amount>,
    /// `funding_since_open`
    pub funding_since_open: Amount,
    /// Leverage.
    pub leverage: i32,
    /// `cross` or `isolated`.
    pub leverage_type: String,
    /// `liquidation_price`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub liquidation_price: Option<Amount>,
    /// `margin_used`
    pub margin_used: Amount,
    /// `position_value`
    pub position_value: Amount,
    /// `return_on_equity`
    pub return_on_equity: Amount,
    /// `size`
    pub size: Amount,
    /// `unrealized_pnl`
    pub unrealized_pnl: Amount,
}

/// A margin summary and the open positions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Positions {
    /// `account_value`
    pub account_value: Amount,
    /// `maintenance_margin`
    pub maintenance_margin: Amount,
    /// `margin_used`
    pub margin_used: Amount,
    /// The open positions.
    #[serde(default)]
    pub positions: Vec<Position>,
    /// `total_notional`
    pub total_notional: Amount,
}

/// A public trade, with nothing that identifies the parties.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FuturesPublicTrade {
    /// `price`
    pub price: Amount,
    /// `buy` or `sell`: the taker's side.
    pub side: String,
    /// `size`
    pub size: Amount,
    /// When, unix milliseconds.
    pub time: i64,
}

/// A public trade.
///
/// Deliberately anonymous: no account identifiers, and no indication of which side was the resting order beyond the aggressor direction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PublicTrade {
    /// Trade id.
    pub id: String,
    /// `price`
    pub price: Amount,
    /// `quantity`
    pub quantity: Amount,
    /// Gapless per-market sequence.
    pub sequence: i64,
    /// `side`
    pub side: OrderSide,
    /// When it executed.
    pub timestamp: DateTime<Utc>,
}

/// The server's clock.
///
/// Two-factor codes are time-based, so a client can compare its own clock against this before a skewed clock gets a correct code rejected.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ServerTime {
    /// Current time in milliseconds since the Unix epoch.
    pub epoch_ms: i64,
    /// Current time as RFC 3339 with an explicit UTC offset.
    pub iso: String,
}

open_enum! {
    /// Sort direction for a paginated listing.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    SortDirection {
        Asc => "asc",
        Desc => "desc",
    }
}

/// A sub-account.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubAccount {
    /// Always `false`. A sub-account has no withdrawal path — stated explicitly so a client does not have to infer it.
    pub can_withdraw: bool,
    /// When it was created.
    pub created_at: DateTime<Utc>,
    /// Opaque identifier. Use it to transfer funds and to issue API keys.
    pub id: String,
    /// Whether it may trade.
    pub is_active: bool,
    /// The label given at creation.
    pub label: String,
}

open_enum! {
    /// How long an order remains eligible to match.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    TimeInForce {
        Gtc => "gtc",
        Ioc => "ioc",
        Fok => "fok",
        PostOnly => "post_only",
    }
}

/// Unique identifier of a trade.
pub type TradeId = String;

open_enum! {
    /// Which way the price must move for a stop to fire.
    ///
    /// Explicit rather than inferred from the side, because the inference is ambiguous: a sell stop below the market is a stop-loss, and a sell stop above it is a take-profit. Both are legitimate, and guessing wrong means an order that fires at exactly the wrong moment — which is the one thing a protective order must never do.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    TriggerDirection {
        Above => "above",
        Below => "below",
    }
}

/// Unique identifier of a user account.
pub type UserId = String;

/// A saved withdrawal address.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WithdrawalAddress {
    /// The address.
    pub address: String,
    /// Asset, when restricted to one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub asset: Option<String>,
    /// When it was saved.
    pub created_at: DateTime<Utc>,
    /// Address-book entry id.
    pub id: String,
    /// Your label.
    pub label: String,
    /// When it was last withdrawn to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_used_at: Option<DateTime<Utc>>,
    /// Memo, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    /// Network code.
    pub network: String,
    /// Whether ownership has been confirmed.
    pub verified: bool,
}

/// One transition in a withdrawal's life.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WithdrawalHistoryEntry {
    /// When.
    pub at: DateTime<Utc>,
    /// Why, where a reason applies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// `status`
    pub status: WithdrawalStatus,
}

/// Unique identifier of a withdrawal.
pub type WithdrawalId = String;

/// A withdrawal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Withdrawal {
    /// Destination.
    pub address: String,
    /// `amount`
    pub amount: Amount,
    /// Asset symbol.
    pub asset: String,
    /// When it was broadcast.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub broadcast_at: Option<DateTime<Utc>>,
    /// Whether the account holder may still cancel it.
    pub cancellable: bool,
    /// When it confirmed to the required depth.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<DateTime<Utc>>,
    /// Confirmations observed.
    pub confirmations: i32,
    /// When it was requested.
    pub created_at: DateTime<Utc>,
    /// Explorer link, when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub explorer_url: Option<String>,
    /// `fee`
    pub fee: Amount,
    /// Asset the fee was charged in.
    pub fee_asset: String,
    /// Transitions this withdrawal has been through.
    #[serde(default)]
    pub history: Vec<WithdrawalHistoryEntry>,
    /// Withdrawal id.
    pub id: String,
    /// Memo, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memo: Option<String>,
    /// Network code.
    pub network: String,
    /// `status`
    pub status: WithdrawalStatus,
    /// Transaction hash, once broadcast.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub txid: Option<String>,
}

open_enum! {
    /// Lifecycle of an outgoing withdrawal.
    ///
    ///
    ///
    /// `pending_approval` waits for an operator to approve the withdrawal. `broadcast_unknown`
    /// means the transaction may have been sent: the funds stay debited until it is resolved
    /// against the chain.
    ///
    /// The type is open: values added to the API later decode as `Other`.
    WithdrawalStatus {
        Requested => "requested",
        PendingApproval => "pending_approval",
        Approved => "approved",
        Processing => "processing",
        Broadcast => "broadcast",
        Completed => "completed",
        Rejected => "rejected",
        Cancelled => "cancelled",
        Failed => "failed",
        BroadcastUnknown => "broadcast_unknown",
        Reverted => "reverted",
    }
}