Kalshi API Starter: Markets, Order Books & Signed Requests in Python (2026)

Kalshi Read-only

Verified working on live data in read-only mode, Nov 4, 2026. Public market data on demo and production. Signing is tested offline against Kalshi's documented algorithm; balance and positions were not run with real demo keys.

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

Short answer: The Kalshi Trade API v2 lives at https://external-api.kalshi.com/trade-api/v2 (https://api.elections.kalshi.com/trade-api/v2 is also supported), with a demo environment at https://external-api.demo.kalshi.co/trade-api/v2. Market data such as GET /markets, order books and trades needs no key. Account calls need three headers and a signature over timestamp + METHOD + path (no query string), using RSA-PSS or Ed25519. This recipe builds a read-only client that handles both, plus the traps we hit running it live.

What are the key facts?

  • Production REST base: https://external-api.kalshi.com/trade-api/v2. https://api.elections.kalshi.com/trade-api/v2 is documented as also supported and covers all markets. From our server the first answered 403 and the second worked, so the client falls back once.
  • Demo REST base: https://external-api.demo.kalshi.co/trade-api/v2 (https://demo-api.kalshi.co/trade-api/v2 also supported). Demo keys only work on demo and production keys only on production.
  • Public data needs no key: GET /markets, GET /markets/{ticker}, GET /markets/{ticker}/orderbook, GET /markets/trades, GET /events.
  • Auth headers: KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP (ms), KALSHI-ACCESS-SIGNATURE. Sign timestamp + METHOD + path with the path from /trade-api/v2/... and no query string. RSA keys use RSA-PSS with SHA-256; Ed25519 keys sign directly.
  • Order books list bids only for YES and NO, sorted ascending (best bid last). YES ask = 1.00 − best NO bid. An empty side can show as 0.0000 or 1.0000, so check the *_size_fp field before trusting a price.
  • Rate limits are token buckets on authenticated requests: most cost 10 tokens, and Basic gets 200 read / 100 write tokens per second. GET /portfolio/balance has its own bucket (1 per second on Basic). A 429 currently carries no Retry-After, so back off exponentially, and honor the header if it ever appears.
  • The status filter and the status field use different words: status=open returns markets whose status reads active, paused returns inactive, closed returns closed or determined, and settled returns finalized. Check status == "active" before treating a book as live.
  • From Nov 5, 2026 the order error market_closed is renamed market_inactive (halted markets return it too), and on-demand RFQ markets (KXRFQ… series) drop out of unscoped GET /markets and GET /markets/trades listings. Print Kalshi's error code as-is; don't match on the string.
DifficultyBeginner
Time45–60 min
Cost$0
Works withClaude Code, Cursor, ChatGPT / Codex, Grok

What will you build?

A read-only Python CLI that finds the active Kalshi markets, prints order books with the implied ask and spread, shows recent trades, watches a market's price and traded volume cycle by cycle, and makes correctly signed balance and position requests. It's a clean data layer for a bot, with no order placement.

Who is it for?

Developers and vibe coders who searched "kalshi api" and keep hitting 401s on signing, or who want a clean base before building a bot.

What happened when we rebuilt it from this prompt

