This guide walks through how to set up a Polymarket bot on a VPS, end to end: installing the SDK, authenticating a wallet, funding with the right collateral, writing order logic, and deploying it to run 24/7 without you watching. Every code sample was tested with polymarket-client 0.17.0, the SDK release current on 5 November 2026.
The case for automating Polymarket isn’t a war story, it’s the on-chain record. The academic analysis of a year of Polymarket data (arXiv:2508.03474) measured roughly $40 million in realized arbitrage profit, with the top wallet earning about $2.0 million across 4,049 trades, roughly $500 per trade, thousands of times, on schedule. Edges on Polymarket are small, repeatable, and harvested by software that never sleeps.
Prerequisites: Python 3.11 or newer, a Polygon wallet, capital in pUSD, and a small amount of POL for gas. Never traded manually? Start with how to start trading on Polymarket first, because a bot amplifies a process, including a bad one.
One warning about older tutorials. Polymarket moved to CLOB V2 in April 2026, and anything published before then is dead code: a different SDK package, a different collateral token, a different order structure. If a guide tells you to install py-clob-client or fund with USDC.e, close it. Polymarket has since replaced its trading libraries with one unified SDK, and new markets are due to start moving to Protocol V2 from 9 November 2026, so a guide built on py-clob-client-v2 is a step behind too. Everything below is the current stack, and the code handles both kinds of market. If you have an existing bot from before the April cutover, the V2 migration guide is the page you want instead of this one, and our Protocol V2 guide covers the November change in depth.
Before you build: how Polymarket’s API architecture works
Bots fail most often at the authentication and collateral layers, not the strategy layer. Knowing how the pieces fit saves hours of debugging.
The three APIs and what each one does
Polymarket splits functionality across three APIs plus WebSocket streams. A complete bot touches all of them.
The CLOB API (https://clob.polymarket.com) is the trading engine: order placement, cancellation, live order book data, fill confirmations. Matching happens off-chain for speed; settlement lands on-chain on Polygon. Your network path determines how fast your orders arrive after you send them, and on the venue side our benchmark observed the API root’s own p99 stretching to 250-650 ms across all providers tested, a reminder that “simultaneous” execution logic must tolerate server-side tails too.
The Gamma API (https://gamma-api.polymarket.com) is the discovery layer: available markets, event metadata, outcome descriptions, token IDs. Indexing lags roughly a second, so use it to find markets, never to price them.
The Data API (https://data-api.polymarket.com) is account-level: positions, trade history, P&L. Monitoring, not execution.
| API | Endpoint | Primary use | Latency sensitivity |
|---|---|---|---|
| CLOB API | clob.polymarket.com | Orders, cancels, order book | High, the execution path |
| Gamma API | gamma-api.polymarket.com | Market discovery, token IDs | Low, poll every 60s |
| Data API | data-api.polymarket.com | Positions, history, P&L | Low, monitoring only |
| CLOB WebSocket | ws-subscriptions-clob.polymarket.com/ws/market (fills on /ws/user) | Live book deltas, fills | Critical, all real-time data |
The SDK connects to all of these for you, including the keepalive the WebSocket needs, a PING every 10 seconds. Endpoints and schemas still evolve, so treat docs.polymarket.com as the source of truth for the current contract.

How the CLOB matches orders, and what it costs
Makers post resting limit orders; takers fill against them. Prices run $0.01 to $0.99 as implied probability, and winning contracts pay $1.00 at resolution.
The fee structure is the single most bot-relevant fact on this page: makers pay 0% on all markets and are eligible for rebates. Takers pay a category formula per share, rate × P × (1−P), which peaks at 50¢: 1.75¢ a share on crypto, 1.25¢ on sports, economics, culture, weather and other markets, and 1¢ on finance, politics, tech and mentions, with geopolitics fee-free. Fees are applied by the protocol at match time rather than embedded in your signed order, so you never compute them yourself.
The implication is mechanical: a pure market-order bot in crypto markets needs a reliable edge of more than 1.75¢ a share at 50¢, which is 3.5% of what it pays, before slippage just to break even, while a maker bot trades free and collects rebates. Order-type choice is fee strategy.
Rates as checked on 5 November 2026. The schedule has changed more than once this year, so confirm the current curve in Polymarket’s fee documentation before pricing a strategy on it. Per-market parameters come with the market itself:
market = await client.get_market(slug="your-market-slug")
print(market.trading.minimum_tick_size) # smallest price step
print(market.trading.minimum_order_size) # smallest order, in shares
print(market.trading.fee_schedule) # taker fee rate and maker rebate share
Where latency actually comes from (measured, not guessed)
You’ll find confident claims online about which AWS region Polymarket “runs in.” Earlier versions of this site’s own pages managed to name two different regions, which tells you what those claims are worth.
Here is what we actually know, because we measured it. The CLOB API is CDN-fronted; our probes terminate at Cloudflare edges. In our June 2026 four-provider benchmark, one purchased box per provider with raw JSON downloadable, Dublin machines saw the live feed at ~13-15 ms median and round-tripped the order book warm at ~21-23 ms median. Our Amsterdam box saw the feed at ~10 ms with order round-trips within about a millisecond of Dublin’s. Nobody measured single-digit milliseconds on the order path, including us.
A US-based box pays the Atlantic crossing on top, tens of milliseconds of physics no provider removes, which matters in proportion to how contested your edge is. Between well-placed bots the race is decided in the tails: order-path p99 ranged 37-55 ms across the four boxes we tested, and the box with the smallest worst-case wins the ties.
So the honest location guidance: for Polymarket-focused bots, a European box with a short, measured path is the right call (the full location comparison has the side-by-side numbers). Our Dublin and Amsterdam locations are built for exactly this, on Ryzen 9 9950X hosts with DDR5 and NVMe. Pick by strategy rather than leaderboard: Amsterdam sees the book first, Dublin edges the order path. The way to verify any of that is the same 20-minute probe we publish, run on a free 3-day demo before you pay us or anyone.
One thing to know before you test from a European box
As of 5 November 2026, Ireland and the Netherlands both sit in Polymarket’s frontend-restricted group: the polymarket.com website is close-only from either country, while the trading API is not restricted. A bot on the CLOB runs normally from both.
This catches first-time builders out in a specific way. If you run curl https://polymarket.com/api/geoblock from your box you will get {"blocked": true, "country": "IE"} back, and that is expected. That endpoint runs on polymarket.com, not on the API servers, so it reports the website’s eligibility rather than the CLOB’s. A different IP in the same country returns exactly the same thing. The only test that answers your question is a real order attempt against the CLOB from the box you’ll trade on.
Restriction groups are set by Polymarket and by regulators, and they move. Check docs.polymarket.com/api-reference/geoblock before provisioning and at renewal.
Step 1: choosing and provisioning the VPS for your Polymarket bot
The server is part of your execution quality, but the sizing logic is simpler than vendors imply. A Polymarket bot is network-bound, not compute-bound: the hot loop (read delta, decide, sign, submit) runs on one core, so single-core speed beats core count, and more cores buy you more bots rather than a faster bot.
A single bot watching a handful of markets runs comfortably on a 2-vCPU box with a few GB of RAM; scale up as you add bots, accounts or markets. The full reasoning about what each resource does and what breaks first (OOM kills, swap death, log-blocked event loops) lives in the VPS specs guide, and current plans are on the pricing page.
NVMe matters more than it looks: continuous log writes on slow storage can block Python’s thread mid-flush, which is a real cause of missed fills.
Operating system
Both work. Linux gives you systemd, the cleanest 24/7 process management with auto-restart, and Ubuntu 24.04 is the standard pick: it ships Python 3.12, while Ubuntu 22.04 ships Python 3.10, which is too old for Polymarket’s SDK. Windows Server handles Python bots fine via Task Scheduler and makes life easier if NinjaTrader or another Windows platform shares the box. Everything below shows the Linux path, with Windows equivalents noted where they differ.
First commands after connecting
SSH in (RDP on Windows), then before anything else:
sudo apt update && sudo apt upgrade -y
sudo timedatectl set-timezone UTC
UTC is not cosmetic. Polymarket’s authenticated requests expire after a short window, and meaningful clock drift fails every signed call with errors that won’t mention the clock. Install chrony as well (sudo apt install chrony) and check chronyc tracking occasionally; the offset should read in milliseconds, not seconds.
Your firewall posture is simple: the bot makes only outbound connections, so block all inbound traffic except SSH or RDP from your own IP. Full commands in the security section.
Setting up Python and the Polymarket SDK
# Ubuntu 24.04 ships Python 3.12; the SDK needs 3.11 or newer
python3 --version
sudo apt install -y python3-venv
# Virtual environment for the bot
python3 -m venv polybot-env
source polybot-env/bin/activate
# The unified Polymarket SDK, pinned to the release this guide was tested with
pip install polymarket-client==0.17.0
pip install python-dotenv
The package is polymarket-client, and your code imports it as polymarket. It is Polymarket’s unified SDK: the older py-clob-client was retired with the April 2026 upgrade, and py-clob-client-v2 has been deprecated since 15 October 2026. If an earlier attempt installed either, run pip uninstall py-clob-client py-clob-client-v2 first.
Three things worth knowing about this package. It needs Python 3.11 or newer, which is why Ubuntu 24.04 is the pick above. It includes the WebSocket client, with the keepalive and reconnection built in, so there is no separate websockets install and no connection code of your own. It does not depend on web3. Older tutorials tell you to pin web3==6.14.0 because a retired SDK broke on newer releases; that advice no longer applies. The dependencies are eth-account, eth-abi, eth-utils, httpx, pydantic, msgpack and websockets, all resolved for you.
Keep the version pinned. The SDK is still below 1.0, and its releases can remove calls (0.16.0 removed one), so read the changelog before you upgrade a bot that is trading.
Environment variables, not hardcoded keys
A committed private key is compromised the moment it touches a remote repository, even if deleted seconds later. All secrets live in a .env file:
# .env: never in version control
POLYMARKET_PRIVATE_KEY=your_polygon_wallet_private_key
POLYMARKET_WALLET=your_polygon_wallet_address
DRY_RUN=true
chmod 600 .env
import os
from dotenv import load_dotenv
load_dotenv()
PRIVATE_KEY = os.environ["POLYMARKET_PRIVATE_KEY"] # a missing value stops the bot here,
WALLET = os.environ["POLYMARKET_WALLET"] # not at its first order
There are no API key, secret or passphrase lines. The SDK obtains those credentials from your private key every time the bot starts, as Step 2 shows.
Step 2: authenticating your wallet and deriving API credentials
Authentication is the most common point of failure for first-time builders. Two layers, both required: L1 uses your Polygon private key to prove ownership and mint API credentials; L2 uses HMAC-signed headers (key, secret, passphrase) for trading operations. The SDK handles both: creating a client signs the L1 request and obtains the L2 credentials, and every trading call after that carries the L2 headers.

The setting that bites people is the wallet type, which Polymarket’s API calls the signature type. There are four:
- 0,
EOA: standard EOA wallet (MetaMask, Rabby, hardware) - 1,
POLY_PROXY: Polymarket email / Magic wallet - 2,
GNOSIS_SAFE: Gnosis Safe or browser proxy wallet - 3,
DEPOSIT_WALLET: deposit wallets (POLY_1271in the API)
With this SDK you never pass the number. It works the type out from the wallet address you give it: your own address means EOA, and an address it can derive from your key as a proxy, Safe or deposit wallet gets that type.
Type 3 is worth understanding before you choose. Polymarket is onboarding new API users onto deposit wallets, a deterministic smart account whose order signatures the CLOB validates through ERC-1271. It has its own funding, approval and cache-sync steps that the EOA path does not, and our deposit-wallet walkthrough covers them in full. It is also the SDK’s default: leave wallet out and the client assumes your deposit wallet and tries to deploy one, which needs a Relayer or Builder API key.
Everything below assumes signature type 0, a standard EOA wallet, which is the simplest path for a first bot.
import asyncio
from polymarket import AsyncSecureClient
async def main() -> None:
# Signs the L1 request and creates your L2 credentials, or derives the existing ones
client = await AsyncSecureClient.create(
private_key=PRIVATE_KEY,
wallet=WALLET, # the address your account trades from
)
async with client:
print(client.wallet_type) # "EOA" on the path this guide follows
cash = await client.get_balance_allowance(asset_type="COLLATERAL")
print(f"pUSD: {cash.balance / 1e6:,.2f}") # an L2-signed request
asyncio.run(main())
If that prints EOA and a balance, the key, the wallet address and both authentication layers work. If you expected an EOA and see another type, the address in POLYMARKET_WALLET is not the one your key controls directly, so fix that before going further. Print the type on every start, not just the first: it is the cheapest check that the bot acts for the wallet you funded.
Older tutorials call create_or_derive_api_key(), pass a signature_type and a funder, and keep an API key, secret and passphrase in .env. This SDK needs none of that: it creates the credentials on the first run and derives the same ones from your key on every later start, so there is nothing extra to store or lose. To skip that request at start-up, pass saved credentials with credentials=, and the SDK checks they are still active.
Everything a bot needs from the SDK runs on asyncio, so the code below uses async and await. A synchronous SecureClient exists, but only the async clients can stream market data.
Step 3: funding the bot with pUSD (not USDC)
This is the step that most often stops a first bot from trading, because the error it produces looks like an auth problem.
pUSD is the collateral for all Polymarket trading. It is a standard ERC-20 on Polygon with 6 decimals, backed by USDC with the backing enforced on-chain. USDC or USDC.e sitting in your wallet is not buying power.
If you fund through polymarket.com, the UI wraps automatically with a one-time approval and there is nothing to do. Deposits through the Bridge API also auto-wrap. If you are API-only, wrap it yourself through the CollateralOnramp:
CollateralOnramp: 0x93070a847efEf7F70739046A929D47a521F5B8ee
USDC.e (Polygon): 0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174

Approve the Onramp (not the pUSD token) to spend your USDC.e, then call wrap(asset, to, amount). To exit, approve the CollateralOfframp for pUSD and call unwrap(), which returns USDC.e.
Fund-critical step. Confirm the Onramp, Offramp and pUSD addresses on Polymarket’s official Contracts page before running this, and wrap a small test amount first. A wrong address here cannot be undone.
Make sure your balance logic reads pUSD. A bot that checks a USDC.e balance will report buying power it does not have.
Token allowances, once per wallet
Before your first order, Polymarket’s contracts need authorization to move your collateral and conditional tokens. Without them, every order fails at the contract level no matter how correct your API auth is.
Two separate things are involved here, and conflating them is a common source of “not enough balance” errors on a funded wallet.
The on-chain approvals are ERC-20 and ERC-1155 transactions sent from your wallet, and the SDK can send them for you:
# Sends whatever is missing from the SDK's standard approval set and waits for each
# transaction. From an EOA you pay the gas in POL; existing approvals are skipped.
await client.setup_trading_approvals()
That standard set is broad. In 0.17.0 it grants unlimited pUSD allowances to seven contracts and operator approvals to ten, covering both kinds of market, the Protocol V2 Router, automatic redemption and Polymarket’s perpetuals deposit contract. A bot that only trades needs fewer: a pUSD allowance for each exchange it uses, and an operator approval for that exchange on the contract that holds its positions, which is CTF for v1 markets and PositionManager for Protocol V2. Send those one at a time with approve_erc20() and approve_erc1155_for_all(); our Protocol V2 guide has the full table. The addresses, from Polymarket’s contracts page:
pUSD (collateral): 0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB
CTF Exchange (v1 markets): 0xE111180000d2663C0091e4f400237545B87B996B
Neg Risk CTF Exchange (v1): 0xe2222d279d744050d28e00520010520000310F59
CTF (v1 positions): 0x4D97DCd97eC945f40cF65F87097ACe5EA0476045
ExchangeV3 (Protocol V2): 0xe3333700cA9d93003F00f0F71f8515005F6c00Aa
PositionManager (V2 positions): 0x006F54F7f9A22e0000CC2AB60031000000ae9fEF
You will need a little POL for the approval gas. 1 to 2 POL covers it, and 5 to 10 POL is a sensible running buffer for an active bot.
The CLOB’s cached view of your balance and allowances is a separate thing. The order book checks your orders against that copy, which can lag the chain after you fund or approve. Read it back to see what the order book sees:
cash = await client.get_balance_allowance(asset_type="COLLATERAL")
print(cash.balance / 1e6) # pUSD, as the CLOB sees it
for spender, amount in cash.allowances.items():
print(spender, amount) # base units: 1 pUSD is 1,000,000
# Outcome tokens: "CONDITIONAL" for a CTF token ID, "CONDITIONAL-V2" for a V2 position ID
# await client.get_balance_allowance(asset_type="CONDITIONAL-V2", asset_id=ASSET_ID)
If orders are rejected for balance while your wallet clearly holds pUSD, this reading is the first thing to check. The Python SDK has no public call that refreshes the cache. It refreshes it on one path only: when the CLOB rejects an order for allowance and the cached allowance is below what the order needs, the SDK sends an unlimited pUSD approval for a buy, or an operator approval for a sell, refreshes the cache and retries the order once. A bot that skips the setup call can therefore send an approval transaction with its first order.
Step 4: writing your Polymarket bot’s strategy logic
Real-time data: WebSocket, never REST polling
REST polling makes your bot permanently as stale as its polling interval. The WebSocket pushes book changes as they happen, and the SDK’s subscribe() looks after the connection itself:
from decimal import Decimal
from polymarket import AsyncSecureClient
from polymarket.streams import MarketEvent, MarketSpec
books: dict[str, dict[str, dict[Decimal, Decimal]]] = {}
async def stream_orderbook(client: AsyncSecureClient, asset_ids: list[str]) -> None:
# The SDK opens the socket, sends the keepalive pings and reconnects by itself
async with await client.subscribe(MarketSpec(asset_ids=asset_ids)) as stream:
async for event in stream:
process_update(event)
def process_update(event: MarketEvent) -> None:
if event.type == "book": # full snapshot: replace your copy
p = event.payload
books[p.asset_id] = {"bids": {lvl.price: lvl.size for lvl in p.bids},
"asks": {lvl.price: lvl.size for lvl in p.asks}}
elif event.type == "price_change": # the new size at one level; 0 removes it
for change in event.payload.price_changes:
book = books.get(change.asset_id)
if book is None:
continue # no snapshot for this asset yet
levels = book["bids"] if change.side == "BUY" else book["asks"]
if change.size == 0:
levels.pop(change.price, None)
else:
levels[change.price] = change.size
# Rebuild top-of-book, run signal logic
A book event is a full snapshot of one asset’s book, sent when you subscribe and again after trades, so replace your copy whenever one arrives. A price_change event carries the new total size at each changed price level, and a size of zero removes the level. The SDK holds up to 1,024 unread events per subscription and drops the oldest when your code falls behind, so keep this handler fast and do slow work, such as disk writes and REST calls, somewhere else.
Market discovery goes through Gamma. Each market carries a version, v1 for CTF markets and v2 for Protocol V2, and Gamma’s lists return CTF markets unless you ask for V2 ones, so ask for each version separately and choose the ID you trade from the version:
from polymarket import AsyncSecureClient, Market
async def get_active_markets(client: AsyncSecureClient, limit: int = 50) -> list[Market]:
"""Open markets that accept orders, from both protocol versions."""
found: list[Market] = []
for version in ("v1", "v2"): # Gamma lists one version per request
pages = client.list_markets(version=version, closed=False, page_size=limit)
page = await pages.first_page()
found += [m for m in page.items if m.state.accepting_orders]
return found
def yes_asset_id(market: Market) -> str | None:
"""The ID to trade comes from the market's version, never from which field is filled."""
if market.version == "v2":
return market.outcomes.yes.position_id
if market.version == "v1":
return market.outcomes.yes.token_id
return None # missing or unknown version: skip it
The version check matters because both ID fields turn up on both kinds of market. Protocol V2 markets repeat their position IDs in clobTokenIds, and many CTF markets carry V2-format positionIds that nothing trades under. The SDK routes each order by the ID you hand it, so the choice has to come from the version. To narrow the list by topic, add a tag_id.
Position sizing: fractional Kelly with a hard cap
Sizing is risk management, not strategy. Full Kelly is aggressive; production bots typically run 0.15 to 0.25 of the Kelly output to absorb model error.
def kelly_criterion(true_prob: float, market_price: float,
bankroll: float, fraction: float = 0.25) -> float:
"""Fractional Kelly position size, in collateral units."""
if market_price <= 0 or market_price >= 1:
return 0.0
b = (1.0 / market_price) - 1.0 # decimal odds
p = true_prob
q = 1.0 - p
full_kelly = (b * p - q) / b
if full_kelly <= 0:
return 0.0 # no edge, no trade
position = fraction * full_kelly * bankroll
return min(position, bankroll * 0.10) # hard 10% cap
size = kelly_criterion(0.72, 0.58, 1000.0) # → 35.00
The zero-output case is the entire point. A bot that passes on 90% of markets and trades only positive-Kelly signals beats one that forces marginal trades, and the profitability data says exactly that about who wins here.
Placing orders: GTC for making, FOK for taking
Order uniqueness is handled by a millisecond timestamp the SDK sets for you, so there is no nonce to track. Fees are not part of the order you sign. In the code below, asset_id is the ID yes_asset_id() chose for the market.
GTC limit orders rest as makers, at zero fees and rebate-eligible. FOK market orders fill now or cancel, and taker fees apply. One classic mistake: a $500 FOK in a market with $200 of depth at your price cancels entirely, so use FAK for partial fills in thin books, or slice into GTC orders.
# GTC limit order: rests on the book as a maker, no fee, rebate-eligible
resting = await client.place_limit_order(
asset_id=asset_id, side="BUY", price="0.55", size="20",
post_only=True, # refused rather than crossing the book and paying taker fees
)
if resting.ok is False: # a refusal can come back as a result, not an exception
print(resting.code, resting.message) # for example post_only_would_cross
# FOK market order: fills in full now or is cancelled, taker fees apply
taken = await client.place_market_order(
asset_id=asset_id, side="BUY",
amount="25", # pUSD to spend
max_price="0.60", # never pay more than this per share
order_type="FOK",
)
Four details that save debugging time.
side is the string "BUY" or "SELL". A limit order rests as GTC unless you pass expiration, a Unix time at least three minutes ahead, which makes it GTD. Market orders default to FAK, so pass order_type="FOK" for all or nothing. Prices and sizes can be passed as strings, which keeps them exact.
post_only=True is the flag that protects your fee position. Without it, a limit order priced through the book crosses and pays taker fees; with it, the order is rejected instead. For a maker strategy that is almost always what you want.
Check ok on every result. A refused order often comes back as a RejectedOrder with a code such as post_only_would_cross or fok_not_filled rather than as an exception, while a malformed or unauthorised request raises RequestRejectedError. If you prefer to inspect an order before sending it, create_limit_order() and create_market_order() sign without sending, and post_order() sends what they return.
The SDK reads each market’s tick size and neg-risk flag itself and refuses a price off the tick grid before signing, so there is nothing to pass for either. max_spend on a market buy sets an estimated all-in spend, fees included, and builder_code attaches attribution if you run an app on top of Polymarket. Both are optional.
Handling rate limits, errors and reconnections
A bot that crashes on its first API error breaks at 3 AM during the event you built it for.
Endpoint ceilings, as of 5 November 2026:
| Endpoint | Burst | Sustained |
|---|---|---|
POST /order | 5,000 / 10 s (500/s) | 120,000 / 10 min (200/s) |
DELETE /order | 5,000 / 10 s (500/s) | 120,000 / 10 min (200/s) |
POST /orders (batch) | 2,000 / 10 s (200/s) | 21,000 / 10 min (35/s) |
Polymarket has also published per-signer trading limits, and they are the tighter ones. Each signing key gets one token bucket for orders and one for cancels. The Standard tier allows 40 orders a second with bursts of 60, and 80 cancels a second with bursts of 120, and higher tiers follow the maker wallet’s 30-day volume. The limiter started in warning mode on 24 July 2026, and on 5 November Polymarket’s page still gave no date for enforcement, so build to these numbers now. To watch them, pass on_rate_limit_update= to AsyncSecureClient.create(): the SDK hands your code each Poly-RateLimit-* reading from order and cancel responses, including a warning flag on requests that enforcement would have refused. The architecture answer is the same regardless of the numbers: real-time data on WebSockets, REST reserved for account data on a slow cadence.
import asyncio
import time
from functools import wraps
def rate_limited(max_per_second: float):
"""Spaces calls to an async function at least 1/max_per_second apart,
without blocking the event loop the feed runs on."""
min_interval = 1.0 / max_per_second
lock = asyncio.Lock()
next_slot = 0.0
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
nonlocal next_slot
async with lock:
now = time.monotonic()
if next_slot > now:
await asyncio.sleep(next_slot - now)
next_slot = max(now, next_slot) + min_interval
return await func(*args, **kwargs)
return wrapper
return decorator
@rate_limited(max_per_second=20) # half the Standard tier's 40 orders a second
async def place_quote(client: AsyncSecureClient, asset_id: str, price: str, size: str):
return await client.place_limit_order(asset_id=asset_id, side="BUY",
price=price, size=size, post_only=True)
The SDK does not retry orders for you. Retry a RequestRejectedError whose status is 5xx with exponential backoff (1s, doubling, cap 30s, give up after 5), and wait out a RateLimitError for its retry_after. Never auto-retry a 400 or 401, which mean fix the request or the auth. A TransportError on an order is the awkward case: the order may have reached the book, so check your open orders before you send it again. Reconnecting is the SDK’s job, but it never announces a gap, so give the feed a watchdog:
async def resync(client: AsyncSecureClient, asset_ids: list[str]) -> None:
"""Rebuild every local book from a REST snapshot."""
for asset_id in asset_ids:
snap = await client.get_order_book(asset_id=asset_id)
books[asset_id] = {"bids": {lvl.price: lvl.size for lvl in snap.bids},
"asks": {lvl.price: lvl.size for lvl in snap.asks}}
async def run_feed(client: AsyncSecureClient, asset_ids: list[str],
quiet_limit: float = 30.0) -> None:
"""The SDK reconnects on its own but never announces a gap, so a silent feed
is treated as a stale one and the books are rebuilt before anyone trusts them."""
async with await client.subscribe(MarketSpec(asset_ids=asset_ids)) as stream:
while True:
try:
event = await asyncio.wait_for(anext(stream), timeout=quiet_limit)
except TimeoutError: # a quiet market, or a reconnect under way
await resync(client, asset_ids)
continue
process_update(event)
After a dropped connection the SDK waits a jittered backoff that starts at a quarter of a second and is capped at 30 seconds, reconnects and resubscribes, and the fresh book snapshot that follows replaces your copy through process_update. For a market-making bot, a missed update is a stale quote on the book, which informed flow will happily fill, so pull your quotes when the watchdog fires and quote again only from a rebuilt book. Never trade on a book you mirrored before the gap.
Three Polymarket bot strategies and what each one demands
Strategy 1, intra-market arbitrage (YES + NO under $1.00). When both sides of one market sum below $1, filling both locks the difference. The academic record shows this lane is real (~$10.6M of the study’s $40M) and industrialized; the authors only counted gaps above 5¢ because execution reality eats thinner ones. Windows close in seconds in liquid markets, making this the most latency-sensitive lane, both legs FOK, tails deciding the race. Full mechanics, fee math and the one-leg risk rule are in the arbitrage guide.
Strategy 2, cross-signal trading (the Binance lag). Polymarket’s short-horizon crypto markets reprice after the spot venue moves, and the repricing lag is the edge window. Measure it rather than trusting folklore numbers. Two measured cautions from our own benchmark: this strategy pays taker fees in the most expensive category (1.75¢ a share at 50¢, so your per-trade edge must clear it), and routing to your signal venue is per-box. Our Dublin machine’s Binance probe hit a far CDN edge at ~313 ms while three competitor boxes saw ~208 ms, same city, different routes. Before deploying, probe both your Polymarket path and your signal-source path from the exact box that will trade. The test script covers it, and yes, it caught our own routing weakness, which we published and put on the roadmap.
Strategy 3, market making. Quote both sides, earn the spread plus rebates, pay zero fees, in exchange for the strictest uptime requirement on this page. Offline means stale quotes, and stale quotes mean adverse fills. Continuous WebSocket, fast cancels, instant reconnect-and-resync, and a process manager that restarts you in seconds are the job description.
Step 5: deploying the bot for 24/7 operation
Copy code up with rsync, excluding secrets (create .env fresh on the box):
rsync -avz --exclude '.env' ./polybot/ user@your-vps-ip:/home/user/polybot/
Then systemd:
# /etc/systemd/system/polybot.service
[Unit]
Description=Polymarket Trading Bot
After=network.target
[Service]
Type=simple
User=your-username
WorkingDirectory=/home/your-username/polybot
EnvironmentFile=/home/your-username/polybot/.env
ExecStart=/home/your-username/polybot-env/bin/python main.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable polybot
sudo systemctl start polybot
sudo journalctl -u polybot -f
Restart=always brings the bot back five seconds after any crash and survives reboots. Log every significant event with UTC timestamps to a rotating file (50MB × 10 keeps weeks of history). On Windows, Task Scheduler with “restart on failure” plays the systemd role. Once this is running, our 24/7 operations guide covers the next layer: watchdogs for hangs, drain procedures before reboots, and restart-time state reconciliation.
The circuit breaker is not optional
Strategies break in production in ways backtests never predicted. A hard daily-loss stop that cancels all open orders and halts is the difference between a bad day and a bad month.
class CircuitBreaker:
def __init__(self, max_daily_loss: float):
self.max_loss = max_daily_loss
self.daily_loss = 0.0
self.triggered = False
def record_loss(self, amount: float):
self.daily_loss += amount
if self.daily_loss >= self.max_loss:
self.triggered = True
def is_ok(self) -> bool:
return not self.triggered
breaker = CircuitBreaker(max_daily_loss=100.0)
# in the main loop:
if not breaker.is_ok():
result = await client.cancel_all()
if result.not_canceled: # order ID -> reason, for anything still open
logger.error(f"orders still open after cancel_all: {result.not_canceled}")
break
Let Polymarket cancel your orders if the bot dies
A circuit breaker only works while your process runs. For the crash, the hang and the dead network, Polymarket has an order heartbeat: once the first one is accepted, the CLOB expects another within 10 seconds and otherwise tries to cancel every open order on that API key, in every market. Send one every 5 seconds:
from polymarket import (OrderHeartbeatMismatchError, RateLimitError,
RequestRejectedError, TransportError)
async def order_heartbeat(client: AsyncSecureClient) -> None:
"""Once the first heartbeat is accepted, 10 seconds without one makes Polymarket
try to cancel every open order on this API key. There is no way to switch it off."""
heartbeat_id = ""
while True:
try:
beat = await client.send_order_heartbeat(heartbeat_id=heartbeat_id)
heartbeat_id = beat.heartbeat_id
except OrderHeartbeatMismatchError as e:
heartbeat_id = e.heartbeat_id # send again at once with the expected ID
continue
except RequestRejectedError as e:
if e.status < 500:
raise # a 4xx means the key or request is wrong
await asyncio.sleep(1) # retry fast: the whole budget is 10 seconds
continue
except (RateLimitError, TransportError):
await asyncio.sleep(1)
continue
await asyncio.sleep(5)
The cancellation is best effort, so on a planned shutdown stop placing orders and cancel them yourself. The heartbeat covers every process that uses the same API key, so run one loop per key, not one per bot. Start it beside the feed and the strategy in one task group, so a crash in any of them stops the whole process and systemd restarts it with the heartbeat running again:
async def main() -> None:
client = await AsyncSecureClient.create(private_key=PRIVATE_KEY, wallet=WALLET)
async with client, asyncio.TaskGroup() as tasks:
tasks.create_task(run_feed(client, ASSET_IDS))
tasks.create_task(order_heartbeat(client))
tasks.create_task(strategy(client)) # your own code
asyncio.run(main())
ASSET_IDS is the list your market discovery produced, and strategy is your own loop of signals, sizing and orders.
Step 6: security hardening before you fund it
The bot holds a private key controlling real collateral. The attack surface is narrow but the failure is irreversible.
# Inbound: SSH from your IP only. The bot needs no inbound ports.
sudo ufw allow from YOUR.IP.ADDRESS to any port 22
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
# /etc/ssh/sshd_config → PasswordAuthentication no, PermitRootLogin no
Fund the trading wallet with this week’s risk budget only; the rest stays in cold storage, so a compromised key drains a float rather than your holdings. Cap position size in code regardless of what Kelly outputs until the strategy has 200+ live trades behind it. And keep secrets in the chmod 600 .env loaded via EnvironmentFile=, never in the unit file’s Environment= line, which is world-readable through systemctl show.
Step 7: testing before going live
Add a DRY_RUN flag and gate every submission on it:
import logging
from typing import Literal
logger = logging.getLogger("polybot")
DRY_RUN = os.getenv("DRY_RUN", "true").lower() == "true"
async def submit_order(client: AsyncSecureClient, asset_id: str,
side: Literal["BUY", "SELL"], price: str, size: str):
if DRY_RUN:
# Signs the order, which checks the price, size and asset ID, but never sends it
await client.create_limit_order(asset_id=asset_id, side=side, price=price,
size=size, post_only=True)
logger.info(f"[DRY RUN] {side} {size} @ {price} on {asset_id}")
return None
return await client.place_limit_order(asset_id=asset_id, side=side, price=price,
size=size, post_only=True)
In dry-run mode the order is still built and signed, so a wrong asset ID or a price off the tick grid fails here rather than with real money.
Run dry for at least 48 hours across different market conditions and check signal frequency, sizing outputs and error patterns. Then go live with $50 to $100 for a week, enough for real fills, slippage and gas while bugs are still cheap, and only scale when live results match the dry-run logs. If they diverge, investigate before adding capital rather than after.
Frequently Asked Questions
polymarket-client for Python, imported as polymarket, or @polymarket/client for TypeScript. These are Polymarket’s unified SDKs, and they trade both CTF and Protocol V2 markets. The older py-clob-client-v2 and @polymarket/clob-client-v2 are deprecated, and the packages without the -v2 suffix were retired in April 2026, which is a common reason a bot built from an older tutorial never places an order. The Python SDK needs Python 3.11 or newer, and the TypeScript one Node 24 or newer.
pUSD. It is the collateral for all Polymarket trading. The polymarket.com UI wraps automatically and Bridge deposits auto-wrap, but if you are API-only you wrap USDC.e yourself through the CollateralOnramp. USDC sitting in your wallet is not buying power, and a bot checking a USDC balance will report capital it cannot trade.
You do not create them by hand. The SDK obtains them from your Polygon private key when you create the client: L1 uses your key to prove ownership and mint the credentials, and L2 uses them as HMAC-signed headers on every trading request. On later starts it derives the same credentials again, so there is nothing to store in .env, and there is no web dashboard step.
The one that matches how your wallet was created: 0 (EOA) for a standard wallet like MetaMask, 1 (POLY_PROXY) for Polymarket email or Magic accounts, 2 (GNOSIS_SAFE) for Gnosis Safe or proxy wallets, and 3 (DEPOSIT_WALLET, or POLY_1271) for deposit wallets. With the SDK you pass the wallet address rather than the number, and client.wallet_type shows what it worked out. If you are creating a new API account today, note that new API users are being onboarded onto deposit wallets, which have their own funding and approval flow.
Two sets apply. The endpoint limits allow POST /order and DELETE /order 500/s in bursts and 200/s sustained, with batch endpoints lower. The per-signer limits are tighter: on the Standard tier, 40 orders a second with bursts of 60 and 80 cancels a second with bursts of 120, rising with your 30-day volume. Polymarket started those in warning mode in July 2026 and says it will announce enforcement, so build to them now. The design answer is fixed either way: WebSockets for all real-time data, REST for slow account polling.
Europe, for Polymarket-focused bots, and the realistic numbers are tens of milliseconds rather than the single-digit claims you’ll see around the internet. In our published benchmark the live feed ran ~13-15 ms median from Dublin and ~10 ms from Amsterdam, with warm order round-trips ~21-23 ms from either and bot-versus-bot races decided in the 37-55 ms p99 tails. The API is CDN-fronted, so ignore confident region trivia and measure from your actual box with the free probe.
blocked: true from my Dublin box. Is something wrong? No. That endpoint runs on polymarket.com and reports the website’s eligibility, not the CLOB’s. Ireland and the Netherlands are close-only on the website while the trading API stays unrestricted, so your bot’s orders go through normally. A different IP in the same country returns the same response. Act only on a genuine rejection from the API itself.
systemd with Restart=always and RestartSec=5 on Linux, or Task Scheduler’s restart-on-failure on Windows, plus rotating logs, a feed watchdog that rebuilds the books before quoting after any gap, Polymarket’s order heartbeat so resting orders are cancelled if the bot dies, and a circuit breaker that cancels everything past a daily loss limit. The box itself should be always-on with an uptime target worthy of resting orders; a home PC is the weak link, not the code.
Yes. Install Python 3.11 or newer from python.org, create the environment the same way (activate it with polybot-env\Scripts\activate), run the same pip install lines, and let Task Scheduler replace systemd. Windows is the convenient choice when the bot shares a box with NinjaTrader or another Windows-native platform.
A Polymarket bot is only as good as its worst minute: the dropped WebSocket during a Fed print, the reboot with resting orders on the book, the log flush that blocked the loop. Build for those minutes, and verify every infrastructure claim, ours included, with measurements. Our current numbers are public in the benchmark, the probe is free, and the 3-day demo exists so the first thing your bot does on our hardware is check whether we told you the truth.
SDK versions, contract addresses, fee figures, rate limits and API details reference Polymarket’s official documentation as of 5 November 2026 and change frequently; verify against docs.polymarket.com and the official Contracts page before deploying, and test any flow that moves funds with a tiny amount first. The code samples were run with polymarket-client 0.17.0 on Python 3.11, 3.12 and 3.13 against a local test server that answers in Polymarket’s documented formats, not against a funded account. Restriction groups are set by Polymarket and regulators, not by any hosting provider, and can change. We operate TradoxVPS and provide infrastructure, not financial advice; automated trading involves substantial risk, including rapid total loss.