Skip to main content

nautilus_kalshi/websocket/
messages.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//! Typed control messages and channel identities for the Predictions WebSocket protocol.
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use strum::EnumIter;
21
22/// Predictions WebSocket channels; subscription support is validated separately.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum KalshiChannel {
26    OrderbookDelta,
27    Ticker,
28    Trade,
29    Fill,
30    MarketPositions,
31    MarketLifecycleV2,
32    UserOrders,
33    MultivariateMarketLifecycle,
34    Communications,
35    OrderGroupUpdates,
36    CfbenchmarksValue,
37    #[serde(rename = "cfbenchmarks_value_5hz")]
38    CfbenchmarksValue5hz,
39    PythValue,
40}
41
42/// A shared subscription's original channel and market filter.
43///
44/// An empty market list selects the channel's global stream where supported.
45/// Order books always request YES-leg pricing. Ticker subscriptions request initial snapshots.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct KalshiSubscription {
48    pub channel: KalshiChannel,
49    pub market_tickers: Vec<String>,
50}
51
52impl KalshiSubscription {
53    /// Validates and sorts the market filter without changing its meaning.
54    ///
55    /// # Errors
56    ///
57    /// Returns an error if tickers are empty or duplicated, order-book markets are absent,
58    /// or the channel subscription or market filter is unsupported.
59    pub(crate) fn normalize(mut self) -> anyhow::Result<Self> {
60        anyhow::ensure!(
61            self.market_tickers
62                .iter()
63                .all(|ticker| !ticker.trim().is_empty()),
64            "market tickers must not be empty"
65        );
66        self.market_tickers.sort();
67        anyhow::ensure!(
68            !self
69                .market_tickers
70                .windows(2)
71                .any(|pair| pair[0] == pair[1]),
72            "duplicate market ticker"
73        );
74
75        match self.channel {
76            KalshiChannel::OrderbookDelta => anyhow::ensure!(
77                !self.market_tickers.is_empty(),
78                "order books require market tickers"
79            ),
80            KalshiChannel::MarketLifecycleV2 => anyhow::ensure!(
81                self.market_tickers.is_empty(),
82                "channel does not support market filters"
83            ),
84            KalshiChannel::Ticker
85            | KalshiChannel::Trade
86            | KalshiChannel::Fill
87            | KalshiChannel::MarketPositions
88            | KalshiChannel::UserOrders => {}
89            _ => anyhow::bail!("channel subscriptions are not supported"),
90        }
91
92        Ok(self)
93    }
94
95    pub(crate) fn topic(&self) -> String {
96        serde_json::to_string(self).expect("subscription serialization is infallible")
97    }
98}
99
100/// Supported updates to an existing Predictions subscription.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter, Serialize, Deserialize)]
102#[serde(rename_all = "snake_case")]
103pub enum KalshiUpdateAction {
104    AddMarkets,
105    DeleteMarkets,
106    GetSnapshot,
107}
108
109/// A client command with a nonzero session-unique correlation ID.
110#[derive(Debug, Clone, Serialize)]
111pub(crate) struct KalshiCommand {
112    pub id: u64,
113    #[serde(flatten)]
114    pub operation: KalshiOperation,
115}
116
117#[derive(Debug, Clone, Serialize)]
118#[serde(tag = "cmd", content = "params", rename_all = "snake_case")]
119pub(crate) enum KalshiOperation {
120    Subscribe {
121        channels: [KalshiChannel; 1],
122        #[serde(skip_serializing_if = "Vec::is_empty")]
123        market_tickers: Vec<String>,
124        #[serde(skip_serializing_if = "Option::is_none")]
125        use_yes_price: Option<bool>,
126        #[serde(skip_serializing_if = "Option::is_none")]
127        send_initial_snapshot: Option<bool>,
128    },
129    Unsubscribe {
130        sids: [u64; 1],
131    },
132    UpdateSubscription {
133        sid: u64,
134        market_tickers: Vec<String>,
135        action: KalshiUpdateAction,
136        #[serde(skip_serializing_if = "Option::is_none")]
137        send_initial_snapshot: Option<bool>,
138    },
139}
140
141/// A single decoded server frame, before domain-specific payload conversion.
142///
143/// Data payloads retain the provider's decimal strings and optional fields unchanged.
144/// The handler validates channel and subscription ownership before emitting them.
145#[derive(Debug, Clone, PartialEq, Deserialize)]
146#[serde(tag = "type", rename_all = "snake_case")]
147pub enum KalshiWsMessage {
148    Subscribed {
149        id: u64,
150        msg: KalshiSubscribed,
151    },
152    Unsubscribed {
153        id: Option<u64>,
154        sid: u64,
155        seq: u64,
156    },
157    Ok {
158        id: Option<u64>,
159        sid: Option<u64>,
160        seq: Option<u64>,
161        sending_ts_ms: Option<u64>,
162        msg: Option<KalshiUpdated>,
163    },
164    Error {
165        id: Option<u64>,
166        sid: Option<u64>,
167        msg: KalshiServerError,
168    },
169    OrderbookSnapshot(KalshiDataMessage),
170    OrderbookDelta(KalshiDataMessage),
171    Ticker(KalshiDataMessage),
172    Trade(KalshiDataMessage),
173    Fill(KalshiDataMessage),
174    MarketPosition(KalshiDataMessage),
175    MarketLifecycleV2(KalshiDataMessage),
176    EventLifecycle(KalshiDataMessage),
177    EventFeeUpdate(KalshiDataMessage),
178    UserOrder(KalshiDataMessage),
179    MultivariateMarketLifecycle(KalshiDataMessage),
180    OrderGroupUpdates(KalshiDataMessage),
181    CfbenchmarksValue(KalshiDataMessage),
182    CfbenchmarksValueIndexlist(KalshiDataMessage),
183    #[serde(rename = "cfbenchmarks_value_5hz")]
184    CfbenchmarksValue5hz(KalshiDataMessage),
185    #[serde(rename = "cfbenchmarks_value_5hz_indexlist")]
186    CfbenchmarksValue5hzIndexlist(KalshiDataMessage),
187    PythValue(KalshiDataMessage),
188    PythValueUnderlyingList(KalshiDataMessage),
189    RfqCreated(KalshiDataMessage),
190    RfqDeleted(KalshiDataMessage),
191    QuoteCreated(KalshiDataMessage),
192    QuoteAccepted(KalshiDataMessage),
193    QuoteExecuted(KalshiDataMessage),
194    RfqBatchCreated(KalshiDataMessage),
195    RfqBatchDeleted(KalshiDataMessage),
196    BatchQuoteCreated(KalshiDataMessage),
197    RfqBatchBestQuotes(KalshiDataMessage),
198    BatchQuoteAccepted(KalshiDataMessage),
199    RfqBatchExecuted(KalshiDataMessage),
200    BatchQuoteExecuted(KalshiDataMessage),
201    #[serde(other)]
202    Unknown,
203}
204
205/// A confirmed channel and its server subscription ID.
206#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
207pub struct KalshiSubscribed {
208    pub channel: KalshiChannel,
209    pub sid: u64,
210}
211
212/// The authoritative market filter after a subscription update.
213#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
214pub struct KalshiUpdated {
215    pub market_tickers: Vec<String>,
216}
217
218/// A protocol error; codes 10 and 25 terminate the affected channel.
219#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
220pub struct KalshiServerError {
221    pub code: u32,
222    pub msg: String,
223}
224
225/// A channel payload with the identity needed for downstream sequence validation.
226#[derive(Debug, Clone, PartialEq, Deserialize)]
227pub struct KalshiDataMessage {
228    pub id: Option<u64>,
229    pub sid: u64,
230    pub seq: Option<u64>,
231    pub sending_ts_ms: Option<u64>,
232    pub msg: Value,
233}
234
235impl KalshiWsMessage {
236    /// Returns the subscription channel and payload of a data frame.
237    ///
238    /// Order-book snapshots and deltas both report [`KalshiChannel::OrderbookDelta`]. Market and
239    /// event lifecycle frames report [`KalshiChannel::MarketLifecycleV2`]; multivariate lifecycle
240    /// frames report [`KalshiChannel::MultivariateMarketLifecycle`].
241    #[must_use]
242    pub fn data(&self) -> Option<(KalshiChannel, &KalshiDataMessage)> {
243        match self {
244            Self::OrderbookSnapshot(data) | Self::OrderbookDelta(data) => {
245                Some((KalshiChannel::OrderbookDelta, data))
246            }
247            Self::Ticker(data) => Some((KalshiChannel::Ticker, data)),
248            Self::Trade(data) => Some((KalshiChannel::Trade, data)),
249            Self::Fill(data) => Some((KalshiChannel::Fill, data)),
250            Self::MarketPosition(data) => Some((KalshiChannel::MarketPositions, data)),
251            Self::MarketLifecycleV2(data)
252            | Self::EventLifecycle(data)
253            | Self::EventFeeUpdate(data) => Some((KalshiChannel::MarketLifecycleV2, data)),
254            Self::UserOrder(data) => Some((KalshiChannel::UserOrders, data)),
255            Self::MultivariateMarketLifecycle(data) => {
256                Some((KalshiChannel::MultivariateMarketLifecycle, data))
257            }
258            Self::OrderGroupUpdates(data) => Some((KalshiChannel::OrderGroupUpdates, data)),
259            Self::CfbenchmarksValue(data) | Self::CfbenchmarksValueIndexlist(data) => {
260                Some((KalshiChannel::CfbenchmarksValue, data))
261            }
262            Self::CfbenchmarksValue5hz(data) | Self::CfbenchmarksValue5hzIndexlist(data) => {
263                Some((KalshiChannel::CfbenchmarksValue5hz, data))
264            }
265            Self::PythValue(data) | Self::PythValueUnderlyingList(data) => {
266                Some((KalshiChannel::PythValue, data))
267            }
268            Self::RfqCreated(data)
269            | Self::RfqDeleted(data)
270            | Self::QuoteCreated(data)
271            | Self::QuoteAccepted(data)
272            | Self::QuoteExecuted(data)
273            | Self::RfqBatchCreated(data)
274            | Self::RfqBatchDeleted(data)
275            | Self::BatchQuoteCreated(data)
276            | Self::RfqBatchBestQuotes(data)
277            | Self::BatchQuoteAccepted(data)
278            | Self::RfqBatchExecuted(data)
279            | Self::BatchQuoteExecuted(data) => Some((KalshiChannel::Communications, data)),
280            _ => None,
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use rstest::rstest;
288
289    use super::*;
290
291    #[rstest]
292    #[case(KalshiChannel::MultivariateMarketLifecycle)]
293    #[case(KalshiChannel::Communications)]
294    #[case(KalshiChannel::OrderGroupUpdates)]
295    #[case(KalshiChannel::CfbenchmarksValue)]
296    #[case(KalshiChannel::CfbenchmarksValue5hz)]
297    #[case(KalshiChannel::PythValue)]
298    fn documented_channels_require_subscription_support(#[case] channel: KalshiChannel) {
299        let subscription = KalshiSubscription {
300            channel,
301            market_tickers: Vec::new(),
302        };
303
304        assert_eq!(
305            subscription.normalize().unwrap_err().to_string(),
306            "channel subscriptions are not supported"
307        );
308    }
309}