Wednesday, Nov 4, 2026, 9:09–9:21 a.m. ET. We built the Oct 25 prompt again in an empty folder and ran every public command against live demo and production data, then pointed it at a local fault proxy. The Oct 25 fixes held: production still answered 403 on external-api.kalshi.com and the client switched hosts once; a scan of 3,000 production markets found 2,031 two-sided ones (demo: 53); the typo ticker KXNOPE-NOTREAL got the one-line "not found" on both environments; balance without keys exited 1 and printed no number; 12 offline tests passed. The fault drills found five things the prompt never asked for:

  • A hung host ended in a traceback. Timeouts weren't caught at all: a ReadTimeout traceback after 15 s, and the same for a refused connection. Retrying them like a 5xx (five times at 15 s) cost 105.7 s per call when we tried it. Now: timeout=(5, 10), one retry, then one line. Measured after the fix: 20.7 s.
  • An HTML page with a 200 crashed it with a JSONDecodeError traceback, and a 503 printed the raw <html><body> tags. Both are one readable line now.
  • Retry-After was ignored. A 429 carrying Retry-After: 3 was retried after 0.5 s. Kalshi's 429s don't send the header today, but honoring it is free. After the fix the retry waited 3 s.
  • markets | head ended in a BrokenPipeError traceback. Now it exits 0 quietly.
  • watch would poll a dead market forever. The market status field doesn't use the filter's words: we asked for 200 markets per filter, and status=open came back as active (200 of 200), paused as inactive, closed as determined (192) or closed (8), settled as finalized. watch now stops with the status if it isn't active. On a closed market: market status is 'determined', not 'active'; stopping.

We also checked the changelog for Nov 5. Nothing in this read-only client breaks, but two items matter if you build on it: the order error market_closed becomes market_inactive (and halted markets return it too), so the prompt now prints Kalshi's error code as-is instead of matching on it; and on-demand RFQ markets (KXRFQ…) drop out of unscoped GET /markets and trades listings, so ask for their series by name if you want them. no_sub_title is deprecated in favor of yes_sub_title, which this client already uses. The new update_interval_ms and clock fields are WebSocket-only and don't touch this REST client.

The rebuilt client (Oct 25 build plus the follow-up below, 21 offline tests) on the S&P 500 10 a.m. market before the open:

$ KALSHI_ENV=prod python cli.py book KXINXU-26NOV04H1000-T7679.9999
[PROD] real exchange data
YES bids (best last): 7¢ x 285, 8¢ x 20, 16¢ x 7, 17¢ x 40,000, 18¢ x 175
NO bids (best last): 26¢ x 1, 27¢ x 317, 75¢ x 86, 76¢ x 8, 78¢ x 40,177
best YES bid $0.18 (18%) | implied YES ask $0.22 (22%) | spread 4¢ | mid $0.200 (20%)
implied NO ask $0.82 (82%)
contracts within 5¢ of best: YES 40,182  NO 40,271
Kalshi lists YES bids and NO bids only, so the YES ask is 1.00 minus the best NO bid.

And watch on one of the busiest production markets that morning, a 15-minute Bitcoin contract, from 9:19 to 9:20 a.m. ET. Eight of nine 10-second cycles changed, the mid moved between 55.5¢ and 71.5¢, and 132,704.84 contracts traded:

09:19:11  #1   bid   63¢  ask   64¢  mid  63.5¢  last   65¢  traded +0
09:19:21  #2   bid   68¢* ask   69¢* mid  68.5¢* last   63¢* traded +24,538.81
09:19:31  #3   bid   63¢* ask   64¢* mid  63.5¢* last   68¢* traded +58,660.10
09:19:41  #4   bid   61¢* ask   62¢* mid  61.5¢* last   62¢* traded +76,940.63
09:19:51  #5   bid   55¢* ask   56¢* mid  55.5¢* last   62¢  traded +86,313.51
09:20:01  #6   bid   65¢* ask   66¢* mid  65.5¢* last   61¢* traded +104,021.67
09:20:11  #7   bid   68¢* ask   69¢* mid  68.5¢* last   63¢* traded +119,946.40
09:20:21  #8   bid   66¢* ask   67¢* mid  66.5¢* last   66¢* traded +126,147.62
09:20:31  #9   bid   71¢* ask   72¢* mid  71.5¢* last   69¢* traded +132,704.84
summary: 9 cycles, 8 with a change; mid 63.5¢ -> 71.5¢, 132,704.84 contracts traded

A quiet market looks very different: a gas-price contract watched for 12 cycles the same morning showed no changes and nothing traded. That's the market, not a bug.

What we found on Oct 25. We built the previous prompt in a clean folder that Sunday and ran it on demo and production public data. The signing code and its tests were right first time; the experience around them wasn't. We fixed four problems that morning, rebuilt at 1 p.m. ET during the NFL early games, and found a fifth.

