Build a Kalshi AI Trading Bot (Demo First, With Hard Limits)

Kalshi Paper / demo first

Verified working on live data in mock mode, Nov 10, 2026. Fresh build from the published prompt, then live demo market data with the mock broker: no demo keys, no signed calls and no orders sent, so the daily-loss limit, order-group and shard-funding behavior on the real exchange were not exercised. Outages were simulated with a local fault-injecting relay.

Starter code on GitHub: github.com/lazyclaw137-ship-it/kalshi-ai-trading-bot. The code from the verified run, MIT licensed, with no keys included.

Short answer: To build a Kalshi AI trading bot safely, have your AI coding tool write it against the Kalshi demo environment first, place orders with Create Order V2 (POST /portfolio/events/orders), cap exposure in code, and add order groups that auto-cancel resting orders when fills exceed a limit. An optional LLM research step only ever sees public market text, never your keys or balances.

What are the key facts?

  • Create orders with POST /portfolio/events/orders (Create Order V2). Kalshi says the legacy /portfolio/orders endpoint will be deprecated no earlier than May 6, 2026.
  • V2 order body: ticker, side (bid/ask), count (string), price (fixed-point dollars, e.g. "0.5600"), time_in_force (good_till_canceled / immediate_or_cancel / fill_or_kill), self_trade_prevention_type, plus optional client_order_id, post_only, reduce_only, cancel_order_on_pause.
  • Order groups (POST /portfolio/order_groups/create) auto-cancel every resting order in the group if fills exceed a contracts limit in a rolling 15-second window.
  • Cancel everything: DELETE /portfolio/events/orders. Cancel one: DELETE /portfolio/events/orders/{order_id}.
  • Demo base URL: https://external-api.demo.kalshi.co/trade-api/v2. Separate keys from production.
  • Kalshi runs several exchange shards (exchange_index on each market). Order groups don't work across shards, so make one per shard, and API orders aren't funded across shards automatically.
DifficultyIntermediate
Time3–4 hours
Cost$0 API · optional LLM API usage
Works withClaude Code, Cursor, ChatGPT / Codex, Grok

What will you build?

A Kalshi bot that runs on demo: it watches a few markets, applies your rule (optionally informed by an LLM research step), checks hard limits, and places small limit orders with a server-side safety net.

Who is it for?

People who've done the Kalshi API starter and want a real bot loop, on their own account, for their own trading.

Not for: Running a bot for friends, selling signals, or copy trading. Kalshi's Developer Agreement prohibits facilitating other members' trading.

What happened when we rebuilt it from this prompt

We have now built this bot three times from its own prompt. Each time there were no demo keys, so a mock broker took the orders while prices came from live markets on Kalshi's demo exchange. Oct 24 found three bugs and Oct 27 found five. On Nov 10 we found one design problem Kalshi's own changes had created, plus four ways the bot fell over. The prompt above includes every fix.

Third pass, Nov 10

We wrote the bot by hand, fresh, from the Oct 27 prompt and ran it against the demo exchange from 9:03 to 9:11 a.m. ET: 38 loops over five tickers, one of them a deliberate typo. The Oct 27 fixes held:

  • One order per ticker. 3 mock orders in 38 loops. After a restart it said "already have a resting order here", and after a simulated fill it said "already ordered today".
  • Closed markets. A 10-minute demo market closed at 9:10 ET. The mock dropped our resting order on it at 9:10:09 and logged it, and the bot then skipped it as closed and later as determined.
  • The other checks. The typo ticker 404'd once and was never asked for again. KILL, BOT_KILL=1, the exposure cap, the per-minute cap after a restart and the second-copy lock all blocked as they should. A bad limits.json or state.json stopped the bot before it ordered anything.

What broke:

One order group for every market. Kalshi now splits trading across several matching engines, called exchange shards, and its docs say plainly: "Order groups do not function across exchange instances." On demo today the tennis market we watched was on shard 3 and the college-basketball market was on shard 0. The prompt made a single order group (which defaults to shard 0) and put every order in it, so the safety net that cancels everything on a fill spike wouldn't have covered the tennis order. We had no keys, so we couldn't see how the real exchange reacts. We found it in the docs, not in a rejection. The fixed prompt reads exchange_index from each market and creates one group per shard. Kalshi also says programmatic orders aren't funded across shards automatically. On an unfunded shard you get insufficient_shard_balance, and the bot now logs that code and leaves the ticker alone for the day.

