Build a Polymarket Bot with Claude Code (Paper Mode + Guardrails)

Polymarket US Paper / demo first

Verified working on live data in paper mode, Nov 27, 2026. Order preview and real orders need your own keys and were not run.

Starter code on GitHub: github.com/lazyclaw137-ship-it/polymarket-paper-trading-bot. The code from the verified run, MIT licensed, with no keys included.

Short answer: You can build a Polymarket US bot with Claude Code by having it write a bot that runs in paper mode by default: it simulates fills locally against the live public order book and can validate orders with POST /v1/order/preview without placing them. Polymarket US has no public demo exchange, so a local paper ledger, hard position limits, a kill switch and a locked live mode are the safe way to start.

What are the key facts?

  • Polymarket US has no public demo exchange for retail API users, so paper mode here means: simulate fills locally against the live public order book, and optionally call POST /v1/order/preview (body wrapped as {"request": order}) to validate an order without placing it.
  • Market data comes from https://gateway.polymarket.us with no key. Live orders go to POST https://api.polymarket.us/v1/orders.
  • Order fields: marketSlug, intent (ORDER_INTENT_BUY_LONG, ORDER_INTENT_SELL_LONG, ORDER_INTENT_BUY_SHORT, ORDER_INTENT_SELL_SHORT), type (ORDER_TYPE_LIMIT/ORDER_TYPE_MARKET), price: {value, currency: "USD"}, quantity, tif (e.g. TIME_IN_FORCE_IMMEDIATE_OR_CANCEL), and manualOrderIndicator, which the docs say is required (MANUAL_ORDER_INDICATOR_AUTOMATIC for a bot).
  • Send an Idempotency-Key header (non-empty, up to 255 bytes) with every POST /v1/orders: a retry with the same key returns the recorded response for 24 hours instead of placing a second order. The docs briefly said idempotencyKey, which the API ignores. Still record each order locally before sending.
  • price.value always refers to the YES (long) side, even when buying NO, and must be between 0.01 and 0.99. An out-of-range order still gets an order ID but never fills.
  • Read each market's orderPriceMinTickSize and minimumTradeQty before ordering. Don't assume them.
  • Cancel everything: POST /v1/orders/open/cancel.
DifficultyIntermediate
Time2–3 hours
Cost$0 API · your AI tool subscription
Works withClaude Code, Cursor, ChatGPT / Codex

What will you build?

A Polymarket US bot skeleton that watches markets you choose, runs your rule, and records simulated fills in a local paper ledger. A live mode exists but is locked behind a flag, a typed confirmation and hard limits.

Who is it for?

Builders who want a real bot structure (data → rule → risk check → order) without risking money on day one.

Not for: Anyone looking for a strategy that makes money. We don't provide one, and nobody honest can promise one.

What happened when we rebuilt it from this prompt

On Nov 27, 2026 we built this bot from scratch again from the prompt below and ran it in paper mode on live Polymarket US data: Vancouver, Nashville and Miami to win MLS Cup, plus a UFC title market priced far above the target. Then we broke it on purpose with a fake server (429s, 5xx errors, a hung connection, an HTML page instead of JSON), restarts, a decided market, the kill switch and each limit. The guardrails all held. The thing that had gone stale was the fee note.

The market's fee field changed under us. Every market's feeCoefficient now reads 0.11. Polymarket US raised its app and website taker tiers at 9:45 PM ET on Nov 25 (Tier 1 went from 0.095 to 0.11). Bot trades through the API still pay a flat 0.0695 through Dec 31, with 70% of it rebated. Our older prompt (before Nov 23) told the bot to use feeCoefficient as its fee rate, so a bot built from it now silently charges itself the app rate: 2 cents instead of 1 on a one-contract buy at 0.289, and $2.26 instead of $1.43 on 100 contracts at 0.29. The prompt now says to log that field but never use it as the rate. If you built before Nov 27, paste the fee fix below.

The bot's log from the live run, first loop (timestamps and a few fields trimmed):