1. Production crashed on the first command. From our server, the main production host external-api.kalshi.com answered every request with an HTML 403 Forbidden. The old prompt mentioned this but only offered a manual override, so the CLI died with a traceback:

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://external-api.kalshi.com/trade-api/v2/markets?status=open&limit=20&mve_filter=exclude

Kalshi documents api.elections.kalshi.com as an "also supported" production host, and it worked from the same machine. The client now switches to it once and says so. Every other HTTP error is one readable line, never a traceback.

2. Empty markets looked free. The first demo screen:

KXRAIN-26OCT26-WPB      yes bid 0.0000 (0%) ask 0.0000  Will it rain in West Palm Beach on Oct 26, 2026?

An ask of $0.00 means nobody is selling, not that YES is free. Of the first 10,000 open demo markets we scanned, 9,705 had no ask at all, and the API showed that as 0.0000 on some and 1.0000 on others. On production, empty asks read 1.0000 and empty bids 0.0000. The only reliable test is the size field: yes_ask_size_fp of 0.00 means the side is empty. The rebuild prints — for an empty side.

3. The default market list was dead. markets showed the first 20 open markets the API returned, which were mostly brand-new, unquoted ones. Production has a lot more than that: we paged through 60,000 open markets (and there were more) in 51 seconds, and the list isn't sorted by volume. So the rebuilt markets command keeps only two-sided markets, sorts them by 24-hour volume, and labels itself honestly as a sample. --series takes you straight to busy markets. Here it is at 1:17 p.m. ET, a few minutes after kickoff:

$ KALSHI_ENV=prod python cli.py markets --series KXNFLGAME --top 6
note: external-api.kalshi.com returned 403 from this network; using api.elections.kalshi.com
[PROD] real exchange data
TICKER                                  BID  ASK SPRD     24H VOL CLOSES  TITLE
KXNFLGAME-26OCT25SFATL-SF               62¢  63¢   1¢   3,011,623     1d  San Francisco
KXNFLGAME-26OCT25CINBAL-CIN             45¢  46¢   1¢   2,704,971     1d  Cincinnati
KXNFLGAME-26OCT25NYGHOU-NYG             21¢  22¢   1¢   2,671,110     1d  New York G
KXNFLGAME-26OCT25SFATL-ATL              37¢  38¢   1¢   1,202,528     1d  Atlanta
KXNFLGAME-26OCT25CLETEN-CLE             29¢  30¢   1¢   1,118,062     1d  Cleveland
KXNFLGAME-26OCT25INDMIN-MIN             59¢  60¢   1¢   1,095,654     1d  Minnesota
scanned 52 open markets (all pages scanned), 52 had both sides quoted
quotes here are the market snapshot; `book <ticker>` reads the live order book

"Closes 1d" on a game that's already being played is right: Kalshi's close_time sits after the expected finish, and these markets close early once there's a result. Without --series, the default scan of 3,000 production markets found 1,973 two-sided ones, led that afternoon by Bundesliga goal-scorer markets. On demo, two scans of 3,000 markets found 43 and 63 with both sides quoted, and the CLI says demo is mostly empty.

4. A typo looked like an empty market. GET /markets/{ticker}/orderbook and GET /markets/trades return 200 with an empty result for a ticker that doesn't exist. Only GET /markets/{ticker} returns 404. The old build printed blank bid ladders for KXNOPE-NOTREAL. The rebuild checks the market first and tells you the ticker isn't on this environment.

5. watch said nothing was trading during an NFL game. The order book for 49ers–Falcons, with the ask worked out for you (Kalshi only lists bids):

