Skip to main content

nautilus_finfeed/python/
config.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//! Python projection of prediction-market configuration.
17
18use nautilus_core::string::secret::SecretString;
19use nautilus_network::retry::RetryConfig;
20use pyo3::prelude::*;
21
22use crate::{
23    config::FinFeedDataClientConfig, http::client::FinFeedHttpConfig,
24    instruments::FinFeedInstrumentSelection,
25};
26
27#[pymethods]
28#[pyo3_stub_gen::derive::gen_stub_pymethods]
29impl FinFeedInstrumentSelection {
30    /// Exact outcome IDs explicitly selected from one FinFeed exchange.
31    ///
32    /// IDs come from discovery or are supplied directly. Loading does not implicitly include
33    /// other outcomes of the same market or event.
34    #[new]
35    fn py_new(exchange_id: String, market_ids: Vec<String>) -> Self {
36        Self {
37            exchange_id: exchange_id.into(),
38            market_ids: market_ids.into_iter().map(Into::into).collect(),
39        }
40    }
41
42    /// Provider exchange identifier, such as `POLYMARKET`.
43    #[getter]
44    fn exchange_id(&self) -> &str {
45        &self.exchange_id
46    }
47
48    /// Exact outcome IDs, including `_YES` or `_NO`; related outcomes are not loaded implicitly.
49    #[getter]
50    fn market_ids(&self) -> Vec<String> {
51        self.market_ids.iter().map(ToString::to_string).collect()
52    }
53}
54
55#[pymethods]
56#[pyo3_stub_gen::derive::gen_stub_pymethods]
57impl FinFeedDataClientConfig {
58    /// Explicit startup selections and bounded REST, bootstrap, and polling controls.
59    ///
60    /// # Bootstrap
61    ///
62    /// `connect_timeout_secs` bounds the whole bootstrap, including request admission.
63    /// Selections and controls are validated when building the client, before network requests.
64    ///
65    /// # Python Configuration
66    ///
67    /// Python exposes nested Rust HTTP controls as flat constructor keywords:
68    ///
69    /// - `http`: `base_url_http`, `proxy_url`, `http_timeout_secs`, `max_concurrent_requests`,
70    ///   `attempt_budget`, and `min_request_interval_ms`.
71    /// - `http.retry`: `max_retries`, `retry_delay_initial_ms`, `retry_delay_max_ms`,
72    ///   `retry_backoff_factor`, `retry_jitter_ms`, `retry_operation_timeout_ms`,
73    ///   `retry_immediate_first`, and `retry_max_elapsed_ms`.
74    ///
75    /// Omitted or `None` options use Rust defaults. Configuration construction rejects unknown
76    /// keywords and wrong types. API keys and proxy URLs expose presence indicators instead of
77    /// plaintext getters.
78    ///
79    /// # Credentials
80    ///
81    /// Creating a config does not read credentials or connect. If `api_key` is absent, the data
82    /// client reads `FINFEED_API_KEY` once at client construction.
83    #[new]
84    #[pyo3(signature = (
85        api_key = None,
86        base_url_http = None,
87        proxy_url = None,
88        instruments = None,
89        http_timeout_secs = None,
90        max_concurrent_requests = None,
91        attempt_budget = None,
92        min_request_interval_ms = None,
93        max_retries = None,
94        retry_delay_initial_ms = None,
95        retry_delay_max_ms = None,
96        retry_backoff_factor = None,
97        retry_jitter_ms = None,
98        retry_operation_timeout_ms = None,
99        retry_immediate_first = None,
100        retry_max_elapsed_ms = None,
101        poll_interval_ms = None,
102        poll_limit = None,
103        connect_timeout_secs = None,
104    ))]
105    #[expect(clippy::too_many_arguments)]
106    fn py_new(
107        api_key: Option<String>,
108        base_url_http: Option<String>,
109        proxy_url: Option<String>,
110        instruments: Option<Vec<FinFeedInstrumentSelection>>,
111        http_timeout_secs: Option<u64>,
112        max_concurrent_requests: Option<usize>,
113        attempt_budget: Option<u64>,
114        min_request_interval_ms: Option<u64>,
115        max_retries: Option<u32>,
116        retry_delay_initial_ms: Option<u64>,
117        retry_delay_max_ms: Option<u64>,
118        retry_backoff_factor: Option<f64>,
119        retry_jitter_ms: Option<u64>,
120        retry_operation_timeout_ms: Option<u64>,
121        retry_immediate_first: Option<bool>,
122        retry_max_elapsed_ms: Option<u64>,
123        poll_interval_ms: Option<u64>,
124        poll_limit: Option<u32>,
125        connect_timeout_secs: Option<u64>,
126    ) -> Self {
127        let defaults = Self::default();
128
129        Self {
130            api_key: api_key.map(SecretString::from),
131            http: http_config(
132                base_url_http,
133                proxy_url,
134                http_timeout_secs,
135                max_concurrent_requests,
136                attempt_budget,
137                min_request_interval_ms,
138                max_retries,
139                retry_delay_initial_ms,
140                retry_delay_max_ms,
141                retry_backoff_factor,
142                retry_jitter_ms,
143                retry_operation_timeout_ms,
144                retry_immediate_first,
145                retry_max_elapsed_ms,
146            ),
147            instruments: instruments.unwrap_or(defaults.instruments),
148            poll_interval_ms: poll_interval_ms.unwrap_or(defaults.poll_interval_ms),
149            poll_limit: poll_limit.unwrap_or(defaults.poll_limit),
150            connect_timeout_secs: connect_timeout_secs.unwrap_or(defaults.connect_timeout_secs),
151        }
152    }
153
154    /// HTTPS endpoint, or a plaintext loopback test peer, including the version prefix.
155    /// Debug output redacts the complete endpoint.
156    #[getter]
157    fn base_url_http(&self) -> &str {
158        self.http.base_url.expose_secret()
159    }
160
161    /// Exact Polymarket Yes/No outcomes loaded and published before readiness.
162    #[getter]
163    fn instruments(&self) -> Vec<FinFeedInstrumentSelection> {
164        self.instruments.clone()
165    }
166
167    /// Transport timeout for one request, in seconds.
168    #[getter]
169    fn http_timeout_secs(&self) -> u64 {
170        self.http.timeout_secs
171    }
172
173    /// Maximum managed requests in flight on this instance.
174    #[getter]
175    fn max_concurrent_requests(&self) -> usize {
176        self.http.max_concurrent_requests
177    }
178
179    /// Lifetime managed attempt allowance, including failed and canceled attempts after admission.
180    #[getter]
181    fn attempt_budget(&self) -> u64 {
182        self.http.attempt_budget
183    }
184
185    /// Minimum spacing between managed attempt starts, in milliseconds.
186    #[getter]
187    fn min_request_interval_ms(&self) -> u64 {
188        self.http.min_request_interval_ms
189    }
190
191    /// Maximum number of retry attempts (total attempts = 1 initial + `max_retries`).
192    #[getter]
193    fn max_retries(&self) -> u32 {
194        self.http.retry.max_retries
195    }
196
197    /// Initial delay between retries in milliseconds.
198    #[getter]
199    fn retry_delay_initial_ms(&self) -> u64 {
200        self.http.retry.initial_delay_ms
201    }
202
203    /// Maximum delay between retries in milliseconds.
204    #[getter]
205    fn retry_delay_max_ms(&self) -> u64 {
206        self.http.retry.max_delay_ms
207    }
208
209    /// Backoff multiplier factor.
210    #[getter]
211    fn retry_backoff_factor(&self) -> f64 {
212        self.http.retry.backoff_factor
213    }
214
215    /// Maximum jitter in milliseconds to add to delays.
216    #[getter]
217    fn retry_jitter_ms(&self) -> u64 {
218        self.http.retry.jitter_ms
219    }
220
221    /// Retry policy with required per-operation and total elapsed deadlines, in milliseconds.
222    /// Both include local admission waits; the total deadline also covers retries and backoff.
223    /// Deadlines must be positive and at most one day. Python `None` retains defaults;
224    /// a Rust `None` deadline fails client validation.
225    /// Unspecified retry fields retain FinFeed defaults during deserialization.
226    #[getter]
227    fn retry_operation_timeout_ms(&self) -> Option<u64> {
228        self.http.retry.operation_timeout_ms
229    }
230
231    /// Whether the first retry occurs without delay.
232    ///
233    /// Connection operations typically enable this, while HTTP and order operations typically
234    /// retain a delay.
235    #[getter]
236    fn retry_immediate_first(&self) -> bool {
237        self.http.retry.immediate_first
238    }
239
240    /// Retry policy with required per-operation and total elapsed deadlines, in milliseconds.
241    /// Both include local admission waits; the total deadline also covers retries and backoff.
242    /// Deadlines must be positive and at most one day. Python `None` retains defaults;
243    /// a Rust `None` deadline fails client validation.
244    /// Unspecified retry fields retain FinFeed defaults during deserialization.
245    #[getter]
246    fn retry_max_elapsed_ms(&self) -> Option<u64> {
247        self.http.retry.max_elapsed_ms
248    }
249
250    /// Delay after each instrument's poll on the same endpoint completes, in milliseconds, in `[100, 86400000]`.
251    #[getter]
252    fn poll_interval_ms(&self) -> u64 {
253        self.poll_interval_ms
254    }
255
256    /// Maximum latest trades and quotes per poll, independently, in `[1, 10000]`.
257    /// OHLCV requests add one record slot for a running period, within the endpoint limit.
258    #[getter]
259    fn poll_limit(&self) -> u32 {
260        self.poll_limit
261    }
262
263    /// Whole bootstrap deadline in seconds, including request admission.
264    #[getter]
265    fn connect_timeout_secs(&self) -> u64 {
266        self.connect_timeout_secs
267    }
268
269    /// Returns whether `api_key` is set.
270    #[getter]
271    fn has_api_key(&self) -> bool {
272        self.api_key.is_some()
273    }
274
275    /// Returns whether `proxy_url` is set.
276    #[getter]
277    fn has_proxy_url(&self) -> bool {
278        self.http.proxy_url.is_some()
279    }
280
281    /// Returns the constant representation `FinFeedDataClientConfig`.
282    fn __repr__(&self) -> &'static str {
283        "FinFeedDataClientConfig"
284    }
285}
286
287#[expect(
288    clippy::too_many_arguments,
289    reason = "shared conversion for the typed HTTP constructor options"
290)]
291pub(super) fn http_config(
292    base_url_http: Option<String>,
293    proxy_url: Option<String>,
294    http_timeout_secs: Option<u64>,
295    max_concurrent_requests: Option<usize>,
296    attempt_budget: Option<u64>,
297    min_request_interval_ms: Option<u64>,
298    max_retries: Option<u32>,
299    retry_delay_initial_ms: Option<u64>,
300    retry_delay_max_ms: Option<u64>,
301    retry_backoff_factor: Option<f64>,
302    retry_jitter_ms: Option<u64>,
303    retry_operation_timeout_ms: Option<u64>,
304    retry_immediate_first: Option<bool>,
305    retry_max_elapsed_ms: Option<u64>,
306) -> FinFeedHttpConfig {
307    let defaults = FinFeedHttpConfig::default();
308
309    FinFeedHttpConfig {
310        base_url: base_url_http
311            .map(SecretString::from)
312            .unwrap_or(defaults.base_url),
313        proxy_url: proxy_url.map(SecretString::from),
314        timeout_secs: http_timeout_secs.unwrap_or(defaults.timeout_secs),
315        max_concurrent_requests: max_concurrent_requests
316            .unwrap_or(defaults.max_concurrent_requests),
317        attempt_budget: attempt_budget.unwrap_or(defaults.attempt_budget),
318        min_request_interval_ms: min_request_interval_ms
319            .unwrap_or(defaults.min_request_interval_ms),
320        retry: RetryConfig {
321            max_retries: max_retries.unwrap_or(defaults.retry.max_retries),
322            initial_delay_ms: retry_delay_initial_ms.unwrap_or(defaults.retry.initial_delay_ms),
323            max_delay_ms: retry_delay_max_ms.unwrap_or(defaults.retry.max_delay_ms),
324            backoff_factor: retry_backoff_factor.unwrap_or(defaults.retry.backoff_factor),
325            jitter_ms: retry_jitter_ms.unwrap_or(defaults.retry.jitter_ms),
326            operation_timeout_ms: retry_operation_timeout_ms
327                .or(defaults.retry.operation_timeout_ms),
328            immediate_first: retry_immediate_first.unwrap_or(defaults.retry.immediate_first),
329            max_elapsed_ms: retry_max_elapsed_ms.or(defaults.retry.max_elapsed_ms),
330        },
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use pyo3::types::PyDict;
337    use rstest::rstest;
338
339    use super::*;
340    use crate::python::http::PyFinFeedHttpClient;
341
342    #[rstest]
343    fn python_projection_preserves_every_rust_field() {
344        Python::initialize();
345        Python::attach(|py| {
346            let kwargs = PyDict::new(py);
347            kwargs.set_item("api_key", "projection-secret").unwrap();
348            kwargs
349                .set_item("base_url_http", "http://localhost:8123/path-sentinel/v1/")
350                .unwrap();
351            kwargs
352                .set_item("proxy_url", "http://user:proxy-secret@localhost:8124")
353                .unwrap();
354            let selection = Py::new(
355                py,
356                FinFeedInstrumentSelection::py_new(
357                    "POLYMARKET".into(),
358                    vec!["first_YES".into(), "second_NO".into()],
359                ),
360            )
361            .unwrap();
362            kwargs.set_item("instruments", vec![selection]).unwrap();
363            for (name, value) in [
364                ("http_timeout_secs", 13),
365                ("max_concurrent_requests", 4),
366                ("attempt_budget", 17),
367                ("min_request_interval_ms", 19),
368                ("max_retries", 2),
369                ("retry_delay_initial_ms", 29),
370                ("retry_delay_max_ms", 53),
371                ("retry_jitter_ms", 7),
372                ("retry_operation_timeout_ms", 31_000),
373                ("retry_max_elapsed_ms", 71_000),
374                ("poll_interval_ms", 137),
375                ("poll_limit", 23),
376                ("connect_timeout_secs", 43),
377            ] {
378                kwargs.set_item(name, value).unwrap();
379            }
380
381            kwargs.set_item("retry_backoff_factor", 1.5).unwrap();
382            kwargs.set_item("retry_immediate_first", true).unwrap();
383            let object = py
384                .get_type::<FinFeedDataClientConfig>()
385                .call((), Some(&kwargs))
386                .unwrap();
387            let config: FinFeedDataClientConfig = object.extract().unwrap();
388            assert_eq!(
389                config.api_key.as_ref().unwrap().expose_secret(),
390                "projection-secret"
391            );
392            assert_eq!(
393                config.http.base_url.expose_secret(),
394                "http://localhost:8123/path-sentinel/v1/"
395            );
396            assert_eq!(
397                object
398                    .getattr("base_url_http")
399                    .unwrap()
400                    .extract::<String>()
401                    .unwrap(),
402                "http://localhost:8123/path-sentinel/v1/"
403            );
404            assert_eq!(
405                config.http.proxy_url.as_ref().unwrap().expose_secret(),
406                "http://user:proxy-secret@localhost:8124"
407            );
408            assert_eq!(config.instruments.len(), 1);
409            assert_eq!(config.instruments[0].exchange_id, "POLYMARKET");
410            assert_eq!(config.instruments[0].market_ids, ["first_YES", "second_NO"]);
411            assert_eq!(config.http.timeout_secs, 13);
412            assert_eq!(config.http.max_concurrent_requests, 4);
413            assert_eq!(config.http.attempt_budget, 17);
414            assert_eq!(config.http.min_request_interval_ms, 19);
415            assert_eq!(config.http.retry.max_retries, 2);
416            assert_eq!(config.http.retry.initial_delay_ms, 29);
417            assert_eq!(config.http.retry.max_delay_ms, 53);
418            assert_eq!(config.http.retry.backoff_factor, 1.5);
419            assert_eq!(config.http.retry.jitter_ms, 7);
420            assert_eq!(config.http.retry.operation_timeout_ms, Some(31_000));
421            assert!(config.http.retry.immediate_first);
422            assert_eq!(config.http.retry.max_elapsed_ms, Some(71_000));
423            assert_eq!(config.poll_interval_ms, 137);
424            assert_eq!(config.poll_limit, 23);
425            assert_eq!(config.connect_timeout_secs, 43);
426            let debug = format!("{config:?}");
427            let http_object = py
428                .get_type::<PyFinFeedHttpClient>()
429                .call1((object.clone(),))
430                .unwrap();
431            let http_client: PyRef<'_, PyFinFeedHttpClient> = http_object.extract().unwrap();
432            let http_debug = format!("{:?}", *http_client);
433
434            assert!(debug.contains("base_url: <redacted>"));
435            assert!(http_debug.contains("base_url: \"http://localhost:8123\""));
436            assert_eq!(
437                object.repr().unwrap().to_str().unwrap(),
438                "FinFeedDataClientConfig"
439            );
440            assert_eq!(
441                http_object.repr().unwrap().to_str().unwrap(),
442                "FinFeedHttpClient"
443            );
444
445            for secret in ["projection-secret", "proxy-secret", "path-sentinel"] {
446                assert!(!debug.contains(secret));
447                assert!(!http_debug.contains(secret));
448            }
449        });
450    }
451
452    #[rstest]
453    fn python_defaults_match_rust() {
454        Python::initialize();
455        Python::attach(|py| {
456            let object = py.get_type::<FinFeedDataClientConfig>().call0().unwrap();
457            let config: FinFeedDataClientConfig = object.extract().unwrap();
458            assert_eq!(
459                serde_json::to_value(config).unwrap(),
460                serde_json::to_value(FinFeedDataClientConfig::default()).unwrap()
461            );
462        });
463    }
464}