Kill Switch & Position Limits for Kalshi and Polymarket US Bots

KalshiPolymarket US Paper / demo first

Verified working on live data in mock mode, Nov 6, 2026. Ran against a local mock exchange on Nov 6 with live public Kalshi demo and Polymarket US prices, on three Kalshi and two Polymarket US markets: a restart, an amend, a KILL plus cancel-all drill, a daily-loss drill and a normal shutdown. No Kalshi demo or Polymarket US keys, so no signed request was sent; the real cancel-all, order-group and position calls are written from the docs and not yet run.

Short answer: A good kill switch for a prediction-market bot has three layers: a local KILL file the bot checks before every order, the venue's cancel-all endpoint (Kalshi DELETE /portfolio/events/orders, Polymarket US POST /v1/orders/open/cancel), and Kalshi order groups as a server-side safety net. Position limits belong in code and are checked before every order.

What are the key facts?

  • Layer 1, local: the bot checks for a KILL file (or BOT_KILL=1) before every order and refuses to trade if it's there.
  • Layer 2, venue cancel-all: Kalshi DELETE /portfolio/events/orders (cancels resting orders across shards; Kalshi notes newly placed orders may also be cancelled during the minute after the request). Polymarket US POST /v1/orders/open/cancel.
  • Layer 3, server-side: Kalshi order groups cancel every resting order in the group and block new ones when fills exceed a contracts limit in a rolling 15-second window (limit range 1–1,000,000).
  • Polymarket US note: pure cancels are never rejected by its 5-second latency stopgap, so cancel-all works even when new orders are being rejected.
  • Limits are enforced in code before every create, amend and modify, not just described in a prompt. Exposure is read from the venue every loop, so a restart can't reset it.
  • Shutdown cancels resting orders and leaves positions alone. Polymarket US close-position is a market order with no slippage limit unless you set one, so the bot never sends it on its own.
DifficultyBeginner
Time1 hour
Cost$0
Works withClaude Code, Cursor, ChatGPT / Codex, Grok

What will you build?

Retrofit any existing bot with hard limits checked in code, a one-file kill switch, a cancel-all command for each venue, and Kalshi's server-side order-group safety net, then prove they work in demo/paper.

Who is it for?

Anyone with a bot (theirs or from GitHub) that doesn't yet have a fast, tested way to stop.

What happened when we rebuilt it from this prompt

On Nov 6, 2026 we built a fresh bot from this page's published one-shot (which already folds in the Oct 25 follow-up) in a clean folder: a small quoter that joins the best bid on three Kalshi demo markets and two Polymarket US markets, five contracts each, with every create/amend/modify going through check_order. No Kalshi demo or Polymarket US keys — orders hit a local mock exchange; prices came live from the public APIs. Twelve offline tests passed, then the live drills:

  • Restart kept exposure. First run placed four resting bids and blocked the fifth (tec-mls-winner-2026-11-07-vwh) at exposure $9.73 > $9. A restart reused order group mock-385f1818, found the four resting orders, amended nothing that was already on the live bid, and still blocked the fifth. Exposure stayed at $8.94 / $9.
  • Amend went through check_order. We moved the resting KXHIGHNY-26NOV06-T67 bid from $0.29 to $0.60 by hand. The next cycle amended it back to the live $0.29 bid (amend counted toward orders/min; only the price delta affected exposure).
  • KILL + cancel-all cleared both venues. touch KILL → bot refused to start. python cancel_all.py printed before/after, triggered the Kalshi order group, and exited 0 with ALL CLEAR (kalshi after: 0, polymarket_us after: 0).
  • Triggered group refuses start. After cancel-all, restart printed order group mock-385f1818 is triggered. Reset it by hand, then restart.
  • Daily-loss stop fired from the main loop. In a copy with max_daily_loss_usd: 1 and a seeded position of 5 KXHIGHNY-26NOV06-T67 contracts bought at $0.95, the live bid was $0.29, so cycle 1 marked daily loss $3.30 / $1, wrote KILL, and ran cancel_all.
  • Shutdown cancelled resting orders only. Ctrl-C printed shutting down: cancelling resting orders (positions are left open), ran cancel_all --no-trigger, left both venues at zero resting, and the mock request log had no close-position or market order.

One new API gotcha on Nov 6: Kalshi's public market payload now exposes bids as yes_bid_dollars (dollar strings like "0.4600"). The old integer-cents yes_bid field is null on these responses. Bots that still divide yes_bid by 100 will mis-read the book. Polymarket US public bids come through bestBidQuote.value on https://gateway.polymarket.us.

From the fresh rebuild, 9:05–9:06 AM ET (market lines trimmed):

created order group mock-385f1818
09:05:37 cycle 1
  exposure $0.00 / $9.0, daily loss $0.00 / $3.0
  placed k:KXNFLGAME-26NOV12WASNYG-WAS bid 0.460 x5
  placed k:KXHIGHNY-26NOV06-T67 bid 0.290 x5
  placed k:KXNFLGAME-26NOV15BUFNYJ-BUF bid 0.800 x5
  placed p:tec-mls-winner-2026-11-07-nas bid 0.237 x5
  BLOCKED p:tec-mls-winner-2026-11-07-vwh: create: exposure 9.73 > max_open_exposure_usd