$ KALSHI_ENV=prod python cli.py book KXNFLGAME-26OCT25SFATL-SF
[PROD] real exchange data
YES bids (best last): 58¢ x 25,727, 59¢ x 445, 60¢ x 9,396, 61¢ x 30,602, 62¢ x 78,614
NO bids (best last): 33¢ x 1,145, 34¢ x 10,184, 35¢ x 82,737, 36¢ x 178,735, 37¢ x 166,245
best YES bid $0.62 (62%) | implied YES ask $0.63 (63%) | spread 1¢ | mid $0.625 (62.5%)
implied NO ask $0.38 (38%)
contracts within 5¢ of best: YES 169,214  NO 443,544
Kalshi lists YES bids and NO bids only, so the YES ask is 1.00 minus the best NO bid.

Then watch on the same market, built from the morning's prompt (* marks a change since the last cycle). San Francisco jumped 5¢ in ten seconds, and the volume column didn't move:

$ KALSHI_ENV=prod python cli.py watch KXNFLGAME-26OCT25SFATL-SF --interval 10 --cycles 6
13:17:22  #1   bid  62¢  ask  63¢  mid 62.5¢  last  63¢  24h vol +0
13:17:33  #2   bid  62¢  ask  63¢  mid 62.5¢  last  63¢  24h vol +0
13:17:43  #3   bid  62¢  ask  63¢  mid 62.5¢  last  62¢* 24h vol +0
13:17:54  #4   bid  67¢* ask  68¢* mid 67.5¢* last  63¢* 24h vol +0
13:18:04  #5   bid  67¢  ask  68¢  mid 67.5¢  last  67¢* 24h vol +0
13:18:15  #6   bid  67¢  ask  68¢  mid 67.5¢  last  68¢* 24h vol +0
summary: 6 cycles, 4 with a change; mid 62.5¢ -> 67.5¢, 24h volume +0

trades showed six fills in the same second, so it wasn't quiet. We polled the market every 20 seconds for two minutes: volume_fp (lifetime volume) climbed from 4,146,334 to 4,220,425, while volume_24h_fp sat at 3,011,623.46 the whole time. The 24-hour figure is a snapshot that refreshes slowly. It's fine for ranking markets and useless for "what traded just now." The rebuilt watch measures the change in volume_fp:

$ KALSHI_ENV=prod python cli.py watch KXNFLGAME-26OCT25SFATL-SF --interval 10 --cycles 6
13:21:03  #1   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +0
13:21:14  #2   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +1,064
13:21:24  #3   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +4,019
13:21:35  #4   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +7,665
13:21:45  #5   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +9,928
13:21:56  #6   bid  67¢  ask  68¢  mid 67.5¢  last  68¢  traded +13,243
summary: 6 cycles, 0 with a change; mid 67.5¢ -> 67.5¢, 13,243 contracts traded

The quote sat still for a minute while 13,243 contracts changed hands. Times are ET.

Things we noticed along the way:

  • The market snapshot and the order book can disagree. We read GET /markets/{ticker} and its order book back to back, 118 times across the 40 busiest production markets. 20 pairs disagreed on the bid or ask, and 7 of them by 5¢ or more, mostly in-play soccer and same-day weather markets. They're separate reads and live books move fast, so watch and book take bid and ask from the book. The markets list uses the snapshot and says so.
  • Contract counts can be fractional. Trades came back as x 29.57 and x 7.73, so parse count_fp as a decimal, not an integer.
  • Demo mirrors some production tickers with no quotes. The Harry Kane anytime-goal market from production existed on demo too, with an empty book on both sides. So "prod tickers 404 on demo" isn't always true. Sometimes you get an empty twin.
  • taker_side in trades is deprecated. The docs say to use taker_outcome_side, so the prompt now names it.
  • What we couldn't test. We don't have Kalshi demo keys, so balance and positions weren't run against a real account. What we did check: signatures from both an RSA and an Ed25519 key verify against their public keys under Kalshi's documented scheme (16 offline tests in the morning build, 12 in the afternoon one, all passing), and an unknown key ID gets a clean 401 not authenticated (NOT_FOUND) with a hint instead of a crash.

Built this before Nov 4, 2026? Paste this into the same session:

