Guides · Kalshi API Integration

Kalshi Trading Bot: How to Build, Test and Run One Safely

A Kalshi trading bot is a strategy wrapped in plumbing: a market data stream, an order path, a running account of what it holds, and the controls that stop it when something goes wrong. The strategy is yours. This guide is the rest: what each part uses on Kalshi's API, the safeguards the exchange gives you for free, the limits and maintenance windows a bot has to live with, and how to test it before it trades real money.

Checked against Kalshi's API documentation on . Kalshi changes its API often; its docs are the final word.

The parts of a Kalshi bot

Whatever it trades (weather, economic releases, sports), a bot that runs unattended has the same six parts. Most losses that aren't the strategy's fault come from one of the last four.

PartWhat it uses on KalshiHow it usually breaks
Market dataWebSocket channels (orderbook_delta, ticker, trade, market_lifecycle_v2); REST for discoveryA missed delta leaves the local book wrong while the bot keeps quoting from it.
StrategyNone: this is your codeDecisions made on stale or crossed books, or on markets that have already closed.
Order managementREST V2 order endpoints (or FIX)Duplicate orders after a timeout and resend; cancels that race fills.
Statefill, user_orders and market_positions channels; REST orders, fills, positions, balanceThe bot's idea of its position drifts from Kalshi's after a disconnect.
Risk controlsOrder groups, Cancel All Orders, cancel_order_on_pause, reduce_only, subaccounts, key scopesA runaway loop with nothing outside it to stop the orders.
OperationsExchange status, maintenance schedule, rate limit headersThursday maintenance, a 429 storm or a drifting clock taken for a bug in the strategy.

Put together, the main loop looks like this:

on start:
    check GET /exchange/status (a 200 with trading_active true)
    reconcile: resting orders, positions, balance over REST
    create or reset the order group for this strategy
    connect the WebSocket, subscribe, wait for snapshots

on every book or lifecycle message:
    update the local book; on a seq gap, resync before deciding
    skip markets that are closed, inactive or determined
    decide; check your own limits (position, open orders, loss)
    place, amend or cancel with a fresh client_order_id

on fill / user_orders messages:
    update orders and exposure; treat positions as pending
    until market_positions or a REST read confirms them

on disconnect, 401, 5xx or anything unexpected:
    stop placing orders
    reconnect with backoff, then reconcile over REST again
    if it can't reconcile: Cancel All Orders and page a human

The rest of this guide takes those lines one at a time. The rule running through all of them: when the bot isn't sure what it holds, it stops placing orders until it is.

Account, keys and API tier

  • Two environments, two sets of keys.Kalshi's demo environment (demo.kalshi.co) trades mock funds, and its credentials don't work in production or the other way round. Make a demo account and key first; the bot should only ever reach production through a setting you change on purpose.
  • Key type. Kalshi recommends Ed25519 keys and still supports RSA. The private key is shown once when the key is made; store it in a secret store or a file outside the repository.
  • Scopes. A key made without scopes gets full read and write. Give the bot read and write::trade: enough to trade and to read its orders, fills and positions, not enough to make keys or move money. A key with only write::tradecan place orders but can't list them, which leaves a bot blind.
  • Clock.Every request is signed with a millisecond timestamp that must be within 30 seconds of Kalshi's clock, or it fails with header_timestamp_expired. Keep the host synced with NTP.
  • API tier. New accounts start on Basic. Advanced takes one call to the upgrade endpoint, which only succeeds once at least one of your latest 100 orders was placed through the API. Higher tiers are earned from trading volume. The tier sets your rate limits and whether you can make subaccounts.

Signing in detail: Kalshi REST API authentication and token management. Key types and scopes are on Kalshi's API keys page.

Market data in

Use REST to find markets and the WebSocket API to watch them. List markets with GET /markets?status=open, following the cursor, and filter to the series your strategy understands. Then subscribe to orderbook_delta for the books you trade, trade if prints matter, and market_lifecycle_v2so the bot hears when a market is deactivated, closes early or is determined. Polling books over REST instead spends your Read budget on markets that haven't moved.

Three lifecycle facts a strategy has to respect:

  • Once close_time passes, every order operation on that market, cancels included, is rejected with MARKET_INACTIVE, and Kalshi cancels resting orders shortly after. close_time can be moved earlier.
  • When an inactivemarket is reactivated, all its resting orders are canceled. A bot that assumes its quotes survived the pause will think it is in a market it isn't.
  • The move from initialized to active at open_time sends no WebSocket event. Watch the clock or read the market again.

