Skip to main content

nautilus_architect_ax/websocket/
messages.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//! WebSocket message types for the AX Exchange API.
17//!
18//! This module contains request and response message structures for both
19//! market data and order management WebSocket streams.
20
21use nautilus_core::{UUID4, UnixNanos, serialization::serialize_decimal_as_str};
22use nautilus_model::{
23    events::OrderInitialized,
24    identifiers::{ClientOrderId, InstrumentId, StrategyId, TraderId, VenueOrderId},
25    types::Currency,
26};
27use rust_decimal::Decimal;
28use serde::{Deserialize, Serialize};
29use ustr::Ustr;
30
31use super::error::AxWsErrorResponse;
32use crate::{
33    common::{
34        enums::{
35            AxCancelReason, AxCancelRejectionReason, AxCandleWidth, AxInstrumentState,
36            AxMarketDataLevel, AxMdRequestType, AxOrderRequestType, AxOrderSide, AxOrderStatus,
37            AxOrderWsMessageType, AxSelfTradeBehavior, AxTimeInForce,
38        },
39        parse::{deserialize_decimal_or_zero, deserialize_optional_decimal_from_str},
40    },
41    http::models::{AxEstimatedFundingRate, AxOrderRejectReason, AxRepriceBehavior},
42};
43
44/// Market data WebSocket message emitted by the data handler.
45///
46/// Contains raw venue types for downstream consumers to parse
47/// into Nautilus domain objects.
48#[derive(Debug, Clone)]
49pub enum AxDataWsMessage {
50    /// Parsed market data message from the venue.
51    MdMessage(AxMdMessage),
52    /// WebSocket reconnected notification.
53    Reconnected,
54    /// A candle subscription was removed (clear cached state for this key).
55    CandleUnsubscribed { symbol: Ustr, width: AxCandleWidth },
56}
57
58/// Subscribe request for market data.
59///
60/// # References
61/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
62#[derive(Clone, Debug, Serialize, Deserialize)]
63pub struct AxMdSubscribe {
64    /// Client request ID for correlation.
65    #[serde(alias = "request_id")]
66    pub rid: i64,
67    /// Request type (always "subscribe").
68    #[serde(rename = "type")]
69    pub msg_type: AxMdRequestType,
70    /// Instrument symbol.
71    pub symbol: Ustr,
72    /// Market data level (LEVEL_1, LEVEL_2, LEVEL_3, TRADES).
73    pub level: AxMarketDataLevel,
74    /// Whether book-level subscriptions should include trade prints.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub trades: Option<bool>,
77    /// Whether book-level subscriptions should include ticker updates.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub ticker: Option<bool>,
80}
81
82/// Unsubscribe request for market data.
83///
84/// # References
85/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
86#[derive(Clone, Debug, Serialize, Deserialize)]
87pub struct AxMdUnsubscribe {
88    /// Client request ID for correlation.
89    #[serde(alias = "request_id")]
90    pub rid: i64,
91    /// Request type (always "unsubscribe").
92    #[serde(rename = "type")]
93    pub msg_type: AxMdRequestType,
94    /// Instrument symbol.
95    pub symbol: Ustr,
96}
97
98/// Subscribe request for candle data.
99///
100/// # References
101/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
102#[derive(Clone, Debug, Serialize, Deserialize)]
103pub struct AxMdSubscribeCandles {
104    /// Client request ID for correlation.
105    #[serde(alias = "request_id")]
106    pub rid: i64,
107    /// Request type (always "subscribe_candles").
108    #[serde(rename = "type")]
109    pub msg_type: AxMdRequestType,
110    /// Instrument symbol.
111    pub symbol: Ustr,
112    /// Candle width/interval.
113    pub width: AxCandleWidth,
114}
115
116/// Unsubscribe request for candle data.
117///
118/// # References
119/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
120#[derive(Clone, Debug, Serialize, Deserialize)]
121pub struct AxMdUnsubscribeCandles {
122    /// Client request ID for correlation.
123    #[serde(alias = "request_id")]
124    pub rid: i64,
125    /// Request type (always "unsubscribe_candles").
126    #[serde(rename = "type")]
127    pub msg_type: AxMdRequestType,
128    /// Instrument symbol.
129    pub symbol: Ustr,
130    /// Candle width/interval.
131    pub width: AxCandleWidth,
132}
133
134/// Heartbeat message from market data WebSocket.
135///
136/// # References
137/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
138#[derive(Clone, Debug, Serialize, Deserialize)]
139pub struct AxMdHeartbeat {
140    /// Timestamp (Unix epoch seconds).
141    pub ts: i64,
142    /// Subsecond timestamp nanoseconds.
143    pub tn: i64,
144}
145
146/// Incoming market data WebSocket message.
147///
148/// Deserializes directly from JSON using the "t" field as discriminator.
149#[derive(Clone, Debug)]
150pub enum AxMdMessage {
151    BookL1(AxMdBookL1),
152    BookL2(AxMdBookL2),
153    BookL3(AxMdBookL3),
154    Ticker(Box<AxMdTicker>),
155    Trade(AxMdTrade),
156    Candle(AxMdCandle),
157    Heartbeat(AxMdHeartbeat),
158    SubscriptionResponse(AxMdSubscriptionResponse),
159    Error(AxWsError),
160}
161
162/// Subscription response from market data WebSocket.
163#[derive(Clone, Debug, Deserialize)]
164pub struct AxMdSubscriptionResponse {
165    /// Request ID for correlation.
166    #[serde(alias = "request_id")]
167    pub rid: i64,
168    /// Result payload (contains subscribed symbol or candle info).
169    #[serde(alias = "res")]
170    pub result: AxMdSubscriptionResult,
171}
172
173/// Result payload for subscription response.
174#[derive(Clone, Debug, Deserialize)]
175pub struct AxMdSubscriptionResult {
176    /// Subscribed symbol (for regular subscriptions).
177    #[serde(default)]
178    pub subscribed: Option<Ustr>,
179    /// Subscribed candle info (for candle subscriptions).
180    #[serde(default)]
181    pub subscribed_candle: Option<Ustr>,
182    /// Unsubscribed symbol (for unsubscription responses).
183    #[serde(default)]
184    pub unsubscribed: Option<Ustr>,
185    /// Unsubscribed candle info (for candle unsubscription responses).
186    #[serde(default)]
187    pub unsubscribed_candle: Option<Ustr>,
188}
189
190/// Error response from market data WebSocket with nested error object.
191#[derive(Clone, Debug, Deserialize)]
192pub struct AxMdErrorResponse {
193    /// Request ID for correlation.
194    #[serde(alias = "request_id")]
195    pub rid: Option<i64>,
196    /// Nested error object containing code and message.
197    #[serde(alias = "err")]
198    pub error: AxMdErrorInner,
199}
200
201/// Inner error object for market data WebSocket errors.
202#[derive(Clone, Debug, Deserialize)]
203pub struct AxMdErrorInner {
204    /// Error code.
205    pub code: i32,
206    /// Error message.
207    pub message: String,
208}
209
210impl From<AxMdErrorResponse> for AxWsError {
211    fn from(resp: AxMdErrorResponse) -> Self {
212        Self {
213            code: Some(resp.error.code.to_string()),
214            message: resp.error.message,
215            request_id: resp.rid,
216        }
217    }
218}
219
220/// Ticker/statistics message from market data WebSocket.
221///
222/// # References
223/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
224#[derive(Clone, Debug, Serialize, Deserialize)]
225pub struct AxMdTicker {
226    /// Timestamp (Unix epoch seconds).
227    pub ts: i64,
228    /// Subsecond timestamp nanoseconds.
229    pub tn: i64,
230    /// Instrument symbol.
231    pub s: Ustr,
232    /// Last price (null when no recent price data, e.g. before first trade).
233    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
234    pub p: Option<Decimal>,
235    /// Last quantity.
236    pub q: u64,
237    /// Open price (24h), null before first session open.
238    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
239    pub o: Option<Decimal>,
240    /// Low price (24h, null when no recent price data).
241    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
242    pub l: Option<Decimal>,
243    /// High price (24h, null when no recent price data).
244    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
245    pub h: Option<Decimal>,
246    /// Volume (24h).
247    pub v: u64,
248    /// Open interest.
249    #[serde(default)]
250    pub oi: Option<i64>,
251    /// Mark price.
252    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
253    pub m: Option<Decimal>,
254    /// Instrument state.
255    #[serde(default)]
256    pub i: Option<AxInstrumentState>,
257    /// Price band lower limit.
258    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
259    pub pl: Option<Decimal>,
260    /// Price band upper limit.
261    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
262    pub pu: Option<Decimal>,
263    /// Last settlement price.
264    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
265    pub lsp: Option<Decimal>,
266    /// Best bid price.
267    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
268    pub bp: Option<Decimal>,
269    /// Best ask price.
270    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
271    pub ap: Option<Decimal>,
272    /// Last settlement timestamp (Unix epoch seconds).
273    #[serde(default)]
274    pub lst: Option<i64>,
275    /// Live funding estimate.
276    #[serde(default)]
277    pub ef: Option<AxEstimatedFundingRate>,
278}
279
280/// Trade message from market data WebSocket.
281///
282/// # References
283/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
284#[derive(Clone, Debug, Serialize, Deserialize)]
285pub struct AxMdTrade {
286    /// Timestamp (Unix epoch seconds).
287    pub ts: i64,
288    /// Nanosecond component of the timestamp.
289    pub tn: i64,
290    /// Instrument symbol.
291    pub s: Ustr,
292    /// Trade price.
293    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
294    pub p: Decimal,
295    /// Trade quantity.
296    pub q: u64,
297    /// Aggressor side of the trade: "B" (buy) or "S" (sell).
298    pub d: AxOrderSide,
299}
300
301/// Candle/OHLCV message from market data WebSocket.
302///
303/// # References
304/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
305#[derive(Clone, Debug, Serialize, Deserialize)]
306pub struct AxMdCandle {
307    /// Instrument symbol.
308    pub symbol: Ustr,
309    /// Candle timestamp (Unix epoch).
310    pub ts: i64,
311    /// Open price.
312    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
313    pub open: Decimal,
314    /// Low price.
315    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
316    pub low: Decimal,
317    /// High price.
318    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
319    pub high: Decimal,
320    /// Close price.
321    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
322    pub close: Decimal,
323    /// Total volume.
324    pub volume: u64,
325    /// Buy volume.
326    pub buy_volume: u64,
327    /// Sell volume.
328    pub sell_volume: u64,
329    /// Candle width/interval.
330    pub width: AxCandleWidth,
331}
332
333/// Price level entry in order book.
334#[derive(Clone, Debug, Serialize, Deserialize)]
335pub struct AxBookLevel {
336    /// Price at this level.
337    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
338    pub p: Decimal,
339    /// Quantity at this level.
340    pub q: u64,
341}
342
343/// Price level entry with individual order breakdown (L3).
344#[derive(Clone, Debug, Serialize, Deserialize)]
345pub struct AxBookLevelL3 {
346    /// Price at this level.
347    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
348    pub p: Decimal,
349    /// Total quantity at this level.
350    pub q: u64,
351    /// Individual order quantities at this price.
352    pub o: Vec<u64>,
353}
354
355/// Level 1 order book update (best bid/ask).
356///
357/// # References
358/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
359#[derive(Clone, Debug, Serialize, Deserialize)]
360pub struct AxMdBookL1 {
361    /// Timestamp (Unix epoch seconds).
362    pub ts: i64,
363    /// Subsecond timestamp nanoseconds.
364    pub tn: i64,
365    /// Instrument symbol.
366    pub s: Ustr,
367    /// Bid levels (typically just best bid).
368    pub b: Vec<AxBookLevel>,
369    /// Ask levels (typically just best ask).
370    pub a: Vec<AxBookLevel>,
371}
372
373/// Level 2 order book update (aggregated price levels).
374///
375/// AX flags every observed frame as a full snapshot (`st: true`), so the parser rebuilds the book
376/// from each message. Incremental frames (`st: false`) are not handled.
377///
378/// # References
379/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
380#[derive(Clone, Debug, Serialize, Deserialize)]
381pub struct AxMdBookL2 {
382    /// Timestamp (Unix epoch seconds).
383    pub ts: i64,
384    /// Subsecond timestamp nanoseconds.
385    pub tn: i64,
386    /// Instrument symbol.
387    pub s: Ustr,
388    /// Bid levels.
389    pub b: Vec<AxBookLevel>,
390    /// Ask levels.
391    pub a: Vec<AxBookLevel>,
392    /// Whether this update is a full snapshot.
393    #[serde(default)]
394    pub st: bool,
395}
396
397/// Level 3 order book update (individual order quantities).
398///
399/// AX flags every observed frame as a full snapshot (`st: true`), so the parser rebuilds the book
400/// from each message. Incremental frames (`st: false`) are not handled.
401///
402/// # References
403/// - <https://docs.architect.exchange/api-reference/marketdata/md-ws>
404#[derive(Clone, Debug, Serialize, Deserialize)]
405pub struct AxMdBookL3 {
406    /// Timestamp (Unix epoch seconds).
407    pub ts: i64,
408    /// Subsecond timestamp nanoseconds.
409    pub tn: i64,
410    /// Instrument symbol.
411    pub s: Ustr,
412    /// Bid levels with order breakdown.
413    pub b: Vec<AxBookLevelL3>,
414    /// Ask levels with order breakdown.
415    pub a: Vec<AxBookLevelL3>,
416    /// Whether this update is a full snapshot.
417    #[serde(default)]
418    pub st: bool,
419}
420
421/// Place order request via WebSocket.
422///
423/// # References
424/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
425#[derive(Clone, Debug, Serialize, Deserialize)]
426pub struct AxWsPlaceOrder {
427    /// Request ID for correlation.
428    #[serde(alias = "request_id")]
429    pub rid: i64,
430    /// Message type (always "p").
431    pub t: AxOrderRequestType,
432    /// Instrument symbol.
433    pub s: Ustr,
434    /// Order side: "B" (buy) or "S" (sell).
435    pub d: AxOrderSide,
436    /// Order quantity.
437    pub q: u64,
438    /// Order price (limit price).
439    #[serde(
440        serialize_with = "serialize_decimal_as_str",
441        deserialize_with = "deserialize_decimal_or_zero"
442    )]
443    pub p: Decimal,
444    /// Time in force.
445    pub tif: AxTimeInForce,
446    /// Post-only flag (maker-or-cancel).
447    pub po: bool,
448    /// Optional client order ID.
449    #[serde(skip_serializing_if = "Option::is_none")]
450    pub cid: Option<u64>,
451    /// Optional self-trade prevention behavior.
452    #[serde(skip_serializing_if = "Option::is_none")]
453    pub st: Option<AxSelfTradeBehavior>,
454    /// Optional order tag (max 10 alphanumeric characters).
455    #[serde(skip_serializing_if = "Option::is_none")]
456    pub tag: Option<String>,
457}
458
459/// Cancel order request via WebSocket.
460///
461/// # References
462/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
463#[derive(Clone, Debug, Serialize, Deserialize)]
464pub struct AxWsCancelOrder {
465    /// Request ID for correlation.
466    #[serde(alias = "request_id")]
467    pub rid: i64,
468    /// Message type (always "x").
469    pub t: AxOrderRequestType,
470    /// Order ID to cancel.
471    pub oid: String,
472}
473
474/// Get open orders request via WebSocket.
475///
476/// # References
477/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
478#[derive(Clone, Debug, Serialize, Deserialize)]
479pub struct AxWsGetOpenOrders {
480    /// Request ID for correlation.
481    #[serde(alias = "request_id")]
482    pub rid: i64,
483    /// Message type (always "o").
484    pub t: AxOrderRequestType,
485}
486
487/// Place order response from WebSocket.
488///
489/// # References
490/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
491#[derive(Clone, Debug, Serialize, Deserialize)]
492pub struct AxWsPlaceOrderResponse {
493    /// Request ID matching the original request.
494    #[serde(alias = "request_id")]
495    pub rid: i64,
496    /// Response result.
497    #[serde(alias = "result")]
498    pub res: AxWsPlaceOrderResult,
499}
500
501/// Result payload for place order response.
502#[derive(Clone, Debug, Serialize, Deserialize)]
503pub struct AxWsPlaceOrderResult {
504    /// Order ID of the placed order.
505    pub oid: String,
506}
507
508/// Cancel order response from WebSocket.
509///
510/// # References
511/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
512#[derive(Clone, Debug, Serialize, Deserialize)]
513pub struct AxWsCancelOrderResponse {
514    /// Request ID matching the original request.
515    #[serde(alias = "request_id")]
516    pub rid: i64,
517    /// Response result.
518    #[serde(alias = "result")]
519    pub res: AxWsCancelOrderResult,
520}
521
522/// Result payload for cancel order response.
523#[derive(Clone, Debug, Serialize, Deserialize)]
524pub struct AxWsCancelOrderResult {
525    /// Whether the cancel request was received.
526    pub cxl_rx: bool,
527}
528
529/// Open orders response from WebSocket.
530///
531/// # References
532/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
533#[derive(Clone, Debug, Serialize, Deserialize)]
534pub struct AxWsOpenOrdersResponse {
535    /// Request ID matching the original request.
536    #[serde(alias = "request_id")]
537    pub rid: i64,
538    /// Open orders result.
539    #[serde(alias = "result")]
540    pub res: AxWsOpenOrdersResult,
541}
542
543/// Result payload for an open orders response.
544#[derive(Clone, Debug, Serialize, Deserialize)]
545pub struct AxWsOpenOrdersResult {
546    /// List of open orders.
547    pub orders: Vec<AxWsOrder>,
548}
549
550/// Error response from the Ax orders WebSocket.
551///
552/// Returned when a request fails (e.g., insufficient margin, invalid order).
553#[derive(Clone, Debug, Deserialize)]
554pub struct AxWsOrderErrorResponse {
555    /// Request ID matching the original request.
556    #[serde(alias = "request_id")]
557    pub rid: i64,
558    /// Error details.
559    #[serde(alias = "error")]
560    pub err: AxWsOrderError,
561}
562
563/// Error details in an error response.
564#[derive(Clone, Debug, Deserialize)]
565pub struct AxWsOrderError {
566    /// Error code (e.g., 400).
567    pub code: Option<i64>,
568    /// Error message.
569    pub msg: Option<String>,
570}
571
572/// List subscription response from the Ax orders WebSocket.
573///
574/// Returned when subscribing to order updates, contains a list ID for the subscription.
575#[derive(Clone, Debug, Deserialize)]
576pub struct AxWsListResponse {
577    /// Request ID matching the original request.
578    #[serde(alias = "request_id")]
579    pub rid: i64,
580    /// Response result.
581    #[serde(alias = "result")]
582    pub res: AxWsListResult,
583}
584
585/// List subscription result payload.
586#[derive(Clone, Debug, Deserialize)]
587pub struct AxWsListResult {
588    /// List subscription ID.
589    pub li: String,
590    /// Order data (null on initial subscription, array of orders otherwise).
591    #[serde(default)]
592    pub o: Option<Vec<AxWsOrder>>,
593    /// Whether orders cancel on disconnect.
594    #[serde(default)]
595    pub cod: Option<bool>,
596    /// Client heartbeat timeout accepted by the server, in seconds.
597    #[serde(default)]
598    pub chb: Option<u64>,
599}
600
601/// Order details in WebSocket messages.
602#[derive(Clone, Debug, Serialize, Deserialize)]
603pub struct AxWsOrder {
604    /// Order ID.
605    pub oid: String,
606    /// User ID.
607    pub u: Ustr,
608    /// Instrument symbol.
609    pub s: Ustr,
610    /// Order price.
611    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
612    pub p: Decimal,
613    /// Order quantity.
614    pub q: u64,
615    /// Executed quantity.
616    pub xq: u64,
617    /// Remaining quantity.
618    pub rq: u64,
619    /// Order status.
620    pub o: AxOrderStatus,
621    /// Order side.
622    pub d: AxOrderSide,
623    /// Time in force.
624    pub tif: AxTimeInForce,
625    /// Timestamp (Unix epoch seconds).
626    pub ts: i64,
627    /// Subsecond timestamp nanoseconds.
628    pub tn: i64,
629    /// Optional client order ID.
630    #[serde(default)]
631    pub cid: Option<u64>,
632    /// Optional order tag.
633    #[serde(default)]
634    pub tag: Option<String>,
635    /// Optional text/description.
636    #[serde(default)]
637    pub txt: Option<String>,
638    /// Account identifier.
639    #[serde(default)]
640    pub aid: Option<Ustr>,
641    /// Whether the order is post-only.
642    #[serde(default)]
643    pub po: bool,
644    /// Post-only reprice behavior reported by AX.
645    #[serde(default)]
646    pub rb: Option<AxRepriceBehavior>,
647    /// Order rejection reason.
648    #[serde(default)]
649    pub r: Option<AxOrderRejectReason>,
650}
651
652/// Heartbeat event from orders WebSocket.
653///
654/// # References
655/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
656#[derive(Clone, Debug, Serialize, Deserialize)]
657pub struct AxWsHeartbeat {
658    /// Message type (always "h").
659    pub t: AxOrderWsMessageType,
660    /// Timestamp (Unix epoch seconds).
661    pub ts: i64,
662    /// Subsecond timestamp nanoseconds.
663    pub tn: i64,
664}
665
666/// Order acknowledged event.
667///
668/// # References
669/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
670#[derive(Clone, Debug, Serialize, Deserialize)]
671pub struct AxWsOrderAcknowledged {
672    /// Timestamp (Unix epoch seconds).
673    pub ts: i64,
674    /// Subsecond timestamp nanoseconds.
675    pub tn: i64,
676    /// Event ID.
677    pub eid: String,
678    /// Order details.
679    pub o: AxWsOrder,
680}
681
682/// Trade execution details for fill events.
683#[derive(Clone, Debug, Serialize, Deserialize)]
684pub struct AxWsTradeExecution {
685    /// Trade ID.
686    pub tid: String,
687    /// Instrument symbol.
688    pub s: Ustr,
689    /// Executed quantity.
690    pub q: u64,
691    /// Execution price.
692    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
693    pub p: Decimal,
694    /// Trade direction.
695    pub d: AxOrderSide,
696    /// Whether this was an aggressor (taker) order.
697    pub agg: bool,
698    /// Account identifier.
699    #[serde(default)]
700    pub aid: Option<Ustr>,
701}
702
703/// Order partially filled event.
704///
705/// # References
706/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
707#[derive(Clone, Debug, Serialize, Deserialize)]
708pub struct AxWsOrderPartiallyFilled {
709    /// Timestamp (Unix epoch seconds).
710    pub ts: i64,
711    /// Subsecond timestamp nanoseconds.
712    pub tn: i64,
713    /// Event ID.
714    pub eid: String,
715    /// Order details.
716    pub o: AxWsOrder,
717    /// Trade execution details.
718    pub xs: AxWsTradeExecution,
719}
720
721/// Order filled event.
722///
723/// # References
724/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
725#[derive(Clone, Debug, Serialize, Deserialize)]
726pub struct AxWsOrderFilled {
727    /// Timestamp (Unix epoch seconds).
728    pub ts: i64,
729    /// Subsecond timestamp nanoseconds.
730    pub tn: i64,
731    /// Event ID.
732    pub eid: String,
733    /// Order details.
734    pub o: AxWsOrder,
735    /// Trade execution details.
736    pub xs: AxWsTradeExecution,
737}
738
739/// Order canceled event.
740///
741/// # References
742/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
743#[derive(Clone, Debug, Serialize, Deserialize)]
744pub struct AxWsOrderCanceled {
745    /// Timestamp (Unix epoch seconds).
746    pub ts: i64,
747    /// Subsecond timestamp nanoseconds.
748    pub tn: i64,
749    /// Event ID.
750    pub eid: String,
751    /// Order details.
752    pub o: AxWsOrder,
753    /// Cancellation reason.
754    pub xr: AxCancelReason,
755    /// Cancellation text/description.
756    #[serde(default)]
757    pub txt: Option<String>,
758}
759
760/// Order rejected event.
761///
762/// # References
763/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
764#[derive(Clone, Debug, Serialize, Deserialize)]
765pub struct AxWsOrderRejected {
766    /// Timestamp (Unix epoch seconds).
767    pub ts: i64,
768    /// Subsecond timestamp nanoseconds.
769    pub tn: i64,
770    /// Event ID.
771    pub eid: String,
772    /// Order details.
773    pub o: AxWsOrder,
774    /// Rejection reason code.
775    #[serde(default)]
776    pub r: Option<AxOrderRejectReason>,
777    /// Rejection text/description.
778    #[serde(default)]
779    pub txt: Option<String>,
780}
781
782/// Order expired event.
783///
784/// # References
785/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
786#[derive(Clone, Debug, Serialize, Deserialize)]
787pub struct AxWsOrderExpired {
788    /// Timestamp (Unix epoch seconds).
789    pub ts: i64,
790    /// Subsecond timestamp nanoseconds.
791    pub tn: i64,
792    /// Event ID.
793    pub eid: String,
794    /// Order details.
795    pub o: AxWsOrder,
796}
797
798/// Order replaced/amended event.
799///
800/// # References
801/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
802#[derive(Clone, Debug, Serialize, Deserialize)]
803pub struct AxWsOrderReplaced {
804    /// Timestamp (Unix epoch seconds).
805    pub ts: i64,
806    /// Subsecond timestamp nanoseconds.
807    pub tn: i64,
808    /// Event ID.
809    pub eid: String,
810    /// Replaced order details.
811    pub ro: Box<AxWsOrder>,
812    /// New order ID for cancel-replace; absent for an in-place amend.
813    #[serde(default)]
814    pub noid: Option<String>,
815    /// New order details for cancel-replace; absent for an in-place amend.
816    #[serde(default)]
817    pub no: Option<Box<AxWsOrder>>,
818}
819
820/// Order done for day event.
821///
822/// # References
823/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
824#[derive(Clone, Debug, Serialize, Deserialize)]
825pub struct AxWsOrderDoneForDay {
826    /// Timestamp (Unix epoch seconds).
827    pub ts: i64,
828    /// Subsecond timestamp nanoseconds.
829    pub tn: i64,
830    /// Event ID.
831    pub eid: String,
832    /// Order details.
833    pub o: AxWsOrder,
834}
835
836/// Cancel rejected event.
837///
838/// # References
839/// - <https://docs.architect.exchange/api-reference/order-management/orders-ws>
840#[derive(Clone, Debug, Serialize, Deserialize)]
841pub struct AxWsCancelRejected {
842    /// Timestamp (Unix epoch seconds).
843    pub ts: i64,
844    /// Subsecond timestamp nanoseconds.
845    pub tn: i64,
846    /// Order ID that failed to cancel.
847    pub oid: String,
848    /// Rejection reason code.
849    pub r: AxCancelRejectionReason,
850    /// Rejection text/description.
851    #[serde(default)]
852    pub txt: Option<String>,
853    /// Client order identifier.
854    #[serde(default)]
855    pub cid: Option<u64>,
856    /// Order details, when provided by the venue.
857    #[serde(default)]
858    pub o: Option<AxWsOrder>,
859}
860
861/// Venue-level order event from the Ax orders WebSocket.
862///
863/// This enum uses serde's tagged deserialization to automatically
864/// discriminate between different event types based on the "t" field.
865#[derive(Debug, Clone, Deserialize)]
866#[serde(tag = "t")]
867pub enum AxWsOrderEvent {
868    /// Heartbeat message.
869    #[serde(rename = "h")]
870    Heartbeat,
871    /// Order acknowledged.
872    #[serde(rename = "n")]
873    Acknowledged(AxWsOrderAcknowledged),
874    /// Order partially filled.
875    #[serde(rename = "p")]
876    PartiallyFilled(AxWsOrderPartiallyFilled),
877    /// Order filled.
878    #[serde(rename = "f")]
879    Filled(AxWsOrderFilled),
880    /// Order canceled.
881    #[serde(rename = "c")]
882    Canceled(AxWsOrderCanceled),
883    /// Order rejected.
884    #[serde(rename = "j")]
885    Rejected(AxWsOrderRejected),
886    /// Order expired.
887    #[serde(rename = "x")]
888    Expired(AxWsOrderExpired),
889    /// Order replaced.
890    #[serde(rename = "r")]
891    Replaced(AxWsOrderReplaced),
892    /// Order done for day.
893    #[serde(rename = "d")]
894    DoneForDay(AxWsOrderDoneForDay),
895    /// Cancel rejected.
896    #[serde(rename = "e")]
897    CancelRejected(AxWsCancelRejected),
898}
899
900/// Internal raw response from the Ax orders WebSocket.
901///
902/// Response messages have "rid" and "res" fields.
903#[derive(Debug, Clone)]
904pub(crate) enum AxWsOrderResponse {
905    /// Place order response (res has "oid").
906    PlaceOrder(AxWsPlaceOrderResponse),
907    /// Cancel order response (res has "cxl_rx").
908    CancelOrder(AxWsCancelOrderResponse),
909    /// Open orders response (res has "orders").
910    OpenOrders(AxWsOpenOrdersResponse),
911    /// List subscription response (res has "li").
912    List(AxWsListResponse),
913}
914
915/// Internal raw message from the Ax orders WebSocket.
916#[derive(Debug, Clone)]
917pub(crate) enum AxOrdersWsFrame {
918    /// Error response message (has "rid" and "err").
919    Error(AxWsOrderErrorResponse),
920    /// Response message (has "rid" and "res").
921    Response(AxWsOrderResponse),
922    /// Event message (has "t" field).
923    Event(Box<AxWsOrderEvent>),
924}
925
926/// Messages from the Ax orders WebSocket handler.
927///
928/// Contains venue-level events and responses for downstream consumers
929/// to parse into Nautilus domain objects.
930#[derive(Debug, Clone)]
931pub enum AxOrdersWsMessage {
932    /// Venue-level order event.
933    Event(Box<AxWsOrderEvent>),
934    /// Place order response.
935    PlaceOrderResponse(AxWsPlaceOrderResponse),
936    /// Cancel order response.
937    CancelOrderResponse(AxWsCancelOrderResponse),
938    /// Open orders response.
939    OpenOrdersResponse(AxWsOpenOrdersResponse),
940    /// Known-unsent place-order failure.
941    PlaceOrderError {
942        /// Client order ID that was not submitted.
943        client_order_id: ClientOrderId,
944        /// Reason the order was not submitted.
945        reason: String,
946    },
947    /// Known-unsent cancel-order failure.
948    CancelOrderError {
949        /// Client order ID whose cancellation was not sent.
950        client_order_id: ClientOrderId,
951        /// Reason the cancellation was not sent.
952        reason: String,
953        /// Command ID that correlates the denial with its pending cancel.
954        command_id: Option<UUID4>,
955    },
956    /// Error from venue or client.
957    Error(AxWsError),
958    /// WebSocket reconnected notification.
959    Reconnected,
960    /// Authentication successful notification.
961    Authenticated,
962}
963
964/// Represents an error event surfaced by the WebSocket client.
965#[derive(Debug, Clone)]
966pub struct AxWsError {
967    /// Error code from Ax.
968    pub code: Option<String>,
969    /// Human readable message.
970    pub message: String,
971    /// Optional request ID related to the failure.
972    pub request_id: Option<i64>,
973}
974
975impl AxWsError {
976    /// Creates a new error with the provided message.
977    #[must_use]
978    pub fn new(message: impl Into<String>) -> Self {
979        Self {
980            code: None,
981            message: message.into(),
982            request_id: None,
983        }
984    }
985
986    /// Creates a new error with code and message.
987    #[must_use]
988    pub fn with_code(code: impl Into<String>, message: impl Into<String>) -> Self {
989        Self {
990            code: Some(code.into()),
991            message: message.into(),
992            request_id: None,
993        }
994    }
995}
996
997impl From<AxWsOrderErrorResponse> for AxWsError {
998    fn from(resp: AxWsOrderErrorResponse) -> Self {
999        Self {
1000            code: resp.err.code.map(|code| code.to_string()),
1001            message: resp
1002                .err
1003                .msg
1004                .unwrap_or_else(|| "AX request failed without an error message".to_owned()),
1005            request_id: Some(resp.rid),
1006        }
1007    }
1008}
1009
1010impl From<AxWsErrorResponse> for AxWsError {
1011    fn from(resp: AxWsErrorResponse) -> Self {
1012        Self {
1013            code: resp.code,
1014            message: resp.message.unwrap_or_else(|| "Unknown error".to_string()),
1015            request_id: resp.rid,
1016        }
1017    }
1018}
1019
1020/// Identity and event context for a tracked order.
1021///
1022/// Retained through uncertain request outcomes until definitive terminal evidence.
1023#[derive(Debug, Clone)]
1024pub struct OrderMetadata {
1025    /// Trader ID for event generation.
1026    pub trader_id: TraderId,
1027    /// Strategy ID for event generation.
1028    pub strategy_id: StrategyId,
1029    /// Instrument ID for event generation.
1030    pub instrument_id: InstrumentId,
1031    /// Client order ID for correlation.
1032    pub client_order_id: ClientOrderId,
1033    /// Submitted Nautilus order, before AX-specific transformations.
1034    /// Absent for external orders registered without a cached Nautilus order.
1035    pub order_init: Option<OrderInitialized>,
1036    /// Whether acceptance is already known.
1037    pub is_accepted: bool,
1038    /// Current venue order ID, including a promoted replacement.
1039    pub venue_order_id: Option<VenueOrderId>,
1040    /// Original order timestamp.
1041    pub ts_init: UnixNanos,
1042    /// Instrument size precision for quantity conversion.
1043    pub size_precision: u8,
1044    /// Instrument price precision for price conversion.
1045    pub price_precision: u8,
1046    /// Quote currency for the instrument.
1047    pub quote_currency: Currency,
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use rstest::rstest;
1053    use rust_decimal_macros::dec;
1054
1055    use super::{
1056        super::parse::{parse_md_message, parse_order_message},
1057        *,
1058    };
1059
1060    #[rstest]
1061    fn test_md_subscribe_serialization() {
1062        let msg = AxMdSubscribe {
1063            rid: 2,
1064            msg_type: AxMdRequestType::Subscribe,
1065            symbol: Ustr::from("EURUSD-PERP"),
1066            level: AxMarketDataLevel::Level2,
1067            trades: None,
1068            ticker: None,
1069        };
1070        let json = serde_json::to_string(&msg).unwrap();
1071        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1072
1073        assert_eq!(parsed["rid"], 2);
1074        assert_eq!(parsed["type"], "subscribe");
1075        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1076        assert_eq!(parsed["level"], "LEVEL_2");
1077        assert!(parsed.get("trades").is_none());
1078        assert!(parsed.get("ticker").is_none());
1079    }
1080
1081    #[rstest]
1082    fn test_md_subscribe_book_only_serialization() {
1083        let msg = AxMdSubscribe {
1084            rid: 2,
1085            msg_type: AxMdRequestType::Subscribe,
1086            symbol: Ustr::from("EURUSD-PERP"),
1087            level: AxMarketDataLevel::Level2,
1088            trades: Some(false),
1089            ticker: Some(false),
1090        };
1091        let json = serde_json::to_string(&msg).unwrap();
1092        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1093
1094        assert_eq!(parsed["rid"], 2);
1095        assert_eq!(parsed["type"], "subscribe");
1096        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1097        assert_eq!(parsed["level"], "LEVEL_2");
1098        assert_eq!(parsed["trades"], false);
1099        assert_eq!(parsed["ticker"], false);
1100    }
1101
1102    #[rstest]
1103    fn test_md_subscribe_trades_serialization() {
1104        let msg = AxMdSubscribe {
1105            rid: 2,
1106            msg_type: AxMdRequestType::Subscribe,
1107            symbol: Ustr::from("EURUSD-PERP"),
1108            level: AxMarketDataLevel::Trades,
1109            trades: None,
1110            ticker: None,
1111        };
1112        let json = serde_json::to_string(&msg).unwrap();
1113        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1114
1115        assert_eq!(parsed["rid"], 2);
1116        assert_eq!(parsed["type"], "subscribe");
1117        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1118        assert_eq!(parsed["level"], "TRADES");
1119        assert!(parsed.get("trades").is_none());
1120        assert!(parsed.get("ticker").is_none());
1121    }
1122
1123    #[rstest]
1124    fn test_md_unsubscribe_serialization() {
1125        let msg = AxMdUnsubscribe {
1126            rid: 3,
1127            msg_type: AxMdRequestType::Unsubscribe,
1128            symbol: Ustr::from("EURUSD-PERP"),
1129        };
1130        let json = serde_json::to_string(&msg).unwrap();
1131        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1132
1133        assert_eq!(parsed["rid"], 3);
1134        assert_eq!(parsed["type"], "unsubscribe");
1135        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1136    }
1137
1138    #[rstest]
1139    fn test_md_subscribe_candles_serialization() {
1140        let msg = AxMdSubscribeCandles {
1141            rid: 4,
1142            msg_type: AxMdRequestType::SubscribeCandles,
1143            symbol: Ustr::from("EURUSD-PERP"),
1144            width: AxCandleWidth::Minutes1,
1145        };
1146        let json = serde_json::to_string(&msg).unwrap();
1147        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1148
1149        assert_eq!(parsed["rid"], 4);
1150        assert_eq!(parsed["type"], "subscribe_candles");
1151        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1152        assert_eq!(parsed["width"], "1m");
1153    }
1154
1155    #[rstest]
1156    fn test_md_unsubscribe_candles_serialization() {
1157        let msg = AxMdUnsubscribeCandles {
1158            rid: 5,
1159            msg_type: AxMdRequestType::UnsubscribeCandles,
1160            symbol: Ustr::from("EURUSD-PERP"),
1161            width: AxCandleWidth::Minutes1,
1162        };
1163        let json = serde_json::to_string(&msg).unwrap();
1164        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1165
1166        assert_eq!(parsed["rid"], 5);
1167        assert_eq!(parsed["type"], "unsubscribe_candles");
1168        assert_eq!(parsed["symbol"], "EURUSD-PERP");
1169        assert_eq!(parsed["width"], "1m");
1170    }
1171
1172    #[rstest]
1173    fn test_ws_place_order_serialization() {
1174        let msg = AxWsPlaceOrder {
1175            rid: 1,
1176            t: AxOrderRequestType::PlaceOrder,
1177            s: Ustr::from("EURUSD-PERP"),
1178            d: AxOrderSide::Buy,
1179            q: 100,
1180            p: dec!(50000.50),
1181            tif: AxTimeInForce::Gtc,
1182            po: false,
1183            st: None,
1184            tag: Some("Nautilus".to_string()),
1185            cid: Some(1234567890),
1186        };
1187
1188        let json = serde_json::to_string(&msg).unwrap();
1189        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1190
1191        assert_eq!(parsed["rid"], 1);
1192        assert_eq!(parsed["t"], "p");
1193        assert_eq!(parsed["s"], "EURUSD-PERP");
1194        assert_eq!(parsed["d"], "B");
1195        assert_eq!(parsed["q"], 100);
1196        assert_eq!(parsed["p"], "50000.50");
1197        assert_eq!(parsed["tif"], "GTC");
1198        assert_eq!(parsed["po"], false);
1199        assert_eq!(parsed["tag"], "Nautilus");
1200        assert_eq!(parsed["cid"], 1234567890);
1201        assert!(parsed.get("order_type").is_none());
1202        assert!(parsed.get("trigger_price").is_none());
1203        assert!(parsed.get("st").is_none());
1204    }
1205
1206    #[rstest]
1207    fn test_ws_place_order_serialization_includes_self_trade_behavior() {
1208        let msg = AxWsPlaceOrder {
1209            rid: 2,
1210            t: AxOrderRequestType::PlaceOrder,
1211            s: Ustr::from("EURUSD-PERP"),
1212            d: AxOrderSide::Sell,
1213            q: 1,
1214            p: dec!(1.12),
1215            tif: AxTimeInForce::Gtc,
1216            po: true,
1217            st: Some(AxSelfTradeBehavior::CancelResting),
1218            tag: Some("arb01".to_string()),
1219            cid: None,
1220        };
1221
1222        let json = serde_json::to_string(&msg).unwrap();
1223        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1224
1225        assert_eq!(parsed["st"], "CancelResting");
1226        assert_eq!(parsed["tag"], "arb01");
1227        assert!(parsed.get("cid").is_none());
1228    }
1229
1230    #[rstest]
1231    fn test_ws_cancel_order_serialization() {
1232        let msg = AxWsCancelOrder {
1233            rid: 2,
1234            t: AxOrderRequestType::CancelOrder,
1235            oid: "O-01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string(),
1236        };
1237        let json = serde_json::to_string(&msg).unwrap();
1238        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1239
1240        assert_eq!(parsed["rid"], 2);
1241        assert_eq!(parsed["t"], "x");
1242        assert_eq!(parsed["oid"], "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
1243    }
1244
1245    #[rstest]
1246    fn test_ws_get_open_orders_serialization() {
1247        let msg = AxWsGetOpenOrders {
1248            rid: 3,
1249            t: AxOrderRequestType::GetOpenOrders,
1250        };
1251        let json = serde_json::to_string(&msg).unwrap();
1252        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
1253
1254        assert_eq!(parsed["rid"], 3);
1255        assert_eq!(parsed["t"], "o");
1256    }
1257
1258    #[rstest]
1259    fn test_load_md_heartbeat_from_file() {
1260        let json = include_str!("../../test_data/ws_md_heartbeat.json");
1261        let msg = parse_md_message(json).unwrap();
1262        assert!(matches!(msg, AxMdMessage::Heartbeat(_)));
1263    }
1264
1265    #[rstest]
1266    fn test_load_md_ticker_from_file() {
1267        let json = include_str!("../../test_data/ws_md_ticker.json");
1268        let msg: AxMdTicker = serde_json::from_str(json).unwrap();
1269        assert_eq!(msg.s, "EURUSD-PERP");
1270        assert_eq!(msg.m, Some(dec!(50010.50)));
1271        assert_eq!(msg.i, Some(AxInstrumentState::Open));
1272    }
1273
1274    #[rstest]
1275    fn test_load_md_ticker_captured_optional_fields_default_to_none() {
1276        let json = include_str!("../../test_data/ws_md_ticker_captured.json");
1277        let msg: AxMdTicker = serde_json::from_str(json).unwrap();
1278        assert_eq!(msg.s, "EURUSD-PERP");
1279        assert_eq!(msg.m, None);
1280        assert_eq!(msg.i, None);
1281    }
1282
1283    #[rstest]
1284    fn test_load_md_ticker_null_prices_decode() {
1285        // Null p/o/l/h must still decode; mark price arrives via `m`
1286        let json = include_str!("../../test_data/ws_md_ticker_null_prices.json");
1287        let msg = parse_md_message(json).unwrap();
1288        let AxMdMessage::Ticker(ticker) = msg else {
1289            panic!("expected ticker message");
1290        };
1291        assert_eq!(ticker.s, "QQQ-PERP");
1292        assert_eq!(ticker.p, None);
1293        assert_eq!(ticker.o, None);
1294        assert_eq!(ticker.l, None);
1295        assert_eq!(ticker.h, None);
1296        assert_eq!(ticker.m, Some(dec!(716.38)));
1297        assert_eq!(ticker.i, Some(AxInstrumentState::Open));
1298    }
1299
1300    #[rstest]
1301    fn test_load_md_trade_from_file() {
1302        let json = include_str!("../../test_data/ws_md_trade.json");
1303        let msg: AxMdTrade = serde_json::from_str(json).unwrap();
1304        assert_eq!(msg.d, AxOrderSide::Buy);
1305    }
1306
1307    #[rstest]
1308    #[case(None, "missing field `d`")]
1309    #[case(Some(serde_json::Value::Null), "invalid type: null")]
1310    #[case(Some(serde_json::json!("X")), "unknown variant `X`")]
1311    #[case(Some(serde_json::json!("b")), "unknown variant `b`")]
1312    fn test_md_trade_rejects_missing_or_invalid_side(
1313        #[case] side: Option<serde_json::Value>,
1314        #[case] expected_error: &str,
1315    ) {
1316        let json = include_str!("../../test_data/ws_md_trade.json");
1317        let mut value: serde_json::Value = serde_json::from_str(json).unwrap();
1318        let fields = value.as_object_mut().unwrap();
1319        fields.remove("t");
1320        fields.remove("d");
1321        if let Some(side) = side {
1322            fields.insert("d".to_string(), side);
1323        }
1324
1325        let raw = serde_json::to_string(&value).unwrap();
1326        let fallback_raw = format!("{},\"t\":\"t\"}}", &raw[..raw.len() - 1]);
1327        let fast_raw = format!("{{\"t\":\"t\",{}", &raw[1..]);
1328
1329        serde_json::from_str::<serde_json::Value>(&fast_raw).unwrap();
1330
1331        let model_error = serde_json::from_value::<AxMdTrade>(value).unwrap_err();
1332        let message_error = parse_md_message(&fallback_raw).unwrap_err();
1333        parse_md_message(&fast_raw).unwrap_err();
1334
1335        assert!(
1336            model_error.to_string().contains(expected_error),
1337            "{model_error}"
1338        );
1339        assert!(
1340            message_error.to_string().contains(expected_error),
1341            "{message_error}"
1342        );
1343    }
1344
1345    #[rstest]
1346    fn test_load_md_candle_from_file() {
1347        let json = include_str!("../../test_data/ws_md_candle.json");
1348        let msg: AxMdCandle = serde_json::from_str(json).unwrap();
1349        assert_eq!(msg.width, AxCandleWidth::Minutes1);
1350    }
1351
1352    #[rstest]
1353    fn test_load_md_book_l1_from_file() {
1354        let json = include_str!("../../test_data/ws_md_book_l1.json");
1355        let msg: AxMdBookL1 = serde_json::from_str(json).unwrap();
1356        assert_eq!(msg.b.len(), 1);
1357        assert_eq!(msg.a.len(), 1);
1358    }
1359
1360    #[rstest]
1361    fn test_load_md_book_l2_from_file() {
1362        let json = include_str!("../../test_data/ws_md_book_l2.json");
1363        let msg: AxMdBookL2 = serde_json::from_str(json).unwrap();
1364        assert_eq!(msg.b.len(), 3);
1365        assert_eq!(msg.a.len(), 3);
1366    }
1367
1368    #[rstest]
1369    fn test_load_md_book_l3_from_file() {
1370        let json = include_str!("../../test_data/ws_md_book_l3.json");
1371        let msg: AxMdBookL3 = serde_json::from_str(json).unwrap();
1372        assert_eq!(msg.b.len(), 2);
1373        assert!(!msg.b[0].o.is_empty());
1374    }
1375
1376    #[rstest]
1377    fn test_load_order_place_response_from_file() {
1378        let json = include_str!("../../test_data/ws_order_place_response.json");
1379        let msg: AxWsPlaceOrderResponse = serde_json::from_str(json).unwrap();
1380        assert_eq!(msg.res.oid, "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
1381    }
1382
1383    #[rstest]
1384    fn test_load_order_cancel_response_from_file() {
1385        let json = include_str!("../../test_data/ws_order_cancel_response.json");
1386        let msg: AxWsCancelOrderResponse = serde_json::from_str(json).unwrap();
1387        assert!(msg.res.cxl_rx);
1388    }
1389
1390    #[rstest]
1391    fn test_load_order_open_orders_response_from_file() {
1392        let json = include_str!("../../test_data/ws_order_open_orders_response.json");
1393        let msg: AxWsOpenOrdersResponse = serde_json::from_str(json).unwrap();
1394        assert_eq!(msg.res.orders.len(), 1);
1395    }
1396
1397    #[rstest]
1398    fn test_load_order_heartbeat_from_file() {
1399        let json = include_str!("../../test_data/ws_order_heartbeat.json");
1400        let msg: AxWsHeartbeat = serde_json::from_str(json).unwrap();
1401        assert_eq!(msg.ts, 1609459200);
1402    }
1403
1404    #[rstest]
1405    fn test_load_order_acknowledged_from_file() {
1406        let json = include_str!("../../test_data/ws_order_acknowledged.json");
1407        let msg: AxWsOrderAcknowledged = serde_json::from_str(json).unwrap();
1408        assert_eq!(msg.o.oid, "O-01ARZ3NDEKTSV4RRFFQ69G5FAV");
1409    }
1410
1411    #[rstest]
1412    fn test_load_order_filled_from_file() {
1413        let json = include_str!("../../test_data/ws_order_filled.json");
1414        let msg: AxWsOrderFilled = serde_json::from_str(json).unwrap();
1415        assert_eq!(msg.o.o, AxOrderStatus::Filled);
1416        assert_eq!(msg.xs.d, AxOrderSide::Buy);
1417    }
1418
1419    #[rstest]
1420    fn test_load_order_partially_filled_from_file() {
1421        let json = include_str!("../../test_data/ws_order_partially_filled.json");
1422        let msg: AxWsOrderPartiallyFilled = serde_json::from_str(json).unwrap();
1423        assert_eq!(msg.xs.q, 50);
1424        assert_eq!(msg.xs.d, AxOrderSide::Buy);
1425    }
1426
1427    #[rstest]
1428    fn test_load_order_canceled_from_file() {
1429        let json = include_str!("../../test_data/ws_order_canceled.json");
1430        let msg: AxWsOrderCanceled = serde_json::from_str(json).unwrap();
1431        assert_eq!(msg.xr, AxCancelReason::UserRequested);
1432    }
1433
1434    #[rstest]
1435    fn test_load_order_rejected_from_file() {
1436        let json = include_str!("../../test_data/ws_order_rejected.json");
1437        let msg: AxWsOrderRejected = serde_json::from_str(json).unwrap();
1438        assert_eq!(msg.r, Some(AxOrderRejectReason::InsufficientMargin));
1439    }
1440
1441    #[rstest]
1442    fn test_load_order_expired_from_file() {
1443        let json = include_str!("../../test_data/ws_order_expired.json");
1444        let msg: AxWsOrderExpired = serde_json::from_str(json).unwrap();
1445        assert_eq!(msg.o.tif, AxTimeInForce::Ioc);
1446    }
1447
1448    #[rstest]
1449    fn test_load_order_replaced_live_shape_from_file() {
1450        let json = include_str!("../../test_data/ws_order_replaced_live.json");
1451        let msg: AxWsOrderReplaced = serde_json::from_str(json).unwrap();
1452
1453        assert_eq!(msg.noid.as_deref(), Some("O-01KWY01WX8JT4DABKC6FRS5NT4"));
1454        assert_eq!(msg.no.as_ref().unwrap().oid, "O-01KWY01WX8JT4DABKC6FRS5NT4");
1455        assert_eq!(msg.no.as_ref().unwrap().p, dec!(1.0926));
1456        assert_eq!(msg.ro.o, AxOrderStatus::Replaced);
1457    }
1458
1459    #[rstest]
1460    fn test_load_order_done_for_day_from_file() {
1461        let json = include_str!("../../test_data/ws_order_done_for_day.json");
1462        let msg: AxWsOrderDoneForDay = serde_json::from_str(json).unwrap();
1463        assert_eq!(msg.o.xq, 50);
1464    }
1465
1466    #[rstest]
1467    fn test_load_cancel_rejected_from_file() {
1468        let json = include_str!("../../test_data/ws_cancel_rejected.json");
1469        let msg: AxWsCancelRejected = serde_json::from_str(json).unwrap();
1470        assert_eq!(msg.r, AxCancelRejectionReason::OrderNotFound);
1471    }
1472
1473    #[rstest]
1474    fn test_load_order_error_response_from_file() {
1475        let json = include_str!("../../test_data/ws_order_error_response.json");
1476        let msg: AxWsOrderErrorResponse = serde_json::from_str(json).unwrap();
1477        assert_eq!(msg.rid, 1);
1478        assert_eq!(msg.err.code, Some(400));
1479        assert!(msg.err.msg.as_deref().unwrap().contains("initial margin"));
1480    }
1481
1482    #[rstest]
1483    fn test_load_order_list_response_from_file() {
1484        let json = include_str!("../../test_data/ws_order_list_response.json");
1485        let msg: AxWsListResponse = serde_json::from_str(json).unwrap();
1486        assert_eq!(msg.rid, 0);
1487        assert_eq!(msg.res.li, "01KCQM-4WP1-0000");
1488        assert!(msg.res.o.is_none());
1489    }
1490
1491    #[rstest]
1492    fn test_load_order_list_response_with_orders_from_file() {
1493        let json = include_str!("../../test_data/ws_order_list_response_with_orders.json");
1494        let msg: AxWsListResponse = serde_json::from_str(json).unwrap();
1495        assert_eq!(msg.rid, 0);
1496        assert_eq!(msg.res.li, "01KCQM-4WP1-0000");
1497        let orders = msg.res.o.unwrap();
1498        assert_eq!(orders.len(), 2);
1499        assert_eq!(orders[0].oid, "O-01KF4QM3VVJEDH98ZVNS1PCSBB");
1500        assert_eq!(orders[1].oid, "O-01KF4QM3K9FJZWYA02JF9Y1FJA");
1501    }
1502
1503    #[derive(Debug, Eq, PartialEq)]
1504    enum FrameKind {
1505        Error,
1506        ListResponse,
1507        AcknowledgedEvent,
1508        PlaceResponse,
1509        CancelResponse,
1510        OpenOrdersResponse,
1511    }
1512
1513    fn classify(frame: &AxOrdersWsFrame) -> FrameKind {
1514        match frame {
1515            AxOrdersWsFrame::Error(_) => FrameKind::Error,
1516            AxOrdersWsFrame::Response(AxWsOrderResponse::List(_)) => FrameKind::ListResponse,
1517            AxOrdersWsFrame::Response(AxWsOrderResponse::PlaceOrder(_)) => FrameKind::PlaceResponse,
1518            AxOrdersWsFrame::Response(AxWsOrderResponse::CancelOrder(_)) => {
1519                FrameKind::CancelResponse
1520            }
1521            AxOrdersWsFrame::Response(AxWsOrderResponse::OpenOrders(_)) => {
1522                FrameKind::OpenOrdersResponse
1523            }
1524            AxOrdersWsFrame::Event(e) => match **e {
1525                AxWsOrderEvent::Acknowledged(_) => FrameKind::AcknowledgedEvent,
1526                _ => panic!("unexpected event variant"),
1527            },
1528        }
1529    }
1530
1531    #[rstest]
1532    #[case::error(
1533        include_str!("../../test_data/ws_order_error_response.json"),
1534        FrameKind::Error,
1535    )]
1536    #[case::list(
1537        include_str!("../../test_data/ws_order_list_response.json"),
1538        FrameKind::ListResponse,
1539    )]
1540    #[case::acknowledged_event(
1541        include_str!("../../test_data/ws_order_acknowledged.json"),
1542        FrameKind::AcknowledgedEvent,
1543    )]
1544    #[case::place_response(
1545        include_str!("../../test_data/ws_order_place_response.json"),
1546        FrameKind::PlaceResponse,
1547    )]
1548    #[case::cancel_response(
1549        include_str!("../../test_data/ws_order_cancel_response.json"),
1550        FrameKind::CancelResponse,
1551    )]
1552    #[case::open_orders(
1553        include_str!("../../test_data/ws_order_open_orders_response.json"),
1554        FrameKind::OpenOrdersResponse,
1555    )]
1556    fn test_parse_order_message_variants(#[case] json: &str, #[case] expected: FrameKind) {
1557        let msg = parse_order_message(json).expect("should parse");
1558        assert_eq!(classify(&msg), expected);
1559    }
1560    #[rstest]
1561    fn test_ticker_missing_prices_remain_absent() {
1562        let mut value: serde_json::Value = serde_json::from_str(include_str!(
1563            "../../test_data/ws_md_ticker_null_prices.json"
1564        ))
1565        .unwrap();
1566
1567        for field in ["p", "o", "l", "h"] {
1568            value.as_object_mut().unwrap().remove(field);
1569        }
1570
1571        let ticker: AxMdTicker = serde_json::from_value(value).unwrap();
1572        assert_eq!(
1573            (ticker.p, ticker.o, ticker.l, ticker.h),
1574            (None, None, None, None)
1575        );
1576        assert_eq!(ticker.m, Some(dec!(716.38)));
1577    }
1578
1579    #[rstest]
1580    #[case(include_str!("../../test_data/captured/open-reject.json"))]
1581    #[case(include_str!("../../test_data/captured/open-backoff.json"))]
1582    #[case(include_str!("../../test_data/captured/open-top.json"))]
1583    #[case(include_str!("../../test_data/captured/open-inactive.json"))]
1584    fn test_ws_order_preserves_captured_metadata(#[case] raw: &str) {
1585        let response: serde_json::Value = serde_json::from_str(raw).unwrap();
1586        for value in response["orders"].as_array().unwrap() {
1587            let order: AxWsOrder = serde_json::from_value(value.clone()).unwrap();
1588            let actual = serde_json::to_value(order).unwrap();
1589
1590            for field in ["aid", "po", "rb", "ts", "tn", "oid", "q", "xq", "rq"] {
1591                assert_eq!(actual[field], value[field], "{field}");
1592            }
1593        }
1594    }
1595}