Polymarket AI trading agent construction guide
Tenten · Field Guide № 04
2026 Edition
AI prediction markets / Polymarket
Reading time: about 35 minutes
From environment setup to deployment, covering technical architecture, prompt engineering, and risk controls.
01 · Foundations / Basics
Polymarket: how prediction markets work
Prediction markets turn the probability of future events into tradable assets. The definitions below clarify the core terminology and the structural differences from ordinary gambling platforms.
Polymarket is a decentralized prediction market built on the Polygon blockchain and settled in USDC. Each market is a yes-or-no question, such as whether BTC will exceed 15 ten-thousand US dollars before 6/2026, whether Trump will win the 2024 election, or who will win the Champions League final in 6/2026. Each question creates two independent ERC-1155 tokens, one for the "Yes" outcome and one for "No." Prices range from 0 to 1 US dollars and can be interpreted as the market's estimate of the event's probability.
When you buy a "Yes" token, you essentially pay a counterparty willing to receive that money if the event does not happen. If the event does happen, each token settles at $1; the difference is your profit. A price of $0.65 means the market assigns a 65% probability, and buying means betting that the actual probability is higher than 65%.
Traders bet on whether the market's implied probability differs from the true probability, rather than on the event's outcome alone. Confusing these is the most common reason retail traders lose money.
Three required concepts
Condition ID
Market identifier
Represents an event question. A hexadecimal string derived from the oracle and question parameters.
Token ID
Outcome token ID
Each outcome (Yes/No) has its own ID. Orders use this ID, not the condition ID.
CTF
Conditional Token Framework
Conditional Token Framework. A smart contract system developed by Gnosis that lets outcome tokens be split and combined.
CLOB
Central Limit Order Book
Central Limit Order Book. An order-book matching architecture similar to Coinbase and Binance, rather than an AMM.
02 · Reality Check / Market reality
Market data to review before entering
The figures below were cross-validated from Bloomberg, Dune Analytics, and multiple academic papers. Understand them before writing your first line of code.
Since early 2025, more than 10 ten-thousand wallets have lost at least $1,000 on Polymarket, nearly twice the number of wallets that earned at least $1,000 over the same period. Among profitable accounts, profits are heavily concentrated in a small number whose behavior resembles automated bots. All remaining accounts together lost about 1.31 hundred-million US dollars.
University of Toronto professor Charles Martineau analyzed data since 2022 and found that about 69% of traders lose money on Polymarket, while the top 1% of accounts take 75% of profits. This is consistent with general research findings on retail trading.
| Group | Result | Interpretation |
|---|---|---|
| Top 0.51% of accounts | Cumulative profit > $1,000 | The vast majority are bots or professional teams |
| Top 1% of accounts | Take 80%+ of platform-wide profits | Highly concentrated |
| Accounts with 50+ trades | Already ahead of 77% of users | Most people only try it briefly |
| All wallets that have traded | 84.1% losing money | On-chain analysis of 2.5M wallets |
| Accounts earning $100K+ | Only 0.033% | Slightly more likely than winning the lottery |
Bots have an advantage in order speed, rather than prediction accuracy. Retail traders can predict the outcome correctly and still lose through delayed entry and poor execution prices.
This directly affects architecture decisions. An agent running on a laptop and calling Claude through the REST API for probability reasoning cannot compete in sub-100ms arbitrage, a segment dominated by bots connected to Chainstack private RPC. An effective alternative is to choose markets requiring semantic judgment and tolerating higher latency.
Markets where "humans + AI" still have a chance
Long-tail markets: Small, low-liquidity markets for which bots are unwilling to write dedicated logic, such as obscure sports or cultural events.
Markets requiring semantic understanding: Ambiguous questions that require reading ToS details to determine resolution.
News-driven but latency-tolerant markets: News analysis takes hours or days, rather than milliseconds.
Cross-market logical arbitrage: Breakdowns in the mathematical relationship between "Trump wins" and "Republicans win."
Endgame Sweep: When a market's price is > 0.97 and the result is almost certain, small retail traders rush to sell, leaving patient traders a small profit from 0.997 to 1.00.
Three APIs, one chain, and one locally managed private key
Polymarket divides its functions among three API endpoints. Knowing each endpoint's responsibilities is essential to diagnosing development errors.
| API | Hostname | Purpose | Authentication required |
|---|---|---|---|
CLOB API | clob.polymarket.com | Order book, orders, cancellations, positions | L1 (wallet) + L2 (HMAC) |
Gamma API | gamma-api.polymarket.com | Market metadata, including questions, token IDs, and 24h volume | None |
Data API | data-api.polymarket.com | Historical positions and PnL for any wallet (public on-chain data) | None |
Three common development problems
Problem one: using Gamma as an order book. Gamma's outcomePrices field is a delayed snapshot and may lag the real CLOB order book by several seconds. For price-sensitive decisions, always read CLOB get_order_book(token_id).
Problem two: confusing condition ID and token ID. Orders require the outcome token's token ID, with a separate ID for YES and NO, not the market's condition ID. Buying the wrong side causes a substantial loss.
Problem three: omitting negRisk: true. Multi-outcome markets, such as "Who will win the 2024 election?" with 5 candidates, use a negative-risk model in which all outcomes share one collateral pool. Orders in these markets must set negRisk: true in order options. Otherwise, the exchange contract rejects the order with an unclear error.
Signature types and client initialization
signature_type = 0
EOA / MetaMask
Wallets that directly hold a private key, including hardware wallets. You must manually approve the CTF contract's USDC allowance first.
signature_type = 1
Email / Magic Link
Accounts registered by email through the Polymarket UI. The most common type. The SDK handles CTF approval automatically.
signature_type = 2
Browser Wallet Proxy
Browser wallets using a proxy contract. Less common.
funder
Funding wallet address
The address that actually holds USDC. For Magic / proxy accounts, it differs from the address associated with PRIVATE_KEY.
Order types
| Type | Role | Behavior | Use case |
|---|---|---|---|
GTC | Maker | Limit order that stays on the book until filled or canceled | Market making and passive orders earning rebates |
GTD | Maker | Limit order that expires at a specified time | Pre-event orders to avoid forgetting them |
FOK | Taker | Market order that fills completely or cancels completely | Fast event-driven entry |
FAK | Taker | Market order that fills as much as possible and cancels the remainder | Large orders consuming liquidity in batches |
04 · Environment / Setup
Environment setup: dependencies and initialization
Python is used here because its SDK is the most mature. The workflow logic is the same in TypeScript or Rust; replace the SDK name.
Required items
Python 3.9+ and one of
venv/poetry/uvA Polymarket account holding USDC on Polygon
The account's private key, exported through Polymarket Settings → Private Key → Export
An Anthropic API key if you want Claude Opus / Sonnet for reasoning
A
.envfile that you will never push to GitHub
Project initialization
# Create the project
mkdir polymarket-agent && cd polymarket-agent
python3 -m venv .venv
source .venv/bin/activate
# Install packages
pip install py-clob-client-v2 python-dotenv requests anthropic
# Create the .env file
cat > .env <<EOF
POLYMARKET_PRIVATE_KEY=0x...
POLYMARKET_FUNDER_ADDRESS=0x...
POLYMARKET_SIGNATURE_TYPE=1
ANTHROPIC_API_KEY=sk-ant-...
EOF
# Remember
echo ".env" >> .gitignore
echo "__pycache__/" >> .gitignore
echo "*.db" >> .gitignoreInitial CLOB connection check
import os
from dotenv import load_dotenv
from py_clob_client_v2 import ClobClient, ApiCreds
load_dotenv()
# Level 0: no authentication, just a ping
client = ClobClient(host="https://clob.polymarket.com", chain_id=137)
print(client.get_ok(), client.get_server_time())
# Level 1: use the private key; derive API credentials on the first call
auth_client = ClobClient(
host="https://clob.polymarket.com",
chain_id=137,
key=os.environ["POLYMARKET_PRIVATE_KEY"],
signature_type=int(os.environ["POLYMARKET_SIGNATURE_TYPE"]),
funder=os.environ["POLYMARKET_FUNDER_ADDRESS"],
)
creds = auth_client.create_or_derive_api_key()
# Level 2: full authentication, with order placement
auth_client.set_api_creds(creds)
print("API credentials derived. You can now place orders.")You should see ok and the server time after execution. The most common error cause is an incorrect signature_type. Set Magic accounts to 1 and MetaMask to 0.
05 · First Trade / Initial trade
Market queries and the first order
Every token ID involves real money. Start with a small $1–$5 order to complete the workflow, then discuss strategies after confirming the path works.
Step 1: Gamma market query
import requests, json
GAMMA = "https://gamma-api.polymarket.com"
resp = requests.get(f"{GAMMA}/markets", params={
"closed": False,
"active": True,
"limit": 20,
"order": "volume24hr",
"ascending": False,
})
markets = resp.json()
for m in markets[:5]:
print(m["question"])
print(f" 24h vol: ${m.get('volume24hr', 0):,.0f}")
print(f" prices: {m.get('outcomePrices')}")
print(f" token_ids: {m.get('clobTokenIds')}")Step 2: Real order-book query (do not use Gamma prices)
target = markets[1]
yes_token_id = json.loads(target["clobTokenIds"])[0]
book = auth_client.get_order_book(yes_token_id)
best_bid = float(book.bids[0].price) if book.bids else None
best_ask = float(book.asks[0].price) if book.asks else None
spread = (best_ask - best_bid) if (best_bid and best_ask) else None
print(f"Best bid: {best_bid} | Best ask: {best_ask} | Spread: {spread}")Step 3: Small maker limit order
from py_clob_client_v2 import (
OrderArgs, OrderType, PartialCreateOrderOptions, Side
)
# Place a buy order 2 cent below best_ask. It fills if someone crosses to us.
# Otherwise wait passively to earn the maker rebate.
my_price = round(best_ask - 0.02, 2)
my_size = 5.0 # 5 shares at $0.XX each, keeping the total amount small
resp = auth_client.create_and_post_order(
order_args=OrderArgs(
token_id=yes_token_id,
price=my_price,
side=Side.BUY,
size=my_size,
),
options=PartialCreateOrderOptions(tick_size="0.01"),
order_type=OrderType.GTC,
)
print(f"Order ID: {resp['orderID']}")
print(f"Status: {resp['status']}")When the workflow succeeds, an order is on Polymarket's order book. All subsequent AI logic eventually reaches this create_and_post_order call.
06 · Anatomy / Agent anatomy
The AI agent's five-layer architecture
Connecting Claude directly to the CLOB API creates a script, not an agent. An agent needs five independently replaceable functional layers.
Postmortems of multiple public Polymarket bots point to the same conclusion: "Losses are usually caused by a missing event log, rather than insufficient reasoning ability." The architecture below is the minimal viable design derived from those cases.
| Layer | Responsibility | Technology |
|---|---|---|
| 1. Data | Snapshot 50–200 target markets every 5–15 minutes, including questions, spreads, depth, volume, and external news | CLOB + Gamma API + news APIs (Tavily, Brave Search, Exa) |
| 2. Filtering | Reduce hundreds of markets to a shortlist of a dozen or so candidates; reject suspicious liquidity, spreads, or wording | Pure Python rules; no LLM required |
| 3. Reasoning | Produce an estimated probability, confidence, reasoning chain, and news evidence for each candidate | Claude Opus 4.7 (accuracy) or Sonnet 4.6 (speed/cost balance) |
| 4. Decision | Use Kelly Criterion / Edge thresholds to decide whether to order and how much | Pure Python with risk limits and correlation checks |
| 5. Execution | Place and cancel orders, track positions, and retry failures | py-clob-client-v2 |
| Memory | Record every decision, including prompt, response, execution result, and subsequent resolution | SQLite / Postgres + Chroma (vector retrieval of news) |
Production discipline usually matters more than squeezing a bit more model accuracy. Upgrading the model version has limited benefit. Improving the logging system has a larger effect.
Key principle: separate opportunity discovery from order placement
A common error is combining the entire workflow into one function: get_markets → ask_claude → place_order. This creates two problems:
No traceability: After a loss, you cannot tell whether the LLM misestimated probability, the prompt received stale news, or the order book changed before the order.
No testing: You cannot simulate hypothetical trades over the past two weeks. Without backtesting, there is no iteration.
The correct approach is to have the reasoning layer output only structured probability estimates and reasoning, and hand the order decision to an independent, purely rule-based, reproducible function. The same LLM output can then be replayed against historical data with different decision parameters to find the best thresholds.
Prompt design for prediction-market probability estimates
According to the research literature, verbalized probability + chain-of-thought + explicit bias prompts are the three main ways to improve LLM probability calibration. The design below reflects the common approach found in multiple public Polymarket agent frameworks from 2026.
Use it as a template. Understand each part's purpose before adapting it to a specific strategy.
SYSTEM PROMPT — Polymarket Market Analyst · Production
You are a calm prediction-market analyst who evaluates probabilities. Estimate an event's true probability and compare it with the market price, rather than only predicting whether it will happen.
## Role and limits
- You are looking at a binary Polymarket market.
- Output a probability estimate between 0.00 and 1.00, to 2 decimal places.
- Do not refuse to answer. When uncertain, state "low confidence" and widen the interval.
- Use the market price as the starting point and assess whether it differs from the true probability.
## Reasoning steps (write each before outputting JSON)
1. Base rate: how often have similar events occurred historically?
2. Current signals: list up to 5 pieces of supporting evidence and up to 5 against.
3. Time decay: is enough time left for the conditions to be met?
4. Wording risk: is the question ambiguous? Could its resolution rules be unexpected?
5. Bias check: are you anchoring too heavily on recent news?
6. Final probability: combine the above into an estimate + a 90% confidence interval.
## Required JSON format
{
"reasoning": "<step-by-step reasoning in Chinese, at least 3 paragraphs>",
"supporting": ["..."],
"opposing": ["..."],
"base_rate": <0.0-1.0>,
"estimated_probability": <0.0-1.0>,
"confidence_interval_90": [<low>, <high>],
"confidence_level": "high" | "medium" | "low",
"key_risks": ["up to 3 factors that could make the estimate wrong"],
"wording_concerns": "<whether the question has semantic issues>"
}
Output JSON only, without surrounding explanations.USER PROMPT — Dynamically assembled for each decision · Per-call
## MARKET
Question: {market.question}
Description: {market.description}
Resolution criteria: {market.resolutionSource}
Resolution date: {market.endDate}
Current YES price: {best_ask}
Current NO price: {1 - best_bid}
24h volume: ${market.volume24hr}
Spread: {spread}
## CONTEXT (retrieved from news + RAG)
{retrieved_news_snippets}
## TODAY
{today_iso_date}
Follow the system prompt's steps and output the probability-estimate JSON.Three key prompt design decisions
1. Enforced JSON output + explicit schema. This lets post-processing call json.loads() directly and store each reasoning step in a database. Without a schema, you must parse with regular expressions, which causes serious problems.
2. Enforced confidence intervals + confidence levels. Anthropic and multiple academic studies report that an LLM's point estimate becomes better calibrated when it is also asked to explain its uncertainty. Compared with asking only for a probability, asking for the probability and its 90% confidence interval gives a Brier score that is 12–18% better on average.
3. An explicit base-rate step. A core point Tetlock repeatedly makes in Superforecasting: good forecasters always start with the historical frequency of similar events. Without a base-rate step, LLMs are easily over-anchored on recent news.
Advanced: swarm of personas
Research frameworks such as PolySwarm (arXiv 2604.03888) have 50 LLM personas assess the same market simultaneously, such as a conservative financial journalist, game theorist, political commentator, and market maker. Their probability estimates are combined through confidence-weighted Bayesian aggregation. This significantly corrects single-LLM bias at the cost of 50 times the API spending.
A practical compromise is to run 5 personas for 70% of the benefit. Anthropic prompt caching avoids recomputing the shared system prompt each time, keeping total cost acceptable.
08 · Strategies / Trading strategies
Five trading strategies with public validation records
These strategies have public implementation and backtesting records. Understand existing strategies thoroughly before developing original methods.
Strategy A — Endgame Sweep
When a market is near resolution and the result is almost certain, such as a match at minute 90 with a 5 to 0 lead, its price approaches $0.99. Many small retail traders, worried about "what if" or eager to close the position, sell at $0.997 or $0.998. Patient buyers can take all these orders and receive $1.00 at resolution a few days later, earning a 0.2–0.5% risk-free profit (under reasonable estimates).
Implementation points:
Trade only markets with < 24 hours remaining and an almost-certain result.
Set a threshold of "Yes probability > 99%" that the LLM must meet.
Use GTD orders with expiry before resolution.
Be careful: a small number of resolutions have unexpected outcomes, such as a referee changing a ruling or an Oracle dispute. Always retain a risk budget.
Strategy B — Logical Arbitrage
Mathematical relationships between related markets sometimes break down. For example, a lower price for "Trump wins" than "Republicans win" is mathematically invalid unless there is a non-Trump Republican candidate. Short the overpriced side and buy the underpriced side simultaneously to lock in the spread.
Another common combination is the sum of "Trump wins AZ" + "Trump wins NV" + ... being approximately equal to "Trump wins 270+." The difference is the arbitrage opportunity.
Strategy C — Latency Arbitrage
In crypto-related markets, such as whether BTC exceeds X US dollars before month-end, BTC spot prices on a CEX typically lead Polymarket's implied probabilities by seconds to minutes. Build a log-normal pricing model to convert live BTC prices into prediction-market implied probabilities, then order when a spread appears.
Drawback: competition is already very intense. Sub-100ms bots capture 73% of arbitrage profits. You need private RPC (Chainstack, QuickNode) to have a chance. Unsuitable for beginners.
Strategy D — Copy Trading Whales
Because all Polymarket trades are public on-chain, you can select wallets with high historical PnL and follow with a small fraction whenever they open a new position. PolyTrack, Stand.trade, and Polymarket Analytics provide whale alerts.
Drawback: leading whales such as Fredi9999 / Theo use multiple wallets to obscure their activity, so you may follow the wrong person. When whales also use bots, by the time your script sees the on-chain event, other copy-trading bots have already pushed the price up.
Strategy E — Nothing Ever Happens (NO baseline strategy)
Since 73.3% of Polymarket markets ultimately resolve NO, blindly buying every NO should theoretically have positive expected value. Sterling Crispin's open-source bot tested this hypothesis and still lost money because opening NO prices had already priced in the base rate.
This strategy teaches developers to explicitly define the conditions under which a simple blind strategy can make a profit. Crispin's revised version, buying only NO below $0.65, has a statistical possibility of positive expected value.
09 · Risk Management / Risk controls
Risk controls: kill switch and position limits
In the case analyzed by Lookonchain, a trader who lost 200 ten-thousand US dollars in 35 days had a 51% win rate. Prediction ability was not the problem. The root causes were oversized individual positions and the lack of an automatic stop-loss mechanism.
Four required programmatic limits
1 — Quarter Kelly
Bet size
Calculate the theoretically optimal position with Kelly Criterion, then use only 1/4 of it. This is the optimal balance supported by academic research and industry consensus, substantially reducing bankruptcy risk while preserving compounding.
2 — Per-trade cap
Per-trade limit
Whatever Kelly produces, a single trade must never exceed 5% of total funds. Beginners should use 1–2%.
3 — Daily loss limit
Daily stop-loss
Automatically stop new orders when daily losses reach 10% of total funds. Revisit it after an overnight pause. Consecutive bad days are an early signal of strategy failure.
4 — Correlation guard
Correlation control
When opening multiple correlated markets, such as several Trump-wins-X-state positions, sum total exposure and reject new orders when it exceeds the limit.
Kill Switch: file-triggered agent shutdown
import os, sys, time
KILL_FILE = "/tmp/polymarket_agent.kill"
DAILY_LOSS_LIMIT = 0.10 # 10% of bankroll
def should_continue(state):
# 1. File kill switch (human emergency stop)
if os.path.exists(KILL_FILE):
print("Kill file detected. Shutting down.")
return False
# 2. Daily loss
today_pnl_pct = state.today_pnl / state.starting_balance
if today_pnl_pct < -DAILY_LOSS_LIMIT:
print(f"Daily loss limit hit: {today_pnl_pct:.1%}. Halting.")
return False
# 3. API connection health
if state.consecutive_api_errors > 5:
print("Too many API errors. Halting.")
return False
return True
# Call before each decision in the main loop
while True:
if not should_continue(agent_state):
sys.exit(0)
run_decision_cycle()
time.sleep(60)An agent inevitably encounters abnormal conditions while running. At that point, the system needs a mechanism for graceful shutdown with touch /tmp/polymarket_agent.kill, rather than more complex program logic.
10 · Community / Community insights
Community feedback: selected r/polymarket advice
r/polymarket (5 ten-thousand members), prediction-market discussions on X, and Crypto Twitter are important sources beyond official documentation, but include many unverified claims. The following practical advice has been filtered.
Common community recommendations (filtered)
High-risk items consistently warned against by the community
Paid "signal" groups: 99% profit from selling services. The 1% who actually win will not charge you $50 per month.
One-click "copy trade everything Theo does" bots: Leading whales use multiple wallets to obscure their activity; you may be following an operation that conceals the real trades.
"Profit immediately on launch" promises without a paper trade period: Too many GitHub bots with hundreds of stars have lost all their money after two weeks.
Giving private keys to cloud IDEs or ChatGPT: This directly leads to bankruptcy, with no recovery.
Higher-quality Reddit analysis usually appears several days after major events. Popular posts during an event contain more emotion and should be treated as noise.
11 · Legal / Law and ethics
Legal and compliance requirements to check before execution
Technical feasibility and legal compliance are independent issues. This section lists specific matters to check with a legal adviser and does not constitute legal advice.
US citizens are explicitly prohibited: Using a VPN to bypass a geofence violates the ToS and may freeze your funds.
Many other jurisdictions also restrict access: These include France, Singapore, Belgium, and others. Check your location first.
Tax obligations: In your jurisdiction, prediction-market profits are generally treated as ordinary income or capital gains. On-chain records are public; pretending they do not exist is not a strategy.
Market manipulation risk: A bot placing many orders simultaneously and causing large price moves may violate the law. Even in crypto markets, the legal gray area for this behavior is rapidly shrinking.
Inside information: Betting with nonpublic information about an event, such as information held by stadium staff or political aides, may constitute fraud in many jurisdictions.
12 · Roadmap / Milestones
Six-week milestones from environment setup to deployment
This is a compressed schedule with explicit weekly deliverables. The fourth week's paper trade stage is the most frequently skipped step and the one that best prevents loss of funds.
Week 1 · Infrastructure
Environment setup + first manual order
Create a Polymarket account, deposit $20 USDC, install the SDK, complete hello world, and manually place then cancel a $1 GTC order. Confirm the whole workflow operates.
Week 2 · Data pipeline
Market snapshots and filter construction
Fetch order books, spreads, and depth for 50 high-volume markets every 15 minutes. Store them in SQLite. Write filtering logic for liquidity, spreads, and wording. Do not place orders yet.
Week 3 · Reasoning layer
Claude connection and probability estimates
Implement the chapter-seven prompt. Call the LLM for every filtered market and record the complete input, output, and token usage. Keep daily cost at $1–$3.
Week 4 · Paper Trading
Complete decision cycle (no real orders)
Connect LLM probability estimates + Kelly calculations + risk rules. The decision layer produces and records hypothetical trades. Simulate at least 200 hypothetical trades and calculate theoretical PnL, Brier score, and calibration.
Week 5 · Live (very small orders)
First real trade
Start with the strategy that had the highest win rate in Week 4, using $1–$5 per trade. Run for a week and manually review every decision each day. You will see LLM output bias, API edge cases, and resolution delays; correct them individually.
Week 6 · Risk hardening
Kill switch + monitoring + alerts
Implement the four limits described earlier, Slack or email alerts, and daily PnL reports. Confirm you can stop the agent within 30 seconds. Only then consider increasing positions.
This guide will be updated continuously. Polymarket's APIs, SDKs, and market structure continue to evolve in 2026. When you see a tool promising guaranteed profit, refer back to the figure at the start of this guide: 84.1%.
A Tenten Field Guide · No. 04 · 2026 Edition
Compiled with research from Polymarket Docs · Bloomberg · Reddit r/polymarket · arXiv · Multiple bot teardowns