Build a Polymarket Bot with Python: Step-by-Step
A complete Python tutorial for building an automated Polymarket trading bot using the official py-clob-client library.
Why Python for Polymarket Bots?
Python is the most popular language for Polymarket bot development, and for good reason. The ecosystem is unmatched for this use case:
- Official client library —
py-clob-clientis Polymarket's maintained Python SDK, handling authentication, signing, and API communication - Data analysis — Libraries like pandas and numpy make it easy to analyze market data, backtest strategies, and calculate risk metrics
- Async support — Python's asyncio enables concurrent WebSocket connections and non-blocking I/O, essential for real-time bots
- Rapid prototyping — Python's concise syntax lets you iterate quickly, testing ideas before committing to production code
- Community — Most Polymarket bot examples and tutorials online use Python, giving you a large reference base
Environment Setup
Create a Virtual Environment
Always isolate your bot's dependencies in a virtual environment. Run python -m venv polybot-env and activate it. This prevents dependency conflicts with other Python projects on your system.
Install Dependencies
Install the core libraries: pip install py-clob-client web3 python-dotenv websockets aiohttp. Pin versions in a requirements.txt file for reproducible deployments.
Configure Environment Variables
Create a .env file with your credentials: POLY_API_KEY, POLY_API_SECRET, POLY_PASSPHRASE, and PRIVATE_KEY. Add .env to .gitignore immediately.
Initializing the CLOB Client
The ClobClient class is your primary interface to Polymarket. Initialize it with your credentials and chain configuration:
Client Configuration
The client requires four parameters: the API host URL, your private key for signing orders, the chain ID (137 for Polygon mainnet), and your API credentials (key, secret, passphrase). The client handles all cryptographic signing internally — you never need to manually construct EIP-712 signatures.
After initialization, verify connectivity by calling the server time endpoint. If this succeeds, your authentication is working correctly.
Fetching Market Data
Before your bot can trade, it needs to understand the available markets and their current state:
Listing Markets
The get_markets() method returns paginated market data. Each market object contains the question text, category, resolution source, end date, and token IDs for each outcome. Store market metadata locally and refresh periodically to catch new markets.
Reading the Order Book
The get_order_book() method returns the current bids and asks for a specific token ID. Parse the response to determine the best bid (highest buy price), best ask (lowest sell price), mid-market price, and available liquidity at each price level.
Tracking Prices Over Time
For strategies that depend on price trends, store historical prices in a local database (SQLite is sufficient for most bots). Record the mid-market price at regular intervals (every 1-5 minutes) and use pandas to calculate moving averages, volatility, and other technical indicators.
Building the Trading Logic
The trading logic is the brain of your bot. Here's a framework for a simple copy trading bot:
Wallet Monitoring
Identify target wallets to copy by analyzing the Polymarket leaderboard or using on-chain analytics. Your bot monitors these wallets for new trades by polling the API or subscribing to on-chain events.
When a target wallet places a trade, extract the market, side (buy/sell), and size. Apply your position sizing rules (e.g., copy at 10% of the target's size, or use a fixed dollar amount per trade).
Order Construction
Use the create_order() method to build an order object. Specify the token ID, side, price, and size. The client library handles nonce generation and signature creation. Before submitting, validate:
- The price hasn't moved more than your slippage tolerance since the target traded
- Your account has sufficient USDC balance
- The position doesn't exceed your per-market or total exposure limits
- You haven't already placed a duplicate order for this signal
Order Execution
Submit the order with post_order(). The API returns an order ID and initial status. Monitor the order for fills — use polling or WebSocket subscription to track whether the order fills completely, partially, or expires unfilled.
Implementing Risk Controls
Risk management code should be written before trading logic, not after. Every trade must pass through risk checks:
Risk Management Module
- Position sizer — Calculate appropriate trade size based on account balance, existing exposure, and per-trade risk limits
- Exposure tracker — Maintain a real-time view of total capital deployed, per-market exposure, and unrealized P&L
- Circuit breaker — Halt trading if daily losses exceed threshold, error rates spike, or consecutive losses accumulate
- Order validator — Final check before every order submission: correct market, correct side, reasonable size, acceptable price
Async Architecture
Production bots need to handle multiple concurrent tasks: monitoring wallets, processing market data, executing trades, and checking risk limits. Python's asyncio library enables this with cooperative multitasking:
- Main event loop — Coordinates all async tasks and handles graceful shutdown
- WebSocket listener — Maintains persistent connection to Polymarket for real-time data
- Trade processor — Async queue that processes trade signals sequentially to prevent race conditions
- Health monitor — Periodic task that checks system health and sends status updates
Use asyncio.gather() to run these tasks concurrently within a single Python process. For CPU-intensive work (like backtesting), use ProcessPoolExecutor to avoid blocking the event loop.
Data Persistence
Your bot needs persistent storage for trade history, position tracking, and configuration. SQLite is the simplest option for single-instance bots:
- trades table — Every order placed: timestamp, market, side, size, price, fill status, P&L
- positions table — Current open positions with entry price, size, and unrealized P&L
- alerts table — Active price alerts and their trigger conditions
- config table — Runtime configuration (target wallets, risk parameters) that can be updated without restarting
Deployment
Package your bot for production deployment:
- Create a
Dockerfilefor containerized deployment — ensures consistent environment across development and production - Use a process manager (systemd, supervisord, or Docker's restart policy) to automatically restart on crashes
- Deploy to a cloud provider with low latency to Polymarket's API servers
- Set up log aggregation (stdout to a logging service) and monitoring dashboards
For detailed security practices during deployment, see our bot safety guide. For testing your strategy before going live, check the backtesting guide.
Want to Copy Top Polymarket Traders Automatically?
Polycool lets you follow the best wallets and copy their trades in one tap. No manual tracking needed.
Try Polycool Free →