{"slug": "build-a-polymarket-bot-with-claude-code-paper-mode-guardrails", "title": "Build a Polymarket Bot with Claude Code (Paper Mode + Guardrails)", "summary": "A developer published a step-by-step recipe on BotCookery for using Claude Code to scaffold a Polymarket US prediction-market trading bot that defaults to paper mode, simulating fills locally against the live public order book and validating orders via POST /v1/order/preview without placing them. The guide specifies a modular Python 3.11+ architecture (config, data, strategy, risk) with hard position limits, a kill switch, bounded exponential backoff on 429/5xx responses, and a live mode locked behind a flag and typed confirmation. It explicitly offers no profitable strategy, warning that \"nobody honest can promise one.", "body_md": "*Originally published on [BotCookery](https://botcookery.com/recipes/polymarket-bot-claude-code-paper-mode/), a free site of build recipes for AI-built trading and prediction-market bots. Written with AI assistance and checked against the Polymarket US docs linked below. Nothing here is financial advice, and there's no strategy in it that makes money.*\n\nYou 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.\n\n**Goal:** 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.\n\n**Who it's for:** Builders who want a real bot structure (data → rule → risk check → order) without risking money on day one.\n\n**Not for:** Anyone looking for a strategy that makes money. We don't provide one, and nobody honest can promise one.\n\n`POST /v1/order/preview` (body wrapped as `{\"request\": order}`) to validate an order without placing it.` https://gateway.polymarket.us` with no key. Live orders go to `POST https://api.polymarket.us/v1/orders`.` 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).`POST /v1/orders` after a timeout.`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.`orderPriceMinTickSize` and `minimumTradeQty` before ordering. Don't assume them.`POST /v1/orders/open/cancel`.\nPaste this into Claude Code (or Cursor, or Codex) in an empty folder:\n\n```\nBuild a Polymarket US trading bot in Python 3.11+ (requests, cryptography,\npytest only) that runs in PAPER MODE by default. Use only endpoints documented\nat https://docs.polymarket.us. If you are unsure an endpoint or field exists,\nask me instead of guessing.\n\nRead CLAUDE.md (the BotCookery safety rules) first and follow it. If you are\nnot allowed to write under .claude/, tell me and I will approve it; do not\nwork around it.\n\nArchitecture (one file per module):\n- config.py   : loads config.toml (markets = list of slugs, poll_seconds,\n                target_price) and limits.json (max_contracts_per_order,\n                max_open_exposure_usd, max_daily_loss_usd,\n                max_orders_per_minute). Fail closed if a limit is missing.\n- data.py     : public market data from https://gateway.polymarket.us, no keys:\n                GET /v1/markets?active=true&closed=false&limit=20 (listing),\n                GET /v1/market/slug/{slug} (response {\"market\": {...}}; read\n                orderPriceMinTickSize and minimumTradeQty; cache 5 min),\n                GET /v1/markets/{slug}/book (response\n                {\"marketData\": {\"bids\":[{\"px\":{\"value\"},\"qty\"}],\"offers\":[...],\n                \"state\"}}; px.value and qty are strings; prices are YES-side),\n                GET /v1/markets/{slug}/bbo.\n                Bounded exponential backoff on 429/5xx.\n- strategy.py : ONE placeholder rule I will replace: \"if best YES offer <=\n                target_price from config, propose buying the minimum quantity\n                of YES\". Return an order body dict or None, plus a one-line\n                reason. No ML, no \"AI picks\".\n- risk.py     : check_order() enforcing every limit in limits.json plus: price\n                within 0.01-0.99 AND on the market's tick, quantity a multiple\n                of minimumTradeQty, no YES+NO buys on the same market\n                (self-match), and a kill switch (file KILL exists or BOT_KILL=1\n                => no orders). Unit-test every rule.\n- paper.py    : local ledger (paper_ledger.json). Fill conservatively against\n                the current book: buys lift offers at or below my limit, sells\n                hit bids at or above it, at the displayed price, never more\n                than displayed size, walking levels. NO intents trade the\n                inverse (BUY_SHORT fills against YES bids at cost 1 - bid).\n                Taker fee = theta * qty * p * (1-p), theta = the market's\n                feeCoefficient (0.0695 standard; Table Tennis 0.10, see\n                https://docs.polymarket.us/fees), rounded to $0.01 per fill\n                with banker's rounding (round half to even), total for one\n                order capped at the rounded cumulative fee. Test against\n                the fee page's worked examples. Track cash, positions, realized\n                and unrealized PnL (mark at the bid).\n- broker.py   : LIVE adapter for https://api.polymarket.us. Ed25519: the secret\n                key from env is base64; the first 32 decoded bytes are the\n                seed. Headers X-PM-Access-Key, X-PM-Timestamp (ms, within 30 s\n                of server time), X-PM-Signature = base64(sign(timestamp +\n                METHOD + path)), e.g. path \"/v1/portfolio/positions\"; the body\n                is not signed. Methods: preview_order (POST /v1/order/preview,\n                body wrapped as {\"request\": order}), create_order\n                (POST /v1/orders), cancel_all (POST /v1/orders/open/cancel,\n                body {\"slugs\": []}), positions (GET /v1/portfolio/positions),\n                balances (GET /v1/account/balances).\n                Order body: marketSlug, type ORDER_TYPE_LIMIT, price\n                {value, currency \"USD\"} (ALWAYS the YES price: buying NO at\n                0.83 sends 0.17), quantity (number), tif\n                TIME_IN_FORCE_IMMEDIATE_OR_CANCEL, intent, and\n                manualOrderIndicator MANUAL_ORDER_INDICATOR_AUTOMATIC.\n- bot.py      : main loop. Default --paper. --preview calls the preview\n                endpoint with my key but never places orders (exit with a\n                clear message if keys are missing). --live requires the flag,\n                keys, AND typing \"I accept the risk\"; refuse if stdin is not a\n                terminal. Every loop: kill-switch check -> data -> strategy ->\n                risk -> paper/preview/live -> log to logs/decisions.jsonl.\n- cancel_all.py : one command that calls cancel-all in live mode.\n\nRules:\n- Keys only from env vars (POLYMARKET_KEY_ID, POLYMARKET_SECRET_KEY).\n  .env.example with blanks; .env in .gitignore; never print keys.\n- Bounded exponential backoff on 429/5xx for reads and cancels. A \"Global Rate\n  Limit Exceeded\" reject on an order is a latency stopgap, not a rate limit:\n  log it, don't retry.\n- The order API has no client order id, so do idempotency locally: record a\n  key (hash of order + nonce) in sent_orders.json BEFORE sending, never\n  re-send a recorded key, and never auto-retry POST /v1/orders after a\n  timeout or 5xx (outcome unknown; check open orders instead).\n- pytest tests for risk.py (each rule), paper.py fills (partial, NO side,\n  sells, fee examples), the YES-price inversion, the live-mode gate, and\n  broker signing (verify with the public key) using a fake HTTP session.\n\nShow me the file plan first. Then build it. Then give me the exact commands\nto run it in paper mode.\n```\n\n`git init`, then add the `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.` config.toml`.` 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. Set a target price for the placeholder rule.`limits.json`, for example 1 contract per order, $5 max exposure, $2 max daily loss, 3 orders a minute.`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. 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.`touch KILL`. The next loop should log \"kill switch on\" and place nothing. Delete the file to resume.`python bot.py --preview`. It calls `--preview` should exit with a clear message.`--live`, with limits you're fine losing entirely. The typed confirmation is there to make you stop and think.\n**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.\n\n**Fees belong in the simulation.** The taker fee is `Θ × contracts × p × (1 − p)` with Θ = 0.0695 on standard markets, 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](https://docs.polymarket.us/fees); binary floating point can round half-cent cases the wrong way, so round with `Decimal` and `ROUND_HALF_EVEN`.\n\n**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.\n\n**What to review before you go further:**\n\n`decisions.jsonl` with no surprise orders.`0.17`. Write a unit test for this; it's the most common way these bots buy the wrong thing.`manualOrderIndicator: MANUAL_ORDER_INDICATOR_AUTOMATIC` on every bot order. The docs mark the field as required.\nYes. 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.\n\nThere'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.\n\nUS 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.\n\nBe 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](https://botcookery.com/recipes/audit-kalshi-polymarket-bot-github-repo/).", "url": "https://wpnews.pro/news/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails", "canonical_source": "https://dev.to/botcookery/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails-3mn1", "published_at": "2026-10-23 16:04:06+00:00", "updated_at": "2026-10-23 16:12:53.977373+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools"], "entities": ["Polymarket", "Claude Code", "BotCookery", "Cursor", "Codex", "Anthropic"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails", "markdown": "https://wpnews.pro/news/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails.md", "text": "https://wpnews.pro/news/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails.txt", "jsonld": "https://wpnews.pro/news/build-a-polymarket-bot-with-claude-code-paper-mode-guardrails.jsonld"}}