A dropped connection or a maintenance page killed the bot. Through a local fault proxy, a dropped connection crashed it with a ConnectionError traceback in 0.1 s. An HTML page returned with status 200 crashed it with a JSONDecodeError. A bot that dies on the first network hiccup isn't much of a bot. Both are now one-line errors for that ticker, and dropped connections are retried like timeouts. 429 with Retry-After: 5, 503 and a hung server already behaved: 40, 47 and 63 seconds for a loop that stopped after two failing tickers.

Logs sent to a file stayed empty. With python bot.py > run.txt, the file was still empty 4 seconds in, when the bot had already written 9 lines to its decision log. Later it ran about a minute behind, because Python buffers output to a file. Prints now flush.

Ctrl-C printed a traceback. It now prints "Stopped (Ctrl-C)." | head was already fine.

Kalshi's Nov 5 changes didn't break anything. The bot doesn't branch on market_closed (now market_inactive). It only trades markets whose status is active, which held through initialized, closed and determined. The KXRFQ markets left out of unscoped lists don't matter to a bot that watches named tickers.

We rebuilt from the fixed prompt (the follow-up below applied to the first build) and ran it again from 9:08 to 9:14 a.m. ET. Pytest: 14 tests on the first build, 20 on the second. Sample output from the second run (fields trimmed, times UTC):

{"ts": "2026-11-10T14:08:53+00:00", "event": "created order group", "exchange_index": 3, "order_group_id": "mock-group-x3-2d0800"}
{"ts": "2026-11-10T14:08:53+00:00", "ticker": "KXATPMATCH-26NOV11FRINOR-NOR", "seen": {"yes_bid": 0.23, "yes_ask": 0.27, "status": "active"}, "rule": "fair 0.32 - ask 0.27 - fee 0.0138 = 0.0362 > margin 0.02", "risk": "ok", "event": "order sent (mock)"}
{"ts": "2026-11-10T14:08:54+00:00", "event": "created order group", "exchange_index": 0, "order_group_id": "mock-group-x0-7fb74d"}
{"ts": "2026-11-10T14:08:55+00:00", "ticker": "KXATPMATCH-26NOV11FRINOR-TYPO", "event": "404: skipping for rest of run"}
{"ts": "2026-11-10T14:10:10+00:00", "ticker": "KXQUICKSETTLE-10NOV26H0910-3", "event": "market closed: 1 resting order(s) dropped (mock)"}
{"ts": "2026-11-10T14:11:39+00:00", "ticker": "KXQUICKSETTLE-10NOV26H0910-3", "seen": {"status": "determined"}, "event": "no order", "rule": "status determined: skip"}
{"ts": "2026-11-10T14:09:52+00:00", "ticker": "KXATPMATCH-26NOV11FRINOR-NOR", "event": "data error", "error": "HTTP 200, not JSON: 'Maintenance'"}

The last line is from the fault-proxy drill. The fair prices are placeholders, so these orders say nothing about edge.

Built this before Nov 10? Paste this follow-up into the same project. If you built it before Oct 27, paste the older ones below first, oldest first.

Update my Kalshi bot:
1. Kalshi runs several exchange shards and order groups don't work across
   them. Read exchange_index from GET /markets/{ticker}. Create one order
   group per exchange_index (pass exchange_index when creating it) the
   first time I order on that shard, save {exchange_index: group id} in
   state.json and reuse them after a restart. An old single saved group id
   becomes shard 0's.
2. If an order is rejected, log Kalshi's error.code as-is (e.g.
   market_inactive, or insufficient_shard_balance if that shard isn't
   funded) and skip that ticker for the rest of the day. Never resend it.
3. HTTP client: retry dropped connections like timeouts (GETs only). A
   response that isn't JSON, even HTTP 200, is a one-line error for that
   ticker, never a crash. Strip HTML from error text.
4. Print with flush=True. Ctrl-C prints "Stopped (Ctrl-C)." and exits 130;
   a closed pipe exits quietly. A missing or unreadable limits.json or
   state.json: one-line message, don't start.
Add tests for each, run them, and show me the diff before changing anything else.

Second pass, Oct 27

The loop, the Create Order V2 body, the order group and the kill switch worked. These didn't:

