codingBy HowDoIUseAI Team

How to build Polymarket AI agents that don't blow up your bankroll

Learn how to build Polymarket AI agents from scratch, connect the CLOB API, design decision logic, and size positions so a losing streak doesn't wipe you out.

Polymarket isn't a niche corner of crypto anymore. It's a market with 2.4 million traders and roughly $62 billion in total volume, and NYSE's parent company invested $2 billion at a $9 billion valuation in 2025. That kind of liquidity, combined with an open API, is exactly why developers have started pointing autonomous agents at it instead of clicking buy and sell buttons themselves.

But here's the part most tutorials skip: building a Polymarket AI agent that executes trades is the easy 20%. The hard 80% is making sure that agent doesn't lose money faster than a human would. This guide walks through both halves — the technical setup and the risk logic that actually keeps an agent solvent.

What exactly is a Polymarket AI agent?

At its core, it's a program that reads market data, forms a probability estimate using an LLM or a statistical model, compares that estimate to the market's current price, and places an order if there's enough of a gap to justify the risk. Polymarket itself is a non-custodial prediction market on Polygon PoS, where users trade binary outcome tokens priced between $0 and $1 based on collective market belief. Markets resolve through UMA's Optimistic Oracle, which means settlement is trustless and doesn't depend on Polymarket manually grading outcomes.

An AI agent slots into this pipeline as the decision-maker. It doesn't need to out-think every trader on the platform — it just needs to be right slightly more often than the price implies, and it needs to size bets so that being wrong doesn't end the experiment.

Which APIs do you actually need?

Start with the official documentation at docs.polymarket.com, which is the primary reference for every SDK and endpoint discussed here. Polymarket splits its API into two completely separate services, and understanding which one to use for what is the first thing that trips up most developers.

Here's the breakdown:

  • Gamma API — the read-only discovery layer you use to browse markets, get metadata, and check prices. No authentication required.
  • CLOB API — handles all trading operations and requires API key authentication with HMAC-SHA256 request signing.
  • Data API — covers user-level analytics like current positions, full trade history, realized and unrealized P&L, and per-wallet activity feeds, which matters once you're building dashboards or analyzing strategy performance.
  • WebSocket feed — delivers real-time updates across four channels: market data, user fills and cancellations, live sports markets, and an institutional feed.

One detail that catches almost everyone off guard: Polymarket cancels all open orders when an authenticated session goes inactive, so bots need to send a heartbeat to stay active. If your agent goes quiet for maintenance and comes back to find its resting limit orders gone, that's expected behavior, not a bug.

Also worth noting for anyone building from scratch in 2026: Polymarket shipped CLOB V2 on April 28, 2026, moving collateral to pUSD, changing order signing, and retiring the legacy py-clob-client. Make sure any tutorial or code snippet you're following targets the current client generation.

How do you set up your development environment?

Polymarket provides official open-source clients in TypeScript, Python, and Rust, and all three support the full CLOB API including market data, order management, and authentication. For most agent builders, Python is the practical choice because it plays nicely with the LLM and data-science tooling you'll need for decision logic.

Install the current client:

pip install py_clob_client_v2

Authentication happens in two layers. First, you derive API credentials from your wallet's private key (this is "L1 auth"). Then you initialize a fully authenticated client using those credentials for actual order placement:

import os
from py_clob_client_v2 import ClobClient, OrderArgs, OrderType, Side

client = ClobClient(host="https://clob.polymarket.com", chain_id=137, key=os.environ["PK"])
creds = client.create_or_derive_api_key()

client = ClobClient(host="https://clob.polymarket.com", chain_id=137, key=os.environ["PK"], creds=creds)

