Which package to install
Kalshi's Python SDK is two packages built from the same spec, with the same method names. Pick by concurrency model, not by features. (There is also a TypeScript SDK, kalshi-typescript on npm.)
| Package | Install | Use it for |
|---|---|---|
kalshi_python_sync | pip install kalshi_python_sync | Blocking client on urllib3. Scripts, notebooks, and bots with one request in flight at a time. |
kalshi_python_async | pip install kalshi_python_async | asyncio client on aiohttp. Bots that read several endpoints at once or share a loop with a WebSocket feed. |
kalshi-python | Don't | The old package. Kalshi marks it deprecated; code using it should move to one of the two above. |
Both wrap the REST API only. Streaming order books, trades and your fills is the WebSocket API, which the SDK has no client for; see our WebSocket API guide for that half of the bot.
Versions and pinning
Kalshi says SDK releases follow its OpenAPI spec and generally go out Tuesday to Wednesday each week, ahead of the API changes they cover. That cadence is the reason to pin an exact version in a bot and upgrade on purpose, reading the API changelog first:
python -m pip install "kalshi_python_sync==3.36.0"
python -c "import kalshi_python_sync; print(kalshi_python_sync.__version__)"Three version facts worth knowing before you pin:
- Python version.Release 3.36.0 declares Python 3.13 or newer. If your bot runs an older interpreter, check the “Requires” line on PyPI for the release you want.
- Ed25519 keys need 3.31.0 or later.RSA keys work with every SDK version. If you generated an Ed25519 key, an older pin can't sign with it.
- The SDK can lag the API.Kalshi's own docs say so, and recommend that active traders treat the OpenAPI spec as the source of truth, or generate their own client from it.
Point it at demo first
Every call goes through a Configuration. Built with no host, it targets production, https://external-api.kalshi.com/trade-api/v2. A script that forgets the argument talks to production: with a demo key that fails authentication, and with a production key it trades real money. Make the host explicit and default it to demo:
import os
from kalshi_python_sync import Configuration, KalshiClient
DEMO = "https://external-api.demo.kalshi.co/trade-api/v2"
PROD = "https://external-api.kalshi.com/trade-api/v2"
# Configuration() with no host means production. Always pass one.
config = Configuration(host=os.environ.get("KALSHI_HOST", DEMO))| Environment | REST base URL |
|---|---|
| Demo | https://external-api.demo.kalshi.co/trade-api/v2 |
| Production | https://external-api.kalshi.com/trade-api/v2 |
| Production (older shared host, still supported) | https://api.elections.kalshi.com/trade-api/v2 |
Kalshi doesn't share credentials between demo and production, so each needs its own key. What demo does and doesn't mirror is in our walkthrough of the demo topology; the host list is on Kalshi's API environments page.
Authenticating
KalshiClient signs every request itself: it sends KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP and KALSHI-ACCESS-SIGNATURE, signing the millisecond timestamp, the method and the request path without its query string. It tells RSA from Ed25519 by reading the PEM, using RSA-PSS with SHA-256 for RSA keys. You give it the key id and the private key text:
config.api_key_id = os.environ["KALSHI_API_KEY_ID"]
with open(os.environ["KALSHI_PRIVATE_KEY_PATH"]) as f:
config.private_key_pem = f.read()
# The client reads both credentials once, here. Setting them
# on config afterwards has no effect on this client.
client = KalshiClient(config)
balance = client.get_balance()
print(balance.balance_dollars) # fixed-point string; .balance is centsOne behaviour catches people out. The client looks for both api_key_id and private_key_pemon the configuration when it is constructed. If either is missing then, it doesn't raise: it sends every request unsigned. Public market data still works, so the mistake only shows up as a 401 on your first portfolio or order call, with the code token_authentication_failure. Set both, then build the client. The private key must be unencrypted PEM; keep it out of source control and load it from a file or secret store. Creating keys and the signing scheme in detail: Kalshi REST API authentication and token management.
Reading market data
Market, event, series, trade and order book reads need no key. A client built without credentials is the simplest way to keep read-only tooling from ever holding one. List endpoints are cursor-paginated: pass back the cursorfrom each response until it comes back empty. Unfiltered listings include combo markets, which usually aren't what a single-market bot wants, so filter them out:
from decimal import Decimal
from kalshi_python_sync import Configuration, KalshiClient
# No credentials: requests go out unsigned, which the public
# market data endpoints accept.
public = KalshiClient(Configuration(host=DEMO))
def open_markets(client, series_ticker=None):
"""Every open market, following the cursor until it comes back empty."""
cursor = None
while True:
page = client.get_markets(
status="open",
series_ticker=series_ticker,
mve_filter="exclude", # leave out combo (multivariate) markets
limit=1000,
cursor=cursor,
)
yield from page.markets
cursor = page.cursor
if not cursor:
returnPrices and sizes arrive as fixed-point strings (yes_bid_dollars, volume_fp and so on). Parse them with Decimal, never float. The order book is bids only, as [price, count] string pairs per side:
book = public.get_market_orderbook(ticker, depth=10).orderbook_fp
yes_bids = [(Decimal(p), Decimal(q)) for p, q in book.yes_dollars]
no_bids = [(Decimal(p), Decimal(q)) for p, q in book.no_dollars]
best_yes_bid = max(yes_bids, default=None)
best_no_bid = max(no_bids, default=None)
# Bids only: the best YES ask is one dollar minus the best NO bid.
best_yes_ask = Decimal(1) - best_no_bid[0] if best_no_bid else NoneTake the best level with max() rather than trusting the list order. Each market also carries price_ranges, the valid price steps for orders on it; check a price against them before you send it. Field-by-field coverage of these responses is in our guide to Kalshi's market data endpoints.
Placing and canceling orders
Use create_order_v2 and cancel_order_v2. Kalshi has removed the legacy /portfolio/orders write endpoints, which now answer 410 Gone, so code from an older SDK or tutorial that places orders that way stops working.
import uuid
from decimal import Decimal
order = client.create_order_v2(
ticker=ticker,
client_order_id=str(uuid.uuid4()), # new one for every order
side="bid", # buy YES; "ask" sells YES
count="5", # fixed-point string, not an int
price="0.4200", # dollars, on the market's price grid
time_in_force="good_till_canceled",
self_trade_prevention_type="taker_at_cross",
post_only=True,
)
print(order.order_id, order.fill_count, order.remaining_count)
if Decimal(order.remaining_count) > 0:
cancel = client.cancel_order_v2(order.order_id, market_ticker=ticker)
print("canceled", cancel.reduced_by)What the V2 shape asks of you:
- One book, quoted from YES.
sideisbid(buy YES) orask(sell YES). There is no separate NO side on the request. - Strings for numbers.
countandpriceare fixed-point strings. Fractional counts are allowed only on markets that trade them. - Required fields.
ticker,side,count,price,time_in_force(good_till_canceled,immediate_or_cancelorfill_or_kill) andself_trade_prevention_type(taker_at_crossormaker). The SDK's model rejects a request missing one before it is sent. - A 201 is not a resting order. It means the order was accepted. Read
fill_countandremaining_counton the response to learn what happened. - Cancel with the ticker. Passing
market_tickertocancel_order_v2lets Kalshi route the cancel to the right exchange shard. The response carriesreduced_by, not a full order.
Send a fresh client_order_id with every order. If a create times out and you resend it, Kalshi rejects the duplicate with order_already_existswhile the first order is still open, but not reliably once it has filled, canceled or expired. So when a write's outcome is unknown, look the order up before resending. The order lifecycle over REST is covered in placing and canceling Kalshi orders via the REST API, and the cancel-versus-fill race in race conditions between cancel and fill confirmation.
Handling errors
Any non-2xx response raises. The class depends on the HTTP status; all of them subclass ApiException, which carries status, headers and the raw body.
| Status | Raised as | Usually means |
|---|---|---|
| 400 | BadRequestException | A field failed validation: price off the market's grid, a malformed count or client_order_id. |
| 401 | UnauthorizedException | The request went out unsigned or with a bad signature. Check that both credentials were set before the client was built. |
| 403 | ForbiddenException | The key's scope or your account's API tier doesn't allow the call. |
| 404 | NotFoundException | Unknown ticker or order. Order reads lag writes, so a just-created order can briefly 404. |
| 409 | ConflictException | On create, order_already_exists: that client_order_id belongs to an open order. Don't resend. |
| 429 | ApiException (status 429) | Rate limited. There is no dedicated class, so check e.status. |
| 5xx | ServiceException | Server-side failure. For writes, the outcome is unknown until you look the order up. |
The status alone rarely tells you what to do. Kalshi's error code does, and it lives in the JSON body, so parse it:
import json
from kalshi_python_sync import ApiException, ConflictException
def error_of(e: ApiException) -> dict:
"""Kalshi's error body is {"error": {"code", "message", "details"}}."""
try:
return json.loads(e.body or "{}").get("error", {})
except ValueError:
return {}
try:
order = client.create_order_v2(**order_fields)
except ConflictException:
# order_already_exists: the first attempt is open. Find it, don't resend.
found = client.get_orders(ticker=order_fields["ticker"], status="resting")
except ApiException as e:
err = error_of(e)
print(e.status, err.get("code"), err.get("details"))Every order error code and its fix is listed on Kalshi's order errors page.
The async client
kalshi_python_async has the same Configuration, the same KalshiClient and the same method names; each call is awaited, and the client is an async context manager that closes its HTTP session on exit.
import asyncio
import os
from kalshi_python_async import Configuration, KalshiClient
DEMO = "https://external-api.demo.kalshi.co/trade-api/v2"
async def main():
config = Configuration(host=DEMO)
config.api_key_id = os.environ["KALSHI_API_KEY_ID"]
with open(os.environ["KALSHI_PRIVATE_KEY_PATH"]) as f:
config.private_key_pem = f.read()
async with KalshiClient(config) as client:
balance, positions = await asyncio.gather(
client.get_balance(),
client.get_positions(count_filter="position"),
)
print(balance.balance_dollars, len(positions.market_positions))
asyncio.run(main())Concurrency makes it easier to spend your rate limit faster, not to get more of it. asyncio.gather over a hundred tickers fires a hundred requests at once; bound it with a semaphore sized to your tier.
What the SDK leaves to you
- Timeouts. The plain methods take no timeout, and none is set by default, so a stalled connection can block a call indefinitely. The
*_with_http_infovariant of each method takes_request_timeoutand returns the parsed result on.data:
resp = client.get_markets_with_http_info(
status="open",
limit=100,
_request_timeout=(3.0, 10.0), # (connect, read) seconds, as floats
)
markets = resp.data.markets- Retries.
Configurationtakesretries. In the async client, retries are off unless you set it, and then cover GET, DELETE and other idempotent methods but never POST, so order creation is never retried for you. The sync client passes the setting to urllib3, and leaves urllib3's own defaults in place when you don't set it. Decide it explicitly either way. - Rate limiting. Nothing in the SDK paces requests. Kalshi meters reads and writes against token budgets set by your API tier; the numbers are on its rate limits page, and pacing strategies are in our piece on rate limits and throttling.
- Streaming. No WebSocket client, as above. Most bots use the SDK to act and reconcile and a WebSocket connection to see fills and book changes as they happen.
- Response drift. Responses are parsed into strict Pydantic models. When the API adds or changes a field ahead of the SDK, parsing can fail even though the request succeeded. The
*_without_preload_contentvariant of each method returns the raw HTTP response instead, which is a useful fallback for the endpoint that broke. - State. The SDK keeps no view of your orders or positions. Reconcile them yourself, as in portfolio and position endpoints for bot state tracking.
Testing code built on it
Because every method lives on one KalshiClient, the cleanest seam in a bot is a thin class of your own that wraps it, so tests can swap in a fake or point the same code at a simulator by changing host. Demo is right for checking signing, field formats and the order calls end to end, but it won't produce the timeouts, 429s and partial fills your error paths need. 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. Record the SDK version you tested against alongside the results; with weekly releases, “it passed” means little without it.