ChatGPT Trading Bot: An Honest Guide + Kalshi Demo Starter (Codex)

Kalshi Paper / demo first

Verified working on live data in paper mode, Nov 12, 2026. Dry run on live Kalshi demo data with no keys, so signed demo orders, exposure and daily loss from a real account are covered by tests only.

Short answer: Yes, ChatGPT and Codex can build a trading bot, but they can't make it profitable, and they often remember outdated API endpoints. The safe way is to give the model the official Kalshi docs, put the BotCookery rules in AGENTS.md, run on Kalshi's demo exchange, keep keys in env vars, and enforce limits and a kill switch in code.

What are the key facts?

  • Chat vs agent: in chat you copy code by hand (slower, you see every line). An agent like Codex edits files and runs commands (faster, so rules matter more).
  • Put the BotCookery rules in AGENTS.md in the repo root. Many coding agents, Codex included, read it for project instructions.
  • Give the model the docs. Paste or link the Kalshi pages you're using. Models often remember old endpoints, and Kalshi moved order creation to POST /portfolio/events/orders (V2).
  • Use Kalshi's demo exchange: https://external-api.demo.kalshi.co/trade-api/v2, with mock funds and separate keys.
  • Never paste keys into ChatGPT. Use env vars and a key file in ~/.config/kalshi/. Outside the project isn't enough for Codex: its default sandbox can read your whole disk, so deny that folder in a permission profile.
  • "1 contract per order" isn't a position limit. The starter holds one position per ticker and computes exposure and daily loss from your demo account, so a restart doesn't reset them.
DifficultyBeginner
Time1–2 hours
Cost$0 API · ChatGPT subscription
Works withChatGPT, Codex

What will you build?

Use ChatGPT (chat) or Codex (agent) to build a small Kalshi bot that runs on the demo exchange, with the BotCookery rules in AGENTS.md and every safety layer in place.

Who is it for?

ChatGPT users who want to turn "write me a trading bot" into something that won't hurt them.

Not for: Asking ChatGPT which trades to make. That's not what this is, and it's not reliable.

What happened when we rebuilt it from this prompt

On Nov 12, 2026 we rebuilt this bot again from the Oct 25 prompt in an empty folder, writing each file to what the prompt says and nothing more, then ran it with no keys against live Kalshi demo data for about 4 minutes (24 loops) and through a set of failure drills. Nothing was signed and no orders were sent.

The October fixes held. It proposed one paper bid (KXNHLGOAL-26NOV12TBCBJ-CBJAFANTILLI19-1 at $0.29, max $0.35) and then logged "holding" 23 times, including after a restart. find_ticker.py paged through 266 pages and found 7,734 markets with an ask in about 64 seconds. Here's what still went wrong:

  • The kill switch looked broken. The bot only checked KILL when it was about to propose an order. With a paper order already held, touch KILL changed nothing in the log: it kept saying "holding". Step 6 tells you to do exactly that drill. Now the bot checks KILL first on every loop and logs "killed".
  • "holding" didn't mean holding. When that NHL market's ask vanished (the demo API shows that as ask $1.00, size 0), a fresh bot with no order logged {"decision": "holding", "ask": 1.0}. Now it logs "waiting" with the ask, size and your max price, and saves "holding" for when you actually hold something.
  • Errors repeated forever without backing off. A 429 with Retry-After: 5, a 503 HTML page, dropped connections and a mistyped ticker all hit the API again on the very next loop and kept logging the same line. The typo just said 404 Client Error: Not Found for url: ... over and over. A maintenance page sent with HTTP 200 came out as Expecting value: line 1 column 1 (char 0). A finalized market logged "skip" forever.
  • Crashes and an empty log file. Missing config.toml and Ctrl-C both ended in a Python traceback. Running python bot.py > run.txt left the file empty (0 bytes after 25 seconds) until the bot stopped, because the output wasn't flushed.
  • find_ticker.py was hard to use. It printed all 7,734 markets. The top of the list (soonest close first) was a market with a March 2026 close time still listed as open, then markets closing within minutes. Its 429 retries were also silent. In a 429 drill it waited 1+2+4+8+16 seconds without saying anything, then crashed with a traceback.

