Article
Build a Polymarket Bot in Python: Read Market Data First
Start a Polymarket Python bot with public APIs, the official SDK and WebSocket data. Learn market IDs, order-book recovery and how to estimate fill prices.

To build a Polymarket bot in Python, start with public market data: find a market, identify its outcome tokens, read the order book, follow live updates and record what arrives. This first version needs no private key and submits no orders.
The tempting plan is simple: let an AI read the news, spot an opportunity and make money. Unfortunately, that describes a wish rather than a working system. Somewhere between the headline and the trade, the program still has to know which market it is looking at and whether the price is real.
A better first project is a bot that watches a few markets and can explain what it saw. It finds the right outcome, keeps track of available bids and offers, records public trades and notices when its own data has gone stale.
That may sound less exciting than an automatic money machine. It is considerably easier to debug before adding the money.
What should your first Polymarket bot do?
Give the prototype a narrow job. It should find selected markets, save their rules and identifiers, read prices and order books, collect live updates and keep a useful history. Basic analysis can then flag an unusually large trade, a wider spread or a sudden loss of liquidity.
The output is an observation or an alert. At this stage, success means being able to show which information the bot had and why it produced that observation.
If the bot cannot distinguish a fresh order book from one left behind by a broken connection, adding an order button will not solve the problem. It will give the problem purchasing power.
Gamma, CLOB, Data API and WebSocket: which does what?
Polymarket has several data interfaces because finding a market and following its order book are different tasks. An API is simply the interface through which your program asks for information or performs a supported operation.
Gamma API is where discovery begins. It provides events and markets, descriptions, identifiers and related metadata. Before looking at a price, use that information to establish what the market actually asks.
CLOB API serves the central limit order book: bids, offers, prices and trading parameters. It also supports trading functions, but this project uses only public data. A price without the quantity available at that price tells an incomplete story.
Data API supplies public analytics such as trades, positions, holders and wallet activity. It helps you investigate what participants have done. It does not explain their intentions automatically.
WebSocket supplies an ongoing stream of updates. A normal request gives you a snapshot; a connection to the stream lets your program follow changes as messages arrive. Occasional analysis can use periodic requests. A continuously updated order book benefits from a stream.
You may also encounter the Relayer API, which supports certain wallet transactions. It has no job in this first observer. You do not need to understand every part of the trading infrastructure before reading your first market.

Choose the Python SDK before copying examples
The official package is called polymarket-client; Python imports it as polymarket. The examples here use version 0.11.0, which requires Python 3.11 or later.
The SDK provides PublicClient and AsyncPublicClient, plus secure variants for authenticated workflows. Public clients are enough for the market data used here. No signing key is required.
A synchronous client is perfectly reasonable for a notebook or a small, occasional export. The asynchronous client is useful when the program must listen to a stream while waiting for other network responses. In this SDK, real-time subscriptions use the asynchronous clients.
Async lets the program use waiting time efficiently. It does not make a slow calculation magically fast, and blocking work can still hold everything up.
Older tutorials may use different packages and method names. Mixing their examples with the newest SDK can turn a short evening project into software archaeology. Pin a version you have checked, then test changes before upgrading.
Set up a small project
Create a virtual environment so that this project's dependencies stay separate from other Python work:
python -m venv .venv
On Linux or macOS, activate it with source .venv/bin/activate. In Windows PowerShell, use .venv\Scripts\Activate.ps1. Then install the version used by the examples:
python -m pip install polymarket-client==0.11.0
That is enough to start. Additional libraries for logging, retries or news feeds can come when there is a concrete need for them. SQLite is a reasonable starting point for a small local history; a larger database can follow when the workload requires it.
Two watched markets do not automatically require seven services and an orchestration platform. Infrastructure enthusiasm benefits from a position limit too.
Read your first page of markets
This complete script retrieves one page of markets that are not marked closed and prints their identifiers. Save it as list_markets.py and run python list_markets.py:
import asyncio
from polymarket import AsyncPublicClient, PolymarketError
async def main():
try:
async with AsyncPublicClient() as client:
pages = client.list_markets(
closed=False, page_size=20
)
page = await pages.first_page()
for market in page.items:
print(market.id, market.slug,
market.condition_id)
except PolymarketError as exc:
print(f"Market data request failed: {exc}")
if __name__ == "__main__":
asyncio.run(main())
The paginator retrieves results in pages rather than downloading the entire catalog at once. One page is a sample of the catalog, not the whole market universe.
Also, closed=False does not prove that a market accepts new orders or has a usable book. Inspect the selected market's status, rules, outcome tokens and trading parameters before treating it as available.
In a running observer, refresh discovery periodically and reserve the stream for frequent market updates. Do not repeatedly scan everything to learn whether one price changed. Handle rate limits separately and retry with limits rather than sending the same request faster.
Market IDs and token IDs are different things
Imagine a fictional event about a game's launch. It could contain several markets, including one asking whether the full game will be available to buy before month-end.
The event ID identifies the group. The market ID identifies the individual question. A condition ID identifies the condition used in market analytics. Each tradable outcome has its own token ID, which you use to request its order book or subscribe to updates.
A slug is a readable identifier useful for finding a market and labeling logs. It does not replace a token ID. Some responses also contain a question ID; keep that field separate rather than assuming every identifier means the same thing.
Passing a condition ID to a method expecting an outcome token is like giving a courier your passport number instead of an address. The information may be valid. It is still the wrong information.

