Skip to main content

nautilus_kalshi/
factories.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//! Factories for Kalshi data and execution clients.
17
18use std::{any::Any, cell::RefCell, rc::Rc};
19
20use anyhow::Context;
21use nautilus_common::{
22    cache::CacheView,
23    clients::{DataClient, ExecutionClient},
24    clock::Clock,
25    factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
26    live::runner::try_get_data_event_sender,
27};
28use nautilus_live::ExecutionClientCore;
29use nautilus_model::{
30    enums::{AccountType, OmsType},
31    identifiers::{ClientId, TraderId},
32    types::Currency,
33};
34
35use crate::{
36    common::consts::{KALSHI, KALSHI_VENUE},
37    config::{KalshiDataClientConfig, KalshiExecutionClientConfig},
38    data::KalshiDataClient,
39    execution::KalshiExecutionClient,
40};
41
42impl ClientConfig for KalshiDataClientConfig {
43    fn as_any(&self) -> &dyn Any {
44        self
45    }
46}
47
48impl ClientConfig for KalshiExecutionClientConfig {
49    fn as_any(&self) -> &dyn Any {
50        self
51    }
52}
53
54/// Factory for creating Kalshi data clients.
55///
56/// Streaming is limited to `instrument_ids` on the data config. Construction requires the
57/// calling thread's data-event sender because the client cannot install one later.
58#[derive(Debug, Clone, Default)]
59#[cfg_attr(
60    feature = "python",
61    pyo3::pyclass(module = "nautilus_trader._libnautilus.kalshi", from_py_object)
62)]
63#[cfg_attr(
64    feature = "python",
65    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kalshi")
66)]
67pub struct KalshiDataClientFactory;
68
69impl KalshiDataClientFactory {
70    /// Creates a new [`KalshiDataClientFactory`] instance.
71    #[must_use]
72    pub const fn new() -> Self {
73        Self
74    }
75}
76
77impl DataClientFactory for KalshiDataClientFactory {
78    fn create(
79        &self,
80        name: &str,
81        config: &dyn ClientConfig,
82        cache: CacheView,
83        _clock: Rc<RefCell<dyn Clock>>,
84    ) -> anyhow::Result<Box<dyn DataClient>> {
85        let config = config
86            .as_any()
87            .downcast_ref::<KalshiDataClientConfig>()
88            .ok_or_else(|| {
89                anyhow::anyhow!(
90                    "Invalid config type for KalshiDataClientFactory. Expected KalshiDataClientConfig, was {config:?}"
91                )
92            })?;
93
94        Ok(Box::new(Self::build(name, config, cache)?))
95    }
96
97    fn name(&self) -> &'static str {
98        KALSHI
99    }
100
101    fn config_type(&self) -> &'static str {
102        "KalshiDataClientConfig"
103    }
104}
105
106impl KalshiDataClientFactory {
107    fn build(
108        name: &str,
109        config: &KalshiDataClientConfig,
110        cache: CacheView,
111    ) -> anyhow::Result<KalshiDataClient> {
112        config.validate()?;
113        anyhow::ensure!(
114            !config.instrument_ids.is_empty(),
115            "KalshiDataClientFactory requires at least one instrument_id"
116        );
117
118        let sender = try_get_data_event_sender().context("data event sender is not installed")?;
119        KalshiDataClient::with_runtime(ClientId::from(name), config.clone(), sender, cache)
120    }
121}
122
123/// Factory for creating Kalshi execution clients.
124///
125/// The node supplies `trader_id`. The client always uses a USD cash account and netting OMS.
126/// A bound execution sender is installed during construction; `start` installs the sender again.
127#[derive(Debug, Clone, Default)]
128#[cfg_attr(
129    feature = "python",
130    pyo3::pyclass(module = "nautilus_trader._libnautilus.kalshi", from_py_object)
131)]
132#[cfg_attr(
133    feature = "python",
134    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.kalshi")
135)]
136pub struct KalshiExecutionClientFactory;
137
138impl KalshiExecutionClientFactory {
139    /// Creates a new [`KalshiExecutionClientFactory`] instance.
140    #[must_use]
141    pub const fn new() -> Self {
142        Self
143    }
144}
145
146impl ExecutionClientFactory for KalshiExecutionClientFactory {
147    fn create(
148        &self,
149        trader_id: TraderId,
150        name: &str,
151        config: &dyn ClientConfig,
152        cache: CacheView,
153        clock: Rc<RefCell<dyn Clock>>,
154    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
155        let config = config
156            .as_any()
157            .downcast_ref::<KalshiExecutionClientConfig>()
158            .ok_or_else(|| {
159                anyhow::anyhow!(
160                    "Invalid config type for KalshiExecutionClientFactory. Expected KalshiExecutionClientConfig, was {config:?}"
161                )
162            })?;
163
164        Ok(Box::new(Self::build(
165            trader_id, name, config, cache, clock,
166        )?))
167    }
168
169    fn name(&self) -> &'static str {
170        KALSHI
171    }
172
173    fn config_type(&self) -> &'static str {
174        "KalshiExecutionClientConfig"
175    }
176}
177
178impl KalshiExecutionClientFactory {
179    fn build(
180        trader_id: TraderId,
181        name: &str,
182        config: &KalshiExecutionClientConfig,
183        cache: CacheView,
184        _clock: Rc<RefCell<dyn Clock>>,
185    ) -> anyhow::Result<KalshiExecutionClient> {
186        config.validate()?;
187
188        let core = ExecutionClientCore::new(
189            trader_id,
190            ClientId::from(name),
191            *KALSHI_VENUE,
192            OmsType::Netting,
193            config.account_id,
194            AccountType::Cash,
195            Some(Currency::USD()),
196            cache,
197        );
198
199        KalshiExecutionClient::new(core, config.clone())
200    }
201}
202
203#[cfg(test)]
204#[cfg(not(all(feature = "simulation", madsim)))] // Factory fixtures require native proxies and threads
205mod tests {
206    use std::{cell::RefCell, rc::Rc};
207
208    use nautilus_common::{
209        cache::Cache,
210        clock::VirtualClock,
211        enums::Environment,
212        live::runner::{replace_data_event_sender, replace_exec_event_sender},
213        messages::{DataEvent, ExecutionEvent},
214    };
215    use nautilus_core::{UUID4, UnixNanos};
216    use nautilus_live::node::LiveNode;
217    use nautilus_model::{
218        accounts::AccountAny,
219        enums::AccountType,
220        events::AccountState,
221        identifiers::{AccountId, ClientId, InstrumentId, Symbol, TraderId},
222        instruments::{BinaryOption, CurrencyPair, Instrument, InstrumentAny},
223        types::{AccountBalance, Currency, Money, Price, Quantity},
224    };
225    use nautilus_network::websocket::TransportBackend;
226    use rstest::rstest;
227
228    use super::*;
229    use crate::{
230        common::enums::KalshiEnvironment,
231        http::{
232            models::{Event, Market},
233            parse::parse_instrument,
234        },
235    };
236
237    #[allow(
238        dead_code,
239        reason = "shared key fixtures serve factory credential setup"
240    )]
241    mod keys {
242        include!(concat!(
243            env!("CARGO_MANIFEST_DIR"),
244            "/tests/integration/keys.rs"
245        ));
246    }
247
248    fn data_config() -> KalshiDataClientConfig {
249        KalshiDataClientConfig {
250            api_key_id: Some("factory-data-key".into()),
251            private_key: Some("factory-data-private".into()),
252            environment: KalshiEnvironment::Demo,
253            base_url_http: Some("http://data-host/path".into()),
254            base_url_ws: Some("ws://data-ws/path".into()),
255            proxy_url: Some("http://user:data-proxy@localhost:12000".into()),
256            http_timeout_secs: 17,
257            ws_timeout_secs: 19,
258            book_snapshot_timeout_secs: 31,
259            update_instruments_interval_mins: 23,
260            transport_backend: TransportBackend::Sockudo,
261            instrument_ids: vec![InstrumentId::from("KXHIGHNY-26OCT31-T70.KALSHI")],
262        }
263    }
264
265    fn exec_config() -> KalshiExecutionClientConfig {
266        KalshiExecutionClientConfig {
267            account_id: AccountId::from("KALSHI-FACTORY"),
268            api_key_id: Some("factory-exec-key".into()),
269            private_key: Some(keys::rsa_pkcs8().into()),
270            environment: KalshiEnvironment::Demo,
271            base_url_http: Some("http://exec-host/path".into()),
272            base_url_ws: Some("ws://exec-ws/path".into()),
273            proxy_url: Some("http://user:exec-proxy@localhost:12001".into()),
274            http_timeout_secs: 41,
275            ws_timeout_secs: 43,
276            exchange_index: 3,
277            subaccount: 7,
278            transport_backend: TransportBackend::Sockudo,
279        }
280    }
281
282    fn live_binary_option() -> BinaryOption {
283        let fixtures: serde_json::Value =
284            serde_json::from_str(include_str!("../test_data/instruments.json")).unwrap();
285        let market: Market =
286            serde_json::from_value(fixtures["definitions"]["live"]["market"].clone()).unwrap();
287        let event: Event =
288            serde_json::from_value(fixtures["definitions"]["live"]["event"].clone()).unwrap();
289        parse_instrument(&market, &event, UnixNanos::from(1)).unwrap()
290    }
291
292    fn foreign_instrument(id: InstrumentId) -> InstrumentAny {
293        let pair = CurrencyPair::builder()
294            .instrument_id(id)
295            .raw_symbol(Symbol::new(id.symbol.as_str()))
296            .base_currency(Currency::from("BTC"))
297            .quote_currency(Currency::from("USDT"))
298            .price_precision(2)
299            .size_precision(0)
300            .price_increment(Price::from("0.01"))
301            .size_increment(Quantity::from("1"))
302            .ts_event(UnixNanos::default())
303            .ts_init(UnixNanos::default())
304            .build()
305            .unwrap();
306        InstrumentAny::CurrencyPair(pair)
307    }
308
309    fn bind_data_sender() {
310        let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel::<DataEvent>();
311        replace_data_event_sender(sender);
312    }
313
314    fn bind_exec_sender() -> tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent> {
315        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
316        replace_exec_event_sender(sender);
317        receiver
318    }
319
320    #[rstest]
321    fn test_factories_name_their_configs() {
322        let data_factory = KalshiDataClientFactory::new();
323        let exec_factory = KalshiExecutionClientFactory::new();
324        assert_eq!(data_factory.name(), KALSHI);
325        assert_eq!(data_factory.config_type(), "KalshiDataClientConfig");
326        assert_eq!(exec_factory.name(), KALSHI);
327        assert_eq!(exec_factory.config_type(), "KalshiExecutionClientConfig");
328    }
329
330    #[rstest]
331    fn test_configs_downcast_through_client_config() {
332        let data = data_config();
333        let execution = exec_config();
334        let data_boxed: Box<dyn ClientConfig> = Box::new(data.clone());
335        let exec_boxed: Box<dyn ClientConfig> = Box::new(execution.clone());
336
337        assert_eq!(
338            data_boxed
339                .as_any()
340                .downcast_ref::<KalshiDataClientConfig>()
341                .unwrap(),
342            &data
343        );
344        assert_eq!(
345            exec_boxed
346                .as_any()
347                .downcast_ref::<KalshiExecutionClientConfig>()
348                .unwrap(),
349            &execution
350        );
351        assert!(
352            data_boxed
353                .as_any()
354                .downcast_ref::<KalshiExecutionClientConfig>()
355                .is_none()
356        );
357    }
358
359    #[rstest]
360    fn test_data_factory_propagates_fields_and_cache() {
361        std::thread::spawn(|| {
362            bind_data_sender();
363            let config = data_config();
364            let cache = Rc::new(RefCell::new(Cache::default()));
365            let marker = ClientId::from("CACHE-MARKER");
366            cache.borrow_mut().add_client_route(marker, *KALSHI_VENUE);
367            let client =
368                KalshiDataClientFactory::build("KALSHI-DATA", &config, cache.into()).unwrap();
369
370            assert_eq!(client.client_id(), ClientId::from("KALSHI-DATA"));
371            assert_eq!(client.venue(), Some(*KALSHI_VENUE));
372            assert_eq!(client.config(), &config);
373            assert_eq!(client.instruments(), config.instrument_ids.as_slice());
374            assert_eq!(
375                client.cache().borrow().client_id_for_venue(&KALSHI_VENUE),
376                Some(&marker)
377            );
378        })
379        .join()
380        .unwrap();
381    }
382
383    #[rstest]
384    fn test_data_factory_rejects_wrong_config_empty_selection_and_missing_sender() {
385        std::thread::spawn(|| {
386            let cache = Rc::new(RefCell::new(Cache::default()));
387            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
388            let wrong = KalshiDataClientFactory.create(
389                "KALSHI",
390                &exec_config(),
391                cache.clone().into(),
392                Rc::clone(&clock),
393            );
394
395            let Err(e) = wrong else {
396                panic!("wrong config type should be rejected");
397            };
398
399            let message = e.to_string();
400            assert!(message.contains("KalshiDataClientFactory"), "{message}");
401            assert!(message.contains("KalshiDataClientConfig"), "{message}");
402
403            bind_data_sender();
404            let empty = KalshiDataClientConfig::default();
405            let message = KalshiDataClientFactory::build("KALSHI", &empty, cache.into())
406                .unwrap_err()
407                .to_string();
408            assert!(message.contains("instrument_id"), "{message}");
409
410            let unbound = std::thread::spawn(|| {
411                let cache = Rc::new(RefCell::new(Cache::default()));
412                KalshiDataClientFactory::build("KALSHI", &data_config(), cache.into())
413                    .unwrap_err()
414                    .to_string()
415            })
416            .join()
417            .unwrap();
418
419            assert!(unbound.contains("data event sender"), "{unbound}");
420        })
421        .join()
422        .unwrap();
423    }
424
425    #[rstest]
426    fn test_data_factory_uses_cached_instrument_type() {
427        std::thread::spawn(|| {
428            bind_data_sender();
429            let instrument = live_binary_option();
430            let id = instrument.id();
431            let mut config = data_config();
432            config.instrument_ids = vec![id];
433            let accepted = Rc::new(RefCell::new(Cache::default()));
434            accepted
435                .borrow_mut()
436                .add_instrument(InstrumentAny::BinaryOption(instrument))
437                .unwrap();
438
439            let client =
440                KalshiDataClientFactory::build("KALSHI", &config, accepted.into()).unwrap();
441
442            assert_eq!(client.instruments(), &[id]);
443
444            let rejected = Rc::new(RefCell::new(Cache::default()));
445            rejected
446                .borrow_mut()
447                .add_instrument(foreign_instrument(id))
448                .unwrap();
449            let message = KalshiDataClientFactory::build("KALSHI", &config, rejected.into())
450                .unwrap_err()
451                .to_string();
452            assert!(message.contains("not a Kalshi binary option"), "{message}");
453        })
454        .join()
455        .unwrap();
456    }
457
458    #[rstest]
459    fn test_execution_factory_propagates_fields_and_initializes_emitter() {
460        std::thread::spawn(|| {
461            let mut output = bind_exec_sender();
462            let trader_id = TraderId::from("TRADER-009");
463            let config = exec_config();
464            let cache = Rc::new(RefCell::new(Cache::default()));
465            let zero = Money::zero(Currency::USD());
466
467            let event = AccountState::new(
468                config.account_id,
469                AccountType::Cash,
470                vec![AccountBalance::new(zero, zero, zero)],
471                Vec::new(),
472                true,
473                UUID4::new(),
474                UnixNanos::from(1),
475                UnixNanos::from(2),
476                Some(Currency::USD()),
477            );
478
479            cache
480                .borrow_mut()
481                .add_account(AccountAny::from(event))
482                .unwrap();
483            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
484
485            let client = KalshiExecutionClientFactory::build(
486                trader_id,
487                "KALSHI-EXEC",
488                &config,
489                cache.into(),
490                Rc::clone(&clock),
491            )
492            .unwrap();
493
494            assert_eq!(client.client_id(), ClientId::from("KALSHI-EXEC"));
495            assert_eq!(client.account_id(), config.account_id);
496            assert_eq!(client.venue(), *KALSHI_VENUE);
497            assert_eq!(client.oms_type(), OmsType::Netting);
498            assert_eq!(client.config(), &config);
499            assert_eq!(client.core().trader_id, trader_id);
500            assert_eq!(client.core().account_type, AccountType::Cash);
501            assert_eq!(client.core().oms_type, OmsType::Netting);
502            assert_eq!(client.core().base_currency, Some(Currency::USD()));
503            assert_eq!(client.get_account().unwrap().id(), config.account_id);
504
505            let balances = vec![AccountBalance::new(
506                Money::from("10 USD"),
507                Money::from("1 USD"),
508                Money::from("9 USD"),
509            )];
510            client
511                .generate_account_state(balances.clone(), vec![], true, UnixNanos::from(9), None)
512                .unwrap();
513
514            let ExecutionEvent::Account(state) = output.try_recv().unwrap() else {
515                panic!("expected account state");
516            };
517
518            assert_eq!(state.account_id, config.account_id);
519            assert_eq!(state.account_type, AccountType::Cash);
520            assert_eq!(state.base_currency, Some(Currency::USD()));
521            assert_eq!(state.balances, balances);
522            assert!(state.is_reported);
523            assert_eq!(state.ts_event, UnixNanos::from(9));
524        })
525        .join()
526        .unwrap();
527    }
528
529    #[rstest]
530    fn test_execution_factory_rejects_wrong_config_and_defers_missing_sender() {
531        std::thread::spawn(|| {
532            let cache = Rc::new(RefCell::new(Cache::default()));
533            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
534            let wrong = KalshiExecutionClientFactory.create(
535                TraderId::from("TRADER-001"),
536                "KALSHI",
537                &data_config(),
538                cache.clone().into(),
539                Rc::clone(&clock),
540            );
541
542            let Err(e) = wrong else {
543                panic!("wrong config type should be rejected");
544            };
545
546            let message = e.to_string();
547            assert!(
548                message.contains("KalshiExecutionClientFactory"),
549                "{message}"
550            );
551            assert!(message.contains("KalshiExecutionClientConfig"), "{message}");
552
553            let mut client = KalshiExecutionClientFactory::build(
554                TraderId::from("TRADER-001"),
555                "KALSHI",
556                &exec_config(),
557                cache.into(),
558                clock,
559            )
560            .unwrap();
561            let message = client.start().unwrap_err().to_string();
562            assert!(message.contains("execution sender"), "{message}");
563            bind_exec_sender();
564            client.start().unwrap();
565        })
566        .join()
567        .unwrap();
568    }
569
570    #[rstest]
571    fn test_execution_start_installs_rebound_sender() {
572        std::thread::spawn(|| {
573            let mut first = bind_exec_sender();
574            let cache = Rc::new(RefCell::new(Cache::default()));
575            let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
576            let mut client = KalshiExecutionClientFactory::build(
577                TraderId::from("TRADER-001"),
578                "KALSHI",
579                &exec_config(),
580                cache.into(),
581                clock,
582            )
583            .unwrap();
584            let mut second = bind_exec_sender();
585            client.start().unwrap();
586            let balances = vec![AccountBalance::new(
587                Money::from("10 USD"),
588                Money::from("1 USD"),
589                Money::from("9 USD"),
590            )];
591            client
592                .generate_account_state(balances, vec![], true, UnixNanos::from(9), None)
593                .unwrap();
594
595            assert!(first.try_recv().is_err());
596
597            let ExecutionEvent::Account(state) = second.try_recv().unwrap() else {
598                panic!("expected account state on the rebound sender");
599            };
600
601            assert_eq!(state.account_id, exec_config().account_id);
602            assert_eq!(state.ts_event, UnixNanos::from(9));
603        })
604        .join()
605        .unwrap();
606    }
607
608    #[rstest]
609    fn test_live_node_constructs_kalshi_clients() {
610        std::thread::spawn(|| {
611            let trader_id = TraderId::from("TRADER-001");
612            let node = LiveNode::builder(trader_id, Environment::Sandbox)
613                .unwrap()
614                .with_name("KALSHI-FACTORY-NODE".to_string())
615                .add_data_client(
616                    None,
617                    Box::new(KalshiDataClientFactory::new()),
618                    Box::new(data_config()),
619                )
620                .unwrap()
621                .add_exec_client(
622                    None,
623                    Box::new(KalshiExecutionClientFactory::new()),
624                    Box::new(exec_config()),
625                )
626                .unwrap()
627                .build()
628                .unwrap();
629
630            assert_eq!(node.trader_id(), trader_id);
631        })
632        .join()
633        .unwrap();
634    }
635}