A filled order was bought again. The Oct 24 fix treated any ticker with a resting order as already ordered. A filled order isn't resting any more, so the next loop saw an empty ticker and bid again. We removed two orders from the mock's saved state to simulate fills; the very next loop sent new orders on both tickers. The prompt now saves the tickers ordered today in state.json and also skips any ticker where you hold a position.

The orders-per-minute cap forgot itself on restart. The count lived in memory. In our drill the cap blocked an order at 13:11:54 UTC; we restarted the bot and the same order went out nine seconds later. Order times are now saved in state.json. The 60-second wait after a cancel-all is saved too, so clearing KILL while the bot is stopped still waits.

A typo'd ticker failed forever. One deliberately wrong ticker (404) logged 126 identical data errors and was retried on every loop. Now a 404 is logged once and the ticker is skipped for the rest of the run.

A closed market's order stayed in exposure. One demo market finalized at 13:20 UTC and the mock still listed our order on it as resting, so it counted against the $5 cap forever. The real exchange cancels resting orders when a market closes; the mock now does the same and logs it. In the longer live run we watched markets go initialized → active → closed → determined, and the new code logged "market closed: 1 resting order(s) now gone".

Retries ignored the server and the clock. We put a fault proxy between the bot and Kalshi's demo host. A 429 carrying Retry-After: 5 was retried after a fixed 0.5 to 8 seconds, ignoring the header. With the server returning 429 or 503, one loop over six tickers took 48 seconds; with a server that answered slowly it took 60. The client now retries only GETs (never an order), honours Retry-After up to 30 seconds, and ends the loop after two tickers in a row fail. Results from the final code, one loop each: 429 with Retry-After: 5 40 seconds, 503 16 seconds, dropped connection 16 seconds. The slow-server drill also caught a bug in our own fix: the 30-second limit covered one attempt, so one ticker could spend 58 seconds on retries. A 25-second budget per call brought it to 32 seconds per ticker, and a loop that gives up after two tickers still takes about 63 seconds. That's no faster than before for a slow server. It just stops hammering it.

The prompt also now subtracts Kalshi's taker fee, 0.07 × price × (1 − price) per contract, before comparing your edge to the margin. The bot bids at the implied ask, so it crosses the book and pays that fee, up to 1.75¢ per contract. This comes from Kalshi's fee schedule, not from the run.

A few other changes are covered by unit tests only, not by the live run: a file lock so a second copy of the bot refuses to start, a stop when the order group is rejected, limits.json that fails closed if a value is missing or not positive, and paginated resting_orders. Pytest: 33 passed.

Clean-folder rebuild, Oct 27. A second build in an empty folder from the published prompts only passed 27 tests. In 44 live loops over about 11 minutes, a simulated fill didn't trigger a re-buy (41 loops skipped it), a restart sent 0 orders, a second copy refused to start, and the closed market's order was dropped. The rebuild also showed that a 30-second Retry-After can't fit a 25-second budget. The prompt now says a wait that would go past the budget ends the retries.

First pass, Oct 24

On Oct 24, 2026 we pasted the original prompt into a clean folder, built the bot exactly as written, and ran it against three live markets. Three things didn't work, and the prompt was fixed for all three.

Restarting the bot stacked a second order. The old prompt said "at most one order per ticker per run". Our build kept that in memory, so stopping and restarting it sent a second resting bid on the same market and created a second order group. The prompt now treats any ticker with a resting order (GET /portfolio/orders?status=resting) as already ordered, and saves the order group id so a restart reuses it.

Daily loss came from the wrong place. The old prompt computed it from GET /portfolio/positions as realized P&L minus fees. That endpoint returns unsettled positions by default, and its P&L is per market, not per day. Fed to the risk module as written:

old unsettled loss counts as today: 2.15
after settlement it vanishes     : 0.0

A loss from last week would block today's trading, and a losing market stops counting the moment it settles. Daily loss now comes from GET /portfolio/balance: equity (balance + portfolio value) at the first loop of the UTC day, minus equity now, saved in state.json.

Resting orders didn't count as exposure. Exposure only counted positions, so bids that hadn't filled yet were invisible to the $5 cap, and the mock broker returned no positions at all, so the cap never ran. Exposure now adds the cost of resting orders, and the mock remembers its own orders so the cap and the one-order rule actually get exercised without an account.

What the Oct 24 version printed (fields trimmed, times UTC):