Six fixes, with tests:
1. kalshi_http: timeout=(5, 10). Catch requests Timeout/ConnectionError:
   retry ONCE after the backoff delay, then raise a one-line error
   ("timed out after 2 tries (<host>)"), never a traceback.
2. On 429/5xx, if Retry-After is present sleep that many seconds (cap 8),
   else keep the exponential backoff.
3. A 2xx body that isn't JSON raises KalshiHTTPError ("response was not
   JSON: ..."). Strip HTML tags from error bodies; print Kalshi's error
   code/message as-is. Don't branch on code strings (market_closed is
   market_inactive from 2026-11-05).
4. cli: on BrokenPipeError (`| head`) exit 0 quietly. Print the banner
   with flush=True. Size the markets ticker column to the longest ticker.
5. watch: before each cycle, if the market's status isn't "active", print
   "market status is '<status>', not 'active'; stopping" and end with the
   summary. (status=open returns "active"; paused reads "inactive",
   closed "closed"/"determined", settled "finalized".)
6. Tests for each, offline. Show me the diff first.

Built it before Oct 25? Apply this one first, then the Nov 4 one above. If you built it on the morning of Oct 25 or later, you only need fix 5.

Five fixes, with tests:
1. HTTP: retry 429/5xx with bounded backoff. If the default prod host
   external-api.kalshi.com returns 403, retry once on the documented
   also-supported host api.elections.kalshi.com, print a one-line note,
   and keep using it. Any other HTTP error prints one line, no traceback.
2. Treat a quote side as empty when its *_size_fp is 0 (the price can
   read 0.0000 or 1.0000). Print "—" for empty sides, never $0.00/$1.00.
3. `markets`: page with limit=1000 and cursor (default 3 pages), keep only
   two-sided markets, sort by volume_24h_fp, show bid/ask/spread/24h
   volume/time to close, and add --series. Footer: how many were scanned,
   how many were two-sided, and that it's a sample, not a full ranking.
4. book/trades: call GET /markets/{ticker} first, because the orderbook
   and trades endpoints return 200 + empty for unknown tickers.
5. watch: take bid/ask/mid from the order book, and show contracts
   traded since the first cycle as the change in volume_fp.
   volume_24h_fp is a slow snapshot and can stay flat for minutes while
   thousands of contracts trade. Parse count_fp as Decimal (it can be
   fractional).
If you don't have them yet, add `trades <ticker>` (use
taker_outcome_side) and `watch <ticker> --interval 10 --cycles 6`
printing bid/ask/mid/last per cycle with * on changes. Show me the diff
first.

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 small, read-only Python client and CLI for the Kalshi Trade API v2.
Use only endpoints and fields documented at https://docs.kalshi.com. If
unsure, ask me. NO order placement anywhere in this project.

Python 3.10+, requests, cryptography, python-dotenv, pytest. Files:

- config.py: KALSHI_ENV = "demo" (default) or "prod".
    demo: https://external-api.demo.kalshi.co/trade-api/v2
    prod: https://external-api.kalshi.com/trade-api/v2
    prod fallback: https://api.elections.kalshi.com/trade-api/v2 (documented
    as "also supported"; same markets, same signing).
    KALSHI_PROD_BASE_URL overrides prod. Every CLI run prints one banner line:
    "[demo] mock money" or "[PROD] real exchange data".
- kalshi_http.py: one requests.Session, timeout=(5, 10). Retry 429 and 5xx
    with exponential backoff (0.5 s doubling, max 8 s, max 5 retries; sleep is
    injectable for tests); if a Retry-After header is present, sleep that
    instead (cap 8 s). Retry a timeout or connection error ONCE, then raise a
    one-line error, so a hung host costs ~20 s, not minutes. A 2xx body that
    isn't JSON (an HTML gateway page) is an error too, not a crash. If the
    default prod host answers 403, retry the
    request ONCE on the fallback host, print "note: <host> returned 403 from
    this network; using api.elections.kalshi.com" once, and keep using it.
    Any other non-2xx raises KalshiHTTPError(status, path, short body text,
    HTML tags stripped); the CLI prints it on one line with Kalshi's own error
    code as-is, never a traceback. Don't branch on error-code strings:
    market_closed became market_inactive on 2026-11-05.