Restart at 9:05 AM ET:

reusing order group mock-385f1818
found 4 resting orders from before; will amend, not duplicate
09:05:42 cycle 1
  exposure $8.94 / $9.0, daily loss $0.00 / $3.0
  BLOCKED p:tec-mls-winner-2026-11-07-vwh: create: exposure 9.73 > max_open_exposure_usd

Amend drill (seeded HighNY resting bid to $0.60), 9:06 AM ET:

[mock] POST /portfolio/events/orders/8239ba6efaef/amend {"yes_price": 0.29, "count": 5}
  amended k:KXHIGHNY-26NOV06-T67 bid 0.290 x5 id=8239ba6efaef

Then touch KILL and python cancel_all.py:

KILL ACTIVE: no new orders. Run cancel_all.py if anything is resting.
[mock] kalshi before: 3 resting [...]
[mock] kalshi order group mock-385f1818 triggered (reset it by hand to trade again)
[mock] kalshi after: 0 resting []
[mock] polymarket_us before: 1 open [...]
[mock] polymarket_us after: 0 open []
ALL CLEAR

Daily-loss drill, 9:06 AM ET:

  exposure $4.75 / $9.0, daily loss $3.30 / $1.0
  DAILY LOSS LIMIT HIT: wrote KILL, running cancel_all.py

A normal stop ends with shutting down: cancelling resting orders (positions are left open), both venues at zero resting, and no close or market order in the request log. We never sent a signed request to Kalshi or Polymarket US, so the real cancel-all, order-group and position calls are written from the docs and not yet run.

Built this before Nov 6? Paste this follow-up if your bot still reads Kalshi public bids from the old cents field (or skips bestBidQuote on Polymarket US):

Update market-data reads only. Don't change risk.py or cancel_all.py.

1. Kalshi public market GETs (demo or prod) now return yes_bid_dollars /
   yes_ask_dollars as dollar strings (e.g. "0.4600"). Prefer those. The
   legacy yes_bid / yes_ask integer-cents fields may be null. Do not divide
   a dollars field by 100.
2. Polymarket US public gateway (https://gateway.polymarket.us): read the
   bid from bestBidQuote.value when present; fall back to outcomePrices.
3. Re-run the restart + amend drills against live public prices and show
   me the cycle log.

Built this before Oct 25? The one-shot below already includes those fixes (exposure from the venue, amend/modify through check_order, cancel_all that really clears the mock, reused order group, daily loss in the main loop, shutdown without close-position). If your copy predates that, paste the Oct 25 follow-up from the git history of this page, or just re-paste the current one-shot into a clean bot folder.

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.

Add hard risk limits and a three-layer kill switch to this existing trading
bot. Read the codebase first and list every place that can create, amend,
modify, replace or close an order. Show me that list before changing code.
(If there is no bot in this folder yet, stop and tell me. Don't invent one.)
Use only endpoints documented at https://docs.kalshi.com and
https://docs.polymarket.us. Ask me if unsure.
Facts to get right (checked Nov 6, 2026):
- Kalshi creates orders with POST /portfolio/events/orders and cancels all
  with DELETE on the same path, so match method AND path. Amend is
  POST /portfolio/events/orders/{id}/amend; its count is the new total.
- Kalshi public market GETs return yes_bid_dollars / yes_ask_dollars as
  dollar strings. Prefer those; legacy yes_bid / yes_ask may be null.
- Polymarket US: public data on https://gateway.polymarket.us (no key);
  signed calls on https://api.polymarket.us. Read bids from
  bestBidQuote.value when present. Modify is a cancel-replace.
  POST /v1/order/close-position is a market order with no slippage limit
  unless you set one.
- Kalshi GET /markets filters by status=open ("active" as a filter value
  returns 400); individual market objects may still show status "active".

1) limits.json + risk.py
   - max_contracts_per_order, max_open_exposure_usd, max_daily_loss_usd,
     max_orders_per_minute, allowed_markets (tickers and slugs).
   - check_order(action, order, state) raises RiskError on any breach.
     Every create, amend, modify and close goes through it. Amends and
     modifies count toward max_orders_per_minute.
   - Open exposure = resting orders + open positions, read from the venue
     (or the mock) at startup and every loop. Never only an in-memory
     counter: a restart must not reset it. Kalshi: GET /portfolio/orders
     ?status=resting and GET /portfolio/positions. Polymarket US:
     GET /v1/orders/open and GET /v1/portfolio/positions.
   - A test walks the code (ast) and fails if any function that sends an
     order request (create, amend, modify, batch, close) skips check_order.
2) Local kill switch
   - If a file named KILL exists in the project root, or BOT_KILL=1, refuse
     every order action and log "KILL ACTIVE" each loop. Check it inside
     check_order AND at the top of the main loop.