{"ts": "2026-10-24T13:54:32+00:00", "ticker": "KXATPCHALLENGERMATCH-26OCT24BRODEB-DEB", "seen": {"yes_bid": 0.18, "yes_ask": 0.19, "status": "active"}, "rule": "fair 0.25 - ask 0.19 = 0.06 > margin 0.03: bid 1 @ 0.1900", "risk": "ok", "event": "order sent (mock)"}
{"ts": "2026-10-24T13:54:43+00:00", "ticker": "KXATPCHALLENGERMATCH-26OCT24BRODEB-DEB", "event": "no order", "rule": "already have a resting order here"}
{"ts": "2026-10-24T13:55:04+00:00", "event": "kill switch on: cancel_all once"}
{"ts": "2026-10-24T13:55:24+00:00", "event": "kill switch cleared: waiting 60s before ordering"}
{"ts": "2026-10-24T13:55:25+00:00", "ticker": "KXATPCHALLENGERMATCH-26OCT24BRODEB-DEB", "event": "no order", "why": "within 60s of cancel-all"}
{"ts": "2026-10-24T13:56:31+00:00", "ticker": "KXATPCHALLENGERMATCH-26OCT24BRODEB-DEB", "risk": "ok", "event": "order sent (mock)"}
--- restarted ---
{"ts": "2026-10-24T13:56:44+00:00", "event": "reusing order group", "order_group_id": "mock-group-7a3c05dc"}
{"ts": "2026-10-24T13:56:45+00:00", "ticker": "KXATPCHALLENGERMATCH-26OCT24BRODEB-DEB", "event": "no order", "rule": "already have a resting order here"}

Why wait 60 seconds after a cancel-all? Kalshi's docs for DELETE /portfolio/events/orders say orders placed in the minute after the request may also be cancelled. Without the wait, the first order after you clear KILL can silently disappear.

Things we noticed along the way:

  • Most demo markets can't be traded. Of the 8,000 open, non-combo demo markets we listed, only 6 had both a YES bid and a YES ask. One of our three went one-sided partway through the run, and the bot correctly logged "no NO bids, so no YES ask: don't trade".
  • Status reads active, not open. You filter with ?status=open, but each market comes back as active. A paused market reads inactive, and when it reopens all resting orders are cancelled. The placeholder now skips anything that isn't active.
  • The production host may refuse you. From our server, external-api.kalshi.com returned 403 while api.elections.kalshi.com answered, which is why the base URL is overridable.
  • Markets change state under you. In the Oct 27 run the bot's own status check skipped markets that were initialized, closed or determined, and logged a one-sided book as "no NO bids, so no YES ask: don't trade" when it had no ask.
  • These runs prove the plumbing, not a strategy. Demo prices barely moved, and the fair prices in the config are placeholders.

Built this before Oct 27? Paste this follow-up into the same project. If you built it before Oct 24, paste the next one first.

Update my Kalshi bot:
1. A filled order is no longer resting, so save the tickers I ordered today
   in state.json and skip them. Also skip any ticker where GET
   /portfolio/positions shows a position.
2. Save order timestamps in state.json so max_orders_per_minute survives a
   restart. Save the 60 s post-cancel-all wait there too, so clearing KILL
   while the bot is stopped still waits.
3. If a ticker returns 404, log it once and skip it for the rest of the run.
4. Mock broker: when a market's status is no longer active, drop its resting
   orders from logs/mock_state.json and log it, so exposure is released.
5. Subtract Kalshi's taker fee, 0.07 * ask * (1 - ask), from my edge before
   comparing it to the margin.
6. HTTP client: retry GETs only, never POSTs. Honor Retry-After (cap 30 s),
   timeout (5 s connect, 10 s read), a 25 s total retry budget per call (a wait that
   would pass it ends the retries), and
   end the loop early if two tickers in a row fail on the network. Page
   through GET /portfolio/orders?status=resting with the cursor.
7. A second copy of the bot must refuse to start (file lock).
Add tests for each, run them, and show me the diff before changing anything else.

Built this before Oct 24? Paste this one first:

Update my Kalshi bot:
1. Daily loss: use GET /portfolio/balance. Equity = balance + portfolio_value
   (cents). Save equity at the first loop of each UTC day in state.json;
   daily loss = max(0, saved - now). Stop using realized_pnl from positions.
2. Exposure = positions' market_exposure_dollars + cost of my resting orders
   (GET /portfolio/orders?status=resting). If any account call fails, place
   nothing this loop.
3. One order per ticker must survive a restart: skip tickers with a resting
   order. Save the order group id in state.json and reuse it.
