---
name: polymarket-bot-builder
description: Build a production-grade trading bot for Polymarket prediction markets, end-to-end. Use this skill whenever the user mentions Polymarket, a prediction market bot, copy-trading on Polymarket, Polymarket arbitrage, a Polymarket market maker, an AI agent that trades on Polymarket, or any automated trading on prediction markets like Polymarket or Kalshi. Also use it when the user wants Claude to build a profitable trading agent, copy successful traders, find arbitrage opportunities, sweep end-game markets, or run AI analysis of binary outcome markets. The skill walks through picking a bot direction from a menu of nine proven strategies, gathering all required credentials and parameters from the user, and producing a clean, runnable Python codebase with proper risk controls, logging, and an optional live dashboard.
category: polymarket
version: 0.1.0
tags: [polymarket, prediction-market, trading-bot, arbitrage, copy-trading, market-making, clob, gamma, negrisk, kalshi, python]
recommended_pip: [py-clob-client, websockets, web3, eth-account, requests, python-dotenv, rich]
license: MIT
author: claude-code-skills
---

# Polymarket Bot Builder

A complete blueprint for shipping a real, runnable, profitable Polymarket bot. The skill is structured for Claude to drive the conversation: pick a direction, ask for everything needed, then write the code.

## What this skill produces

A self-contained Python project the user can run with `python main.py`. It will include:

- A `.env`-driven configuration (no secrets in code)
- A modular architecture (data → strategy → execution → risk → logging)
- Real risk controls (per-trade caps, daily loss limits, liquidity filters, dedup)
- Structured JSONL logs for every decision and trade
- An optional terminal-based live dashboard (preferred over a web UI for a single trader — see `references/architecture-patterns.md` on why)

## How to use this skill

The flow has four phases. Do them in order — do not skip ahead.

1. **Read the right references.** The body below covers the high-level workflow. Detailed material lives in `references/`. Always read at least `references/bot-strategies.md` (so you can present an informed menu) and `references/polymarket-apis.md` (so you know the actual endpoints) before asking the user anything substantive.
2. **Present the menu and pick a direction** with `ask_user_input_v0`. Nine strategies, summarized below, full detail in `references/bot-strategies.md`.
3. **Gather everything needed** for that specific direction with one or two `ask_user_input_v0` calls. The required fields per strategy are listed in section "Information to collect per strategy" below.
4. **Build the project.** Start from the matching `scripts/starter_*.py` template, customize it to the user's parameters, plug in the shared modules from `scripts/common/`, and write the project files into `/mnt/user-data/outputs/`. Then `present_files` the entry point.

## Step 1 — Present the bot direction menu

Open the conversation by acknowledging what the user wants, then offer the nine directions. Keep your prose short — the menu does most of the work.

The nine directions (full descriptions in `references/bot-strategies.md`):

1. **Copy-trading bot** — mirror trades from top leaderboard wallets in real time. Most popular path for beginners; works without any market modeling.
2. **Single-market rebalancing arbitrage** — buy YES+NO when their sum drops below $1. Risk-free in theory, dominated by HFT in practice — needs WebSocket and tight execution.
3. **NegRisk multi-condition arbitrage** — same idea across N mutually exclusive options (elections, championship winners). Generated $29M of the documented $40M extracted from Polymarket Apr 2024–Apr 2025.
4. **Cross-platform arbitrage (Polymarket ↔ Kalshi / Limitless)** — exploit price gaps for the same event across venues.
5. **End-game sweep bot** — buy at $0.95–$0.99 once an event is essentially decided but the market hasn't settled. Slow, capital-heavy, very high hit rate.
6. **Market-making bot** — quote both sides of an illiquid book, earn the spread + Polymarket maker rewards.
7. **AI / LLM-driven discretionary bot** — Claude (or any LLM) reads the question, researches it, returns a structured Yes/No + confidence, the bot trades when confidence is high.
8. **Whale / insider tracker (alerts only)** — watch flagged wallets, push Discord/Telegram notifications, no auto-execution. Lowest risk, often the right first project.
9. **5-minute crypto Up/Down bot** — specialized for Polymarket's BTC/ETH/SOL/XRP 5m markets, using Binance + Chainlink reference prices and a small TA model.

