nautilus_kalshi/websocket/
client.rs1use std::{
19 collections::BTreeMap,
20 fmt::Debug,
21 sync::{
22 Arc, Mutex,
23 atomic::{AtomicBool, AtomicU64, Ordering},
24 },
25 time::Duration,
26};
27
28use nautilus_common::live::dst::time;
29use nautilus_core::{string::secret::SecretString, time::get_atomic_clock_realtime};
30use nautilus_live::task::TaskGroup;
31use nautilus_network::websocket::{
32 AuthTracker, MessageHandler, SubscriptionState, WebSocketClient, WebSocketConfig,
33};
34use tokio_util::sync::CancellationToken;
35use url::Url;
36
37use super::{
38 error::KalshiWsError,
39 handler::{HandlerCommand, KalshiWsHandler},
40 messages::{KalshiSubscription, KalshiUpdateAction, KalshiWsMessage},
41};
42use crate::{common::credential::KalshiCredential, config::KalshiDataClientConfig};
43
44#[derive(Debug, Clone, PartialEq)]
46pub enum KalshiWsEvent {
47 Ready { generation: u64 },
49 Message {
51 generation: u64,
52 message: KalshiWsMessage,
53 },
54 Error { generation: u64, message: String },
56 BookSequenceGap { generation: u64, sid: u64 },
58 BookSnapshotRequested {
60 generation: u64,
61 sid: u64,
62 id: u64,
63 attempt: u64,
64 },
65}
66
67impl KalshiWsEvent {
68 pub(crate) fn generation(&self) -> u64 {
69 match self {
70 Self::Ready { generation }
71 | Self::Message { generation, .. }
72 | Self::Error { generation, .. }
73 | Self::BookSequenceGap { generation, .. }
74 | Self::BookSnapshotRequested { generation, .. } => *generation,
75 }
76 }
77}
78
79#[derive(Clone)]
87pub struct KalshiWebSocketClient {
88 inner: Arc<Shared>,
89 tasks: Arc<TaskGroup>,
90}
91
92impl Debug for KalshiWebSocketClient {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.debug_struct(stringify!(KalshiWebSocketClient))
95 .field("active", &self.is_active())
96 .finish_non_exhaustive()
97 }
98}
99
100#[allow(
101 clippy::missing_panics_doc,
102 reason = "client state mutex poisoning is not expected"
103)]
104impl KalshiWebSocketClient {
105 pub fn new(
111 config: KalshiDataClientConfig,
112 ) -> anyhow::Result<(Self, tokio::sync::mpsc::UnboundedReceiver<KalshiWsEvent>)> {
113 config.validate()?;
114 let (events, receiver) = tokio::sync::mpsc::unbounded_channel();
115
116 let inner = Arc::new(Shared {
117 config,
118 state: Mutex::new(ClientState::default()),
119 lifecycle: tokio::sync::Mutex::new(()),
120 generation: AtomicU64::new(0),
121 subscriptions: SubscriptionState::new('|'),
122 auth: AuthTracker::new(),
123 ready: AtomicBool::new(false),
124 ready_notify: tokio::sync::Notify::new(),
125 events,
126 });
127
128 Ok((
129 Self {
130 inner,
131 tasks: Arc::new(TaskGroup::new()),
132 },
133 receiver,
134 ))
135 }
136
137 pub async fn connect(&self) -> anyhow::Result<()> {
144 let _lifecycle = self.inner.lifecycle.lock().await;
145
146 let exists = {
147 let state = self
148 .inner
149 .state
150 .lock()
151 .expect("client state lock is not poisoned");
152 anyhow::ensure!(!state.disposed, "Kalshi WebSocket client is disposed");
153 state.sender.is_some()
154 };
155
156 if !exists {
157 if !self.tasks.is_open() {
158 self.tasks.start_generation()?;
159 }
160
161 let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
162 let input = sender.clone();
163 let config = connection_config(&self.inner.config)?;
164 self.inner.auth.begin();
165
166 let result = WebSocketClient::epoch_builder()
167 .config(config)
168 .epoch_handler(Arc::new(move |epoch, message| {
169 let _ = input.send(HandlerCommand::Frame {
170 epoch,
171 received: time::Instant::now(),
172 message,
173 });
174 }))
175 .connect()
176 .await;
177
178 let ws_client = match result {
179 Ok(ws_client) => Arc::new(ws_client),
180 Err(e) => {
181 self.inner.auth.fail("Kalshi WebSocket handshake failed");
182 anyhow::bail!(
183 "Kalshi WebSocket connection failed: {}",
184 e.redacted_message()
185 );
186 }
187 };
188
189 ws_client.set_auth_tracker(self.inner.auth.clone(), false);
190 self.inner.auth.succeed();
191 {
192 let mut state = self
193 .inner
194 .state
195 .lock()
196 .expect("client state lock is not poisoned");
197
198 let handler = KalshiWsHandler::new(
199 Arc::clone(&self.inner),
200 Arc::clone(&ws_client),
201 receiver,
202 self.tasks.cancellation_token(),
203 );
204
205 self.tasks.spawn(handler.run())?;
206 state.ws_client = Some(ws_client);
207 state.sender = Some(sender.clone());
208 let _ = sender.send(HandlerCommand::Reconcile);
209 }
210 }
211
212 let timeout = Duration::from_secs(self.inner.config.ws_timeout_secs);
213 if time::timeout(timeout, self.wait_ready()).await.is_err() {
214 self.stop_locked().await?;
215 anyhow::bail!("Kalshi WebSocket subscription restoration timed out");
216 }
217
218 Ok(())
219 }
220
221 async fn wait_ready(&self) {
222 loop {
223 let notified = self.inner.ready_notify.notified();
224 tokio::pin!(notified);
225 notified.as_mut().enable();
226
227 if self.is_active() {
228 return;
229 }
230
231 notified.await;
232 }
233 }
234
235 #[must_use]
237 pub fn is_active(&self) -> bool {
238 let state = self
239 .inner
240 .state
241 .lock()
242 .expect("client state lock is not poisoned");
243 self.inner.ready.load(Ordering::Acquire)
244 && self.inner.auth.is_authenticated()
245 && state
246 .ws_client
247 .as_ref()
248 .is_some_and(|ws_client| ws_client.is_active())
249 }
250
251 pub(crate) fn connection_epoch(&self) -> Option<(u64, u64)> {
252 if !self.is_active() {
253 return None;
254 }
255
256 self.inner
257 .state
258 .lock()
259 .expect("client state lock is not poisoned")
260 .ws_client
261 .as_ref()
262 .map(|ws_client| {
263 (
264 self.inner.generation.load(Ordering::Acquire),
265 ws_client.connection_epoch_atomic().load(Ordering::Acquire),
266 )
267 })
268 }
269
270 pub fn subscribe(&self, subscription: KalshiSubscription) -> anyhow::Result<()> {
276 let subscription = subscription.normalize()?;
277 let topic = subscription.topic();
278 let mut state = self
279 .inner
280 .state
281 .lock()
282 .expect("client state lock is not poisoned");
283 anyhow::ensure!(!state.disposed, "Kalshi WebSocket client is disposed");
284
285 if self.inner.subscriptions.add_reference(&topic) {
286 self.inner.subscriptions.mark_subscribe(&topic);
287 state.desired.insert(topic, subscription);
288 self.inner.ready.store(false, Ordering::Release);
289 state.notify()?;
290 }
291
292 Ok(())
293 }
294
295 pub fn unsubscribe(&self, subscription: &KalshiSubscription) -> anyhow::Result<()> {
301 let topic = subscription.clone().normalize()?.topic();
302 let mut state = self
303 .inner
304 .state
305 .lock()
306 .expect("client state lock is not poisoned");
307
308 if self.inner.subscriptions.remove_reference(&topic) {
309 self.inner.subscriptions.mark_unsubscribe(&topic);
310 state.desired.remove(&topic);
311 self.inner.ready.store(false, Ordering::Release);
312 state.notify()?;
313 }
314
315 Ok(())
316 }
317
318 pub fn update_subscription(
329 &self,
330 original: &KalshiSubscription,
331 action: KalshiUpdateAction,
332 markets: Vec<String>,
333 ) -> anyhow::Result<()> {
334 let original = original.clone().normalize()?;
335 let topic = original.topic();
336 anyhow::ensure!(
337 matches!(
338 original.channel,
339 super::messages::KalshiChannel::OrderbookDelta
340 | super::messages::KalshiChannel::Ticker
341 | super::messages::KalshiChannel::Fill
342 | super::messages::KalshiChannel::UserOrders
343 ),
344 "channel does not support market updates"
345 );
346 anyhow::ensure!(!markets.is_empty(), "market updates require tickers");
347
348 let requested = KalshiSubscription {
349 channel: original.channel,
350 market_tickers: markets,
351 }
352 .normalize()?;
353
354 let mut state = self
355 .inner
356 .state
357 .lock()
358 .expect("client state lock is not poisoned");
359 anyhow::ensure!(!state.disposed, "Kalshi WebSocket client is disposed");
360 let subscription = state
361 .desired
362 .get_mut(&topic)
363 .ok_or_else(|| anyhow::anyhow!("subscription intent is absent"))?;
364
365 if action == KalshiUpdateAction::GetSnapshot {
366 anyhow::ensure!(
367 original.channel == super::messages::KalshiChannel::OrderbookDelta,
368 "snapshots require an order-book subscription"
369 );
370 anyhow::ensure!(
371 self.inner.ready.load(Ordering::Acquire),
372 "snapshot requires a ready connection"
373 );
374 let sender = state
375 .sender
376 .as_ref()
377 .ok_or_else(|| anyhow::anyhow!("snapshot requires a connected handler"))?;
378 sender
379 .send(HandlerCommand::Snapshot {
380 topic,
381 markets: requested.market_tickers,
382 })
383 .map_err(|_| anyhow::anyhow!("Kalshi WebSocket handler stopped"))?;
384
385 return Ok(());
386 }
387
388 anyhow::ensure!(
389 !subscription.market_tickers.is_empty(),
390 "global subscription filters cannot be updated"
391 );
392 let mut updated = subscription.clone();
393
394 match action {
395 KalshiUpdateAction::AddMarkets => {
396 updated.market_tickers.extend(requested.market_tickers);
397 updated.market_tickers.sort();
398 updated.market_tickers.dedup();
399 }
400 KalshiUpdateAction::DeleteMarkets => updated
401 .market_tickers
402 .retain(|market| !requested.market_tickers.contains(market)),
403 KalshiUpdateAction::GetSnapshot => unreachable!(),
404 }
405
406 anyhow::ensure!(
407 !updated.market_tickers.is_empty(),
408 "unsubscribe to remove all markets"
409 );
410 *subscription = updated;
411 self.inner.subscriptions.mark_failure(&topic);
412 self.inner.ready.store(false, Ordering::Release);
413 state.notify()
414 }
415
416 pub(crate) async fn request_book_snapshot(
417 &self,
418 subscription: &KalshiSubscription,
419 market: String,
420 attempt: u64,
421 cancel: CancellationToken,
422 ) -> Result<(), KalshiWsError> {
423 let sender = {
424 let state = self
425 .inner
426 .state
427 .lock()
428 .expect("client state lock is not poisoned");
429
430 if state.disposed {
431 return Err(KalshiWsError::Client(
432 "Kalshi WebSocket client is disposed".into(),
433 ));
434 }
435
436 state
437 .sender
438 .clone()
439 .ok_or_else(|| KalshiWsError::Client("handler is stopped".into()))?
440 };
441
442 let (completed, result) = tokio::sync::oneshot::channel();
443 sender
444 .send(HandlerCommand::BookSnapshot {
445 topic: subscription.topic(),
446 markets: vec![market],
447 attempt,
448 cancel: cancel.clone(),
449 completed,
450 })
451 .map_err(|_| KalshiWsError::Client("handler is stopped".into()))?;
452
453 tokio::select! {
454 biased;
455 () = cancel.cancelled() => Err(KalshiWsError::Client("snapshot attempt canceled".into())),
456 result = result => result.unwrap_or_else(|_| Err(KalshiWsError::Client("snapshot write abandoned".into()))),
457 }
458 }
459
460 pub async fn stop(&self) -> anyhow::Result<()> {
466 let _lifecycle = self.inner.lifecycle.lock().await;
467 self.stop_locked().await
468 }
469
470 pub async fn reset(&self) -> anyhow::Result<()> {
476 let _lifecycle = self.inner.lifecycle.lock().await;
477 self.stop_locked().await?;
478 let mut state = self
479 .inner
480 .state
481 .lock()
482 .expect("client state lock is not poisoned");
483 state.desired.clear();
484 self.inner.subscriptions.clear();
485 Ok(())
486 }
487
488 pub async fn dispose(&self) -> anyhow::Result<()> {
494 let _lifecycle = self.inner.lifecycle.lock().await;
495 self.inner
496 .state
497 .lock()
498 .expect("client state lock is not poisoned")
499 .disposed = true;
500 self.stop_locked().await?;
501 let mut state = self
502 .inner
503 .state
504 .lock()
505 .expect("client state lock is not poisoned");
506 state.desired.clear();
507 self.inner.subscriptions.clear();
508 Ok(())
509 }
510
511 async fn stop_locked(&self) -> anyhow::Result<()> {
512 let ws_client = {
513 let mut state = self
514 .inner
515 .state
516 .lock()
517 .expect("client state lock is not poisoned");
518 state.sender = None;
519 self.inner.ready.store(false, Ordering::Release);
520 self.inner.auth.fail("Kalshi WebSocket client stopped");
521 state.ws_client.clone()
522 };
523
524 self.tasks.begin_shutdown();
525
526 if let Some(ws_client) = ws_client {
527 ws_client.disconnect().await;
528 }
529
530 self.tasks
531 .finish_shutdown(Duration::from_secs(2), Duration::from_secs(2))
532 .await?;
533 self.inner
534 .state
535 .lock()
536 .expect("client state lock is not poisoned")
537 .ws_client = None;
538 self.inner.subscriptions.reset_after_reconnect();
539 Ok(())
540 }
541}
542
543pub(super) struct Shared {
544 pub config: KalshiDataClientConfig,
545 pub state: Mutex<ClientState>,
546 lifecycle: tokio::sync::Mutex<()>,
547 pub generation: AtomicU64,
548 pub subscriptions: SubscriptionState,
549 pub auth: AuthTracker,
550 pub ready: AtomicBool,
551 pub ready_notify: tokio::sync::Notify,
552 pub events: tokio::sync::mpsc::UnboundedSender<KalshiWsEvent>,
553}
554
555#[derive(Default)]
556pub(super) struct ClientState {
557 pub desired: BTreeMap<String, KalshiSubscription>,
558 sender: Option<tokio::sync::mpsc::UnboundedSender<HandlerCommand>>,
559 ws_client: Option<Arc<WebSocketClient>>,
560 disposed: bool,
561}
562
563impl ClientState {
564 fn notify(&self) -> anyhow::Result<()> {
565 if let Some(sender) = &self.sender {
566 sender
567 .send(HandlerCommand::Reconcile)
568 .map_err(|_| anyhow::anyhow!("Kalshi WebSocket handler stopped"))?;
569 }
570
571 Ok(())
572 }
573}
574
575pub async fn connect(
584 config: &KalshiDataClientConfig,
585 message_handler: MessageHandler,
586) -> anyhow::Result<WebSocketClient> {
587 let transport = connection_config(config)?;
588 WebSocketClient::builder()
589 .config(transport)
590 .message_handler(message_handler)
591 .connect()
592 .await
593 .map_err(|e| {
594 anyhow::anyhow!(
595 "Kalshi WebSocket connection failed: {}",
596 e.redacted_message()
597 )
598 })
599}
600
601fn connection_config(config: &KalshiDataClientConfig) -> anyhow::Result<WebSocketConfig> {
602 config.validate()?;
603 let credential = KalshiCredential::resolve(
604 config.api_key_id.clone(),
605 config.private_key.clone(),
606 config.environment,
607 )?;
608 let endpoint = Url::parse(config.ws_url())
609 .map_err(|_| anyhow::anyhow!("invalid Kalshi WebSocket endpoint"))?;
610 let path = SecretString::from(endpoint.path());
611 let endpoint = SecretString::from(String::from(endpoint));
612
613 let headers = credential
614 .headers(
615 get_atomic_clock_realtime().get_time_ms(),
616 "GET",
617 path.expose_secret(),
618 )
619 .map_err(|_| {
620 anyhow::anyhow!("Kalshi WebSocket connection failed: I/O error: InvalidInput")
621 })?
622 .into_iter()
623 .map(|(name, value)| (name, value.into_inner()))
624 .collect();
625
626 let transport = WebSocketConfig::builder()
627 .url(endpoint.into_inner())
628 .headers(headers)
629 .connect_timeout_ms(config.ws_timeout_secs * 1_000)
630 .reconnect_max_attempts(0)
631 .maybe_proxy_url(
632 config
633 .proxy_url
634 .as_ref()
635 .map(|s| s.expose_secret().to_owned()),
636 )
637 .backend(config.transport_backend)
638 .build()?;
639 Ok(transport)
640}
641
642#[cfg(all(test, not(all(feature = "simulation", madsim))))]
643pub(super) mod tests {
644 use std::sync::Arc;
645
646 use super::{KalshiWebSocketClient, KalshiWsEvent, Shared, WebSocketConfig};
647 use crate::config::KalshiDataClientConfig;
648
649 pub(in crate::websocket) fn transport_config(
650 config: &KalshiDataClientConfig,
651 ) -> WebSocketConfig {
652 super::connection_config(config).unwrap()
653 }
654
655 pub(in crate::websocket) fn shared(
656 config: KalshiDataClientConfig,
657 ) -> (
658 Arc<Shared>,
659 tokio::sync::mpsc::UnboundedReceiver<KalshiWsEvent>,
660 ) {
661 let (client, events) = KalshiWebSocketClient::new(config).unwrap();
662 (Arc::clone(&client.inner), events)
663 }
664}