Build a Polymarket bot: architecture for scanners, sizing, execution
A developer's guide to building a Polymarket bot: scanner, risk sizing, executor, and monitoring. Practical architecture and API references.
Build a Polymarket bot: scanner, sizing, execution, monitoring
This guide shows how to build a Polymarket bot that continuously scans markets, sizes opportunities, executes through the CLOB, and monitors performance. It focuses on architecture and developer patterns you can implement using Polymarket's public APIs and the Relayer model.
Key takeaways
- Architect the bot as four independent services: scanner, sizer, executor, and monitor.
- Use Polymarket's Gamma and CLOB APIs for listings and order placement; WebSocket for real-time book updates.
- Prefer FAK market orders for arbitrary-speed execution but always account for slippage and fees.
- Instrument monitoring and fast kill switches for oracle disputes, settlement delays, or unexpected fills.
Why this structure
Trading systems are easier to reason about when responsibilities are separated. A scanner finds candidate edges, a sizer converts edge into a position, an executor places orders via the CLOB, and a monitor ensures correctness and safety. This separation lets you scale, test, and reason about latency and risk independently.
H2: Data sources and APIs
Start by wiring these Polymarket endpoints into your services:
- Gamma (market metadata): https://gamma-api.polymarket.com — markets, events, tags, series. Use pagination with after_cursor; avoid offset.
- CLOB (order book & trading): https://clob.polymarket.com — orderbook reads are public; trading requires API key + HMAC. The CLOB SDKs handle order placement.
- Market WebSocket (real-time book): wss://ws-subscriptions-clob.polymarket.com/ws/market — subscribe for book, price_change, best_bid_ask, and tick_size_change. PING every 10s.
- Data API (positions, open interest): https://data-api.polymarket.com for post-trade analytics.
Design note: combine Gamma listings with the WebSocket feed for efficient live scanning. Respect Gamma rate limits (e.g., /markets caps) and CLOB key requirements for order placement.
H2: Scanner — finding candidate opportunities
Function
The scanner discovers opportunities matching your strategy: intra-market binary spreads, multi-outcome sums, or endgame patterns. It should be stateless, horizontally scalable, and focused on calculating raw edges.
Inputs and cadence
- Subscribe to the Market WebSocket with custom_feature_enabled: true to receive best_bid_ask and tick changes.
- Backfill with Gamma /markets when you first encounter a new instrument to get metadata and outcomes.
- Maintain a small in-memory view of best asks/bids for each outcome.
Edge computation
- Binary intra-market: compute edge = 1.00 - (bestAsk(YES) + bestAsk(NO)). Positive edge is a candidate.
- Multi-outcome: edge = 1.00 - sum(bestAsk(outcomes)).
Thresholds and filters
- Minimum edge threshold (e.g., > configured cents) to cover taker fees and execution risk.
- Minimum liquidity checks: depth at best ask must satisfy minimum fill size.
- Tick-size awareness: account for tick_size_change events — price granularity may change to $0.001 near extremes.
H2: Sizing — risk and capital allocation
Goals
Sizing turns a raw edge into an order plan: how many shares to buy per outcome, and how to split across orders to limit slippage.
Components
- Exposure caps: per-market and global pUSD exposure limits.
- Depth-limited sizing: compute the cumulative volume available at successive price levels on the ask side; only size to the volume that keeps expected slippage within tolerance.
- Fee allowance: subtract expected taker fee (variable, up to 1.8% in some categories) from the gross edge before deciding to trade.
Practical pattern
- Start with conservative fills: prefer multiple small FAK market orders rather than a single large order unless you control the book.
- If you buy a complete set via CTF split/merge flows, include the cost of split/merge gas (handled by the Relayer) and potential rounding due to tick size.
H2: Executor — placing orders and handling fills
Order types and constraints
- Use the CLOB trading endpoint for order placement: https://clob.polymarket.com. The CLOB SDK and Relayer manage wallet deployment, approvals, and order signing.
- For speed, use FAK (Fill-And-Kill) market orders where appropriate. FAKs execute immediately or cancel; they help avoid lingering exposure but can partial-fill.
Execution flow
- Prepare trade intent: list of outcome token ids and target quantities returned by the sizer.
- If executing multi-outcome complete-set, you may instead perform a CTF split (mint a complete set) and then sell legs — the Relayer and SDK abstract CTF ops.
- Submit orders via the CLOB trading API with proper attribution headers if you are part of the Builder Program.
- Observe fills from the WebSocket last_trade_price and best_bid_ask updates or from CLOB trade responses.
Safety and reconciliation
- Track partial fills and cancel remainder or re-price immediately.
- Reconcile on-chain CTF balances (via Data API) after fills to ensure you actually hold the outcome tokens you expect.
- Implement idempotency keys and nonce handling for order retries.
H2: Monitoring and operational safety
What to monitor
- Fill rates, average slippage versus expected, realized edge after fees.
- Latency between WebSocket updates and order submission.
- Unusual events: UMA disputes, tick_size_change, marketplace-wide outages.
Alerts and kill-switches
- Automated soft kill: pause new order placement when net realized P&L dips below a threshold or when fill slippage exceeds limits.
- Hard kill: immediately stop all traffic if UMA reports a dispute for a market you hold positions in, or if the Relayer signals settlement issues.
Audit logs and observability
- Store all order intents, raw market snapshots, and executed fills. Use these logs for post-mortem and backtesting.
- Tag logs with market id, condition_ids, and request ids to match Gamma and CLOB records.
H2: Builder Program, credentials, and rate limits
If you plan to route orders with attribution, join the Builder Program and manage keys via Polymarket settings. Builder tiers control daily relayer limits and rewards. For trading via the CLOB you will need API key + HMAC and must respect rate limits and relayer quotas.
H2: Common risks and mitigations
Never assume the mathematical edge is guaranteed. Risks to account for:
- Resolution risk: UMA disputes can pause or alter payouts.
- Slippage and partial fills: FAKs can partially fill; plan for leftover exposure.
- Fees: taker fees vary by category and can erode small edges (Geopolitics is fee-free).
- Settlement timing: redeem/merge timing and oracle resolution delays can hold capital.
- Smart-contract or Relayer failures: instrument fallbacks and human alerting.
How this affects your trading
Design your bot so that every trade unit is small, observable, and reversible within your risk limits. Conservative sizing, rapid monitoring, and clear kill conditions reduce tail risk. Use the Gamma and CLOB endpoints for deterministic market state and prefer FAK orders for fast execution, but always measure realized slippage against expectations.
Closing
The architecture above gives a pragmatic blueprint to build a Polymarket trading bot: a high-throughput scanner, conservative sizer, robust executor using the CLOB and Relayer, and layered monitoring. Start small, instrument aggressively, and iterate on sizing and filters as you accumulate live data.
Frequently asked questions
Which APIs should I use to get market listings and live book data?
Use https://gamma-api.polymarket.com for market metadata (/markets) and wss://ws-subscriptions-clob.polymarket.com/ws/market for real-time order book and best_bid_ask events. Use https://clob.polymarket.com for order-book reads and trading; reads are public but trading requires API key + HMAC.
Should I use limit orders or market (FAK) orders for arbitrage?
FAK (Fill-And-Kill) market orders are commonly used for speed and to avoid lingering exposure. They can partial-fill, so design sizing and reconciliation accordingly. The CLOB SDK exposes helpers for creating FAK market orders.
How do I account for fees when sizing trades?
Subtract expected taker fees from your gross edge before trading. Taker fees vary by category (0% to 1.8% currently). Use a net-edge threshold that covers fees plus expected slippage and monitoring buffers.
What monitoring is essential for a live bot?
Monitor fill rates, realized slippage, latency, UMA dispute notices, tick_size_change events, and Relayer health. Implement soft and hard kill-switches for large slippage, P&L drawdowns, or oracle disputes.
Can I route orders through the Builder Program?
Yes. The Builder Program lets third parties route orders with attribution and earn builder fees. Tiers control daily relayer limits and rewards; credentials are obtained at polymarket.com/settings.
參考術語
相關指南
僅作教育用途。非財務、法律或稅務建議。Polymarket 可能在你的司法管轄區無法使用。