1use nautilus_common::python::config_error_to_pyvalue_err;
19use nautilus_core::string::secret::SecretString;
20use nautilus_model::identifiers::{AccountId, InstrumentId};
21use nautilus_network::websocket::TransportBackend;
22use pyo3::{PyResult, pymethods};
23use rust_decimal::Decimal;
24
25use crate::{
26 common::enums::DeriveEnvironment,
27 config::{DeriveDataClientConfig, DeriveExecutionClientConfig},
28};
29
30#[pymethods]
31#[pyo3_stub_gen::derive::gen_stub_pymethods]
32impl DeriveDataClientConfig {
33 #[new]
35 #[pyo3(signature = (
36 base_url_rest = None,
37 base_url_ws = None,
38 proxy_url = None,
39 environment = None,
40 http_timeout_secs = None,
41 ws_timeout_secs = None,
42 update_instruments_interval_mins = None,
43 currencies = None,
44 include_expired = None,
45 auto_load_missing_instruments = None,
46 transport_backend = None,
47 book_snapshot_timeout_secs = None,
48 book_stale_threshold_secs = None,
49 ))]
50 #[expect(clippy::too_many_arguments)]
51 fn py_new(
52 base_url_rest: Option<String>,
53 base_url_ws: Option<String>,
54 proxy_url: Option<String>,
55 environment: Option<DeriveEnvironment>,
56 http_timeout_secs: Option<u64>,
57 ws_timeout_secs: Option<u64>,
58 update_instruments_interval_mins: Option<u64>,
59 currencies: Option<Vec<String>>,
60 include_expired: Option<bool>,
61 auto_load_missing_instruments: Option<bool>,
62 transport_backend: Option<TransportBackend>,
63 book_snapshot_timeout_secs: Option<u64>,
64 book_stale_threshold_secs: Option<u64>,
65 ) -> PyResult<Self> {
66 let defaults = Self::default();
67
68 let config = Self {
69 base_url_rest: base_url_rest.map(SecretString::from),
70 base_url_ws: base_url_ws.map(SecretString::from),
71 proxy_url: proxy_url.map(SecretString::from),
72 environment: environment.unwrap_or(defaults.environment),
73 http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
74 ws_timeout_secs,
75 book_snapshot_timeout_secs: book_snapshot_timeout_secs
76 .unwrap_or(defaults.book_snapshot_timeout_secs),
77 book_stale_threshold_secs: book_stale_threshold_secs
78 .unwrap_or(defaults.book_stale_threshold_secs),
79 update_instruments_interval_mins: update_instruments_interval_mins
80 .unwrap_or(defaults.update_instruments_interval_mins),
81 currencies: currencies.unwrap_or(defaults.currencies),
82 include_expired: include_expired.unwrap_or(defaults.include_expired),
83 auto_load_missing_instruments: auto_load_missing_instruments
84 .unwrap_or(defaults.auto_load_missing_instruments),
85 transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
86 };
87
88 config.validate().map_err(config_error_to_pyvalue_err)?;
89 Ok(config)
90 }
91
92 #[getter]
93 fn base_url_rest(&self) -> Option<String> {
94 self.base_url_rest
95 .as_ref()
96 .map(|url| url.expose_secret().to_string())
97 }
98
99 #[getter]
100 fn base_url_ws(&self) -> Option<String> {
101 self.base_url_ws
102 .as_ref()
103 .map(|url| url.expose_secret().to_string())
104 }
105
106 #[getter]
107 const fn has_proxy_url(&self) -> bool {
108 self.proxy_url.is_some()
109 }
110
111 fn __repr__(&self) -> String {
112 stringify!(DeriveDataClientConfig).to_string()
113 }
114}
115
116#[pymethods]
117#[pyo3_stub_gen::derive::gen_stub_pymethods]
118impl DeriveExecutionClientConfig {
119 #[new]
121 #[pyo3(signature = (
122 account_id = None,
123 wallet_address = None,
124 session_key = None,
125 subaccount_id = None,
126 base_url_rest = None,
127 base_url_ws = None,
128 proxy_url = None,
129 environment = None,
130 http_timeout_secs = None,
131 max_retries = None,
132 retry_delay_initial_ms = None,
133 retry_delay_max_ms = None,
134 ws_timeout_secs = None,
135 max_fee_per_contract = None,
136 domain_separator = None,
137 action_typehash = None,
138 trade_module_address = None,
139 signature_expiry_secs = None,
140 market_order_slippage_bps = None,
141 max_matching_requests_per_second = None,
142 max_per_instrument_matching_requests_per_second = None,
143 transport_backend = None,
144 cancel_on_disconnect = None,
145 load_ids = None,
146 ))]
147 #[expect(clippy::too_many_arguments)]
148 fn py_new(
149 account_id: Option<AccountId>,
150 wallet_address: Option<String>,
151 session_key: Option<String>,
152 subaccount_id: Option<u64>,
153 base_url_rest: Option<String>,
154 base_url_ws: Option<String>,
155 proxy_url: Option<String>,
156 environment: Option<DeriveEnvironment>,
157 http_timeout_secs: Option<u64>,
158 max_retries: Option<u32>,
159 retry_delay_initial_ms: Option<u64>,
160 retry_delay_max_ms: Option<u64>,
161 ws_timeout_secs: Option<u64>,
162 max_fee_per_contract: Option<Decimal>,
163 domain_separator: Option<String>,
164 action_typehash: Option<String>,
165 trade_module_address: Option<String>,
166 signature_expiry_secs: Option<u64>,
167 market_order_slippage_bps: Option<u32>,
168 max_matching_requests_per_second: Option<u32>,
169 max_per_instrument_matching_requests_per_second: Option<u32>,
170 transport_backend: Option<TransportBackend>,
171 cancel_on_disconnect: Option<bool>,
172 load_ids: Option<Vec<InstrumentId>>,
173 ) -> PyResult<Self> {
174 let defaults = Self::default();
175
176 let config = Self {
177 account_id: account_id.unwrap_or(defaults.account_id),
178 wallet_address,
179 session_key: session_key.map(SecretString::from),
180 subaccount_id,
181 base_url_rest: base_url_rest.map(SecretString::from),
182 base_url_ws: base_url_ws.map(SecretString::from),
183 proxy_url: proxy_url.map(SecretString::from),
184 environment: environment.unwrap_or(defaults.environment),
185 http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
186 max_retries: max_retries.unwrap_or(defaults.max_retries),
187 retry_delay_initial_ms: retry_delay_initial_ms
188 .unwrap_or(defaults.retry_delay_initial_ms),
189 retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
190 ws_timeout_secs,
191 max_fee_per_contract,
192 transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
193 domain_separator,
194 action_typehash,
195 trade_module_address,
196 signature_expiry_secs: signature_expiry_secs.unwrap_or(defaults.signature_expiry_secs),
197 market_order_slippage_bps: market_order_slippage_bps
198 .unwrap_or(defaults.market_order_slippage_bps),
199 max_matching_requests_per_second,
200 max_per_instrument_matching_requests_per_second,
201 cancel_on_disconnect: cancel_on_disconnect.unwrap_or(defaults.cancel_on_disconnect),
202 load_ids,
203 };
204
205 config
206 .validate_load_ids()
207 .map_err(config_error_to_pyvalue_err)?;
208 Ok(config)
209 }
210
211 #[getter]
212 fn base_url_rest(&self) -> Option<String> {
213 self.base_url_rest
214 .as_ref()
215 .map(|url| url.expose_secret().to_string())
216 }
217
218 #[getter]
219 fn base_url_ws(&self) -> Option<String> {
220 self.base_url_ws
221 .as_ref()
222 .map(|url| url.expose_secret().to_string())
223 }
224
225 #[getter]
226 const fn has_proxy_url(&self) -> bool {
227 self.proxy_url.is_some()
228 }
229
230 fn __repr__(&self) -> String {
231 stringify!(DeriveExecutionClientConfig).to_string()
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use pyo3::{prelude::*, types::PyDict};
238 use rstest::rstest;
239
240 use super::*;
241
242 #[rstest]
243 #[case::unset(None)]
244 #[case::empty(Some(vec![]))]
245 #[case::explicit(Some(vec![InstrumentId::from("ETH-PERP.DERIVE"), InstrumentId::from("BTC-PERP.DERIVE")]))]
246 fn test_python_load_ids(#[case] load_ids: Option<Vec<InstrumentId>>) {
247 Python::initialize();
248 Python::attach(|py| {
249 let kwargs = PyDict::new(py);
250 kwargs.set_item("load_ids", load_ids.clone()).unwrap();
251 let config = py
252 .get_type::<DeriveExecutionClientConfig>()
253 .call((), Some(&kwargs))
254 .unwrap();
255 let getter = config
256 .getattr("load_ids")
257 .unwrap()
258 .extract::<Option<Vec<InstrumentId>>>()
259 .unwrap();
260 let rust_config = config
261 .extract::<PyRef<DeriveExecutionClientConfig>>()
262 .unwrap();
263 assert_eq!(getter, load_ids);
264 assert_eq!(rust_config.load_ids, load_ids);
265 assert_eq!(rust_config.max_fee_per_contract, None);
266 });
267 }
268
269 #[rstest]
270 #[case::duplicate(vec![InstrumentId::from("ETH-PERP.DERIVE"), InstrumentId::from("ETH-PERP.DERIVE")], "duplicate load_ids")]
271 #[case::other_venue(vec![InstrumentId::from("ETH-PERP.BINANCE")], "invalid load_ids: ETH-PERP.BINANCE is not a DERIVE instrument")]
272 fn test_python_load_ids_reject_invalid_selection(
273 #[case] ids: Vec<InstrumentId>,
274 #[case] expected: &str,
275 ) {
276 Python::initialize();
277 Python::attach(|py| {
278 let kwargs = PyDict::new(py);
279 kwargs.set_item("load_ids", ids).unwrap();
280 let error = py
281 .get_type::<DeriveExecutionClientConfig>()
282 .call((), Some(&kwargs))
283 .unwrap_err();
284 assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
285 assert_eq!(error.value(py).str().unwrap().to_str().unwrap(), expected);
286 });
287 }
288
289 #[rstest]
290 fn test_python_endpoint_overrides(
291 #[values(false, true)] execution: bool,
292 #[values(false, true)] overrides: bool,
293 ) {
294 Python::initialize();
295 Python::attach(|py| {
296 let rest = "https://REST_USER:REST_PASSWORD@rest.example/REST_PATH?token=REST_QUERY#REST_FRAGMENT";
297 let ws = "wss://WS_USER:WS_PASSWORD@stream.example/WS_PATH?token=WS_QUERY#WS_FRAGMENT";
298 let kwargs = PyDict::new(py);
299 kwargs
300 .set_item("base_url_rest", overrides.then_some(rest))
301 .unwrap();
302 kwargs
303 .set_item("base_url_ws", overrides.then_some(ws))
304 .unwrap();
305 kwargs
306 .set_item(
307 "proxy_url",
308 "http://PROXY_USER:PROXY_PASSWORD@proxy.example",
309 )
310 .unwrap();
311
312 let (class, name) = if execution {
313 kwargs
314 .set_item("session_key", "SESSION_KEY_SENTINEL")
315 .unwrap();
316 (
317 py.get_type::<DeriveExecutionClientConfig>(),
318 "DeriveExecutionClientConfig",
319 )
320 } else {
321 (
322 py.get_type::<DeriveDataClientConfig>(),
323 "DeriveDataClientConfig",
324 )
325 };
326
327 let config = class.call((), Some(&kwargs)).unwrap();
328 let rest_getter = config
329 .getattr("base_url_rest")
330 .unwrap()
331 .extract::<Option<String>>()
332 .unwrap();
333 let ws_getter = config
334 .getattr("base_url_ws")
335 .unwrap()
336 .extract::<Option<String>>()
337 .unwrap();
338 let has_proxy = config
339 .getattr("has_proxy_url")
340 .unwrap()
341 .extract::<bool>()
342 .unwrap();
343
344 assert_eq!(rest_getter.as_deref(), overrides.then_some(rest));
345 assert_eq!(ws_getter.as_deref(), overrides.then_some(ws));
346 assert!(has_proxy);
347 assert_eq!(config.repr().unwrap().to_str().unwrap(), name);
348 assert_eq!(config.str().unwrap().to_str().unwrap(), name);
349 });
350 }
351
352 #[rstest]
353 #[case::default(None, false)]
354 #[case::disabled(Some(false), false)]
355 #[case::enabled(Some(true), true)]
356 fn test_python_cancel_on_disconnect(#[case] enabled: Option<bool>, #[case] expected: bool) {
357 Python::initialize();
358 Python::attach(|py| {
359 let kwargs = PyDict::new(py);
360 if let Some(enabled) = enabled {
361 kwargs.set_item("cancel_on_disconnect", enabled).unwrap();
362 }
363
364 let config = py
365 .get_type::<DeriveExecutionClientConfig>()
366 .call((), Some(&kwargs))
367 .unwrap();
368 let getter = config
369 .getattr("cancel_on_disconnect")
370 .unwrap()
371 .extract::<bool>()
372 .unwrap();
373 let rust_config = config
374 .extract::<PyRef<DeriveExecutionClientConfig>>()
375 .unwrap();
376
377 assert_eq!(getter, expected);
378 assert_eq!(rust_config.cancel_on_disconnect, expected);
379 });
380 }
381
382 #[rstest]
383 fn test_python_currencies_normalized_uniqueness(#[values(false, true)] duplicate: bool) {
384 Python::initialize();
385 Python::attach(|py| {
386 let mut values = vec![" ETH ".to_string(), "BTC".to_string()];
387 if duplicate {
388 values.push("ETH".to_string());
389 }
390
391 let kwargs = PyDict::new(py);
392 kwargs.set_item("currencies", &values).unwrap();
393 let result = py
394 .get_type::<DeriveDataClientConfig>()
395 .call((), Some(&kwargs));
396
397 if duplicate {
398 let error = result.unwrap_err();
399 assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
400 assert_eq!(
401 error.value(py).str().unwrap().to_str().unwrap(),
402 "duplicate currencies"
403 );
404 } else {
405 let config = result.unwrap();
406 let config = config.extract::<PyRef<DeriveDataClientConfig>>().unwrap();
407 assert_eq!(config.currencies, values);
408 }
409 });
410 }
411}