After the follow-up below, same day: a typo exits with ticker not found: ... (check config.toml), a finalized market logs once and exits, a 429 waits the 5 seconds the server asks for (retry: HTTP 429, waiting 5s), and errors double the sleep up to 60 seconds. The order POST is never retried. If Kalshi rejects an order, the bot logs its error code. Since Nov 5, 2026 a halted or closed market returns market_inactive (it used to be market_closed). That last path needs keys, so we only tested it with a fake HTTP session. 17 tests pass. The run from that build, on KXNHLGOAL-26NOV12MINTOR-MINKKAPRIZOV97-1 (ask $0.48, max $0.50), timestamps trimmed:

{"decision": "dry_run", "body": {... "count": "1", "price": "0.4800", ...}, "exposure": 0, "daily_loss": "not tracked in dry run"}
{"decision": "holding", "reason": "resting order, position or paper order on this ticker", "ask": 0.48}
--- touch KILL
{"decision": "killed", "reason": "KILL file or BOT_KILL=1; proposing nothing"}
--- rm KILL, restart
{"decision": "holding", "reason": "resting order, position or paper order on this ticker", "ask": 0.48}

find_ticker.py now skips markets that close within 24 hours. It found 7,061 that close later and showed the 30 soonest.

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

Update this Kalshi demo bot. Use only the Kalshi docs pages I paste
below. Never run the bot with my keys; I run it myself.
1. Kill switch first: at the top of every loop, if KILL exists or
   BOT_KILL=1, log "killed" and propose nothing, even while holding.
2. Say why: log "holding" only when I already have a resting order,
   position or paper order on the ticker; log "waiting" with the ask,
   size and my max price when the price or size is wrong.
3. Requests: 10 s timeout. Retry GETs up to 3 tries on HTTP 429 (wait
   Retry-After if sent, else 1, 2, 4 s), 5xx, dropped connections and
   timeouts, and log each wait. Never retry the order POST; the next
   loop's resting-order check decides. If a reply isn't JSON, show the
   HTTP status and its first 80 characters. After a failed loop, double
   the sleep (cap 60 s) and reset it after a good one.
4. Stop cleanly: 404 on the market means "ticker not found, check
   config.toml", exit 2. Status closed, determined, disputed, amended or
   finalized: log once and exit 0. Keep waiting on initialized or
   inactive. If Kalshi rejects an order, log its error code (a halted or
   closed market returns market_inactive since Nov 5, 2026).
5. Missing or bad config.toml or limits.json: one plain line, exit 2.
   Ctrl-C: print "Stopped." and exit 0. Flush every log line, so
   `python bot.py > run.txt` fills the file as it runs.
6. find_ticker.py: same retry rules, log each 429 wait, skip markets
   that close within 24 hours, print the 30 soonest (--all for every
   one) and the total.
7. Tests with a fake HTTP session for each item.
Show me the diff before running anything.

What we found on Oct 25 (fixed in the prompt below): the bot re-bought the same contract every loop, 38 orders in under 13 minutes. "$5 exposure" and "$2 daily loss" were in-memory counters, and daily loss was stuck at 0. Codex CLI 0.164.0's default sandbox could read ~/.config/kalshi/demo.pem (we tested with a throwaway file). The pasted docs didn't cover every endpoint, the ticker search read only one page of 1,000 markets, and only risk.py had tests. Built this before Oct 25? Do step 3 below, paste this follow-up prompt first, then the Nov 12 one above:

Update this Kalshi demo bot. Use only the Kalshi docs pages I paste
below (Get Market, Get Markets, Get Orders, Get Positions, Get Balance,
Cancel All Orders). Never run the bot with my keys; I run it myself.
1. 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. Skip unless the market status is "active".
2. 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.
3. 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.
4. Save order timestamps in state/ so a restart doesn't reset the
   per-minute limit. If any risk check errors, block the order.
5. cancel_all.py with no credentials: exit 1, "Nothing was sent."
6. Add find_ticker.py: follow the cursor through
   GET /markets?status=open&mve_filter=exclude&limit=1000, wait and
   retry on HTTP 429, print markets with 0 < yes_ask_dollars < 1.
