When to use the WebSocket API
Kalshi's REST API is for actions and reconciliation: placing and canceling orders, reading a market once, checking your balance. Anything that changes continuously (the order book, trade prints, market status, your fills) belongs on the WebSocket API. Polling those over REST spends your Read token budget on markets that may not have moved; a WebSocket subscription sends a snapshot once, then only the changes. Most production bots run both: REST to act, WebSocket to know what happened. The trade-offs are covered in our piece on rate limits and throttling and placing and canceling orders over REST.
Endpoints
Everything goes over one connection to one path, /trade-api/ws/v2. You pick channels after connecting.
| Environment | Host |
|---|---|
| Production | wss://external-api-ws.kalshi.com/trade-api/ws/v2 |
| Demo | wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2 |
| Production (older shared host, still supported) | wss://api.elections.kalshi.com/trade-api/ws/v2 |
| Demo (older shared host, still supported) | wss://demo-api.kalshi.co/trade-api/ws/v2 |
What the demo environment does and doesn't mirror is in our walkthrough of the demo topology; the full host list is on Kalshi's API environments page.
Authenticating the handshake
Every WebSocket connection is authenticated, including one that only reads public market data. There is no login message: you send the same three headers REST requests carry, on the HTTP upgrade request itself.
KALSHI-ACCESS-KEY: <your API key id>
KALSHI-ACCESS-TIMESTAMP: <unix time in milliseconds>
KALSHI-ACCESS-SIGNATURE: base64(sign(timestamp + "GET" + "/trade-api/ws/v2"))The signed string is the millisecond timestamp, the method GET, and the fixed path /trade-api/ws/v2, with no query string. Sign it with your key's algorithm (RSA-PSS with SHA-256 for RSA keys, or Ed25519) and base64 the result. Signing a REST path instead, or appending a query string, gets the handshake rejected. Key creation and signing in detail: Kalshi REST API authentication and token management.
A rejected handshake answers with an HTTP error instead of upgrading. A 429 Too Many Requests with code too_many_requestsmeans either you hit your tier's concurrent connection limit or you are opening connections too quickly; the response is the same for both, so back off exponentially and close connections you no longer use.
Channels
Channels split into two groups. Public market-data channels need nothing beyond the authenticated connection. Private channels carry your own activity; an API key limited to market data gets error code 9 on fill, market_positions, order_group_updates and user_orders, but can still subscribe to orderbook_delta and communications, which carry public data too.
| Channel | What it carries | Access | Market filter |
|---|---|---|---|
orderbook_delta | An orderbook_snapshot per market, then an orderbook_delta per price-level change | Private group; market-data keys can subscribe | Required (market_ticker or market_tickers) |
ticker | Price, volume and open interest, flushed about once a second per changed market | Public market data | Optional; omit for all markets |
trade | Public trades, sent right after execution | Public market data | Optional; omit for all trades |
fill | Your own fills | Private | Optional |
user_orders | Your orders being created, filled, canceled or otherwise updated | Private | Optional |
market_positions | Your position changes from trades, settlements and so on | Private | Optional (tickers only) |
market_lifecycle_v2 | Market creation, (de)activation, close date changes, determination, settlement; event creation | Public market data | Not supported; you get everything |
multivariate_market_lifecycle | The same lifecycle events for multivariate events | Public market data | Not supported |
order_group_updates | Order groups created, triggered, reset, deleted or with limits updated | Private | Ignored |
communications | RFQ and quote events, with optional sharding | Private group; market-data keys can subscribe | Ignored |
Two details catch bots out. tickerconflates: it sends each changed market's current values on a roughly one-second flush, so intermediate prices never arrive; use trade or orderbook_delta when every change matters. And market_positions messages carry no seq and are not ordered against fill: the position update for a trade can land after its fill, so don't read your position as current the moment a fill arrives. Kalshi also runs reference-price feeds (CF Benchmarks, Pyth) on this connection; see the WebSocket API reference for those.
Commands
Commands are JSON with an id you choose (start at 1 and increment per command), a cmd and its params. A new subscription is acknowledged with subscribed and a server-assigned sid; every message on that subscription carries the sid.
{"id": 1, "cmd": "subscribe",
"params": {"channels": ["orderbook_delta"],
"market_tickers": ["FED-23DEC-T3.00"]}}
{"id": 2, "cmd": "update_subscription",
"params": {"sid": 1, "action": "add_markets",
"market_tickers": ["HIGHNY-22DEC23-B53.5"]}}
{"id": 3, "cmd": "unsubscribe", "params": {"sids": [1]}}
{"id": 4, "cmd": "list_subscriptions"}update_subscription takes add_markets, delete_markets or, on orderbook_delta, get_snapshot, and targets exactly one subscription. A connection holds at most one subscription per channel: subscribing again to a channel you already have does not open a second one. On a channel with a market filter it adds the listed markets to the existing sid and replies ok (or an error); it does not resend snapshots for markets already subscribed. To change anything else about a subscription, unsubscribe, wait for unsubscribed, then subscribe again.
Keeping a local order book in sync
orderbook_delta first sends an orderbook_snapshot per market, with yes_dollars_fp and no_dollars_fp as lists of [price_in_dollars, contract_count] string pairs. Either key is missing when that side is empty. Kalshi returns bids only: a YES bid at a price is the same as a NO ask at one dollar minus it. After the snapshot, each orderbook_delta changes one price level:
{"type": "orderbook_delta", "sid": 2, "seq": 3,
"msg": {"market_ticker": "FED-23DEC-T3.00",
"clock": 4182061,
"price_dollars": "0.9600",
"delta_fp": "-54.00",
"side": "yes",
"ts_ms": 1669149841000}}Add delta_fp to the size at price_dollars on sideand drop the level when it reaches zero. Prices and sizes are fixed-point strings, so parse them as decimals, not floats. When the delta was caused by one of your own orders, it also carries that order's client_order_id.
Four rules keep the book correct:
- Check
seq. It counts messages on one subscription and should rise by exactly one. On a gap, requestget_snapshotfor every subscribed market (or unsubscribe and subscribe again) and replace each book with its new snapshot. A repeatedsubscribealone does not resynchronize markets you already have. - A snapshot always replaces.Any snapshot, including one you asked for, replaces that market's local book before you apply later deltas.
- Use
clockacross connections, notseq.clockis the exchange's clock and matches across redundant connections; a snapshot includes every change at or below its clock. Clocks skip values, aren't comparable between markets, and can go backwards across exchange maintenance. - Watch for the empty snapshot. When a market is determined, Kalshi sends an empty snapshot for it and removes it from the subscription, with no other notice. Replace the book with the empty one and stop quoting it.
If you don't need every change, set update_interval_ms to 100 or 1000 on the first subscribe to get conflated deltas (0, the default, is real time). The interval is fixed for the life of the subscription. Conflated subscriptions follow different clock rules: clocks can go down between messages, so never drop a conflated delta for having a lower clock, and never merge two conflated streams by clock. Updates to your own orders skip the interval, so between flushes the public levels can lag yours and the book can look crossed.
Testing this reconciliation logic is where most WebSocket bugs surface; our guide to Kalshi's market data endpoints covers reconciling the stream against REST reads.
Keep-alive, disconnects and reconnects
Kalshi sends a WebSocket Ping frame only after 10 seconds without sending you a data message; answer it with a Pong. Most client libraries, including Python's websockets, do that for you. A busy connection can go a long time without a Ping, so its absence is not a sign the connection is dead.
The server can close the connection at any time. What you will see:
- Close code 1008, “WebSocket server delivery exceeded 15 seconds”: your client fell behind reading. Read the socket continuously, move slow work off the reading path, or subscribe to fewer markets.
- Close code 1000: a normal closure, such as a server shutdown during a release. It names no cause; reconnect with backoff.
- An error with code 10 or 25 carrying a
sid, thenunsubscribed: that subscription ended but the connection and your other subscriptions are fine. Subscribe to it again.
Subscriptions and sid values do not survive a reconnect. After reconnecting, subscribe again, throw away every local book and rebuild from the new snapshots. Between the drop and the new snapshot your bot is blind: it may have been filled or canceled in the gap, which is where cancel-versus-fill races come from. Reconcile open orders and positions over REST before trading again.
Limits
- Concurrent connectionsare capped per user and set by your API tier, shared between Kalshi's prediction and perps (margin) WebSocket connections. Reaching the cap makes new handshakes return 429. Check the current number for your tier on Kalshi's rate limits page.
- Markets per order book subscription: at most 500,000; a command that would go over adds none of its markets (error 26).
- Command rate:
subscribeandadd_marketscommands onorderbook_deltasent too fast are refused with error 27 and not applied.
Error codes worth handling
Errors arrive as {"type": "error", "msg": {"code": …, "msg": …}}, with the id of the command that caused them when there is one. The ones a bot should handle in code:
| Code | Error | What to do |
|---|---|---|
| 9 | Authentication required | The key can't use that channel. A market-data-only key gets this on fill, market_positions, order_group_updates and user_orders. |
| 10 | Channel error | With a sid and no id, a running subscription ended (an unsubscribed follows): subscribe again. With your command's id, the subscribe never opened. |
| 11 | Invalid parameter | Also what a repeated orderbook_delta subscribe with a different update_interval_ms returns. Use update_subscription to add markets. |
| 13 / 14 | Unsupported action / Market Ticker required | Usually a repeated subscribe on ticker (made without a market filter) or trade (sent without markets). Unsubscribe and subscribe again with a filter. |
| 25 | Subscription buffer overflow | The subscription ended during a burst. Read faster or subscribe to fewer markets, then subscribe again. |
| 26 | Subscription market limit exceeded | The command would take an orderbook_delta subscription past 500,000 markets; none of its markets were added. |
| 27 | Too many requests | orderbook_delta subscribe or add_markets commands sent too fast. Not applied: wait briefly and resend. |
The full table is in Kalshi's WebSocket quick start.
A reconnecting order book client in Python
A sketch of the pieces above using the websockets and cryptography packages, pointed at the demo host: sign the handshake, subscribe, rebuild each book from its snapshot, apply deltas, ask for fresh snapshots on a seq gap, and reconnect with exponential backoff. It signs with an RSA key; for an Ed25519 key, call private_key.sign(message) without the padding arguments.
import asyncio, base64, json, time
from decimal import Decimal
import websockets
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
WS_URL = "wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2" # demo
WS_PATH = "/trade-api/ws/v2"
def auth_headers(key_id, private_key):
"""RSA-PSS signature over timestamp + GET + the fixed WebSocket path."""
ts = str(int(time.time() * 1000))
sig = private_key.sign(
(ts + "GET" + WS_PATH).encode(),
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH),
hashes.SHA256(),
)
return {
"KALSHI-ACCESS-KEY": key_id,
"KALSHI-ACCESS-SIGNATURE": base64.b64encode(sig).decode(),
"KALSHI-ACCESS-TIMESTAMP": ts,
}
def book_from_snapshot(msg):
return {
side: {Decimal(p): Decimal(q) for p, q in msg.get(f"{side}_dollars_fp", [])}
for side in ("yes", "no")
}
def apply_delta(book, msg):
levels = book[msg["side"]]
price = Decimal(msg["price_dollars"])
size = levels.get(price, Decimal(0)) + Decimal(msg["delta_fp"])
if size > 0:
levels[price] = size
else:
levels.pop(price, None)
async def stream_books(key_id, private_key, tickers, on_update):
backoff = 1
while True:
try:
async with websockets.connect(
WS_URL, additional_headers=auth_headers(key_id, private_key)
) as ws:
backoff = 1
# Subscriptions don't survive a reconnect: start clean every time.
books, last_seq, next_id = {}, None, 2
await ws.send(json.dumps({
"id": 1, "cmd": "subscribe",
"params": {"channels": ["orderbook_delta"],
"market_tickers": tickers},
}))
async for raw in ws:
m = json.loads(raw)
kind = m.get("type")
if kind == "error":
print("error", m["msg"])
continue
if kind not in ("orderbook_snapshot", "orderbook_delta"):
continue
if last_seq is not None and m["seq"] != last_seq + 1:
# A message was missed: every book is suspect until
# fresh snapshots replace them.
await ws.send(json.dumps({
"id": next_id, "cmd": "update_subscription",
"params": {"sid": m["sid"], "action": "get_snapshot",
"market_tickers": tickers},
}))
next_id += 1
last_seq = m["seq"]
msg = m["msg"]
ticker = msg["market_ticker"]
if kind == "orderbook_snapshot":
books[ticker] = book_from_snapshot(msg)
elif ticker in books:
apply_delta(books[ticker], msg)
on_update(ticker, books.get(ticker))
except (websockets.ConnectionClosed, OSError) as exc:
print("disconnected:", exc)
await asyncio.sleep(backoff)
backoff = min(backoff * 2, 60)Load the key with serialization.load_pem_private_key(pem_bytes, password=None) and keep it out of source control. Before this goes near real money, add the REST reconciliation step after each reconnect.
Testing it before production
The demo host behaves like production for the handshake, channels and reconnects, but it won't produce the drops, gaps and bursts you need to prove the recovery paths. Those come from a simulator you control: see stateful Kalshi API simulation for local bot development and CI pipeline testing for Kalshi bot order logic, which drop and re-establish the connection mid-sequence and assert on sequence tracking and book patching.