Skip to main content

nautilus_okx/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//! Data structures modeling OKX WebSocket request and response payloads.
17
18use derive_builder::Builder;
19use nautilus_core::string::secret::SecretString;
20use nautilus_model::{
21    data::{Data, FundingRateUpdate, InstrumentStatus, OrderBookDeltas},
22    events::{
23        AccountState, OrderAccepted, OrderCancelRejected, OrderCanceled, OrderExpired,
24        OrderModifyRejected, OrderRejected, OrderTriggered, OrderUpdated,
25    },
26    identifiers::ClientOrderId,
27    instruments::InstrumentAny,
28    reports::{FillReport, OrderStatusReport, PositionStatusReport},
29};
30use serde::{
31    Deserialize, Serialize,
32    de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor},
33};
34use serde_json::value::RawValue;
35use ustr::Ustr;
36use zeroize::Zeroize;
37
38use super::enums::{OKXWsChannel, OKXWsOperation};
39use crate::{
40    common::{
41        enums::{
42            OKXAlgoOrderStatus, OKXAlgoOrderType, OKXBookAction, OKXCandleConfirm, OKXExecType,
43            OKXInstrumentType, OKXMarginMode, OKXOrderCategory, OKXOrderStatus, OKXOrderType,
44            OKXPositionSide, OKXPriceType, OKXQuickMarginType, OKXSelfTradePreventionMode,
45            OKXSettlementState, OKXSide, OKXTargetCurrency, OKXTradeMode, OKXTriggerType,
46        },
47        models::{OKXInstrument, OKXRpiBookLevel},
48        parse::{
49            deserialize_empty_string_as_none, deserialize_empty_ustr_as_none,
50            deserialize_string_to_u64, deserialize_target_currency_as_none,
51        },
52    },
53    http::models::OKXSpreadOrder,
54    websocket::enums::OKXSubscriptionEvent,
55};
56
57#[derive(Debug, Clone)]
58pub enum NautilusWsMessage {
59    Data(Vec<Data>),
60    Deltas(OrderBookDeltas),
61    FundingRates(Vec<FundingRateUpdate>),
62    Instrument(Box<InstrumentAny>, Option<InstrumentStatus>),
63    InstrumentStatus(InstrumentStatus),
64    AccountUpdate(AccountState),
65    PositionUpdate(PositionStatusReport),
66    OrderAccepted(OrderAccepted),
67    OrderCanceled(OrderCanceled),
68    OrderExpired(OrderExpired),
69    OrderRejected(OrderRejected),
70    OrderCancelRejected(OrderCancelRejected),
71    OrderModifyRejected(OrderModifyRejected),
72    OrderTriggered(OrderTriggered),
73    OrderUpdated(OrderUpdated),
74    ExecutionReports(Vec<ExecutionReport>),
75    Error(OKXWebSocketError),
76    Raw(serde_json::Value), // Unhandled channels
77    Reconnected,
78    Authenticated,
79}
80
81/// Represents an OKX WebSocket error.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct OKXWebSocketError {
84    /// Error code from OKX (e.g., "50101").
85    pub code: String,
86    /// Error message from OKX.
87    pub message: String,
88    /// Connection ID if available.
89    pub conn_id: Option<String>,
90    /// Timestamp when the error occurred.
91    pub timestamp: u64,
92}
93
94#[derive(Debug, Clone)]
95#[allow(
96    clippy::large_enum_variant,
97    reason = "the variant size gap only crosses the threshold when high-precision widens the raw types"
98)]
99pub enum ExecutionReport {
100    Order(OrderStatusReport),
101    Fill(FillReport),
102}
103
104/// Output from the OKX WebSocket handler.
105///
106/// Contains venue-specific types only. Data parsing occurs in `PyOKXWebSocketClient`
107/// (using an instruments cache), and execution parsing occurs in `execution.rs`
108/// (using the system Cache for order lookups).
109#[derive(Debug)]
110pub enum OKXWsMessage {
111    /// Order book snapshot or update.
112    BookData {
113        arg: OKXWebSocketArg,
114        action: OKXBookAction,
115        data: Vec<OKXBookMsg>,
116    },
117    /// Retail Price Improvement order book snapshot or update.
118    RpiBookData {
119        arg: OKXWebSocketArg,
120        action: OKXBookAction,
121        data: Vec<OKXRpiBookMsg>,
122    },
123    /// Data from a non-book channel (trades, tickers, mark price, funding, candles, etc.).
124    ChannelData {
125        channel: OKXWsChannel,
126        inst_id: Option<Ustr>,
127        data: serde_json::Value,
128    },
129    /// Response to a WebSocket order command (place, cancel, amend, mass-cancel).
130    OrderResponse {
131        id: Option<String>,
132        op: OKXWsOperation,
133        code: String,
134        msg: String,
135        data: Vec<serde_json::Value>,
136        /// Client order IDs correlated with the sent request, if still retained.
137        client_order_ids: Vec<ClientOrderId>,
138    },
139    /// Order push channel updates.
140    Orders(Vec<OKXOrderMsg>),
141    /// Nitro spread order push channel updates.
142    SpreadOrders(Vec<OKXSpreadOrder>),
143    /// Algo order push channel updates.
144    AlgoOrders(Vec<OKXAlgoOrderMsg>),
145    /// Account channel update (raw JSON).
146    Account(serde_json::Value),
147    /// Positions channel update (raw JSON).
148    Positions(serde_json::Value),
149    /// Liquidation risk warnings for account positions.
150    LiquidationWarnings(Vec<OKXLiquidationWarningMsg>),
151    /// Instrument definition updates.
152    Instruments(Vec<OKXInstrument>),
153    /// A WebSocket send failed without a structured venue response.
154    SendFailed {
155        request_id: String,
156        client_order_ids: Vec<ClientOrderId>,
157        op: Option<OKXWsOperation>,
158        error: super::error::OKXWsError,
159    },
160    /// The venue rejected a subscribe request, so no data will flow for it.
161    SubscriptionFailed {
162        channel: OKXWsChannel,
163        inst_id: Option<Ustr>,
164        code: String,
165        msg: String,
166    },
167    /// Error received from OKX.
168    Error(OKXWebSocketError),
169    /// WebSocket reconnected.
170    Reconnected,
171    /// WebSocket authenticated.
172    Authenticated,
173}
174
175/// Generic WebSocket request for OKX trading commands.
176#[derive(Debug, Serialize)]
177#[serde(rename_all = "camelCase")]
178pub struct OKXWsRequest<T> {
179    /// Client request ID (required for order operations).
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub id: Option<String>,
182    /// Operation type (order, cancel-order, amend-order).
183    pub op: OKXWsOperation,
184    /// Request effective deadline. Unix timestamp format in milliseconds.
185    /// This is when the request itself expires, not related to order expiration.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub exp_time: Option<String>,
188    /// Arguments payload for the operation.
189    pub args: Vec<T>,
190}
191
192/// OKX WebSocket authentication message.
193#[derive(Debug, Serialize, Zeroize)]
194pub struct OKXAuthentication {
195    #[zeroize(skip)]
196    pub op: &'static str,
197    pub args: Vec<OKXAuthenticationArg>,
198}
199
200/// OKX WebSocket authentication arguments.
201#[derive(Debug, Serialize, Zeroize)]
202#[serde(rename_all = "camelCase")]
203pub struct OKXAuthenticationArg {
204    pub api_key: SecretString,
205    pub passphrase: SecretString,
206    pub timestamp: String,
207    pub sign: SecretString,
208}
209
210#[derive(Debug, Serialize)]
211pub struct OKXSubscription {
212    pub op: OKXWsOperation,
213    pub args: Vec<OKXSubscriptionArg>,
214}
215
216#[derive(Clone, Debug)]
217pub struct OKXSubscriptionArg {
218    pub channel: OKXWsChannel,
219    pub inst_type: Option<OKXInstrumentType>,
220    pub inst_family: Option<Ustr>,
221    pub inst_id: Option<Ustr>,
222}
223
224impl Serialize for OKXSubscriptionArg {
225    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
226        use serde::ser::SerializeMap;
227
228        let mut map = serializer.serialize_map(None)?;
229        map.serialize_entry("channel", &self.channel)?;
230
231        if self.channel == OKXWsChannel::Positions {
232            // Periodic snapshots would keep restarting the position reconciliation grace window
233            map.serialize_entry("extraParams", r#"{"updateInterval":"0"}"#)?;
234        }
235
236        if let Some(inst_type) = &self.inst_type {
237            map.serialize_entry("instType", inst_type)?;
238        }
239
240        if let Some(inst_family) = &self.inst_family {
241            map.serialize_entry("instFamily", inst_family)?;
242        }
243
244        if let Some(inst_id) = &self.inst_id {
245            let key = if self.channel.is_spread() {
246                "sprdId"
247            } else {
248                "instId"
249            };
250            map.serialize_entry(key, inst_id)?;
251        }
252
253        map.end()
254    }
255}
256
257/// OKX WebSocket message variants.
258///
259/// Uses custom deserialization that checks discriminant fields (event, op, action)
260/// to determine the correct variant.
261#[derive(Debug)]
262pub enum OKXWsFrame {
263    Login {
264        event: String,
265        code: String,
266        msg: String,
267        conn_id: String,
268    },
269    Subscription {
270        event: OKXSubscriptionEvent,
271        arg: OKXWebSocketArg,
272        conn_id: String,
273        code: Option<String>,
274        msg: Option<String>,
275    },
276    ChannelConnCount {
277        event: String,
278        channel: OKXWsChannel,
279        conn_count: String,
280        conn_id: String,
281    },
282    OrderResponse {
283        id: Option<String>,
284        op: OKXWsOperation,
285        code: String,
286        msg: String,
287        data: Vec<serde_json::Value>,
288    },
289    BookData {
290        arg: OKXWebSocketArg,
291        action: OKXBookAction,
292        data: Vec<OKXBookMsg>,
293    },
294    RpiBookData {
295        arg: OKXWebSocketArg,
296        action: OKXBookAction,
297        data: Vec<OKXRpiBookMsg>,
298    },
299    Data {
300        arg: OKXWebSocketArg,
301        data: serde_json::Value,
302    },
303    Error {
304        arg: Option<OKXWebSocketArg>,
305        code: String,
306        msg: String,
307    },
308    Ping,
309    Reconnected,
310}
311
312impl<'de> Deserialize<'de> for OKXWsFrame {
313    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
314    where
315        D: serde::Deserializer<'de>,
316    {
317        deserializer.deserialize_map(OKXWsFrameVisitor)
318    }
319}
320
321#[derive(Deserialize)]
322#[serde(field_identifier, rename_all = "camelCase")]
323enum OKXWsFrameKey {
324    Event,
325    Op,
326    Action,
327    Arg,
328    Data,
329    Code,
330    Msg,
331    ConnId,
332    Id,
333    Channel,
334    ConnCount,
335    #[serde(other)]
336    Other,
337}
338
339// Decodes a frame in one pass. Small fields are held as raw JSON text so the
340// variant is still chosen from field presence once every key is seen, while
341// `data` decodes straight into typed book levels when the keys before it fix
342// the type (OKX sends `arg` and `action` ahead of `data`). Buffering the whole
343// frame as a `serde_json::Value` tree dominated the inbound decode cost for L2
344// books, and holding `data` as raw text meant scanning it twice.
345#[derive(Default)]
346struct OKXWsFrameFields {
347    event: Option<Box<RawValue>>,
348    op: Option<Box<RawValue>>,
349    action: Option<Box<RawValue>>,
350    arg: Option<Box<RawValue>>,
351    arg_decoded: Option<OKXWebSocketArg>,
352    data: Option<OKXWsFrameData>,
353    code: Option<Box<RawValue>>,
354    msg: Option<Box<RawValue>>,
355    conn_id: Option<Box<RawValue>>,
356    id: Option<Box<RawValue>>,
357    channel: Option<Box<RawValue>>,
358    conn_count: Option<Box<RawValue>>,
359}
360
361enum OKXWsFrameData {
362    Value(serde_json::Value),
363    Book(Vec<OKXBookMsg>),
364    RpiBook(Vec<OKXRpiBookMsg>),
365}
366
367impl OKXWsFrameData {
368    fn into_value<E: serde::de::Error>(self) -> Result<serde_json::Value, E> {
369        match self {
370            Self::Value(value) => Ok(value),
371            Self::Book(_) | Self::RpiBook(_) => {
372                Err(E::custom("invalid data: book levels in a non-book frame"))
373            }
374        }
375    }
376}
377
378struct OKXWsFrameVisitor;
379
380impl<'de> Visitor<'de> for OKXWsFrameVisitor {
381    type Value = OKXWsFrame;
382
383    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
384        formatter.write_str("JSON object for OKXWsFrame")
385    }
386
387    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
388    where
389        A: MapAccess<'de>,
390    {
391        let mut fields = OKXWsFrameFields::default();
392
393        while let Some(key) = map.next_key::<OKXWsFrameKey>()? {
394            let slot = match key {
395                OKXWsFrameKey::Event => &mut fields.event,
396                OKXWsFrameKey::Op => &mut fields.op,
397                OKXWsFrameKey::Action => &mut fields.action,
398                OKXWsFrameKey::Arg => {
399                    fields.arg_decoded = None;
400                    &mut fields.arg
401                }
402                OKXWsFrameKey::Data => {
403                    fields.data = Some(fields.next_data(&mut map)?);
404                    continue;
405                }
406                OKXWsFrameKey::Code => &mut fields.code,
407                OKXWsFrameKey::Msg => &mut fields.msg,
408                OKXWsFrameKey::ConnId => &mut fields.conn_id,
409                OKXWsFrameKey::Id => &mut fields.id,
410                OKXWsFrameKey::Channel => &mut fields.channel,
411                OKXWsFrameKey::ConnCount => &mut fields.conn_count,
412                OKXWsFrameKey::Other => {
413                    map.next_value::<IgnoredAny>()?;
414                    continue;
415                }
416            };
417
418            *slot = Some(map.next_value()?);
419        }
420
421        fields.into_frame()
422    }
423}
424
425impl OKXWsFrameFields {
426    fn next_data<'de, A: MapAccess<'de>>(
427        &mut self,
428        map: &mut A,
429    ) -> Result<OKXWsFrameData, A::Error> {
430        let invalid_data = |e: A::Error| A::Error::custom(format!("invalid data: {e}"));
431
432        if self.event.is_none()
433            && self.op.is_none()
434            && self.action.is_some()
435            && let Some(raw) = self.arg.as_deref()
436        {
437            let arg: OKXWebSocketArg = parse_raw(raw, "arg")?;
438
439            let data = if arg.channel == OKXWsChannel::BooksRpi {
440                OKXWsFrameData::RpiBook(map.next_value().map_err(invalid_data)?)
441            } else {
442                OKXWsFrameData::Book(map.next_value().map_err(invalid_data)?)
443            };
444
445            self.arg_decoded = Some(arg);
446            return Ok(data);
447        }
448
449        Ok(OKXWsFrameData::Value(map.next_value()?))
450    }
451
452    fn take_arg<E: serde::de::Error>(&mut self) -> Result<OKXWebSocketArg, E> {
453        match self.arg_decoded.take() {
454            Some(arg) => Ok(arg),
455            None => take_typed(self.arg.take(), "arg"),
456        }
457    }
458
459    fn into_frame<E: serde::de::Error>(self) -> Result<OKXWsFrame, E> {
460        // Check discriminant fields in priority order
461
462        // 1. "event" field - Login, Subscription, ChannelConnCount, or Error
463        if let Some(event) = self.event.as_deref().and_then(raw_as_string) {
464            match event.as_str() {
465                "login" => return parse_login(self),
466                "subscribe" | "unsubscribe" => return parse_subscription(self),
467                "error" => return parse_error(self),
468                _ if self.channel.is_some() && self.conn_count.is_some() => {
469                    return parse_channel_conn_count(self);
470                }
471                _ => {}
472            }
473        }
474
475        // 2. "op" field - OrderResponse
476        if self.op.is_some() {
477            return parse_order_response(self);
478        }
479
480        // 3. "action" + "arg" - BookData
481        if self.action.is_some() && self.arg.is_some() {
482            return parse_book_data(self);
483        }
484
485        // 4. "arg" + "data" without "action" - Data
486        if self.arg.is_some() && self.data.is_some() {
487            return parse_data(self);
488        }
489
490        // 5. Fallback to Error if it has "code" and "msg"
491        if self.code.is_some() && self.msg.is_some() {
492            return parse_error(self);
493        }
494
495        Err(E::custom("cannot determine OKXWsFrame variant"))
496    }
497}
498
499fn raw_as_string(raw: &RawValue) -> Option<String> {
500    serde_json::from_str(raw.get()).ok()
501}
502
503fn parse_raw<T: DeserializeOwned, E: serde::de::Error>(
504    raw: &RawValue,
505    key: &'static str,
506) -> Result<T, E> {
507    serde_json::from_str(raw.get()).map_err(|e| E::custom(format!("invalid {key}: {e}")))
508}
509
510fn take_typed<T: DeserializeOwned, E: serde::de::Error>(
511    raw: Option<Box<RawValue>>,
512    key: &'static str,
513) -> Result<T, E> {
514    let raw = raw.ok_or_else(|| E::missing_field(key))?;
515    parse_raw(&raw, key)
516}
517
518fn take_data_typed<T: DeserializeOwned, E: serde::de::Error>(data: OKXWsFrameData) -> Result<T, E> {
519    serde_json::from_value(data.into_value()?).map_err(|e| E::custom(format!("invalid data: {e}")))
520}
521
522fn take_str<E: serde::de::Error>(
523    raw: Option<Box<RawValue>>,
524    key: &'static str,
525) -> Result<String, E> {
526    let raw = raw.ok_or_else(|| E::missing_field(key))?;
527    raw_as_string(&raw).ok_or_else(|| E::custom(format!("field `{key}` is not a string")))
528}
529
530fn take_optional_str(raw: Option<Box<RawValue>>) -> Option<String> {
531    raw.and_then(|raw| raw_as_string(&raw))
532}
533
534fn parse_login<E: serde::de::Error>(fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
535    Ok(OKXWsFrame::Login {
536        event: take_str(fields.event, "event")?,
537        code: take_str(fields.code, "code")?,
538        msg: take_str(fields.msg, "msg")?,
539        conn_id: take_str(fields.conn_id, "connId")?,
540    })
541}
542
543fn parse_subscription<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
544    let event: OKXSubscriptionEvent = take_typed(fields.event.take(), "event")?;
545    let arg = fields.take_arg()?;
546
547    Ok(OKXWsFrame::Subscription {
548        event,
549        arg,
550        conn_id: take_str(fields.conn_id, "connId")?,
551        code: take_optional_str(fields.code),
552        msg: take_optional_str(fields.msg),
553    })
554}
555
556fn parse_channel_conn_count<E: serde::de::Error>(
557    fields: OKXWsFrameFields,
558) -> Result<OKXWsFrame, E> {
559    let channel: OKXWsChannel = take_typed(fields.channel, "channel")?;
560
561    Ok(OKXWsFrame::ChannelConnCount {
562        event: take_str(fields.event, "event")?,
563        channel,
564        conn_count: take_str(fields.conn_count, "connCount")?,
565        conn_id: take_str(fields.conn_id, "connId")?,
566    })
567}
568
569fn parse_order_response<E: serde::de::Error>(fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
570    let op: OKXWsOperation = take_typed(fields.op, "op")?;
571
572    let data: Vec<serde_json::Value> = match fields.data {
573        Some(OKXWsFrameData::Value(serde_json::Value::Array(values))) => values,
574        Some(data) => take_data_typed(data)?,
575        None => Vec::new(),
576    };
577
578    Ok(OKXWsFrame::OrderResponse {
579        id: take_optional_str(fields.id),
580        op,
581        code: take_str(fields.code, "code")?,
582        msg: take_str(fields.msg, "msg")?,
583        data,
584    })
585}
586
587fn parse_book_data<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
588    let arg = fields.take_arg()?;
589    let action: OKXBookAction = take_typed(fields.action, "action")?;
590    let data = fields.data.ok_or_else(|| E::missing_field("data"))?;
591
592    if arg.channel == OKXWsChannel::BooksRpi {
593        let data: Vec<OKXRpiBookMsg> = match data {
594            OKXWsFrameData::RpiBook(data) => data,
595            data => take_data_typed(data)?,
596        };
597
598        return Ok(OKXWsFrame::RpiBookData { arg, action, data });
599    }
600
601    let data: Vec<OKXBookMsg> = match data {
602        OKXWsFrameData::Book(data) => data,
603        data => take_data_typed(data)?,
604    };
605
606    Ok(OKXWsFrame::BookData { arg, action, data })
607}
608
609fn parse_data<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
610    let arg = fields.take_arg()?;
611    let data = fields
612        .data
613        .ok_or_else(|| E::missing_field("data"))?
614        .into_value()?;
615
616    Ok(OKXWsFrame::Data { arg, data })
617}
618
619fn parse_error<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
620    let arg = if fields.arg.is_some() {
621        Some(fields.take_arg()?)
622    } else {
623        None
624    };
625
626    Ok(OKXWsFrame::Error {
627        arg,
628        code: take_str(fields.code, "code")?,
629        msg: take_str(fields.msg, "msg")?,
630    })
631}
632
633#[derive(Debug, Serialize, Deserialize)]
634#[serde(rename_all = "camelCase")]
635pub struct OKXWebSocketArg {
636    /// Channel name that pushed the data.
637    pub channel: OKXWsChannel,
638    // Spread channels identify the instrument by `sprdId`; a spread's symbol equals
639    // its `sprdId`, and a message carries `instId` xor `sprdId`, so the alias resolves
640    // both to one field without collision.
641    #[serde(default, alias = "sprdId")]
642    pub inst_id: Option<Ustr>,
643    #[serde(default)]
644    pub inst_type: Option<OKXInstrumentType>,
645    #[serde(default)]
646    pub inst_family: Option<Ustr>,
647    #[serde(default)]
648    pub bar: Option<Ustr>,
649}
650
651/// Ticker data for an instrument.
652#[derive(Debug, Serialize, Deserialize)]
653#[serde(rename_all = "camelCase")]
654pub struct OKXTickerMsg {
655    /// Instrument type, e.g. "SPOT", "SWAP".
656    pub inst_type: OKXInstrumentType,
657    /// Instrument ID, e.g. "BTC-USDT".
658    pub inst_id: Ustr,
659    /// Last traded price.
660    #[serde(rename = "last")]
661    pub last_px: String,
662    /// Last traded size.
663    pub last_sz: String,
664    /// Best ask price.
665    pub ask_px: String,
666    /// Best ask size.
667    pub ask_sz: String,
668    /// Best bid price.
669    pub bid_px: String,
670    /// Best bid size.
671    pub bid_sz: String,
672    /// 24-hour opening price.
673    pub open24h: String,
674    /// 24-hour highest price.
675    pub high24h: String,
676    /// 24-hour lowest price.
677    pub low24h: String,
678    /// 24-hour trading volume in quote currency.
679    pub vol_ccy_24h: String,
680    /// 24-hour trading volume.
681    pub vol24h: String,
682    /// The opening price of the day (UTC 0).
683    pub sod_utc0: String,
684    /// The opening price of the day (UTC 8).
685    pub sod_utc8: String,
686    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
687    #[serde(deserialize_with = "deserialize_string_to_u64")]
688    pub ts: u64,
689    /// Order source for RPI liquidity identification.
690    #[serde(default)]
691    pub source: Option<String>,
692}
693
694/// Represents a single order in the order book.
695#[derive(Debug, Serialize, Deserialize)]
696pub struct OrderBookEntry {
697    /// Price of the order.
698    pub price: String,
699    /// Size of the order.
700    pub size: String,
701    // Spread book levels (`sprd-books5`) are 3-element `[price, size, count]`,
702    // omitting the liquidated-orders field standard books carry; default the
703    // trailing counts so both array shapes deserialize, spread order counts
704    // occupy `liquidated_orders_count`.
705    /// Number of liquidated orders.
706    #[serde(default)]
707    pub liquidated_orders_count: String,
708    /// Total number of orders at this price.
709    #[serde(default)]
710    pub orders_count: String,
711}
712
713/// Order book data for an instrument.
714#[derive(Debug, Serialize, Deserialize)]
715#[serde(rename_all = "camelCase")]
716pub struct OKXBookMsg {
717    /// Order book asks [price, size, liquidated orders count, orders count].
718    pub asks: Vec<OrderBookEntry>,
719    /// Order book bids [price, size, liquidated orders count, orders count].
720    pub bids: Vec<OrderBookEntry>,
721    /// Checksum value.
722    pub checksum: Option<i64>,
723    /// Sequence ID of the last sent message. Only applicable to books, books-l2-tbt, books50-l2-tbt.
724    pub prev_seq_id: Option<i64>,
725    /// Sequence ID of the current message, implementation details below.
726    pub seq_id: u64,
727    /// Order book generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
728    #[serde(deserialize_with = "deserialize_string_to_u64")]
729    pub ts: u64,
730}
731
732/// Retail Price Improvement order book data for an instrument.
733#[derive(Debug, Serialize, Deserialize)]
734#[serde(rename_all = "camelCase", deny_unknown_fields)]
735pub struct OKXRpiBookMsg {
736    /// Ask levels [price, total quantity, non-RPI quantity, order count].
737    pub asks: Vec<OKXRpiBookLevel>,
738    /// Bid levels [price, total quantity, non-RPI quantity, order count].
739    pub bids: Vec<OKXRpiBookLevel>,
740    /// Sequence ID of the previous message.
741    pub prev_seq_id: i64,
742    /// Sequence ID of the current message.
743    pub seq_id: u64,
744    /// Order book generation time, Unix timestamp in milliseconds.
745    #[serde(deserialize_with = "deserialize_string_to_u64")]
746    pub ts: u64,
747}
748
749/// Trade data for an instrument.
750#[derive(Debug, Serialize, Deserialize)]
751#[serde(rename_all = "camelCase")]
752pub struct OKXTradeMsg {
753    // Spread public trades (`sprd-public-trades`) key the instrument as `sprdId`
754    // and omit `count`; the actual instrument is resolved from the channel arg, so
755    // both fields are tolerated here and unused by parsing.
756    /// Instrument ID (`instId`, or `sprdId` for spread public trades).
757    #[serde(default, alias = "sprdId")]
758    pub inst_id: Ustr,
759    /// Trade ID.
760    pub trade_id: String,
761    /// Trade price.
762    pub px: String,
763    /// Trade size.
764    pub sz: String,
765    /// Trade direction (buy or sell).
766    pub side: OKXSide,
767    /// Count (absent on spread public trades).
768    #[serde(default)]
769    pub count: String,
770    /// Trade timestamp, Unix timestamp format in milliseconds.
771    #[serde(deserialize_with = "deserialize_string_to_u64")]
772    pub ts: u64,
773    /// Order source (0: normal, 1: RPI).
774    #[serde(default)]
775    pub source: Option<String>,
776    /// Sequence ID for trade events.
777    #[serde(default)]
778    pub seq_id: Option<u64>,
779}
780
781/// Funding rate data for perpetual swaps.
782#[derive(Debug, Serialize, Deserialize)]
783#[serde(rename_all = "camelCase")]
784pub struct OKXFundingRateMsg {
785    /// Instrument type.
786    #[serde(default)]
787    pub inst_type: Option<OKXInstrumentType>,
788    /// Instrument ID.
789    pub inst_id: Ustr,
790    /// Current funding rate.
791    pub funding_rate: Ustr,
792    /// Predicted next funding rate.
793    pub next_funding_rate: Ustr,
794    /// Minimum funding rate.
795    #[serde(default)]
796    pub min_funding_rate: Option<String>,
797    /// Maximum funding rate.
798    #[serde(default)]
799    pub max_funding_rate: Option<String>,
800    /// Settlement state.
801    #[serde(default)]
802    pub sett_state: OKXSettlementState,
803    /// Settlement funding rate.
804    #[serde(default)]
805    pub sett_funding_rate: Option<String>,
806    /// Current premium.
807    #[serde(default)]
808    pub premium: Option<String>,
809    /// Funding rate calculation method.
810    #[serde(default)]
811    pub method: Option<String>,
812    /// Funding time, Unix timestamp format in milliseconds.
813    #[serde(deserialize_with = "deserialize_string_to_u64")]
814    pub funding_time: u64,
815    /// Next funding time, Unix timestamp format in milliseconds (used to determine funding interval).
816    #[serde(deserialize_with = "deserialize_string_to_u64")]
817    pub next_funding_time: u64,
818    /// Message timestamp, Unix timestamp format in milliseconds.
819    #[serde(deserialize_with = "deserialize_string_to_u64")]
820    pub ts: u64,
821}
822
823/// Mark price data for perpetual swaps.
824#[derive(Debug, Serialize, Deserialize)]
825#[serde(rename_all = "camelCase")]
826pub struct OKXMarkPriceMsg {
827    /// Instrument ID.
828    pub inst_id: Ustr,
829    /// Current mark price.
830    pub mark_px: String,
831    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
832    #[serde(deserialize_with = "deserialize_string_to_u64")]
833    pub ts: u64,
834}
835
836/// Index price data.
837#[derive(Debug, Serialize, Deserialize)]
838#[serde(rename_all = "camelCase")]
839pub struct OKXIndexPriceMsg {
840    /// Index name, e.g. "BTC-USD".
841    pub inst_id: Ustr,
842    /// Latest index price.
843    pub idx_px: String,
844    /// 24-hour highest price.
845    pub high24h: String,
846    /// 24-hour lowest price.
847    pub low24h: String,
848    /// 24-hour opening price.
849    pub open24h: String,
850    /// The opening price of the day (UTC 0).
851    pub sod_utc0: String,
852    /// The opening price of the day (UTC 8).
853    pub sod_utc8: String,
854    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
855    #[serde(deserialize_with = "deserialize_string_to_u64")]
856    pub ts: u64,
857}
858
859/// Price limit data (upper and lower limits).
860#[derive(Debug, Serialize, Deserialize)]
861#[serde(rename_all = "camelCase")]
862pub struct OKXPriceLimitMsg {
863    /// Instrument ID.
864    pub inst_id: Ustr,
865    /// Buy limit price.
866    pub buy_lmt: String,
867    /// Sell limit price.
868    pub sell_lmt: String,
869    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
870    #[serde(deserialize_with = "deserialize_string_to_u64")]
871    pub ts: u64,
872}
873
874/// Candlestick data for an instrument.
875#[derive(Debug, Serialize, Deserialize)]
876#[serde(rename_all = "camelCase")]
877pub struct OKXCandleMsg {
878    /// Candlestick timestamp, Unix timestamp format in milliseconds.
879    #[serde(deserialize_with = "deserialize_string_to_u64")]
880    pub ts: u64,
881    /// Opening price.
882    pub o: String,
883    /// Highest price.
884    pub h: String,
885    /// Lowest price.
886    pub l: String,
887    /// Closing price.
888    pub c: String,
889    /// Trading volume in contracts.
890    pub vol: String,
891    /// Trading volume in quote currency.
892    pub vol_ccy: String,
893    pub vol_ccy_quote: String,
894    /// Whether this is a completed candle.
895    pub confirm: OKXCandleConfirm,
896}
897
898/// Open interest data.
899#[derive(Debug, Serialize, Deserialize)]
900#[serde(rename_all = "camelCase")]
901pub struct OKXOpenInterestMsg {
902    /// Instrument ID.
903    pub inst_id: Ustr,
904    /// Open interest in contracts.
905    pub oi: String,
906    /// Open interest in quote currency.
907    pub oi_ccy: String,
908    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
909    #[serde(deserialize_with = "deserialize_string_to_u64")]
910    pub ts: u64,
911}
912
913/// Option market data summary.
914#[derive(Debug, Serialize, Deserialize)]
915#[serde(rename_all = "camelCase")]
916pub struct OKXOptionSummaryMsg {
917    /// Instrument type.
918    #[serde(default)]
919    pub inst_type: Option<OKXInstrumentType>,
920    /// Instrument ID.
921    pub inst_id: Ustr,
922    /// Underlying.
923    pub uly: String,
924    /// Delta.
925    pub delta: String,
926    /// Gamma.
927    pub gamma: String,
928    /// Theta.
929    pub theta: String,
930    /// Vega.
931    pub vega: String,
932    /// Black-Scholes delta.
933    #[serde(alias = "deltaBS")]
934    pub delta_bs: String,
935    /// Black-Scholes gamma.
936    #[serde(alias = "gammaBS")]
937    pub gamma_bs: String,
938    /// Black-Scholes theta.
939    #[serde(alias = "thetaBS")]
940    pub theta_bs: String,
941    /// Black-Scholes vega.
942    #[serde(alias = "vegaBS")]
943    pub vega_bs: String,
944    /// Realized volatility.
945    pub real_vol: String,
946    /// Bid volatility.
947    pub bid_vol: String,
948    /// Ask volatility.
949    pub ask_vol: String,
950    /// Mark volatility.
951    pub mark_vol: String,
952    /// Leverage.
953    pub lever: String,
954    /// Forward price.
955    #[serde(default)]
956    pub fwd_px: Option<String>,
957    /// Mark price.
958    #[serde(default)]
959    pub mark_px: Option<String>,
960    /// Volatility level.
961    #[serde(default)]
962    pub vol_lv: Option<String>,
963    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
964    #[serde(deserialize_with = "deserialize_string_to_u64")]
965    pub ts: u64,
966}
967
968/// Estimated delivery/exercise price data.
969#[derive(Debug, Serialize, Deserialize)]
970#[serde(rename_all = "camelCase")]
971pub struct OKXEstimatedPriceMsg {
972    /// Instrument ID.
973    pub inst_id: Ustr,
974    /// Estimated settlement price.
975    pub settle_px: String,
976    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
977    #[serde(deserialize_with = "deserialize_string_to_u64")]
978    pub ts: u64,
979}
980
981/// Platform status updates.
982#[derive(Debug, Serialize, Deserialize)]
983#[serde(rename_all = "camelCase")]
984pub struct OKXStatusMsg {
985    /// System maintenance status.
986    pub title: Ustr,
987    /// Status type: planned or scheduled.
988    #[serde(rename = "type")]
989    pub status_type: Ustr,
990    /// System maintenance state: canceled, completed, pending, ongoing.
991    pub state: Ustr,
992    /// Expected completion timestamp.
993    pub end_time: Option<String>,
994    /// Planned start timestamp.
995    pub begin_time: Option<String>,
996    /// Service involved.
997    pub service_type: Option<Ustr>,
998    /// Reason for status change.
999    pub reason: Option<String>,
1000    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
1001    #[serde(deserialize_with = "deserialize_string_to_u64")]
1002    pub ts: u64,
1003}
1004
1005pub use crate::common::models::OKXAttachedAlgoOrd;
1006
1007/// Liquidation risk warning pushed by the `liquidation-warning` channel.
1008///
1009/// OKX sends this when an isolated position, or all positions under cross
1010/// margin, approach liquidation. It is a risk warning only: the position may
1011/// already be liquidated by the time the message arrives.
1012#[derive(Clone, Debug, Serialize, Deserialize)]
1013#[serde(rename_all = "camelCase")]
1014pub struct OKXLiquidationWarningMsg {
1015    /// Instrument type.
1016    pub inst_type: OKXInstrumentType,
1017    /// Instrument family.
1018    #[serde(default)]
1019    pub inst_family: Option<Ustr>,
1020    /// Instrument ID.
1021    pub inst_id: Ustr,
1022    /// Margin mode.
1023    pub mgn_mode: OKXMarginMode,
1024    /// Position ID.
1025    #[serde(default)]
1026    pub pos_id: Option<Ustr>,
1027    /// Position side.
1028    pub pos_side: OKXPositionSide,
1029    /// Position quantity.
1030    pub pos: String,
1031    /// Position currency (margin positions only).
1032    #[serde(default)]
1033    pub pos_ccy: Option<Ustr>,
1034    /// Leverage.
1035    pub lever: String,
1036    /// Mark price.
1037    pub mark_px: String,
1038    /// Maintenance margin ratio.
1039    pub mgn_ratio: String,
1040    /// Margin currency.
1041    pub ccy: Ustr,
1042    /// Creation time, Unix timestamp in milliseconds.
1043    #[serde(deserialize_with = "deserialize_string_to_u64")]
1044    pub c_time: u64,
1045    /// Last update time, Unix timestamp in milliseconds.
1046    #[serde(deserialize_with = "deserialize_string_to_u64")]
1047    pub u_time: u64,
1048    /// Push time, Unix timestamp in milliseconds.
1049    #[serde(default)]
1050    pub p_time: Option<String>,
1051}
1052
1053/// Linked algo order metadata from order push updates.
1054#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1055#[serde(rename_all = "camelCase")]
1056pub struct OKXLinkedAlgoOrd {
1057    /// Parent algo order ID.
1058    #[serde(default)]
1059    pub algo_id: String,
1060}
1061
1062/// Order update message from WebSocket orders channel.
1063#[derive(Clone, Debug, Serialize, Deserialize)]
1064#[serde(rename_all = "camelCase")]
1065pub struct OKXOrderMsg {
1066    /// Accumulated filled size.
1067    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1068    pub acc_fill_sz: Option<String>,
1069    /// Algo order ID.
1070    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1071    pub algo_id: Option<String>,
1072    /// Average price.
1073    pub avg_px: String,
1074    /// Creation time, Unix timestamp in milliseconds.
1075    #[serde(deserialize_with = "deserialize_string_to_u64")]
1076    pub c_time: u64,
1077    /// Cancel source.
1078    #[serde(default)]
1079    pub cancel_source: Option<String>,
1080    /// Cancel source reason.
1081    #[serde(default)]
1082    pub cancel_source_reason: Option<String>,
1083    /// Order category (normal, liquidation, ADL, etc.).
1084    pub category: OKXOrderCategory,
1085    /// Currency.
1086    pub ccy: Ustr,
1087    /// Client order ID.
1088    pub cl_ord_id: String,
1089    /// Parent algo client order ID if present.
1090    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1091    pub algo_cl_ord_id: Option<String>,
1092    /// Attached child client order ID if surfaced at the top level.
1093    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1094    pub attach_algo_cl_ord_id: Option<String>,
1095    /// Attached TP/SL child order metadata.
1096    #[serde(default)]
1097    pub attach_algo_ords: Vec<OKXAttachedAlgoOrd>,
1098    /// Event contract market outcome, if applicable.
1099    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1100    pub outcome: Option<String>,
1101    /// Fee (cumulative).
1102    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1103    pub fee: Option<String>,
1104    /// Fee currency.
1105    pub fee_ccy: Ustr,
1106    /// Fee for this fill.
1107    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1108    pub fill_fee: Option<String>,
1109    /// Fill fee currency.
1110    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1111    pub fill_fee_ccy: Option<Ustr>,
1112    /// Mark price at fill time.
1113    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1114    pub fill_mark_px: Option<String>,
1115    /// Mark volatility at fill time (options).
1116    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1117    pub fill_mark_vol: Option<String>,
1118    /// Implied volatility at fill time (options).
1119    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1120    pub fill_px_vol: Option<String>,
1121    /// Fill price in USD (options).
1122    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1123    pub fill_px_usd: Option<String>,
1124    /// Forward price at fill time (options).
1125    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1126    pub fill_fwd_px: Option<String>,
1127    /// Fill notional in USD.
1128    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1129    pub fill_notional_usd: Option<String>,
1130    /// PnL for this fill.
1131    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1132    pub fill_pnl: Option<String>,
1133    /// Fill price.
1134    pub fill_px: String,
1135    /// Fill size.
1136    pub fill_sz: String,
1137    /// Fill time, Unix timestamp in milliseconds.
1138    #[serde(deserialize_with = "deserialize_string_to_u64")]
1139    pub fill_time: u64,
1140    /// Instrument ID.
1141    pub inst_id: Ustr,
1142    /// Instrument type.
1143    pub inst_type: OKXInstrumentType,
1144    /// Whether the TP order is a limit order.
1145    #[serde(default)]
1146    pub is_tp_limit: Option<String>,
1147    /// Leverage.
1148    pub lever: String,
1149    /// Linked algo order metadata.
1150    #[serde(default)]
1151    pub linked_algo_ord: Option<OKXLinkedAlgoOrd>,
1152    /// Notional value in USD.
1153    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1154    pub notional_usd: Option<String>,
1155    /// Order ID.
1156    pub ord_id: Ustr,
1157    /// Order type.
1158    pub ord_type: OKXOrderType,
1159    /// Profit and loss.
1160    pub pnl: String,
1161    /// Position side.
1162    pub pos_side: OKXPositionSide,
1163    /// Price (algo orders use ordPx instead).
1164    #[serde(default)]
1165    pub px: String,
1166    /// Price type (options).
1167    #[serde(default)]
1168    pub px_type: OKXPriceType,
1169    /// Price in USD (options).
1170    #[serde(default)]
1171    pub px_usd: Option<String>,
1172    /// Price in volatility (options).
1173    #[serde(default)]
1174    pub px_vol: Option<String>,
1175    /// Quick margin type.
1176    #[serde(default)]
1177    pub quick_mgn_type: OKXQuickMarginType,
1178    /// Rebate amount.
1179    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1180    pub rebate: Option<String>,
1181    /// Rebate currency.
1182    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1183    pub rebate_ccy: Option<Ustr>,
1184    /// Reduce only flag.
1185    pub reduce_only: String,
1186    /// Side.
1187    pub side: OKXSide,
1188    /// Stop-loss order price.
1189    #[serde(default)]
1190    pub sl_ord_px: Option<String>,
1191    /// Stop-loss trigger price.
1192    #[serde(default)]
1193    pub sl_trigger_px: Option<String>,
1194    /// Stop-loss trigger price type (last, mark, index).
1195    #[serde(default)]
1196    pub sl_trigger_px_type: Option<OKXTriggerType>,
1197    /// Order source.
1198    #[serde(default)]
1199    pub source: Option<String>,
1200    /// Order state.
1201    pub state: OKXOrderStatus,
1202    /// Self-trade prevention ID.
1203    #[serde(default)]
1204    pub stp_id: Option<String>,
1205    /// Self-trade prevention mode.
1206    #[serde(default)]
1207    pub stp_mode: OKXSelfTradePreventionMode,
1208    /// Execution type.
1209    pub exec_type: OKXExecType,
1210    /// Size.
1211    pub sz: String,
1212    /// Order tag.
1213    #[serde(default)]
1214    pub tag: Option<String>,
1215    /// Trade mode.
1216    pub td_mode: OKXTradeMode,
1217    /// Quantity unit for spot market orders (`base_ccy` or `quote_ccy`).
1218    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
1219    pub tgt_ccy: Option<OKXTargetCurrency>,
1220    /// Take-profit order price.
1221    #[serde(default)]
1222    pub tp_ord_px: Option<String>,
1223    /// Take-profit trigger price.
1224    #[serde(default)]
1225    pub tp_trigger_px: Option<String>,
1226    /// Take-profit trigger price type (last, mark, index).
1227    #[serde(default)]
1228    pub tp_trigger_px_type: Option<OKXTriggerType>,
1229    /// Trade ID.
1230    pub trade_id: String,
1231    /// Last update time, Unix timestamp in milliseconds.
1232    #[serde(deserialize_with = "deserialize_string_to_u64")]
1233    pub u_time: u64,
1234    /// Amend result code.
1235    #[serde(default)]
1236    pub amend_result: Option<String>,
1237    /// Request ID (for amend responses).
1238    #[serde(default)]
1239    pub req_id: Option<String>,
1240    /// Error code.
1241    #[serde(default)]
1242    pub code: Option<String>,
1243    /// Error message.
1244    #[serde(default)]
1245    pub msg: Option<String>,
1246}
1247
1248/// Represents an algo order message from WebSocket updates.
1249#[derive(Clone, Debug, Deserialize, Serialize)]
1250#[serde(rename_all = "camelCase")]
1251pub struct OKXAlgoOrderMsg {
1252    /// Algorithm ID.
1253    pub algo_id: String,
1254    /// Algorithm client order ID.
1255    #[serde(default)]
1256    pub algo_cl_ord_id: String,
1257    /// Client order ID (empty for algo orders until triggered).
1258    pub cl_ord_id: String,
1259    /// Order ID (empty until algo order is triggered).
1260    pub ord_id: String,
1261    /// Triggered child order IDs.
1262    #[serde(default)]
1263    pub ord_id_list: Vec<String>,
1264    /// Instrument ID.
1265    pub inst_id: Ustr,
1266    /// Instrument type.
1267    pub inst_type: OKXInstrumentType,
1268    /// Algo order type (trigger, `move_order_stop`, oco, iceberg, twap).
1269    pub ord_type: OKXAlgoOrderType,
1270    /// Order state.
1271    pub state: OKXAlgoOrderStatus,
1272    /// Side.
1273    pub side: OKXSide,
1274    /// Position side.
1275    pub pos_side: OKXPositionSide,
1276    /// Size.
1277    #[serde(default)]
1278    pub sz: String,
1279    /// Trigger price.
1280    #[serde(default)]
1281    pub trigger_px: String,
1282    /// Trigger price type (last, mark, index).
1283    #[serde(default)]
1284    pub trigger_px_type: OKXTriggerType,
1285    /// Stop-loss trigger price for conditional close orders.
1286    #[serde(default)]
1287    pub sl_trigger_px: String,
1288    /// Stop-loss order price for conditional close orders.
1289    #[serde(default)]
1290    pub sl_ord_px: String,
1291    /// Stop-loss trigger price type (last, mark, index).
1292    #[serde(default)]
1293    pub sl_trigger_px_type: OKXTriggerType,
1294    /// Take-profit trigger price for conditional close orders.
1295    #[serde(default)]
1296    pub tp_trigger_px: String,
1297    /// Take-profit order price for conditional close orders.
1298    #[serde(default)]
1299    pub tp_ord_px: String,
1300    /// Take-profit trigger price type (last, mark, index).
1301    #[serde(default)]
1302    pub tp_trigger_px_type: OKXTriggerType,
1303    /// Order price (-1 for market orders).
1304    #[serde(default)]
1305    pub ord_px: String,
1306    /// Trade mode.
1307    pub td_mode: OKXTradeMode,
1308    /// Leverage.
1309    pub lever: String,
1310    /// Reduce only flag.
1311    #[serde(default)]
1312    pub reduce_only: String,
1313    /// Fraction of the position to close for close-order algos.
1314    #[serde(default)]
1315    pub close_fraction: String,
1316    /// Actual filled price.
1317    #[serde(default)]
1318    pub actual_px: String,
1319    /// Actual filled size.
1320    #[serde(default)]
1321    pub actual_sz: String,
1322    /// Notional USD value.
1323    #[serde(default)]
1324    pub notional_usd: String,
1325    /// Creation time, Unix timestamp in milliseconds.
1326    #[serde(deserialize_with = "deserialize_string_to_u64")]
1327    pub c_time: u64,
1328    /// Update time, Unix timestamp in milliseconds.
1329    #[serde(deserialize_with = "deserialize_string_to_u64")]
1330    pub u_time: u64,
1331    /// Trigger time (empty until triggered).
1332    #[serde(default)]
1333    pub trigger_time: String,
1334    /// Failure code for rejected algo orders.
1335    #[serde(default)]
1336    pub fail_code: String,
1337    /// Tag.
1338    #[serde(default)]
1339    pub tag: String,
1340    /// Callback price ratio for trailing stop (e.g. "0.01" for 1%).
1341    #[serde(default)]
1342    pub callback_ratio: String,
1343    /// Callback price spread for trailing stop (absolute distance).
1344    #[serde(default)]
1345    pub callback_spread: String,
1346    /// Activation price for trailing stop.
1347    #[serde(default)]
1348    pub active_px: String,
1349    /// Currency.
1350    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1351    pub ccy: Option<Ustr>,
1352    /// Target currency (`base_ccy` or `quote_ccy`).
1353    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
1354    pub tgt_ccy: Option<OKXTargetCurrency>,
1355    /// Fee amount.
1356    #[serde(default)]
1357    pub fee: Option<String>,
1358    /// Fee currency.
1359    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1360    pub fee_ccy: Option<Ustr>,
1361    /// Trigger order type (fok, ioc).
1362    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1363    pub advance_ord_type: Option<String>,
1364}
1365
1366/// Parameters for WebSocket place order operation.
1367#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1368#[builder(default)]
1369#[builder(setter(into, strip_option))]
1370#[serde(rename_all = "camelCase")]
1371pub struct WsAttachAlgoOrdParams {
1372    /// Attached algo client order ID.
1373    #[serde(skip_serializing_if = "Option::is_none")]
1374    pub attach_algo_cl_ord_id: Option<String>,
1375    /// Stop-loss trigger price.
1376    #[serde(skip_serializing_if = "Option::is_none")]
1377    pub sl_trigger_px: Option<String>,
1378    /// Stop-loss order price (`-1` for market).
1379    #[serde(skip_serializing_if = "Option::is_none")]
1380    pub sl_ord_px: Option<String>,
1381    /// Stop-loss trigger price type (last, mark, index).
1382    #[serde(skip_serializing_if = "Option::is_none")]
1383    pub sl_trigger_px_type: Option<OKXTriggerType>,
1384    /// Take-profit trigger price.
1385    #[serde(skip_serializing_if = "Option::is_none")]
1386    pub tp_trigger_px: Option<String>,
1387    /// Take-profit order price (`-1` for market).
1388    #[serde(skip_serializing_if = "Option::is_none")]
1389    pub tp_ord_px: Option<String>,
1390    /// Take-profit trigger price type (last, mark, index).
1391    #[serde(skip_serializing_if = "Option::is_none")]
1392    pub tp_trigger_px_type: Option<OKXTriggerType>,
1393    /// Callback ratio for attached trailing stop orders.
1394    #[serde(skip_serializing_if = "Option::is_none")]
1395    pub callback_ratio: Option<String>,
1396    /// Callback spread for attached trailing stop orders.
1397    #[serde(skip_serializing_if = "Option::is_none")]
1398    pub callback_spread: Option<String>,
1399    /// Activation price for attached trailing stop orders.
1400    #[serde(skip_serializing_if = "Option::is_none")]
1401    pub active_px: Option<String>,
1402    /// New callback ratio for amended attached trailing stop orders.
1403    #[serde(skip_serializing_if = "Option::is_none")]
1404    pub new_callback_ratio: Option<String>,
1405    /// New callback spread for amended attached trailing stop orders.
1406    #[serde(skip_serializing_if = "Option::is_none")]
1407    pub new_callback_spread: Option<String>,
1408    /// New activation price for amended attached trailing stop orders.
1409    #[serde(skip_serializing_if = "Option::is_none")]
1410    pub new_active_px: Option<String>,
1411}
1412
1413/// Parameters for WebSocket place order operation.
1414#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1415#[builder(setter(into, strip_option))]
1416#[serde(rename_all = "camelCase")]
1417pub struct WsPostOrderParams {
1418    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION (optional for WebSocket).
1419    #[builder(default)]
1420    #[serde(skip_serializing_if = "Option::is_none")]
1421    pub inst_type: Option<OKXInstrumentType>,
1422    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1423    pub inst_id_code: u64,
1424    /// Trading mode: cash, isolated, cross.
1425    pub td_mode: OKXTradeMode,
1426    /// Margin currency (only for isolated margin).
1427    #[builder(default)]
1428    #[serde(skip_serializing_if = "Option::is_none")]
1429    pub ccy: Option<Ustr>,
1430    /// Unique client order ID.
1431    #[builder(default)]
1432    #[serde(skip_serializing_if = "Option::is_none")]
1433    pub cl_ord_id: Option<String>,
1434    /// Order side: buy or sell.
1435    pub side: OKXSide,
1436    /// Position side: long, short, net (optional).
1437    #[builder(default)]
1438    #[serde(skip_serializing_if = "Option::is_none")]
1439    pub pos_side: Option<OKXPositionSide>,
1440    /// Order type: limit, market, `post_only`, fok, ioc, etc.
1441    pub ord_type: OKXOrderType,
1442    /// Order size.
1443    pub sz: String,
1444    /// Order price (required for limit orders).
1445    #[builder(default)]
1446    #[serde(skip_serializing_if = "Option::is_none")]
1447    pub px: Option<String>,
1448    /// Price in USD, only applicable to options. Mutually exclusive with `px` and `px_vol`.
1449    #[builder(default)]
1450    #[serde(rename = "pxUsd", skip_serializing_if = "Option::is_none")]
1451    pub px_usd: Option<String>,
1452    /// Price in implied volatility (1 = 100%), only applicable to options.
1453    /// Mutually exclusive with `px` and `px_usd`.
1454    #[builder(default)]
1455    #[serde(rename = "pxVol", skip_serializing_if = "Option::is_none")]
1456    pub px_vol: Option<String>,
1457    /// Reduce-only flag.
1458    #[builder(default)]
1459    #[serde(skip_serializing_if = "Option::is_none")]
1460    pub reduce_only: Option<bool>,
1461    /// Whether to close the entire position.
1462    #[builder(default)]
1463    #[serde(rename = "closePosition", skip_serializing_if = "Option::is_none")]
1464    pub close_position: Option<bool>,
1465    /// Target currency for net orders.
1466    #[builder(default)]
1467    #[serde(skip_serializing_if = "Option::is_none")]
1468    pub tgt_ccy: Option<OKXTargetCurrency>,
1469    /// Quote currency used for trading. Only applicable to SPOT.
1470    #[builder(default)]
1471    #[serde(skip_serializing_if = "Option::is_none")]
1472    pub trade_quote_ccy: Option<Ustr>,
1473    /// Order tag for categorization.
1474    #[builder(default)]
1475    #[serde(skip_serializing_if = "Option::is_none")]
1476    pub tag: Option<String>,
1477    /// Attached TP/SL orders submitted with the parent order.
1478    #[builder(default)]
1479    #[serde(skip_serializing_if = "Option::is_none")]
1480    pub attach_algo_ords: Option<Vec<WsAttachAlgoOrdParams>>,
1481    /// Event contract market outcome: yes or no.
1482    #[builder(default)]
1483    #[serde(skip_serializing_if = "Option::is_none")]
1484    pub outcome: Option<String>,
1485    /// Slippage tolerance for market orders, expressed as a decimal fraction
1486    /// (e.g., "0.005" for 0.5%). Supported instrument/order-type scope is
1487    /// venue-controlled; rejected with `54084`/`54085` if exceeded or out of
1488    /// the venue's accepted range. See the OKX v5 docs for the current matrix.
1489    #[builder(default)]
1490    #[serde(skip_serializing_if = "Option::is_none")]
1491    pub slippage_pct: Option<String>,
1492    /// Whether the order may take RPI liquidity.
1493    #[builder(default)]
1494    #[serde(skip_serializing_if = "Option::is_none")]
1495    pub rpi_taker_access: Option<bool>,
1496    /// Whether OKX may round the order price to an eligible RPI price.
1497    #[builder(default)]
1498    #[serde(skip_serializing_if = "Option::is_none")]
1499    pub rpi_px_round: Option<bool>,
1500}
1501
1502/// Parameters for WebSocket cancel order operation (instType not included).
1503#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1504#[builder(default)]
1505#[builder(setter(into, strip_option))]
1506#[serde(rename_all = "camelCase")]
1507pub struct WsCancelOrderParams {
1508    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1509    pub inst_id_code: u64,
1510    /// Exchange-assigned order ID.
1511    #[serde(skip_serializing_if = "Option::is_none")]
1512    pub ord_id: Option<String>,
1513    /// User-assigned client order ID.
1514    #[serde(skip_serializing_if = "Option::is_none")]
1515    pub cl_ord_id: Option<String>,
1516}
1517
1518/// Parameters for WebSocket mass cancel operation.
1519#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1520#[builder(default)]
1521#[builder(setter(into, strip_option))]
1522#[serde(rename_all = "camelCase")]
1523pub struct WsMassCancelParams {
1524    /// Instrument type.
1525    pub inst_type: OKXInstrumentType,
1526    /// Instrument family, e.g. "BTC-USD", "BTC-USDT".
1527    pub inst_family: Ustr,
1528}
1529
1530/// Parameters for WebSocket amend order operation (instType not included).
1531#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1532#[builder(default)]
1533#[builder(setter(into, strip_option))]
1534#[serde(rename_all = "camelCase")]
1535pub struct WsAmendOrderParams {
1536    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1537    pub inst_id_code: u64,
1538    /// Exchange-assigned order ID (optional if using clOrdId).
1539    #[serde(skip_serializing_if = "Option::is_none")]
1540    pub ord_id: Option<String>,
1541    /// User-assigned client order ID (optional if using ordId).
1542    #[serde(skip_serializing_if = "Option::is_none")]
1543    pub cl_ord_id: Option<String>,
1544    /// Client request ID for correlating the amendment response.
1545    #[serde(skip_serializing_if = "Option::is_none")]
1546    pub req_id: Option<String>,
1547    /// New order price (optional).
1548    #[serde(skip_serializing_if = "Option::is_none")]
1549    pub new_px: Option<String>,
1550    /// New price in USD, only applicable to options. Must match the pricing mode used at placement.
1551    #[serde(rename = "newPxUsd", skip_serializing_if = "Option::is_none")]
1552    pub new_px_usd: Option<String>,
1553    /// New price in implied volatility, only applicable to options.
1554    /// Must match the pricing mode used at placement.
1555    #[serde(rename = "newPxVol", skip_serializing_if = "Option::is_none")]
1556    pub new_px_vol: Option<String>,
1557    /// New order size (optional).
1558    #[serde(skip_serializing_if = "Option::is_none")]
1559    pub new_sz: Option<String>,
1560    /// Whether the order may take RPI liquidity after amendment.
1561    #[serde(skip_serializing_if = "Option::is_none")]
1562    pub rpi_taker_access: Option<bool>,
1563    /// Whether OKX may round the amended price to an eligible RPI price.
1564    #[serde(skip_serializing_if = "Option::is_none")]
1565    pub rpi_px_round: Option<bool>,
1566}
1567
1568/// Parameters for WebSocket algo order placement.
1569#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1570#[builder(setter(into, strip_option))]
1571#[serde(rename_all = "camelCase")]
1572pub struct WsPostAlgoOrderParams {
1573    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1574    pub inst_id_code: u64,
1575    /// Trading mode: cash, isolated, cross.
1576    pub td_mode: OKXTradeMode,
1577    /// Order side: buy or sell.
1578    pub side: OKXSide,
1579    /// Order type: trigger (for stop orders).
1580    pub ord_type: OKXAlgoOrderType,
1581    /// Order size.
1582    pub sz: String,
1583    /// Client order ID (optional).
1584    #[builder(default)]
1585    #[serde(skip_serializing_if = "Option::is_none")]
1586    pub cl_ord_id: Option<String>,
1587    /// Position side: long, short, net (optional).
1588    #[builder(default)]
1589    #[serde(skip_serializing_if = "Option::is_none")]
1590    pub pos_side: Option<OKXPositionSide>,
1591    /// Trigger price for stop/conditional orders.
1592    #[serde(skip_serializing_if = "Option::is_none")]
1593    pub trigger_px: Option<String>,
1594    /// Trigger price type: last, index, mark.
1595    #[builder(default)]
1596    #[serde(skip_serializing_if = "Option::is_none")]
1597    pub trigger_px_type: Option<OKXTriggerType>,
1598    /// Order price (for limit orders after trigger).
1599    #[builder(default)]
1600    #[serde(skip_serializing_if = "Option::is_none")]
1601    pub order_px: Option<String>,
1602    /// Reduce-only flag.
1603    #[builder(default)]
1604    #[serde(skip_serializing_if = "Option::is_none")]
1605    pub reduce_only: Option<bool>,
1606    /// Order tag for categorization.
1607    #[builder(default)]
1608    #[serde(skip_serializing_if = "Option::is_none")]
1609    pub tag: Option<String>,
1610    /// Callback rate for trailing stop (e.g., "0.01" for 1%).
1611    #[builder(default)]
1612    #[serde(skip_serializing_if = "Option::is_none")]
1613    pub callback_ratio: Option<String>,
1614    /// Callback spread for trailing stop (fixed price distance).
1615    #[builder(default)]
1616    #[serde(skip_serializing_if = "Option::is_none")]
1617    pub callback_spread: Option<String>,
1618    /// Activation price for trailing stop.
1619    #[builder(default)]
1620    #[serde(skip_serializing_if = "Option::is_none")]
1621    pub active_px: Option<String>,
1622}
1623
1624/// Parameters for WebSocket cancel algo order operation.
1625#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1626#[builder(setter(into, strip_option))]
1627#[serde(rename_all = "camelCase")]
1628pub struct WsCancelAlgoOrderParams {
1629    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1630    pub inst_id_code: u64,
1631    /// Algo order ID.
1632    #[builder(default)]
1633    #[serde(skip_serializing_if = "Option::is_none")]
1634    pub algo_id: Option<String>,
1635    /// Client algo order ID.
1636    #[builder(default)]
1637    #[serde(skip_serializing_if = "Option::is_none")]
1638    pub algo_cl_ord_id: Option<String>,
1639}
1640
1641#[cfg(test)]
1642mod tests {
1643    use nautilus_core::string::secret::REDACTED;
1644    use rstest::rstest;
1645    use rust_decimal::Decimal;
1646
1647    use super::*;
1648
1649    #[rstest]
1650    fn authentication_preserves_wire_values_and_redacts_debug() {
1651        let authentication = OKXAuthentication {
1652            op: "login",
1653            args: vec![OKXAuthenticationArg {
1654                api_key: SecretString::from("api-key-value"),
1655                passphrase: SecretString::from("passphrase-value"),
1656                timestamp: "1700000000".to_string(),
1657                sign: SecretString::from("signature-value"),
1658            }],
1659        };
1660
1661        let json = serde_json::to_value(&authentication).unwrap();
1662        let formatted = format!("{authentication:?}");
1663
1664        assert_eq!(json["op"], "login");
1665        assert_eq!(json["args"][0]["apiKey"], "api-key-value");
1666        assert_eq!(json["args"][0]["passphrase"], "passphrase-value");
1667        assert_eq!(json["args"][0]["sign"], "signature-value");
1668        assert!(formatted.contains(REDACTED));
1669        assert!(!formatted.contains("api-key-value"));
1670        assert!(!formatted.contains("passphrase-value"));
1671        assert!(!formatted.contains("signature-value"));
1672    }
1673    use crate::common::testing::load_test_json;
1674
1675    #[rstest]
1676    fn test_deserialize_websocket_arg() {
1677        let json_str = r#"{"channel":"instruments","instType":"SPOT"}"#;
1678
1679        let result: Result<OKXWebSocketArg, _> = serde_json::from_str(json_str);
1680        match result {
1681            Ok(arg) => {
1682                assert_eq!(arg.channel, OKXWsChannel::Instruments);
1683                assert_eq!(arg.inst_type, Some(OKXInstrumentType::Spot));
1684                assert_eq!(arg.inst_id, None);
1685            }
1686            Err(e) => {
1687                panic!("Failed to deserialize WebSocket arg: {e}");
1688            }
1689        }
1690    }
1691
1692    #[rstest]
1693    fn test_deserialize_subscribe_confirmation() {
1694        let json_str = r#"{"event":"subscribe","arg":{"channel":"instruments","instType":"SPOT"},"connId":"380cfa6a"}"#;
1695
1696        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1697        match result {
1698            Ok(msg) => {
1699                if let OKXWsFrame::Subscription {
1700                    event,
1701                    arg,
1702                    conn_id,
1703                    ..
1704                } = msg
1705                {
1706                    assert_eq!(event, OKXSubscriptionEvent::Subscribe);
1707                    assert_eq!(arg.channel, OKXWsChannel::Instruments);
1708                    assert_eq!(conn_id, "380cfa6a");
1709                } else {
1710                    panic!("Expected Subscribe variant, was: {msg:?}");
1711                }
1712            }
1713            Err(e) => {
1714                panic!("Failed to deserialize subscription confirmation: {e}");
1715            }
1716        }
1717    }
1718
1719    #[rstest]
1720    fn test_deserialize_subscribe_with_inst_id() {
1721        let json_str = r#"{"event":"subscribe","arg":{"channel":"candle1m","instId":"ETH-USDT"},"connId":"358602f5"}"#;
1722
1723        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1724        match result {
1725            Ok(msg) => {
1726                if let OKXWsFrame::Subscription {
1727                    event,
1728                    arg,
1729                    conn_id,
1730                    ..
1731                } = msg
1732                {
1733                    assert_eq!(event, OKXSubscriptionEvent::Subscribe);
1734                    assert_eq!(arg.channel, OKXWsChannel::Candle1Minute);
1735                    assert_eq!(conn_id, "358602f5");
1736                } else {
1737                    panic!("Expected Subscribe variant, was: {msg:?}");
1738                }
1739            }
1740            Err(e) => {
1741                panic!("Failed to deserialize subscription confirmation: {e}");
1742            }
1743        }
1744    }
1745
1746    #[rstest]
1747    fn test_channel_serialization_for_logging() {
1748        let channel = OKXWsChannel::Candle1Minute;
1749        let serialized = serde_json::to_string(&channel).unwrap();
1750        let cleaned = serialized.trim_matches('"').to_string();
1751        assert_eq!(cleaned, "candle1m");
1752
1753        let channel = OKXWsChannel::BboTbt;
1754        let serialized = serde_json::to_string(&channel).unwrap();
1755        let cleaned = serialized.trim_matches('"').to_string();
1756        assert_eq!(cleaned, "bbo-tbt");
1757
1758        let channel = OKXWsChannel::Trades;
1759        let serialized = serde_json::to_string(&channel).unwrap();
1760        let cleaned = serialized.trim_matches('"').to_string();
1761        assert_eq!(cleaned, "trades");
1762    }
1763
1764    #[rstest]
1765    fn test_order_response_with_enum_operation() {
1766        let json_str = r#"{"id":"req-123","op":"order","code":"0","msg":"","data":[]}"#;
1767        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1768        match result {
1769            Ok(OKXWsFrame::OrderResponse {
1770                id,
1771                op,
1772                code,
1773                msg,
1774                data,
1775            }) => {
1776                assert_eq!(id, Some("req-123".to_string()));
1777                assert_eq!(op, OKXWsOperation::Order);
1778                assert_eq!(code, "0");
1779                assert_eq!(msg, "");
1780                assert!(data.is_empty());
1781            }
1782            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1783            Err(e) => panic!("Failed to deserialize: {e}"),
1784        }
1785
1786        let json_str = r#"{"id":"cancel-456","op":"cancel-order","code":"50001","msg":"Order not found","data":[]}"#;
1787        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1788        match result {
1789            Ok(OKXWsFrame::OrderResponse {
1790                id,
1791                op,
1792                code,
1793                msg,
1794                data,
1795            }) => {
1796                assert_eq!(id, Some("cancel-456".to_string()));
1797                assert_eq!(op, OKXWsOperation::CancelOrder);
1798                assert_eq!(code, "50001");
1799                assert_eq!(msg, "Order not found");
1800                assert!(data.is_empty());
1801            }
1802            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1803            Err(e) => panic!("Failed to deserialize: {e}"),
1804        }
1805
1806        let json_str = r#"{"id":"amend-789","op":"amend-order","code":"50002","msg":"Invalid price","data":[]}"#;
1807        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1808        match result {
1809            Ok(OKXWsFrame::OrderResponse {
1810                id,
1811                op,
1812                code,
1813                msg,
1814                data,
1815            }) => {
1816                assert_eq!(id, Some("amend-789".to_string()));
1817                assert_eq!(op, OKXWsOperation::AmendOrder);
1818                assert_eq!(code, "50002");
1819                assert_eq!(msg, "Invalid price");
1820                assert!(data.is_empty());
1821            }
1822            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1823            Err(e) => panic!("Failed to deserialize: {e}"),
1824        }
1825    }
1826
1827    #[rstest]
1828    fn test_operation_enum_serialization() {
1829        let op = OKXWsOperation::Order;
1830        let serialized = serde_json::to_string(&op).unwrap();
1831        assert_eq!(serialized, "\"order\"");
1832
1833        let op = OKXWsOperation::CancelOrder;
1834        let serialized = serde_json::to_string(&op).unwrap();
1835        assert_eq!(serialized, "\"cancel-order\"");
1836
1837        let op = OKXWsOperation::AmendOrder;
1838        let serialized = serde_json::to_string(&op).unwrap();
1839        assert_eq!(serialized, "\"amend-order\"");
1840
1841        let op = OKXWsOperation::Subscribe;
1842        let serialized = serde_json::to_string(&op).unwrap();
1843        assert_eq!(serialized, "\"subscribe\"");
1844    }
1845
1846    #[rstest]
1847    fn test_order_response_parsing() {
1848        let success_response = r#"{
1849            "id": "req-123",
1850            "op": "order",
1851            "code": "0",
1852            "msg": "",
1853            "data": [{"sMsg": "Order placed successfully"}]
1854        }"#;
1855
1856        let parsed: OKXWsFrame = serde_json::from_str(success_response).unwrap();
1857
1858        match parsed {
1859            OKXWsFrame::OrderResponse {
1860                id,
1861                op,
1862                code,
1863                msg,
1864                data,
1865            } => {
1866                assert_eq!(id, Some("req-123".to_string()));
1867                assert_eq!(op, OKXWsOperation::Order);
1868                assert_eq!(code, "0");
1869                assert_eq!(msg, "");
1870                assert_eq!(data.len(), 1);
1871            }
1872            _ => panic!("Expected OrderResponse variant"),
1873        }
1874
1875        let failure_response = r#"{
1876            "id": "req-456",
1877            "op": "cancel-order",
1878            "code": "50001",
1879            "msg": "Order not found",
1880            "data": [{"sMsg": "Order with client order ID not found"}]
1881        }"#;
1882
1883        let parsed: OKXWsFrame = serde_json::from_str(failure_response).unwrap();
1884
1885        match parsed {
1886            OKXWsFrame::OrderResponse {
1887                id,
1888                op,
1889                code,
1890                msg,
1891                data,
1892            } => {
1893                assert_eq!(id, Some("req-456".to_string()));
1894                assert_eq!(op, OKXWsOperation::CancelOrder);
1895                assert_eq!(code, "50001");
1896                assert_eq!(msg, "Order not found");
1897                assert_eq!(data.len(), 1);
1898            }
1899            _ => panic!("Expected OrderResponse variant"),
1900        }
1901    }
1902
1903    #[rstest]
1904    fn test_subscription_event_parsing() {
1905        let subscription_json = r#"{
1906            "event": "subscribe",
1907            "arg": {
1908                "channel": "tickers",
1909                "instId": "BTC-USDT"
1910            },
1911            "connId": "a4d3ae55"
1912        }"#;
1913
1914        let parsed: OKXWsFrame = serde_json::from_str(subscription_json).unwrap();
1915
1916        match parsed {
1917            OKXWsFrame::Subscription {
1918                event,
1919                arg,
1920                conn_id,
1921                ..
1922            } => {
1923                assert_eq!(
1924                    event,
1925                    crate::websocket::enums::OKXSubscriptionEvent::Subscribe
1926                );
1927                assert_eq!(arg.channel, OKXWsChannel::Tickers);
1928                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USDT")));
1929                assert_eq!(conn_id, "a4d3ae55");
1930            }
1931            _ => panic!("Expected Subscription variant"),
1932        }
1933    }
1934
1935    #[rstest]
1936    fn test_login_event_parsing() {
1937        let login_success = r#"{
1938            "event": "login",
1939            "code": "0",
1940            "msg": "Login successful",
1941            "connId": "a4d3ae55"
1942        }"#;
1943
1944        let parsed: OKXWsFrame = serde_json::from_str(login_success).unwrap();
1945
1946        match parsed {
1947            OKXWsFrame::Login {
1948                event,
1949                code,
1950                msg,
1951                conn_id,
1952            } => {
1953                assert_eq!(event, "login");
1954                assert_eq!(code, "0");
1955                assert_eq!(msg, "Login successful");
1956                assert_eq!(conn_id, "a4d3ae55");
1957            }
1958            _ => panic!("Expected Login variant, was: {parsed:?}"),
1959        }
1960    }
1961
1962    #[rstest]
1963    fn test_error_event_parsing() {
1964        let error_json = r#"{
1965            "code": "60012",
1966            "msg": "Invalid request"
1967        }"#;
1968
1969        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
1970
1971        match parsed {
1972            OKXWsFrame::Error { arg, code, msg } => {
1973                assert!(arg.is_none());
1974                assert_eq!(code, "60012");
1975                assert_eq!(msg, "Invalid request");
1976            }
1977            _ => panic!("Expected Error variant"),
1978        }
1979    }
1980
1981    #[rstest]
1982    fn test_error_event_with_event_field_parsing() {
1983        // OKX sends error events with "event":"error" field (e.g., login failures)
1984        let error_json = r#"{
1985            "event": "error",
1986            "code": "60018",
1987            "msg": "Invalid sign"
1988        }"#;
1989
1990        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
1991
1992        match parsed {
1993            OKXWsFrame::Error { arg, code, msg } => {
1994                assert!(arg.is_none());
1995                assert_eq!(code, "60018");
1996                assert_eq!(msg, "Invalid sign");
1997            }
1998            _ => panic!("Expected Error variant, was: {parsed:?}"),
1999        }
2000    }
2001
2002    #[rstest]
2003    fn test_subscription_error_with_arg_field_parsing() {
2004        // OKX sends subscription errors with arg field (channel subscription failures)
2005        let error_json = r#"{
2006            "event": "error",
2007            "arg": {"channel": "tickers", "instId": "INVALID-INST"},
2008            "code": "60012",
2009            "msg": "Invalid request: channel not found",
2010            "connId": "a4d3ae55"
2011        }"#;
2012
2013        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
2014
2015        match parsed {
2016            OKXWsFrame::Error { arg, code, msg } => {
2017                let arg = arg.expect("subscription error arg");
2018                assert_eq!(arg.channel, OKXWsChannel::Tickers);
2019                assert_eq!(arg.inst_id, Some(Ustr::from("INVALID-INST")));
2020                assert_eq!(code, "60012");
2021                assert_eq!(msg, "Invalid request: channel not found");
2022            }
2023            _ => panic!("Expected Error variant, was: {parsed:?}"),
2024        }
2025    }
2026
2027    #[rstest]
2028    fn test_websocket_request_serialization() {
2029        let request = OKXWsRequest {
2030            id: Some("req-123".to_string()),
2031            op: OKXWsOperation::Order,
2032            args: vec![serde_json::json!({
2033                "instId": "BTC-USDT",
2034                "tdMode": "cash",
2035                "side": "buy",
2036                "ordType": "market",
2037                "sz": "0.1"
2038            })],
2039            exp_time: None,
2040        };
2041
2042        let serialized = serde_json::to_string(&request).unwrap();
2043        let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
2044
2045        assert_eq!(parsed["id"], "req-123");
2046        assert_eq!(parsed["op"], "order");
2047        assert!(parsed["args"].is_array());
2048        assert_eq!(parsed["args"].as_array().unwrap().len(), 1);
2049    }
2050
2051    #[rstest]
2052    fn test_subscription_request_serialization() {
2053        let subscription = OKXSubscription {
2054            op: OKXWsOperation::Subscribe,
2055            args: vec![OKXSubscriptionArg {
2056                channel: OKXWsChannel::Tickers,
2057                inst_type: Some(OKXInstrumentType::Spot),
2058                inst_family: None,
2059                inst_id: Some(Ustr::from("BTC-USDT")),
2060            }],
2061        };
2062
2063        let serialized = serde_json::to_string(&subscription).unwrap();
2064        let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
2065
2066        assert_eq!(parsed["op"], "subscribe");
2067        assert!(parsed["args"].is_array());
2068        assert_eq!(parsed["args"][0]["channel"], "tickers");
2069        assert_eq!(parsed["args"][0]["instType"], "SPOT");
2070        assert_eq!(parsed["args"][0]["instId"], "BTC-USDT");
2071    }
2072
2073    #[rstest]
2074    fn test_book_data_parsing() {
2075        let parsed: OKXWsFrame =
2076            serde_json::from_str(&load_test_json("ws_books_snapshot.json")).unwrap();
2077
2078        match parsed {
2079            OKXWsFrame::BookData { arg, action, data } => {
2080                assert_eq!(arg.channel, OKXWsChannel::Books);
2081                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USDT")));
2082                assert_eq!(
2083                    action,
2084                    super::super::super::common::enums::OKXBookAction::Snapshot
2085                );
2086                assert_eq!(data.len(), 1);
2087            }
2088            _ => panic!("Expected BookData variant"),
2089        }
2090    }
2091
2092    #[rstest]
2093    #[case::arg_first(
2094        r#"{"arg":{"channel":"books","instId":"ETH-USDT"},"action":"update","data":[{"asks":[["3000.5","2","0","3"]],"bids":[["2999.5","4","1","5"]],"ts":"1640995200001","checksum":-42,"prevSeqId":1001,"seqId":1002}]}"#
2095    )]
2096    #[case::data_first(
2097        r#"{"data":[{"asks":[["3000.5","2","0","3"]],"bids":[["2999.5","4","1","5"]],"ts":"1640995200001","checksum":-42,"prevSeqId":1001,"seqId":1002}],"action":"update","arg":{"channel":"books","instId":"ETH-USDT"}}"#
2098    )]
2099    fn test_book_data_parsing_is_independent_of_key_order(#[case] json: &str) {
2100        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2101
2102        let OKXWsFrame::BookData { arg, action, data } = parsed else {
2103            panic!("Expected BookData variant");
2104        };
2105
2106        assert_eq!(arg.channel, OKXWsChannel::Books);
2107        assert_eq!(arg.inst_id, Some(Ustr::from("ETH-USDT")));
2108        assert_eq!(action, OKXBookAction::Update);
2109        assert_eq!(data.len(), 1);
2110        let msg = &data[0];
2111        assert_eq!(msg.asks.len(), 1);
2112        assert_eq!(msg.asks[0].price, "3000.5");
2113        assert_eq!(msg.asks[0].size, "2");
2114        assert_eq!(msg.asks[0].liquidated_orders_count, "0");
2115        assert_eq!(msg.asks[0].orders_count, "3");
2116        assert_eq!(msg.bids.len(), 1);
2117        assert_eq!(msg.bids[0].price, "2999.5");
2118        assert_eq!(msg.bids[0].size, "4");
2119        assert_eq!(msg.bids[0].liquidated_orders_count, "1");
2120        assert_eq!(msg.bids[0].orders_count, "5");
2121        assert_eq!(msg.checksum, Some(-42));
2122        assert_eq!(msg.prev_seq_id, Some(1001));
2123        assert_eq!(msg.seq_id, 1002);
2124        assert_eq!(msg.ts, 1_640_995_200_001);
2125    }
2126
2127    #[rstest]
2128    #[case::op_first(
2129        r#"{"id":"req-7","op":"cancel-order","data":[{"sCode":"51400","sMsg":"Cancellation failed"}],"code":"1","msg":"Operation failed"}"#
2130    )]
2131    #[case::data_first(
2132        r#"{"data":[{"sCode":"51400","sMsg":"Cancellation failed"}],"code":"1","msg":"Operation failed","op":"cancel-order","id":"req-7"}"#
2133    )]
2134    fn test_order_response_parsing_is_independent_of_key_order(#[case] json: &str) {
2135        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2136
2137        let OKXWsFrame::OrderResponse {
2138            id,
2139            op,
2140            code,
2141            msg,
2142            data,
2143        } = parsed
2144        else {
2145            panic!("Expected OrderResponse variant");
2146        };
2147
2148        assert_eq!(id, Some("req-7".to_string()));
2149        assert_eq!(op, OKXWsOperation::CancelOrder);
2150        assert_eq!(code, "1");
2151        assert_eq!(msg, "Operation failed");
2152        assert_eq!(
2153            data,
2154            vec![serde_json::json!({"sCode": "51400", "sMsg": "Cancellation failed"})]
2155        );
2156    }
2157
2158    #[rstest]
2159    #[case::op_first(r#"{"op":"order","data":null,"event":"error","code":"60012","msg":"Bad"}"#)]
2160    #[case::event_first(r#"{"event":"error","code":"60012","msg":"Bad","op":"order","data":null}"#)]
2161    fn test_error_event_takes_priority_over_op_in_any_key_order(#[case] json: &str) {
2162        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2163
2164        let OKXWsFrame::Error { arg, code, msg } = parsed else {
2165            panic!("Expected Error variant");
2166        };
2167
2168        assert!(arg.is_none());
2169        assert_eq!(code, "60012");
2170        assert_eq!(msg, "Bad");
2171    }
2172
2173    #[rstest]
2174    fn test_rpi_book_fixtures_preserve_depth_types_and_sequence() {
2175        let snapshot: OKXWsFrame =
2176            serde_json::from_str(&load_test_json("ws_books_rpi_snapshot.json")).unwrap();
2177        let update: OKXWsFrame =
2178            serde_json::from_str(&load_test_json("ws_books_rpi_update.json")).unwrap();
2179
2180        let OKXWsFrame::RpiBookData { arg, action, data } = snapshot else {
2181            panic!("Expected RPI book snapshot");
2182        };
2183        let snapshot = &data[0];
2184        assert_eq!(arg.channel, OKXWsChannel::BooksRpi);
2185        assert_eq!(arg.inst_id, Some(Ustr::from("OMI-USD")));
2186        assert_eq!(action, OKXBookAction::Snapshot);
2187        assert_eq!(data.len(), 1);
2188        assert_eq!(snapshot.asks.len(), 4);
2189        assert_eq!(snapshot.bids.len(), 10);
2190        assert_eq!(
2191            snapshot.asks[0],
2192            OKXRpiBookLevel(
2193                Decimal::from_str_exact("0.0001617").unwrap(),
2194                Decimal::from_str_exact("12325166.992").unwrap(),
2195                Decimal::from(1000),
2196                2,
2197            )
2198        );
2199        assert_eq!(
2200            serde_json::to_value(&snapshot.asks[0]).unwrap(),
2201            serde_json::json!(["0.0001617", "12325166.992", "1000", "2"])
2202        );
2203        assert_eq!(snapshot.prev_seq_id, -1);
2204        assert_eq!(snapshot.seq_id, 1_082_831_226);
2205        assert_eq!(snapshot.ts, 1_785_406_442_403);
2206
2207        let OKXWsFrame::RpiBookData { arg, action, data } = update else {
2208            panic!("Expected RPI book update");
2209        };
2210        let update = &data[0];
2211        assert_eq!(arg.channel, OKXWsChannel::BooksRpi);
2212        assert_eq!(arg.inst_id, Some(Ustr::from("OMI-USD")));
2213        assert_eq!(action, OKXBookAction::Update);
2214        assert_eq!(data.len(), 1);
2215        assert_eq!(update.asks.len(), 2);
2216        assert!(update.bids.is_empty());
2217        assert_eq!(
2218            update.asks[1],
2219            OKXRpiBookLevel(
2220                Decimal::from_str_exact("0.0001625").unwrap(),
2221                Decimal::from_str_exact("12324367.786").unwrap(),
2222                Decimal::from(1000),
2223                2,
2224            )
2225        );
2226        assert_eq!(update.prev_seq_id, snapshot.seq_id as i64);
2227        assert_eq!(update.seq_id, 1_082_831_230);
2228        assert_eq!(update.ts, 1_785_406_443_903);
2229    }
2230
2231    #[rstest]
2232    fn test_rpi_book_rejects_checksum_field() {
2233        let mut payload: serde_json::Value =
2234            serde_json::from_str(&load_test_json("ws_books_rpi_update.json")).unwrap();
2235        payload["data"][0]["checksum"] = serde_json::json!(0);
2236
2237        let error = serde_json::from_value::<OKXWsFrame>(payload).unwrap_err();
2238
2239        assert!(error.to_string().contains("checksum"));
2240    }
2241
2242    #[rstest]
2243    fn test_data_event_parsing() {
2244        let parsed: OKXWsFrame = serde_json::from_str(&load_test_json("ws_trades.json")).unwrap();
2245
2246        match parsed {
2247            OKXWsFrame::Data { arg, data } => {
2248                assert_eq!(arg.channel, OKXWsChannel::Trades);
2249                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USD")));
2250                assert!(data.is_array());
2251            }
2252            _ => panic!("Expected Data variant"),
2253        }
2254    }
2255
2256    #[rstest]
2257    fn test_ws_post_order_params_serializes_inst_id_code() {
2258        use super::WsPostOrderParamsBuilder;
2259        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2260
2261        let params = WsPostOrderParamsBuilder::default()
2262            .inst_id_code(10459u64)
2263            .td_mode(OKXTradeMode::Cross)
2264            .side(OKXSide::Buy)
2265            .ord_type(OKXOrderType::Limit)
2266            .sz("0.01".to_string())
2267            .px("50000".to_string())
2268            .build()
2269            .unwrap();
2270
2271        let json = serde_json::to_string(&params).unwrap();
2272
2273        assert!(json.contains("\"instIdCode\":10459"));
2274        assert!(!json.contains("\"instId\""));
2275    }
2276
2277    #[rstest]
2278    fn test_ws_post_order_params_serializes_slippage_pct() {
2279        use super::WsPostOrderParamsBuilder;
2280        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2281
2282        let params = WsPostOrderParamsBuilder::default()
2283            .inst_id_code(10459u64)
2284            .td_mode(OKXTradeMode::Cross)
2285            .side(OKXSide::Buy)
2286            .ord_type(OKXOrderType::Market)
2287            .sz("0.01".to_string())
2288            .slippage_pct("0.005".to_string())
2289            .build()
2290            .unwrap();
2291
2292        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2293        assert_eq!(json["slippagePct"], "0.005");
2294    }
2295
2296    #[rstest]
2297    fn test_ws_post_order_params_omits_slippage_pct_when_unset() {
2298        use super::WsPostOrderParamsBuilder;
2299        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2300
2301        let params = WsPostOrderParamsBuilder::default()
2302            .inst_id_code(10459u64)
2303            .td_mode(OKXTradeMode::Cross)
2304            .side(OKXSide::Buy)
2305            .ord_type(OKXOrderType::Market)
2306            .sz("0.01".to_string())
2307            .build()
2308            .unwrap();
2309
2310        let json = serde_json::to_string(&params).unwrap();
2311        assert!(!json.contains("slippagePct"));
2312        assert!(!json.contains("tradeQuoteCcy"));
2313    }
2314
2315    #[rstest]
2316    fn test_ws_post_order_params_serializes_trade_quote_ccy_usd() {
2317        use super::WsPostOrderParamsBuilder;
2318        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2319
2320        let params = WsPostOrderParamsBuilder::default()
2321            .inst_id_code(20459u64)
2322            .td_mode(OKXTradeMode::Cash)
2323            .side(OKXSide::Buy)
2324            .ord_type(OKXOrderType::Limit)
2325            .sz("0.01".to_string())
2326            .px("100000".to_string())
2327            .trade_quote_ccy("USD")
2328            .build()
2329            .unwrap();
2330
2331        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2332        assert_eq!(json["instIdCode"], 20459);
2333        assert_eq!(json["tradeQuoteCcy"], "USD");
2334        assert!(json.get("instId").is_none());
2335    }
2336
2337    #[rstest]
2338    fn test_ws_post_order_params_serializes_trade_quote_ccy_usdc() {
2339        use super::WsPostOrderParamsBuilder;
2340        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2341
2342        let params = WsPostOrderParamsBuilder::default()
2343            .inst_id_code(20459u64)
2344            .td_mode(OKXTradeMode::Cash)
2345            .side(OKXSide::Buy)
2346            .ord_type(OKXOrderType::Limit)
2347            .sz("0.01".to_string())
2348            .px("100000".to_string())
2349            .trade_quote_ccy("USDC")
2350            .build()
2351            .unwrap();
2352
2353        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2354        assert_eq!(json["tradeQuoteCcy"], "USDC");
2355    }
2356
2357    #[rstest]
2358    fn test_ws_post_order_params_serializes_attached_tp_sl() {
2359        use super::{WsAttachAlgoOrdParamsBuilder, WsPostOrderParamsBuilder};
2360        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode, OKXTriggerType};
2361
2362        let params = WsPostOrderParamsBuilder::default()
2363            .inst_id_code(10459u64)
2364            .td_mode(OKXTradeMode::Cross)
2365            .side(OKXSide::Buy)
2366            .ord_type(OKXOrderType::Limit)
2367            .sz("0.01".to_string())
2368            .px("50000".to_string())
2369            .attach_algo_ords(vec![
2370                WsAttachAlgoOrdParamsBuilder::default()
2371                    .attach_algo_cl_ord_id("O-bracket-sl")
2372                    .sl_trigger_px("39000")
2373                    .sl_ord_px("-1")
2374                    .sl_trigger_px_type(OKXTriggerType::Last)
2375                    .build()
2376                    .unwrap(),
2377                WsAttachAlgoOrdParamsBuilder::default()
2378                    .attach_algo_cl_ord_id("O-bracket-tp")
2379                    .tp_trigger_px("41000")
2380                    .tp_ord_px("-1")
2381                    .tp_trigger_px_type(OKXTriggerType::Last)
2382                    .build()
2383                    .unwrap(),
2384            ])
2385            .build()
2386            .unwrap();
2387
2388        let json = serde_json::to_string(&params).unwrap();
2389
2390        assert!(json.contains("\"attachAlgoOrds\""));
2391        assert!(json.contains("\"attachAlgoClOrdId\":\"O-bracket-sl\""));
2392        assert!(json.contains("\"slTriggerPx\":\"39000\""));
2393        assert!(json.contains("\"slOrdPx\":\"-1\""));
2394        assert!(json.contains("\"attachAlgoClOrdId\":\"O-bracket-tp\""));
2395        assert!(json.contains("\"tpTriggerPx\":\"41000\""));
2396        assert!(json.contains("\"tpOrdPx\":\"-1\""));
2397    }
2398
2399    #[rstest]
2400    fn test_ws_cancel_order_params_serializes_inst_id_code() {
2401        use super::WsCancelOrderParamsBuilder;
2402
2403        let params = WsCancelOrderParamsBuilder::default()
2404            .inst_id_code(10461u64)
2405            .ord_id("12345678".to_string())
2406            .build()
2407            .unwrap();
2408
2409        let json = serde_json::to_string(&params).unwrap();
2410
2411        assert!(json.contains("\"instIdCode\":10461"));
2412        assert!(!json.contains("\"instId\""));
2413        assert!(json.contains("\"ordId\":\"12345678\""));
2414    }
2415
2416    #[rstest]
2417    fn test_ws_amend_order_params_serializes_inst_id_code() {
2418        use super::WsAmendOrderParamsBuilder;
2419
2420        let params = WsAmendOrderParamsBuilder::default()
2421            .inst_id_code(10459u64)
2422            .cl_ord_id("client123".to_string())
2423            .new_px("51000".to_string())
2424            .build()
2425            .unwrap();
2426
2427        let json = serde_json::to_string(&params).unwrap();
2428
2429        assert!(json.contains("\"instIdCode\":10459"));
2430        assert!(!json.contains("\"instId\""));
2431        assert!(json.contains("\"newPx\":\"51000\""));
2432    }
2433
2434    #[rstest]
2435    fn test_ws_post_algo_order_params_serializes_inst_id_code() {
2436        use super::WsPostAlgoOrderParamsBuilder;
2437        use crate::common::enums::{OKXAlgoOrderType, OKXSide, OKXTradeMode, OKXTriggerType};
2438
2439        let params = WsPostAlgoOrderParamsBuilder::default()
2440            .inst_id_code(10459u64)
2441            .td_mode(OKXTradeMode::Cross)
2442            .side(OKXSide::Buy)
2443            .ord_type(OKXAlgoOrderType::Trigger)
2444            .sz("0.01".to_string())
2445            .trigger_px("48000".to_string())
2446            .trigger_px_type(OKXTriggerType::Last)
2447            .build()
2448            .unwrap();
2449
2450        let json = serde_json::to_string(&params).unwrap();
2451
2452        assert!(json.contains("\"instIdCode\":10459"));
2453        assert!(!json.contains("\"instId\""));
2454        assert!(json.contains("\"triggerPx\":\"48000\""));
2455    }
2456
2457    #[rstest]
2458    fn test_ws_cancel_algo_order_params_serializes_inst_id_code() {
2459        let params = WsCancelAlgoOrderParams {
2460            inst_id_code: 10459,
2461            algo_id: Some("987654321".to_string()),
2462            algo_cl_ord_id: None,
2463        };
2464
2465        let json = serde_json::to_string(&params).unwrap();
2466
2467        assert!(json.contains("\"instIdCode\":10459"));
2468        assert!(!json.contains("\"instId\""));
2469        assert!(json.contains("\"algoId\":\"987654321\""));
2470    }
2471
2472    #[rstest]
2473    fn test_ws_cancel_algo_order_params_builder_allows_either_identifier() {
2474        use super::WsCancelAlgoOrderParamsBuilder;
2475
2476        let by_cl_ord_id = WsCancelAlgoOrderParamsBuilder::default()
2477            .inst_id_code(10459u64)
2478            .algo_cl_ord_id("Odstalgocancel0000001".to_string())
2479            .build()
2480            .unwrap();
2481        let json = serde_json::to_value(&by_cl_ord_id).unwrap();
2482        assert_eq!(json["algoClOrdId"], "Odstalgocancel0000001");
2483        assert!(json.get("algoId").is_none());
2484
2485        let by_algo_id = WsCancelAlgoOrderParamsBuilder::default()
2486            .inst_id_code(10459u64)
2487            .algo_id("987654321".to_string())
2488            .build()
2489            .unwrap();
2490        let json = serde_json::to_value(&by_algo_id).unwrap();
2491        assert_eq!(json["algoId"], "987654321");
2492        assert!(json.get("algoClOrdId").is_none());
2493    }
2494
2495    #[rstest]
2496    fn test_ws_post_order_params_serializes_px_usd() {
2497        use super::WsPostOrderParamsBuilder;
2498        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2499
2500        let params = WsPostOrderParamsBuilder::default()
2501            .inst_id_code(10459u64)
2502            .td_mode(OKXTradeMode::Cross)
2503            .side(OKXSide::Buy)
2504            .ord_type(OKXOrderType::Limit)
2505            .sz("1".to_string())
2506            .px_usd("100.5".to_string())
2507            .build()
2508            .unwrap();
2509
2510        let json = serde_json::to_string(&params).unwrap();
2511        assert!(json.contains("\"pxUsd\":\"100.5\""));
2512        assert!(!json.contains("\"pxVol\""));
2513        assert!(!json.contains("\"px\":"));
2514    }
2515
2516    #[rstest]
2517    fn test_ws_post_order_params_serializes_px_vol() {
2518        use super::WsPostOrderParamsBuilder;
2519        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2520
2521        let params = WsPostOrderParamsBuilder::default()
2522            .inst_id_code(10459u64)
2523            .td_mode(OKXTradeMode::Cross)
2524            .side(OKXSide::Buy)
2525            .ord_type(OKXOrderType::Limit)
2526            .sz("1".to_string())
2527            .px_vol("0.55".to_string())
2528            .build()
2529            .unwrap();
2530
2531        let json = serde_json::to_string(&params).unwrap();
2532        assert!(json.contains("\"pxVol\":\"0.55\""));
2533        assert!(!json.contains("\"pxUsd\""));
2534        assert!(!json.contains("\"px\":"));
2535    }
2536
2537    #[rstest]
2538    fn test_ws_amend_order_params_serializes_new_px_usd() {
2539        use super::WsAmendOrderParamsBuilder;
2540
2541        let params = WsAmendOrderParamsBuilder::default()
2542            .inst_id_code(10459u64)
2543            .cl_ord_id("client123".to_string())
2544            .new_px_usd("105.0".to_string())
2545            .build()
2546            .unwrap();
2547
2548        let json = serde_json::to_string(&params).unwrap();
2549        assert!(json.contains("\"newPxUsd\":\"105.0\""));
2550        assert!(!json.contains("\"newPx\":"));
2551        assert!(!json.contains("\"newPxVol\""));
2552    }
2553
2554    #[rstest]
2555    fn test_ws_amend_order_params_serializes_new_px_vol() {
2556        use super::WsAmendOrderParamsBuilder;
2557
2558        let params = WsAmendOrderParamsBuilder::default()
2559            .inst_id_code(10459u64)
2560            .cl_ord_id("client123".to_string())
2561            .new_px_vol("0.60".to_string())
2562            .build()
2563            .unwrap();
2564
2565        let json = serde_json::to_string(&params).unwrap();
2566        assert!(json.contains("\"newPxVol\":\"0.60\""));
2567        assert!(!json.contains("\"newPx\":"));
2568        assert!(!json.contains("\"newPxUsd\""));
2569    }
2570
2571    #[rstest]
2572    fn test_ws_event_contract_markets_channel_serialization() {
2573        let json = serde_json::to_string(&OKXWsChannel::EventContractMarkets).unwrap();
2574        let channel: OKXWsChannel = serde_json::from_str(&json).unwrap();
2575
2576        assert_eq!(json, "\"event-contract-markets\"");
2577        assert_eq!(channel, OKXWsChannel::EventContractMarkets);
2578    }
2579
2580    #[rstest]
2581    fn test_ws_post_order_params_serializes_event_contract_fields() {
2582        use super::WsPostOrderParamsBuilder;
2583        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2584
2585        let params = WsPostOrderParamsBuilder::default()
2586            .inst_id_code(10459u64)
2587            .td_mode(OKXTradeMode::Cash)
2588            .side(OKXSide::Buy)
2589            .ord_type(OKXOrderType::Limit)
2590            .sz("10".to_string())
2591            .px("0.42".to_string())
2592            .outcome("yes")
2593            .build()
2594            .unwrap();
2595
2596        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2597
2598        assert!(json.get("speedBump").is_none());
2599        assert_eq!(json["outcome"], "yes");
2600    }
2601
2602    #[rstest]
2603    fn test_ws_amend_order_params_omits_speed_bump() {
2604        use super::WsAmendOrderParamsBuilder;
2605
2606        let params = WsAmendOrderParamsBuilder::default()
2607            .inst_id_code(10459u64)
2608            .cl_ord_id("event-1".to_string())
2609            .new_px("0.43".to_string())
2610            .build()
2611            .unwrap();
2612
2613        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2614
2615        assert_eq!(
2616            json,
2617            serde_json::json!({
2618                "instIdCode": 10459,
2619                "clOrdId": "event-1",
2620                "newPx": "0.43",
2621            })
2622        );
2623    }
2624
2625    #[rstest]
2626    fn test_ws_attach_algo_ord_params_serializes_trailing_fields() {
2627        use super::WsAttachAlgoOrdParamsBuilder;
2628
2629        let params = WsAttachAlgoOrdParamsBuilder::default()
2630            .attach_algo_cl_ord_id("trail-1")
2631            .callback_ratio("0.01")
2632            .active_px("64000")
2633            .new_callback_ratio("0.02")
2634            .new_callback_spread("25")
2635            .new_active_px("65000")
2636            .build()
2637            .unwrap();
2638
2639        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2640
2641        assert_eq!(json["callbackRatio"], "0.01");
2642        assert_eq!(json["activePx"], "64000");
2643        assert_eq!(json["newCallbackRatio"], "0.02");
2644        assert_eq!(json["newCallbackSpread"], "25");
2645        assert_eq!(json["newActivePx"], "65000");
2646        assert!(json.get("callbackSpread").is_none());
2647    }
2648
2649    #[rstest]
2650    #[case::positions(
2651        OKXWsChannel::Positions,
2652        serde_json::json!({
2653            "channel":"positions",
2654            "instType":"SWAP",
2655            "extraParams":serde_json::json!({"updateInterval":"0"}).to_string(),
2656        }),
2657    )]
2658    #[case::orders(
2659        OKXWsChannel::Orders,
2660        serde_json::json!({"channel":"orders", "instType":"SWAP"}),
2661    )]
2662    fn test_subscription_arg_update_interval(
2663        #[case] channel: OKXWsChannel,
2664        #[case] expected: serde_json::Value,
2665    ) {
2666        let arg = OKXSubscriptionArg {
2667            channel,
2668            inst_type: Some(OKXInstrumentType::Swap),
2669            inst_family: None,
2670            inst_id: None,
2671        };
2672
2673        let actual = serde_json::to_value(&arg).unwrap();
2674
2675        assert_eq!(actual, expected);
2676    }
2677
2678    #[rstest]
2679    fn test_subscription_arg_serializes_sprd_id_for_spread_channels() {
2680        let arg = OKXSubscriptionArg {
2681            channel: OKXWsChannel::SprdBooks5,
2682            inst_type: None,
2683            inst_family: None,
2684            inst_id: Some(Ustr::from("ETH-USD-260925_ETH-USD-261225")),
2685        };
2686        let json = serde_json::to_value(&arg).unwrap();
2687        assert_eq!(json["channel"], "sprd-books5");
2688        assert_eq!(json["sprdId"], "ETH-USD-260925_ETH-USD-261225");
2689        assert!(json.get("instId").is_none());
2690    }
2691
2692    #[rstest]
2693    fn test_subscription_arg_serializes_inst_id_for_standard_channels() {
2694        let arg = OKXSubscriptionArg {
2695            channel: OKXWsChannel::BboTbt,
2696            inst_type: None,
2697            inst_family: None,
2698            inst_id: Some(Ustr::from("BTC-USDT")),
2699        };
2700        let json = serde_json::to_value(&arg).unwrap();
2701        assert_eq!(json["instId"], "BTC-USDT");
2702        assert!(json.get("sprdId").is_none());
2703    }
2704
2705    #[rstest]
2706    fn test_websocket_arg_resolves_sprd_id_into_inst_id() {
2707        let arg: OKXWebSocketArg = serde_json::from_value(serde_json::json!({
2708            "channel": "sprd-bbo-tbt",
2709            "sprdId": "ETH-USD-260925_ETH-USD-261225",
2710        }))
2711        .unwrap();
2712        assert_eq!(arg.channel, OKXWsChannel::SprdBboTbt);
2713        assert_eq!(
2714            arg.inst_id,
2715            Some(Ustr::from("ETH-USD-260925_ETH-USD-261225"))
2716        );
2717    }
2718
2719    #[rstest]
2720    fn test_book_msg_parses_three_element_spread_levels() {
2721        // sprd-books5 levels are [price, size, count] (3 elements), unlike the
2722        // 4-element standard book levels.
2723        let msg: OKXBookMsg = serde_json::from_value(serde_json::json!({
2724            "asks": [["16.7", "100", "1"]],
2725            "bids": [["16.65", "100", "1"]],
2726            "ts": "1780044924909",
2727            "seqId": 1_779_935_772_619_784_u64,
2728        }))
2729        .unwrap();
2730        assert_eq!(msg.asks[0].price, "16.7");
2731        assert_eq!(msg.asks[0].size, "100");
2732        assert_eq!(msg.bids[0].price, "16.65");
2733    }
2734
2735    #[rstest]
2736    fn test_trade_msg_parses_spread_public_trade() {
2737        // sprd-public-trades keys the instrument as `sprdId` and omits `count`.
2738        let msg: OKXTradeMsg = serde_json::from_value(serde_json::json!({
2739            "sprdId": "ETH-USD-260925_ETH-USD-261225",
2740            "tradeId": "3392538740127301632",
2741            "px": "16.9",
2742            "sz": "100",
2743            "side": "sell",
2744            "ts": "1780047866507",
2745        }))
2746        .unwrap();
2747        assert_eq!(msg.inst_id, Ustr::from("ETH-USD-260925_ETH-USD-261225"));
2748        assert_eq!(msg.px, "16.9");
2749        assert_eq!(msg.side, OKXSide::Sell);
2750        assert!(msg.count.is_empty());
2751    }
2752}