Grok Trading Bot: Build a Kalshi Paper Bot with Grok (Spending Limits Included)

Kalshi Paper / demo first

Verified working on live data in paper mode, Nov 5, 2026. Ran live in paper mode against Kalshi's public demo market data on the morning of Nov 5 (ET), for several runs plus kill-switch, cancel-all, settlement and HTTP fault drills. We had no demo keys, so no signed request was sent and no demo order was placed; real demo fills and order-group rejections are untested. The optional research step was not called (research_enabled false; no xAI API call). Settlement was drilled with a test position on a demo market that had already been finalized.

Short answer: You can use Grok to build a trading bot by having it scaffold a Kalshi bot that runs only on the demo exchange, with spending limits enforced in code (limits.json + risk.py) rather than in the prompt, a one-command kill switch, and an optional research step that only sees public market text. Grok writes the code; you set the rules.

What are the key facts?

  • Same recipe shape as our Claude and ChatGPT starters: the AI writes code, you set the rules and limits, and the bot runs in paper mode against Kalshi demo data until you have demo keys.
  • Spending limits belong in code (limits.json + risk.py), not in the agent's instructions. An agent can misread a prompt; it can't skip a code check it doesn't control.
  • Best YES ask: yes_ask_dollars from GET /markets/{ticker} when it is above $0 and below $1, or $1.00 minus the highest NO bid in the order book (the book returns bids only). On demo, markets where nobody is offering YES show yes_ask_dollars as "1.0000" or "0.0000"; treat both as no ask. Never compute "100 − X" on dollar prices.
  • Create Order V2 (POST /portfolio/events/orders) requires side, count, price, time_in_force (fill_or_kill, good_till_canceled or immediate_or_cancel) and self_trade_prevention_type (taker_at_cross or maker). GTT isn't a valid value. Cancel-all is DELETE /portfolio/events/orders.
  • Research step (optional): POST https://api.x.ai/v1/chat/completions (xAI files this under legacy and recommends its Responses API for new code; Chat Completions is still documented) with only the public title, rules text and prices, never keys, balances or positions. Its output is logged and never changes the bid.
  • Kalshi demo REST base: https://external-api.demo.kalshi.co/trade-api/v2. Public market reads work there without a key. Demo books are thin and change by the minute: of the first 1,000 open markets (mve_filter=exclude) around 9:04 AM ET on Nov 5, 13 had a real YES ask and none of those 1,000 were ≤ $0.15 — we found cheap asks deeper in the list a few minutes earlier.
  • Public reads: timeout=(5, 10), at most 2 retries, honor Retry-After (cap 8s). HTML or non-JSON becomes one line, not a traceback.
  • Use one order group and reuse it. Kalshi caps matched contracts per group over a rolling 15 seconds, so a new group per order never trips.
  • Kalshi changelog Nov 5, 2026: order errors on a halted/closed market return market_inactive (was market_closed); unscoped GET /markets skips on-demand KXRFQ series.
  • Agent-run bots on X: be wary of any account offering to "run your bot" or "manage your account." That's exactly what we never do.
DifficultyBeginner
Time1–2 hours
Cost$0 API · your AI subscription
Works withGrok, Any AI coding agent

What will you build?

Have Grok (or any agent) scaffold a Kalshi demo bot whose spending is capped in code, whose research step only sees public market text, and that you can stop with one command.

Who is it for?

People seeing "Grok trading" posts on X who want to try building, not buying, a bot, with the guardrails on from the start.

Not for: Letting an AI agent loose on a funded account, or anything sold as "Grok signals."

What happened when we rebuilt it from this prompt

