Skip to main content

nautilus_okx/websocket/
subscription.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//! OKX subscription topic construction.
17
18use nautilus_network::websocket::SubscriptionState;
19use ustr::Ustr;
20
21use crate::{
22    common::{consts::OKX_WS_TOPIC_DELIMITER, enums::OKXInstrumentType},
23    websocket::{
24        enums::OKXWsChannel,
25        messages::{OKXSubscriptionArg, OKXWebSocketArg},
26    },
27};
28
29fn topic_from_parts(
30    channel: &OKXWsChannel,
31    inst_id: Option<&Ustr>,
32    inst_family: Option<&Ustr>,
33    inst_type: Option<&OKXInstrumentType>,
34    bar: Option<&Ustr>,
35) -> String {
36    let base = channel.as_ref();
37
38    if let Some(inst_id) = inst_id {
39        let inst_id = inst_id.as_str();
40
41        if let Some(bar) = bar {
42            format!("{base}:{inst_id}:{}", bar.as_str())
43        } else {
44            format!("{base}:{inst_id}")
45        }
46    } else if let Some(inst_family) = inst_family {
47        format!("{base}:{}", inst_family.as_str())
48    } else if let Some(inst_type) = inst_type {
49        format!("{base}:{}", inst_type.as_ref())
50    } else {
51        base.to_string()
52    }
53}
54
55pub(crate) fn topic_from_subscription_arg(arg: &OKXSubscriptionArg) -> String {
56    topic_from_parts(
57        &arg.channel,
58        arg.inst_id.as_ref(),
59        arg.inst_family.as_ref(),
60        arg.inst_type.as_ref(),
61        None,
62    )
63}
64
65pub(crate) fn topic_from_websocket_arg(arg: &OKXWebSocketArg) -> String {
66    topic_from_parts(
67        &arg.channel,
68        arg.inst_id.as_ref(),
69        arg.inst_family.as_ref(),
70        arg.inst_type.as_ref(),
71        arg.bar.as_ref(),
72    )
73}
74
75pub(super) fn is_topic_subscribed(state: &SubscriptionState, topic: &str) -> bool {
76    let (channel, symbol) = topic
77        .split_once(OKX_WS_TOPIC_DELIMITER)
78        .unwrap_or((topic, ""));
79
80    let (Some(channel), Some(symbol)) = (Ustr::from_existing(channel), Ustr::from_existing(symbol))
81    else {
82        return false;
83    };
84
85    state.is_subscribed(&channel, &symbol)
86}