
Kalshi WebSocket API: Python Guide and Live Latency Tests
You want live Kalshi prices in your bot instead of polling REST every few seconds, so you connect to wss://external-api-ws.kalshi.com/trade-api/ws/v2, send a subscribe command, and get back nothing. Or worse, you get a stream that looks right until your local orderbook drifts away from the real book within minutes. The Kalshi WebSocket API is well documented at the message level and thin on the operational details that decide whether a bot survives the night.
Everything below was checked against the live exchange on October 19, 2026: the handshake, every channel name against production, the wire format of snapshots and deltas, the error codes we provoked on purpose, throughput, and per-channel latency. Where the docs and the running system disagree, we say so.
Key Takeaway: A Kalshi WebSocket connection needs the same signed headers as REST, with
timestamp + GET + /trade-api/ws/v2as the signed string. Then subscribe narrowly:tradeandorderbook_deltafor decisions,tickerfor display only (440 ms median lag in our test), sequence numbers are per subscription ID, and a gap means resync with theget_snapshotaction rather than patching deltas onto stale state.
What the Kalshi WebSocket gives you
The Trade API WebSocket is a single connection that carries thirteen subscribable channels, which is what we got when we sent a subscribe command for every name in the official AsyncAPI specification (version 2.0.0) against production on October 19, 2026. They split into two groups:
- Private, user-specific:
fill,market_positions,communications,order_group_updates,user_orders - Public market data:
ticker,trade,market_lifecycle_v2,multivariate_market_lifecycle, pluscfbenchmarks_value,cfbenchmarks_value_5hzandpyth_valuefor index and underlying price feeds
orderbook_delta sits in between. It needs no account-level permission, but it does require you to name the markets you want.
One name to cross off your list: the Quick Start lists a channel called multivariate, but production rejects that subscribe with error code 8, “Unknown channel name”. The real channel is multivariate_market_lifecycle.
Hosts, from the endpoint documentation:
| Environment | Recommended WebSocket URL | Still supported |
|---|---|---|
| Production | wss://external-api-ws.kalshi.com/trade-api/ws/v2 | wss://api.elections.kalshi.com/trade-api/ws/v2 |
| Demo | wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2 | wss://demo-api.kalshi.co/trade-api/ws/v2 |
Credentials do not cross environments. We sent a working production key to the demo host and the handshake was rejected with HTTP 401, same as an unauthenticated attempt. Demo keys only work on demo hosts.
The handshake: sign once, then forget about auth
There is a widespread assumption that public channels are open. They are not. On October 19, 2026 we opened connections to all three hosts above with no headers and every one of them answered HTTP 401 before a single byte of WebSocket framing. The Quick Start states it plainly: authentication happens during the handshake, and public channels only skip the additional channel-level check afterwards.
The signed string is shorter than the REST version because the path has no query parameters:
timestamp + "GET" + "/trade-api/ws/v2"
timestamp is Unix milliseconds as a string. Kalshi documents two key types: Ed25519 (default for new keys) and RSA-PSS over SHA-256 with salt_length = PSS.DIGEST_LENGTH. We connected with a 2048-bit RSA key, and the handshake succeeded on the first attempt with exactly this construction. If your signature fails, the debugging checklist is the same as for REST, and the API key guide walks through the four failure modes we reproduced there.
import base64, json, os, time
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
WS_PATH = "/trade-api/ws/v2"
def ws_headers(key_id: str, pem: str) -> dict:
key = serialization.load_pem_private_key(pem.encode(), password=None)
ts = str(int(time.time() * 1000))
msg = (ts + "GET" + WS_PATH).encode()
if isinstance(key, Ed25519PrivateKey):
sig = key.sign(msg)
else:
sig = key.sign(
msg,
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,
}
One operational note: the signature is tied to a timestamp, so generate headers at connection time, not at process start. Long-running bots that reconnect after a network blip must re-sign, not reuse the header dict from three hours ago.
Build a live orderbook in Python
This is the smallest version that stays correct: connect, subscribe to orderbook_delta for a named list of markets, replace your local book on orderbook_snapshot, and apply signed deltas afterwards. It ran unchanged against production while we wrote this.
import asyncio, collections, json
import websockets
WS_URL = "wss://external-api-ws.kalshi.com/trade-api/ws/v2"
class Book:
def __init__(self):
self.levels = {"yes": {}, "no": {}}
self.seq = None
def apply_snapshot(self, msg):
self.levels = {"yes": {}, "no": {}}
for side, key in (("yes", "yes_dollars_fp"), ("no", "no_dollars_fp")):
for price, size in msg.get(key, []):
self.levels[side][float(price)] = float(size)
self.seq = None
def apply_delta(self, msg):
side = msg["side"]
price = float(msg["price_dollars"])
new = self.levels[side].get(price, 0.0) + float(msg["delta_fp"])
if new <= 0:
self.levels[side].pop(price, None)
else:
self.levels[side][price] = new
def best(self):
yes_bid = max(self.levels["yes"], default=None)
no_bid = max(self.levels["no"], default=None)
yes_ask = None if no_bid is None else round(1 - no_bid, 4)
return yes_bid, yes_ask
async def run(key_id, pem, tickers):
books = {t: Book() for t in tickers}
backoff = 1
while True:
try:
async with websockets.connect(WS_URL, additional_headers=ws_headers(key_id, pem)) as ws:
backoff = 1
await ws.send(json.dumps({
"id": 1, "cmd": "subscribe",
"params": {"channels": ["orderbook_delta"], "market_tickers": tickers},
}))
async for raw in ws:
msg = json.loads(raw)
kind = msg.get("type")
if kind == "error":
print("error", msg["msg"]); continue
if kind not in ("orderbook_snapshot", "orderbook_delta"):
continue
payload = msg["msg"]
book = books[payload["market_ticker"]]
seq = msg.get("seq")
if kind == "orderbook_snapshot":
book.apply_snapshot(payload)
elif book.seq is not None and seq != book.seq + 1:
print(f"gap on {payload['market_ticker']}: {book.seq} -> {seq}, resync")
book.seq = None
continue
else:
book.apply_delta(payload)
book.seq = seq
except Exception as exc:
print("reconnect:", exc)
await asyncio.sleep(backoff)
backoff = min(backoff * 2, 60)
Real messages from that connection, trimmed to the fields that matter:
{"type":"orderbook_snapshot","sid":1,"seq":1,
"msg":{"market_ticker":"KXELONMARS-99","market_id":"f1a31d77-...",
"yes_dollars_fp":[["0.0100","4055.78"],["0.0200","3540.17"]],
"no_dollars_fp":[["0.0100","19691.00"],["0.0200","7660.00"]]}}
{"type":"orderbook_delta","sid":2,"seq":7,
"msg":{"market_ticker":"KXETH15M-26OCT190330-30",
"price_dollars":"0.7800","delta_fp":"-20.00","side":"no",
"ts":"2026-10-19T07:23:23.702Z","ts_ms":1792394603702}}
Three things in those payloads cost people an afternoon:
- Prices and sizes are fixed-point dollar strings, in
price_dollarsanddelta_fp.-20.00means twenty contracts left that level, not twenty cents. - The book only contains bids. There are no asks on the wire, on either protocol: the orderbook endpoint returns yes and no bids only, because a no bid at 0.22 is economically a yes ask at 0.78. Derive the ask, do not look for it.
- Sequence numbers are per subscription ID (
sid), not per market. Oneorderbook_deltasubscription over six markets shares a single counter, so a gap does not tell you which market you missed.
Resync without reconnecting
The clean recovery path is documented but easy to miss: update_subscription supports an action called get_snapshot, which returns a fresh orderbook_snapshot for the markets you name and leaves the subscription untouched. We called it mid-stream and the returned snapshot carried the next sequence number on the same subscription, which is the behaviour you want: replace your local state, adopt that seq, continue.
await ws.send(json.dumps({
"id": 5, "cmd": "update_subscription",
"params": {"sid": 1, "market_tickers": ["KXELONMARS-99"], "action": "get_snapshot"},
}))
The same command pair, add_markets and delete_markets, lets you rotate which markets a long-lived subscription covers without tearing down the socket. If you trade a set that rolls every fifteen minutes, as the crypto series do, this is the difference between a stable process and one that reconnects every quarter hour.
Ticker is a status feed, not a price feed
Here is the number we did not find in any documentation. Kalshi stamps every message twice: the event timestamp inside msg.ts_ms, and the send timestamp on the envelope in sending_ts_ms. The difference is the delay between the exchange changing state and you hearing about it.
Over a 15-second window we collected 8,120 ticker messages and 1,536 trade messages on a single connection:
| Channel | Median delay | p90 | Max |
|---|---|---|---|
ticker | 440 ms | 897 ms | 1,067 ms |
trade | 6 ms | 8 ms | 19 ms |
The ticker channel is batched for fan-out and can be a full second stale. The trade channel is pushed almost immediately. If your bot makes a decision from ticker.yes_bid_dollars and then sends an order, the price it acted on may already be gone, and on a 15-minute market with an active crowd that is the whole game. Decide on trade plus your reconstructed orderbook_delta book; use ticker for dashboards, alerts and position marks.
Expert insight: The observable gap between
msg.ts_msandsending_ts_msis the cheapest latency monitor you will ever build. Log its median per channel at startup, alert when it triples, and you will notice an exchange-side slowdown or a saturated local event loop before your fills start looking mysteriously bad.
Subscribing to everything is a mistake
With no market filter, ticker and trade subscribe you to the entire exchange. In a 12-second window that connection delivered 6,758 messages, about 560 per second (5,720 ticker, 1,036 trade). Add orderbook_delta for six of the busiest 15-minute crypto markets and we counted 29,185 deltas in 12 seconds, roughly 2,400 per second. A single Python event loop can keep up, but only if the handler does almost nothing: parse, update two dictionaries, return. Any per-message database write or JSON re-serialisation will put you minutes behind within an hour.
Practical filters, in order of impact:
- Subscribe per market list, never globally, and rotate with
update_subscription. - Batch your own writes (to disk, database, or a queue) outside the receive loop.
- Cap the book: you rarely need more than the top ten levels on each side, and trimming costs less than carrying 20,000 price points.
Error codes we provoked on purpose
Verbatim responses from production, October 19, 2026:
| What we sent | Response | Reading |
|---|---|---|
subscribe with channel nope_channel | {"type":"error","id":9,"msg":{"code":8,"msg":"Unknown channel name"}} | Channel name typo or retired channel |
orderbook_delta without market_ticker / market_tickers | {"type":"error","id":10,"msg":{"code":2,"msg":"Params required"}} | Market filter is mandatory here |
Malformed JSON ({not json) | {"type":"error","msg":{"code":1,"msg":"Unable to process message"}} | No id echoed back, so you cannot correlate it to a command |
| No auth headers at handshake | HTTP 401 before the upgrade | Auth is at connection level |
Note the mismatch on the second row: the published error table describes code 14 as “Market Ticker required” for a missing market filter, but the running system answers code 2, “Params required”. Match on both if you branch on codes.
A second undocumented-in-the-quickstart behaviour: subscribing to market_lifecycle_v2 also delivers event_lifecycle messages on the same sid and the same sequence counter. In our capture, 40 lifecycle messages arrived in 25 seconds across both types. If your handler assumes type == "market_lifecycle_v2" for everything on that subscription, new events will be silently ignored, which is exactly what you do not want when a market you trade is created or settles.
Checklist before you ship a WebSocket bot
- Sign at connect time with the shorter
/trade-api/ws/v2string, and re-sign on every reconnect. - Subscribe per market list; rotate with
update_subscriptioninstead of reconnecting. - Treat
orderbook_snapshotas the only source of truth and a sequence gap as “resync now”. - Derive asks from opposite bids; the wire carries bids only.
- Decide on
tradeplus the delta book, keeptickerfor display, and logsending_ts_msminusts_msso latency drift is visible. - Handle
errorframes in the main loop (code 1 carries noid) and reconnect with exponential backoff plus jitter.
Update, November 16, 2026: for fill and user_orders Kalshi now points to the user-ws.kalshi.com host (the warp-ws host is deprecated), and orderbook_delta accepts an update_interval_ms of 100 or 1000. These and other recent changes are tracked in our Kalshi API changelog tracker.
That is the plumbing. If you have already solved it once, the v2 field reference saves you from guessing at payload names, and the cheat sheet keeps the endpoints and fee formulas in one page. If you would rather start from working code than from a blank file, the Kalshi Bot Kit ships this subscription loop with market rotation, resync and order placement already wired together, and you can backtest the strategy before you run it live using the historical data workflow. Historical candles and settled books are also on the Kalshi data reference.
One prerequisite that catches people out: the handshake needs a key, and a key needs an account. If you are setting that up from scratch, that is the moment to create a Kalshi account and then follow the API key steps before returning here.
EdgeOutcome may earn a commission if you sign up through our affiliate links. Nothing here is trading advice.
18+. Prediction markets involve real financial risk. Availability depends on your country and US state.
Frequently Asked Questions
Does the Kalshi WebSocket API require authentication?
Yes, and it requires it at the handshake, not per channel. We opened connections to external-api-ws.kalshi.com, api.elections.kalshi.com and external-api-ws.demo.kalshi.co without headers on October 19, 2026 and all three answered HTTP 401. Even the public channel ticker needs the authenticated session; once connected it just skips per-channel authorization checks.
What do I sign for a Kalshi WebSocket connection?
The string timestamp + GET + /trade-api/ws/v2, signed with your private key exactly like a REST call. Kalshi documents RSA-PSS over SHA-256 and Ed25519. We connected with a 2048-bit RSA key on October 19, 2026 and the handshake succeeded first try. Query parameters are not part of the string because the WebSocket path has none.
How do I keep a Kalshi WebSocket connection alive?
You do not have to do anything if you use the Python websockets library, which answers ping frames automatically. Kalshi sends a ping frame (0x9) with the body heartbeat and expects a pong (0xA). Libraries without automatic keepalive, including several Node clients, drop the connection silently after a few minutes idle.
Why does my Kalshi orderbook stop matching the real book?
Two reasons dominate. First, snapshots and deltas carry yes and no bids only, so the best ask has to be derived as 1 minus the best opposite bid. Second, seq is per subscription ID: if you see a gap, discard the local book and request a fresh snapshot with the update_subscription get_snapshot action instead of patching deltas onto a stale state.
Is the Kalshi ticker channel fast enough for a trading bot?
Not for execution. In our October 19, 2026 test we compared the exchange send stamp with each message's own timestamp across 8,120 ticker and 1,536 trade messages: ticker arrived with a median delay of 440 ms (p90 897 ms), while the trade channel arrived with a median of 6 ms (p90 8 ms). Use trade and orderbook_delta for decisions and ticker for display only.