- kalshi_public.py (no auth):
    list_markets(status="open", limit=1000, max_pages=2, series_ticker=None)
      -> GET /markets with mve_filter=exclude, following `cursor`.
    get_market(ticker) -> GET /markets/{ticker}
    get_orderbook(ticker, depth=None) -> GET /markets/{ticker}/orderbook.
      Root key "orderbook_fp" with "yes_dollars" and "no_dollars": lists of
      [price, count] strings sorted by price ASCENDING, so the best bid is
      the LAST item. Either list can be missing or empty.
    get_trades(ticker, limit=10) -> GET /markets/trades. Use
      taker_outcome_side (taker_side is deprecated), yes_price_dollars,
      count_fp (can be fractional, e.g. "29.57": parse as Decimal),
      created_time.
    list_events(limit=20) -> GET /events
- quotes.py (pure functions, no network; most of the tests live here):
    Use Decimal for prices. quote(market) -> yes_bid, yes_ask (None when the
    matching *_size_fp is 0: an empty side can read "0.0000" OR "1.0000",
    so never trust the price alone), spread, mid (only when both sides
    exist), last, volume_24h. book_summary(orderbook): best YES bid, best NO
    bid, implied YES ask = 1 - best NO bid, implied NO ask = 1 - best YES
    bid, spread, mid, contracts within 5 cents of each best bid.
    active(markets, top): keep markets with both sides quoted, sort by
    volume_24h_fp descending.
- kalshi_auth.py:
    Key id from KALSHI_API_KEY_ID; PEM path from KALSHI_PRIVATE_KEY_PATH.
    The key file must live OUTSIDE this repo: resolve the path and raise if
    it is inside the project folder. message = timestamp_ms + METHOD + path,
    where path starts /trade-api/v2/... with the query string removed.
    RSA keys: RSA-PSS, MGF1(SHA256), salt_length=DIGEST_LENGTH, SHA256.
    Ed25519 keys: sign the message directly. Detect key type after loading.
    Headers: KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP, KALSHI-ACCESS-SIGNATURE.
    get_balance() -> GET /portfolio/balance (cents; its own rate bucket, at
    most once a second on Basic, so never call it faster).
    get_positions() -> GET /portfolio/positions (unsettled by default).
    Missing keys: raise NoKeys; the CLI prints "no Kalshi keys set; balance
    unavailable" (or "positions unavailable") and exits 1. NEVER print a
    simulated, mock or placeholder balance; a test must check this.
    On 401, print the error body's "details" plus: "check the key belongs
    to this KALSHI_ENV (demo keys only work on demo), the timestamp is in
    milliseconds, and the signed path has no query string".
