Polymarket copy trading bot construction guide

Document type
Tutorial
Updated
Reading time
9 min

Polymarket copy trading bot setup with CLOB APIs, wallet monitoring, proportional orders, risk controls, deployment, and security checks.

Open original report
Document details

Build a copy trading system that automatically monitors smart money and mirrors trades in real time. Covers the CLOB V2 API, on-chain event detection, risk controls, and 2026 best practices.

01Section

Polymarket copy trading bot construction guide

  • Python / TypeScript

  • Polygon chain

  • CLOB V2 API

  • USDC settlement

  • Non-custodial

02Section

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.

03Section

System architecture

A production-grade copy trading bot has five core modules with distinct roles, each independently testable and replaceable.

  1. Target detection

    Monitor

  2. Proportional sizing

    Sizer

  3. Risk checks

    Risk Mgr

  4. On-chain ordering

    Executor

ModuleMain responsibilityTechnical approachRecommended language
MonitorDetect new target wallet tradesData API polling + WebSocketTypeScript
SizerCalculate proportional order amountsPortfolio ratio or fixed riskPython
Risk ManagerSafety checks before executionLimit rules and market blocklistsAny
ExecutorSign and submit ordersCLOB SDK + EIP-712TypeScript
LoggerPosition tracking and performance analysisMongoDB / PostgreSQLAny

04Section

Polymarket API guide

Polymarket offers APIs at three different layers. The bot uses all three together.

APIBase URLAuthenticationMain uses
Gamma APIgamma-api.polymarket.comNone requiredMarkets, events, search, and public trader data
Data APIdata-api.polymarket.comNone requiredWallet activity history for copy-trade detection
CLOB APIclob.polymarket.comL1/L2 authentication requiredPlace and cancel orders, query positions, and order books

Python · L2 authentication header example

python
# 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

EndpointPurposeRecommended polling frequency
GET /activity?user=0x...Retrieve target wallet trade history to detect new ordersEvery 2 seconds through REST, or use WebSocket
GET /book?token_id=...Retrieve a market's order bookQuery in real time before ordering
POST /orderSubmit a new order, requiring L2 + EIP-712Event-triggered
DELETE /order/{id}Cancel a specific orderEvent-triggered
GET /positionsQuery current positionsAt startup and during periodic synchronization

WebSocket subscriptions (recommended)

JavaScript · Subscribe to the market channel

javascript
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);
  }
};

05Section

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

bash
# TypeScript (recommended)
npm install @polymarket/clob-client ethers@5

# Python
pip install py-clob-client

3. 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

typescript
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

python
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 seconds

5. 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

typescript
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

bash
# 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 100

06Section

Risk 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.

07Section

Recommended ecosystem tools for 2026

Existing tools can substantially shorten development time and improve copy-trading quality.

ToolTypeFeaturesSuitable users
Stand.tradeWhale monitoringSmart-money tracking and live position increase / decrease notificationsSelecting copy targets
BetmoarInformation aggregationFull-market dashboard, Telegram/Discord trading, and live newsHeavy traders
PolytraderAI automationLLM probability estimates and autonomous AI agent strategiesAI-assisted trading
OpenClawNo-codeCopy trading bot creation without coding and a visual dashboardNontechnical users
QuickNodeRPC nodeHigh-speed Polygon RPC endpoints with HTTP + WSSDeveloper infrastructure
GitHub open-source botsOpen-source frameworkAuditable code and Supabase + Python implementationsDevelopers building their own

08Section

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 .env or 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