Use `ask_user_input_v0` with `single_select` and exactly these nine options. Keep labels short (≤ 4 words). After the user picks, immediately call `view` on the matching template (`scripts/starter_<name>.py`) and the relevant reference section before asking for parameters — this lets you ask precise, strategy-specific questions instead of a generic dump.

## Step 2 — Gather credentials and parameters

Every strategy needs the same three Polymarket credentials, plus its own parameters. Ask for the common credentials first (single message), then the strategy-specific ones. Do not ask for the private key in chat unless the user explicitly insists — instead, instruct them to paste it into the generated `.env` file themselves and confirm only that they have it.

### Common to every bot

- `POLYMARKET_PRIVATE_KEY` — the wallet's private key (Polygon). Tell the user where to get it: Polymarket → Cash → ⋯ menu → Export Private Key.
- `POLYMARKET_FUNDER_ADDRESS` — the proxy/funder address that actually holds the USDC. This is **not** the same as the EOA address derived from the private key when the user funded via the Polymarket UI. See `references/authentication.md` for the signature_type / funder mismatch trap (this is the single most common bug for new builders).
- `RPC_URL` — a Polygon RPC endpoint. QuickNode, Alchemy, or Infura free tier all work; recommend QuickNode for production.
- `BANKROLL_USD` — total capital the bot is allowed to deploy.
- `MAX_TRADE_SIZE_USD` — hard cap per single order.
- `MAX_DAILY_LOSS_USD` — bot kill-switch threshold.

### Information to collect per strategy

Below is the minimum extra ask for each direction. `references/bot-strategies.md` has the long form.