- cli.py commands (prices as dollars with implied % next to them, "—" for
    an empty side; never print an empty side as $0.00 or $1.00):
    markets [--pages 3] [--top 15] [--series S]: scan open markets, show the
      most active two-sided ones: ticker, title (yes_sub_title when set,
      e.g. the team), YES bid/ask, spread, 24h volume, time to close. Kalshi has tens of thousands of open markets
      and /markets is NOT sorted by volume, so this is a sample of the first
      N pages, not an exchange-wide ranking. Footer: "scanned N open markets
      (more not scanned: a sample, not a full ranking; use --series or
      --pages), M had both sides quoted", then "quotes here are the market
      snapshot; `book <ticker>` reads the live order book" (the two can
      differ by several cents on in-play markets). On demo, if M is small,
      say demo has few live quotes.
    market <ticker> | book <ticker> [--depth 5] | trades <ticker> [--limit 10]
      book prints both bid ladders (best last), the implied asks, spread and
      mid, and one line explaining that Kalshi lists YES bids and NO bids
      only, so the YES ask is 1.00 minus the best NO bid.
    watch <ticker> [--interval 10] [--cycles 6]: poll market + book each
      cycle (interval >= 2 s) and print one line per cycle: time, bid, ask
      and mid FROM THE BOOK, last from the market, contracts traded since
      the first cycle (change in volume_fp; volume_24h_fp is a slow
      snapshot that can sit still for minutes during heavy trading), and
      "*" where a price changed. Ctrl-C exits cleanly with a summary. Before
      each cycle check the market's status field: only "active" is live
      (status=open in the filter returns "active"; paused markets read
      "inactive", closed ones "closed" or "determined"). Otherwise print the
      status and stop instead of polling a dead book.
    events | balance | positions
    The orderbook and trades endpoints return 200 with an EMPTY result for
    a ticker that does not exist, so book/trades/watch call get_market first
    (it 404s) before reading the book. On a 404 for market/book/trades/watch:
    "not found on <env>: demo and prod list different markets; pick a
    ticker from `markets` in the same env".
    Show a half-cent mid as 52.5¢, not rounded to 52¢. Size the ticker
    column to the longest ticker. Print the banner with flush=True. When
    stdout is closed (`| head`), exit 0 quietly with no BrokenPipeError.
- .env.example with blanks, .env in .gitignore, never print secrets.
- tests (offline, no network, never a real key; generate throwaway keys in a
    temp dir): signing message without query string; Ed25519 AND RSA
    signatures verify with the public key; key inside the repo rejected; no
    keys -> no balance printed; quote() with empty sides as "0.0000" and as
    "1.0000"; book_summary on the docs' example book (best YES bid 0.42,
    implied YES ask 0.44, spread 0.02); 429 backoff bounded; 403 fallback
    switches host once; Retry-After honored and capped; a timeout retried
    once then one line; HTML 200 body is an error, not a crash; watch marks
    changed values and counts traded contracts from volume_fp, not
    volume_24h_fp; watch stops on a non-active status without reading the
    book.
- README: demo vs prod, the commands, and that demo and prod list different
  markets (a prod ticker may 404 on demo, or exist there with no quotes).

Show the plan, build it, run the tests, then tell me the commands to run.

