cexy 0.1.0-dev.2

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
// 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;

/// 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>>,
    /// 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,
    /// `locked`
    pub locked: Amount,
    /// `pending`
    pub pending: Amount,
    /// `total`
    pub total: Amount,
}

/// 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,
}

/// 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. `INVALID_STATE` for an order still being placed when the wait ran out, or `MARKET_UNAVAILABLE`.
    pub code: String,
    /// Its message.
    pub message: String,
    /// The order.
    pub order_id: String,
}

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,
}

/// 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",
        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",
        InsufficientFunds => "INSUFFICIENT_FUNDS",
        InsufficientFeeFunds => "INSUFFICIENT_FEE_FUNDS",
        MarketUnavailable => "MARKET_UNAVAILABLE",
        DepositDisabled => "DEPOSIT_DISABLED",
        WithdrawalDisabled => "WITHDRAWAL_DISABLED",
        SelfTradeBlocked => "SELF_TRADE_BLOCKED",
        LimitExceeded => "LIMIT_EXCEEDED",
        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 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,
}

/// Adds liquidity to a pool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JoinPoolRequest {
    /// `base_amount`
    pub base_amount: Amount,
    /// How far, in percent, the offered ratio may sit from the pool's own before the request is refused rather than repriced. Defaults to 1%.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_ratio_deviation_percent: Option<String>,
    /// `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",
        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",
        TradeFeeRevenue => "trade_fee_revenue",
        WithdrawalFeeRevenue => "withdrawal_fee_revenue",
        FuturesTransferFeeRevenue => "futures_transfer_fee_revenue",
        FuturesHyperliquidCost => "futures_hyperliquid_cost",
        FuturesTransferDiscrepancy => "futures_transfer_discrepancy",
        ExchangeCapital => "exchange_capital",
    }
}

/// 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,
    /// What caused the entry.
    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
    pub reference: serde_json::Value,
    /// Position in this account's history for this asset.
    pub sequence: i64,
}

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",
        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 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>,
}

/// 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,
}

/// 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,
}

/// 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",
    }
}

/// 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",
    }
}

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",
    }
}

/// 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,
}

/// 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",
    }
}