On Nov 5, 2026 we pasted this page's one-shot prompt into a clean folder, built it by hand and ran it in paper mode against Kalshi's live public demo data that morning (ET). No demo keys, so nothing was signed or sent. The Oct 25 bookkeeping fixes (one order group, paper IOC fill, held-ticker skip, settle-first daily loss, cancel_all leaves filled exposure alone) held up. What broke was the HTTP edge:

  • Retry-After was ignored. A 429 with Retry-After: 3 retried after ~0.5 s of homemade backoff. Reads now sleep the header value (cap 8 s) when it is present.
  • HTML 200 printed a JSON decode error. A gateway login page as a 200 became Expecting value: line 1 column 1. Now: fetch failed: response was not JSON: gateway login.
  • Hung host chewed the clock. Default timeouts were generous and retries stacked; against a hung proxy the process sat until an outer 55 s kill with no useful line. Now: timeout=(5, 10), at most 2 retries, then fetch failed: timed out (~16 s in our drill).
  • 503 HTML leaked tags into the error. Stripped now (503 Service Unavailable).
  • Demo books are thinner than the Oct 25 sample suggested. Around 8:57 AM ET we scanned 5,000 open markets (mve_filter=exclude) and found 56 with a real YES ask, 18 of them ≤ $0.15. Around 9:04 AM the first 1,000 had 13 real asks and zero ≤ $0.15. Pick the ticker right before you run.

Oct 25 condensed (still true): a new order group every run meant the server-side 15 s cap never bit; cancel_all had been zeroing exposure for IOC fills; paper reserved the limit price instead of filling at the book; the bot re-bought the same ticker every run; daily_loss_usd was never written. Those are all in the one-shot now.

From the fresh rebuild this morning (16 tests pass), 8:58–9:03 AM ET:

08:58:39 KXNFLRECYDS-26NOV08CINATL-ATLAHOOPER81-40 (Austin Hooper: 40+ receiving yards) ask 0.0600 x50.00, limit 0.1500: PAPER IOC bid 1 @ 0.1500 -> filled 1.00 @ 0.0600 fee 0.01; exposure $0.070000, group paper-6cfc6744
08:58:39 KXNFLRECYDS-26NOV08CINATL-ATLAHOOPER81-40 … already hold 1.00, skip
KILL is on. No order, no order group.
{'paper_cancelled_resting': 0}
positions kept: {'KXNFLRECYDS-26NOV08CINATL-ATLAHOOPER81-40': {…}} exposure $0.070000
08:58:50 settled KXLIGAPROMATCH-26NOV050700LOBALO-LOB: no, pnl -0.13
08:58:51 KXNFLTD-26NOV08DENCAR-CARJCOKER18-3 (Jalen Coker: 3+ touchdowns) ask 0.0100 x25.00, limit 0.1500: PAPER IOC bid 1 @ 0.1500 -> filled 1.00 @ 0.0100 fee 0.01; exposure $0.090000, group paper-6cfc6744

The settlement line is a drill: we injected a test position on a demo market Kalshi had already finalized as "no", and the bot booked a $0.13 loss toward the daily limit. The second buy reused the first run's order group. After the HTTP fixes, fault drills against a local proxy: 429+Retry-After slept ~3 s; HTML 200 and 503 printed one clean line; hang ended with timed out in 16.5 s.

What we still can't test without demo keys: real demo fills, order-group rejection, signed cancels. Without an xAI key: the Grok research reply. kalshi.com/fee-schedule returned 429 during this check; the taker fee formula in the prompt (ceil to the cent of 0.07 * count * price * (1 - price)) still matches what we charge in paper. Docs pages we rely on were 200; demo and elections hosts both answered. Changelog Nov 5: market_closed → market_inactive on order errors; KXRFQ series excluded from unscoped lists.

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

Update the Kalshi demo bot with these HTTP and docs fixes. Stay in
paper mode; send nothing to the network except public market reads.

1. Public GETs: timeout=(5, 10), at most 2 retries. On 429/5xx use
   bounded exponential backoff. If the response has Retry-After, sleep
   that many seconds instead (cap 8).
2. Never print a traceback for HTTP or JSON failures. One line only:
   "fetch failed: …". HTML or non-JSON 200 -> "response was not JSON: …"
   (strip tags, truncate). 503 HTML -> "503 Service Unavailable".
3. Hang/timeout -> "fetch failed: timed out" after the retries, then exit.
4. Catch BrokenPipeError around main (exit 0) so `| head` is quiet.
   KeyboardInterrupt -> one line, exit 130.
