kalshi-cpp 0.6.2
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 <cstdint>
10#include <functional>
11#include <memory>
12#include <optional>
13#include <string>
14#include <string_view>
15#include <vector>
16
17namespace kalshi {
18
22
24struct WsError {
26 std::int64_t code{0};
27 std::string message;
29 std::optional<std::int64_t> id;
30 std::optional<std::int64_t> sid;
31 std::optional<std::int64_t> seq;
33 std::optional<ws::Subscription> subscription;
34};
35
36enum class WsState : std::uint8_t { Disconnected, Connecting, Connected, Reconnecting };
37
38[[nodiscard]] constexpr std::string_view to_string(WsState state) noexcept {
39 switch (state) {
41 return "disconnected";
43 return "connecting";
45 return "connected";
47 return "reconnecting";
48 }
49 return "";
50}
51
52struct WsConfig {
55 std::chrono::milliseconds connect_timeout{std::chrono::seconds{10}};
57 bool auto_reconnect{true};
60 std::chrono::milliseconds reconnect_delay{std::chrono::milliseconds{500}};
61 std::chrono::milliseconds max_reconnect_delay{std::chrono::seconds{30}};
64 std::uint32_t max_reconnect_attempts{0};
67 std::chrono::seconds ping_interval{std::chrono::seconds{15}};
68 std::chrono::seconds idle_timeout{std::chrono::seconds{30}};
71 bool resync_on_gap{true};
72
73 [[nodiscard]] static WsConfig for_environment(Environment environment) {
74 WsConfig config;
75 config.url = std::string(websocket_url(environment));
76 return config;
77 }
78};
79
90public:
92 explicit WebSocketClient(Signer signer, WsConfig config = {});
94
96 WebSocketClient& operator=(WebSocketClient&&) noexcept;
98 WebSocketClient& operator=(const WebSocketClient&) = delete;
99
102 [[nodiscard]] Result<void> connect();
103
107
108 [[nodiscard]] WsState state() const noexcept;
109 [[nodiscard]] bool is_connected() const noexcept;
110
113 [[nodiscard]] Result<ws::Subscription> subscribe(ws::Channel channel,
114 ws::SubscribeParams params = {});
115 [[nodiscard]] Result<void> unsubscribe(ws::Subscription subscription);
117 const ws::UpdateSubscriptionParams& params);
118 [[nodiscard]] Result<void> add_markets(ws::Subscription subscription,
119 std::vector<std::string> market_tickers);
120 [[nodiscard]] Result<void> remove_markets(ws::Subscription subscription,
121 std::vector<std::string> market_tickers);
125 std::vector<std::string> market_tickers);
130 [[nodiscard]] std::vector<ws::Subscription> subscriptions() const;
131
132 void on_message(std::function<void(const WsMessage&)> callback);
133 void on_error(std::function<void(const WsError&)> callback);
134 void on_state_change(std::function<void(WsState)> callback);
135
136 [[nodiscard]] const WsConfig& config() const noexcept;
137
138private:
139 struct Impl;
140 std::shared_ptr<Impl> impl_;
141};
142
143} // namespace kalshi
Signs Kalshi requests with an API key.
Definition signer.hpp:32
Streams Kalshi's WebSocket channels.
Definition websocket.hpp:89
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)
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< 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:1041
Definition api.hpp:15
constexpr std::string_view to_string(HttpMethod method) noexcept
Definition http_client.hpp:22
WsState
Definition websocket.hpp:36
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:21
constexpr std::string_view websocket_url(Environment environment) noexcept
WebSocket URL for streaming market and account data.
Definition environment.hpp:19
Definition websocket.hpp:52
std::chrono::milliseconds reconnect_delay
The first reconnect waits about this long; each failure doubles the wait, with jitter,...
Definition websocket.hpp:60
std::chrono::seconds idle_timeout
Definition websocket.hpp:68
static WsConfig for_environment(Environment environment)
Definition websocket.hpp:73
std::chrono::milliseconds connect_timeout
How long connect() waits for the handshake.
Definition websocket.hpp:55
std::chrono::seconds ping_interval
Ping after this much silence, and drop the connection after idle_timeout without a reply.
Definition websocket.hpp:67
bool auto_reconnect
Reconnect and resubscribe after the connection drops.
Definition websocket.hpp:57
bool resync_on_gap
Request fresh order book snapshots when an orderbook_delta sequence number is skipped.
Definition websocket.hpp:71
std::uint32_t max_reconnect_attempts
Stop after this many failed attempts in a row; 0 keeps trying.
Definition websocket.hpp:64
std::chrono::milliseconds max_reconnect_delay
Definition websocket.hpp:61
std::string url
Definition websocket.hpp:53
An error frame from the server, or a problem the client found itself.
Definition websocket.hpp:24
std::string message
Definition websocket.hpp:27
std::optional< ws::Subscription > subscription
The subscription the error concerns, when known.
Definition websocket.hpp:33
std::optional< std::int64_t > id
The command that failed, when the server names one.
Definition websocket.hpp:29
std::int64_t code
Kalshi's error code (see ws::error_code_name), or 0 for a client error.
Definition websocket.hpp:26
std::optional< std::int64_t > seq
Definition websocket.hpp:31
std::optional< std::int64_t > sid
Definition websocket.hpp:30
A handle for one channel subscription.
Definition ws_models.hpp:359
Options for update_subscription; the client sets the subscription.
Definition ws_models.hpp:922