Skip to main content

nautilus_kalshi/python/
mod.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 bindings from `pyo3`.
17
18mod config;
19mod factories;
20
21use std::sync::OnceLock;
22
23use nautilus_common::factories::{ClientConfig, DataClientFactory, ExecutionClientFactory};
24use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
25use nautilus_system::get_global_pyo3_registry;
26use pyo3::prelude::*;
27
28use crate::{
29    common::{
30        consts::{KALSHI, KALSHI_CLIENT_ID, KALSHI_VENUE},
31        enums::KalshiEnvironment,
32    },
33    config::{KalshiDataClientConfig, KalshiExecutionClientConfig},
34    factories::{KalshiDataClientFactory, KalshiExecutionClientFactory},
35};
36
37#[expect(clippy::needless_pass_by_value)]
38fn extract_kalshi_data_factory(
39    py: Python<'_>,
40    factory: Py<PyAny>,
41) -> PyResult<Box<dyn DataClientFactory>> {
42    match factory.extract::<KalshiDataClientFactory>(py) {
43        Ok(factory) => Ok(Box::new(factory)),
44        Err(e) => Err(to_pyvalue_err(format!(
45            "Failed to extract KalshiDataClientFactory: {e}"
46        ))),
47    }
48}
49
50#[expect(clippy::needless_pass_by_value)]
51fn extract_kalshi_exec_factory(
52    py: Python<'_>,
53    factory: Py<PyAny>,
54) -> PyResult<Box<dyn ExecutionClientFactory>> {
55    match factory.extract::<KalshiExecutionClientFactory>(py) {
56        Ok(factory) => Ok(Box::new(factory)),
57        Err(e) => Err(to_pyvalue_err(format!(
58            "Failed to extract KalshiExecutionClientFactory: {e}"
59        ))),
60    }
61}
62
63#[expect(clippy::needless_pass_by_value)]
64fn extract_kalshi_data_config(
65    py: Python<'_>,
66    config: Py<PyAny>,
67) -> PyResult<Box<dyn ClientConfig>> {
68    match config.extract::<KalshiDataClientConfig>(py) {
69        Ok(config) => Ok(Box::new(config)),
70        Err(e) => Err(to_pyvalue_err(format!(
71            "Failed to extract KalshiDataClientConfig: {e}"
72        ))),
73    }
74}
75
76#[expect(clippy::needless_pass_by_value)]
77fn extract_kalshi_exec_config(
78    py: Python<'_>,
79    config: Py<PyAny>,
80) -> PyResult<Box<dyn ClientConfig>> {
81    match config.extract::<KalshiExecutionClientConfig>(py) {
82        Ok(config) => Ok(Box::new(config)),
83        Err(e) => Err(to_pyvalue_err(format!(
84            "Failed to extract KalshiExecutionClientConfig: {e}"
85        ))),
86    }
87}
88
89/// Loaded as `nautilus_trader._libnautilus.kalshi`.
90///
91/// # Errors
92///
93/// Returns an error if a binding or extractor fails to register.
94#[pymodule]
95pub fn kalshi(m: &Bound<'_, PyModule>) -> PyResult<()> {
96    m.add(stringify!(KALSHI), KALSHI)?;
97    m.add(stringify!(KALSHI_CLIENT_ID), *KALSHI_CLIENT_ID)?;
98    m.add(stringify!(KALSHI_VENUE), *KALSHI_VENUE)?;
99    m.add_class::<KalshiEnvironment>()?;
100    m.add_class::<KalshiDataClientConfig>()?;
101    m.add_class::<KalshiDataClientFactory>()?;
102    m.add_class::<KalshiExecutionClientConfig>()?;
103    m.add_class::<KalshiExecutionClientFactory>()?;
104    register_extractors()
105}
106
107fn register_extractors() -> PyResult<()> {
108    static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
109    REGISTERED
110        .get_or_init(register_extractors_once)
111        .clone()
112        .map_err(to_pyruntime_err)
113}
114
115fn register_extractors_once() -> Result<(), String> {
116    let registry = get_global_pyo3_registry();
117    registry
118        .register_factory_extractor(KALSHI.to_string(), extract_kalshi_data_factory)
119        .map_err(|e| format!("Failed to register Kalshi data factory extractor: {e}"))?;
120    registry
121        .register_exec_factory_extractor(KALSHI.to_string(), extract_kalshi_exec_factory)
122        .map_err(|e| format!("Failed to register Kalshi exec factory extractor: {e}"))?;
123    registry
124        .register_config_extractor(
125            "KalshiDataClientConfig".to_string(),
126            extract_kalshi_data_config,
127        )
128        .map_err(|e| format!("Failed to register Kalshi data config extractor: {e}"))?;
129    registry
130        .register_config_extractor(
131            "KalshiExecutionClientConfig".to_string(),
132            extract_kalshi_exec_config,
133        )
134        .map_err(|e| format!("Failed to register Kalshi exec config extractor: {e}"))?;
135
136    Ok(())
137}