Documentation Index
Fetch the complete documentation index at: https://docs.kalshi.com/llms.txt
Use this file to discover all available pages before exploring further.
Overview
Kalshi’s WebSocket API provides real-time updates for:- Order book changes
- Trade executions
- Market status updates
- Fill notifications
Connection URL
Connect to the WebSocket endpoint at:wss://api.elections.kalshi.com/trade-api/ws/v2 for production and wss://demo-api.kalshi.co/trade-api/ws/v2 for demo, remain supported. For the full endpoint list, see API Environments and Endpoints.
Authentication
WebSocket connections require authentication during the connection handshake. Once connected, channels fall into two groups:- Private channels (user-specific data):
orderbook_delta,fill,market_positions,communications,order_group_updates - Public market-data channels (no additional channel-level auth):
ticker,trade,market_lifecycle_v2,multivariate_market_lifecycle,multivariate
For detailed information about API key generation and request signing, see our API Keys documentation.
Required Headers
When establishing the WebSocket connection, include these headers:Signing the WebSocket Request
The signature for WebSocket connections follows the same pattern as REST API requests:-
Create the message to sign:
- Generate the signature using your private key (see API Keys documentation)
- Include the headers when opening the WebSocket connection
Establishing a Connection
To connect to the WebSocket API, you need to:- Generate authentication headers (same as REST API)
- Create a WebSocket connection with those headers
- Handle the connection lifecycle
Subscribing to Data
Once connected, subscribe to channels by sending a subscription command:Processing Messages
Handle incoming messages based on their type:Connection Keep-Alive
The Python
websockets library automatically handles WebSocket ping/pong frames to keep connections alive. No manual heartbeat handling is required. Learn more about automatic keepalive in the websockets documentation.Other WebSocket libraries may require manual ping/pong implementation.Subscribing to Channels
Once connected, subscribe to specific data channels:Subscribe to Ticker Updates
To receive real-time ticker updates for all markets:Subscribe to Specific Markets
To subscribe to orderbook or trade updates for specific markets:Connection Lifecycle
- Initial Connection: Establish WebSocket with authentication headers
- Subscribe: Send subscription commands for desired channels
- Receive Updates: Process incoming messages based on their type
- Handle Disconnects: Implement reconnection logic with exponential backoff
Error Handling
The server sends error messages in this format:WebSocket Error Codes
| Code | Error | Description | User error? |
|---|---|---|---|
| 1 | Unable to process message | The incoming message was not valid JSON, or a JSON field had a type incompatible with the websocket command schema. | Y |
| 2 | Params required | The command requires params or required subscription parameters are missing. | Y |
| 3 | Channels required | The subscribe command must include at least one channel. | Y |
| 4 | Subscription IDs required | The unsubscribe command must include at least one subscription ID in sids. | Y |
| 5 | Unknown command | The cmd value is not supported. | Y |
| 6 | Already subscribed | A subscription to the same channel is already active in this session. | Y |
| 7 | Unknown subscription ID | The command references a subscription ID that is not active in the session. | Y |
| 8 | Unknown channel name | The requested channel is not supported by this endpoint. | Y |
| 9 | Authentication required | The requested channel or action requires authentication or channel access that was not granted. | Y |
| 10 | Channel error | An internal channel error occurred while starting or running the subscription. If it persists, contact support@kalshi.com. | N |
| 11 | Invalid parameter | A parameter has an invalid format, such as a malformed market ID. | Y |
| 12 | Exactly one subscription ID is required | The update_subscription command must target exactly one subscription. | Y |
| 13 | Unsupported action | The subscription does not support the requested action. | Y |
| 14 | Market Ticker required | The command requires a market filter such as market_ticker or market_tickers. | Y |
| 15 | Action required | The update_subscription command must include params.action. | Y |
| 16 | Market not found | The specified market_ticker or market_id does not match any known market. | Y |
| 17 | Internal error | An unexpected server-side error occurred. If it persists, contact support@kalshi.com. | N |
| 18 | Command timeout | The server timed out while routing a command to an existing subscription. | N |
| 19 | shard_factor must be > 0 | The supplied communications shard_factor value is invalid. | Y |
| 20 | shard_factor is required when shard_key is set | communications set shard_key without a valid shard factor. | Y |
| 21 | shard_key must be >= 0 and < shard_factor | The communications shard key is outside the valid range. | Y |
| 22 | shard_factor must be <= 100 | The communications shard factor exceeds the maximum. | Y |
| 25 | Subscription buffer overflow | The subscription’s event buffer overflowed during a message burst. Subscribe to a smaller subset of data, or ensure that your connection read throughput is optimized. | Y |
Best Practices
Connection Management
- Implement automatic reconnection with exponential backoff
- Handle network interruptions gracefully
- Use the websockets library’s built-in keepalive
Data Handling
- Process messages asynchronously to avoid blocking
- Implement proper error handling for malformed messages
- Cache initial orderbook state before applying updates
Security
- Never expose your private key in client-side code
- Rotate API keys regularly
- Use secure key storage practices
Performance
- Subscribe only to markets you need
- Implement message buffering for high-frequency updates
- Consider using connection pooling for multiple subscriptions
Complete Example
Here’s a complete, runnable example that connects to the WebSocket API and subscribes to orderbook updates:- Establishes an authenticated WebSocket connection
- Subscribes to orderbook updates for the specified market
- Processes both the initial snapshot and incremental updates
- Displays orderbook changes in real-time
- Replace
KEY_IDwith your API key ID - Replace
PRIVATE_KEY_PATHwith the path to your private key file - Replace
MARKET_TICKERwith any open market ticker - Run with Python 3.7+
Next Steps
- Review the WebSocket API Reference for detailed message specifications
- Explore Market Data Quick Start for REST API integration
- Check out our Demo Environment for testing