5. Docs: orders on a halted/closed market return market_inactive (Kalshi
   changelog Nov 5, 2026; was market_closed). Unscoped GET /markets skips
   on-demand KXRFQ series. Fee formula unchanged
   (ceil-cent 0.07 * count * price * (1 - price)); kalshi.com/fee-schedule
   may 429 — use the formula in the prompt.
6. Beginner gotcha: demo books are thin. When picking a ticker, scan
   status=open&mve_filter=exclude until yes_ask_dollars is strictly
   between 0 and 1 ("0.0000" and "1.0000" mean no ask).
7. Keep Oct 25 behaviour: one reused order group, paper IOC fill at the
   ask with fee, held-ticker skip, settle-first daily loss, cancel_all
   does not clear filled exposure.

Built this before Oct 25? (and not yet on the Nov 5 follow-up) paste this first:

Update the Kalshi demo bot with these fixes. Stay in paper mode; send
nothing to the network except public market reads.

1. Order group: create one with {"contracts_limit": 3} only if
   ledger.json has no order_group_id, save the id and reuse it on every
   run. If an order is rejected because the group was triggered, log it
   and stop. I reset it by hand: PUT /portfolio/order_groups/{id}/reset.
2. Paper fills copy immediate_or_cancel: fill min(count, size of the best
   NO bid) at the YES ask (1 - best NO bid), not at bid_price, if the ask
   <= bid_price. Otherwise nothing fills and nothing is reserved.