How do you build it, step by step?

  1. New folder + Safety Pack. Make an empty folder and add the rules file, .gitignore and deny rules from the Safety Pack.
  2. Paste the prompt into your AI tool and let it build. Then run python -m pytest -q. The tests run offline and generate throwaway keys, so they need no account. Before going further, check that kalshi_auth.py strips the query string before signing. It's the #1 cause of signature errors.
  3. Look at demo: python cli.py markets. Expect a short list (on Nov 4, two scans of 3,000 demo markets found 53 and 52 two-sided ones) and a note that demo is mostly empty. That's normal.
  4. Look at real markets, read-only: KALSHI_ENV=prod python cli.py markets. No account or key is needed for public data. For a busy category, add a series, for example --series KXLOLGAME. You'll find series tickers in market tickers (the part before the first dash). If you see "note: … returned 403", the client already switched to the other production host.
  5. Pick a ticker and dig in: python cli.py book <ticker> for the bid ladders, implied ask and spread; python cli.py trades <ticker> for recent prints; python cli.py watch <ticker> --interval 10 --cycles 6 to watch it move and count what trades. A live game on a Sunday afternoon is the most interesting thing to watch. Use a ticker from the same environment you're querying.
  6. Optional, for signed calls: create a Kalshi demo account at demo.kalshi.co (Kalshi's step-by-step guide). It uses mock funds and separate credentials. Then go to Account & security → API Keys → Create Key, save the private key file outside your project folder (for example ~/.config/kalshi/demo.pem), and note the Key ID. Kalshi can't show the private key again.
  7. Set .env: KALSHI_ENV=demo, KALSHI_API_KEY_ID=..., KALSHI_PRIVATE_KEY_PATH=/home/you/.config/kalshi/demo.pem.
  8. Try signed calls: python cli.py balance and python cli.py positions. A 401 prints Kalshi's reason and a checklist: a key from the other environment, a timestamp in seconds instead of milliseconds, or a query string in the signed path. NOT_FOUND in the reason means the key ID isn't known on this environment.

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

Everything here runs against Kalshi demo by default and nothing in it can place an order, with mock money and separate keys, so a mistake costs nothing. Kalshi warns that demo prices and behavior may not match real markets, so don't treat demo results as evidence a strategy works.

Keep the environment switch boring and explicit: KALSHI_ENV=demo is the default, and prod should print a loud banner. When you build the bot in the next recipe, live trading gets a second, separate gate.

To see how Kalshi's auth, order types, order book and rate limits line up against Polymarket's, read the Kalshi vs Polymarket API comparison.

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 4, 2026. APIs change, so if something here disagrees with the official docs, trust the docs and tell us.

Frequently asked questions

What is the Kalshi API base URL?

Production is https://external-api.kalshi.com/trade-api/v2, and https://api.elections.kalshi.com/trade-api/v2 is also supported and covers all markets. Demo is https://external-api.demo.kalshi.co/trade-api/v2 (or https://demo-api.kalshi.co/trade-api/v2).

Do I need an API key for Kalshi market data?

No. Public market data like GET /markets and GET /markets/{ticker}/orderbook works without authentication. You need a key for anything about your account: balance, positions and orders.

Why does my Kalshi API signature fail?

The most common causes are signing the path with the query string attached, using a timestamp in seconds instead of milliseconds, signing only /portfolio/balance instead of /trade-api/v2/portfolio/balance, or using the wrong algorithm for your key type (RSA-PSS for RSA keys, a direct signature for Ed25519 keys).

What are Kalshi API rate limits?

Kalshi uses token buckets for authenticated requests. Most cost 10 tokens. The Basic tier refills 200 read tokens and 100 write tokens per second, and higher tiers get more. GET /portfolio/balance has its own bucket: 1 request per second on Basic. A 429 comes with no Retry-After header, so back off exponentially; there's no extra penalty.

Does Kalshi have a demo environment?

Yes, at demo.kalshi.co, with mock funds and its own API keys and endpoints.

Why does the Kalshi API show an ask of 0.0000 or 1.0000?

That side of the market is empty. Kalshi still fills in a price field, 0.0000 on some markets and 1.0000 on others, but the matching size field (yes_ask_size_fp, yes_bid_size_fp) is 0.00. Check the size before treating the price as a real quote.

Why does external-api.kalshi.com return 403?

We saw an HTML 403 Forbidden from that host on our server while api.elections.kalshi.com, which Kalshi documents as also supported, worked from the same machine. If it happens to you, use the other host; this recipe's client switches automatically, once.

Why is the order book empty for my ticker?

Either the market really has no bids, or the ticker doesn't exist. The orderbook endpoint returns 200 with an empty book for unknown tickers, so call GET /markets/{ticker} first. That one returns 404 for a typo, or for a ticker that exists on production but not on demo.

Why does a market from `status=open` say `active`?

The status filter on GET /markets takes unopened, open, paused, closed and settled, but the status field on each market uses other words. On Nov 4, 2026, open returned markets reading active, paused returned inactive, closed returned determined or closed, settled returned finalized, and unopened returned initialized. Compare against active when you check whether a book is live.

What is the Kalshi `market_inactive` error?

From Nov 5, 2026, the order error market_closed is called market_inactive, and orders on a halted market return it too. Read-only calls aren't affected. If your code matches on market_closed, update it, or better, show Kalshi's code as-is and don't branch on the string.

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

Use an AI coding tool to build your own Kalshi trading bot that runs on the Kalshi demo environment first, with order groups, reduce-only exits, a kill switch and optional LLM-assisted research that never sees your keys.

Kalshi Paper / demo first Intermediate

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