7. Add .env.*, *.key and state/ to .gitignore.
8. Tests with a fake HTTP session for each of these, plus RSA and
   Ed25519 signature checks against the public key.
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.

Act as a careful senior Python developer. I'm building a small Kalshi bot
that runs ONLY on the Kalshi demo exchange. Follow AGENTS.md (pasted
below). Use only endpoints from the Kalshi docs pages I paste below. If
something isn't in them, say so instead of guessing. Never run the bot
with my keys; I run it myself. My key file lives in ~/.config/kalshi/.

Build, one file at a time, waiting for my "next" between files:
1. kalshi_client.py: signed requests. Headers KALSHI-ACCESS-KEY,
   KALSHI-ACCESS-TIMESTAMP (milliseconds), KALSHI-ACCESS-SIGNATURE =
   base64(sign(timestamp + METHOD + path)), path starting /trade-api/v2,
   query string removed. RSA keys: RSA-PSS + SHA-256 (salt = digest
   length); Ed25519 keys: sign directly. Base URL fixed to
   https://external-api.demo.kalshi.co/trade-api/v2. Key id and key FILE
   PATH from env vars (KALSHI_API_KEY_ID, KALSHI_PRIVATE_KEY_PATH). If
   they are not set, run in DRY-RUN: read public data, log what would be
   sent, send nothing. Tests: query string stripped, and RSA and Ed25519
   signatures verified with the public key, using a fake HTTP session.
   Requests: 10 s timeout. Retry GETs up to 3 tries on HTTP 429 (wait
   Retry-After if sent, else 1, 2, 4 s), 5xx, dropped connections and
   timeouts, and log each wait. Never retry the order POST. If a reply
   isn't JSON, raise an error with the HTTP status and its first 80
   characters. Keep Kalshi's error code from error replies.
2. risk.py: limits.json (1 contract/order, $5 open exposure, $2 daily
   loss, 3 orders/min) + KILL file (or BOT_KILL=1). check_order blocks
   the order if any check errors. Compute, don't count:
   - open exposure from the exchange before each order: resting orders
     (GET /portfolio/orders?status=resting, yes_price_dollars *
     remaining_count_fp) plus positions' market_exposure_dollars
     (GET /portfolio/positions);
   - daily loss = today's first (balance + portfolio_value) from
     GET /portfolio/balance (cents, saved in state/day_start.json) minus
     the current value;
   - orders/min from timestamps saved in state/, so restarts don't reset.
   In dry-run, keep paper orders in state/paper.json and use those for
   exposure; log "daily loss not tracked" instead of pretending it's 0.
   Tests for every rule with a fake HTTP session.
3. bot.py: at the top of every loop, if KILL exists or BOT_KILL=1, log
   "killed" and propose nothing. Watch one ticker (GET /markets/{ticker}).
   404 means "ticker not found, check config.toml": exit 2. Status
   closed, determined, disputed, amended or finalized: log once, exit 0.
   Any other status but "active": log it and wait. Read the best YES ask from yes_ask_dollars and its size
   from yes_ask_size_fp (dollar and contract strings, not cents). If the
   ask is <= my max price in config.toml and the size is >= 1, and I have
   no resting order or position on this ticker (or paper order in
   dry-run), propose a 1-contract limit bid. Log "holding" only when I
   already have one; log "waiting" with ask, size and max price when
   the price or size is wrong.
   Call risk.check_order; place with POST /portfolio/events/orders using
   ticker, side "bid", count "1", price as a dollar string like "0.4500",
   time_in_force "good_till_canceled", self_trade_prevention_type
   "taker_at_cross", client_order_id uuid4. If Kalshi rejects it, log
   the error code (market_inactive for a halted or closed market). Log
   every decision to logs/decisions.jsonl and stdout, flushed per line.
   After a failed loop, double the sleep (cap 60 s); reset after a good
   one. Missing or bad config.toml or limits.json: one plain line, exit
   2. Ctrl-C: print "Stopped." and exit 0. Tests: a second loop logs
   "holding", KILL while holding logs "killed", 404 and finalized stop.
4. cancel_all.py: DELETE /portfolio/events/orders. With no credentials,
   exit 1 and say nothing was sent.
