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, subaccount = 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        subaccount: Option<u32>,
132    ) -> PyResult<Self> {
133        let defaults = Self::default();
134
135        let config = Self {
136            account_id: account_id.unwrap_or(defaults.account_id),
137            subaccount: subaccount.unwrap_or(defaults.subaccount),
138            api_key_id: api_key_id.map(SecretString::from),
139            private_key: private_key.map(SecretString::from),
140            environment: environment.unwrap_or(defaults.environment),
141            base_url_http: base_url_http.map(SecretString::from),
142            base_url_ws: base_url_ws.map(SecretString::from),
143            proxy_url: proxy_url.map(SecretString::from),
144            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
145            ws_timeout_secs: ws_timeout_secs.unwrap_or(defaults.ws_timeout_secs),
146            exchange_index: exchange_index.unwrap_or(defaults.exchange_index),
147            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
148        };
149
150        config.validate().map_err(config_error_to_pyvalue_err)?;
151        Ok(config)
152    }
153
154    /// Returns whether both explicit credential fields contain non-empty values.
155    #[getter(has_credentials)]
156    fn py_has_credentials(&self) -> bool {
157        Self::has_credentials(self)
158    }
159
160    #[getter]
161    const fn has_proxy_url(&self) -> bool {
162        self.proxy_url.is_some()
163    }
164
165    fn __repr__(&self) -> String {
166        format!("{self:?}")
167    }
168
169    fn __str__(&self) -> String {
170        self.__repr__()
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use pyo3::types::PyDict;
177    use rstest::rstest;
178
179    use super::*;
180
181    #[rstest]
182    #[case("KalshiDataClientConfig")]
183    #[case("KalshiExecutionClientConfig")]
184    fn test_python_constructor_defaults_and_secret_representations(#[case] name: &str) {
185        Python::initialize();
186        Python::attach(|py| {
187            let module = PyModule::new(py, "kalshi").unwrap();
188            crate::python::kalshi(&module).unwrap();
189            let class = module.getattr(name).unwrap();
190            let default = class.call0().unwrap();
191            let kwargs = PyDict::new(py);
192
193            let backend = TransportBackend::Sockudo;
194
195            kwargs
196                .set_item("api_key_id", "python-distinct-key")
197                .unwrap();
198            kwargs
199                .set_item("private_key", "python-distinct-private")
200                .unwrap();
201            kwargs
202                .set_item("base_url_http", "http://secret-host/path")
203                .unwrap();
204            kwargs
205                .set_item("base_url_ws", "ws://secret-ws/path")
206                .unwrap();
207            kwargs
208                .set_item("proxy_url", "http://user:python-proxy@localhost:12000")
209                .unwrap();
210            kwargs.set_item("http_timeout_secs", 17).unwrap();
211            kwargs.set_item("ws_timeout_secs", 19).unwrap();
212            kwargs
213                .set_item("environment", KalshiEnvironment::Demo)
214                .unwrap();
215            kwargs.set_item("transport_backend", backend).unwrap();
216            if name == "KalshiDataClientConfig" {
217                kwargs.set_item("book_snapshot_timeout_secs", 31).unwrap();
218                kwargs
219                    .set_item("update_instruments_interval_mins", 23)
220                    .unwrap();
221                kwargs
222                    .set_item(
223                        "instrument_ids",
224                        vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
225                    )
226                    .unwrap();
227            } else {
228                kwargs
229                    .set_item("account_id", AccountId::from("KALSHI-PYTHON"))
230                    .unwrap();
231                kwargs.set_item("exchange_index", 3).unwrap();
232                kwargs.set_item("subaccount", 7).unwrap();
233            }
234
235            let config = class.call((), Some(&kwargs)).unwrap();
236            if name == "KalshiDataClientConfig" {
237                let actual = config.extract::<KalshiDataClientConfig>().unwrap();
238
239                let expected = KalshiDataClientConfig {
240                    api_key_id: Some("python-distinct-key".into()),
241                    private_key: Some("python-distinct-private".into()),
242                    environment: KalshiEnvironment::Demo,
243                    base_url_http: Some("http://secret-host/path".into()),
244                    base_url_ws: Some("ws://secret-ws/path".into()),
245                    proxy_url: Some("http://user:python-proxy@localhost:12000".into()),
246                    http_timeout_secs: 17,
247                    ws_timeout_secs: 19,
248                    update_instruments_interval_mins: 23,
249                    book_snapshot_timeout_secs: 31,
250                    transport_backend: backend,
251                    instrument_ids: vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
252                };
253
254                assert_eq!(actual, expected);
255                assert_eq!(
256                    default.extract::<KalshiDataClientConfig>().unwrap(),
257                    KalshiDataClientConfig::default()
258                );
259            } else {
260                let actual = config.extract::<KalshiExecutionClientConfig>().unwrap();
261
262                let expected = KalshiExecutionClientConfig {
263                    account_id: AccountId::from("KALSHI-PYTHON"),
264                    api_key_id: Some("python-distinct-key".into()),
265                    private_key: Some("python-distinct-private".into()),
266                    environment: KalshiEnvironment::Demo,
267                    base_url_http: Some("http://secret-host/path".into()),
268                    base_url_ws: Some("ws://secret-ws/path".into()),
269                    proxy_url: Some("http://user:python-proxy@localhost:12000".into()),
270                    http_timeout_secs: 17,
271                    ws_timeout_secs: 19,
272                    exchange_index: 3,
273                    transport_backend: backend,
274                    subaccount: 7,
275                };
276
277                assert_eq!(actual, expected);
278                assert_eq!(
279                    default.extract::<KalshiExecutionClientConfig>().unwrap(),
280                    KalshiExecutionClientConfig::default()
281                );
282            }
283
284            assert_eq!(
285                default
286                    .getattr("http_timeout_secs")
287                    .unwrap()
288                    .extract::<u64>()
289                    .unwrap(),
290                60
291            );
292            assert_eq!(
293                default
294                    .getattr("ws_timeout_secs")
295                    .unwrap()
296                    .extract::<u64>()
297                    .unwrap(),
298                30
299            );
300            assert!(
301                !default
302                    .getattr("has_credentials")
303                    .unwrap()
304                    .extract::<bool>()
305                    .unwrap()
306            );
307            assert!(
308                !default
309                    .getattr("has_proxy_url")
310                    .unwrap()
311                    .extract::<bool>()
312                    .unwrap()
313            );
314            assert_eq!(
315                config
316                    .getattr("http_timeout_secs")
317                    .unwrap()
318                    .extract::<u64>()
319                    .unwrap(),
320                17
321            );
322            assert_eq!(
323                config
324                    .getattr("ws_timeout_secs")
325                    .unwrap()
326                    .extract::<u64>()
327                    .unwrap(),
328                19
329            );
330            assert!(
331                config
332                    .getattr("has_credentials")
333                    .unwrap()
334                    .extract::<bool>()
335                    .unwrap()
336            );
337            assert!(
338                config
339                    .getattr("has_proxy_url")
340                    .unwrap()
341                    .extract::<bool>()
342                    .unwrap()
343            );
344
345            for output in [
346                config.repr().unwrap().to_string(),
347                config.str().unwrap().to_string(),
348            ] {
349                assert_eq!(output.matches("<redacted>").count(), 5);
350
351                for secret in [
352                    "python-distinct-key",
353                    "python-distinct-private",
354                    "secret-host",
355                    "secret-ws",
356                    "python-proxy",
357                ] {
358                    assert!(!output.contains(secret));
359                }
360            }
361
362            for field in [
363                "api_key_id",
364                "private_key",
365                "proxy_url",
366                "base_url_http",
367                "base_url_ws",
368            ] {
369                assert!(!config.hasattr(field).unwrap());
370            }
371
372            kwargs
373                .set_item("transport_backend", TransportBackend::Tungstenite)
374                .unwrap();
375            let error = class.call((), Some(&kwargs)).unwrap_err();
376            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
377            assert!(
378                error
379                    .to_string()
380                    .contains("Kalshi requires the Sockudo WebSocket backend")
381            );
382            kwargs.set_item("transport_backend", backend).unwrap();
383
384            kwargs.set_item("unknown_field", true).unwrap();
385            assert!(
386                class
387                    .call((), Some(&kwargs))
388                    .unwrap_err()
389                    .is_instance_of::<pyo3::exceptions::PyTypeError>(py)
390            );
391            kwargs.del_item("unknown_field").unwrap();
392            kwargs.set_item("http_timeout_secs", 0).unwrap();
393            assert!(
394                class
395                    .call((), Some(&kwargs))
396                    .unwrap_err()
397                    .is_instance_of::<pyo3::exceptions::PyValueError>(py)
398            );
399
400            kwargs.set_item("http_timeout_secs", u64::MAX).unwrap();
401            let error = class.call((), Some(&kwargs)).unwrap_err();
402            assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
403            assert_eq!(
404                error.value(py).str().unwrap().to_string(),
405                "invalid http_timeout_secs: exceeds the supported clock range"
406            );
407
408            if name == "KalshiDataClientConfig" {
409                kwargs.set_item("http_timeout_secs", 17).unwrap();
410                kwargs
411                    .set_item(
412                        "instrument_ids",
413                        vec![InstrumentId::from("BTC-USD.BINANCE")],
414                    )
415                    .unwrap();
416                let error = class.call((), Some(&kwargs)).unwrap_err();
417                assert!(error.is_instance_of::<pyo3::exceptions::PyValueError>(py));
418                assert!(
419                    error
420                        .to_string()
421                        .contains("instrument venue must be KALSHI")
422                );
423            }
424
425            assert!(!module.hasattr("KalshiExecClientConfig").unwrap());
426        });
427    }
428}