Skip to main content

nautilus_okx/
factories.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//! Factory functions for creating OKX clients and components.
17
18use std::{any::Any, cell::RefCell, rc::Rc};
19
20use nautilus_common::{
21    cache::CacheView,
22    clients::{DataClient, ExecutionClient},
23    clock::Clock,
24    factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
25    live::runner::try_get_exec_event_sender,
26};
27use nautilus_live::ExecutionClientCore;
28use nautilus_model::{
29    enums::{AccountType, OmsType},
30    identifiers::{ClientId, TraderId},
31};
32
33use crate::{
34    common::{
35        consts::{OKX, OKX_VENUE},
36        enums::OKXInstrumentType,
37    },
38    config::{OKXDataClientConfig, OKXExecutionClientConfig},
39    data::OKXDataClient,
40    execution::OKXExecutionClient,
41};
42
43impl ClientConfig for OKXDataClientConfig {
44    fn as_any(&self) -> &dyn Any {
45        self
46    }
47}
48
49impl ClientConfig for OKXExecutionClientConfig {
50    fn as_any(&self) -> &dyn Any {
51        self
52    }
53}
54
55/// Factory for creating OKX data clients.
56#[derive(Debug, Clone)]
57#[cfg_attr(
58    feature = "python",
59    pyo3::pyclass(module = "nautilus_trader.adapters.okx", from_py_object)
60)]
61#[cfg_attr(
62    feature = "python",
63    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
64)]
65pub struct OKXDataClientFactory;
66
67impl OKXDataClientFactory {
68    /// Creates a new [`OKXDataClientFactory`] instance.
69    #[must_use]
70    pub const fn new() -> Self {
71        Self
72    }
73}
74
75impl Default for OKXDataClientFactory {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl DataClientFactory for OKXDataClientFactory {
82    fn create(
83        &self,
84        name: &str,
85        config: &dyn ClientConfig,
86        _cache: CacheView,
87        _clock: Rc<RefCell<dyn Clock>>,
88    ) -> anyhow::Result<Box<dyn DataClient>> {
89        let okx_config = config
90            .as_any()
91            .downcast_ref::<OKXDataClientConfig>()
92            .ok_or_else(|| {
93                anyhow::anyhow!(
94                    "Invalid config type for OKXDataClientFactory. Expected OKXDataClientConfig, was {config:?}",
95                )
96            })?
97            .clone();
98
99        let client_id = ClientId::from(name);
100        let client = OKXDataClient::new(client_id, okx_config)?;
101        Ok(Box::new(client))
102    }
103
104    fn name(&self) -> &'static str {
105        OKX
106    }
107
108    fn config_type(&self) -> &'static str {
109        "OKXDataClientConfig"
110    }
111}
112
113/// Factory for creating OKX execution clients.
114#[derive(Debug, Clone)]
115#[cfg_attr(
116    feature = "python",
117    pyo3::pyclass(module = "nautilus_trader.adapters.okx", from_py_object)
118)]
119#[cfg_attr(
120    feature = "python",
121    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.okx")
122)]
123pub struct OKXExecutionClientFactory;
124
125impl OKXExecutionClientFactory {
126    /// Creates a new [`OKXExecutionClientFactory`] instance.
127    #[must_use]
128    pub const fn new() -> Self {
129        Self
130    }
131}
132
133impl Default for OKXExecutionClientFactory {
134    fn default() -> Self {
135        Self::new()
136    }
137}
138
139impl ExecutionClientFactory for OKXExecutionClientFactory {
140    fn create(
141        &self,
142        trader_id: TraderId,
143        name: &str,
144        config: &dyn ClientConfig,
145        cache: CacheView,
146        _clock: Rc<RefCell<dyn Clock>>,
147    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
148        let okx_config = config
149            .as_any()
150            .downcast_ref::<OKXExecutionClientConfig>()
151            .ok_or_else(|| {
152                anyhow::anyhow!(
153                    "Invalid config type for OKXExecutionClientFactory. Expected OKXExecutionClientConfig, was {config:?}",
154                )
155            })?
156            .clone();
157
158        let has_derivatives = okx_config.instrument_types.iter().any(|t| {
159            matches!(
160                t,
161                OKXInstrumentType::Swap | OKXInstrumentType::Futures | OKXInstrumentType::Option
162            )
163        });
164
165        let account_type = if okx_config.uses_spot_margin() || has_derivatives {
166            AccountType::Margin
167        } else {
168            AccountType::Cash
169        };
170
171        let oms_type = okx_config.oms_type.unwrap_or(if has_derivatives {
172            OmsType::Netting
173        } else {
174            OmsType::Hedging
175        });
176
177        let core = ExecutionClientCore::new(
178            trader_id,
179            ClientId::from(name),
180            *OKX_VENUE,
181            oms_type,
182            okx_config.account_id,
183            account_type,
184            None, // base_currency
185            cache,
186        );
187
188        let mut client = OKXExecutionClient::new(core, okx_config)?;
189        if let Some(sender) = try_get_exec_event_sender() {
190            client.set_event_sender(sender);
191        }
192
193        Ok(Box::new(client))
194    }
195
196    fn name(&self) -> &'static str {
197        OKX
198    }
199
200    fn config_type(&self) -> &'static str {
201        "OKXExecutionClientConfig"
202    }
203}