Skip to main content

nautilus_finfeed/
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//! Configuration for prediction-market requests and polling subscriptions.
17
18use nautilus_core::string::secret::SecretString;
19use serde::{Deserialize, Serialize};
20
21use crate::{http::client::FinFeedHttpConfig, instruments::FinFeedInstrumentSelection};
22
23/// Explicit startup selections and bounded REST, bootstrap, and polling controls.
24///
25/// # Bootstrap
26///
27/// `connect_timeout_secs` bounds the whole bootstrap, including request admission.
28/// Selections and controls are validated when building the client, before network requests.
29///
30/// # Python Configuration
31///
32/// Python exposes nested Rust HTTP controls as flat constructor keywords:
33///
34/// - `http`: `base_url_http`, `proxy_url`, `http_timeout_secs`, `max_concurrent_requests`,
35///   `attempt_budget`, and `min_request_interval_ms`.
36/// - `http.retry`: `max_retries`, `retry_delay_initial_ms`, `retry_delay_max_ms`,
37///   `retry_backoff_factor`, `retry_jitter_ms`, `retry_operation_timeout_ms`,
38///   `retry_immediate_first`, and `retry_max_elapsed_ms`.
39///
40/// Omitted or `None` options use Rust defaults. Configuration construction rejects unknown
41/// keywords and wrong types. API keys and proxy URLs expose presence indicators instead of
42/// plaintext getters.
43///
44/// # Credentials
45///
46/// Creating a config does not read credentials or connect. If `api_key` is absent, the data
47/// client reads `FINFEED_API_KEY` once at client construction.
48#[derive(Debug, Clone, Serialize, Deserialize, bon::Builder)]
49#[serde(default, deny_unknown_fields)]
50#[cfg_attr(
51    feature = "python",
52    pyo3::pyclass(module = "nautilus_trader.adapters.finfeed", from_py_object)
53)]
54#[cfg_attr(
55    feature = "python",
56    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.finfeed")
57)]
58pub struct FinFeedDataClientConfig {
59    /// Explicit key, or `FINFEED_API_KEY` read once at client construction and reused on reconnect.
60    pub api_key: Option<SecretString>,
61    /// REST transport, pacing, retry, and local attempt controls for each connection generation.
62    #[builder(default = FinFeedHttpConfig::default())]
63    pub http: FinFeedHttpConfig,
64    /// Exact Polymarket Yes/No outcomes loaded and published before readiness.
65    #[builder(default = Vec::new())]
66    pub instruments: Vec<FinFeedInstrumentSelection>,
67    /// Delay after each instrument's poll on the same endpoint completes, in milliseconds, in `[100, 86400000]`.
68    #[builder(default = FinFeedDataClientConfig::default().poll_interval_ms)]
69    pub poll_interval_ms: u64,
70    /// Maximum latest trades and quotes per poll, independently, in `[1, 10000]`.
71    /// OHLCV requests add one record slot for a running period, within the endpoint limit.
72    #[builder(default = FinFeedDataClientConfig::default().poll_limit)]
73    pub poll_limit: u32,
74    /// Whole bootstrap deadline in seconds, including request admission.
75    #[builder(default = FinFeedDataClientConfig::default().connect_timeout_secs)]
76    pub connect_timeout_secs: u64,
77}
78
79impl Default for FinFeedDataClientConfig {
80    fn default() -> Self {
81        Self {
82            api_key: None,
83            http: FinFeedHttpConfig::default(),
84            instruments: Vec::new(),
85            poll_interval_ms: 10_000,
86            poll_limit: 100,
87            connect_timeout_secs: 120,
88        }
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use rstest::rstest;
95
96    use super::*;
97
98    #[rstest]
99    fn builder_and_serde_defaults_match() {
100        let config = FinFeedDataClientConfig::default();
101        let expected = serde_json::to_value(&config).unwrap();
102        let empty = serde_json::Value::Object(serde_json::Map::new());
103        let decoded: FinFeedDataClientConfig = serde_json::from_value(empty).unwrap();
104
105        assert_eq!(config.http.timeout_secs, 300);
106        assert_eq!(config.http.retry.operation_timeout_ms, Some(330_000));
107        assert_eq!(config.http.retry.max_elapsed_ms, Some(600_000));
108        assert_eq!(
109            serde_json::to_value(FinFeedDataClientConfig::builder().build()).unwrap(),
110            expected
111        );
112        assert_eq!(serde_json::to_value(decoded).unwrap(), expected);
113    }
114
115    #[rstest]
116    fn partial_retry_override_preserves_finfeed_defaults() {
117        let value = serde_json::json!({"http": {"retry": {"max_retries": 5}}});
118        let config: FinFeedDataClientConfig = serde_json::from_value(value).unwrap();
119
120        assert_eq!(
121            serde_json::to_value(config.http.retry).unwrap(),
122            serde_json::json!({
123                "max_retries": 5,
124                "initial_delay_ms": 1000,
125                "max_delay_ms": 10000,
126                "backoff_factor": 2.0,
127                "jitter_ms": 0,
128                "operation_timeout_ms": 330000,
129                "immediate_first": false,
130                "max_elapsed_ms": 600000,
131            })
132        );
133    }
134
135    #[rstest]
136    fn retry_overrides_preserve_explicit_values_and_nulls() {
137        let retry = serde_json::json!({
138            "max_retries": 2,
139            "initial_delay_ms": 29,
140            "max_delay_ms": 53,
141            "backoff_factor": 1.5,
142            "jitter_ms": 7,
143            "operation_timeout_ms": 31000,
144            "immediate_first": true,
145            "max_elapsed_ms": 71000,
146        });
147        let value = serde_json::json!({"http": {"retry": retry}});
148        let config: FinFeedDataClientConfig = serde_json::from_value(value).unwrap();
149        assert_eq!(serde_json::to_value(config.http.retry).unwrap(), retry);
150
151        let value = serde_json::json!({"http": {"retry": {"max_elapsed_ms": null}}});
152        let config: FinFeedDataClientConfig = serde_json::from_value(value).unwrap();
153        assert_eq!(config.http.retry.max_elapsed_ms, None);
154        assert_eq!(config.http.retry.jitter_ms, 0);
155    }
156
157    #[rstest]
158    #[case(serde_json::json!({"unknown": 1}))]
159    #[case(serde_json::json!({"http": {"unknown": 2}}))]
160    #[case(serde_json::json!({"http": {"retry": {"unknown": 3}}}))]
161    #[case(serde_json::json!({"instruments": [{"exchange_id": "POLYMARKET", "market_ids": ["a_YES"], "unknown": 4}]}))]
162    fn rejects_unknown_fields(#[case] value: serde_json::Value) {
163        let error = serde_json::from_value::<FinFeedDataClientConfig>(value).unwrap_err();
164        assert!(error.to_string().contains("unknown field `unknown`"));
165    }
166}