Skip to main content

rust_okx/ws/ops/
raw.rs

1//! Generic WebSocket operation transport.
2
3use serde::Serialize;
4
5use crate::Error;
6use crate::ws::WsError;
7use crate::ws::client::OkxWs;
8use crate::ws::conn::WsConnector;
9use crate::ws::request::OperationRequest;
10
11impl<C: WsConnector> OkxWs<C> {
12    /// Send a raw WebSocket operation request.
13    ///
14    /// The response is returned asynchronously through
15    /// [`WsEvent::Operation`](crate::ws::WsEvent::Operation).
16    ///
17    /// OKX docs: <https://www.okx.com/docs-v5/en/#overview-websocket>
18    pub async fn send_request<A: Serialize>(
19        &mut self,
20        id: impl Into<String>,
21        op: impl Into<String>,
22        args: &[A],
23    ) -> Result<(), Error> {
24        self.send_request_with_expiry(id, op, None, args).await
25    }
26
27    /// Send a raw WebSocket operation request with an optional effective deadline.
28    ///
29    /// `exp_time` is a Unix timestamp in milliseconds. OKX discards the request
30    /// when it reaches the matching trading engine after this deadline.
31    ///
32    /// OKX docs: <https://www.okx.com/docs-v5/en/#overview-websocket>
33    pub async fn send_request_with_expiry<A: Serialize>(
34        &mut self,
35        id: impl Into<String>,
36        op: impl Into<String>,
37        exp_time: Option<String>,
38        args: &[A],
39    ) -> Result<(), Error> {
40        let payload = operation_payload_with_expiry(id, op, exp_time, args)?;
41        self.send_operation_payload(payload).await
42    }
43}
44
45pub(crate) fn operation_payload_with_expiry<A: Serialize>(
46    id: impl Into<String>,
47    op: impl Into<String>,
48    exp_time: Option<String>,
49    args: &[A],
50) -> Result<String, Error> {
51    let mut payload = OperationRequest::new(id, op, args);
52    if let Some(exp_time) = exp_time {
53        payload = payload.exp_time(exp_time);
54    }
55    serde_json::to_string(&payload)
56        .map_err(|e| WsError::Encode { source: e })
57        .map_err(Error::from)
58}