Skip to main content

nautilus_kalshi/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 the Rust Kalshi configs.
17
18use 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::prelude::*;
23
24use crate::{
25    common::enums::KalshiEnvironment,
26    config::{KalshiDataClientConfig, KalshiExecutionClientConfig},
27};
28
29#[pymethods]
30#[pyo3_stub_gen::derive::gen_stub_pymethods]
31impl KalshiDataClientConfig {
32    /// Configuration for the Kalshi data client.
33    #[new]
34    #[pyo3(signature = (
35        api_key_id = None,
36        private_key = None,
37        environment = None,
38        base_url_http = None,
39        base_url_ws = None,
40        proxy_url = None,
41        http_timeout_secs = None,
42        ws_timeout_secs = None,
43        update_instruments_interval_mins = None,
44        transport_backend = None,
45        book_snapshot_timeout_secs = None,
46        instrument_ids = None,
47    ))]
48    #[expect(
49        clippy::too_many_arguments,
50        reason = "thin projection of the Rust config fields"
51    )]
52    fn py_new(
53        api_key_id: Option<String>,
54        private_key: Option<String>,
55        environment: Option<KalshiEnvironment>,
56        base_url_http: Option<String>,
57        base_url_ws: Option<String>,
58        proxy_url: Option<String>,
59        http_timeout_secs: Option<u64>,
60        ws_timeout_secs: Option<u64>,
61        update_instruments_interval_mins: Option<u64>,
62        transport_backend: Option<TransportBackend>,
63        book_snapshot_timeout_secs: Option<u64>,
64        instrument_ids: Option<Vec<InstrumentId>>,
65    ) -> PyResult<Self> {
66        let defaults = Self::default();
67
68        let config = Self {
69            api_key_id: api_key_id.map(SecretString::from),
70            private_key: private_key.map(SecretString::from),
71            environment: environment.unwrap_or(defaults.environment),
72            base_url_http: base_url_http.map(SecretString::from),
73            base_url_ws: base_url_ws.map(SecretString::from),
74            proxy_url: proxy_url.map(SecretString::from),
75            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
76            ws_timeout_secs: ws_timeout_secs.unwrap_or(defaults.ws_timeout_secs),
77            book_snapshot_timeout_secs: book_snapshot_timeout_secs
78                .unwrap_or(defaults.book_snapshot_timeout_secs),
79            update_instruments_interval_mins: update_instruments_interval_mins
80                .unwrap_or(defaults.update_instruments_interval_mins),
81            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
82            instrument_ids: instrument_ids.unwrap_or(defaults.instrument_ids),
83        };
84
85        config.validate().map_err(config_error_to_pyvalue_err)?;
86        Ok(config)
87    }
88
89    /// Returns whether both explicit credential fields contain non-empty values.
90    #[getter(has_credentials)]
91    fn py_has_credentials(&self) -> bool {
92        Self::has_credentials(self)
93    }
94
95    #[getter]
96    const fn has_proxy_url(&self) -> bool {
97        self.proxy_url.is_some()
98    }
99
100    fn __repr__(&self) -> String {
101        format!("{self:?}")
102    }
103
104    fn __str__(&self) -> String {
105        self.__repr__()
106    }
107}
108
109#[pymethods]
110#[pyo3_stub_gen::derive::gen_stub_pymethods]
111impl KalshiExecutionClientConfig {
112    /// Configuration for the Kalshi execution client.
113    #[new]
114    #[pyo3(signature = (account_id = None, api_key_id = None, private_key = None, environment = None, base_url_http = None, base_url_ws = None, proxy_url = None, http_timeout_secs = None, ws_timeout_secs = None, exchange_index = None, transport_backend = None))]
115    #[expect(
116        clippy::too_many_arguments,
117        reason = "thin projection of the Rust config fields"
118    )]
119    fn py_new(
120        account_id: Option<AccountId>,
121        api_key_id: Option<String>,
122        private_key: Option<String>,
123        environment: Option<KalshiEnvironment>,
124        base_url_http: Option<String>,
125        base_url_ws: Option<String>,
126        proxy_url: Option<String>,
127        http_timeout_secs: Option<u64>,
128        ws_timeout_secs: Option<u64>,
129        exchange_index: Option<u32>,
130        transport_backend: Option<TransportBackend>,
131    ) -> PyResult<Self> {
132        let defaults = Self::default();
133
134        let config = Self {
135            account_id: account_id.unwrap_or(defaults.account_id),
136            api_key_id: api_key_id.map(SecretString::from),
137            private_key: private_key.map(SecretString::from),
138            environment: environment.unwrap_or(defaults.environment),
139            base_url_http: base_url_http.map(SecretString::from),
140            base_url_ws: base_url_ws.map(SecretString::from),
141            proxy_url: proxy_url.map(SecretString::from),
142            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
143            ws_timeout_secs: ws_timeout_secs.unwrap_or(defaults.ws_timeout_secs),
144            exchange_index: exchange_index.unwrap_or(defaults.exchange_index),
145            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
146        };
147
148        config.validate().map_err(config_error_to_pyvalue_err)?;
149        Ok(config)
150    }
151
152    /// Returns whether both explicit credential fields contain non-empty values.
153    #[getter(has_credentials)]
154    fn py_has_credentials(&self) -> bool {
155        Self::has_credentials(self)
156    }
157
158    #[getter]
159    const fn has_proxy_url(&self) -> bool {
160        self.proxy_url.is_some()
161    }
162
163    fn __repr__(&self) -> String {
164        format!("{self:?}")
165    }
166
167    fn __str__(&self) -> String {
168        self.__repr__()
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use pyo3::types::PyDict;
175    use rstest::rstest;
176
177    use super::*;
178
179    #[rstest]
180    #[case("KalshiDataClientConfig")]
181    #[case("KalshiExecutionClientConfig")]
182    fn test_python_constructor_defaults_and_secret_representations(#[case] name: &str) {
183        Python::initialize();
184        Python::attach(|py| {
185            let module = PyModule::new(py, "kalshi").unwrap();
186            crate::python::kalshi(&module).unwrap();
187            let class = module.getattr(name).unwrap();
188            let default = class.call0().unwrap();
189            let kwargs = PyDict::new(py);
190
191            let backend = TransportBackend::Sockudo;
192
193            kwargs
194                .set_item("api_key_id", "python-distinct-key")
195                .unwrap();
196            kwargs
197                .set_item("private_key", "python-distinct-private")
198                .unwrap();
199            kwargs
200                .set_item("base_url_http", "http://secret-host/path")
201                .unwrap();
202            kwargs
203                .set_item("base_url_ws", "ws://secret-ws/path")
204                .unwrap();
205            kwargs
206                .set_item("proxy_url", "http://user:python-proxy@localhost:12000")
207                .unwrap();
208            kwargs.set_item("http_timeout_secs", 17).unwrap();
209            kwargs.set_item("ws_timeout_secs", 19).unwrap();
210            kwargs
211                .set_item("environment", KalshiEnvironment::Demo)
212                .unwrap();
213            kwargs.set_item("transport_backend", backend).unwrap();
214            if name == "KalshiDataClientConfig" {
215                kwargs.set_item("book_snapshot_timeout_secs", 31).unwrap();
216                kwargs
217                    .set_item("update_instruments_interval_mins", 23)
218                    .unwrap();
219                kwargs
220                    .set_item(
221                        "instrument_ids",
222                        vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
223                    )
224                    .unwrap();
225            } else {
226                kwargs
227                    .set_item("account_id", AccountId::from("KALSHI-PYTHON"))
228                    .unwrap();
229                kwargs.set_item("exchange_index", 3).unwrap();
230            }
231
232            let config = class.call((), Some(&kwargs)).unwrap();
233            if name == "KalshiDataClientConfig" {
234                let actual = config.extract::<KalshiDataClientConfig>().unwrap();
235
236                let expected = KalshiDataClientConfig {
237                    api_key_id: Some("python-distinct-key".into()),
238                    private_key: Some("python-distinct-private".into()),
239                    environment: KalshiEnvironment::Demo,
240                    base_url_http: Some("http://secret-host/path".into()),
241                    base_url_ws: Some("ws://secret-ws/path".into()),
242                    proxy_url: Some("http://user:python-proxy@localhost:12000".into()),
243                    http_timeout_secs: 17,
244                    ws_timeout_secs: 19,
245                    update_instruments_interval_mins: 23,
246                    book_snapshot_timeout_secs: 31,
247                    transport_backend: backend,
248                    instrument_ids: vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
249                };
250
251                assert_eq!(actual, expected);
252                assert_eq!(
253                    default.extract::<KalshiDataClientConfig>().unwrap(),
254                    KalshiDataClientConfig::default()
255                );
256            } else {
257                let actual = config.extract::<KalshiExecutionClientConfig>().unwrap();
258
259                let expected = KalshiExecutionClientConfig {
260                    account_id: AccountId::from("KALSHI-PYTHON"),
261                    api_key_id: Some("python-distinct-key".into()),
262                    private_key: Some("python-distinct-private".into()),
263                    environment: KalshiEnvironment::Demo,
264                    base_url_http: Some("http://secret-host/path".into()),
265                    base_url_ws: Some("ws://secret-ws/path".into()),
266                    proxy_url: Some("http://user:python-proxy@localhost:12000".into()),
267                    http_timeout_secs: 17,
268                    ws_timeout_secs: 19,
269                    exchange_index: 3,
270                    transport_backend: backend,
271                };
272
273                assert_eq!(actual, expected);
274                assert_eq!(
275                    default.extract::<KalshiExecutionClientConfig>().unwrap(),
276                    KalshiExecutionClientConfig::default()
277                );
278            }
279
280            assert_eq!(
281                default
282                    .getattr("http_timeout_secs")
283                    .unwrap()
284                    .extract::<u64>()
285                    .unwrap(),
286                60
287            );
288            assert_eq!(
289                default
290                    .getattr("ws_timeout_secs")
291                    .unwrap()
292                    .extract::<u64>()
293                    .unwrap(),
294                30
295            );
296            assert!(
297                !default
298                    .getattr("has_credentials")
299                    .unwrap()
300                    .extract::<bool>()
301                    .unwrap()
302            );
303            assert!(
304                !default
305                    .getattr("has_proxy_url")
306                    .unwrap()
307                    .extract::<bool>()
308                    .unwrap()
309            );
310            assert_eq!(
311                config
312                    .getattr("http_timeout_secs")
313                    .unwrap()
314                    .extract::<u64>()
315                    .unwrap(),
316                17
317            );
318            assert_eq!(
319                config
320                    .getattr("ws_timeout_secs")
321                    .unwrap()
322                    .extract::<u64>()
323                    .unwrap(),
324                19
325            );
326            assert!(
327                config
328                    .getattr("has_credentials")
329                    .unwrap()
330                    .extract::<bool>()
331                    .unwrap()
332            );
333            assert!(
334                config
335                    .getattr("has_proxy_url")
336                    .unwrap()
337                    .extract::<bool>()
338                    .unwrap()
339            );
340
341            for output in [
342                config.repr().unwrap().to_string(),
343                config.str().unwrap().to_string(),
344            ] {
345                assert_eq!(output.matches("<redacted>").count(), 5);
346
347                for secret in [
348                    "python-distinct-key",
349                    "python-distinct-private",
350                    "secret-host",
351                    "secret-ws",
352                    "python-proxy",
353                ] {
354                    assert!(!output.contains(secret));
355                }
356            }
357
358            for field in [
359                "api_key_id",
360                "private_key",
361                "proxy_url",
362                "base_url_http",
363                "base_url_ws",
364            ] {
365                assert!(!config.hasattr(field).unwrap());
366            }
367
368            kwargs
369                .set_item("transport_backend", TransportBackend::Tungstenite)
370                .unwrap();
371            let error = class.call((), Some(&kwargs)).unwrap_err();
372            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
373            assert!(
374                error
375                    .to_string()
376                    .contains("Kalshi requires the Sockudo WebSocket backend")
377            );
378            kwargs.set_item("transport_backend", backend).unwrap();
379
380            kwargs.set_item("unknown_field", true).unwrap();
381            assert!(
382                class
383                    .call((), Some(&kwargs))
384                    .unwrap_err()
385                    .is_instance_of::<pyo3::exceptions::PyTypeError>(py)
386            );
387            kwargs.del_item("unknown_field").unwrap();
388            kwargs.set_item("http_timeout_secs", 0).unwrap();
389            assert!(
390                class
391                    .call((), Some(&kwargs))
392                    .unwrap_err()
393                    .is_instance_of::<pyo3::exceptions::PyValueError>(py)
394            );
395
396            kwargs.set_item("http_timeout_secs", u64::MAX).unwrap();
397            let error = class.call((), Some(&kwargs)).unwrap_err();
398            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
399            assert_eq!(
400                error.value(py).str().unwrap().to_string(),
401                "invalid http_timeout_secs: exceeds the supported clock range"
402            );
403
404            if name == "KalshiDataClientConfig" {
405                kwargs.set_item("http_timeout_secs", 17).unwrap();
406                kwargs
407                    .set_item(
408                        "instrument_ids",
409                        vec![InstrumentId::from("BTC-USD.BINANCE")],
410                    )
411                    .unwrap();
412                let error = class.call((), Some(&kwargs)).unwrap_err();
413                assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
414                assert!(
415                    error
416                        .to_string()
417                        .contains("instrument venue must be KALSHI")
418                );
419            }
420
421            assert!(!module.hasattr("KalshiExecClientConfig").unwrap());
422        });
423    }
424}