{"event": "market", "slug": "tec-mls-winner-2026-11-07-vwh", "feeCoefficient": 0.11, "tick": 0.001, "min_qty": 1, "paper_theta": 0.0695}
{"event": "paper_fill", "slug": "tec-mls-winner-2026-11-07-vwh", "seen": {"bid": 0.288, "offer": 0.289}, "fills": [[0.289, 1.0]], "fee": 0.01, "rebate_due": 0.007}
{"event": "no_order", "slug": "aachc-ufc-lightw-2026-12-31-champ-jusgae", "seen": {"bid": 0.92, "offer": 0.95}, "reason": "best offer 0.95 > target 0.3"}
{"event": "ledger", "cash": 99.395, "fees_paid": 0.03, "rebates_due": 0.021, "open_exposure_usd": 0.575, "daily_loss_usd": 0.033}

After that, every loop logged "already hold YES here" for the three MLS markets. The 3.3 cents of "daily loss" is the spread plus fees on three fresh one-contract positions, marked at the bid.

What the break-it tests showed:

  • 429 with Retry-After: 3, twice: waited 3 s each time, then traded normally (6.4 s total). A 429 that never stops: gave up after 5 tries, logged it, and placed nothing that loop.
  • One 502: retried after 1 s and carried on. A 500 on every request: gave up after 5 tries (about 15 s per request) and skipped the loop.
  • A server that hangs: each request timed out after 10 s and was retried, so one market took about 65 s to give up on. No orders went out, but with several markets a full outage makes each loop take minutes. If that bothers you, ask for the loop to stop fetching after the first failure.
  • An HTML page with a 200: one clear line ("200 but not JSON: 'maintenance'"), no crash, no orders.
  • Restart: the day's loss ($0.022) and the 2-orders-a-minute count survived a restart; the third order was still refused right after it.
  • Decided market: a held contract bought at 0.028 settled at 1.00 (+$0.972), and its exposure dropped to zero.
  • Kill switch, exposure cap, daily-loss cap, missing limits, no keys: each refused cleanly with a one-line reason. --preview and --live without keys exit with a message; --live without a terminal refuses.

From the Oct 26 rebuild. On Oct 26, 2026 we found three problems that the prompt now covers. A restart wiped out the day's losses ($0.048 went to $0.00) and reset the order counter (a third order went through 8 seconds after a restart, under a 2-a-minute cap); the prompt now saves both in paper_ledger.json. A decided market showed up as a total loss: a Chargers win from 2025 had an empty book with state MARKET_STATE_EXPIRED and a settlement price of 1.00, and marking at the bid valued it at $0. The bot now settles a held market at settlementPx once its status is MARKET_STATUS_RESOLVED. Open markets carry a settlementPx too (Tampa Bay's was 0.09 while it traded at 0.167), so never use it to price an open position.

Other notes:

  • Real 429s are rare. On Oct 26, 80 parallel requests to the public API all came back 200. Another of our builds hit Cloudflare 429s on Oct 25 with an HTML body and Retry-After: 10, which is why the prompt waits for Retry-After and never parses the 429 body.
  • Quiet books. Over about 12 minutes on Nov 27, not one of the four books moved. A short paper run tests the plumbing, not a strategy.

From the first rebuild (Oct 24). Daily loss was computed with only some books fetched. A $0.27 real loss looked like $1.10 to the risk check, and $2.18 during a data error, which would have tripped a $2 cap. The placeholder rule also bought again on every loop: 39 of 80 log lines were rate-limit rejections. Both are fixed in the prompt. Two smaller notes from that run: at one contract, the spread costs more than the $0.01 fee, and ticks on these markets are 0.001, not 0.01.

Built this before Nov 27? Paste the fee fix into the same Claude Code session. If your build is from before Oct 26, paste the Oct 26 fixes too, and before Oct 24, the Oct 24 fixes as well.

Nov 27 fee fix:

Fee fix, with tests:
1. In paper.py, default theta = 0.0695: from Nov 21 to Dec 31, 2026
   every taker trade placed through the Polymarket US API pays 0.0695
   at any volume. Do not use the market's feeCoefficient as theta; it
   shows the app/web Tier 1 rate (0.11 since Nov 25, 2026). Keep
   logging it.
2. Log a 70% rebate of each fee separately (rebates_due in the ledger
   summary); don't net it at the fill.
3. Test the five worked examples on https://docs.polymarket.us/fees:
   100 contracts at 0.10, 0.65, 0.30, 0.90, 0.50 cost 0.63, 1.58,
   1.46, 0.63, 1.74.
Show me the diff first.

Oct 26 fixes:

Three fixes, with tests:
1. Save the UTC date, the day-start equity and the send times of the last
   minute's orders in paper_ledger.json, and reload them on start, so a
   restart doesn't reset the daily-loss limit or orders-per-minute.
2. Add stats.settlementPx to data.book(). When a held market's book state
   is MARKET_STATE_EXPIRED or MARKET_STATE_TERMINATED, fetch
   GET /v1/market/slug/{slug}. If status is MARKET_STATUS_RESOLVED, settle
   the position (YES gets px, NO gets 1 - px) into cash and realized PnL.
   If not, treat it as a missing book. Never mark an open market at
   settlementPx.
3. On a 429, wait at least the Retry-After header; don't parse the body
   as JSON.
Show me the diff first.

Oct 24 fixes:

Two fixes, with tests:
1. In bot.py, fetch the book for every configured market before deciding
   anything. Daily loss = max(0, equity at the first loop of the UTC day -
   equity now), with equity = cash + every position marked at the bid from
   THIS loop's books. If a held market has no book this loop, log it and
   place no orders.
2. In strategy.py, only propose a buy if the market state is
   MARKET_STATE_OPEN and I don't already hold YES on that market.
Also log the ledger summary only when it changes. Show me the diff first.

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.

Build a Polymarket US trading bot in Python 3.11+ (requests, cryptography,
pytest only) that runs in PAPER MODE by default. Use only endpoints documented
at https://docs.polymarket.us. If you are unsure an endpoint or field exists,
ask me instead of guessing.

Read CLAUDE.md (the BotCookery safety rules) first and follow it. If you are
not allowed to write under .claude/, tell me and I will approve it; do not
work around it.

Architecture (one file per module):
- config.py   : loads config.toml (markets = list of slugs, poll_seconds,
                target_price) and limits.json (max_contracts_per_order,
                max_open_exposure_usd, max_daily_loss_usd,
                max_orders_per_minute). Fail closed if a limit is missing.
- data.py     : public market data from https://gateway.polymarket.us, no keys:
                GET /v1/markets?active=true&closed=false&limit=20 (listing),
                GET /v1/market/slug/{slug} (response {"market": {...}}; read
                orderPriceMinTickSize and minimumTradeQty; cache 5 min),
                GET /v1/markets/{slug}/book (response
                {"marketData": {"bids":[{"px":{"value"},"qty"}],"offers":[...],
                "state"}}; px.value and qty are strings; prices are YES-side),
                GET /v1/markets/{slug}/bbo.
                Also return the book's stats.settlementPx.
                Bounded exponential backoff on 429/5xx. On a 429, wait at
                least the Retry-After header if there is one; the 429 body
                can be HTML, so don't parse it as JSON.
- strategy.py : ONE placeholder rule I will replace: "if the market state is
                MARKET_STATE_OPEN, I hold no YES on it yet, and best YES offer
                <= target_price from config, propose buying minimumTradeQty
                of YES at the best offer". Return an order body dict or None,
                plus a one-line reason. No ML, no "AI picks".
- risk.py     : check_order() enforcing every limit in limits.json plus: price
                within 0.01-0.99 AND on the market's tick, quantity a multiple
                of minimumTradeQty, no YES+NO buys on the same market
                (self-match), and a kill switch (file KILL exists or BOT_KILL=1
                => no orders). Unit-test every rule.
- paper.py    : local ledger (paper_ledger.json). Fill conservatively against
                the current book: buys lift offers at or below my limit, sells
                hit bids at or above it, at the displayed price, never more
                than displayed size, walking levels. NO intents trade the
                inverse (BUY_SHORT fills against YES bids at cost 1 - bid).
                Taker fee = theta * qty * p * (1-p). Default theta 0.0695:
                from Nov 21 to Dec 31, 2026 every taker trade placed through
                the API pays 0.0695 at any volume, and Polymarket rebates
                70% of those fees (log the rebate separately; don't net it
                at the fill). Read and log the market's feeCoefficient but
                never use it as theta: it shows the app/web Tier 1 rate
                (0.11 since Nov 25, 2026), not the API rate. Use the fee
                from the order response if one is returned. See
                https://docs.polymarket.us/fees. Rounded to $0.01 per fill
                with banker's rounding (round half to even), total for one
                order capped at the rounded cumulative fee. Test against
                the fee page's worked examples. Track cash, positions, realized
                and unrealized PnL (mark at the bid).
                Settlement: when a held market's book state is
                MARKET_STATE_EXPIRED or MARKET_STATE_TERMINATED, check
                GET /v1/market/slug/{slug}; if status is
                MARKET_STATUS_RESOLVED, close the position at the book's
                stats.settlementPx (YES gets px, NO gets 1 - px) into realized
                PnL and cash. If it isn't resolved yet, treat it like a
                missing book. Never mark an OPEN market at settlementPx; open
                markets carry one too and it can be far from the bid.
