1use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
19
20use log;
21use nautilus_common::{
22 cache::CacheView,
23 clients::{DataClient, ExecutionClient},
24 clock::Clock,
25 factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
26};
27use nautilus_live::ExecutionClientCore;
28use nautilus_model::{
29 enums::{AccountType, OmsType},
30 identifiers::{ClientId, TraderId},
31};
32use nautilus_network::retry::RetryConfig;
33
34use crate::{
35 common::{
36 consts::{DYDX, DYDX_VENUE},
37 credential::{DydxCredential, resolve_wallet_address},
38 instrument_cache::InstrumentCache,
39 urls,
40 },
41 config::{DydxAdapterConfig, DydxDataClientConfig, DydxExecutionClientConfig},
42 data::DydxDataClient,
43 execution::DydxExecutionClient,
44 http::client::DydxHttpClient,
45 websocket::client::DydxWebSocketClient,
46};
47
48impl ClientConfig for DydxDataClientConfig {
49 fn as_any(&self) -> &dyn Any {
50 self
51 }
52}
53
54impl ClientConfig for DydxExecutionClientConfig {
55 fn as_any(&self) -> &dyn Any {
56 self
57 }
58}
59
60#[derive(Debug, Clone)]
62#[cfg_attr(
63 feature = "python",
64 pyo3::pyclass(module = "nautilus_trader.adapters.dydx", from_py_object)
65)]
66#[cfg_attr(
67 feature = "python",
68 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.dydx")
69)]
70pub struct DydxDataClientFactory;
71
72impl DydxDataClientFactory {
73 #[must_use]
75 pub const fn new() -> Self {
76 Self
77 }
78}
79
80impl Default for DydxDataClientFactory {
81 fn default() -> Self {
82 Self::new()
83 }
84}
85
86impl DataClientFactory for DydxDataClientFactory {
87 fn create(
88 &self,
89 name: &str,
90 config: &dyn ClientConfig,
91 _cache: CacheView,
92 _clock: Rc<RefCell<dyn Clock>>,
93 ) -> anyhow::Result<Box<dyn DataClient>> {
94 let dydx_config = config
95 .as_any()
96 .downcast_ref::<DydxDataClientConfig>()
97 .ok_or_else(|| {
98 anyhow::anyhow!(
99 "Invalid config type for DydxDataClientFactory. Expected DydxDataClientConfig, was {config:?}",
100 )
101 })?
102 .clone();
103
104 let client_id = ClientId::from(name);
105
106 let http_url = dydx_config
107 .base_url_http
108 .clone()
109 .unwrap_or_else(|| urls::http_base_url(dydx_config.network).to_string());
110 let ws_url = dydx_config
111 .base_url_ws
112 .clone()
113 .unwrap_or_else(|| urls::ws_url(dydx_config.network).to_string());
114
115 let retry_config = Some(RetryConfig {
116 max_retries: dydx_config.max_retries as u32,
117 initial_delay_ms: dydx_config.retry_delay_initial_ms,
118 max_delay_ms: dydx_config.retry_delay_max_ms,
119 ..Default::default()
120 });
121 let proxy_url = dydx_config
122 .proxy_url
123 .as_ref()
124 .map(|value| value.expose_secret().to_owned());
125
126 let http_client = DydxHttpClient::new(
127 Some(http_url),
128 dydx_config.http_timeout_secs,
129 proxy_url.clone(),
130 dydx_config.network,
131 retry_config,
132 )?;
133
134 let ws_client = DydxWebSocketClient::new_public_with_cache_and_pool(
135 ws_url,
136 Arc::new(InstrumentCache::new()),
137 Some(20),
138 dydx_config.transport_backend,
139 proxy_url,
140 dydx_config.max_ws_connections,
141 dydx_config.per_channel_subscription_limit,
142 );
143
144 let client = DydxDataClient::new(client_id, dydx_config, http_client, ws_client)?;
145 Ok(Box::new(client))
146 }
147
148 fn name(&self) -> &'static str {
149 DYDX
150 }
151
152 fn config_type(&self) -> &'static str {
153 "DydxDataClientConfig"
154 }
155}
156
157#[derive(Debug, Clone)]
159#[cfg_attr(
160 feature = "python",
161 pyo3::pyclass(module = "nautilus_trader.adapters.dydx", from_py_object)
162)]
163#[cfg_attr(
164 feature = "python",
165 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.dydx")
166)]
167pub struct DydxExecutionClientFactory;
168
169impl DydxExecutionClientFactory {
170 #[must_use]
172 pub const fn new() -> Self {
173 Self
174 }
175}
176
177impl Default for DydxExecutionClientFactory {
178 fn default() -> Self {
179 Self::new()
180 }
181}
182
183impl ExecutionClientFactory for DydxExecutionClientFactory {
184 fn create(
185 &self,
186 trader_id: TraderId,
187 name: &str,
188 config: &dyn ClientConfig,
189 cache: CacheView,
190 _clock: Rc<RefCell<dyn Clock>>,
191 ) -> anyhow::Result<Box<dyn ExecutionClient>> {
192 let dydx_config = config
193 .as_any()
194 .downcast_ref::<DydxExecutionClientConfig>()
195 .ok_or_else(|| {
196 anyhow::anyhow!(
197 "Invalid config type for DydxExecutionClientFactory. Expected DydxExecutionClientConfig, was {config:?}",
198 )
199 })?
200 .clone();
201
202 let oms_type = OmsType::Netting;
204
205 let account_type = AccountType::Margin;
207
208 let core = ExecutionClientCore::new(
209 trader_id,
210 ClientId::from(name),
211 *DYDX_VENUE,
212 oms_type,
213 dydx_config.account_id,
214 account_type,
215 None, cache,
217 );
218
219 let adapter_config = DydxAdapterConfig {
220 network: dydx_config.network,
221 base_url: dydx_config.get_http_url(),
222 ws_url: dydx_config.get_ws_url(),
223 grpc_url: dydx_config
224 .get_grpc_urls()
225 .first()
226 .cloned()
227 .unwrap_or_default(),
228 grpc_urls: dydx_config.get_grpc_urls(),
229 chain_id: dydx_config.get_chain_id().to_string(),
230 timeout_secs: dydx_config.http_timeout_secs.unwrap_or(30),
231 wallet_address: dydx_config.wallet_address.clone(),
232 subaccount: dydx_config.subaccount_number,
233 private_key: dydx_config.private_key.clone(),
234 authenticator_ids: dydx_config.authenticator_ids.clone(),
235 max_retries: dydx_config.max_retries.unwrap_or(3),
236 retry_delay_initial_ms: dydx_config.retry_delay_initial_ms.unwrap_or(1000),
237 retry_delay_max_ms: dydx_config.retry_delay_max_ms.unwrap_or(10000),
238 grpc_rate_limit_per_second: dydx_config.grpc_rate_limit_per_second,
239 proxy_url: dydx_config.proxy_url.clone(),
240 transport_backend: dydx_config.transport_backend,
241 };
242
243 log::debug!(
244 "Resolving wallet address: config={:?}, network={}, env_var={}",
245 dydx_config.wallet_address,
246 dydx_config.network,
247 if dydx_config.is_testnet() {
248 "DYDX_TESTNET_WALLET_ADDRESS"
249 } else {
250 "DYDX_WALLET_ADDRESS"
251 }
252 );
253 let wallet_address = if let Some(addr) =
254 resolve_wallet_address(dydx_config.wallet_address.clone(), dydx_config.network)
255 {
256 log::debug!("Using wallet address from config/env: {addr}");
257 addr
258 } else if let Some(credential) = DydxCredential::resolve(
259 dydx_config
260 .private_key
261 .as_ref()
262 .map(|value| value.expose_secret()),
263 dydx_config.network,
264 dydx_config.authenticator_ids.clone(),
265 )? {
266 log::debug!(
267 "Derived wallet address from private key: {}",
268 credential.address
269 );
270 credential.address
271 } else {
272 anyhow::bail!(
273 "No wallet credentials found: set wallet_address or private_key in config, or use environment variables (DYDX_WALLET_ADDRESS/DYDX_PRIVATE_KEY for mainnet, DYDX_TESTNET_* for testnet)"
274 )
275 };
276
277 let client = DydxExecutionClient::new(
278 core,
279 adapter_config,
280 wallet_address,
281 dydx_config.subaccount_number,
282 )?;
283
284 Ok(Box::new(client))
285 }
286
287 fn name(&self) -> &'static str {
288 DYDX
289 }
290
291 fn config_type(&self) -> &'static str {
292 "DydxExecutionClientConfig"
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use std::{cell::RefCell, rc::Rc};
299
300 use nautilus_common::{
301 cache::Cache,
302 clock::VirtualClock,
303 factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
304 };
305 use nautilus_model::identifiers::{AccountId, TraderId};
306 use rstest::rstest;
307
308 use super::*;
309 use crate::{
310 common::enums::DydxNetwork,
311 config::{DydxDataClientConfig, DydxExecutionClientConfig},
312 };
313
314 #[rstest]
315 fn test_dydx_data_client_factory_creation() {
316 let factory = DydxDataClientFactory::new();
317 assert_eq!(factory.name(), DYDX);
318 assert_eq!(factory.config_type(), "DydxDataClientConfig");
319 }
320
321 #[rstest]
322 fn test_dydx_data_client_factory_default() {
323 let factory = DydxDataClientFactory;
324 assert_eq!(factory.name(), DYDX);
325 }
326
327 #[rstest]
328 fn test_dydx_execution_client_factory_creation() {
329 let factory = DydxExecutionClientFactory::new();
330 assert_eq!(factory.name(), DYDX);
331 assert_eq!(factory.config_type(), "DydxExecutionClientConfig");
332 }
333
334 #[rstest]
335 fn test_dydx_execution_client_factory_default() {
336 let factory = DydxExecutionClientFactory;
337 assert_eq!(factory.name(), DYDX);
338 }
339
340 #[rstest]
341 fn test_dydx_data_client_config_implements_client_config() {
342 let config = DydxDataClientConfig::default();
343 let boxed_config: Box<dyn ClientConfig> = Box::new(config);
344 let downcasted = boxed_config.as_any().downcast_ref::<DydxDataClientConfig>();
345
346 assert!(downcasted.is_some());
347 }
348
349 #[rstest]
350 fn test_dydx_exec_client_config_implements_client_config() {
351 let config = DydxExecutionClientConfig {
352 account_id: AccountId::from("DYDX-001"),
353 network: DydxNetwork::Mainnet,
354 grpc_endpoint: None,
355 grpc_urls: vec![],
356 ws_endpoint: None,
357 http_endpoint: None,
358 private_key: None,
359 wallet_address: Some("dydx1abc123".to_string()),
360 subaccount_number: 0,
361 authenticator_ids: vec![],
362 http_timeout_secs: None,
363 max_retries: None,
364 retry_delay_initial_ms: None,
365 retry_delay_max_ms: None,
366 grpc_rate_limit_per_second: Some(4),
367 proxy_url: None,
368 transport_backend: Default::default(),
369 };
370
371 let boxed_config: Box<dyn ClientConfig> = Box::new(config);
372 let downcasted = boxed_config
373 .as_any()
374 .downcast_ref::<DydxExecutionClientConfig>();
375
376 assert!(downcasted.is_some());
377 }
378
379 #[rstest]
380 fn test_dydx_data_client_factory_rejects_wrong_config_type() {
381 let factory = DydxDataClientFactory::new();
382 let wrong_config = DydxExecutionClientConfig {
383 account_id: AccountId::from("DYDX-001"),
384 network: DydxNetwork::Mainnet,
385 grpc_endpoint: None,
386 grpc_urls: vec![],
387 ws_endpoint: None,
388 http_endpoint: None,
389 private_key: None,
390 wallet_address: None,
391 subaccount_number: 0,
392 authenticator_ids: vec![],
393 http_timeout_secs: None,
394 max_retries: None,
395 retry_delay_initial_ms: None,
396 retry_delay_max_ms: None,
397 grpc_rate_limit_per_second: Some(4),
398 proxy_url: None,
399 transport_backend: Default::default(),
400 };
401
402 let cache = Rc::new(RefCell::new(Cache::default()));
403 let clock = Rc::new(RefCell::new(VirtualClock::new()));
404
405 let result = factory.create("DYDX-TEST", &wrong_config, cache.into(), clock);
406 assert!(result.is_err());
407 assert!(
408 result
409 .err()
410 .unwrap()
411 .to_string()
412 .contains("Invalid config type")
413 );
414 }
415
416 #[rstest]
417 fn test_dydx_execution_client_factory_rejects_wrong_config_type() {
418 let factory = DydxExecutionClientFactory::new();
419 let wrong_config = DydxDataClientConfig::default();
420
421 let cache = Rc::new(RefCell::new(Cache::default()));
422
423 let result = factory.create(
424 TraderId::from("TRADER-001"),
425 "DYDX-TEST",
426 &wrong_config,
427 cache.into(),
428 Rc::new(RefCell::new(VirtualClock::new())),
429 );
430 assert!(result.is_err());
431 assert!(
432 result
433 .err()
434 .unwrap()
435 .to_string()
436 .contains("Invalid config type")
437 );
438 }
439}