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`, `min_request_interval_ms`, and `kalshi_metadata_url`.
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        kalshi_metadata_url = None,
105    ))]
106    #[expect(clippy::too_many_arguments)]
107    fn py_new(
108        api_key: Option<String>,
109        base_url_http: Option<String>,
110        proxy_url: Option<String>,
111        instruments: Option<Vec<FinFeedInstrumentSelection>>,
112        http_timeout_secs: Option<u64>,
113        max_concurrent_requests: Option<usize>,
114        attempt_budget: Option<u64>,
115        min_request_interval_ms: Option<u64>,
116        max_retries: Option<u32>,
117        retry_delay_initial_ms: Option<u64>,
118        retry_delay_max_ms: Option<u64>,
119        retry_backoff_factor: Option<f64>,
120        retry_jitter_ms: Option<u64>,
121        retry_operation_timeout_ms: Option<u64>,
122        retry_immediate_first: Option<bool>,
123        retry_max_elapsed_ms: Option<u64>,
124        poll_interval_ms: Option<u64>,
125        poll_limit: Option<u32>,
126        connect_timeout_secs: Option<u64>,
127        kalshi_metadata_url: Option<String>,
128    ) -> Self {
129        let defaults = Self::default();
130
131        Self {
132            api_key: api_key.map(SecretString::from),
133            http: http_config(
134                base_url_http,
135                proxy_url,
136                http_timeout_secs,
137                max_concurrent_requests,
138                attempt_budget,
139                min_request_interval_ms,
140                max_retries,
141                retry_delay_initial_ms,
142                retry_delay_max_ms,
143                retry_backoff_factor,
144                retry_jitter_ms,
145                retry_operation_timeout_ms,
146                retry_immediate_first,
147                retry_max_elapsed_ms,
148                kalshi_metadata_url,
149            ),
150            instruments: instruments.unwrap_or(defaults.instruments),
151            poll_interval_ms: poll_interval_ms.unwrap_or(defaults.poll_interval_ms),
152            poll_limit: poll_limit.unwrap_or(defaults.poll_limit),
153            connect_timeout_secs: connect_timeout_secs.unwrap_or(defaults.connect_timeout_secs),
154        }
155    }
156
157    /// HTTPS endpoint, or a plaintext loopback test peer, including the version prefix.
158    /// Debug output redacts the complete endpoint.
159    #[getter]
160    fn base_url_http(&self) -> &str {
161        self.http.base_url.expose_secret()
162    }
163
164    /// Public Kalshi metadata endpoint override, or `None` for production.
165    #[getter]
166    fn kalshi_metadata_url(&self) -> Option<&str> {
167        self.http
168            .kalshi_metadata_url
169            .as_ref()
170            .map(SecretString::expose_secret)
171    }
172
173    /// Exact Polymarket or Kalshi Yes/No outcomes loaded and published before readiness.
174    #[getter]
175    fn instruments(&self) -> Vec<FinFeedInstrumentSelection> {
176        self.instruments.clone()
177    }
178
179    /// Transport timeout for one request, in seconds.
180    #[getter]
181    fn http_timeout_secs(&self) -> u64 {
182        self.http.timeout_secs
183    }
184
185    /// Maximum managed requests in flight on this instance.
186    #[getter]
187    fn max_concurrent_requests(&self) -> usize {
188        self.http.max_concurrent_requests
189    }
190
191    /// Lifetime FinFeed attempt allowance, including failed and canceled attempts after admission.
192    #[getter]
193    fn attempt_budget(&self) -> u64 {
194        self.http.attempt_budget
195    }
196
197    /// Minimum spacing between managed attempt starts, in milliseconds.
198    #[getter]
199    fn min_request_interval_ms(&self) -> u64 {
200        self.http.min_request_interval_ms
201    }
202
203    /// Maximum number of retry attempts (total attempts = 1 initial + `max_retries`).
204    #[getter]
205    fn max_retries(&self) -> u32 {
206        self.http.retry.max_retries
207    }
208
209    /// Initial delay between retries in milliseconds.
210    #[getter]
211    fn retry_delay_initial_ms(&self) -> u64 {
212        self.http.retry.initial_delay_ms
213    }
214
215    /// Maximum delay between retries in milliseconds.
216    #[getter]
217    fn retry_delay_max_ms(&self) -> u64 {
218        self.http.retry.max_delay_ms
219    }
220
221    /// Backoff multiplier factor.
222    #[getter]
223    fn retry_backoff_factor(&self) -> f64 {
224        self.http.retry.backoff_factor
225    }
226
227    /// Maximum jitter in milliseconds to add to delays.
228    #[getter]
229    fn retry_jitter_ms(&self) -> u64 {
230        self.http.retry.jitter_ms
231    }
232
233    /// Retry policy with required per-operation and total elapsed deadlines, in milliseconds.
234    /// Both include local admission waits; the total deadline also covers retries and backoff.
235    /// Deadlines must be positive and at most one day. Python `None` retains defaults;
236    /// a Rust `None` deadline fails client validation.
237    /// Unspecified retry fields retain FinFeed defaults during deserialization.
238    #[getter]
239    fn retry_operation_timeout_ms(&self) -> Option<u64> {
240        self.http.retry.operation_timeout_ms
241    }
242
243    /// Whether the first retry occurs without delay.
244    ///
245    /// Connection operations typically enable this, while HTTP and order operations typically
246    /// retain a delay.
247    #[getter]
248    fn retry_immediate_first(&self) -> bool {
249        self.http.retry.immediate_first
250    }
251
252    /// Retry policy with required per-operation and total elapsed deadlines, in milliseconds.
253    /// Both include local admission waits; the total deadline also covers retries and backoff.
254    /// Deadlines must be positive and at most one day. Python `None` retains defaults;
255    /// a Rust `None` deadline fails client validation.
256    /// Unspecified retry fields retain FinFeed defaults during deserialization.
257    #[getter]
258    fn retry_max_elapsed_ms(&self) -> Option<u64> {
259        self.http.retry.max_elapsed_ms
260    }
261
262    /// Delay after each instrument's poll on the same endpoint completes, in milliseconds, in `[100, 86400000]`.
263    #[getter]
264    fn poll_interval_ms(&self) -> u64 {
265        self.poll_interval_ms
266    }
267
268    /// Maximum latest trades and quotes per poll, independently, in `[1, 10000]`.
269    /// OHLCV requests add one record slot for a running period, within the endpoint limit.
270    #[getter]
271    fn poll_limit(&self) -> u32 {
272        self.poll_limit
273    }
274
275    /// Whole bootstrap deadline in seconds, including request admission.
276    #[getter]
277    fn connect_timeout_secs(&self) -> u64 {
278        self.connect_timeout_secs
279    }
280
281    /// Returns whether `api_key` is set.
282    #[getter]
283    fn has_api_key(&self) -> bool {
284        self.api_key.is_some()
285    }
286
287    /// Returns whether `proxy_url` is set.
288    #[getter]
289    fn has_proxy_url(&self) -> bool {
290        self.http.proxy_url.is_some()
291    }
292
293    /// Returns the constant representation `FinFeedDataClientConfig`.
294    fn __repr__(&self) -> &'static str {
295        "FinFeedDataClientConfig"
296    }
297}
298
299#[expect(
300    clippy::too_many_arguments,
301    reason = "shared conversion for the typed HTTP constructor options"
302)]
303pub(super) fn http_config(
304    base_url_http: Option<String>,
305    proxy_url: Option<String>,
306    http_timeout_secs: Option<u64>,
307    max_concurrent_requests: Option<usize>,
308    attempt_budget: Option<u64>,
309    min_request_interval_ms: Option<u64>,
310    max_retries: Option<u32>,
311    retry_delay_initial_ms: Option<u64>,
312    retry_delay_max_ms: Option<u64>,
313    retry_backoff_factor: Option<f64>,
314    retry_jitter_ms: Option<u64>,
315    retry_operation_timeout_ms: Option<u64>,
316    retry_immediate_first: Option<bool>,
317    retry_max_elapsed_ms: Option<u64>,
318    kalshi_metadata_url: Option<String>,
319) -> FinFeedHttpConfig {
320    let defaults = FinFeedHttpConfig::default();
321
322    FinFeedHttpConfig {
323        base_url: base_url_http
324            .map(SecretString::from)
325            .unwrap_or(defaults.base_url),
326        proxy_url: proxy_url.map(SecretString::from),
327        timeout_secs: http_timeout_secs.unwrap_or(defaults.timeout_secs),
328        max_concurrent_requests: max_concurrent_requests
329            .unwrap_or(defaults.max_concurrent_requests),
330        attempt_budget: attempt_budget.unwrap_or(defaults.attempt_budget),
331        min_request_interval_ms: min_request_interval_ms
332            .unwrap_or(defaults.min_request_interval_ms),
333        retry: RetryConfig {
334            max_retries: max_retries.unwrap_or(defaults.retry.max_retries),
335            initial_delay_ms: retry_delay_initial_ms.unwrap_or(defaults.retry.initial_delay_ms),
336            max_delay_ms: retry_delay_max_ms.unwrap_or(defaults.retry.max_delay_ms),
337            backoff_factor: retry_backoff_factor.unwrap_or(defaults.retry.backoff_factor),
338            jitter_ms: retry_jitter_ms.unwrap_or(defaults.retry.jitter_ms),
339            operation_timeout_ms: retry_operation_timeout_ms
340                .or(defaults.retry.operation_timeout_ms),
341            immediate_first: retry_immediate_first.unwrap_or(defaults.retry.immediate_first),
342            max_elapsed_ms: retry_max_elapsed_ms.or(defaults.retry.max_elapsed_ms),
343        },
344        kalshi_metadata_url: kalshi_metadata_url.map(SecretString::from),
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use pyo3::types::PyDict;
351    use rstest::rstest;
352
353    use super::*;
354    use crate::python::http::PyFinFeedHttpClient;
355
356    #[rstest]
357    fn python_projection_preserves_every_rust_field() {
358        Python::initialize();
359        Python::attach(|py| {
360            let kwargs = PyDict::new(py);
361            kwargs.set_item("api_key", "projection-secret").unwrap();
362            kwargs
363                .set_item("base_url_http", "http://localhost:8123/path-sentinel/v1/")
364                .unwrap();
365            kwargs
366                .set_item("proxy_url", "http://user:proxy-secret@localhost:8124")
367                .unwrap();
368            kwargs
369                .set_item(
370                    "kalshi_metadata_url",
371                    "http://localhost:8125/metadata-sentinel/",
372                )
373                .unwrap();
374            let selection = Py::new(
375                py,
376                FinFeedInstrumentSelection::py_new(
377                    "POLYMARKET".into(),
378                    vec!["first_YES".into(), "second_NO".into()],
379                ),
380            )
381            .unwrap();
382            kwargs.set_item("instruments", vec![selection]).unwrap();
383            for (name, value) in [
384                ("http_timeout_secs", 13),
385                ("max_concurrent_requests", 4),
386                ("attempt_budget", 17),
387                ("min_request_interval_ms", 19),
388                ("max_retries", 2),
389                ("retry_delay_initial_ms", 29),
390                ("retry_delay_max_ms", 53),
391                ("retry_jitter_ms", 7),
392                ("retry_operation_timeout_ms", 31_000),
393                ("retry_max_elapsed_ms", 71_000),
394                ("poll_interval_ms", 137),
395                ("poll_limit", 23),
396                ("connect_timeout_secs", 43),
397            ] {
398                kwargs.set_item(name, value).unwrap();
399            }
400
401            kwargs.set_item("retry_backoff_factor", 1.5).unwrap();
402            kwargs.set_item("retry_immediate_first", true).unwrap();
403            let object = py
404                .get_type::<FinFeedDataClientConfig>()
405                .call((), Some(&kwargs))
406                .unwrap();
407            let config: FinFeedDataClientConfig = object.extract().unwrap();
408            assert_eq!(
409                config
410                    .http
411                    .kalshi_metadata_url
412                    .as_ref()
413                    .unwrap()
414                    .expose_secret(),
415                "http://localhost:8125/metadata-sentinel/"
416            );
417            assert_eq!(
418                object
419                    .getattr("kalshi_metadata_url")
420                    .unwrap()
421                    .extract::<String>()
422                    .unwrap(),
423                "http://localhost:8125/metadata-sentinel/"
424            );
425            assert_eq!(
426                config.api_key.as_ref().unwrap().expose_secret(),
427                "projection-secret"
428            );
429            assert_eq!(
430                config.http.base_url.expose_secret(),
431                "http://localhost:8123/path-sentinel/v1/"
432            );
433            assert_eq!(
434                object
435                    .getattr("base_url_http")
436                    .unwrap()
437                    .extract::<String>()
438                    .unwrap(),
439                "http://localhost:8123/path-sentinel/v1/"
440            );
441            assert_eq!(
442                config.http.proxy_url.as_ref().unwrap().expose_secret(),
443                "http://user:proxy-secret@localhost:8124"
444            );
445            assert_eq!(config.instruments.len(), 1);
446            assert_eq!(config.instruments[0].exchange_id, "POLYMARKET");
447            assert_eq!(config.instruments[0].market_ids, ["first_YES", "second_NO"]);
448            assert_eq!(config.http.timeout_secs, 13);
449            assert_eq!(config.http.max_concurrent_requests, 4);
450            assert_eq!(config.http.attempt_budget, 17);
451            assert_eq!(config.http.min_request_interval_ms, 19);
452            assert_eq!(config.http.retry.max_retries, 2);
453            assert_eq!(config.http.retry.initial_delay_ms, 29);
454            assert_eq!(config.http.retry.max_delay_ms, 53);
455            assert_eq!(config.http.retry.backoff_factor, 1.5);
456            assert_eq!(config.http.retry.jitter_ms, 7);
457            assert_eq!(config.http.retry.operation_timeout_ms, Some(31_000));
458            assert!(config.http.retry.immediate_first);
459            assert_eq!(config.http.retry.max_elapsed_ms, Some(71_000));
460            assert_eq!(config.poll_interval_ms, 137);
461            assert_eq!(config.poll_limit, 23);
462            assert_eq!(config.connect_timeout_secs, 43);
463            let debug = format!("{config:?}");
464            let http_object = py
465                .get_type::<PyFinFeedHttpClient>()
466                .call1((object.clone(),))
467                .unwrap();
468            let http_client: PyRef<'_, PyFinFeedHttpClient> = http_object.extract().unwrap();
469            let http_debug = format!("{:?}", *http_client);
470
471            assert!(debug.contains("base_url: <redacted>"));
472            assert!(http_debug.contains("base_url: \"http://localhost:8123\""));
473            assert_eq!(
474                object.repr().unwrap().to_str().unwrap(),
475                "FinFeedDataClientConfig"
476            );
477            assert_eq!(
478                http_object.repr().unwrap().to_str().unwrap(),
479                "FinFeedHttpClient"
480            );
481
482            for secret in ["projection-secret", "proxy-secret", "path-sentinel"] {
483                assert!(!debug.contains(secret));
484                assert!(!http_debug.contains(secret));
485            }
486        });
487    }
488
489    #[rstest]
490    fn python_defaults_match_rust() {
491        Python::initialize();
492        Python::attach(|py| {
493            let object = py.get_type::<FinFeedDataClientConfig>().call0().unwrap();
494            let config: FinFeedDataClientConfig = object.extract().unwrap();
495            assert_eq!(
496                serde_json::to_value(config).unwrap(),
497                serde_json::to_value(FinFeedDataClientConfig::default()).unwrap()
498            );
499        });
500    }
501}