Get the outcome tokens, then read the book
Inside an existing async with AsyncPublicClient() as client: block, fetch a selected market by its actual slug. The placeholder below must be replaced:
market = await client.get_market(slug="YOUR_MARKET_SLUG")
yes_id = market.outcomes.yes.token_id
no_id = market.outcomes.no.token_id
if not yes_id or not no_id:
raise ValueError("Missing outcome token IDs")
book = await client.get_order_book(token_id=yes_id)
best_bid = max((x.price for x in book.bids), default=None)
best_ask = min((x.price for x in book.asks), default=None)
Store the token together with its market, condition and outcome label. Do not rely on remembering that the first element of an unfamiliar array “must be YES.”
The highest bid is the best current buying offer; the lowest ask is the best selling offer. Compute them explicitly instead of assuming that the first returned level is best. Either side can be empty, which is why the example allows None.
When both sides exist, the spread is best ask minus best bid, and the midpoint is halfway between them. Neither value tells you the average price of a large purchase. That requires depth.
Use WebSocket to follow changes
The following function listens to a selected outcome token and prints event types. Call it with a token ID you have obtained from the market:
from polymarket import AsyncPublicClient
from polymarket.streams import MarketSpec
async def watch(token_id):
async with AsyncPublicClient() as client:
async with await client.subscribe(
MarketSpec(token_ids=[token_id])
) as stream:
async for event in stream:
print(event.type)
For example, a script can call asyncio.run(watch("YOUR_TOKEN_ID")) after importing asyncio. This is a subscription example, not a complete local order book.
The standard market events include book for a snapshot, price_change for level changes, last_trade_price for trade information and tick_size_change for a change in the price increment. Additional events require the appropriate subscription option.
Those messages have different jobs. A trade print should not be processed as though it were a replacement order-book level. Receiving messages is the beginning; keeping their meaning straight is the work.
Build a local book that can become stale
A local order book is your program's current picture of available bids and asks. Keep the two sides separate, with a price and size for each level.
A full snapshot replaces that picture. A level update sets the new size at the specified price; it is not an extra amount to add. A zero size removes the level. Check the outcome token and the side before applying the change, then recalculate the best prices.
Keep the latest trade and market parameters separately. If you have already applied an order-book update, subtracting the associated trade again can count the same change twice.
There is also an easy gap to miss: fetch a REST snapshot, spend a moment opening the socket, and changes may happen in between. Simply joining those two sets of data does not make them one continuous history.
For a first stream-based book, establish a baseline from a complete book snapshot on the subscription, then process subsequent updates from that connection. If you combine REST and streamed data, you need an explicit ordering and recovery design.
After a disconnect or suspected inconsistency, mark the previous state stale. Stop using it for price-sensitive alerts, establish a fresh baseline and only then treat updates as current again. A new connection does not restore every message you missed.
Record snapshots, connection changes and recovery attempts. Monitor connection health and data age; a quiet market alone does not prove the connection is dead. A book hash can help identify a reported state, but it is not a sequence number proving that your history is complete.
A bot using liquidity from ten minutes ago has become a historical research project. That is a valid hobby, but it needs a different label.

Why prices and sizes should use Decimal
Binary floating-point numbers can introduce small representation errors into decimal prices. For price, share size and money calculations, use decimal values consistently. The SDK already uses Decimal for precision-sensitive fields.
When creating your own values, construct them from strings, such as Decimal("0.45"), rather than converting a float after the approximation has already happened.
This keeps the arithmetic predictable. It does not fix the wrong token, an outdated book or an incorrect calculation. Better numbers still need a correct question.
The best ask is not the price of your whole purchase
Suppose a hypothetical order book has these offers:
| Price per share | Shares available | Shares used for a 100-share purchase |
|---|---|---|
| $0.45 | 10 | 10 |
| $0.49 | 40 | 40 |
| $0.54 | 100 | 50 |
| $0.60 | 500 | 0 |
The first ten shares cost $4.50, the next forty cost $19.60, and the remaining fifty cost $27.00. The total is $51.10, giving an average price of $0.511 per share.
The best ask was $0.45. It was the price of the first ten shares, not a promise that the whole purchase could happen there.
This estimate excludes fees and assumes those offers remain available. In a live market, other participants can trade or cancel before your order arrives. A calculation from a snapshot is an estimate, not a reservation.