4. Skip markets whose status isn't "active".
5. After the kill switch is cleared, wait 60 s before ordering (cancel-all
   can also cancel orders placed in the following minute).
6. The mock broker keeps its orders as resting in logs/mock_state.json and
   returns a fixed $100 balance labeled mock.
Add tests for each, run them, and show me the diff before changing anything else.

What prompt do you paste into your AI coding tool?

Works in Claude Code, Cursor, Codex/ChatGPT, Grok or any agent that can write files. Paste it into an empty folder. Read what it builds before you run anything.

Build a Kalshi trading bot in Python that runs on the Kalshi DEMO environment
by default. Use only endpoints/fields from https://docs.kalshi.com. Follow the
rules in CLAUDE.md/AGENTS.md. If unsure about an endpoint, ask me.

Reuse (or create) a signed client: headers KALSHI-ACCESS-KEY,
KALSHI-ACCESS-TIMESTAMP (ms), KALSHI-ACCESS-SIGNATURE over
timestamp+METHOD+path (path from /trade-api/v2, no query string; RSA-PSS
SHA-256 for RSA keys, direct signature for Ed25519). Key file path and key id
come from env vars; the key file lives outside the repo.

Modules:
- config.toml: env ("demo"|"prod", default demo), tickers to watch (from
  the SAME env: demo and prod list different markets, so a prod ticker
  returns 404 on demo; never read quotes from one env and order on another),
  poll seconds, strategy params, and the base URL per env (demo:
  https://external-api.demo.kalshi.co/trade-api/v2; prod: the URL in the
  docs, overridable by an env var because some networks get a 403 on
  one production host and not the other).
- limits.json: max_contracts_per_order, max_open_exposure_usd,
  max_daily_loss_usd, max_orders_per_minute, order_group_contracts_limit.
- data.py: GET /markets/{ticker}, GET /markets/{ticker}/orderbook (public).
  Use *_dollars price fields. Remember the book has bids only: the response
  is {"orderbook_fp": {"yes_dollars", "no_dollars"}}, each sorted by price
  ascending, so the best bid is the LAST entry. Implied YES ask = 1.00 minus
  the best NO bid; if there are no NO bids, there is no ask, so don't trade.
  Also read each market's exchange_index (Kalshi runs several matching
  engines; e.g. on Nov 10 demo tennis was 3, college basketball 0).
  A ticker that returns 404: log it once and skip it for the rest of the run.
  Don't fall back to the market's yes_ask_dollars snapshot: in our run it
  showed an ask while the live book had no NO bids.