3. Charge the taker fee on paper fills: round up to the cent
   0.07 * count * price * (1 - price) (https://kalshi.com/fee-schedule).
   Live fills come from the order response: fill_count,
   average_fill_price, average_fee_paid.
4. ledger.json keeps positions. open_exposure_usd is cost plus fees of
   filled, unsettled contracts. It drops only when a position settles.
5. cancel_all.py cancels resting orders only. It must not lower exposure
   for filled contracts. IOC orders never rest.
6. Skip a ticker this bot already holds.
7. Settle first on every run: for each held ticker, GET /markets/{ticker}.
   If status is "finalized" and result is "yes" or "no", pnl =
   count * (1 if yes else 0) - cost - fees. Add any loss to
   daily_loss_usd for today's local date; a new date starts at 0.
8. Treat yes_ask_dollars of "0.0000" as no ask, like "1.0000".
9. Drop order timestamps older than 60 seconds from the ledger.
10. research.py: strip

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 my coding partner. We're building a small Kalshi bot that runs ONLY
on the Kalshi demo exchange. Paper mode is the default. Do not invent
endpoints. If a field below disagrees with the docs you fetch, stop and
quote the doc.

Read these pages first and quote the line you rely on for each endpoint:
- https://docs.kalshi.com/getting_started/demo_env
- https://docs.kalshi.com/getting_started/quick_start_authenticated_requests
- https://docs.kalshi.com/api-reference/orders/create-order-v2
- https://docs.kalshi.com/api-reference/orders/cancel-all-orders
- https://docs.kalshi.com/api-reference/order-groups/create-order-group
- https://docs.kalshi.com/api-reference/order-groups/reset-order-group
- https://kalshi.com/fee-schedule
- https://docs.kalshi.com/api-reference/market/get-market
- https://docs.kalshi.com/getting_started/orderbook_responses

SAFETY RULES (BotCookery Safety Pack; also save them as AGENTS.md):
Secrets
- Never read, print, log or summarize .env, *.pem, *.key or any file with
  keys. Credentials come only from env vars: KALSHI_API_KEY_ID,
  KALSHI_PRIVATE_KEY_PATH (PEM file outside the repo) and XAI_API_KEY.
- Never start a web server, file server or tunnel in this folder. Never
  push or make the repo public without my OK.
Money
- The only base URL in code: https://external-api.demo.kalshi.co/trade-api/v2
- PAPER_MODE defaults to 1. A signed order or cancel only hits the network
  with PAPER_MODE=0 AND --live AND me typing exactly "I accept the risk".
  If keys are missing, exit. Never invent a key.
- A KILL file in the project folder, or BOT_KILL=1, blocks new orders.
  python cancel_all.py still runs.
- Enforce limits.json in risk.py before every order. Reject and log any
  order that breaks a limit; never retry it in a loop. Public reads use
  timeout=(5, 10) and at most 2 retries. On 429/5xx, bounded exponential
  backoff; if Retry-After is present, sleep that many seconds (cap 8)
  instead of the backoff. Non-JSON or HTML bodies become one line
  ("response was not JSON: …"); never print a traceback for HTTP or
  parse failures. Catch BrokenPipeError (exit 0) and KeyboardInterrupt
  (exit 130, one line).
- Research is off by default and never changes the bid.
Venue rules
- Only documented endpoints from docs.kalshi.com. Don't trade for anyone
  else, copy other traders, or share Kalshi data.
Code hygiene
- Log every decision to a local file with no secrets. Write the limit and
  kill-switch tests before the strategy.

limits.json, exactly:
  max_contracts_per_order 1
  max_open_exposure_usd 5
  max_daily_loss_usd 2
  max_orders_per_minute 3
  order_group_contracts_limit 3

risk.py, tests first. check_order(proposal, state, limits, now, kill_path)
returns allowed plus reasons. It does not raise for a bad order.
- proposal: ticker, side "bid" or "ask", count (Decimal contracts), price
  (Decimal dollars).
- state: open_exposure_usd, daily_loss_usd (non-negative dollars already
  lost today, not signed PnL), recent_order_times, group_submissions as
  (timestamp, contracts) pairs.
- Block if the KILL file exists or BOT_KILL=1.
- Block if count > max_contracts_per_order, or count <= 0, or price is not
  strictly between 0 and 1.
- A bid's cost is count * price. Block if open exposure plus that cost
  exceeds max_open_exposure_usd. Equal to the cap is allowed.
- Block if daily_loss_usd >= max_daily_loss_usd.
- Block if there are already max_orders_per_minute submissions in the
  last 60 seconds.
- The order-group limit mirrors Kalshi's rolling 15-second matched-contract
  cap. Locally, block if contracts submitted in the last 15 seconds plus
  this count would exceed order_group_contracts_limit. Say in a comment
  that the server counts fills and we count submissions.

config.toml:
  ticker = "<one demo ticker>"
  bid_price = "0.1500"          # dollars, not cents
  research_enabled = false

How to read the market (public, no auth header):
  GET /markets/{ticker}
  GET /markets/{ticker}/orderbook
Best YES ask:
  1. Use market.yes_ask_dollars when it is greater than 0 and less than 1.
     Demo returns "1.0000" or "0.0000" when nobody offers YES: no ask.
  2. Otherwise use $1.00 minus the highest NO bid in
     orderbook_fp.no_dollars. Never compute "100 - X" on dollar strings.
  3. If neither exists, there is no ask. Do not bid.
  The size you can buy at that ask is the size of the best NO bid.
title is deprecated; if it's empty, fall back to yes_sub_title.
When browsing for a ticker, pass status=open and mve_filter=exclude.
Demo books are thin: many open markets show yes_ask_dollars "0.0000" or
"1.0000" (no ask). Scan until you find 0 < ask < 1. Unscoped GET /markets
skips on-demand KXRFQ series (changelog Nov 5, 2026). Order errors on a
halted/closed market return market_inactive (was market_closed).

client.py:
  Sign timestamp_ms + METHOD + full path from the API root, query stripped.
  Example message: 1703123456789GET/trade-api/v2/portfolio/balance
  RSA-PSS SHA-256 (salt length = digest length) or Ed25519, then base64.
  Headers: KALSHI-ACCESS-KEY, KALSHI-ACCESS-TIMESTAMP, KALSHI-ACCESS-SIGNATURE.
  Public GETs stay unsigned so missing keys still allow a market read.
  Paper mode (default) handles POST /portfolio/order_groups/create,
  POST /portfolio/events/orders and DELETE /portfolio/events/orders on disk
  and does not open a socket for those. Persist paper state so cancel_all.py
  in a second process can see it.
  Paper fills copy immediate_or_cancel: fill min(count, size at the best
  YES ask) at that ask, not at bid_price, if the ask <= the limit. The rest
  is cancelled. Nothing fills means nothing is held or reserved. Charge the
  taker fee: round up to the cent 0.07 * count * price * (1 - price).
  Live fills come from the order response: fill_count, average_fill_price,
  average_fee_paid. IOC never rests, so there is nothing left to cancel.

research.py, off unless research_enabled is true:
  POST https://api.x.ai/v1/chat/completions
  Authorization: Bearer $XAI_API_KEY
  Model from XAI_MODEL, default grok-4.7. stream false, temperature 0.
  The user message may contain only title, rules_primary and these prices:
  yes_bid_dollars, yes_ask_dollars, no_bid_dollars, no_ask_dollars,
  last_price_dollars. No credentials, balances, positions, previous-day
  prices or notional value. Ask for JSON:
  {"summary": "<exactly three sentences>", "probability": 0.0, "reasoning": ""}
  Log the public view and the parsed reply to logs/research.jsonl.
  Strip ``` fences before parsing the reply.
  If XAI_API_KEY is missing, do not call the network. A --stub flag may use
  a deterministic local stub and must say it is not a forecast.
  A research failure is logged and ignored. It never blocks or places
  orders.

bot.py, one decision per run, no loop:
  1. If the kill switch is on, log and exit. Do not create an order group.
  2. Settle first: for each held ticker, GET /markets/{ticker}. If status
     is "finalized" and result is "yes" or "no", pnl = count * (1 if yes
     else 0) - cost - fees. Add any loss to today's daily_loss_usd (local
     date; a new date starts at 0) and drop the position.
  3. Fetch the market and the order book. If the fetch fails, log and exit.
  4. If status is not "active", or there is no YES ask, or the ask is above
     bid_price, or this bot already holds the ticker, log and exit.
     Ask == bid_price is a yes.
  5. check_order for a bid of exactly 1 contract at bid_price.
  6. Only if that passes: reuse the order_group_id saved in ledger.json.
     If there is none, POST /portfolio/order_groups/create with
     {"contracts_limit": 3} (integer) once and save the id. A new group per
     run gives every order its own 15-second window, so the cap never
     bites. If the server rejects an order because the group was
     triggered, log it and stop; I reset it by hand with
     PUT /portfolio/order_groups/{id}/reset. Then POST
     /portfolio/events/orders with
     ticker, side "bid", count "1.00", price as a 4-decimal dollar string,
     time_in_force "immediate_or_cancel", self_trade_prevention_type
     "taker_at_cross", client_order_id (UUID), order_group_id.
     Do not send GTT. It is not a valid time_in_force.
  7. Append every step to logs/decisions.jsonl. No secrets in the log.
     Print one plain line per run: what it saw, did and why.
  Track positions, exposure and the rate limit in a local ledger.json.
  open_exposure_usd is cost plus fees of contracts actually filled and not
  yet settled, plus resting bids (none with IOC). It drops only when a
  position settles. daily_loss_usd is non-negative dollars lost today.
  Drop order timestamps older than 60 seconds.
  Portfolio reads are authenticated and never go into the research
  prompt. If you later read GET /portfolio/balance for the ledger, use
  balance_dollars or treat the integer balance as cents. Never divide a
  dollar order price by 100.

cancel_all.py: DELETE /portfolio/events/orders (paper: clear saved resting
orders). It cancels orders, not positions, so it never lowers exposure for
filled contracts. The kill switch does not apply.

Tests: the risk rules above, plus paper IOC fill at the ask with the right
size and fee, no fill above bid_price, held ticker skipped, settlement loss
added to daily_loss_usd, cancel_all leaves position exposure alone, and one
order group reused across runs.

Also add .gitignore (.env, *.pem, *.key, KILL, logs/), .env.example with
empty values, AGENTS.md containing the safety rules above, and a gitleaks
pre-commit hook. Explain each file in a short README. Flag anything this
prompt still doesn't specify instead of guessing.

How do you build it, step by step?

  1. Set up the folder with the Safety Pack .gitignore and gitleaks hook (pip install pre-commit, save the pack's .pre-commit-config.yaml, run pre-commit install). The safety rules are already inside the prompt, and it saves them as AGENTS.md.
  2. Paste the prompt into Grok (or your agent of choice). Ask it to confirm the endpoints it will use and quote the docs line for each.
  3. Build tests first (risk.py), run them, then the client, then the bot.
  4. Pick a demo ticker. Run GET https://external-api.demo.kalshi.co/trade-api/v2/markets?status=open&mve_filter=exclude (no key needed) and choose one with a yes_ask_dollars above $0 and below $1 ("1.0000" or "0.0000" means nobody is offering YES). Demo books are thin and change by the minute — of the first 1,000 open markets around 9:04 AM ET on Nov 5, only 13 had a real ask — so pick the ticker right before you run. Without mve_filter=exclude the list is mostly multivariate combos with empty rules. Unscoped lists also skip on-demand KXRFQ series.
  5. Run in paper mode first: python bot.py. With no demo keys, paper mode reads the live public demo market, fills against the book the way an immediate-or-cancel order would, charges the taker fee and sends nothing. Run it again: it should skip the ticker it now holds. Drill touch KILL, run python bot.py (it should refuse), then python cancel_all.py. Your position and its exposure should still be there.
  6. Get Kalshi demo keys at demo.kalshi.co when you want real demo orders. Without a demo account this step can't be done: POST /portfolio/events/orders needs signed requests, so the bot stays in paper mode. Save the key file outside the project. Demo orders need PAPER_MODE=0, --live and the typed confirmation; demo uses mock funds.
  7. Try the research step only after the plumbing works (research_enabled = true, XAI_API_KEY in your environment). Read every summary. Over a few weeks, compare its probabilities with how markets actually resolved before letting it influence anything.

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

No demo keys yet? Paper mode is the default. It reads live public demo market data (no key needed), runs the same risk checks and fills the order against the current book instead of calling the exchange: at the ask, up to the size shown, with Kalshi's taker fee. Positions stay in ledger.json until Kalshi marks the market finalized, and any loss counts toward the daily limit. That's enough to prove the data → rule → risk → order → settle path.

With demo keys: the client is hardwired to Kalshi demo (mock funds, separate keys). That's your next step: real API, real rejections, no real money. Kalshi warns demo prices may not reflect production, so use it to prove the code works.

Paper scorecard to keep: orders proposed vs. blocked by risk (and why), demo fills, kill-switch drill times, research-step probability vs. outcome.

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

Frequently asked questions

Can Grok build a trading bot?

Yes. Like other capable AI models, Grok can write a bot's code from the official docs and a clear prompt. It can't guarantee profits or bug-free code, so build on Kalshi's demo exchange first and enforce limits in code.

Can I let an AI agent trade for me automatically?

You can technically wire an agent to an exchange API, but it's risky: agents misread instructions and can be steered by text they read. If you do automate, keep hard limits in code, use server-side protections like Kalshi order groups, and keep the AI out of the order path or behind strict checks.

Does cancel_all.py close my positions?

No. It cancels resting orders. This bot's orders are immediate-or-cancel, so they fill at once or die and never rest. Contracts you hold stay held until the market settles or you sell them, and they keep counting against your exposure cap.

Why can't I find a demo ticker with a YES ask?

Demo books are thin. yes_ask_dollars of "0.0000" or "1.0000" means no ask — keep paging status=open&mve_filter=exclude until you see a value strictly between 0 and 1, and do it right before you run. Unscoped lists also skip on-demand KXRFQ markets.

What is market_inactive?

As of Kalshi's Nov 5, 2026 changelog, orders on a halted or closed market return market_inactive (it used to say market_closed). Market lifecycle status values like active / finalized are unchanged; this bot still only bids when status is active.

Are "Grok trading signals" accounts legit?

BotCookery doesn't provide or endorse signals. Be very careful with any account selling signals or offering to run a bot on your account. Build and run your own tools, on your own account, with limits.

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