Keeping a local book correct (snapshots, seq gaps, reconnects) is its own subject; see our Kalshi WebSocket API guide. Statuses and transitions are on Kalshi's market lifecycle page.

Orders out

Orders go through the V2 endpoints: create is POST /portfolio/events/orders, with V2 amend, cancel and batch forms beside it. The legacy /portfolio/orders write endpoints are gone and answer 410 Gone, so a bot or tutorial written against them no longer places orders. An order from a bot that uses the safeguards below:

POST /trade-api/v2/portfolio/events/orders
{
  "ticker": "<market ticker>",
  "client_order_id": "<new UUID for every order>",
  "side": "bid",
  "count": "5",
  "price": "0.4200",
  "time_in_force": "good_till_canceled",
  "self_trade_prevention_type": "maker",
  "post_only": true,
  "cancel_order_on_pause": true,
  "order_group_id": "<from POST /portfolio/order_groups/create>"
}
  • One book, quoted from YES. side is bid (buy YES) or ask(sell YES); prices are dollar strings on the market's price grid and counts are strings.
  • A fresh client_order_id every time. If a create times out, look the order up before resending. Kalshi rejects a duplicate id while the first order is open, but not reliably after it has filled or been canceled.
  • The write's response is the only immediate truth. Order reads are updated after the matching engine processes a write, so an order you just created, amended or canceled can briefly read as not found or as its old state.
  • A 201 is not a fill. Read the fill and remaining counts on the response.

In Python, the official SDK wraps these calls; see our Kalshi Python SDK guide. The order lifecycle over REST is in placing and canceling Kalshi orders via the REST API, and keeping place, amend and cancel in the right order in enforcing order-of-operations correctness.

Knowing what you hold

A bot keeps its own view of open orders, fills, positions and cash, and Kalshi's is the one that counts. Subscribe to fill and user_orders to see changes as they happen. market_positions isn't ordered against fill, so the position for a trade can arrive after its fill; count the fill as exposure straight away and the position as settled only once it is confirmed.

Reconcile over REST (resting orders, fills, positions, balance) at start-up, after every reconnect, and on a timer. A WebSocket drop is a gap in which the bot may have been filled or canceled without seeing it; that is where cancel-versus-fill races come from. Don't poll balance to learn about fills: it has its own small rate limit and only changes on fills, settlements and transfers. How the portfolio endpoints fit together: portfolio and position endpoints for bot state tracking; what happens at settlement: the event resolution and settlement workflow.

Risk controls Kalshi gives you

Your own limits (maximum position per market, maximum open orders, a daily loss at which the bot stops) live in your code, and a bug can skip them. These live on the exchange, so they still work when your process is the thing that broke:

ControlHowWhat it does for a bot
Order groupsPOST /portfolio/order_groups/create with a contracts_limit, then order_group_id on each orderIf more than the limit fills within a rolling 15 seconds, Kalshi cancels every resting order in the group and rejects new ones until you reset it. A ceiling on how fast the bot can get filled, enforced outside your process.
Trigger an order groupThe group's trigger endpointCancels the group's orders and blocks new ones on demand, whether or not the limit was reached. A per-strategy stop button.
Cancel All OrdersDELETE /portfolio/events/orders (optionally ?subaccount=)Cancels all resting event-market orders across every exchange shard, and may also cancel orders placed in the minute after. The account-wide kill switch.
cancel_order_on_pauseField on Create Order (V2)The order is canceled if trading pauses for any reason, instead of resting through the pause and waking up on a market that has moved.
reduce_onlyField on Create Order (V2), with time_in_force immediate_or_cancelCaps the order at your current position, so an exit can't overshoot into a new position. Rejected with any other time in force.
post_onlyField on Create Order (V2)The order may only rest, never take. Keeps a quoting bot from crossing the spread by mistake.
SubaccountsAdvanced API tier and up (demo doesn't enforce the tier)Gives a bot its own balance and positions inside your account, so one strategy can't spend another's cash.
Key scopesscopes when the key is createdA read-only key for dashboards and research; read plus write::trade for the bot. Neither can move money.

An order group belongs to the subaccount and exchange shard it was made on, and only orders from that subaccount on that shard's markets can join it; an order naming a triggered group is rejected with exceeded_order_group_contracts_limit. Wire Cancel All Orders to something a person can press without logging in to the bot's host. Details are on Kalshi's order groups page and Cancel All Orders.

Rate limits

Kalshi meters requests in tokens. Your tier sets how fast two separate buckets refill: Read, for most GET calls, and Write, for order creates, amends, cancels and order groups. Most requests cost 10 tokens; a cancel costs 2.

TierRead tokens per secondWrite tokens per secondOrders per second at 10 tokens
Basic20010010
Advanced30030030

What that means for a bot:

  • Basic's Write bucket holds one second of budget, so there is no banked burst. Above Basic, Write buckets hold three seconds, so an idle bot can send a burst of up to three times its per-second budget when the market moves.
  • Batch endpoints don't save tokens: 25 orders in a batch cost the same as 25 single orders, and the whole batch must fit in the bucket at once or all of it is rejected.
  • A rate-limited request gets 429 with code too_many_requests and no Retry-After. There is no penalty; back off exponentially. Responses carry X-RateLimit-* headers, and GET /account/limits returns your current tier and budgets.
  • Keep a share of the Write budget free for cancels. A bot that spends all of it on new quotes can't pull them when it needs to.

Higher tiers and their numbers are on Kalshi's rate limits page, which changes; pacing strategies are in our piece on rate limits and throttling, and finding your bot's ceiling under load in throughput ceiling and order burst profiling.

Running it

  • Thursday maintenance. Every Thursday from 3:00 to 5:00 AM ET, Kalshi pauses trading. Orders can be canceled and decreased but not placed or amended (409, trading_is_paused); connections may drop. Resting orders stay on the book unless they were placed with cancel_order_on_pause. Schedule the bot around it.
  • Exchange pauses. Rarer, and outside that window a sign of an outage: nothing can be placed or canceled (exchange_is_paused). Check GET /exchange/status, and trust its flags only on a 200; a 5xx answer doesn't mean the exchange is paused.
  • Retry by error, not by habit. A 401 with authentication_errorwon't fix itself on a retry; the same code with a 500 or 503 will. A 5xx on an order write means its outcome is unknown: look the order up before sending another.
  • Log every request with its client_order_id. When the bot's state and Kalshi's disagree, the log is how you find out which one is wrong.

The full schedule and pause rules are on Kalshi's maintenance and pauses page.

Fees and P&L

Kalshi charges trading fees that differ by series and can be overridden for single events, so an edge that looks real before fees can disappear after them. Don't hard-code a fee: read the fee schedule on Kalshi's site for the markets you trade, and use the series and event fee-change endpoints to notice when it changes. How fees are rounded is on Kalshi's fee rounding page. Compute P&L from your fills and settlements, and check it against your balance.

Testing before real money

Demo is the place to prove signing, field formats and the order calls end to end, but Kalshi warns that prices and behaviour there may not reflect real markets, and it won't produce the timeouts, 429s, partial fills and dropped connections the bot's recovery paths need. Those come from a simulator you control. In order:

  1. Unit-test the strategy and your own limits against recorded books; constructing a backtest from raw API event logs.
  2. Run the whole bot against a stateful simulator, through every order state: stateful Kalshi API simulation for local bot development and testing against full order-lifecycle state transitions.
  3. Run those tests on every commit: CI pipeline testing for Kalshi bot order logic; and check the tests themselves catch bugs with mutation testing.
  4. Run it on demo against the real API surface; see what demo actually exposes to a staging bot.
  5. Go live small, with an order group limit, a subaccount holding only what you are prepared to lose, and the evidence written down: the correctness evidence to compile before the first live order.

Judging a ready-made bot

Open-source Kalshi bots, and bots written with an AI assistant, save the plumbing but inherit its bugs. Before running one with a production key, check that it:

  • places orders through the V2 endpoints, not the removed /portfolio/orders writes;
  • defaults to the demo host, and needs a deliberate setting to reach production;
  • reads keys from the environment or a file, and has none committed;
  • parses prices and counts as decimals, not floats;
  • sends a new client_order_id per order and looks an order up before resending;
  • tracks seq on the order book stream and resyncs on a gap;
  • reconciles orders and positions over REST after a reconnect;
  • handles 429s with backoff and keeps Write budget for cancels;
  • has a kill switch, and uses order groups or its own hard limits.

Anything it doesn't do is yours to add before it trades. Whether your use is allowed under Kalshi's terms for your account is a question for Kalshi's own documents, not for the bot's README.