- broker.py   : LIVE adapter for https://api.polymarket.us. Ed25519: the secret
                key from env is base64; the first 32 decoded bytes are the
                seed. Headers X-PM-Access-Key, X-PM-Timestamp (ms, within 30 s
                of server time), X-PM-Signature = base64(sign(timestamp +
                METHOD + path)), e.g. path "/v1/portfolio/positions"; the body
                is not signed. Methods: preview_order (POST /v1/order/preview,
                body wrapped as {"request": order}), create_order
                (POST /v1/orders), cancel_all (POST /v1/orders/open/cancel,
                body {"slugs": []}), positions (GET /v1/portfolio/positions),
                balances (GET /v1/account/balances).
                Order body: marketSlug, type ORDER_TYPE_LIMIT, price
                {value, currency "USD"} (ALWAYS the YES price: buying NO at
                0.83 sends 0.17), quantity (number), tif
                TIME_IN_FORCE_IMMEDIATE_OR_CANCEL, intent, and
                manualOrderIndicator MANUAL_ORDER_INDICATOR_AUTOMATIC.
- bot.py      : main loop. Default --paper. --preview calls the preview
                endpoint with my key but never places orders (exit with a
                clear message if keys are missing). --live requires the flag,
                keys, AND typing "I accept the risk"; refuse if stdin is not a
                terminal. Every loop: kill-switch check -> fetch the book for
                EVERY configured market first (if any fetch fails, log it and
                place nothing this loop: you can't mark positions) -> strategy
                -> risk -> paper/preview/live -> log to logs/decisions.jsonl.
                Daily loss passed to risk = max(0, equity at the first loop of
                the UTC day - equity now), where equity = cash + every position
                marked at the bid using THIS loop's books. Log the ledger
                summary only when it changes.
                Restarts must not reset the limits: save the UTC date, the
                day-start equity and the send times of the last minute's
                orders in paper_ledger.json, and reload them on start.
- cancel_all.py : one command that calls cancel-all in live mode.

Rules:
- Keys only from env vars (POLYMARKET_KEY_ID, POLYMARKET_SECRET_KEY).
  .env.example with blanks; .env in .gitignore; never print keys.
- Bounded exponential backoff on 429/5xx for reads and cancels. A "Global Rate
  Limit Exceeded" reject on an order is a latency stopgap, not a rate limit:
  log it, don't retry.
- Idempotency: make a new key (uuid4) per order intent, record it in
  sent_orders.json BEFORE sending, and send it as the Idempotency-Key header
  (exact spelling; "idempotencyKey" is ignored). After a timeout or 5xx,
  retry at most once with the SAME key, then reconcile with open orders and
  fills before any new order. Never send the same intent with a new key.
- pytest tests for risk.py (each rule), paper.py fills (partial, NO side,
  sells, fee examples), the YES-price inversion, the live-mode gate, broker
  signing (verify with the public key) using a fake HTTP session, daily
  loss (a held market with no book this loop must block orders, not count
  as a loss), a restart (a new Bot on the same ledger keeps the day's loss
  and the per-minute count), settlement of a resolved market at
  settlementPx, and a 429 with Retry-After.

Show me the file plan first. Then build it. Then give me the exact commands
to run it in paper mode.

How do you build it, step by step?

  1. Set up the kitchen. New folder, git init, then add the Safety Pack: save the rules file as CLAUDE.md, add the .gitignore, and add .claude/settings.json with the deny rules so Claude Code can't read your .env or key files. Claude Code will ask permission before writing under .claude/; approve it.
  2. Start Claude Code in the folder and paste the prompt. Review the file plan before it writes code. If it proposes any endpoint you can't find on docs.polymarket.us, push back.
  3. Fill in config.toml. Pick 1–3 market slugs from GET https://gateway.polymarket.us/v1/markets?active=true&closed=false&limit=20. Without closed=false, the list can include markets that have already closed. Choose markets with both a bid and an offer between 0.01 and 0.99; on Nov 27, 6 of the 20 listed didn't have that (three UFC markets had no bid at all). Set a target price for the placeholder rule.
  4. Set tiny limits in limits.json, for example 1 contract per order, $5 max exposure, $2 max daily loss, 3 orders a minute.
  5. Run paper mode with python bot.py --paper. Watch logs/decisions.jsonl. Every line should show the data it saw, what the rule proposed, and whether risk said yes or no. Expect one paper fill per market whose offer is under your target, then "already hold YES here" on every loop after that. Some markets quote below $0.01 (their tick can be 0.001); the risk check refuses those because the exchange only accepts 0.01–0.99, so a "price outside 0.01-0.99" line is the guardrail working, not a bug.
  6. Test the kill switch. While it's running, touch KILL. The next loop should log "kill switch on" and place nothing. Delete the file to resume. Also stop and restart the bot once: the daily loss in the ledger line should be the same after the restart.
  7. Replace the placeholder rule with your own logic. Keep it simple and explainable. The bot should be able to tell you in one sentence why it wanted each order.
  8. Optional preview mode. Once you have a verified Polymarket US account and API key, run python bot.py --preview. It calls POST /v1/order/preview with the order wrapped as {"request": order} to validate it and show expected fills, and it places nothing. Without keys, --preview should exit with a clear message.
  9. Only after days of clean paper logs would you even consider --live, with limits you're fine losing entirely. The typed confirmation is there to make you stop and think.

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

Level 1: local paper ledger (no account needed). paper.py simulates fills against the real public book. Be conservative: fill at the ask for buys and the bid for sells, never better, and never more than the displayed size. Mark open positions at the bid, so a fresh position shows a loss equal to the spread. Real fills are often worse than paper fills because of latency, queue position and fees, so treat paper profits with suspicion.

Fees belong in the simulation. The taker fee is Θ × contracts × p × (1 − p). From 12:01 AM ET on Nov 21, 2026 through Dec 31, 2026, every taker trade placed through the Polymarket US API pays Θ = 0.0695 at any volume, and Polymarket rebates 70% of those fees on straight trades (100 contracts at $0.50: $1.74 charged, $1.22 rebated). Trades placed in the app or website pay by taker tier, raised from 9:45 PM ET on Nov 25, 2026: 0.11 under $10,000 of trailing 30-day taker volume, 0.10 up to $50,000, 0.09 up to $250,000, and 0.0695 above that (and in a new account's first 7 days). Each market's feeCoefficient field now reads 0.11, the app Tier 1 rate (it read 0.095 until Nov 25), so don't use it as Θ for API trades. Fees are rounded to the cent with banker's rounding (round half to even). Have the AI write tests against the worked examples on the fee schedule; binary floating point can round half-cent cases the wrong way, so round with Decimal and ROUND_HALF_EVEN.

Level 2: order preview (needs a key, places nothing). POST /v1/order/preview checks your parameters against the exchange (tick size, minimum quantity, price validity) and returns what it expects would happen. It's the best way to catch "valid in my head, rejected by the exchange" bugs before going live.

What to review before you go further:

  • At least a week of decisions.jsonl with no surprise orders.
  • Every rejected order has a clear reason.
  • Paper PnL includes fees.

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

Frequently asked questions

Can Claude Code build a Polymarket trading bot?

Yes. Claude Code can write the whole structure (data, strategy, risk checks, broker adapter) from a good prompt. It can't make the strategy profitable, and it will make mistakes, so run it in paper mode and read the code, especially the parts that touch keys and orders.

Does Polymarket US have a paper trading or demo mode?

There's no public retail demo exchange documented. The practical approach is a local paper ledger that simulates fills against the live public order book, plus the POST /v1/order/preview endpoint, which validates an order and shows expected fills without placing it.

Can I run a Polymarket bot from the US?

US residents should use Polymarket US, the CFTC-regulated exchange, which requires identity verification before you can create API keys. International Polymarket is close-only for the US, and using a VPN to get around that breaks its terms.

Should I buy a Polymarket bot instead of building one?

Be careful. Many "bots for sale" are scams or repackaged public GitHub code, and any repo you run can hide code that steals keys. If you use someone else's code, audit it first. See our GitHub audit recipe.

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