PASS WITH FIXESTested on Grok 4.7, , result: PASS WITH FIXES.We built this bot from the prompt and ran it in paper mode on a live public Kalshi demo market (48 tests passing). Signed orders used a fake transport and the xAI research call used a deterministic stub: no real keys, orders or money. The prompt below includes the fixes from that run.
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.
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}, or $1.00 minus the highest NO bid in the order book (the book returns bids only). 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 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.
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 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/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. Retry reads with
bounded exponential backoff on 429/5xx.
- 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 present and greater than 0.
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.
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.
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 orders so cancel_all.py
in a second process can see them.
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.
If XAI_API_KEY is missing, do not call the network. A --stub flag may use
a deterministic local stand-in and must say it is not a forecast.
A research failure is logged and ignored. It must not block or place 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. Fetch the market and the order book. If the fetch fails, log and exit.
3. If status is not "active", or there is no YES ask, or the ask is above
bid_price, log and exit. Ask == bid_price is a yes.
4. check_order for a bid of exactly 1 contract at bid_price.
5. Only if that passes: POST /portfolio/order_groups/create with
{"contracts_limit": 3} (integer). 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.
6. Append every step to logs/decisions.jsonl. No secrets in the log.
Track exposure and the rate limit in a local ledger.json. 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 the saved paper
orders), then drop local reserved exposure. The kill switch does not apply.
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?
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.
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.
Build tests first (risk.py), run them, then the client, then the bot.
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. Without mve_filter=exclude the list is mostly multivariate combos with empty rules.
Run in paper mode first:python bot.py. With no demo keys, paper mode reads the live public demo market, records the order it would place on disk and sends nothing. Drill touch KILL, run python bot.py again (it should refuse), then python cancel_all.py.
Get Kalshi demo keys at demo.kalshi.co when you want real demo orders. Save the key file outside the project. Demo orders need PAPER_MODE=0, --live and the typed confirmation; demo uses mock funds.
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 writes the order it would send to a local file instead of calling the exchange. cancel_all.py clears those paper orders. That's enough to prove the data → rule → risk → order 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.
Key handling: API keys and private-key files live in environment variables or a secrets manager. Never in code, prompts, chat logs, screenshots or git. .env and *.pem are in .gitignore, and your AI tool is blocked from reading them (see the Safety Pack).
Position limits: hard caps in config (max contracts per order, max total exposure, max daily loss). The bot refuses any order above them, and the caps are checked in code, not just in the prompt.
Kill switch: one command or one file (touch KILL) stops new orders immediately, and a second command cancels every resting order through the venue's cancel-all endpoint.
Paper first: paper or demo mode is the default. Live trading needs an explicit --live flag and a typed confirmation, and you only flip it after days of clean paper logs.
Spending limits live in limits.json and risk.py, enforced before every order, plus a Kalshi order group as a server-side backstop, created only after the risk check passes.
Daily loss is tracked as a positive dollar amount already lost. A check written against signed PnL can silently never trip.
The research model never sees credentials, balances or positions, and its output never changes the bid.
Don't connect an AI agent to a funded account with broad permissions "to see what happens."
Your bot, your account, your trades. Running it for other people breaks Kalshi's Developer Agreement.
Endpoints and rules were checked against these pages on Oct 19, 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.
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.
The Daily Bot Recipe
One new build recipe, one safety tip, and API changes worth knowing about. Free. No picks, ever.
Get started with the Kalshi API using an AI coding tool: public market data with no key, then RSA-PSS or Ed25519 signed requests against the Kalshi demo environment. Endpoints checked against the official docs.
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.
An honest guide to building a trading bot with Claude, Claude Code or Claude AI: where it helps, where it fails, and a safe Kalshi-demo starter prompt with a rules file, deny settings, limits and a kill switch.