Polymarket copy trading bot construction guide
Python / TypeScript
Polygon chain
CLOB V2 API
USDC settlement
Non-custodial
How a copy trading bot works
A Polymarket Copy Trading Bot monitors designated target wallets in real time. When it detects a new trade, it automatically places a proportional mirrored order from your own wallet.
Target wallet monitoring
Continuously scans on-chain activity to detect opening, increasing, reducing, and closing positions at smart-money addresses.
Proportional position sizing
Calculates order size from your capital ratio or fixed risk parameters rather than blindly copying the original amount.
Real-time trade execution
Signs EIP-712 orders automatically and submits them through the CLOB API to minimize slippage and latency.
Position synchronization
Tracks target position changes, synchronizes your positions to remain consistent, and applies stop-loss / take-profit logic.
System architecture
A production-grade copy trading bot has five core modules with distinct roles, each independently testable and replaceable.
Target detection
Monitor
Proportional sizing
Sizer
Risk checks
Risk Mgr
On-chain ordering
Executor
| Module | Main responsibility | Technical approach | Recommended language |
|---|---|---|---|
| Monitor | Detect new target wallet trades | Data API polling + WebSocket | TypeScript |
| Sizer | Calculate proportional order amounts | Portfolio ratio or fixed risk | Python |
| Risk Manager | Safety checks before execution | Limit rules and market blocklists | Any |
| Executor | Sign and submit orders | CLOB SDK + EIP-712 | TypeScript |
| Logger | Position tracking and performance analysis | MongoDB / PostgreSQL | Any |
Polymarket API guide
Polymarket offers APIs at three different layers. The bot uses all three together.
| API | Base URL | Authentication | Main uses |
|---|---|---|---|
| Gamma API | gamma-api.polymarket.com | None required | Markets, events, search, and public trader data |
| Data API | data-api.polymarket.com | None required | Wallet activity history for copy-trade detection |
| CLOB API | clob.polymarket.com | L1/L2 authentication required | Place and cancel orders, query positions, and order books |
Python · L2 authentication header example
# Required HTTP headers (when placing an order)
headers = {
"POLY_ADDRESS": wallet_address,
"POLY_SIGNATURE": hmac_sha256_signature,
"POLY_TIMESTAMP": str(int(time.time())),
"POLY_API_KEY": api_key,
"POLY_PASSPHRASE": api_passphrase,
}Core copy-trading API endpoints
| Endpoint | Purpose | Recommended polling frequency |
|---|---|---|
GET /activity?user=0x... | Retrieve target wallet trade history to detect new orders | Every 2 seconds through REST, or use WebSocket |
GET /book?token_id=... | Retrieve a market's order book | Query in real time before ordering |
POST /order | Submit a new order, requiring L2 + EIP-712 | Event-triggered |
DELETE /order/{id} | Cancel a specific order | Event-triggered |
GET /positions | Query current positions | At startup and during periodic synchronization |
WebSocket subscriptions (recommended)
JavaScript · Subscribe to the market channel
const ws = new WebSocket('wss://ws-subscriptions-clob.polymarket.com/ws/market');
ws.onopen = () => {
ws.send(JSON.stringify({
type: "market",
assets_ids: [tokenId_1, tokenId_2] // Subscribe to multiple markets
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
// data.event_type === "trade" triggers copy-trading logic
if (data.event_type === "trade") {
handleNewTrade(data);
}
};Step-by-step implementation
The complete construction process runs from environment setup to the first successful copied trade.
1. Environment and wallet setup
Create a dedicated EOA wallet rather than using your main wallet. Deposit USDC for trading and POL for gas on Polygon mainnet; the wallet address is the bot's funder address. New users use signatureType=3 (deposit wallet), while existing Proxy/Safe users can retain their original type.
2. Install the CLOB SDK
Official SDKs for TypeScript, Python, and Go support CLOB V2. Using an SDK rather than handling EIP-712 signatures yourself is strongly recommended to avoid extensive cryptographic work.
Shell · Installation commands
# TypeScript (recommended)
npm install @polymarket/clob-client ethers@5
# Python
pip install py-clob-client3. Initialize the CLOB client and derive API keys
On first execution, the SDK derives or creates L2 API credentials (key, secret, passphrase) with the private key. All subsequent trading requests authenticate with HMAC signatures using these credentials.
TypeScript · Client initialization
import { ClobClient } from "@polymarket/clob-client";
import { ethers } from "ethers";
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY!);
const client = new ClobClient(
"https://clob.polymarket.com",
137, // Polygon Mainnet chainId
wallet,
undefined,
0, // signatureType: 0=EOA, 1=Proxy, 2=Safe, 3=Deposit
funderAddress
);
// Derive or create L2 API credentials
let creds = await client.deriveApiKey().catch(() => null);
if (!creds) creds = await client.createApiKey();4. Monitor target wallet activity
Detect new target wallet trades through Data API polling or WebSocket. Use both: WebSocket offers the lowest latency at millisecond scale, while REST polling provides backup to avoid missed trades.
Python · Detect new trades through REST polling
import requests, time
TARGET = "0xTARGET_WALLET"
last_seen = int(time.time()) - 60
while True:
resp = requests.get(
"https://data-api.polymarket.com/activity",
params={"user": TARGET, "type": "TRADE",
"limit": 50, "start": last_seen}
)
trades = resp.json()
for t in trades:
handle_new_trade(t)
last_seen = int(time.time())
time.sleep(2) # Poll every 2 seconds5. Calculate proportional positions and submit orders
After detecting a target trade, calculate the order amount from your capital size, query the live order book to confirm liquidity, and submit an FOK (Fill or Kill) or GTC order.
TypeScript · Core ordering logic
async function executeCopyTrade(trade: Trade) {
// 1. Calculate the proportional amount (POSITION_MULTIPLIER = 0.1 means copying 10%)
const copySize = trade.size * POSITION_MULTIPLIER;
if (copySize < MIN_TRADE_SIZE || copySize > MAX_TRADE_SIZE) return;
// 2. Risk checks
const check = riskManager.checkTrade(trade, copySize);
if (!check.allowed) { console.warn(check.reason); return; }
// 3. Get the current market price
const { price } = await clobClient.getPrice(trade.tokenId, "buy");
const priceWithSlippage = price * (1 + SLIPPAGE_TOLERANCE);
// 4. Create and sign the order
const order = await clobClient.createOrder({
tokenID: trade.tokenId,
price: priceWithSlippage,
side: "BUY",
size: copySize / priceWithSlippage, // Convert to shares
});
// 5. Submit the order (FOK mode)
return await clobClient.postOrder(order, OrderType.FOK);
}6. Deploy to a low-latency VPS (24/7 operation)
Running on a local computer is unreliable and has high latency. Deployment to a VPS near Polymarket's API servers, in Dublin, Ireland or the US East Coast, is recommended and can achieve 0.4–0.8ms latency. Use PM2 or systemd to keep the bot running and restart it automatically.
Shell · PM2 deployment commands
# Use PM2 to keep the process running (Node.js)
npm install -g pm2
pm2 start dist/index.js --name polymarket-bot
pm2 save
pm2 startup # Configure automatic startup on boot
# View logs
pm2 logs polymarket-bot --lines 100Risk controls
Automated trading magnifies errors. Comprehensive risk controls are central to capital preservation.
High risk
Private-key leaks
Never write private keys into code or commit them to Git. Use .env environment variables and create a dedicated wallet for the bot, fully isolated from the main wallet.
High risk
Strategy drift
The trader you follow may change strategy, increase risk appetite, or stop trading. Reassess target wallet performance regularly and set conditions to stop following automatically.
Medium risk
Insufficient market liquidity
Copy orders in small markets may cause severe slippage. Check order book depth before trading and set maximum acceptable slippage, recommended at ≤2%.
Medium risk
Smart contract risk
Although Polymarket has been audited, CLOB V2 is relatively new infrastructure. Deposit only funds you can afford to lose entirely.
Low risk
API rate limits
Frequent REST polling triggers rate limits. Use intervals of ≥2 seconds and implement exponential-backoff retries for 502/503/504 errors.
Low risk
Code errors
Validate thoroughly in a test environment with small amounts. Automation magnifies coding errors' consequences by tens of times. Complete an audit before launch.
Recommended ecosystem tools for 2026
Existing tools can substantially shorten development time and improve copy-trading quality.
| Tool | Type | Features | Suitable users |
|---|---|---|---|
| Stand.trade | Whale monitoring | Smart-money tracking and live position increase / decrease notifications | Selecting copy targets |
| Betmoar | Information aggregation | Full-market dashboard, Telegram/Discord trading, and live news | Heavy traders |
| Polytrader | AI automation | LLM probability estimates and autonomous AI agent strategies | AI-assisted trading |
| OpenClaw | No-code | Copy trading bot creation without coding and a visual dashboard | Nontechnical users |
| QuickNode | RPC node | High-speed Polygon RPC endpoints with HTTP + WSS | Developer infrastructure |
| GitHub open-source bots | Open-source framework | Auditable code and Supabase + Python implementations | Developers building their own |
2026 best-practice checklist
Check each item before launch.
🔐 Security
- Not completed:
Dedicated wallet: Create a separate EOA wallet for the bot; never use the main wallet
- Not completed:
Environment variables: Keep private keys and API credentials only in
.envor Vault, outside version control - Not completed:
Least privilege: Give the L2 API Key only necessary trading permissions and rotate it regularly
- Not completed:
Code audits: Review all dependencies' security before using an open-source framework
📡 Technical infrastructure
- Not completed:
CLOB V2 SDK: Use the latest SDK; the old order structure became invalid after the 2026/4 upgrade
- Not completed:
Low-latency VPS: Deploy in Dublin or the US East Coast for Polymarket API latency <1ms
- Not completed:
WebSocket + REST: Use WebSocket as the primary subscription and REST polling as backup to avoid missed trades
- Not completed:
Automatic retries: Implement exponential backoff for 502/503/504/rate-limit errors; abandon nonretryable 401/403/duplicate errors
- Not completed:
RPC endpoint rotation: Use multiple backup Polygon RPC endpoints to avoid a single point of failure
📊 Strategy and risk
- Not completed:
Small tests first: Start MAX_TRADE_SIZE at $5–10 and raise it after confirming correct behavior
- Not completed:
Hard limits: Apply three protections for daily total exposure, maximum position per market, and maximum order amount
- Not completed:
Slippage management: Query the order book before trading and use FOK with 2% slippage tolerance
- Not completed:
Target wallet reviews: Review copy targets weekly and replace addresses whose performance deteriorates
- Not completed:
Backtesting: Test the strategy before launch using historical price data from the CLOB API
📝 Monitoring and logging
- Not completed:
Persistent logs: Store all filled trades in MongoDB / PostgreSQL and back up regularly
- Not completed:
Real-time alerts: Notify through Telegram or Discord when API error rates spike, balances are insufficient, or connections fail
- Not completed:
Performance tracking: Track PnL, win rate, average slippage, daily volume, and other key metrics
Polymarket Copy Trading Bot Guide · 2026 edition · Sources: Polymarket official documentation, QuickNode, TradingVPS
This document is for technical reference only and is not investment advice