- research.py (OPTIONAL, off by default): sends ONLY public market text
  (title, rules_primary, current prices) to an LLM and asks for a short
  written summary and a probability estimate with reasoning. Never send keys,
  balances or positions to the LLM. Log every LLM output. If no LLM API key
  is set, don't call the network: use a deterministic stub that is clearly
  labeled "stub, not a forecast", or skip research. (Python's hash() of a
  string changes between runs, so it can't make a deterministic stub.)
- strategy.py: my rule. Start with a placeholder: if the market's status is
  "active", propose a 1-contract limit bid at the implied YES ask only if my
  own configured fair price minus that ask minus Kalshi's taker fee
  (0.07 * ask * (1 - ask) per contract; you bid at the ask, so you cross the
  book) is above a configured margin.
  The research output is advisory input only.
- risk.py: kill switch (KILL file or BOT_KILL=1) + every limit in
  limits.json, checked before every order. Unit tests.
  Daily loss: equity = balance + portfolio_value from GET /portfolio/balance
  (both in cents). Save the equity from the first loop of each UTC day in
  state.json; daily loss = max(0, that - equity now). Don't build it from
  /portfolio/positions: realized_pnl_dollars there is per market, not per
  day, and a market drops out of the default (unsettled) list once it
  settles. Open exposure = sum of market_exposure_dollars from
  GET /portfolio/positions PLUS the cost of my resting orders from
  GET /portfolio/orders?status=resting (page through it with the cursor).
  If any of these calls fails, place nothing this loop. Save order
  timestamps in state.json so max_orders_per_minute survives a restart.
- broker.py:
    create_order_group(contracts_limit) -> POST /portfolio/order_groups/create
    place_order(...) -> POST /portfolio/events/orders with ticker, side
      ("bid" = buy YES, "ask" = sell YES), count (string, e.g. "1.00"),
      price (fixed-point dollars string, e.g. "0.3500"), time_in_force
      (fill_or_kill | good_till_canceled | immediate_or_cancel; GTT is not a
      valid value), self_trade_prevention_type (taker_at_cross | maker), client_order_id (uuid4), and the order
      group id (field: order_group_id). Use post_only where sensible; reduce_only for exits
      (Kalshi rejects reduce_only=true unless time_in_force is
      immediate_or_cancel); cancel_order_on_pause=true.
    cancel_all() -> DELETE /portfolio/events/orders
    positions() -> GET /portfolio/positions
    balance() -> GET /portfolio/balance
    resting_orders() -> GET /portfolio/orders?status=resting (all pages)
- bot.py: loop = kill switch -> data -> (research) -> strategy -> risk ->
  broker -> log to logs/decisions.jsonl. At most one order per ticker,
  and that must survive a restart: at startup and every loop, treat any
  ticker with a resting order as already ordered. A filled order is no
  longer resting, so also save the tickers ordered today in state.json and
  skip any ticker where GET /portfolio/positions shows a position. Order
  groups don't work across exchange shards, so create one group per
  exchange_index (pass exchange_index when creating it) the first time you
  order on that shard; save {exchange_index: group id} in state.json and
  reuse them after a restart. If an order is rejected, log Kalshi's
  error.code as-is (e.g. market_inactive, insufficient_shard_balance when
  that shard isn't funded) and skip that ticker for the rest of the day. When the
  kill switch trips mid-run, call cancel_all() once, then stop ordering.
  After the switch is cleared, wait 60 seconds before ordering again
  (Kalshi says cancel-all can also cancel orders placed in the following
  minute); save the wait in state.json so a restart can't skip it. A
  second copy of the bot must refuse to start (file lock). A missing or
  unreadable limits.json or state.json: one-line message, don't start. If the order
  group is rejected, stop. "prod" requires --live AND typing
  "I accept the risk". Print the environment loudly at startup. Print with
  flush=True so a log redirected to a file updates live. Ctrl-C prints
  "Stopped (Ctrl-C)." and exits 130; a closed pipe (| head) exits quietly.
- cancel_all.py: one-shot cancel-all.
- HTTP client: retry GETs only (429/5xx/timeouts/dropped connections),
  never POSTs; bounded
  exponential backoff, honor Retry-After (cap 30 s), timeout 5 s connect and
  10 s read, a 25 s total retry budget per call (a wait that
  would pass it ends the retries), and end the loop early if
  two tickers in a row fail on the network. A response that isn't JSON (even
  HTTP 200, e.g. a maintenance page) is a one-line error for that ticker,
  never a crash; strip HTML from error text. Never retry a rejected order in a
  loop. Use client_order_id so retries can't double-submit.
- If demo keys are not set (or BROKER_MOCK=1), use a mock broker that logs
  the exact request it would send and sends nothing, so the whole loop runs
  without an account. The mock remembers its own orders as resting (in
  logs/mock_state.json) so the exposure and one-order-per-ticker rules are
  exercised. When a market's status is no longer active, drop its resting
  orders from the mock and log it (the real exchange cancels them), so the
  exposure is released. Its balance is a fixed $100 labeled "mock", so daily loss can
  only really be tested with demo keys. Print that at startup.
- pytest tests for risk, signing, the live gate, daily loss from the saved
  start-of-day equity, exposure that includes resting orders, a restart
  that must not place a second order on a ticker with a resting one, a
  filled (no longer resting) ticker that must not be bought again, the
  orders-per-minute cap across a restart, a 404 ticker logged once,
  retry behavior (GET only, Retry-After, budget, dropped connection),
  HTML 200 as a one-line error, one order group per exchange_index, and a
  rejected order not sent again.

Show the plan, build, then give me the commands to run on demo.

How do you build it, step by step?

  1. Do the Kalshi API Starter first so you have demo keys and a working signed client.
  2. Add the Safety Pack (rules file, .gitignore, deny rules, gitleaks hook).
  3. Paste the prompt. Check broker.py against the Create Order V2 page: path /portfolio/events/orders, count as a string, price as a fixed-point dollar string.
  4. Pick 1–3 demo tickers with GET https://external-api.demo.kalshi.co/trade-api/v2/markets?status=open&mve_filter=exclude, and put them in config.toml. Pick ones with both a yes_bid_dollars above 0 and a yes_ask_dollars below 1; most demo markets are one-sided. Take them from demo: demo and production list different markets, so a ticker copied from kalshi.com usually returns 404 on demo. Each market's exchange_index tells you its shard. If you use demo keys, check that shard has funds: Kalshi says API orders aren't moved between shards for you (the Exchange Indexes page in your account, or the Intra Account Transfer endpoint).
  5. Set tiny limits (1 contract per order, $5 exposure, $2 daily loss) and an order-group limit of a few contracts.
  6. Run on demo: python bot.py. No demo keys yet? Run BROKER_MOCK=1 python bot.py first; the mock broker logs each order it would send and sends nothing. Watch logs/decisions.jsonl and your demo account's open orders. Demo books are often one-sided (many have no NO bids, so there's no YES ask), so the placeholder strategy may log "no order" for a while. That's the code working, not a bug. In mock mode the balance is a fixed $100, so the daily-loss limit only really runs with demo keys.
  7. Drill the safety net. touch KILL: the bot cancels everything once and stops ordering. Remove KILL and it waits 60 seconds before ordering again. python cancel_all.py does the same cancel by hand. Confirm in the demo UI that the orders are gone. Then restart the bot and check it doesn't place a second order on a market where one is still resting. To simulate a fill in mock mode, delete that order from logs/mock_state.json: the bot must not buy the ticker again.
  8. Turn on research only if you want it. Set research.enabled = true. Read what the LLM writes. LLM probability estimates are often confident and badly calibrated, so measure them against outcomes over time before trusting them.
  9. Live is a separate decision. If you ever switch to prod, create a new production key, keep the same tiny limits, and stay at the keyboard for the first sessions.