An estimator should work from the cheapest ask upward and report both the average price and how many shares it could fill. If only sixty of the requested hundred are available, return that shortfall explicitly. Averaging the sixty and calling the whole order filled would hide the important part.
Before turning a price observation into a trading decision, account for available size, price limits, fees and the liquidity left afterward. A large entry can be difficult to unwind even when the first quote looked attractive.
Read public trades and holders without guessing intent
With an open public client and a known condition ID, the checked SDK uses these calls for the first pages of trades and holders:
trades = await client.list_trades(
condition_id=condition_id, page_size=20
).first_page()
holders = await client.list_market_holders(
condition_ids=[condition_id], page_size=20
).first_page()
Trade records can include a wallet, side, price, share size, timestamp and outcome. In this SDK version the outcome asset identifier is exposed as asset_id. Read fields from the model you are actually using rather than mixing raw API responses with an older tutorial.
Holder results are grouped by outcome asset. The page size applies per outcome, and reading a full history or holder set requires pagination. A first page is not a complete picture of ownership.
The current holder list shows who holds a position now; it does not by itself reconstruct every entry that built it. Combine it with recorded trades and position changes when investigating behavior.
Even then, a purchase might be a directional view, a hedge or part of market making. The data gives you an action. The explanation remains something to investigate.
A whale alert needs units and context
“Size greater than 50,000” is not yet a useful rule. Fifty thousand shares and fifty thousand dollars are different quantities. A trade also means something different in a deep market than in a nearly empty one.
Compare size with current book depth, recent volume and the wallet's previous activity. Keep those measures distinct: open interest describes outstanding positions, not immediately available offers.
Wallet specialization, entry quality and repeated results can add context. They still do not reveal every hedge, position on another platform or the identity behind an address. Avoid turning missing information into a confident story.
Historical testing adds another trap. A wallet's eventual profit or the outcome of a market cannot be used to label it “smart” before your system could have known that result. Otherwise, the backtest has invented time travel and filed it under analytics.
Record what arrived first. Evaluate what happened afterward separately.
Save when the event happened and when you saw it
Keep the source timestamp alongside received_at, the time your program received the information. These answer different questions: when the source says something happened, and when your bot could begin using it.
The difference can help investigate delays, but it is not a pure network measurement. Source processing, indexing and clock differences can all affect it.
For each observation, save the market and outcome mapping, source, available prices and quantities, and the raw event or enough detail to reconstruct your analysis. Store trade fields separately from book fields. Do not invent a wallet address for an anonymous book update.
Also record the code and SDK versions, relevant configuration, disconnects and fresh snapshots. A log should let you explain why the bot produced an alert, including whether its data was current at the time.
Without that history, “the bot saw something unusual” is difficult to distinguish from “the bot had a bug.” Both can generate an impressively urgent notification.
Keep the architecture small and the responsibilities clear
A practical observer has two data paths. Discovery selects the markets and establishes their identifiers. The live-book path then maintains prices and depth, while a separate analytics path collects public trades and wallet information.
Storage records the observations and technical events. Analysis compares them and produces local alerts: a wider spread, disappearing liquidity, an unusual trade or a change in a watched position.
These responsibilities can live in one Python process. Separate modules for discovery, streams, books, storage and analysis are enough to prevent one function from doing every job in the project.

The design needs tests for wrong identifiers, empty books, incomplete depth and recovery after a connection loss. A successful request proves that one request worked. It does not prove continuous monitoring will remain correct overnight.
Does the first version need an LLM?
No. A language model may later help read news or extract conditions from text. First establish reliable market selection, identifiers, book updates, public records and history.
An LLM cannot reconstruct a missed snapshot just because the prompt asks it to be careful. Nor can fluent reasoning repair a YES token accidentally mapped to NO.
Add text interpretation when the data system is ready to support it. Otherwise, you risk using a prompt to explain away a plumbing problem.
Questions about building a Polymarket Python bot
Which Python SDK should I use?
The official package is polymarket-client. These examples target version 0.11.0 with Python 3.11 or later. Match examples to your installed version and check changes before upgrading.
Do I need a private key to read markets?
No. The public market, order-book and analytics workflows described here use public clients without signing keys. Authenticated account and trading operations are a separate scope.
Do I need a WebSocket connection?
Not for every task. Periodic requests can serve occasional analysis. A stream is useful for a continuously updated book, provided the program handles freshness, disconnects and recovery.
Can Python read wallet data?
Yes. Public interfaces expose records such as trades, holders and positions. Those records do not automatically identify the person behind an address or explain the complete strategy.
Can Polygon monitoring reveal a whale's next order?
No. Orders are created and matched off-chain, while settlement is recorded on-chain. A resting order may appear in the public book before execution, but that is different from knowing someone's future intention.
Why use Decimal instead of float?
Decimal arithmetic avoids binary representation errors in decimal prices when values are created correctly. It helps make calculations predictable, but does not validate the market data or the strategy.
Can I add order submission immediately?
The SDK supports trading workflows, but the examples here establish only a starting point for observation. Execution needs separate work on authorization, realistic costs, risk limits, recovery and stop conditions.
Observe first, then decide what deserves automation
The useful milestone is a bot that knows which outcome it is watching, can tell whether its book is current, calculates the cost of a quantity correctly and leaves a reproducible record.
The short scripts begin that work. They do not create a complete trading system or demonstrate a profitable strategy.
Before considering live orders, test decisions without execution, model fees and realistic fills, check geographic eligibility and define when the system must stop. Sending an order is a small piece of code. Knowing when it should not be sent is the larger project.