kalshi-cpp 0.8.0
C++23 client for Kalshi's Predictions API
Loading...
Searching...
No Matches
websocket.hpp
Go to the documentation of this file.
1#pragma once
2
4#include "kalshi/error.hpp"
5#include "kalshi/signer.hpp"
7
8#include <chrono>
9#include <cstddef>
10#include <cstdint>
11#include <functional>
12#include <memory>
13#include <optional>
14#include <string>
15#include <string_view>
16#include <vector>
17
18namespace kalshi {
19
23
25struct WsError {
27 std::int64_t code{0};
28 std::string message;
30 std::optional<std::int64_t> id;
31 std::optional<std::int64_t> sid;
32 std::optional<std::int64_t> seq;
34 std::optional<ws::Subscription> subscription;
35 std::optional<std::int64_t> sending_ts_ms;
36};
37
38enum class WsState : std::uint8_t { Disconnected, Connecting, Connected, Reconnecting };
39
40[[nodiscard]] constexpr std::string_view to_string(WsState state) noexcept {
41 switch (state) {
43 return "disconnected";
45 return "connecting";
47 return "connected";
49 return "reconnecting";
50 }
51 return "";
52}
53
54struct WsConfig {
57 std::chrono::milliseconds connect_timeout{std::chrono::seconds{10}};
59 bool auto_reconnect{true};
62 std::chrono::milliseconds reconnect_delay{std::chrono::milliseconds{500}};
63 std::chrono::milliseconds max_reconnect_delay{std::chrono::seconds{30}};
66 std::uint32_t max_reconnect_attempts{0};
69 std::chrono::seconds ping_interval{std::chrono::seconds{15}};
70 std::chrono::seconds idle_timeout{std::chrono::seconds{30}};
73 bool resync_on_gap{true};
75 std::size_t max_message_bytes{std::size_t{64} * 1024 * 1024};
76
77 [[nodiscard]] static WsConfig for_environment(Environment environment) {
78 WsConfig config;
79 config.url = std::string(websocket_url(environment));
80 return config;
81 }
82};
83
95public:
97 explicit WebSocketClient(Signer signer, WsConfig config = {});
99
101 WebSocketClient& operator=(WebSocketClient&&) noexcept;
103 WebSocketClient& operator=(const WebSocketClient&) = delete;
104
107 [[nodiscard]] Result<void> connect();
108
112
113 [[nodiscard]] WsState state() const noexcept;
114 [[nodiscard]] bool is_connected() const noexcept;
115
120 [[nodiscard]] Result<ws::Subscription> subscribe(ws::Channel channel,
121 ws::SubscribeParams params = {});
122 [[nodiscard]] Result<void> unsubscribe(ws::Subscription subscription);
125 const ws::UpdateSubscriptionParams& params);
126 [[nodiscard]] Result<void> add_markets(ws::Subscription subscription,
127 std::vector<std::string> market_tickers);
128 [[nodiscard]] Result<void> remove_markets(ws::Subscription subscription,
129 std::vector<std::string> market_tickers);
133 std::vector<std::string> market_tickers);
138 [[nodiscard]] std::vector<ws::Subscription> subscriptions() const;
139
140 void on_message(std::function<void(const WsMessage&)> callback);
141 void on_error(std::function<void(const WsError&)> callback);
142 void on_state_change(std::function<void(WsState)> callback);
143
144 [[nodiscard]] const WsConfig& config() const noexcept;
145
146private:
147 struct Impl;
148 std::shared_ptr<Impl> impl_;
149};
150
151} // namespace kalshi
Signs Kalshi requests with an API key.
Definition signer.hpp:32
Streams Kalshi's WebSocket channels.
Definition websocket.hpp:94
std::vector< ws::Subscription > subscriptions() const
The subscriptions this client holds.
void on_message(std::function< void(const WsMessage &)> callback)
Result< void > add_markets(ws::Subscription subscription, std::vector< std::string > market_tickers)
WebSocketClient(WebSocketClient &&) noexcept
bool is_connected() const noexcept
Result< void > unsubscribe(ws::Subscription subscription)
void on_state_change(std::function< void(WsState)> callback)
WsState state() const noexcept
WebSocketClient(Signer signer, WsConfig config={})
Creates a client that authenticates with a copy of signer.
Result< ws::Subscription > subscribe(ws::Channel channel, ws::SubscribeParams params={})
Subscribes to one channel.
Result< void > request_snapshot(ws::Subscription subscription, std::vector< std::string > market_tickers)
Asks for order book snapshots of markets in an orderbook_delta subscription, without changing it.
Result< void > connect()
Opens the connection and waits up to connect_timeout for the handshake.
void disconnect()
Closes the connection and forgets every subscription.
Result< std::int64_t > list_subscriptions()
Asks the server for its view of this connection's subscriptions.
Result< void > remove_markets(ws::Subscription subscription, std::vector< std::string > market_tickers)
Result< void > update_subscription(ws::Subscription subscription, const ws::UpdateSubscriptionParams &params)
Rejects updates while unsubscription is pending.
const WsConfig & config() const noexcept
void on_error(std::function< void(const WsError &)> callback)
std::variant< Update< OrderbookSnapshot >, Update< OrderbookDelta >, Update< Ticker >, Update< Trade >, Update< Fill >, Update< MarketPosition >, Update< EventLifecycle >, Update< EventFeeUpdate >, Update< MultivariateMarketLifecycle >, Update< RfqCreated >, Update< RfqDeleted >, Update< QuoteCreated >, Update< QuoteAccepted >, Update< QuoteExecuted >, Update< RfqBatchCreated >, Update< RfqBatchDeleted >, Update< BatchQuoteCreated >, Update< RfqBatchBestQuotes >, Update< BatchQuoteAccepted >, Update< RfqBatchExecuted >, Update< BatchQuoteExecuted >, Update< OrderGroupUpdates >, Update< UserOrder >, Update< CfbenchmarksValue >, Update< CfbenchmarksIndexList >, Update< CfbenchmarksValue5Hz >, Update< Cfbenchmarks5HzIndexList >, Update< PythValue >, Update< PythUnderlyingList >, Update< MarketMetadataUpdated >, Update< MarketLifecycleV2 >, Subscribed, Unsubscribed, Updated, SubscriptionList > Message
Everything WebSocketClient delivers to on_message.
Definition ws_models.hpp:1349
Definition api.hpp:15
constexpr std::string_view to_string(HttpMethod method) noexcept
Definition http_client.hpp:23
WsState
Definition websocket.hpp:38
Environment
Kalshi deployment.
Definition environment.hpp:10
std::expected< T, Error > Result
Result type for SDK operations.
Definition error.hpp:50
ws::Message WsMessage
Everything on_message delivers: channel data as ws::Update<T>, and subscription events.
Definition websocket.hpp:22
constexpr std::string_view websocket_url(Environment environment) noexcept
WebSocket URL for streaming market and account data.
Definition environment.hpp:19
Definition websocket.hpp:54
std::chrono::milliseconds reconnect_delay
The first reconnect waits about this long; each failure doubles the wait, with jitter,...
Definition websocket.hpp:62
std::chrono::seconds idle_timeout
Definition websocket.hpp:70
static WsConfig for_environment(Environment environment)
Definition websocket.hpp:77
std::chrono::milliseconds connect_timeout
How long connect() waits for the handshake.
Definition websocket.hpp:57
std::size_t max_message_bytes
Maximum received message size; zero disables the limit.
Definition websocket.hpp:75
std::chrono::seconds ping_interval
Ping after this much silence, and drop the connection after idle_timeout without a reply.
Definition websocket.hpp:69
bool auto_reconnect
Reconnect and resubscribe after the connection drops.
Definition websocket.hpp:59
bool resync_on_gap
Request fresh order book snapshots when an orderbook_delta sequence number is skipped.
Definition websocket.hpp:73
std::uint32_t max_reconnect_attempts
Stop after this many failed attempts in a row; 0 keeps trying.
Definition websocket.hpp:66
std::chrono::milliseconds max_reconnect_delay
Definition websocket.hpp:63
std::string url
Definition websocket.hpp:55
An error frame from the server, or a problem the client found itself.
Definition websocket.hpp:25
std::string message
Definition websocket.hpp:28
std::optional< ws::Subscription > subscription
The subscription the error concerns, when known.
Definition websocket.hpp:34
std::optional< std::int64_t > id
The command that failed, when the server names one.
Definition websocket.hpp:30
std::optional< std::int64_t > sending_ts_ms
Definition websocket.hpp:35
std::int64_t code
Kalshi's error code (see ws::error_code_name), or 0 for a client error.
Definition websocket.hpp:27
std::optional< std::int64_t > seq
Definition websocket.hpp:32
std::optional< std::int64_t > sid
Definition websocket.hpp:31
A handle for one channel subscription.
Definition ws_models.hpp:427
Options for update_subscription; the client sets the subscription.
Definition ws_models.hpp:1222