How do you test it in paper or demo mode first?

Kalshi gives you a real demo exchange with mock funds, which is better than a simulated ledger: your orders hit a real matching engine, get real rejections and exercise your real code paths.

  • Demo base URL: https://external-api.demo.kalshi.co/trade-api/v2, with WebSocket at wss://external-api-ws.demo.kalshi.co/trade-api/ws/v2.
  • Demo keys can't touch production, so a bug can't drain a real account.
  • Kalshi notes demo prices and behavior may differ from real markets. Use demo to prove your code works, not that your strategy works.

Track a simple scorecard in demo: orders placed, rejected (and why), filled, kill-switch drills passed, and PnL after fees.

What safety checks does it need before real money?

Tick every box before the bot touches real money. The full rules file, .gitignore and pre-commit hook are in the Safety Pack.

Which official docs did we check?

Endpoints and rules were checked against these pages on Nov 10, 2026. APIs change, so if something here disagrees with the official docs, trust the docs and tell us.

Frequently asked questions

Are trading bots allowed on Kalshi?

Kalshi offers a public trading API, and its Developer Agreement allows using it to facilitate your own trading. It prohibits facilitating trading for other members, sharing API data with third parties without written permission, and manipulative behavior like spoofing or wash trading.

Which Kalshi endpoint places orders now?

Use Create Order V2 at POST /portfolio/events/orders. Kalshi's docs say the legacy /portfolio/orders endpoint will be deprecated no earlier than May 6, 2026, and clients should migrate.

How do I stop a Kalshi bot fast?

Have three layers: a local kill switch (a KILL file your bot checks before every order), a cancel-all command using DELETE /portfolio/events/orders, and Kalshi order groups, which auto-cancel resting orders when fills exceed a limit in a rolling 15-second window.

Can an AI predict Kalshi markets?

An LLM can summarize information and produce a probability estimate, but there's no guarantee it beats the market price, and its estimates are often overconfident. Treat it as a research assistant, log every output, and measure it in demo before relying on it. BotCookery doesn't provide predictions or picks.

Why was my order rejected with insufficient_shard_balance or market_inactive?

insufficient_shard_balance means the market sits on an exchange shard your account hasn't funded. Kalshi doesn't move money between shards for API orders, so transfer funds to that shard first. market_inactive replaced market_closed on Nov 5, 2026, and also covers halted markets. Either way the bot should log the code, skip that ticker, and not resend.

Is there a Kalshi trading bot on GitHub I can use?

There are several. If you use one, audit it first and run it on demo with demo keys. See how to audit a bot repo.

More from the kitchen: Recipes by platform · Kalshi & Polymarket fee calculator · How we verify recipes · Safety Pack