Skip to main content

nautilus_architect_ax/http/
models.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Data transfer objects for deserializing Ax HTTP API payloads.
17
18use 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
39/// Default instrument state when not provided by API.
40fn default_instrument_state() -> AxInstrumentState {
41    AxInstrumentState::Open
42}
43
44/// An account entry within a [`AxWhoAmI`] response.
45///
46/// Fee rates and close-only state are per account rather than per user.
47///
48/// # References
49/// - <https://docs.architect.exchange/api-reference/user-management/get-whoami>
50#[derive(Clone, Debug, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub struct AxWhoAmIAccount {
53    /// Account identifier.
54    pub id: Ustr,
55    /// Account display name.
56    pub name: Option<String>,
57    /// Whether the account is in close-only mode.
58    pub is_close_only: bool,
59    /// Maker fee rate; absent when the venue supplies no rate, which is distinct from zero.
60    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
61    pub maker_fee: Option<Decimal>,
62    /// Taker fee rate; absent when the venue supplies no rate, which is distinct from zero.
63    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
64    pub taker_fee: Option<Decimal>,
65    /// Whether the account may list its own state.
66    pub can_list: bool,
67    /// Whether the account may read venue state.
68    pub can_read: bool,
69    /// Whether the account may set risk limits.
70    pub can_set_limits: bool,
71    /// Whether the account may reduce or close existing positions.
72    pub can_reduce_or_close: bool,
73    /// Whether the account may open new positions.
74    pub can_trade: bool,
75}
76
77/// Response payload returned by `GET /whoami`.
78///
79/// # References
80/// - <https://docs.architect.exchange/api-reference/user-management/get-whoami>
81#[derive(Clone, Debug, Serialize, Deserialize)]
82#[serde(rename_all = "snake_case")]
83pub struct AxWhoAmI {
84    /// User identifier.
85    pub id: Ustr,
86    /// Username for the account.
87    pub username: Ustr,
88    /// Account creation timestamp.
89    pub created_at: Timestamp,
90    /// Whether two-factor authentication is required.
91    pub require_2fa: bool,
92    /// Whether the user has completed onboarding, when supplied by the venue.
93    #[serde(default)]
94    pub is_onboarded: Option<bool>,
95    /// Whether the account is frozen, when supplied by the venue.
96    #[serde(default)]
97    pub is_frozen: Option<bool>,
98    /// Whether the user has admin privileges.
99    pub is_admin: bool,
100    /// Accounts the credentials can act on.
101    #[serde(default)]
102    pub accounts: Vec<AxWhoAmIAccount>,
103    /// Human-readable alias for the user (optional).
104    #[serde(default)]
105    pub pseudonym: Option<String>,
106    /// Reference code for fiat deposits (optional).
107    #[serde(default)]
108    pub fiat_deposit_code: Option<String>,
109}
110
111/// Individual instrument definition.
112///
113/// # References
114/// - <https://docs.architect.exchange/api-reference/symbols-instruments/get-instruments>
115#[derive(Clone, Debug, Serialize, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub struct AxInstrument {
118    /// Trading symbol for the instrument.
119    pub symbol: Ustr,
120    /// Umbrella product shared by sibling contracts.
121    #[serde(default)]
122    pub product: Option<Ustr>,
123    /// Current trading state of the instrument (defaults to Open if not provided).
124    #[serde(default = "default_instrument_state")]
125    pub state: AxInstrumentState,
126    /// Contract multiplier.
127    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
128    pub multiplier: Decimal,
129    /// Minimum order size.
130    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
131    pub minimum_order_size: Decimal,
132    /// Price tick size.
133    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
134    pub tick_size: Decimal,
135    /// Quote currency symbol.
136    pub quote_currency: Ustr,
137    /// Funding settlement currency.
138    pub funding_settlement_currency: Ustr,
139    /// Instrument category (e.g. fx, equities, metals).
140    pub category: AxCategory,
141    /// Maintenance margin percentage.
142    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
143    pub maintenance_margin_pct: Decimal,
144    /// Initial margin percentage.
145    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
146    pub initial_margin_pct: Decimal,
147    /// Contract mark price description (optional).
148    #[serde(default)]
149    pub contract_mark_price: Option<String>,
150    /// Contract size description (optional).
151    #[serde(default)]
152    pub contract_size: Option<String>,
153    /// Instrument description (optional).
154    #[serde(default)]
155    pub description: Option<String>,
156    /// Contract expiration; absent for perpetual contracts.
157    #[serde(default)]
158    pub expiration: Option<Timestamp>,
159    /// Funding calendar schedule (optional).
160    #[serde(default)]
161    pub funding_calendar_schedule: Option<String>,
162    /// Funding frequency (optional).
163    #[serde(default)]
164    pub funding_frequency: Option<String>,
165    /// Lower cap for funding rate percentage (optional).
166    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
167    pub funding_rate_cap_lower_pct: Option<Decimal>,
168    /// Upper cap for funding rate percentage (optional).
169    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
170    pub funding_rate_cap_upper_pct: Option<Decimal>,
171    /// Lower deviation percentage for price bands (optional).
172    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
173    pub price_band_lower_deviation_pct: Option<Decimal>,
174    /// Upper deviation percentage for price bands (optional).
175    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
176    pub price_band_upper_deviation_pct: Option<Decimal>,
177    /// Price bands configuration (optional).
178    #[serde(default)]
179    pub price_bands: Option<String>,
180    /// Price quotation format (optional).
181    #[serde(default)]
182    pub price_quotation: Option<String>,
183    /// Underlying benchmark price description (optional).
184    #[serde(default)]
185    pub underlying_benchmark_price: Option<String>,
186    /// Price scale.
187    #[serde(default)]
188    pub price_scale: Option<i64>,
189    /// Additional product specs.
190    #[serde(default)]
191    pub additional_product_specs: Option<serde_json::Map<String, serde_json::Value>>,
192    /// Time the instrument was delisted.
193    #[serde(default)]
194    pub delisted_at: Option<Timestamp>,
195    /// Whether new orders and modifications are blocked ahead of delisting.
196    #[serde(default)]
197    pub is_closing: bool,
198    /// Whether the instrument publishes live funding estimates.
199    #[serde(default)]
200    pub estimated_funding_supported: bool,
201    /// Funding schedule calendar description.
202    #[serde(default)]
203    pub funding_schedule_calendar_description: Option<String>,
204    /// Funding schedule time description.
205    #[serde(default)]
206    pub funding_schedule_time_description: Option<String>,
207    /// Funding schedule.
208    #[serde(default)]
209    pub funding_schedule: Option<AxFundingSchedule>,
210    /// Trading schedule.
211    #[serde(default)]
212    pub trading_schedule: Option<AxTradingSchedule>,
213}
214
215/// Time of day in the containing schedule's timezone.
216#[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/// Recurring funding time with ISO weekday numbers in [1, 7].
225#[derive(Clone, Debug, Serialize, Deserialize)]
226pub struct AxFundingTime {
227    pub days_of_week: Vec<u32>,
228    pub time_of_day: AxTimeOfDay,
229}
230
231/// Funding schedule override for a date in the schedule's timezone.
232#[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/// Machine-readable funding schedule.
240#[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/// Trading session segment with ISO weekday numbers in [1, 7].
248#[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/// Machine-readable trading schedule.
259#[derive(Clone, Debug, Serialize, Deserialize)]
260pub struct AxTradingSchedule {
261    pub segments: Vec<AxTradingSegment>,
262}
263
264/// Availability of a live funding estimate.
265#[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/// Live funding estimate carried by a ticker.
276#[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/// Response payload returned by `GET /instruments`.
293///
294/// # References
295/// - <https://docs.architect.exchange/api-reference/symbols-instruments/get-instruments>
296#[derive(Clone, Debug, Serialize, Deserialize)]
297#[serde(rename_all = "snake_case")]
298pub struct AxInstrumentsResponse {
299    /// List of instruments.
300    pub instruments: Vec<AxInstrument>,
301}
302
303/// Individual balance entry.
304///
305/// # References
306/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-balances>
307#[derive(Clone, Debug, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub struct AxBalance {
310    /// Asset symbol.
311    pub symbol: Ustr,
312    /// Available balance amount.
313    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
314    pub amount: Decimal,
315    /// Account identifier.
316    #[serde(default)]
317    pub account_id: Option<Ustr>,
318}
319
320/// Response payload returned by `GET /balances`.
321///
322/// # References
323/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-balances>
324#[derive(Clone, Debug, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub struct AxBalancesResponse {
327    /// List of balances.
328    pub balances: Vec<AxBalance>,
329    /// USD borrowed against the account.
330    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
331    pub usd_borrow: Option<Decimal>,
332}
333
334/// Individual position entry.
335///
336/// # References
337/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-positions>
338#[derive(Clone, Debug, Serialize, Deserialize)]
339#[serde(rename_all = "snake_case")]
340pub struct AxPosition {
341    /// Account identifier.
342    pub account_id: Ustr,
343    /// Instrument symbol.
344    pub symbol: Ustr,
345    /// Signed quantity (positive for long, negative for short).
346    pub signed_quantity: i64,
347    /// Signed notional value.
348    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
349    pub signed_notional: Decimal,
350    /// Position timestamp.
351    pub timestamp: Timestamp,
352    /// Realized profit and loss.
353    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
354    pub realized_pnl: Decimal,
355    /// Signed cost basis.
356    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
357    pub signed_cost_basis: Option<Decimal>,
358}
359
360/// Response payload returned by `GET /positions`.
361///
362/// # References
363/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-positions>
364#[derive(Clone, Debug, Serialize, Deserialize)]
365#[serde(rename_all = "snake_case")]
366pub struct AxPositionsResponse {
367    /// List of positions.
368    pub positions: Vec<AxPosition>,
369}
370
371/// Individual ticker entry.
372///
373/// # References
374/// - <https://docs.architect.exchange/api-reference/marketdata/get-ticker>
375#[derive(Clone, Debug, Serialize, Deserialize)]
376#[serde(rename_all = "snake_case")]
377pub struct AxTicker {
378    /// Instrument symbol.
379    #[serde(rename = "s")]
380    pub symbol: Ustr,
381    /// Best bid price.
382    #[serde(
383        default,
384        rename = "bp",
385        deserialize_with = "deserialize_optional_decimal"
386    )]
387    pub bid: Option<Decimal>,
388    /// Best ask price.
389    #[serde(
390        default,
391        rename = "ap",
392        deserialize_with = "deserialize_optional_decimal"
393    )]
394    pub ask: Option<Decimal>,
395    /// Last trade price.
396    #[serde(
397        default,
398        rename = "p",
399        deserialize_with = "deserialize_optional_decimal"
400    )]
401    pub last: Option<Decimal>,
402    /// Mark price.
403    #[serde(
404        default,
405        rename = "m",
406        deserialize_with = "deserialize_optional_decimal"
407    )]
408    pub mark: Option<Decimal>,
409    /// 24-hour volume.
410    #[serde(
411        default,
412        rename = "v",
413        deserialize_with = "deserialize_optional_decimal"
414    )]
415    pub volume_24h: Option<Decimal>,
416    /// 24-hour high price.
417    #[serde(
418        default,
419        rename = "h",
420        deserialize_with = "deserialize_optional_decimal"
421    )]
422    pub high_24h: Option<Decimal>,
423    /// 24-hour low price.
424    #[serde(
425        default,
426        rename = "l",
427        deserialize_with = "deserialize_optional_decimal"
428    )]
429    pub low_24h: Option<Decimal>,
430    /// Timestamp seconds.
431    #[serde(default)]
432    pub ts: Option<i64>,
433    /// Timestamp nanosecond component.
434    #[serde(default)]
435    pub tn: Option<i64>,
436    /// Last trade quantity.
437    #[serde(default, rename = "q")]
438    pub last_quantity: Option<u64>,
439    /// Open interest.
440    #[serde(default, rename = "oi")]
441    pub open_interest: Option<i64>,
442    /// Instrument state.
443    #[serde(default, rename = "i")]
444    pub instrument_state: Option<AxInstrumentState>,
445    /// Price band lower limit.
446    #[serde(
447        default,
448        rename = "pl",
449        deserialize_with = "deserialize_optional_decimal"
450    )]
451    pub price_band_lower: Option<Decimal>,
452    /// Price band upper limit.
453    #[serde(
454        default,
455        rename = "pu",
456        deserialize_with = "deserialize_optional_decimal"
457    )]
458    pub price_band_upper: Option<Decimal>,
459    /// Last settlement price.
460    #[serde(
461        default,
462        rename = "lsp",
463        deserialize_with = "deserialize_optional_decimal"
464    )]
465    pub last_settlement_price: Option<Decimal>,
466    /// Last settlement time as epoch seconds.
467    #[serde(default, rename = "lst")]
468    pub last_settlement_time: Option<i64>,
469    /// Opening price for the ticker window.
470    #[serde(
471        default,
472        rename = "o",
473        deserialize_with = "deserialize_optional_decimal_from_str"
474    )]
475    pub open: Option<Decimal>,
476    /// Estimated funding.
477    #[serde(default, rename = "ef")]
478    pub estimated_funding: Option<AxEstimatedFundingRate>,
479}
480
481/// Response payload returned by `GET /tickers`.
482///
483/// # References
484/// - <https://docs.architect.exchange/api-reference/marketdata/get-tickers>
485#[derive(Clone, Debug, Serialize, Deserialize)]
486#[serde(rename_all = "snake_case")]
487pub struct AxTickersResponse {
488    /// List of tickers.
489    pub tickers: Vec<AxTicker>,
490    /// Total matching records.
491    pub total_count: i64,
492    /// Applied limit.
493    pub limit: i32,
494    /// Applied offset.
495    pub offset: i32,
496}
497
498/// Response payload returned by `GET /ticker`.
499///
500/// # References
501/// - <https://docs.architect.exchange/api-reference/marketdata/get-ticker>
502#[derive(Clone, Debug, Serialize, Deserialize)]
503#[serde(rename_all = "snake_case")]
504pub struct AxTickerResponse {
505    /// The ticker data.
506    pub ticker: AxTicker,
507}
508
509/// Response payload returned by `POST /authenticate`.
510///
511/// # References
512/// - <https://docs.architect.exchange/api-reference/user-management/authenticate>
513#[derive(Debug, Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
514#[serde(rename_all = "snake_case")]
515pub struct AxAuthenticateResponse {
516    /// Session token for authenticated requests.
517    pub token: SecretString,
518}
519
520impl AxAuthenticateResponse {
521    /// Consumes the response and returns the session token.
522    #[must_use]
523    pub fn into_token(mut self) -> SecretString {
524        std::mem::take(&mut self.token)
525    }
526}
527
528/// Response payload returned by `POST /place-order`.
529///
530/// # References
531/// - <https://docs.architect.exchange/api-reference/order-management/place-order>
532#[derive(Clone, Debug, Serialize, Deserialize)]
533pub struct AxPlaceOrderResponse {
534    /// Order ID of the placed order.
535    pub oid: String,
536}
537
538/// Response payload returned by `POST /cancel-order`.
539///
540/// # References
541/// - <https://docs.architect.exchange/api-reference/order-management/cancel-order>
542#[derive(Clone, Debug, Serialize, Deserialize)]
543pub struct AxCancelOrderResponse {
544    /// Whether the cancel request has been accepted.
545    pub cxl_rx: bool,
546}
547
548/// Individual trade entry from the REST API.
549///
550/// # References
551/// - <https://docs.architect.exchange/api-reference/marketdata/get-trades>
552#[derive(Clone, Debug, Serialize, Deserialize)]
553pub struct AxRestTrade {
554    /// Timestamp (Unix epoch seconds).
555    pub ts: i64,
556    /// Nanosecond component of the timestamp.
557    pub tn: i64,
558    /// Trade price (decimal string).
559    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
560    pub p: Decimal,
561    /// Trade quantity.
562    pub q: i64,
563    /// Symbol.
564    pub s: Ustr,
565    /// Trade direction (aggressor side).
566    pub d: AxOrderSide,
567}
568
569/// Response payload returned by `GET /trades`.
570///
571/// # References
572/// - <https://docs.architect.exchange/api-reference/marketdata/get-trades>
573#[derive(Clone, Debug, Serialize, Deserialize)]
574pub struct AxTradesResponse {
575    /// List of trades.
576    pub trades: Vec<AxRestTrade>,
577}
578
579/// Individual price level in the order book.
580///
581/// # References
582/// - <https://docs.architect.exchange/api-reference/marketdata/get-book>
583#[derive(Clone, Debug, Serialize, Deserialize)]
584pub struct AxBookLevel {
585    /// Price (decimal string).
586    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
587    pub p: Decimal,
588    /// Quantity at this price level.
589    pub q: i64,
590    /// Individual order IDs (Level 3 only).
591    #[serde(default)]
592    pub o: Option<Vec<i64>>,
593}
594
595/// Order book snapshot.
596///
597/// # References
598/// - <https://docs.architect.exchange/api-reference/marketdata/get-book>
599#[derive(Clone, Debug, Serialize, Deserialize)]
600pub struct AxBook {
601    /// Timestamp (Unix epoch seconds).
602    pub ts: i64,
603    /// Nanosecond component of the timestamp.
604    pub tn: i64,
605    /// Symbol.
606    pub s: Ustr,
607    /// Bid levels (best to worst).
608    pub b: Vec<AxBookLevel>,
609    /// Ask levels (best to worst).
610    pub a: Vec<AxBookLevel>,
611}
612
613/// Response payload returned by `GET /book`.
614///
615/// # References
616/// - <https://docs.architect.exchange/api-reference/marketdata/get-book>
617#[derive(Clone, Debug, Serialize, Deserialize)]
618pub struct AxBookResponse {
619    /// The order book snapshot.
620    pub book: AxBook,
621}
622
623/// Detailed order status from single-order lookup.
624///
625/// # References
626/// - <https://docs.architect.exchange/api-reference/order-management/get-order-status>
627#[derive(Clone, Debug, Serialize, Deserialize)]
628pub struct AxOrderStatusDetail {
629    /// Trading symbol.
630    pub symbol: Ustr,
631    /// Order ID.
632    pub order_id: String,
633    /// Current order state.
634    pub state: AxOrderStatus,
635    /// Client order ID.
636    #[serde(default)]
637    pub clord_id: Option<u64>,
638    /// Filled quantity.
639    #[serde(default)]
640    pub filled_quantity: Option<i64>,
641    /// Remaining quantity.
642    #[serde(default)]
643    pub remaining_quantity: Option<i64>,
644    /// Reject reason.
645    #[serde(default)]
646    pub reject_reason: Option<AxOrderRejectReason>,
647    /// Reject message.
648    #[serde(default)]
649    pub reject_message: Option<String>,
650}
651
652/// Response payload returned by `GET /order-status`.
653///
654/// # References
655/// - <https://docs.architect.exchange/api-reference/order-management/get-order-status>
656#[derive(Clone, Debug, Serialize, Deserialize)]
657pub struct AxOrderStatusQueryResponse {
658    /// The order status detail.
659    pub status: AxOrderStatusDetail,
660}
661
662/// Reason for order rejection from the exchange.
663///
664/// # References
665/// - <https://docs.architect.exchange/api-reference/order-management/get-orders>
666#[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    /// Formats a venue reject reason for events and reports: the known enum
689    /// spelling when available, otherwise the order text. Returns `None` when
690    /// neither carries a usable reason.
691    #[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/// Post-only repricing behavior from the latest place or replace request.
703#[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/// Detailed order entry from historical orders query.
716///
717/// # References
718/// - <https://docs.architect.exchange/api-reference/order-management/get-orders>
719#[derive(Clone, Debug, Serialize, Deserialize)]
720pub struct AxOrderDetail {
721    /// Timestamp (Unix epoch seconds).
722    pub ts: i64,
723    /// Nanosecond component.
724    #[serde(default)]
725    pub tn: i64,
726    /// Order ID.
727    pub oid: String,
728    /// Account ID.
729    #[serde(default)]
730    pub aid: Option<Ustr>,
731    /// User ID.
732    pub u: Ustr,
733    /// Symbol.
734    pub s: Ustr,
735    /// Price.
736    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
737    pub p: Decimal,
738    /// Order quantity.
739    pub q: u64,
740    /// Executed quantity.
741    pub xq: u64,
742    /// Remaining quantity.
743    pub rq: u64,
744    /// Order state.
745    pub o: AxOrderStatus,
746    /// Order side.
747    pub d: AxOrderSide,
748    /// Time in force.
749    pub tif: AxTimeInForce,
750    /// Client order ID.
751    #[serde(default)]
752    pub cid: Option<u64>,
753    /// Reject reason.
754    #[serde(default)]
755    pub r: Option<AxOrderRejectReason>,
756    /// Order tag.
757    #[serde(default)]
758    pub tag: Option<String>,
759    /// Text note.
760    #[serde(default)]
761    pub txt: Option<String>,
762    /// Whether the order is post-only.
763    #[serde(default)]
764    pub po: bool,
765    /// Repricing behavior from the latest place or replace, effective only when `po` is true.
766    #[serde(default)]
767    pub rb: Option<AxRepriceBehavior>,
768}
769
770/// Response payload returned by `GET /orders`.
771///
772/// # References
773/// - <https://docs.architect.exchange/api-reference/order-management/get-orders>
774#[derive(Clone, Debug, Serialize, Deserialize)]
775pub struct AxOrdersResponse {
776    /// List of order details.
777    pub orders: Vec<AxOrderDetail>,
778    /// Total matching records (for pagination).
779    #[serde(default)]
780    pub total_count: Option<i64>,
781    /// Applied limit.
782    #[serde(default)]
783    pub limit: Option<i32>,
784    /// Applied offset.
785    #[serde(default)]
786    pub offset: Option<i32>,
787    /// Next page cursor.
788    #[serde(default)]
789    pub next_cursor: Option<String>,
790}
791
792/// Response payload returned by `POST /initial-margin-requirement`.
793///
794/// # References
795/// - <https://docs.architect.exchange/api-reference/order-management/calculate-initial-margin-requirement>
796#[derive(Clone, Debug, Serialize, Deserialize)]
797pub struct AxInitialMarginRequirementResponse {
798    /// Initial margin requirement.
799    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
800    pub im: Decimal,
801    /// Initial margin percentage.
802    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
803    pub im_pct: Option<Decimal>,
804    /// Contract multiplier.
805    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
806    pub mult: Option<Decimal>,
807    /// Signed position quantity.
808    #[serde(default)]
809    pub pos: Option<i64>,
810}
811
812/// Individual open order entry.
813///
814/// # References
815/// - <https://docs.architect.exchange/api-reference/order-management/get-open-orders>
816#[derive(Clone, Debug, Serialize, Deserialize)]
817pub struct AxOpenOrder {
818    /// Trade number.
819    pub tn: i64,
820    /// Timestamp (Unix epoch).
821    pub ts: i64,
822    /// Order side: "B" (buy) or "S" (sell).
823    pub d: AxOrderSide,
824    /// Order status.
825    pub o: AxOrderStatus,
826    /// Order ID.
827    pub oid: String,
828    /// Price.
829    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
830    pub p: Decimal,
831    /// Quantity.
832    pub q: u64,
833    /// Remaining quantity.
834    pub rq: u64,
835    /// Symbol.
836    pub s: Ustr,
837    /// Time in force.
838    pub tif: AxTimeInForce,
839    /// User ID.
840    pub u: Ustr,
841    /// Executed quantity.
842    pub xq: u64,
843    /// Optional client ID for order correlation.
844    #[serde(default)]
845    pub cid: Option<u64>,
846    /// Optional order tag.
847    #[serde(default)]
848    pub tag: Option<String>,
849    /// Whether the order is post-only.
850    #[serde(default)]
851    pub po: bool,
852    /// Repricing behavior from the latest place or replace, effective only when `po` is true.
853    #[serde(default)]
854    pub rb: Option<AxRepriceBehavior>,
855    /// Account identifier.
856    #[serde(default)]
857    pub aid: Option<Ustr>,
858    /// Order rejection reason.
859    #[serde(default)]
860    pub r: Option<AxOrderRejectReason>,
861    /// Additional venue explanation.
862    #[serde(default)]
863    pub txt: Option<String>,
864}
865
866/// Response payload returned by `GET /open-orders`.
867///
868/// # References
869/// - <https://docs.architect.exchange/api-reference/order-management/get-open-orders>
870#[derive(Clone, Debug, Serialize, Deserialize)]
871pub struct AxOpenOrdersResponse {
872    /// List of open orders.
873    pub orders: Vec<AxOpenOrder>,
874    /// Total matching records.
875    pub total_count: i64,
876    /// Applied limit.
877    pub limit: i32,
878    /// Applied offset.
879    pub offset: i32,
880}
881
882/// Individual fill/trade entry.
883///
884/// # References
885/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-fills>
886#[derive(Clone, Debug, Serialize, Deserialize)]
887#[serde(rename_all = "snake_case")]
888pub struct AxFill {
889    /// Trade ID (execution identifier).
890    pub trade_id: String,
891    /// Order ID.
892    pub order_id: Option<String>,
893    /// Fee amount.
894    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
895    pub fee: Decimal,
896    /// Whether this was a taker order.
897    pub is_taker: bool,
898    /// Whether this fill was generated by an off-book block trade.
899    pub is_block_trade: Option<bool>,
900    /// Whether this fill was generated by final contract settlement.
901    pub is_final_settlement: Option<bool>,
902    /// Execution price.
903    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
904    pub price: Decimal,
905    /// Executed quantity (always non-negative).
906    pub quantity: u64,
907    /// Order side.
908    pub side: AxOrderSide,
909    /// Instrument symbol.
910    pub symbol: Ustr,
911    /// Execution timestamp.
912    pub timestamp: Timestamp,
913    /// Account identifier.
914    pub account_id: Ustr,
915    /// Realized PnL for this fill.
916    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
917    pub realized_pnl: Option<Decimal>,
918}
919
920/// Response payload returned by `GET /fills`.
921///
922/// # References
923/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-fills>
924#[derive(Clone, Debug, Serialize, Deserialize)]
925#[serde(rename_all = "snake_case")]
926pub struct AxFillsResponse {
927    /// List of fills.
928    pub fills: Vec<AxFill>,
929    /// Total matching records, when supplied by AX.
930    #[serde(default)]
931    pub total_count: Option<i64>,
932    /// Applied limit, when supplied by AX.
933    #[serde(default)]
934    pub limit: Option<i32>,
935    /// Cursor for the next page, when one exists.
936    #[serde(default)]
937    pub next_cursor: Option<String>,
938}
939
940/// Individual candle/OHLCV entry.
941///
942/// # References
943/// - <https://docs.architect.exchange/api-reference/marketdata/get-candles>
944#[derive(Clone, Debug, Serialize, Deserialize)]
945#[serde(rename_all = "snake_case")]
946pub struct AxCandle {
947    /// Instrument symbol.
948    pub symbol: Ustr,
949    /// Candle timestamp (Unix epoch seconds).
950    pub ts: i64,
951    /// Open price.
952    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
953    pub open: Decimal,
954    /// High price.
955    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
956    pub high: Decimal,
957    /// Low price.
958    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
959    pub low: Decimal,
960    /// Close price.
961    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
962    pub close: Decimal,
963    /// Buy volume.
964    pub buy_volume: u64,
965    /// Sell volume.
966    pub sell_volume: u64,
967    /// Total volume.
968    pub volume: u64,
969    /// Candle width/interval.
970    pub width: AxCandleWidth,
971}
972
973/// Response payload returned by `GET /candles`.
974///
975/// # References
976/// - <https://docs.architect.exchange/api-reference/marketdata/get-candles>
977#[derive(Clone, Debug, Serialize, Deserialize)]
978#[serde(rename_all = "snake_case")]
979pub struct AxCandlesResponse {
980    /// List of candles.
981    pub candles: Vec<AxCandle>,
982}
983
984/// Response payload returned by `GET /candles/current` and `GET /candles/last`.
985///
986/// # References
987/// - <https://docs.architect.exchange/api-reference/marketdata/get-current-candle>
988/// - <https://docs.architect.exchange/api-reference/marketdata/get-last-candle>
989#[derive(Clone, Debug, Serialize, Deserialize)]
990#[serde(rename_all = "snake_case")]
991pub struct AxCandleResponse {
992    /// The candle data.
993    pub candle: AxCandle,
994}
995
996/// Individual funding rate entry.
997///
998/// # References
999/// - <https://docs.architect.exchange/api-reference/marketdata/get-funding-rates>
1000#[derive(Clone, Debug, Serialize, Deserialize)]
1001#[serde(rename_all = "snake_case")]
1002pub struct AxFundingRate {
1003    /// Instrument symbol.
1004    pub symbol: Ustr,
1005    /// Timestamp in nanoseconds.
1006    pub timestamp_ns: i64,
1007    /// Funding rate.
1008    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1009    pub funding_rate: Decimal,
1010    /// Funding amount.
1011    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1012    pub funding_amount: Option<Decimal>,
1013    /// Benchmark price.
1014    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1015    pub benchmark_price: Option<Decimal>,
1016    /// Settlement price.
1017    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1018    pub settlement_price: Decimal,
1019}
1020
1021/// Response payload returned by `GET /funding-rates`.
1022///
1023/// # References
1024/// - <https://docs.architect.exchange/api-reference/marketdata/get-funding-rates>
1025#[derive(Clone, Debug, Serialize, Deserialize)]
1026#[serde(rename_all = "snake_case")]
1027pub struct AxFundingRatesResponse {
1028    /// List of funding rates.
1029    pub funding_rates: Vec<AxFundingRate>,
1030    /// Total matching records, when supplied by AX.
1031    #[serde(default)]
1032    pub total_count: Option<i64>,
1033    /// Applied limit, when supplied by AX.
1034    #[serde(default)]
1035    pub limit: Option<i32>,
1036    /// Cursor for the next page, when one exists.
1037    #[serde(default)]
1038    pub next_cursor: Option<String>,
1039}
1040
1041/// One funding slot of a trading day, as returned by `GET /funding-slots`.
1042///
1043/// # References
1044/// - <https://docs.architect.exchange/api-reference>
1045#[derive(Clone, Debug, Serialize, Deserialize)]
1046#[serde(rename_all = "snake_case")]
1047pub struct AxFundingSlot {
1048    /// 1-based position within the day's schedule.
1049    pub index: i32,
1050    /// Scheduled settlement time of the slot.
1051    pub funding_time: Timestamp,
1052    /// Slot settlement state.
1053    pub status: AxFundingSlotStatus,
1054    /// True when the rate was clamped by the symbol's funding rate cap.
1055    pub capped: bool,
1056    /// Mark-price TWAP over the slot, when available.
1057    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1058    pub mark_twap: Option<Decimal>,
1059    /// Underlying-price TWAP over the slot, when available.
1060    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1061    pub underlying_twap: Option<Decimal>,
1062    /// Premium of the mark TWAP over the underlying TWAP, in basis points.
1063    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1064    pub premium_bps: Option<Decimal>,
1065    /// Slot funding rate in basis points; positive means longs pay shorts.
1066    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1067    pub funding_rate_bps: Option<Decimal>,
1068    /// Why a skipped slot did not settle; present only on skipped slots.
1069    #[serde(default)]
1070    pub reason: Option<String>,
1071}
1072
1073/// Response payload returned by `GET /funding-slots`.
1074///
1075/// A full trading day of funding slots with running totals. `daily_close`
1076/// symbols report a single slot.
1077///
1078/// # References
1079/// - <https://docs.architect.exchange/api-reference>
1080#[derive(Clone, Debug, Serialize, Deserialize)]
1081#[serde(rename_all = "snake_case")]
1082pub struct AxFundingSlotsResponse {
1083    /// Instrument symbol.
1084    pub symbol: Ustr,
1085    /// Trading day the schedule covers.
1086    pub date: Date,
1087    /// IANA name of the funding schedule's timezone.
1088    pub timezone: Ustr,
1089    /// How the symbol's funding accrues over the day.
1090    pub variant: AxFundingVariant,
1091    /// Number of funding slots scheduled on `date`; 0 on holidays and weekends.
1092    pub interval_count: i32,
1093    /// Per-slot cap on the funding rate in basis points, when configured.
1094    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1095    pub cap_bps: Option<Decimal>,
1096    /// Funding slots for the day.
1097    pub slots: Vec<AxFundingSlot>,
1098    /// Sum of realized slot rates so far, in basis points.
1099    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1100    pub realized_sum_bps: Decimal,
1101    /// Projected end-of-day total in basis points: realized plus remaining projections.
1102    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1103    pub projected_eod_bps: Decimal,
1104    /// Minutes between intraday funding slots, when supplied by AX.
1105    #[serde(default)]
1106    pub slot_interval_minutes: Option<u32>,
1107}
1108
1109/// Per-symbol risk metrics.
1110///
1111/// # References
1112/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-risk-snapshot>
1113#[derive(Clone, Debug, Serialize, Deserialize)]
1114#[serde(rename_all = "snake_case")]
1115pub struct AxPerSymbolRisk {
1116    /// Signed quantity (positive for long, negative for short).
1117    pub signed_quantity: i64,
1118    /// Signed notional value.
1119    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1120    pub signed_notional: Decimal,
1121    /// Average entry price.
1122    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1123    pub average_price: Option<Decimal>,
1124    /// Liquidation price.
1125    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1126    pub liquidation_price: Option<Decimal>,
1127    /// Initial margin required for the position.
1128    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1129    pub initial_margin_required_position: Decimal,
1130    /// Initial margin required for open orders.
1131    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1132    pub initial_margin_required_open_orders: Decimal,
1133    /// Total initial margin required.
1134    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1135    pub initial_margin_required_total: Decimal,
1136    /// Maintenance margin required.
1137    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1138    pub maintenance_margin_required: Decimal,
1139    /// Unrealized P&L.
1140    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1141    pub unrealized_pnl: Decimal,
1142    /// Signed cost basis.
1143    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1144    pub signed_cost_basis: Option<Decimal>,
1145    /// Signed USD notional.
1146    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1147    pub signed_usd_notional: Option<Decimal>,
1148    /// Mark price.
1149    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1150    pub mark_price: Option<Decimal>,
1151}
1152
1153/// Risk snapshot data.
1154///
1155/// # References
1156/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-risk-snapshot>
1157#[derive(Clone, Debug, Serialize, Deserialize)]
1158#[serde(rename_all = "snake_case")]
1159pub struct AxRiskSnapshot {
1160    /// USD account balance.
1161    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1162    pub balance_usd: Decimal,
1163    /// Total equity value.
1164    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1165    pub equity: Decimal,
1166    /// Available initial margin.
1167    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1168    pub initial_margin_available: Decimal,
1169    /// Margin required for open orders.
1170    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1171    pub initial_margin_required_for_open_orders: Decimal,
1172    /// Margin required for positions.
1173    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1174    pub initial_margin_required_for_positions: Decimal,
1175    /// Total initial margin requirement.
1176    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1177    pub initial_margin_required_total: Decimal,
1178    /// Available maintenance margin.
1179    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1180    pub maintenance_margin_available: Decimal,
1181    /// Required maintenance margin.
1182    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1183    pub maintenance_margin_required: Decimal,
1184    /// Unrealized profit/loss.
1185    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1186    pub unrealized_pnl: Decimal,
1187    /// Snapshot timestamp.
1188    pub timestamp_ns: Timestamp,
1189    /// Account identifier.
1190    pub account_id: Ustr,
1191    /// Per-symbol risk data.
1192    #[serde(default)]
1193    pub per_symbol: AHashMap<Ustr, AxPerSymbolRisk>,
1194}
1195
1196/// Response payload returned by `GET /risk-snapshot`.
1197///
1198/// # References
1199/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-risk-snapshot>
1200#[derive(Clone, Debug, Serialize, Deserialize)]
1201#[serde(rename_all = "snake_case")]
1202pub struct AxRiskSnapshotResponse {
1203    /// The risk snapshot data.
1204    pub risk_snapshot: AxRiskSnapshot,
1205}
1206
1207/// Individual transaction entry.
1208///
1209/// # References
1210/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-transactions>
1211#[derive(Clone, Debug, Serialize, Deserialize)]
1212#[serde(rename_all = "snake_case")]
1213pub struct AxTransaction {
1214    /// Account identifier.
1215    pub account_id: Ustr,
1216    /// Transaction amount.
1217    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
1218    pub amount: Decimal,
1219    /// Unique event identifier.
1220    pub event_id: String,
1221    /// Asset symbol.
1222    pub symbol: Ustr,
1223    /// Transaction timestamp.
1224    pub timestamp: Timestamp,
1225    /// Type of transaction.
1226    pub transaction_type: Ustr,
1227    /// User who initiated the transaction, when available.
1228    #[serde(default)]
1229    pub initiated_by_user_id: Option<Ustr>,
1230    /// Optional reference identifier.
1231    #[serde(default)]
1232    pub reference_id: Option<String>,
1233}
1234
1235/// Response payload returned by `GET /transactions`.
1236///
1237/// # References
1238/// - <https://docs.architect.exchange/api-reference/portfolio-management/get-transactions>
1239#[derive(Clone, Debug, Serialize, Deserialize)]
1240#[serde(rename_all = "snake_case")]
1241pub struct AxTransactionsResponse {
1242    /// List of transactions.
1243    pub transactions: Vec<AxTransaction>,
1244    /// Total matching records.
1245    #[serde(default)]
1246    pub total_count: Option<i64>,
1247    /// Applied limit.
1248    #[serde(default)]
1249    pub limit: Option<i32>,
1250    /// Next page cursor.
1251    #[serde(default)]
1252    pub next_cursor: Option<String>,
1253}
1254
1255/// Request body for `POST /authenticate` using API key and secret.
1256///
1257/// # References
1258/// - <https://docs.architect.exchange/api-reference/user-management/authenticate>
1259#[derive(Debug, Clone, Serialize, Deserialize, Zeroize)]
1260#[serde(rename_all = "snake_case")]
1261pub struct AuthenticateApiKeyRequest {
1262    /// API key.
1263    pub api_key: SecretString,
1264    /// API secret.
1265    pub api_secret: SecretString,
1266    /// Token expiration in seconds.
1267    pub expiration_seconds: i32,
1268}
1269
1270impl AuthenticateApiKeyRequest {
1271    /// Creates a new [`AuthenticateApiKeyRequest`].
1272    #[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/// Request body for `POST /place-order`.
1287///
1288/// # References
1289/// - <https://docs.architect.exchange/api-reference/order-management/place-order>
1290#[derive(Clone, Debug, Serialize, Deserialize)]
1291pub struct PlaceOrderRequest {
1292    /// Order side: "B" (buy) or "S" (sell).
1293    pub d: AxOrderSide,
1294    /// Order price (limit price).
1295    #[serde(serialize_with = "serialize_decimal_as_str")]
1296    pub p: Decimal,
1297    /// Post-only flag (maker-or-cancel).
1298    pub po: bool,
1299    /// Order quantity in contracts.
1300    pub q: u64,
1301    /// Order symbol.
1302    pub s: Ustr,
1303    /// Time in force.
1304    pub tif: AxTimeInForce,
1305    /// Optional order tag (max 10 alphanumeric characters).
1306    #[serde(skip_serializing_if = "Option::is_none")]
1307    pub tag: Option<String>,
1308}
1309
1310impl PlaceOrderRequest {
1311    /// Creates a new [`PlaceOrderRequest`] for the AX priced order shape.
1312    #[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    /// Sets the optional order tag.
1333    #[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/// Request body for `POST /preview-aggressive-limit-order`.
1341///
1342/// # References
1343/// - <https://docs.architect.exchange/api-reference/marketdata/preview-aggressive-limit-order>
1344#[derive(Clone, Debug, Serialize, Deserialize)]
1345pub struct PreviewAggressiveLimitOrderRequest {
1346    /// Trading symbol.
1347    pub symbol: Ustr,
1348    /// Order quantity in contracts.
1349    pub quantity: u64,
1350    /// Order side: "B" (buy) or "S" (sell).
1351    pub side: AxOrderSide,
1352}
1353
1354impl PreviewAggressiveLimitOrderRequest {
1355    /// Creates a new [`PreviewAggressiveLimitOrderRequest`].
1356    #[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/// Response payload returned by `POST /preview-aggressive-limit-order`.
1367///
1368/// # References
1369/// - <https://docs.architect.exchange/api-reference/marketdata/preview-aggressive-limit-order>
1370#[derive(Clone, Debug, Serialize, Deserialize)]
1371pub struct AxPreviewAggressiveLimitOrderResponse {
1372    /// Quantity that would be filled at the aggressive price.
1373    pub filled_quantity: u64,
1374    /// Quantity that cannot be filled (insufficient book depth).
1375    pub remaining_quantity: u64,
1376    /// The aggressive limit price ("take through" price), or None if no liquidity.
1377    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1378    pub limit_price: Option<Decimal>,
1379    /// Volume-weighted average price of expected fills.
1380    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
1381    pub vwap: Option<Decimal>,
1382}
1383
1384/// Request body for `POST /cancel-order`.
1385///
1386/// # References
1387/// - <https://docs.architect.exchange/api-reference/order-management/cancel-order>
1388#[derive(Clone, Debug, Serialize, Deserialize)]
1389pub struct CancelOrderRequest {
1390    /// Order ID to cancel.
1391    pub oid: String,
1392}
1393
1394impl CancelOrderRequest {
1395    /// Creates a new [`CancelOrderRequest`].
1396    #[must_use]
1397    pub fn new(order_id: impl Into<String>) -> Self {
1398        Self {
1399            oid: order_id.into(),
1400        }
1401    }
1402}
1403
1404/// Request body for `POST /replace-order`.
1405///
1406/// Replaces (amends) an existing order. Unspecified optional fields inherit
1407/// from the original order. The exchange returns a new order ID.
1408///
1409/// # References
1410/// - <https://docs.architect.exchange/api-reference/order-management/replace-order>
1411#[derive(Clone, Debug, Serialize, Deserialize)]
1412pub struct ReplaceOrderRequest {
1413    /// Order ID to replace.
1414    pub oid: String,
1415    /// New limit price (optional, inherits from original if omitted).
1416    #[serde(
1417        skip_serializing_if = "Option::is_none",
1418        serialize_with = "serialize_optional_decimal_as_str"
1419    )]
1420    pub p: Option<Decimal>,
1421    /// New quantity in contracts (optional, inherits from original if omitted).
1422    #[serde(skip_serializing_if = "Option::is_none")]
1423    pub q: Option<u64>,
1424    /// New post-only flag (optional, inherits from original if omitted).
1425    #[serde(skip_serializing_if = "Option::is_none")]
1426    pub po: Option<bool>,
1427    /// New time-in-force (optional, inherits from original if omitted).
1428    #[serde(skip_serializing_if = "Option::is_none")]
1429    pub tif: Option<AxTimeInForce>,
1430}
1431
1432impl ReplaceOrderRequest {
1433    /// Creates a new [`ReplaceOrderRequest`] with only the order ID.
1434    ///
1435    /// Use the builder methods to set the fields to amend.
1436    #[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    /// Sets the new limit price.
1448    #[must_use]
1449    pub fn with_price(mut self, price: Decimal) -> Self {
1450        self.p = Some(price);
1451        self
1452    }
1453
1454    /// Sets the new quantity.
1455    #[must_use]
1456    pub fn with_quantity(mut self, quantity: u64) -> Self {
1457        self.q = Some(quantity);
1458        self
1459    }
1460}
1461
1462/// Response payload returned by `POST /replace-order`.
1463///
1464/// # References
1465/// - <https://docs.architect.exchange/api-reference/order-management/replace-order>
1466#[derive(Clone, Debug, Serialize, Deserialize)]
1467pub struct AxReplaceOrderResponse {
1468    /// New order ID assigned to the replacement order.
1469    pub oid: String,
1470}
1471
1472/// Request body for `POST /cancel-all-orders`.
1473///
1474/// # References
1475/// - <https://docs.architect.exchange/api-reference/order-management/place-order>
1476#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1477pub struct CancelAllOrdersRequest {
1478    /// Optional account ID. AX infers the session account when omitted.
1479    #[serde(skip_serializing_if = "Option::is_none")]
1480    pub account_id: Option<Ustr>,
1481    /// Optional symbol filter - only cancel orders for this symbol.
1482    #[serde(skip_serializing_if = "Option::is_none")]
1483    pub symbol: Option<Ustr>,
1484}
1485
1486impl CancelAllOrdersRequest {
1487    /// Creates a new [`CancelAllOrdersRequest`] to cancel all orders.
1488    #[must_use]
1489    pub fn new() -> Self {
1490        Self::default()
1491    }
1492
1493    /// Sets the account filter.
1494    #[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    /// Sets the symbol filter.
1501    #[must_use]
1502    pub fn with_symbol(mut self, symbol: Ustr) -> Self {
1503        self.symbol = Some(symbol);
1504        self
1505    }
1506}
1507
1508/// Response payload returned by `POST /cancel-all-orders`.
1509///
1510/// # References
1511/// - <https://docs.architect.exchange/api-reference/order-management/place-order>
1512#[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        // A zero rate is valid, so an absent rate must not deserialize to zero
1633        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}