From there, placing a resting limit order takes a token ID (pulled from the Gamma API for the specific market outcome you're targeting), a price, a side, and a size. If you'd rather work in TypeScript, Polymarket's clob-client repo mirrors the same structure with ApiKeyCreds and ClobClient objects.

Don't want to build the agent scaffolding yourself? Polymarket's own agents repository is built for exactly this — it standardizes connectors for data sources and order types, and it's worth cloning even if you plan to heavily modify it.

Two things to sort out before you write a single line of trading logic:

  1. Fund a wallet on Polygon. You'll need USDC (or the newer pUSD collateral) plus a small amount of MATIC for gas.
  2. Check your jurisdiction. Terms of Service prohibit US persons and persons from certain other jurisdictions from trading on Polymarket, via the UI, the API, and agents developed by persons in restricted jurisdictions. This applies to your agent's operator, not just the interface it uses.

How do you build the decision-making logic?

This is where most tutorials get vague, so let's get specific. A working agent pipeline typically looks like this:

  1. Pull candidate markets from the Gamma API, filtered by volume, category, or time-to-resolution.
  2. Gather context — news, historical odds movement, related market prices. Some agent frameworks use a vector database like Chroma for vectorizing news sources and other API data, so the reasoning layer can retrieve relevant context instead of stuffing everything into a single prompt.
  3. Generate a probability estimate. This is usually where an LLM (or an ensemble of models) reads the gathered context and outputs a number: "I estimate a 63% chance this resolves YES."
  4. Compare against market price. If your model says an event has a 60% chance of occurring and the market is pricing it at $0.45, you have a 15-point edge. That gap is your signal.
  5. Size the position (covered below) and route the order through the CLOB.
  6. Log everything. Every estimate, every trade, every outcome. You cannot improve calibration without a record to check it against.

Frameworks like Polymarket's Gamma client class exist specifically to fetch and parse market and event metadata, retrieving current and tradable markets and specific information, which makes step one straightforward to automate rather than something you hand-roll from raw HTTP calls.

What risk management rules keep your agent alive?

This is the section that separates agents that survive from agents that get shut off after one bad week. A notable share of Polymarket wallets lose money overall — and it's rarely because their predictions were bad. It's because position sizing was reckless.

Use fractional Kelly, not full Kelly. The Kelly Criterion tells you the mathematically optimal bet size given your edge, but full Kelly can suggest betting 30% of your bankroll on a single position, which is almost certainly too aggressive. Why? Your probability estimate is never perfectly accurate — if you think the true probability is 72% but it's actually 65%, your Kelly fraction is wildly overstated, and small estimation errors compound dramatically at full Kelly. The research backs this up hard: full Kelly creates roughly a 33% probability of halving your bankroll before doubling it. Most agent operators can't stomach that swing, and neither can most business cases for running a bot.

The practical fix is to bet a fraction of what Kelly recommends. Quarter Kelly captures most of the compounding benefit while reducing variance by roughly 75% compared to full Kelly.

Cap correlated exposure. If your agent is running multiple positions tied to the same underlying event — say, several election-adjacent markets — treat them as one combined bet for sizing purposes. The working rule is that if correlated positions could all resolve against you on the same night, their combined Kelly fraction shouldn't exceed 20-25% of your bankroll.

Set a hard portfolio ceiling. Most disciplined traders cap total Kelly exposure at 20-30% of bankroll regardless of what individual position calculations suggest, and this rule should be coded into your agent's order logic, not left to discretion. An agent doesn't get nervous and skip a trade the way a human might — it will happily execute every signal you give it, which means the guardrails need to live in code.

Cap any single position. A reasonable ceiling is 2-5% of bankroll per position, which lands roughly between quarter-Kelly and half-Kelly for a typical prediction market edge.

Build in an exit and redemption routine. Winning positions don't automatically become cash. Verify approvals with allowance reads at startup, and redeem resolved positions so capital doesn't sit idle. An agent that forgets to redeem is an agent leaving money parked in resolved markets doing nothing.

If you want to skip building the sizing math yourself, a Kelly Criterion calculator built specifically for binary prediction markets can sanity-check your agent's position sizes before you wire the logic into production.

What does a profitable agent configuration actually look like?

The agents that hold up over time tend to share a few traits. They don't spread bets evenly across every category — sports, politics, crypto, and pop-culture markets all behave differently, and treating them the same is a common rookie mistake. Sports markets resolve fast and frequently, which gives an agent far more data points to calibrate against in a short window compared to a single presidential election that resolves once every four years.

They also run on tight, well-documented rulesets for exits. Instead of "sell when it feels right," a working config specifies exact conditions: sell the full position at a defined profit target, scale out in fixed dollar increments as a market moves in your favor, or exit entirely if the probability gap closes below a minimum threshold. Vague exit logic is where a lot of otherwise-solid agents leak profit back to the market.

And they log obsessively. Every agent worth running in production tracks its calibration — how often a "70% confident" call actually resolved YES — because that's the only way to know if the model driving your decisions is actually any good, or just riding a lucky streak.

What mistakes should you avoid?

  • Skipping the heartbeat. Your orders vanish if the session goes idle, and a silently cancelled order is worse than no order at all if your agent assumes it's still working.
  • Ignoring correlation. Five "independent" bets on the same election night are really one big bet.
  • Trusting full Kelly. Prediction market participants are systematically overconfident by 5-10 percentage points on average, which alone makes full-Kelly sizing ruinous.
  • Forgetting jurisdiction rules. Automating a trade doesn't change who's legally responsible for placing it.
  • Not versioning your prompts and models. If your LLM provider updates silently, your agent's "edge" might quietly disappear with it.

Where should you go from here?

Clone Polymarket's agents repository, read through the CLOB client SDKs, and build your first version against a small, boring market before pointing it at anything with real volume. The unglamorous work — heartbeats, redemption routines, correlation caps — is what determines whether your agent is still running in six months or whether it's a cautionary tale in someone else's blog post.

The edge in prediction markets was never really about having the smartest model. It's about being the only trader in the room with a sizing rule you actually follow.