Claude Trading Bot: What Claude Can (and Can't) Do, Plus a Safe Starter

KalshiPolymarket US Paper / demo first

Verified working on live data in paper mode, Nov 9, 2026. Dry run on live Kalshi demo data with no keys, plus local fault drills. Signed demo orders, exposure and daily loss from a real account need your own demo keys and weren't run.

Short answer: Claude can't find you a winning strategy, but Claude Code is good at building a trading bot's plumbing: API clients from docs, the bot loop, tests and logging. The safe setup is a CLAUDE.md rules file, permissions.deny rules that block reading .env and key files, limits enforced in code, a kill switch, and Kalshi's demo environment before any real money.

What are the key facts?

  • Claude is good at: writing API clients from docs, building the bot loop, tests, logging, refactoring and explaining code. It's weak at: knowing today's API details unless you give it the docs, and anything resembling a guaranteed edge.
  • Put the BotCookery rules in CLAUDE.md. Claude Code reads it for every task in that folder.
  • Block secret files with permissions.deny in .claude/settings.json, e.g. "Read(**/.env)". Patterns like **/*.pem only cover the project folder, so a key in ~/.config/kalshi/ needs its own rule, plus the sandbox's denyRead to stop scripts reading it.
  • A real 2026 incident: a Claude Code session started python3 -m http.server in a folder holding a .env with a private key, on an internet-facing server, and the user reported a $1,324 loss (#34133).
  • Start on Kalshi's demo exchange (https://external-api.demo.kalshi.co/trade-api/v2), with mock funds and separate keys. With no keys at all, the starter dry-runs on public demo market data and sends nothing.
  • "1 contract per order" isn't a position limit. The starter holds one position per ticker and computes exposure and daily loss from your Kalshi account, so a restart doesn't reset them.
  • Kalshi's V2 order body needs side (bid = buy YES, ask = sell YES), and request signatures cover the full path from the API root, such as /trade-api/v2/portfolio/events/orders, without the query string. Keys can be RSA (RSA-PSS) or Ed25519. Since Nov 5, 2026 an order on a halted market fails with market_inactive (it used to be market_closed).
DifficultyBeginner
Time1–2 hours
Cost$0 API · Claude subscription
Works withClaude Code, Claude (chat)

What will you build?

Set up Claude Code so it builds trading bots safely by default, then use it to scaffold a demo-only Kalshi bot you understand line by line.

Who is it for?

People who watched a "Claude made me a trading bot" video and want to try it without leaking keys or blowing up an account.

Not for: Anyone hoping Claude will pick winning trades. It won't, and anyone claiming it does is selling something.

What happened when we rebuilt it from this prompt

On Nov 9, 2026 we rebuilt this bot from the prompt below in an empty folder, writing every file it asks for and nothing more, and ran it without keys on live Kalshi demo data from 9:02 to 9:14 AM ET. No key was used and no order was sent. The Oct 25 fixes held: one paper order, then "holding" on every loop, across restarts. The kill file, BOT_KILL=1, the exposure cap and the per-minute limit (seeded, then a restart) all blocked as they should. A closed market was skipped.

What broke was everything around the happy path:

  • A 429 ignored Retry-After. Through a local proxy that answered 429 with Retry-After: 5, the bot retried after 0.5, 1 and 2 seconds and gave up in 3.6 s. Now it waits what Kalshi asks, capped at 8 s.
  • Non-JSON replies were cryptic. An HTML maintenance page with status 200 logged JSONDecodeError: Expecting value: line 1 column 1. A dropped connection wasn't retried at all. Now every request has a timeout of (5, 10) seconds, reads retry twice on timeouts and dropped connections, and errors are one line, like HTTP 200, not JSON: 'Maintenance'. Orders are never retried.
  • A typo'd ticker looped forever. It logged a 404 every 15 seconds. Now the bot stops and tells you to run find_ticker.py.
  • Paper orders never went away. In a dry run, an order on a market that later closed stayed in state/paper.json, so the bot held forever and the order counted toward exposure. Now it's dropped when the market isn't active.
  • Ctrl-C and | head crashed. Ctrl-C printed a traceback. With python bot.py | head -1, the closed pipe was caught by the holding check and logged as holding check error: BrokenPipeError, then crashed. And with output sent to a file, nothing showed up until the bot exited, because Python buffers it. Now prints are flushed, Ctrl-C exits with "Stopped (Ctrl-C).", and a closed pipe exits quietly.
  • find_ticker.py printed 8,046 lines. It read all 243 pages of open demo markets in about 59 seconds and listed every one with an ask. One of them had a close time in March 2026, and 66 had less than one contract on offer. Now it takes --max-price, skips those, and prints the 25 soonest to close.

After the fixes (20 tests pass), the same loop on KXATPCHALLENGERMATCH-26NOV09AGUSAN-AGU (ask $0.43, max price $0.45), then the drills (timestamps and IDs trimmed):

{"decision": "dry_run", "body": {... "price": "0.4300", ...}, "exposure": 0, "daily_loss": "daily loss not tracked"}
{"decision": "holding", "ask": 0.43}
--- 429 with Retry-After: 5 (waited 5 s twice, 10.2 s total)
{"decision": "error", "error": "GET /markets/...: HTTP 429 too_many_requests too many requests"}
--- HTML page with status 200
{"decision": "error", "error": "GET /markets/...: HTTP 200, not JSON: 'Maintenance'"}
--- typo ticker
Ticker KXATPCHALLENGERMATCH-26NOV09AGUSAN-AGUX not found on demo. Run find_ticker.py and fix config.toml.
--- paper order on a market that closed
{"decision": "paper_dropped", "reason": "market status closed"}

A hung server costs up to about 33 seconds per loop (three 10-second tries plus waits) before the bot logs "timed out" and moves on. Exposure, daily loss and the holding check against a real demo account are covered by tests with a fake HTTP session, not by a signed run. You'll need your own demo keys for that.

Built this before Nov 9? Paste this follow-up prompt into the same project:

Update this Kalshi demo bot. Read the current Kalshi docs and
changelog (https://docs.kalshi.com/changelog) first.
1. broker.py: every request gets timeout=(5, 10). Reads and cancel-all
   retry up to 2 times on 429, 5xx, timeouts and dropped connections.
   On 429 wait the Retry-After seconds if sent (cap 8), else 1 s then
   2 s. Never retry an order POST.
2. A reply that isn't JSON (like an HTML maintenance page) is a
   one-line error with the status code and the first 80 characters of
   text with HTML tags stripped, not a traceback. For Kalshi errors,
   log error.code as-is (since Nov 5, 2026 a halted market returns
   market_inactive, formerly market_closed).
3. bot.py: if GET /markets/{ticker} returns 404, stop with "ticker not
   found, run find_ticker.py". If the market isn't "active" and there's
   a paper order for it in state/paper.json, drop it and log
   "paper_dropped".
4. Print each decision with flush=True, and don't print inside a try
   block that catches errors. Ctrl-C exits with "Stopped (Ctrl-C)." and
   no traceback. A closed pipe (python bot.py | head) exits quietly.
5. find_ticker.py: add --max-price and --top (default 25). Skip markets
   whose close_time has passed or whose yes_ask_size_fp is below 1.
   Show page progress on stderr and end with the count of usable
   markets.
6. Tests with a fake HTTP session: Retry-After honored and capped,
   HTML 200, timeout retried then one line, order POST not retried,
   error code kept, 404 stops, paper order dropped.
Show me the diff before running anything.

The Oct 25 pass found the bigger problems in the first version of this prompt. It proposed a new buy on every loop: 38 orders in 13 minutes on a $0.13 ask, and 38 more after a restart. Exposure was counted from orders sent, in memory, so a restart wiped it. The daily loss limit was a fixed 0 and could never trip. The deny rules missed the key in ~/.config/kalshi/, and the ticker search read 1 page of 217. The prompt below has the fixes: one position per ticker, exposure and daily loss from your Kalshi account, state on disk, and the key folder blocked by a deny rule and the sandbox.

Built this before Oct 25? Paste this first, then the Nov 9 one above:

Update this Kalshi demo bot. Read the current Kalshi docs first.
1. .claude/settings.json: add Read(~/.config/kalshi/**) to
   permissions.deny, and add
   "sandbox": {"enabled": true,
               "filesystem": {"denyRead": ["~/.config/kalshi"]}}.
   Add state/ to .gitignore. Never run the bot with my keys yourself.
2. One position only: before proposing, skip and log "holding" if this
   ticker has a resting order (GET /portfolio/orders?ticker=...&
   status=resting) or a position (GET /portfolio/positions?ticker=...,
   position_fp != 0). In dry-run, keep paper orders in state/paper.json
   and apply the same rule.
3. Skip unless the market's status is "active".
4. Open exposure: compute it from the exchange before each order
   (resting yes_price_dollars * remaining_count_fp plus positions'
   market_exposure_dollars), not from a counter of orders sent.
5. Daily loss: save today's first balance + portfolio_value from
   GET /portfolio/balance (cents) in state/day_start.json and block when
   the current value is max_daily_loss_usd below it. No placeholder 0.
6. Save order timestamps in state/ so a restart doesn't reset the
   per-minute limit. If any risk check errors, block the order.
7. cancel_all.py with no credentials: exit 1, "Nothing was sent."
8. Add find_ticker.py that follows the cursor through
   GET /markets?status=open&mve_filter=exclude&limit=1000.
9. Tests with a fake HTTP session for each of these.
Show me the diff before running anything.

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.

You're helping me build my first trading bot. Safety beats speed.

Step 0 (do this first, then stop and show me):
- Create CLAUDE.md containing the BotCookery Safety Pack rules pasted below.
- Create .gitignore covering .env, .env.*, *.pem, *.key, secrets/, KILL,
  logs/, state/, .venv/ (but keep .env.example tracked).
- Create .claude/settings.json with:
  permissions.deny: Read(**/.env), Read(**/.env.*), Read(**/*.pem),
  Read(**/*.key), Read(./secrets/**), Read(~/.config/kalshi/**),
  Bash(git push *)
  sandbox: {"enabled": true,
            "filesystem": {"denyRead": ["~/.config/kalshi"]}}
  (If you are not allowed to write under .claude/, tell me and I will
  approve it; do not work around it.)
- Create limits.json with: max_contracts_per_order 1,
  max_open_exposure_usd 5, max_daily_loss_usd 2, max_orders_per_minute 3.
- Create .env.example with blank KALSHI_API_KEY_ID and
  KALSHI_PRIVATE_KEY_PATH. My key will live in ~/.config/kalshi/, outside
  this folder. Never run the bot with my keys yourself; I run it.

Step 1: Build a Kalshi DEMO bot in Python 3.11+ (requests, cryptography,
pytest only) using only endpoints from https://docs.kalshi.com (fetch and
read the pages before coding). Files: broker.py, risk.py, bot.py,
cancel_all.py, find_ticker.py, config.toml, tests/.
- broker.py: base URL https://external-api.demo.kalshi.co/trade-api/v2
  (hardcode demo; production is a separate, deliberate change later).
  Every request: timeout=(5, 10). Reads and cancel-all retry up to 2
  times on 429, 5xx, timeouts and dropped connections; on 429 wait the
  Retry-After seconds if sent (cap 8), else 1 s then 2 s. Never retry
  an order POST. A non-JSON reply is a one-line error (status code plus
  the first 80 characters, HTML tags stripped). Log Kalshi's error.code
  as-is (a halted market returns market_inactive since Nov 5, 2026).
- Signed requests: headers KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP (ms),
  KALSHI-ACCESS-SIGNATURE = base64 signature of
  timestamp + METHOD + FULL path from the API root, e.g.
  "/trade-api/v2/portfolio/events/orders", with no query string. Support
  both key types: RSA (RSA-PSS, SHA-256, salt length = digest length) and
  Ed25519 (sign the message directly).
  Key id from KALSHI_API_KEY_ID; key file path from KALSHI_PRIVATE_KEY_PATH.
  Never print or log the key file contents.
- No credentials = DRY-RUN: read public market data, log what would be
  sent, send nothing. Keep dry-run "orders" in state/paper.json so the
  same rules apply and survive a restart.
- find_ticker.py: page through
  GET /markets?status=open&mve_filter=exclude&limit=1000 using the cursor
  (show page progress on stderr) and print the --top (default 25)
  soonest-closing markets with 0 < yes_ask_dollars <= --max-price,
  yes_ask_size_fp >= 1 and close_time still in the future: ticker, ask,
  ask size, bid, close_time, title. End with the usable count.
- bot.py watches one ticker and max_price from config.toml. Each loop:
  GET /markets/{ticker}; a 404 stops the bot with "ticker not found,
  run find_ticker.py". Skip unless status is "active"; if it isn't and
  a paper order exists for this ticker, drop it and log "paper_dropped".
  Rule: best YES ask (yes_ask_dollars, yes_ask_size_fp; fixed-point
  strings) is at or below max_price and size >= 1.
  ONE POSITION ONLY: before proposing, check for a resting order
  (GET /portfolio/orders?ticker=...&status=resting) or a position
  (GET /portfolio/positions?ticker=..., position_fp != 0) on this ticker,
  or a paper order in dry-run. If any exists, log "holding" and skip.
- risk.py checks, before every order, and fails closed if a check errors:
  KILL file (or BOT_KILL=1); max contracts; open exposure computed from
  the exchange each time (resting price*remaining_count_fp plus
  positions' market_exposure_dollars), or from state/paper.json in
  dry-run; daily loss = today's first (balance + portfolio_value) from
  GET /portfolio/balance (cents, saved in state/day_start.json) minus the
  current value (in dry-run log "daily loss not tracked"); orders per
  minute, from timestamps saved in state/ so a restart doesn't reset it.
- Orders via POST /portfolio/events/orders with body:
  ticker, side "bid" (bid = buy YES), count "1.00", price like "0.3500",
  client_order_id (uuid4), time_in_force good_till_canceled,
  self_trade_prevention_type taker_at_cross.
- cancel_all.py -> DELETE /portfolio/events/orders; with no credentials,
  exit 1 and say nothing was sent.
- Log every decision (skip, holding, blocked, dry_run, paper_dropped,
  sent, error) to logs/decisions.jsonl and print it with flush=True,
  outside any try block that catches errors. Ctrl-C exits with
  "Stopped (Ctrl-C)." and no traceback; a closed pipe exits quietly.
- Tests (fake HTTP session, no network or keys): every risk rule, the
  one-position rule, exposure from fake orders/positions, daily loss
  from a fake balance, restart keeps state, the signing message (query
  string stripped, full path), RSA and Ed25519 signatures verified
  with the public key, Retry-After honored, HTML reply, timeout, order
  POST not retried, 404 stop and paper order dropped.

Explain each file in plain English when you're done, and list anything
you weren't sure about.

[PASTE THE SAFETY PACK RULES FILE HERE]

How do you build it, step by step?

  1. Install Claude Code and open an empty folder. Grab the rules file from the Safety Pack and paste it at the bottom of the prompt where it says to.
  2. Run step 0 only. Claude Code will ask permission before writing .claude/settings.json; approve it. Check that the file has the deny rules and CLAUDE.md has the rules. Run /status to confirm the settings file loaded, and /sandbox to confirm the sandbox is on (on Linux and WSL2 it needs bubblewrap and socat; the panel's Dependencies tab says what's missing).
  3. Get Kalshi demo keys (optional for a first run). Without keys the bot dry-runs on public demo data and sends nothing. When you're ready, create keys in the API Keys section of your profile at demo.kalshi.co. Ed25519 and RSA both work. Save the key file at ~/.config/kalshi/demo.pem, the folder the deny rule and sandbox block. Run the bot with keys in your own terminal, not through Claude.
  4. Let Claude build step 1. Ask it to fetch the Kalshi docs pages before writing code, so it uses the current V2 order endpoint instead of something from its training data.
  5. Pick a ticker. Run python find_ticker.py --max-price 0.50. It pages through every open demo market (243 pages, about a minute, on Nov 9) and lists the 25 soonest to close that have a real ask. Pick one that doesn't close today and put it in config.toml. Demo books are thin, and many have no bid at all.
  6. Read every file. Ask Claude to walk you through broker.py and risk.py line by line. If you can't explain what a line does, don't run it.
  7. Run on demo and drill the kill switch. touch KILL works with or without keys (the next loop logs "kill switch on" and sends nothing). python cancel_all.py needs demo keys; without them it exits and says nothing was sent. The first loop proposes one order; after that the log says "holding" until that order or position is gone. In a dry run the paper order lives in state/paper.json, so delete that file to start over. Ctrl-C stops the bot.
  8. Iterate in small steps. One change per prompt, run the tests after each, commit after each. Big "rewrite everything" prompts are where bots break.

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

This starter hardcodes the Kalshi demo base URL on purpose. Switching to production should be a separate, deliberate change you make yourself, with a new production key and the live gate from the Kalshi AI Trading Bot recipe.

Prefer Polymarket US? Use the paper-ledger setup in Build a Polymarket Bot with Claude Code.

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

Frequently asked questions

Can Claude build a trading bot?

Yes. Claude Code can write a full bot (API client, strategy loop, risk checks, tests) from a clear prompt and the official docs. What it can't do is guarantee the strategy makes money. Use it as a fast, careful junior developer, not an oracle.

Is it safe to give Claude Code my API keys?

Don't give it the keys themselves. Load keys from environment variables, keep key files outside the project, add permissions.deny rules for .env files and your key folder, and turn on the sandbox so scripts can't read that folder either. Real incidents in 2026 involved agents exposing .env files.

Claude AI trading bot vs Claude Code trading bot: what's the difference?

Claude (chat) can explain concepts and draft code you copy by hand. Claude Code works directly in your project folder, writing files and running commands, which is faster and also riskier. That's why the rules file and deny settings matter.

Which market should my first Claude trading bot use?

In the US, Kalshi's demo environment is the easiest safe start: real API, mock money, separate keys. Polymarket US works too, using a local paper ledger and its order preview endpoint.

Why does my Kalshi bot get market_inactive errors?

Since Nov 5, 2026 Kalshi returns market_inactive (it used to be market_closed) when you order on a market that's closed or halted. The bot logs the code and doesn't retry the order. Note the status words differ: you filter lists with status=open, but a market's own status field says active.

Claude Code Hooks for Trading Bots: Block Secrets, Gate Live Orders

Copy-paste Claude Code hooks for Kalshi and Polymarket US bot projects: a PreToolUse guard that blocks secret-file access, live-trading commands and git push, plus a PostToolUse hook that re-runs your limit tests. Tested in the input formats Claude Code, Cursor, Grok Build and Codex send.

KalshiPolymarket US Agent guardrails (no trading) Intermediate

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