1use 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#[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 #[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#[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 #[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)))] mod 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 transport_backend: TransportBackend::Sockudo,
278 }
279 }
280
281 fn live_binary_option() -> BinaryOption {
282 let fixtures: serde_json::Value =
283 serde_json::from_str(include_str!("../test_data/instruments.json")).unwrap();
284 let market: Market =
285 serde_json::from_value(fixtures["definitions"]["live"]["market"].clone()).unwrap();
286 let event: Event =
287 serde_json::from_value(fixtures["definitions"]["live"]["event"].clone()).unwrap();
288 parse_instrument(&market, &event, UnixNanos::from(1)).unwrap()
289 }
290
291 fn foreign_instrument(id: InstrumentId) -> InstrumentAny {
292 let pair = CurrencyPair::builder()
293 .instrument_id(id)
294 .raw_symbol(Symbol::new(id.symbol.as_str()))
295 .base_currency(Currency::from("BTC"))
296 .quote_currency(Currency::from("USDT"))
297 .price_precision(2)
298 .size_precision(0)
299 .price_increment(Price::from("0.01"))
300 .size_increment(Quantity::from("1"))
301 .ts_event(UnixNanos::default())
302 .ts_init(UnixNanos::default())
303 .build()
304 .unwrap();
305 InstrumentAny::CurrencyPair(pair)
306 }
307
308 fn bind_data_sender() {
309 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel::<DataEvent>();
310 replace_data_event_sender(sender);
311 }
312
313 fn bind_exec_sender() -> tokio::sync::mpsc::UnboundedReceiver<ExecutionEvent> {
314 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
315 replace_exec_event_sender(sender);
316 receiver
317 }
318
319 #[rstest]
320 fn test_factories_name_their_configs() {
321 let data_factory = KalshiDataClientFactory::new();
322 let exec_factory = KalshiExecutionClientFactory::new();
323 assert_eq!(data_factory.name(), KALSHI);
324 assert_eq!(data_factory.config_type(), "KalshiDataClientConfig");
325 assert_eq!(exec_factory.name(), KALSHI);
326 assert_eq!(exec_factory.config_type(), "KalshiExecutionClientConfig");
327 }
328
329 #[rstest]
330 fn test_configs_downcast_through_client_config() {
331 let data = data_config();
332 let execution = exec_config();
333 let data_boxed: Box<dyn ClientConfig> = Box::new(data.clone());
334 let exec_boxed: Box<dyn ClientConfig> = Box::new(execution.clone());
335
336 assert_eq!(
337 data_boxed
338 .as_any()
339 .downcast_ref::<KalshiDataClientConfig>()
340 .unwrap(),
341 &data
342 );
343 assert_eq!(
344 exec_boxed
345 .as_any()
346 .downcast_ref::<KalshiExecutionClientConfig>()
347 .unwrap(),
348 &execution
349 );
350 assert!(
351 data_boxed
352 .as_any()
353 .downcast_ref::<KalshiExecutionClientConfig>()
354 .is_none()
355 );
356 }
357
358 #[rstest]
359 fn test_data_factory_propagates_fields_and_cache() {
360 std::thread::spawn(|| {
361 bind_data_sender();
362 let config = data_config();
363 let cache = Rc::new(RefCell::new(Cache::default()));
364 let marker = ClientId::from("CACHE-MARKER");
365 cache.borrow_mut().add_client_route(marker, *KALSHI_VENUE);
366 let client =
367 KalshiDataClientFactory::build("KALSHI-DATA", &config, cache.into()).unwrap();
368
369 assert_eq!(client.client_id(), ClientId::from("KALSHI-DATA"));
370 assert_eq!(client.venue(), Some(*KALSHI_VENUE));
371 assert_eq!(client.config(), &config);
372 assert_eq!(client.instruments(), config.instrument_ids.as_slice());
373 assert_eq!(
374 client.cache().borrow().client_id_for_venue(&KALSHI_VENUE),
375 Some(&marker)
376 );
377 })
378 .join()
379 .unwrap();
380 }
381
382 #[rstest]
383 fn test_data_factory_rejects_wrong_config_empty_selection_and_missing_sender() {
384 std::thread::spawn(|| {
385 let cache = Rc::new(RefCell::new(Cache::default()));
386 let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
387 let wrong = KalshiDataClientFactory.create(
388 "KALSHI",
389 &exec_config(),
390 cache.clone().into(),
391 Rc::clone(&clock),
392 );
393
394 let Err(e) = wrong else {
395 panic!("wrong config type should be rejected");
396 };
397
398 let message = e.to_string();
399 assert!(message.contains("KalshiDataClientFactory"), "{message}");
400 assert!(message.contains("KalshiDataClientConfig"), "{message}");
401
402 bind_data_sender();
403 let empty = KalshiDataClientConfig::default();
404 let message = KalshiDataClientFactory::build("KALSHI", &empty, cache.into())
405 .unwrap_err()
406 .to_string();
407 assert!(message.contains("instrument_id"), "{message}");
408
409 let unbound = std::thread::spawn(|| {
410 let cache = Rc::new(RefCell::new(Cache::default()));
411 KalshiDataClientFactory::build("KALSHI", &data_config(), cache.into())
412 .unwrap_err()
413 .to_string()
414 })
415 .join()
416 .unwrap();
417
418 assert!(unbound.contains("data event sender"), "{unbound}");
419 })
420 .join()
421 .unwrap();
422 }
423
424 #[rstest]
425 fn test_data_factory_uses_cached_instrument_type() {
426 std::thread::spawn(|| {
427 bind_data_sender();
428 let instrument = live_binary_option();
429 let id = instrument.id();
430 let mut config = data_config();
431 config.instrument_ids = vec![id];
432 let accepted = Rc::new(RefCell::new(Cache::default()));
433 accepted
434 .borrow_mut()
435 .add_instrument(InstrumentAny::BinaryOption(instrument))
436 .unwrap();
437
438 let client =
439 KalshiDataClientFactory::build("KALSHI", &config, accepted.into()).unwrap();
440
441 assert_eq!(client.instruments(), &[id]);
442
443 let rejected = Rc::new(RefCell::new(Cache::default()));
444 rejected
445 .borrow_mut()
446 .add_instrument(foreign_instrument(id))
447 .unwrap();
448 let message = KalshiDataClientFactory::build("KALSHI", &config, rejected.into())
449 .unwrap_err()
450 .to_string();
451 assert!(message.contains("not a Kalshi binary option"), "{message}");
452 })
453 .join()
454 .unwrap();
455 }
456
457 #[rstest]
458 fn test_execution_factory_propagates_fields_and_initializes_emitter() {
459 std::thread::spawn(|| {
460 let mut output = bind_exec_sender();
461 let trader_id = TraderId::from("TRADER-009");
462 let config = exec_config();
463 let cache = Rc::new(RefCell::new(Cache::default()));
464 let zero = Money::zero(Currency::USD());
465
466 let event = AccountState::new(
467 config.account_id,
468 AccountType::Cash,
469 vec![AccountBalance::new(zero, zero, zero)],
470 Vec::new(),
471 true,
472 UUID4::new(),
473 UnixNanos::from(1),
474 UnixNanos::from(2),
475 Some(Currency::USD()),
476 );
477
478 cache
479 .borrow_mut()
480 .add_account(AccountAny::from(event))
481 .unwrap();
482 let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
483
484 let client = KalshiExecutionClientFactory::build(
485 trader_id,
486 "KALSHI-EXEC",
487 &config,
488 cache.into(),
489 Rc::clone(&clock),
490 )
491 .unwrap();
492
493 assert_eq!(client.client_id(), ClientId::from("KALSHI-EXEC"));
494 assert_eq!(client.account_id(), config.account_id);
495 assert_eq!(client.venue(), *KALSHI_VENUE);
496 assert_eq!(client.oms_type(), OmsType::Netting);
497 assert_eq!(client.config(), &config);
498 assert_eq!(client.core().trader_id, trader_id);
499 assert_eq!(client.core().account_type, AccountType::Cash);
500 assert_eq!(client.core().oms_type, OmsType::Netting);
501 assert_eq!(client.core().base_currency, Some(Currency::USD()));
502 assert_eq!(client.get_account().unwrap().id(), config.account_id);
503
504 let balances = vec![AccountBalance::new(
505 Money::from("10 USD"),
506 Money::from("1 USD"),
507 Money::from("9 USD"),
508 )];
509 client
510 .generate_account_state(balances.clone(), vec![], true, UnixNanos::from(9), None)
511 .unwrap();
512
513 let ExecutionEvent::Account(state) = output.try_recv().unwrap() else {
514 panic!("expected account state");
515 };
516
517 assert_eq!(state.account_id, config.account_id);
518 assert_eq!(state.account_type, AccountType::Cash);
519 assert_eq!(state.base_currency, Some(Currency::USD()));
520 assert_eq!(state.balances, balances);
521 assert!(state.is_reported);
522 assert_eq!(state.ts_event, UnixNanos::from(9));
523 })
524 .join()
525 .unwrap();
526 }
527
528 #[rstest]
529 fn test_execution_factory_rejects_wrong_config_and_defers_missing_sender() {
530 std::thread::spawn(|| {
531 let cache = Rc::new(RefCell::new(Cache::default()));
532 let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
533 let wrong = KalshiExecutionClientFactory.create(
534 TraderId::from("TRADER-001"),
535 "KALSHI",
536 &data_config(),
537 cache.clone().into(),
538 Rc::clone(&clock),
539 );
540
541 let Err(e) = wrong else {
542 panic!("wrong config type should be rejected");
543 };
544
545 let message = e.to_string();
546 assert!(
547 message.contains("KalshiExecutionClientFactory"),
548 "{message}"
549 );
550 assert!(message.contains("KalshiExecutionClientConfig"), "{message}");
551
552 let mut client = KalshiExecutionClientFactory::build(
553 TraderId::from("TRADER-001"),
554 "KALSHI",
555 &exec_config(),
556 cache.into(),
557 clock,
558 )
559 .unwrap();
560 let message = client.start().unwrap_err().to_string();
561 assert!(message.contains("execution sender"), "{message}");
562 bind_exec_sender();
563 client.start().unwrap();
564 })
565 .join()
566 .unwrap();
567 }
568
569 #[rstest]
570 fn test_execution_start_installs_rebound_sender() {
571 std::thread::spawn(|| {
572 let mut first = bind_exec_sender();
573 let cache = Rc::new(RefCell::new(Cache::default()));
574 let clock: Rc<RefCell<dyn Clock>> = Rc::new(RefCell::new(VirtualClock::new()));
575 let mut client = KalshiExecutionClientFactory::build(
576 TraderId::from("TRADER-001"),
577 "KALSHI",
578 &exec_config(),
579 cache.into(),
580 clock,
581 )
582 .unwrap();
583 let mut second = bind_exec_sender();
584 client.start().unwrap();
585 let balances = vec![AccountBalance::new(
586 Money::from("10 USD"),
587 Money::from("1 USD"),
588 Money::from("9 USD"),
589 )];
590 client
591 .generate_account_state(balances, vec![], true, UnixNanos::from(9), None)
592 .unwrap();
593
594 assert!(first.try_recv().is_err());
595
596 let ExecutionEvent::Account(state) = second.try_recv().unwrap() else {
597 panic!("expected account state on the rebound sender");
598 };
599
600 assert_eq!(state.account_id, exec_config().account_id);
601 assert_eq!(state.ts_event, UnixNanos::from(9));
602 })
603 .join()
604 .unwrap();
605 }
606
607 #[rstest]
608 fn test_live_node_constructs_kalshi_clients() {
609 std::thread::spawn(|| {
610 let trader_id = TraderId::from("TRADER-001");
611 let node = LiveNode::builder(trader_id, Environment::Sandbox)
612 .unwrap()
613 .with_name("KALSHI-FACTORY-NODE".to_string())
614 .add_data_client(
615 None,
616 Box::new(KalshiDataClientFactory::new()),
617 Box::new(data_config()),
618 )
619 .unwrap()
620 .add_exec_client(
621 None,
622 Box::new(KalshiExecutionClientFactory::new()),
623 Box::new(exec_config()),
624 )
625 .unwrap()
626 .build()
627 .unwrap();
628
629 assert_eq!(node.trader_id(), trader_id);
630 })
631 .join()
632 .unwrap();
633 }
634}