1use ahash::AHashMap;
19use jiff::{Timestamp, civil::Date};
20use nautilus_core::string::secret::SecretString;
21use rust_decimal::Decimal;
22use serde::{Deserialize, Serialize};
23use strum::{AsRefStr, Display};
24use ustr::Ustr;
25use zeroize::{Zeroize, ZeroizeOnDrop};
26
27use crate::common::{
28 enums::{
29 AxCandleWidth, AxCategory, AxFundingSlotStatus, AxFundingVariant, AxInstrumentState,
30 AxOrderSide, AxOrderStatus, AxTimeInForce,
31 },
32 parse::{
33 deserialize_decimal_or_zero, deserialize_optional_decimal,
34 deserialize_optional_decimal_from_str, serialize_decimal_as_str,
35 serialize_optional_decimal_as_str,
36 },
37};
38
39fn default_instrument_state() -> AxInstrumentState {
41 AxInstrumentState::Open
42}
43
44#[derive(Clone, Debug, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub struct AxWhoAmIAccount {
53 pub id: Ustr,
55 pub name: Option<String>,
57 pub is_close_only: bool,
59 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
61 pub maker_fee: Option<Decimal>,
62 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
64 pub taker_fee: Option<Decimal>,
65 pub can_list: bool,
67 pub can_read: bool,
69 pub can_set_limits: bool,
71 pub can_reduce_or_close: bool,
73 pub can_trade: bool,
75}
76
77#[derive(Clone, Debug, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub struct AxWhoAmI {
84 pub id: Ustr,
86 pub username: Ustr,
88 pub created_at: Timestamp,
90 pub require_2fa: bool,
92 #[serde(default)]
94 pub is_onboarded: Option<bool>,
95 #[serde(default)]
97 pub is_frozen: Option<bool>,
98 pub is_admin: bool,
100 #[serde(default)]
102 pub accounts: Vec<AxWhoAmIAccount>,
103 #[serde(default)]
105 pub pseudonym: Option<String>,
106 #[serde(default)]
108 pub fiat_deposit_code: Option<String>,
109}
110
111#[derive(Clone, Debug, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub struct AxInstrument {
118 pub symbol: Ustr,
120 #[serde(default)]
122 pub product: Option<Ustr>,
123 #[serde(default = "default_instrument_state")]
125 pub state: AxInstrumentState,
126 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
128 pub multiplier: Decimal,
129 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
131 pub minimum_order_size: Decimal,
132 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
134 pub tick_size: Decimal,
135 pub quote_currency: Ustr,
137 pub funding_settlement_currency: Ustr,
139 pub category: AxCategory,
141 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
143 pub maintenance_margin_pct: Decimal,
144 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
146 pub initial_margin_pct: Decimal,
147 #[serde(default)]
149 pub contract_mark_price: Option<String>,
150 #[serde(default)]
152 pub contract_size: Option<String>,
153 #[serde(default)]
155 pub description: Option<String>,
156 #[serde(default)]
158 pub expiration: Option<Timestamp>,
159 #[serde(default)]
161 pub funding_calendar_schedule: Option<String>,
162 #[serde(default)]
164 pub funding_frequency: Option<String>,
165 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
167 pub funding_rate_cap_lower_pct: Option<Decimal>,
168 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
170 pub funding_rate_cap_upper_pct: Option<Decimal>,
171 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
173 pub price_band_lower_deviation_pct: Option<Decimal>,
174 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
176 pub price_band_upper_deviation_pct: Option<Decimal>,
177 #[serde(default)]
179 pub price_bands: Option<String>,
180 #[serde(default)]
182 pub price_quotation: Option<String>,
183 #[serde(default)]
185 pub underlying_benchmark_price: Option<String>,
186 #[serde(default)]
188 pub price_scale: Option<i64>,
189 #[serde(default)]
191 pub additional_product_specs: Option<serde_json::Map<String, serde_json::Value>>,
192 #[serde(default)]
194 pub delisted_at: Option<Timestamp>,
195 #[serde(default)]
197 pub is_closing: bool,
198 #[serde(default)]
200 pub estimated_funding_supported: bool,
201 #[serde(default)]
203 pub funding_schedule_calendar_description: Option<String>,
204 #[serde(default)]
206 pub funding_schedule_time_description: Option<String>,
207 #[serde(default)]
209 pub funding_schedule: Option<AxFundingSchedule>,
210 #[serde(default)]
212 pub trading_schedule: Option<AxTradingSchedule>,
213}
214
215#[derive(Clone, Debug, Serialize, Deserialize)]
217pub struct AxTimeOfDay {
218 pub hours: u32,
219 pub minutes: u32,
220 #[serde(default)]
221 pub seconds: u32,
222}
223
224#[derive(Clone, Debug, Serialize, Deserialize)]
226pub struct AxFundingTime {
227 pub days_of_week: Vec<u32>,
228 pub time_of_day: AxTimeOfDay,
229}
230
231#[derive(Clone, Debug, Serialize, Deserialize)]
233pub struct AxFundingException {
234 pub date: Date,
235 pub times: Vec<AxTimeOfDay>,
236 pub reason: Option<String>,
237}
238
239#[derive(Clone, Debug, Serialize, Deserialize)]
241pub struct AxFundingSchedule {
242 pub timezone: Ustr,
243 pub times: Vec<AxFundingTime>,
244 pub exceptions: Vec<AxFundingException>,
245}
246
247#[derive(Clone, Debug, Serialize, Deserialize)]
249pub struct AxTradingSegment {
250 pub days_of_week: Vec<u32>,
251 pub time_of_day: AxTimeOfDay,
252 pub duration_seconds: u64,
253 pub state: AxInstrumentState,
254 pub hide_market_data: bool,
255 pub expire_all_orders: bool,
256}
257
258#[derive(Clone, Debug, Serialize, Deserialize)]
260pub struct AxTradingSchedule {
261 pub segments: Vec<AxTradingSegment>,
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "snake_case")]
267pub enum AxEstimatedFundingStatus {
268 Ready,
269 SettlementPending,
270 Unavailable,
271 #[serde(other)]
272 Unknown,
273}
274
275#[derive(Clone, Debug, Serialize, Deserialize)]
277pub struct AxEstimatedFundingRate {
278 pub symbol: Ustr,
279 pub status: AxEstimatedFundingStatus,
280 pub timestamp: Timestamp,
281 pub reason: Option<String>,
282 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
283 pub funding_rate: Option<Decimal>,
284 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
285 pub funding_amount: Option<Decimal>,
286 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
287 pub benchmark_price: Option<Decimal>,
288 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
289 pub settlement_price: Option<Decimal>,
290}
291
292#[derive(Clone, Debug, Serialize, Deserialize)]
297#[serde(rename_all = "snake_case")]
298pub struct AxInstrumentsResponse {
299 pub instruments: Vec<AxInstrument>,
301}
302
303#[derive(Clone, Debug, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub struct AxBalance {
310 pub symbol: Ustr,
312 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
314 pub amount: Decimal,
315 #[serde(default)]
317 pub account_id: Option<Ustr>,
318}
319
320#[derive(Clone, Debug, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub struct AxBalancesResponse {
327 pub balances: Vec<AxBalance>,
329 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
331 pub usd_borrow: Option<Decimal>,
332}
333
334#[derive(Clone, Debug, Serialize, Deserialize)]
339#[serde(rename_all = "snake_case")]
340pub struct AxPosition {
341 pub account_id: Ustr,
343 pub symbol: Ustr,
345 pub signed_quantity: i64,
347 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
349 pub signed_notional: Decimal,
350 pub timestamp: Timestamp,
352 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
354 pub realized_pnl: Decimal,
355 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
357 pub signed_cost_basis: Option<Decimal>,
358}
359
360#[derive(Clone, Debug, Serialize, Deserialize)]
365#[serde(rename_all = "snake_case")]
366pub struct AxPositionsResponse {
367 pub positions: Vec<AxPosition>,
369}
370
371#[derive(Clone, Debug, Serialize, Deserialize)]
376#[serde(rename_all = "snake_case")]
377pub struct AxTicker {
378 #[serde(rename = "s")]
380 pub symbol: Ustr,
381 #[serde(
383 default,
384 rename = "bp",
385 deserialize_with = "deserialize_optional_decimal"
386 )]
387 pub bid: Option<Decimal>,
388 #[serde(
390 default,
391 rename = "ap",
392 deserialize_with = "deserialize_optional_decimal"
393 )]
394 pub ask: Option<Decimal>,
395 #[serde(
397 default,
398 rename = "p",
399 deserialize_with = "deserialize_optional_decimal"
400 )]
401 pub last: Option<Decimal>,
402 #[serde(
404 default,
405 rename = "m",
406 deserialize_with = "deserialize_optional_decimal"
407 )]
408 pub mark: Option<Decimal>,
409 #[serde(
411 default,
412 rename = "v",
413 deserialize_with = "deserialize_optional_decimal"
414 )]
415 pub volume_24h: Option<Decimal>,
416 #[serde(
418 default,
419 rename = "h",
420 deserialize_with = "deserialize_optional_decimal"
421 )]
422 pub high_24h: Option<Decimal>,
423 #[serde(
425 default,
426 rename = "l",
427 deserialize_with = "deserialize_optional_decimal"
428 )]
429 pub low_24h: Option<Decimal>,
430 #[serde(default)]
432 pub ts: Option<i64>,
433 #[serde(default)]
435 pub tn: Option<i64>,
436 #[serde(default, rename = "q")]
438 pub last_quantity: Option<u64>,
439 #[serde(default, rename = "oi")]
441 pub open_interest: Option<i64>,
442 #[serde(default, rename = "i")]
444 pub instrument_state: Option<AxInstrumentState>,
445 #[serde(
447 default,
448 rename = "pl",
449 deserialize_with = "deserialize_optional_decimal"
450 )]
451 pub price_band_lower: Option<Decimal>,
452 #[serde(
454 default,
455 rename = "pu",
456 deserialize_with = "deserialize_optional_decimal"
457 )]
458 pub price_band_upper: Option<Decimal>,
459 #[serde(
461 default,
462 rename = "lsp",
463 deserialize_with = "deserialize_optional_decimal"
464 )]
465 pub last_settlement_price: Option<Decimal>,
466 #[serde(default, rename = "lst")]
468 pub last_settlement_time: Option<i64>,
469 #[serde(
471 default,
472 rename = "o",
473 deserialize_with = "deserialize_optional_decimal_from_str"
474 )]
475 pub open: Option<Decimal>,
476 #[serde(default, rename = "ef")]
478 pub estimated_funding: Option<AxEstimatedFundingRate>,
479}
480
481#[derive(Clone, Debug, Serialize, Deserialize)]
486#[serde(rename_all = "snake_case")]
487pub struct AxTickersResponse {
488 pub tickers: Vec<AxTicker>,
490 pub total_count: i64,
492 pub limit: i32,
494 pub offset: i32,
496}
497
498#[derive(Clone, Debug, Serialize, Deserialize)]
503#[serde(rename_all = "snake_case")]
504pub struct AxTickerResponse {
505 pub ticker: AxTicker,
507}
508
509#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
514#[serde(rename_all = "snake_case")]
515pub struct AxAuthenticateResponse {
516 pub token: SecretString,
518}
519
520impl AxAuthenticateResponse {
521 #[must_use]
523 pub fn into_token(mut self) -> SecretString {
524 std::mem::take(&mut self.token)
525 }
526}
527
528#[derive(Clone, Debug, Serialize, Deserialize)]
533pub struct AxPlaceOrderResponse {
534 pub oid: String,
536}
537
538#[derive(Clone, Debug, Serialize, Deserialize)]
543pub struct AxCancelOrderResponse {
544 pub cxl_rx: bool,
546}
547
548#[derive(Clone, Debug, Serialize, Deserialize)]
553pub struct AxRestTrade {
554 pub ts: i64,
556 pub tn: i64,
558 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
560 pub p: Decimal,
561 pub q: i64,
563 pub s: Ustr,
565 pub d: AxOrderSide,
567}
568
569#[derive(Clone, Debug, Serialize, Deserialize)]
574pub struct AxTradesResponse {
575 pub trades: Vec<AxRestTrade>,
577}
578
579#[derive(Clone, Debug, Serialize, Deserialize)]
584pub struct AxBookLevel {
585 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
587 pub p: Decimal,
588 pub q: i64,
590 #[serde(default)]
592 pub o: Option<Vec<i64>>,
593}
594
595#[derive(Clone, Debug, Serialize, Deserialize)]
600pub struct AxBook {
601 pub ts: i64,
603 pub tn: i64,
605 pub s: Ustr,
607 pub b: Vec<AxBookLevel>,
609 pub a: Vec<AxBookLevel>,
611}
612
613#[derive(Clone, Debug, Serialize, Deserialize)]
618pub struct AxBookResponse {
619 pub book: AxBook,
621}
622
623#[derive(Clone, Debug, Serialize, Deserialize)]
628pub struct AxOrderStatusDetail {
629 pub symbol: Ustr,
631 pub order_id: String,
633 pub state: AxOrderStatus,
635 #[serde(default)]
637 pub clord_id: Option<u64>,
638 #[serde(default)]
640 pub filled_quantity: Option<i64>,
641 #[serde(default)]
643 pub remaining_quantity: Option<i64>,
644 #[serde(default)]
646 pub reject_reason: Option<AxOrderRejectReason>,
647 #[serde(default)]
649 pub reject_message: Option<String>,
650}
651
652#[derive(Clone, Debug, Serialize, Deserialize)]
657pub struct AxOrderStatusQueryResponse {
658 pub status: AxOrderStatusDetail,
660}
661
662#[derive(Clone, Copy, Debug, Display, Eq, PartialEq, Hash, AsRefStr, Serialize, Deserialize)]
667#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
668#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
669pub enum AxOrderRejectReason {
670 CloseOnly,
671 InsufficientMargin,
672 MaxOpenOrdersExceeded,
673 UnknownSymbol,
674 ExchangeClosed,
675 IncorrectQuantity,
676 InvalidPriceIncrement,
677 IncorrectOrderType,
678 PriceOutOfBounds,
679 NoLiquidity,
680 InsufficientCreditLimit,
681 OriginalOrderTerminated,
682 DuplicateClientOrderId,
683 #[serde(other)]
684 Unknown,
685}
686
687impl AxOrderRejectReason {
688 #[must_use]
692 pub fn reason_str(reason: Option<Self>, text: Option<&str>) -> Option<String> {
693 if let Some(known) = reason.filter(|r| !matches!(r, Self::Unknown)) {
694 return Some(known.to_string());
695 }
696
697 text.filter(|text| !text.trim().is_empty())
698 .map(str::to_string)
699 }
700}
701
702#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
704pub enum AxRepriceBehavior {
705 #[serde(rename = "rej")]
706 Reject,
707 #[serde(rename = "bo")]
708 BackOff,
709 #[serde(rename = "tbl")]
710 TopOfBook,
711 #[serde(other)]
712 Unknown,
713}
714
715#[derive(Clone, Debug, Serialize, Deserialize)]
720pub struct AxOrderDetail {
721 pub ts: i64,
723 #[serde(default)]
725 pub tn: i64,
726 pub oid: String,
728 #[serde(default)]
730 pub aid: Option<Ustr>,
731 pub u: Ustr,
733 pub s: Ustr,
735 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
737 pub p: Decimal,
738 pub q: u64,
740 pub xq: u64,
742 pub rq: u64,
744 pub o: AxOrderStatus,
746 pub d: AxOrderSide,
748 pub tif: AxTimeInForce,
750 #[serde(default)]
752 pub cid: Option<u64>,
753 #[serde(default)]
755 pub r: Option<AxOrderRejectReason>,
756 #[serde(default)]
758 pub tag: Option<String>,
759 #[serde(default)]
761 pub txt: Option<String>,
762 #[serde(default)]
764 pub po: bool,
765 #[serde(default)]
767 pub rb: Option<AxRepriceBehavior>,
768}
769
770#[derive(Clone, Debug, Serialize, Deserialize)]
775pub struct AxOrdersResponse {
776 pub orders: Vec<AxOrderDetail>,
778 #[serde(default)]
780 pub total_count: Option<i64>,
781 #[serde(default)]
783 pub limit: Option<i32>,
784 #[serde(default)]
786 pub offset: Option<i32>,
787 #[serde(default)]
789 pub next_cursor: Option<String>,
790}
791
792#[derive(Clone, Debug, Serialize, Deserialize)]
797pub struct AxInitialMarginRequirementResponse {
798 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
800 pub im: Decimal,
801 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
803 pub im_pct: Option<Decimal>,
804 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
806 pub mult: Option<Decimal>,
807 #[serde(default)]
809 pub pos: Option<i64>,
810}
811
812#[derive(Clone, Debug, Serialize, Deserialize)]
817pub struct AxOpenOrder {
818 pub tn: i64,
820 pub ts: i64,
822 pub d: AxOrderSide,
824 pub o: AxOrderStatus,
826 pub oid: String,
828 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
830 pub p: Decimal,
831 pub q: u64,
833 pub rq: u64,
835 pub s: Ustr,
837 pub tif: AxTimeInForce,
839 pub u: Ustr,
841 pub xq: u64,
843 #[serde(default)]
845 pub cid: Option<u64>,
846 #[serde(default)]
848 pub tag: Option<String>,
849 #[serde(default)]
851 pub po: bool,
852 #[serde(default)]
854 pub rb: Option<AxRepriceBehavior>,
855 #[serde(default)]
857 pub aid: Option<Ustr>,
858 #[serde(default)]
860 pub r: Option<AxOrderRejectReason>,
861 #[serde(default)]
863 pub txt: Option<String>,
864}
865
866#[derive(Clone, Debug, Serialize, Deserialize)]
871pub struct AxOpenOrdersResponse {
872 pub orders: Vec<AxOpenOrder>,
874 pub total_count: i64,
876 pub limit: i32,
878 pub offset: i32,
880}
881
882#[derive(Clone, Debug, Serialize, Deserialize)]
887#[serde(rename_all = "snake_case")]
888pub struct AxFill {
889 pub trade_id: String,
891 pub order_id: Option<String>,
893 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
895 pub fee: Decimal,
896 pub is_taker: bool,
898 pub is_block_trade: Option<bool>,
900 pub is_final_settlement: Option<bool>,
902 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
904 pub price: Decimal,
905 pub quantity: u64,
907 pub side: AxOrderSide,
909 pub symbol: Ustr,
911 pub timestamp: Timestamp,
913 pub account_id: Ustr,
915 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
917 pub realized_pnl: Option<Decimal>,
918}
919
920#[derive(Clone, Debug, Serialize, Deserialize)]
925#[serde(rename_all = "snake_case")]
926pub struct AxFillsResponse {
927 pub fills: Vec<AxFill>,
929 #[serde(default)]
931 pub total_count: Option<i64>,
932 #[serde(default)]
934 pub limit: Option<i32>,
935 #[serde(default)]
937 pub next_cursor: Option<String>,
938}
939
940#[derive(Clone, Debug, Serialize, Deserialize)]
945#[serde(rename_all = "snake_case")]
946pub struct AxCandle {
947 pub symbol: Ustr,
949 pub ts: i64,
951 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
953 pub open: Decimal,
954 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
956 pub high: Decimal,
957 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
959 pub low: Decimal,
960 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
962 pub close: Decimal,
963 pub buy_volume: u64,
965 pub sell_volume: u64,
967 pub volume: u64,
969 pub width: AxCandleWidth,
971}
972
973#[derive(Clone, Debug, Serialize, Deserialize)]
978#[serde(rename_all = "snake_case")]
979pub struct AxCandlesResponse {
980 pub candles: Vec<AxCandle>,
982}
983
984#[derive(Clone, Debug, Serialize, Deserialize)]
990#[serde(rename_all = "snake_case")]
991pub struct AxCandleResponse {
992 pub candle: AxCandle,
994}
995
996#[derive(Clone, Debug, Serialize, Deserialize)]
1001#[serde(rename_all = "snake_case")]
1002pub struct AxFundingRate {
1003 pub symbol: Ustr,
1005 pub timestamp_ns: i64,
1007 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1009 pub funding_rate: Decimal,
1010 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1012 pub funding_amount: Option<Decimal>,
1013 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1015 pub benchmark_price: Option<Decimal>,
1016 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1018 pub settlement_price: Decimal,
1019}
1020
1021#[derive(Clone, Debug, Serialize, Deserialize)]
1026#[serde(rename_all = "snake_case")]
1027pub struct AxFundingRatesResponse {
1028 pub funding_rates: Vec<AxFundingRate>,
1030 #[serde(default)]
1032 pub total_count: Option<i64>,
1033 #[serde(default)]
1035 pub limit: Option<i32>,
1036 #[serde(default)]
1038 pub next_cursor: Option<String>,
1039}
1040
1041#[derive(Clone, Debug, Serialize, Deserialize)]
1046#[serde(rename_all = "snake_case")]
1047pub struct AxFundingSlot {
1048 pub index: i32,
1050 pub funding_time: Timestamp,
1052 pub status: AxFundingSlotStatus,
1054 pub capped: bool,
1056 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1058 pub mark_twap: Option<Decimal>,
1059 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1061 pub underlying_twap: Option<Decimal>,
1062 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1064 pub premium_bps: Option<Decimal>,
1065 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1067 pub funding_rate_bps: Option<Decimal>,
1068 #[serde(default)]
1070 pub reason: Option<String>,
1071}
1072
1073#[derive(Clone, Debug, Serialize, Deserialize)]
1081#[serde(rename_all = "snake_case")]
1082pub struct AxFundingSlotsResponse {
1083 pub symbol: Ustr,
1085 pub date: Date,
1087 pub timezone: Ustr,
1089 pub variant: AxFundingVariant,
1091 pub interval_count: i32,
1093 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1095 pub cap_bps: Option<Decimal>,
1096 pub slots: Vec<AxFundingSlot>,
1098 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1100 pub realized_sum_bps: Decimal,
1101 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1103 pub projected_eod_bps: Decimal,
1104 #[serde(default)]
1106 pub slot_interval_minutes: Option<u32>,
1107}
1108
1109#[derive(Clone, Debug, Serialize, Deserialize)]
1114#[serde(rename_all = "snake_case")]
1115pub struct AxPerSymbolRisk {
1116 pub signed_quantity: i64,
1118 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1120 pub signed_notional: Decimal,
1121 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1123 pub average_price: Option<Decimal>,
1124 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1126 pub liquidation_price: Option<Decimal>,
1127 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1129 pub initial_margin_required_position: Decimal,
1130 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1132 pub initial_margin_required_open_orders: Decimal,
1133 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1135 pub initial_margin_required_total: Decimal,
1136 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1138 pub maintenance_margin_required: Decimal,
1139 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1141 pub unrealized_pnl: Decimal,
1142 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1144 pub signed_cost_basis: Option<Decimal>,
1145 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1147 pub signed_usd_notional: Option<Decimal>,
1148 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1150 pub mark_price: Option<Decimal>,
1151}
1152
1153#[derive(Clone, Debug, Serialize, Deserialize)]
1158#[serde(rename_all = "snake_case")]
1159pub struct AxRiskSnapshot {
1160 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1162 pub balance_usd: Decimal,
1163 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1165 pub equity: Decimal,
1166 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1168 pub initial_margin_available: Decimal,
1169 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1171 pub initial_margin_required_for_open_orders: Decimal,
1172 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1174 pub initial_margin_required_for_positions: Decimal,
1175 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1177 pub initial_margin_required_total: Decimal,
1178 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1180 pub maintenance_margin_available: Decimal,
1181 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1183 pub maintenance_margin_required: Decimal,
1184 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1186 pub unrealized_pnl: Decimal,
1187 pub timestamp_ns: Timestamp,
1189 pub account_id: Ustr,
1191 #[serde(default)]
1193 pub per_symbol: AHashMap<Ustr, AxPerSymbolRisk>,
1194}
1195
1196#[derive(Clone, Debug, Serialize, Deserialize)]
1201#[serde(rename_all = "snake_case")]
1202pub struct AxRiskSnapshotResponse {
1203 pub risk_snapshot: AxRiskSnapshot,
1205}
1206
1207#[derive(Clone, Debug, Serialize, Deserialize)]
1212#[serde(rename_all = "snake_case")]
1213pub struct AxTransaction {
1214 pub account_id: Ustr,
1216 #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1218 pub amount: Decimal,
1219 pub event_id: String,
1221 pub symbol: Ustr,
1223 pub timestamp: Timestamp,
1225 pub transaction_type: Ustr,
1227 #[serde(default)]
1229 pub initiated_by_user_id: Option<Ustr>,
1230 #[serde(default)]
1232 pub reference_id: Option<String>,
1233}
1234
1235#[derive(Clone, Debug, Serialize, Deserialize)]
1240#[serde(rename_all = "snake_case")]
1241pub struct AxTransactionsResponse {
1242 pub transactions: Vec<AxTransaction>,
1244 #[serde(default)]
1246 pub total_count: Option<i64>,
1247 #[serde(default)]
1249 pub limit: Option<i32>,
1250 #[serde(default)]
1252 pub next_cursor: Option<String>,
1253}
1254
1255#[derive(Debug, Clone, Serialize, Deserialize, Zeroize)]
1260#[serde(rename_all = "snake_case")]
1261pub struct AuthenticateApiKeyRequest {
1262 pub api_key: SecretString,
1264 pub api_secret: SecretString,
1266 pub expiration_seconds: i32,
1268}
1269
1270impl AuthenticateApiKeyRequest {
1271 #[must_use]
1273 pub fn new(
1274 api_key: impl Into<SecretString>,
1275 api_secret: impl Into<SecretString>,
1276 expiration_seconds: i32,
1277 ) -> Self {
1278 Self {
1279 api_key: api_key.into(),
1280 api_secret: api_secret.into(),
1281 expiration_seconds,
1282 }
1283 }
1284}
1285
1286#[derive(Clone, Debug, Serialize, Deserialize)]
1291pub struct PlaceOrderRequest {
1292 pub d: AxOrderSide,
1294 #[serde(serialize_with = "serialize_decimal_as_str")]
1296 pub p: Decimal,
1297 pub po: bool,
1299 pub q: u64,
1301 pub s: Ustr,
1303 pub tif: AxTimeInForce,
1305 #[serde(skip_serializing_if = "Option::is_none")]
1307 pub tag: Option<String>,
1308}
1309
1310impl PlaceOrderRequest {
1311 #[must_use]
1313 pub fn new(
1314 side: AxOrderSide,
1315 price: Decimal,
1316 quantity: u64,
1317 symbol: Ustr,
1318 time_in_force: AxTimeInForce,
1319 post_only: bool,
1320 ) -> Self {
1321 Self {
1322 d: side,
1323 p: price,
1324 po: post_only,
1325 q: quantity,
1326 s: symbol,
1327 tif: time_in_force,
1328 tag: None,
1329 }
1330 }
1331
1332 #[must_use]
1334 pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
1335 self.tag = Some(tag.into());
1336 self
1337 }
1338}
1339
1340#[derive(Clone, Debug, Serialize, Deserialize)]
1345pub struct PreviewAggressiveLimitOrderRequest {
1346 pub symbol: Ustr,
1348 pub quantity: u64,
1350 pub side: AxOrderSide,
1352}
1353
1354impl PreviewAggressiveLimitOrderRequest {
1355 #[must_use]
1357 pub fn new(symbol: Ustr, quantity: u64, side: AxOrderSide) -> Self {
1358 Self {
1359 symbol,
1360 quantity,
1361 side,
1362 }
1363 }
1364}
1365
1366#[derive(Clone, Debug, Serialize, Deserialize)]
1371pub struct AxPreviewAggressiveLimitOrderResponse {
1372 pub filled_quantity: u64,
1374 pub remaining_quantity: u64,
1376 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1378 pub limit_price: Option<Decimal>,
1379 #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1381 pub vwap: Option<Decimal>,
1382}
1383
1384#[derive(Clone, Debug, Serialize, Deserialize)]
1389pub struct CancelOrderRequest {
1390 pub oid: String,
1392}
1393
1394impl CancelOrderRequest {
1395 #[must_use]
1397 pub fn new(order_id: impl Into<String>) -> Self {
1398 Self {
1399 oid: order_id.into(),
1400 }
1401 }
1402}
1403
1404#[derive(Clone, Debug, Serialize, Deserialize)]
1412pub struct ReplaceOrderRequest {
1413 pub oid: String,
1415 #[serde(
1417 skip_serializing_if = "Option::is_none",
1418 serialize_with = "serialize_optional_decimal_as_str"
1419 )]
1420 pub p: Option<Decimal>,
1421 #[serde(skip_serializing_if = "Option::is_none")]
1423 pub q: Option<u64>,
1424 #[serde(skip_serializing_if = "Option::is_none")]
1426 pub po: Option<bool>,
1427 #[serde(skip_serializing_if = "Option::is_none")]
1429 pub tif: Option<AxTimeInForce>,
1430}
1431
1432impl ReplaceOrderRequest {
1433 #[must_use]
1437 pub fn new(order_id: impl Into<String>) -> Self {
1438 Self {
1439 oid: order_id.into(),
1440 p: None,
1441 q: None,
1442 po: None,
1443 tif: None,
1444 }
1445 }
1446
1447 #[must_use]
1449 pub fn with_price(mut self, price: Decimal) -> Self {
1450 self.p = Some(price);
1451 self
1452 }
1453
1454 #[must_use]
1456 pub fn with_quantity(mut self, quantity: u64) -> Self {
1457 self.q = Some(quantity);
1458 self
1459 }
1460}
1461
1462#[derive(Clone, Debug, Serialize, Deserialize)]
1467pub struct AxReplaceOrderResponse {
1468 pub oid: String,
1470}
1471
1472#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1477pub struct CancelAllOrdersRequest {
1478 #[serde(skip_serializing_if = "Option::is_none")]
1480 pub account_id: Option<Ustr>,
1481 #[serde(skip_serializing_if = "Option::is_none")]
1483 pub symbol: Option<Ustr>,
1484}
1485
1486impl CancelAllOrdersRequest {
1487 #[must_use]
1489 pub fn new() -> Self {
1490 Self::default()
1491 }
1492
1493 #[must_use]
1495 pub fn with_account_id(mut self, account_id: Ustr) -> Self {
1496 self.account_id = Some(account_id);
1497 self
1498 }
1499
1500 #[must_use]
1502 pub fn with_symbol(mut self, symbol: Ustr) -> Self {
1503 self.symbol = Some(symbol);
1504 self
1505 }
1506}
1507
1508#[derive(Clone, Debug, Serialize, Deserialize)]
1513pub struct AxCancelAllOrdersResponse {}
1514
1515#[cfg(test)]
1516mod tests {
1517 use rstest::rstest;
1518 use rust_decimal_macros::dec;
1519 use serde_json::json;
1520
1521 use super::*;
1522 use crate::websocket::{
1523 messages::{AxOrdersWsFrame, AxWsOrderEvent},
1524 parse::parse_order_message,
1525 };
1526
1527 fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
1528
1529 #[rstest]
1530 fn test_deserialize_authenticate_response() {
1531 let json = include_str!("../../test_data/http_authenticate.json");
1532 let response: AxAuthenticateResponse = serde_json::from_str(json).unwrap();
1533 assert!(response.token.expose_secret().starts_with("test-token"));
1534 }
1535
1536 #[rstest]
1537 fn test_reason_str_prefers_known_reason_over_text() {
1538 assert_eq!(
1539 AxOrderRejectReason::reason_str(
1540 Some(AxOrderRejectReason::PriceOutOfBounds),
1541 Some("order price is above the exchange's maximum price limit"),
1542 ),
1543 Some("PRICE_OUT_OF_BOUNDS".to_string()),
1544 );
1545 }
1546
1547 #[rstest]
1548 fn test_reason_str_falls_back_to_text() {
1549 assert_eq!(
1550 AxOrderRejectReason::reason_str(
1551 Some(AxOrderRejectReason::Unknown),
1552 Some("risk blocked")
1553 ),
1554 Some("risk blocked".to_string()),
1555 );
1556 assert_eq!(
1557 AxOrderRejectReason::reason_str(None, Some("risk blocked")),
1558 Some("risk blocked".to_string()),
1559 );
1560 }
1561
1562 #[rstest]
1563 fn test_reason_str_rejects_blank_text() {
1564 assert_eq!(AxOrderRejectReason::reason_str(None, Some("")), None);
1565 assert_eq!(AxOrderRejectReason::reason_str(None, Some(" ")), None);
1566 assert_eq!(AxOrderRejectReason::reason_str(None, None), None);
1567 assert_eq!(
1568 AxOrderRejectReason::reason_str(Some(AxOrderRejectReason::Unknown), None),
1569 None,
1570 );
1571 }
1572
1573 #[rstest]
1574 fn test_serialize_cancel_all_orders_request() {
1575 let request = CancelAllOrdersRequest::new()
1576 .with_account_id(Ustr::from("account-1"))
1577 .with_symbol(Ustr::from("XAU-PERP"));
1578
1579 let value = serde_json::to_value(request).unwrap();
1580
1581 assert_eq!(value["account_id"], "account-1");
1582 assert_eq!(value["symbol"], "XAU-PERP");
1583 assert!(value.get("execution_venue").is_none());
1584 }
1585
1586 #[rstest]
1587 fn test_deserialize_whoami_response() {
1588 let json = include_str!("../../test_data/http_get_whoami.json");
1589
1590 let response: AxWhoAmI = serde_json::from_str(json).unwrap();
1591
1592 assert_eq!(response.id, "01JBXR-7QK2-0000");
1593 assert_eq!(response.username, "trader@example.com");
1594 assert_eq!(response.pseudonym.as_deref(), Some("quiet-amber-heron"));
1595 assert_eq!(
1596 response.created_at,
1597 "2025-12-18T02:20:42.675817Z".parse::<Timestamp>().unwrap()
1598 );
1599 assert!(!response.require_2fa);
1600 assert_eq!(response.is_onboarded, Some(true));
1601 assert_eq!(response.is_frozen, Some(false));
1602 assert!(!response.is_admin);
1603 assert_eq!(
1604 response.fiat_deposit_code.as_deref(),
1605 Some("01JBXR7QK20000Y")
1606 );
1607 assert_eq!(response.accounts.len(), 1);
1608
1609 let account = &response.accounts[0];
1610
1611 assert_eq!(account.id, "01JBXR-7QK2-0000");
1612 assert_eq!(account.name.as_deref(), Some("trader@example.com"));
1613 assert!(!account.is_close_only);
1614 assert_eq!(account.maker_fee, Some(dec!(0.0002)));
1615 assert_eq!(account.taker_fee, Some(dec!(0.0025)));
1616 assert!(account.can_list);
1617 assert!(account.can_read);
1618 assert!(account.can_set_limits);
1619 assert!(account.can_reduce_or_close);
1620 assert!(account.can_trade);
1621 }
1622
1623 #[rstest]
1624 #[case(json!(""), None)]
1625 #[case(json!(null), None)]
1626 #[case(json!("0"), Some(Decimal::ZERO))]
1627 #[case(json!("0.0002"), Some(dec!(0.0002)))]
1628 fn test_deserialize_whoami_account_fee_distinguishes_absent_from_zero(
1629 #[case] wire_value: serde_json::Value,
1630 #[case] expected: Option<Decimal>,
1631 ) {
1632 let json = json!({
1634 "id": "01JBXR-7QK2-0000",
1635 "name": "trader@example.com",
1636 "is_close_only": false,
1637 "maker_fee": wire_value,
1638 "taker_fee": wire_value,
1639 "can_list": true,
1640 "can_read": true,
1641 "can_set_limits": true,
1642 "can_reduce_or_close": true,
1643 "can_trade": true,
1644 })
1645 .to_string();
1646
1647 let account: AxWhoAmIAccount = serde_json::from_str(&json).unwrap();
1648
1649 assert_eq!(account.maker_fee, expected);
1650 assert_eq!(account.taker_fee, expected);
1651 }
1652
1653 #[rstest]
1654 fn test_deserialize_whoami_account_rejects_malformed_fee() {
1655 let json = json!({
1656 "id": "01JBXR-7QK2-0000",
1657 "name": "trader@example.com",
1658 "is_close_only": false,
1659 "maker_fee": "not-a-decimal",
1660 "taker_fee": "0.0025",
1661 "can_list": true,
1662 "can_read": true,
1663 "can_set_limits": true,
1664 "can_reduce_or_close": true,
1665 "can_trade": true,
1666 })
1667 .to_string();
1668
1669 let error = serde_json::from_str::<AxWhoAmIAccount>(&json).unwrap_err();
1670
1671 assert!(
1672 error.to_string().contains("Invalid decimal"),
1673 "unexpected error: {error}"
1674 );
1675 }
1676
1677 #[rstest]
1678 #[case(true, false)]
1679 #[case(false, true)]
1680 #[case(true, true)]
1681 fn test_deserialize_whoami_response_without_user_status(
1682 #[case] omit_onboarded: bool,
1683 #[case] omit_frozen: bool,
1684 ) {
1685 let mut json: serde_json::Value =
1686 serde_json::from_str(include_str!("../../test_data/http_get_whoami.json")).unwrap();
1687 let fields = json.as_object_mut().unwrap();
1688 if omit_onboarded {
1689 fields.remove("is_onboarded");
1690 }
1691
1692 if omit_frozen {
1693 fields.remove("is_frozen");
1694 }
1695
1696 let response: AxWhoAmI = serde_json::from_value(json).unwrap();
1697
1698 assert_eq!(response.is_onboarded, (!omit_onboarded).then_some(true));
1699 assert_eq!(response.is_frozen, (!omit_frozen).then_some(false));
1700 assert_eq!(response.accounts.len(), 1);
1701 assert_eq!(response.accounts[0].maker_fee, Some(dec!(0.0002)));
1702 assert_eq!(response.accounts[0].taker_fee, Some(dec!(0.0025)));
1703 }
1704
1705 #[rstest]
1706 #[case::null(json!(null), json!(null), None, None)]
1707 #[case::boolean(json!(false), json!(true), Some(false), Some(true))]
1708 fn test_deserialize_whoami_response_user_status(
1709 #[case] onboarded: serde_json::Value,
1710 #[case] frozen: serde_json::Value,
1711 #[case] expected_onboarded: Option<bool>,
1712 #[case] expected_frozen: Option<bool>,
1713 ) {
1714 let mut json: serde_json::Value = serde_json::from_str(include_str!(
1715 "../../test_data/captured/whoami-without-status.json"
1716 ))
1717 .unwrap();
1718 json["is_onboarded"] = onboarded;
1719 json["is_frozen"] = frozen;
1720
1721 let response: AxWhoAmI = serde_json::from_value(json).unwrap();
1722
1723 assert_eq!(response.is_onboarded, expected_onboarded);
1724 assert_eq!(response.is_frozen, expected_frozen);
1725 }
1726
1727 #[rstest]
1728 #[case("is_onboarded")]
1729 #[case("is_frozen")]
1730 fn test_deserialize_whoami_response_rejects_malformed_user_status(#[case] field: &str) {
1731 let mut json: serde_json::Value = serde_json::from_str(include_str!(
1732 "../../test_data/captured/whoami-without-status.json"
1733 ))
1734 .unwrap();
1735 json[field] = json!("true");
1736
1737 let e = serde_json::from_value::<AxWhoAmI>(json).unwrap_err();
1738
1739 assert_eq!(
1740 e.to_string(),
1741 "invalid type: string \"true\", expected a boolean"
1742 );
1743 }
1744
1745 #[rstest]
1746 fn test_deserialize_whoami_response_without_optional_profile_fields() {
1747 let json = json!({
1748 "id": "01JBXR-7QK2-0001",
1749 "username": "sub@example.com",
1750 "created_at": "2025-12-18T02:20:42.675817Z",
1751 "is_onboarded": true,
1752 "is_frozen": false,
1753 "is_admin": false,
1754 "require_2fa": true,
1755 "accounts": [],
1756 })
1757 .to_string();
1758
1759 let response: AxWhoAmI = serde_json::from_str(&json).unwrap();
1760
1761 assert!(response.require_2fa);
1762 assert_eq!(response.pseudonym, None);
1763 assert_eq!(response.fiat_deposit_code, None);
1764 assert!(response.accounts.is_empty());
1765 }
1766
1767 #[rstest]
1768 fn test_deserialize_instruments_response() {
1769 let json = include_str!("../../test_data/http_get_instruments.json");
1770 let response: AxInstrumentsResponse = serde_json::from_str(json).unwrap();
1771
1772 assert_eq!(response.instruments.len(), 3);
1773 let eurusd = &response.instruments[0];
1774 assert_eq!(eurusd.symbol, "EURUSD-PERP");
1775 assert_eq!(eurusd.category, AxCategory::Fx);
1776 assert_eq!(eurusd.tick_size, dec!(0.0001));
1777 assert_eq!(eurusd.minimum_order_size, dec!(100));
1778 assert_eq!(response.instruments[1].symbol, "XAU-PERP");
1779 assert_eq!(response.instruments[1].category, AxCategory::Metals);
1780 assert_eq!(response.instruments[2].symbol, "NVDA-PERP");
1781 assert_eq!(response.instruments[2].category, AxCategory::Equities);
1782 }
1783
1784 #[rstest]
1785 fn test_deserialize_balances_response() {
1786 let json = include_str!("../../test_data/http_get_balances.json");
1787 let response: AxBalancesResponse = serde_json::from_str(json).unwrap();
1788 assert_eq!(response.balances.len(), 3);
1789 assert_eq!(response.balances[0].symbol, "USD");
1790 }
1791
1792 #[rstest]
1793 fn test_deserialize_positions_response() {
1794 let json = include_str!("../../test_data/http_get_positions.json");
1795 let response: AxPositionsResponse = serde_json::from_str(json).unwrap();
1796 assert_eq!(response.positions.len(), 2);
1797 assert_eq!(response.positions[0].symbol, "BTC-PERP");
1798 assert_eq!(response.positions[1].signed_quantity, -5);
1799 }
1800
1801 #[rstest]
1802 fn test_deserialize_tickers_response() {
1803 let json = include_str!("../../test_data/http_get_tickers.json");
1804 let response: AxTickersResponse = serde_json::from_str(json).unwrap();
1805 assert_eq!(response.tickers.len(), 3);
1806 assert_eq!(response.total_count, 3);
1807 assert_eq!(response.limit, 100);
1808 assert_eq!(response.offset, 0);
1809 assert_eq!(response.tickers[0].symbol, "EURUSD-PERP");
1810 assert!(response.tickers[0].bid.is_some());
1811 assert!(response.tickers[2].bid.is_none());
1812 }
1813
1814 #[rstest]
1815 fn test_deserialize_funding_rates_response() {
1816 let json = include_str!("../../test_data/http_get_funding_rates.json");
1817 let response: AxFundingRatesResponse = serde_json::from_str(json).unwrap();
1818 assert_eq!(response.funding_rates.len(), 2);
1819 assert_eq!(response.funding_rates[0].symbol, "JPYUSD-PERP");
1820 }
1821
1822 #[rstest]
1823 fn test_deserialize_funding_slots_response() {
1824 let json = include_str!("../../test_data/http_get_funding_slots.json");
1825 let response: AxFundingSlotsResponse = serde_json::from_str(json).unwrap();
1826 assert_eq!(response.symbol, "EURUSD-PERP");
1827 assert_eq!(response.date, Date::new(2026, 7, 6).unwrap());
1828 assert_eq!(response.timezone, "America/New_York");
1829 assert_eq!(response.variant, AxFundingVariant::IntradayTwap);
1830 assert_eq!(response.interval_count, 4);
1831 assert_eq!(
1832 response.cap_bps.map(|d| d.to_string()),
1833 Some("5.0".to_string())
1834 );
1835 assert_eq!(response.slots.len(), 4);
1836
1837 let first = &response.slots[0];
1838 assert_eq!(first.index, 1);
1839 assert_eq!(first.status, AxFundingSlotStatus::Realized);
1840 assert!(!first.capped);
1841 assert_eq!(
1842 first.funding_rate_bps.map(|d| d.to_string()),
1843 Some("0.0921".to_string())
1844 );
1845 assert!(first.reason.is_none());
1846
1847 let capped = &response.slots[1];
1848 assert!(capped.capped);
1849 assert_eq!(
1850 capped.funding_rate_bps.map(|d| d.to_string()),
1851 Some("5.0000".to_string())
1852 );
1853
1854 let projected = &response.slots[2];
1855 assert_eq!(projected.status, AxFundingSlotStatus::Projected);
1856
1857 let skipped = &response.slots[3];
1858 assert_eq!(skipped.status, AxFundingSlotStatus::Skipped);
1859 assert!(skipped.mark_twap.is_none());
1860 assert!(skipped.funding_rate_bps.is_none());
1861 assert_eq!(skipped.reason.as_deref(), Some("holiday"));
1862
1863 assert_eq!(response.realized_sum_bps.to_string(), "5.0921");
1864 assert_eq!(response.projected_eod_bps.to_string(), "5.1842");
1865 }
1866
1867 #[rstest]
1868 fn test_funding_variant_and_slot_status_deserialization() {
1869 let daily: AxFundingVariant =
1870 serde_json::from_value(serde_json::json!("daily_close")).unwrap();
1871 let twap: AxFundingVariant =
1872 serde_json::from_value(serde_json::json!("intraday_twap")).unwrap();
1873 assert_eq!(daily, AxFundingVariant::DailyClose);
1874 assert_eq!(twap, AxFundingVariant::IntradayTwap);
1875
1876 let statuses = [
1877 ("realized", AxFundingSlotStatus::Realized),
1878 ("projected", AxFundingSlotStatus::Projected),
1879 ("skipped", AxFundingSlotStatus::Skipped),
1880 ("pending", AxFundingSlotStatus::Pending),
1881 ];
1882
1883 for (raw, expected) in statuses {
1884 let parsed: AxFundingSlotStatus =
1885 serde_json::from_value(serde_json::json!(raw)).unwrap();
1886 assert_eq!(parsed, expected);
1887 }
1888 }
1889
1890 #[rstest]
1891 #[case::reject(Some("rej"), Some(AxRepriceBehavior::Reject))]
1892 #[case::back_off(Some("bo"), Some(AxRepriceBehavior::BackOff))]
1893 #[case::top_of_book(Some("tbl"), Some(AxRepriceBehavior::TopOfBook))]
1894 #[case::unknown(Some("future_behavior"), Some(AxRepriceBehavior::Unknown))]
1895 #[case::null(None, None)]
1896 fn test_deserialize_order_reprice_behavior(
1897 #[case] raw: Option<&str>,
1898 #[case] expected: Option<AxRepriceBehavior>,
1899 #[values(true, false)] post_only: bool,
1900 ) {
1901 let mut history: serde_json::Value =
1902 serde_json::from_str(include_str!("../../test_data/http_get_orders.json")).unwrap();
1903 let mut open: serde_json::Value =
1904 serde_json::from_str(include_str!("../../test_data/http_get_open_orders.json"))
1905 .unwrap();
1906
1907 for response in [&mut history, &mut open] {
1908 response["orders"][0]["po"] = serde_json::json!(post_only);
1909 response["orders"][0]["rb"] = serde_json::json!(raw);
1910 }
1911
1912 let history: AxOrdersResponse = serde_json::from_value(history).unwrap();
1913 let open: AxOpenOrdersResponse = serde_json::from_value(open).unwrap();
1914
1915 assert_eq!(history.orders[0].po, post_only);
1916 assert_eq!(history.orders[0].rb, expected);
1917 assert_eq!(open.orders[0].po, post_only);
1918 assert_eq!(open.orders[0].rb, expected);
1919 assert_eq!(history.orders[1].rb, None);
1920 assert_eq!(open.orders[1].rb, None);
1921 }
1922
1923 #[rstest]
1924 fn test_deserialize_open_orders_response() {
1925 let json = include_str!("../../test_data/http_get_open_orders.json");
1926 let response: AxOpenOrdersResponse = serde_json::from_str(json).unwrap();
1927 assert_eq!(response.orders.len(), 2);
1928 assert_eq!(response.orders[0].oid, "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
1929 assert_eq!(response.orders[0].d, AxOrderSide::Buy);
1930 assert_eq!(response.orders[0].o, AxOrderStatus::Accepted);
1931 assert_eq!(response.orders[1].xq, 300);
1932 assert_eq!(response.total_count, 2);
1933 assert_eq!(response.limit, 100);
1934 assert_eq!(response.offset, 0);
1935 assert!(response.orders[0].po);
1936 assert_eq!(response.orders[0].rb, Some(AxRepriceBehavior::Reject));
1937 assert!(!response.orders[1].po);
1938 assert_eq!(response.orders[1].rb, None);
1939 }
1940
1941 #[rstest]
1942 fn test_deserialize_fills_response() {
1943 let json = include_str!("../../test_data/http_get_fills.json");
1944 let response: AxFillsResponse = serde_json::from_str(json).unwrap();
1945 assert_eq!(response.fills.len(), 2);
1946 assert_eq!(response.fills[0].side, AxOrderSide::Buy);
1947 assert!(response.fills[0].is_taker);
1948 assert!(!response.fills[1].is_taker);
1949 assert_eq!(response.fills[0].is_block_trade, Some(false));
1950 assert_eq!(response.fills[0].is_final_settlement, Some(false));
1951 assert_eq!(response.total_count, Some(2));
1952 assert_eq!(response.limit, Some(100));
1953 assert_eq!(response.next_cursor, None);
1954 }
1955
1956 #[rstest]
1957 fn test_deserialize_candles_response() {
1958 let json = include_str!("../../test_data/http_get_candles.json");
1959 let response: AxCandlesResponse = serde_json::from_str(json).unwrap();
1960 assert_eq!(response.candles.len(), 2);
1961 assert_eq!(response.candles[0].symbol, "EURUSD-PERP");
1962 assert_eq!(response.candles[0].width, AxCandleWidth::Minutes1);
1963 }
1964
1965 #[rstest]
1966 fn test_deserialize_candle_response() {
1967 let json = include_str!("../../test_data/http_get_candle.json");
1968 let response: AxCandleResponse = serde_json::from_str(json).unwrap();
1969 assert_eq!(response.candle.symbol, "EURUSD-PERP");
1970 assert_eq!(response.candle.width, AxCandleWidth::Minutes1);
1971 }
1972
1973 #[rstest]
1974 fn test_deserialize_risk_snapshot_response() {
1975 let json = include_str!("../../test_data/http_get_risk_snapshot.json");
1976 let response: AxRiskSnapshotResponse = serde_json::from_str(json).unwrap();
1977 assert_eq!(
1978 response.risk_snapshot.account_id,
1979 Ustr::from("3c90c3cc-0d44-4b50-8888-8dd25736052a")
1980 );
1981 assert_eq!(response.risk_snapshot.per_symbol.len(), 2);
1982 assert!(
1983 response
1984 .risk_snapshot
1985 .per_symbol
1986 .contains_key(&Ustr::from("EURUSD-PERP"))
1987 );
1988 assert_eq!(
1989 response.risk_snapshot.per_symbol[&Ustr::from("GBPUSD-PERP")].average_price,
1990 None
1991 );
1992 }
1993
1994 #[rstest]
1995 fn test_deserialize_transactions_response() {
1996 let json = include_str!("../../test_data/http_get_transactions.json");
1997 let response: AxTransactionsResponse = serde_json::from_str(json).unwrap();
1998 assert_eq!(response.transactions.len(), 2);
1999 assert_eq!(response.total_count, Some(2));
2000 assert_eq!(response.limit, Some(100));
2001 assert_eq!(response.transactions[0].account_id, Ustr::from("account-1"));
2002 assert_eq!(response.transactions[0].transaction_type, "deposit");
2003 assert!(response.transactions[0].initiated_by_user_id.is_some());
2004 assert!(response.transactions[1].reference_id.is_none());
2005 }
2006
2007 #[rstest]
2008 fn test_deserialize_preview_aggressive_limit_order_response() {
2009 let json = include_str!("../../test_data/http_preview_aggressive_limit_order.json");
2010 let response: AxPreviewAggressiveLimitOrderResponse = serde_json::from_str(json).unwrap();
2011 assert_eq!(response.filled_quantity, 1000);
2012 assert_eq!(response.remaining_quantity, 0);
2013 assert!(response.limit_price.is_some());
2014 assert!(response.vwap.is_some());
2015 }
2016
2017 #[rstest]
2018 fn test_deserialize_place_order_response() {
2019 let json = include_str!("../../test_data/http_place_order.json");
2020 let response: AxPlaceOrderResponse = serde_json::from_str(json).unwrap();
2021 assert_eq!(response.oid, "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
2022 }
2023
2024 #[rstest]
2025 fn test_deserialize_cancel_order_response() {
2026 let json = include_str!("../../test_data/http_cancel_order.json");
2027 let response: AxCancelOrderResponse = serde_json::from_str(json).unwrap();
2028 assert!(response.cxl_rx);
2029 }
2030
2031 #[rstest]
2032 fn test_deserialize_cancel_all_orders_response() {
2033 let json = include_str!("../../test_data/http_cancel_all_orders.json");
2034 let _response: AxCancelAllOrdersResponse = serde_json::from_str(json).unwrap();
2035 }
2036
2037 #[rstest]
2038 fn test_deserialize_trades_response() {
2039 let json = include_str!("../../test_data/http_get_trades.json");
2040 let response: AxTradesResponse = serde_json::from_str(json).unwrap();
2041 assert_eq!(response.trades.len(), 2);
2042 assert_eq!(response.trades[0].s, "EURUSD-PERP");
2043 assert_eq!(response.trades[0].d, AxOrderSide::Buy);
2044 assert_eq!(response.trades[0].q, 100);
2045 assert_eq!(response.trades[1].d, AxOrderSide::Sell);
2046 }
2047
2048 #[rstest]
2049 fn test_deserialize_book_response() {
2050 let json = include_str!("../../test_data/http_get_book.json");
2051 let response: AxBookResponse = serde_json::from_str(json).unwrap();
2052 assert_eq!(response.book.s, "EURUSD-PERP");
2053 assert_eq!(response.book.b.len(), 3);
2054 assert_eq!(response.book.a.len(), 3);
2055 assert_eq!(response.book.b[0].q, 500);
2056 assert_eq!(response.book.a[0].q, 400);
2057 }
2058
2059 #[rstest]
2060 fn test_deserialize_order_status_query_response() {
2061 let json = include_str!("../../test_data/http_get_order_status.json");
2062 let response: AxOrderStatusQueryResponse = serde_json::from_str(json).unwrap();
2063 assert_eq!(response.status.symbol, "EURUSD-PERP");
2064 assert_eq!(response.status.order_id, "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
2065 assert_eq!(response.status.state, AxOrderStatus::PartiallyFilled);
2066 assert_eq!(response.status.clord_id, Some(12345));
2067 assert_eq!(response.status.filled_quantity, Some(300));
2068 assert_eq!(response.status.remaining_quantity, Some(700));
2069 assert_eq!(response.status.reject_reason, None);
2070 assert_eq!(response.status.reject_message, None);
2071 }
2072
2073 #[rstest]
2074 fn test_deserialize_orders_response() {
2075 let json = include_str!("../../test_data/http_get_orders.json");
2076 let response: AxOrdersResponse = serde_json::from_str(json).unwrap();
2077 assert_eq!(response.orders.len(), 2);
2078 assert_eq!(response.total_count, Some(2));
2079 assert_eq!(response.limit, Some(100));
2080 assert_eq!(response.next_cursor, None);
2081 assert_eq!(response.orders[0].aid.as_deref(), Some("account-1"));
2082 assert_eq!(response.orders[0].o, AxOrderStatus::PartiallyFilled);
2083 assert_eq!(response.orders[0].xq, 300);
2084 assert_eq!(response.orders[1].o, AxOrderStatus::Filled);
2085 assert_eq!(response.orders[1].d, AxOrderSide::Sell);
2086 assert!(response.orders[0].po);
2087 assert_eq!(response.orders[0].rb, Some(AxRepriceBehavior::Reject));
2088 assert!(!response.orders[1].po);
2089 assert_eq!(response.orders[1].rb, None);
2090 }
2091
2092 #[rstest]
2093 fn test_deserialize_initial_margin_requirement_response() {
2094 let json = include_str!("../../test_data/http_initial_margin_requirement.json");
2095 let response: AxInitialMarginRequirementResponse = serde_json::from_str(json).unwrap();
2096 assert_eq!(response.im, Decimal::new(125050, 2));
2097 }
2098
2099 #[rstest]
2100 fn test_deserialize_replace_order_response() {
2101 let json = include_str!("../../test_data/http_replace_order.json");
2102 let response: AxReplaceOrderResponse = serde_json::from_str(json).unwrap();
2103 assert_eq!(response.oid, "O-01ARZ3NDEKTSV4RRFFQ69G5NEW");
2104 }
2105
2106 #[rstest]
2107 fn test_replace_order_request_serialization() {
2108 let request = ReplaceOrderRequest::new("O-01ARZ3NDEKTSV4RRFFQ69G5FAV")
2109 .with_price(Decimal::new(10550, 4))
2110 .with_quantity(200);
2111
2112 let json = serde_json::to_value(&request).unwrap();
2113 assert_eq!(json["oid"], "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
2114 assert_eq!(json["p"], "1.0550");
2115 assert_eq!(json["q"], 200);
2116 assert!(json.get("po").is_none());
2117 assert!(json.get("tif").is_none());
2118 assert!(json.get("trigger_price").is_none());
2119 }
2120
2121 #[rstest]
2122 fn test_replace_order_request_minimal() {
2123 let request = ReplaceOrderRequest::new("O-TEST");
2124 let json = serde_json::to_value(&request).unwrap();
2125 assert_eq!(json["oid"], "O-TEST");
2126 assert!(json.get("p").is_none());
2127 assert!(json.get("q").is_none());
2128 }
2129
2130 #[rstest]
2131 fn test_authenticate_request_serializes_and_redacts_debug() {
2132 let request = AuthenticateApiKeyRequest::new("api-key-token", "api-secret-value", 3600);
2133
2134 let json = serde_json::to_value(&request).unwrap();
2135 let formatted = format!("{request:?}");
2136
2137 assert_eq!(json["api_key"], "api-key-token");
2138 assert_eq!(json["api_secret"], "api-secret-value");
2139 assert_eq!(json["expiration_seconds"], 3600);
2140 assert_eq!(
2141 formatted,
2142 "AuthenticateApiKeyRequest { api_key: <redacted>, api_secret: <redacted>, expiration_seconds: 3600 }",
2143 );
2144 assert!(!formatted.contains("api-key-token"));
2145 assert!(!formatted.contains("api-secret-value"));
2146 }
2147
2148 #[rstest]
2149 fn test_authenticate_response_redacts_debug() {
2150 assert_zeroize_on_drop::<AxAuthenticateResponse>();
2151
2152 let response = AxAuthenticateResponse {
2153 token: SecretString::from("session-token-value"),
2154 };
2155
2156 let formatted = format!("{response:?}");
2157
2158 assert_eq!(formatted, "AxAuthenticateResponse { token: <redacted> }");
2159 assert!(!formatted.contains("session-token-value"));
2160 }
2161
2162 #[rstest]
2163 #[case(false)]
2164 #[case(true)]
2165 fn test_optional_account_names_and_funding_prices(#[case] explicit_null: bool) {
2166 let mut who: serde_json::Value =
2167 serde_json::from_str(include_str!("../../test_data/http_get_whoami.json")).unwrap();
2168 let mut funding: serde_json::Value =
2169 serde_json::from_str(include_str!("../../test_data/http_get_funding_rates.json"))
2170 .unwrap();
2171
2172 for (value, field) in [
2173 (&mut who["accounts"][0], "name"),
2174 (&mut funding["funding_rates"][0], "funding_amount"),
2175 ] {
2176 if explicit_null {
2177 value[field] = serde_json::Value::Null;
2178 } else {
2179 value.as_object_mut().unwrap().remove(field);
2180 }
2181 }
2182
2183 if explicit_null {
2184 funding["funding_rates"][0]["benchmark_price"] = serde_json::Value::Null;
2185 } else {
2186 funding["funding_rates"][0]
2187 .as_object_mut()
2188 .unwrap()
2189 .remove("benchmark_price");
2190 }
2191
2192 let account: AxWhoAmI = serde_json::from_value(who.clone()).unwrap();
2193 who.as_object_mut().unwrap().remove("accounts");
2194 let without_accounts: AxWhoAmI = serde_json::from_value(who).unwrap();
2195 let rates: AxFundingRatesResponse = serde_json::from_value(funding).unwrap();
2196
2197 assert_eq!(account.accounts[0].name, None);
2198 assert!(without_accounts.accounts.is_empty());
2199 assert_eq!(rates.funding_rates[0].funding_amount, None);
2200 assert_eq!(rates.funding_rates[0].benchmark_price, None);
2201 }
2202
2203 #[rstest]
2204 #[case(
2205 "ORIGINAL_ORDER_TERMINATED",
2206 AxOrderRejectReason::OriginalOrderTerminated
2207 )]
2208 #[case(
2209 "DUPLICATE_CLIENT_ORDER_ID",
2210 AxOrderRejectReason::DuplicateClientOrderId
2211 )]
2212 fn test_additional_reject_reasons(#[case] wire: &str, #[case] expected: AxOrderRejectReason) {
2213 let value = serde_json::Value::String(wire.to_owned());
2214 let reason: AxOrderRejectReason = serde_json::from_value(value.clone()).unwrap();
2215 assert_eq!(reason, expected);
2216 assert_eq!(serde_json::to_value(reason).unwrap(), value);
2217 assert_eq!(
2218 AxOrderRejectReason::reason_str(Some(reason), None),
2219 Some(wire.to_owned())
2220 );
2221 }
2222
2223 #[rstest]
2224 #[case(include_str!("../../test_data/captured/whoami.json"), captured_response::<AxWhoAmI>)]
2225 #[case::whoami_without_status(include_str!("../../test_data/captured/whoami-without-status.json"), captured_response::<AxWhoAmI>)]
2226 #[case(include_str!("../../test_data/captured/balances.json"), captured_response::<AxBalancesResponse>)]
2227 #[case(include_str!("../../test_data/captured/positions.json"), captured_response::<AxPositionsResponse>)]
2228 #[case(include_str!("../../test_data/captured/risk.json"), captured_response::<AxRiskSnapshotResponse>)]
2229 #[case(include_str!("../../test_data/captured/instruments.json"), captured_response::<AxInstrumentsResponse>)]
2230 #[case(include_str!("../../test_data/captured/ticker.json"), captured_response::<AxTickerResponse>)]
2231 #[case(include_str!("../../test_data/captured/tickers.json"), captured_response::<AxTickersResponse>)]
2232 #[case(include_str!("../../test_data/captured/book.json"), captured_response::<AxBookResponse>)]
2233 #[case(include_str!("../../test_data/captured/trades.json"), captured_response::<AxTradesResponse>)]
2234 #[case(include_str!("../../test_data/captured/candles.json"), captured_response::<AxCandlesResponse>)]
2235 #[case(include_str!("../../test_data/captured/current-candle.json"), captured_response::<AxCandleResponse>)]
2236 #[case(include_str!("../../test_data/captured/last-candle.json"), captured_response::<AxCandleResponse>)]
2237 #[case(include_str!("../../test_data/captured/funding-rates.json"), captured_response::<AxFundingRatesResponse>)]
2238 #[case(include_str!("../../test_data/captured/funding-slots.json"), captured_response::<AxFundingSlotsResponse>)]
2239 #[case(include_str!("../../test_data/captured/transactions.json"), captured_response::<AxTransactionsResponse>)]
2240 #[case(include_str!("../../test_data/captured/fills.json"), captured_response::<AxFillsResponse>)]
2241 #[case(include_str!("../../test_data/captured/orders.json"), captured_response::<AxOrdersResponse>)]
2242 #[case(include_str!("../../test_data/captured/open-orders.json"), captured_response::<AxOpenOrdersResponse>)]
2243 #[case(include_str!("../../test_data/captured/open-reject.json"), captured_response::<AxOpenOrdersResponse>)]
2244 #[case(include_str!("../../test_data/captured/open-backoff.json"), captured_response::<AxOpenOrdersResponse>)]
2245 #[case(include_str!("../../test_data/captured/open-top.json"), captured_response::<AxOpenOrdersResponse>)]
2246 #[case(include_str!("../../test_data/captured/open-default.json"), captured_response::<AxOpenOrdersResponse>)]
2247 #[case(include_str!("../../test_data/captured/open-inactive.json"), captured_response::<AxOpenOrdersResponse>)]
2248 #[case(include_str!("../../test_data/captured/fills-live.json"), captured_response::<AxFillsResponse>)]
2249 #[case(include_str!("../../test_data/captured/orders-live.json"), captured_response::<AxOrdersResponse>)]
2250 #[case(include_str!("../../test_data/captured/positions-long.json"), captured_response::<AxPositionsResponse>)]
2251 #[case(include_str!("../../test_data/captured/positions-short.json"), captured_response::<AxPositionsResponse>)]
2252 #[case(include_str!("../../test_data/captured/initial-margin.json"), captured_response::<AxInitialMarginRequirementResponse>)]
2253 #[case(include_str!("../../test_data/captured/preview.json"), captured_response::<AxPreviewAggressiveLimitOrderResponse>)]
2254 #[case(include_str!("../../test_data/captured/order-status-canceled.json"), captured_response::<AxOrderStatusQueryResponse>)]
2255 #[case(include_str!("../../test_data/captured/order-status-filled.json"), captured_response::<AxOrderStatusQueryResponse>)]
2256 #[case(include_str!("../../test_data/captured/order-status-replaced.json"), captured_response::<AxOrderStatusQueryResponse>)]
2257 #[case(include_str!("../../test_data/captured/ws-orders-acknowledged.json"), captured_order_event)]
2258 #[case(include_str!("../../test_data/captured/ws-orders-replaced.json"), captured_order_event)]
2259 #[case(include_str!("../../test_data/captured/ws-orders-canceled.json"), captured_order_event)]
2260 #[case(include_str!("../../test_data/captured/ws-orders-expired.json"), captured_order_event)]
2261 #[case(include_str!("../../test_data/captured/ws-orders-rejected.json"), captured_order_event)]
2262 #[case(include_str!("../../test_data/captured/ws-orders-filled-b.json"), captured_order_event)]
2263 #[case(include_str!("../../test_data/captured/ws-orders-filled-s.json"), captured_order_event)]
2264 fn test_captured_response_preserves_every_field(
2265 #[case] raw: &str,
2266 #[case] decode: fn(&serde_json::Value) -> serde_json::Value,
2267 ) {
2268 let mut expected: serde_json::Value = serde_json::from_str(raw).unwrap();
2269 let actual = decode(&expected);
2270 if expected["t"] == "c" && expected["xr"] == "" {
2271 expected["xr"] = "UNKNOWN".into();
2272 }
2273
2274 assert_captured_fields(&expected, &actual, "$");
2275 }
2276
2277 fn captured_response<T: serde::de::DeserializeOwned + Serialize>(
2278 raw: &serde_json::Value,
2279 ) -> serde_json::Value {
2280 serde_json::to_value(serde_json::from_value::<T>(raw.clone()).unwrap()).unwrap()
2281 }
2282
2283 fn captured_order_event(raw: &serde_json::Value) -> serde_json::Value {
2284 let AxOrdersWsFrame::Event(event) = parse_order_message(&raw.to_string()).unwrap() else {
2285 panic!("expected order event");
2286 };
2287
2288 let (tag, actual) = match *event {
2289 AxWsOrderEvent::Acknowledged(message) => ("n", serde_json::to_value(message)),
2290 AxWsOrderEvent::Replaced(message) => ("r", serde_json::to_value(message)),
2291 AxWsOrderEvent::Canceled(message) => ("c", serde_json::to_value(message)),
2292 AxWsOrderEvent::Expired(message) => ("x", serde_json::to_value(message)),
2293 AxWsOrderEvent::Rejected(message) => ("j", serde_json::to_value(message)),
2294 AxWsOrderEvent::Filled(message) => ("f", serde_json::to_value(message)),
2295 AxWsOrderEvent::PartiallyFilled(message) => ("p", serde_json::to_value(message)),
2296 AxWsOrderEvent::DoneForDay(message) => ("d", serde_json::to_value(message)),
2297 AxWsOrderEvent::CancelRejected(message) => ("e", serde_json::to_value(message)),
2298 AxWsOrderEvent::Heartbeat => panic!("expected lifecycle event"),
2299 };
2300
2301 let mut actual = actual.unwrap();
2302 actual["t"] = tag.into();
2303 actual
2304 }
2305
2306 fn assert_captured_fields(
2307 expected: &serde_json::Value,
2308 actual: &serde_json::Value,
2309 path: &str,
2310 ) {
2311 match expected {
2312 serde_json::Value::Object(fields) => {
2313 for (key, value) in fields {
2314 let child = actual
2315 .get(key)
2316 .unwrap_or_else(|| panic!("missing {path}.{key}"));
2317 assert_captured_fields(value, child, &format!("{path}.{key}"));
2318 }
2319 }
2320 serde_json::Value::Array(values) => {
2321 let children = actual.as_array().unwrap();
2322 assert_eq!(children.len(), values.len(), "{path}");
2323
2324 for (i, (value, child)) in values.iter().zip(children).enumerate() {
2325 assert_captured_fields(value, child, &format!("{path}[{i}]"));
2326 }
2327 }
2328 serde_json::Value::String(value) if expected != actual => {
2329 let text = actual
2330 .as_str()
2331 .unwrap_or_else(|| panic!("expected string at {path}: {actual}"));
2332
2333 if let Ok(decimal) = value.parse::<rust_decimal::Decimal>() {
2334 assert_eq!(
2335 text.parse::<rust_decimal::Decimal>().unwrap(),
2336 decimal,
2337 "{path}"
2338 );
2339 } else if let Ok(timestamp) = value.parse::<Timestamp>() {
2340 assert_eq!(text.parse::<Timestamp>().unwrap(), timestamp, "{path}");
2341 } else {
2342 assert_eq!(expected, actual, "{path}");
2343 }
2344 }
2345 serde_json::Value::Number(value) if actual.is_string() => {
2346 assert_eq!(
2347 value.to_string().parse::<rust_decimal::Decimal>().unwrap(),
2348 actual
2349 .as_str()
2350 .unwrap()
2351 .parse::<rust_decimal::Decimal>()
2352 .unwrap(),
2353 "{path}"
2354 );
2355 }
2356 _ => assert_eq!(expected, actual, "{path}"),
2357 }
2358 }
2359}