3) cancel_all.py, for both venues
   - Kalshi: list GET /portfolio/orders?status=resting, then DELETE
     /portfolio/events/orders (204, no body), then list again. If we have
     an order group, also PUT /portfolio/order_groups/{id}/trigger so
     Kalshi rejects new orders in it until I reset it. Skip the trigger
     only with --no-trigger (used by a normal shutdown).
   - Polymarket US: POST /v1/orders/open/cancel with {"slugs": []}, then
     GET /v1/orders/open. canceledOrderIds isn't proof; the re-list is.
   - Print before, cancelled and after for each venue. Exit 1 if
     anything is still resting.
   - With no keys, run against the bot's local mock and really cancel
     there, so the drill shows "after: 0". Print each request too.
4) Kalshi order group
   - Create one with POST /portfolio/order_groups/create
     (contracts_limit = order_group_contracts_limit), save its id in
     state.json, and reuse it on restart; GET it first to check it still
     exists. Pass order_group_id on every Kalshi order. If there's no
     group, or it has been triggered, refuse to start until I reset it.
5) Daily loss stop
   - PnL = realized + unrealized, open positions marked at the best bid.
     Save PnL at the first loop of each local day in state.json; daily
     loss = that minus PnL now. Compute it every loop from the venue (or
     the mock), not only when a fill handler runs.
   - At max_daily_loss_usd: create KILL, run cancel_all, log it. Only a
     human deletes KILL.
6) Shutdown: on Ctrl-C or SIGTERM, run cancel_all --no-trigger, print
   whether anything is still resting, exit. Positions stay open. Never
   send a close-position or market order automatically.
7) Tests for every limit, KILL, amend/modify checks, exposure after a
   restart, the daily loss stop firing from the main loop, and cancel_all
   on the mock. Add pytest.ini with `pythonpath = .`. Run them.

Don't change the strategy logic. Show me a diff summary when done.

How do you build it, step by step?

  1. Commit your bot first so you can see exactly what changes. This recipe retrofits an existing bot. Don't have one? Build the Kalshi AI Trading Bot first and run this prompt in that folder.
  2. Paste the prompt into your AI coding tool. Check its list of order paths before it changes anything: amends, modifies and closes count, not just new orders.
  3. Set limits you'd be fine losing entirely. Then halve them.
  4. Run the tests. Then delete check_order from one amend function and run them again. The ast test should fail; if it doesn't, it isn't checking amends.
  5. Drill restarts: run the bot, stop it with orders resting, start it again. Exposure should start where it left off, not at $0.
  6. Drill the kill switch (no keys? it runs on the mock): touch KILL, confirm no new orders, run python cancel_all.py and look for "after: 0" on both venues. With real keys, also check the venue UI.
  7. Drill the daily-loss stop in a copy: set a $1 limit, seed a losing position in the mock, and confirm the main loop writes KILL and cancels everything.
  8. Write your stop procedure on a sticky note: touch KILL → python cancel_all.py → check the venue UI → revoke the API key if anything looks wrong.

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

Test every layer before any live use:

  • Kalshi: run the drills on the demo exchange (https://external-api.demo.kalshi.co/trade-api/v2) with demo keys, including a deliberately low order_group_contracts_limit and a manual trigger. We haven't run these against demo ourselves yet, so check that each call does what the docs say before trusting it.
  • Polymarket US: there's no public demo exchange, so drill the local layers (KILL file, limits, daily-loss stop) against your paper ledger. Test cancel-all live only with a single tiny resting limit order far from the market, when you're ready.

Time yourself. You want "something's wrong" → "everything cancelled" in under 30 seconds.

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

Frequently asked questions

What is a kill switch for a trading bot?

A fast, reliable way to stop a bot from placing new orders and cancel the ones already resting. Good setups have a local switch (a file or flag the bot checks before every order), a cancel-all command using the venue's API, and if available, a server-side limit like Kalshi order groups.

What are Kalshi order groups?

A Kalshi feature that tracks fills for a group of orders in a rolling 15-second window. If fills exceed the group's contracts limit, Kalshi cancels all resting orders in the group and rejects new ones until you reset it.

How do I cancel all orders on Kalshi via the API?

Send a signed DELETE /portfolio/events/orders request. It cancels resting event-market orders across exchange shards, and Kalshi notes orders placed in the following minute may also be cancelled.

How do I cancel all orders on Polymarket US via the API?

Send a signed POST https://api.polymarket.us/v1/orders/open/cancel, which cancels all your open orders, optionally filtered by market. Pure cancels aren't affected by the 5-second latency stopgap that can reject new orders.

Why shouldn't the bot close positions when it shuts down?

Closing means a market order, and on Polymarket US close-position has no slippage limit unless you set one. In a thin or fast market that can cost more than the position. Cancelling resting orders stops new risk; deciding what to do with open positions is a job for a person looking at the book.

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