- **Copy-trading**: target wallet address(es), copy ratio (e.g. 0.05 = 5% of their notional), min trade size to mirror (skip dust), max time-to-resolution to copy (don't mirror trades on markets resolving in <24h by default).
- **Single-market arbitrage**: minimum edge after fees and gas (default 2.5%), market liquidity floor (default $5k 24h volume), order type (default FOK).
- **NegRisk arbitrage**: same as single + max number of legs per opportunity (default 4), max % of book depth to take per leg (default 5%).
- **Cross-platform**: which second venue (Kalshi / Limitless / other), Kalshi credentials if applicable, max latency between legs (default 30s).
- **End-game sweep**: price floor to enter (default 0.95), max wait time after the event to enter (default 4h), market category whitelist (politics / sports / crypto / etc).
- **Market-making**: which markets/condition_ids to make in, target spread, max inventory per side, refresh interval, whether to opt into Polymarket's reward tiers.
- **AI / LLM**: which model (default `claude-sonnet-4-7`), Anthropic API key, confidence threshold to trade (default High only), per-market budget.
- **Whale tracker**: list of wallet addresses to watch, alert channel (Discord webhook URL or Telegram bot token + chat ID), min trade size to alert on.
- **5-min crypto**: which assets (BTC / ETH / SOL / XRP), entry threshold (price delta % at T-10s that triggers a trade), strike price source (Chainlink Polygon feed or RTDS WebSocket).

When asking for these, group related questions in one `ask_user_input_v0` call (max 3 questions). If a parameter has a sane default, mention the default in the question prompt and present the choices around it instead of forcing the user to type a number — buttons are easier than typing.

## Step 3 — Build the project

Once you have everything, write the project to `/mnt/user-data/outputs/<bot-name>/`. Use this layout:

```
<bot-name>/
├── README.md            # quickstart + parameters table + safety notes
├── requirements.txt     # pinned versions
├── .env.example         # all keys, never the actual values
├── main.py              # entry point that wires everything together
├── config.py            # loads .env, validates, exposes a typed Config object
├── strategy.py          # the actual trading logic for the chosen direction
├── execution.py         # CLOB client wrapper, order placement, retries
├── risk.py              # pre-trade validation, daily loss tracking, kill switch
├── data.py              # Gamma + Data API + WebSocket helpers
├── logger.py            # structured JSONL logging
├── dashboard.py         # optional — terminal dashboard via rich.live
└── logs/                # gitignored, created on first run
```

Hard rules when generating the code:

1. **Always start from the relevant `scripts/starter_*.py` template** in this skill. Read it with `view`, then adapt — do not generate from memory. The templates encode the lessons in `references/risks-and-pitfalls.md`.
2. **Always include the shared modules** from `scripts/common/`: `clob_helpers.py`, `gamma_helpers.py`, `risk_management.py`. They're not optional — they contain the wei-conversion fix, the signature-type detection, and the dedup window logic.
3. **Always write a real README.md.** Include: install command, how to fill `.env`, what to expect on first run (token allowance approvals on EOA wallets), the kill-switch hotkey, and a "what could go wrong" section linking back to specific failure modes.
4. **Pin dependencies.** `py-clob-client==0.34.6` (or `py-clob-client-v2` if user opted in), `python-dotenv>=1.0.0`, `httpx>=0.27`, `websockets>=12.0`, `rich>=13.7` for the dashboard.
5. **Never put secrets in code.** Always `os.getenv()` through `config.py`. Always include `.env` in a `.gitignore` even if the user doesn't ask.
6. **Default to dry-run.** The bot must start in `DRY_RUN=true` mode by default. The user has to explicitly flip it to false in `.env` to place real orders. Print a giant banner on startup that says which mode it's in.
7. **Log every decision, not just trades.** Including: signals seen and skipped (with reason), API errors, rate limit hits. JSONL format, one event per line.

After generating files, copy the entry point and README into `/mnt/user-data/outputs/<bot-name>/` and call `present_files` with the `main.py` path first, README second.

## Step 4 — Show the user what to do next

End the build with a short message:

- which mode the bot ships in (always dry-run)
- the three concrete things they need to do to go live (fill `.env`, run `python -c "from execution import set_allowances; set_allowances()"` if EOA, flip `DRY_RUN=false`)
- the kill switch (Ctrl+C, or whatever you wired)
- a one-line warning that prediction-market bots can lose money and they should test with the smallest possible position first

Do **not** promise any specific return. The "$500/day" framing in the source videos is marketing — see `references/risks-and-pitfalls.md`.

## Reference files — read these as you go

- `references/bot-strategies.md` — full description of each of the nine directions, with edge sources, capital requirements, expected hit rate, and known competitors. **Always read this before step 1.**
- `references/polymarket-apis.md` — Gamma API, CLOB API (v1 + v2), Data API, the four WebSocket channels. Endpoint URLs, auth model, rate limits. **Read before step 3.**
- `references/authentication.md` — signature types, EOA vs proxy/Magic/Gnosis, the funder address trap, allowance setup for EOA wallets. **Always read this — the funder bug eats hours.**
- `references/risks-and-pitfalls.md` — what kills bots: slippage on thin books, the Feb-2026 nonce-cancel attack, oracle latency, the 2% fee on profits, gas surprises, paper-trading-vs-live divergence, copy-trading on terminal markets. **Read before you ship code.**
- `references/architecture-patterns.md` — the four-layer modular design, why CLI > web dashboard for a single trader, where to put state, JSONL log conventions.
- `references/facts-and-figures.md` — fun and useful numbers to drop into the README so the user knows what they're stepping into ($40M extracted in 12 months, 41% of conditions historically mispriced, 2.3M tracked traders, etc).

## Tone for the conversation

The user asked for "максимально правильно, красиво, быстро, удобно и профитно". Translate that into:

- **Correct**: the code actually runs, signature_type matches the funder, allowances are set, FOK is used where appropriate.
- **Beautiful**: the terminal dashboard is clean, the README has a parameters table, log lines are JSONL not f-string spaghetti.
- **Fast**: prefer WebSocket over polling, prefer one shared HTTP client over per-call sessions, prefer FOK over market orders on thin books.
- **Convenient**: dry-run by default, `.env`-driven, one-command install, one-command run, kill switch is Ctrl+C.
- **Profitable**: be honest. Profitable is a function of strategy + capital + execution + luck. The skill makes the execution part not embarrassing; the rest is on the user. Surface this in the README.

Push back gently if the user asks for something that's a known foot-gun (e.g. "copy a wallet that has 3 trades and is up 800%" — that's variance, not edge; "use NegRisk for arbitrage" — NegRisk is capital efficiency, not arbitrage, see `references/bot-strategies.md`).