5. find_ticker.py: follow the cursor through
   GET /markets?status=open&mve_filter=exclude&limit=1000 and print
   markets with 0 < yes_ask_dollars < 1 (ticker, ask, size, bid,
   close_time) that close more than 24 hours out, the 30 soonest
   (--all for every one), then the total. Same retry rules as the
   client.
6. README + .gitignore (.env, .env.*, *.pem, *.key, KILL, logs/,
   state/).

After each file, explain it in plain English and list risks.

--- AGENTS.md ---
[PASTE THE SAFETY PACK RULES FILE]
--- KALSHI DOCS ---
[PASTE: Quick Start authenticated requests, Create Order (V2), Get
Market, Get Markets, Get Orders, Get Positions, Get Balance, Cancel All
Orders]

How do you build it, step by step?

  1. Get Kalshi demo keys in the API Keys section of your profile at demo.kalshi.co. Save the key file in ~/.config/kalshi/, e.g. ~/.config/kalshi/demo.pem.

  2. Create AGENTS.md from the Safety Pack rules file in a new folder, along with the .gitignore.

  3. Codex users: block the key folder. Install Codex with npm install -g @openai/codex or the installer on the Codex CLI page. Edit ~/.codex/config.toml yourself, not through Codex, and restart it:

    default_permissions = "kalshi-bot"
    
    [permissions.kalshi-bot]
    extends = ":workspace"
    
    [permissions.kalshi-bot.filesystem]
    "~/.config/kalshi" = "deny"
    

    Permission profiles are a beta feature, and they don't combine with sandbox_mode or --sandbox, so leave those out. That includes --sandbox workspace-write, which Codex's CLI reference suggests for low-friction local work: it quietly switches you back to the old sandbox. Don't pick another mode in /permissions mid-session either. Ask Codex to cat ~/.config/kalshi/demo.pem; it should get "Permission denied". In plain ChatGPT chat, skip this step, since chat can't read your files.

  4. Paste the prompt with the rules and every Kalshi page it lists filled in. In Codex, point it at the repo and let it read AGENTS.md.

  5. Go file by file. The "wait for next" instruction keeps changes small enough to actually read. Run the tests after kalshi_client.py and risk.py, before any code that places orders.

  6. Pick a ticker and run on demo. Run python find_ticker.py. It pages through every open demo market (266 pages on Nov 12) and lists the 30 soonest-closing ones with an ask that close more than a day out. Put one in config.toml and run python bot.py in your own terminal. Without keys it dry-runs, proposes one paper order, then logs "holding" ("waiting" means the price or size isn't right yet). Then drill touch KILL: the next loop should log "killed". Delete KILL to resume. python cancel_all.py needs demo keys.

  7. Ask ChatGPT to review its own code for security issues: "List every place a secret could leak or an unintended order could be sent." Then fix what it finds and check the fixes yourself.

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

The client hardcodes Kalshi's demo URL. Demo uses mock funds and separate credentials, so you can make every beginner mistake for free. Kalshi notes demo prices may not reflect real markets, so judge your code there, not your strategy.

Keep a simple log: what the bot saw, what it proposed, what risk decided, what the exchange returned. Review it daily for a week before considering anything else.

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

Frequently asked questions

Can ChatGPT make a trading bot?

ChatGPT can write the code for a trading bot, including API clients, risk checks and tests, especially if you give it the official docs. It can't make the bot profitable or guarantee it's bug-free, so run it in demo or paper mode and review the code.

Is a ChatGPT trading bot profitable?

There's no evidence that asking ChatGPT for trades produces reliable profits, and BotCookery doesn't make profit claims. Use ChatGPT to build tools; make trading decisions yourself, carefully, with limits.

Should I use ChatGPT chat or Codex?

Chat is slower but you see every line you copy. Codex edits your project directly, which is faster, so put the safety rules in AGENTS.md and review its changes before running them.

Why does ChatGPT write old Kalshi endpoints?

Models learn from older documentation. Kalshi's current order endpoint is POST /portfolio/events/orders (Create Order V2). The legacy create-order page is gone from Kalshi's docs, and the V2 page says to migrate. Paste the current docs into your prompt.

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