Unified Polymarket APIs with Pydantic data validation - Clob, Gamma, Data, Web3, Websockets, GraphQL clients.
Project description
polymarket-apis 
Unified Polymarket APIs with Pydantic data validation - Clob, Gamma, Data, Web3, Websockets, GraphQL clients.
Polymarket Mental Models
Events, Markets and Outcomes
The Polymarket ecosystem is organized hierarchically:
flowchart LR
A([Event]) --- B([Market A])
A --- C([Market B])
A ~~~ Dot1@{ shape: sm-circ}
A ~~~ Dot2@{ shape: sm-circ}
A ~~~ Dot3@{ shape: sm-circ}
A -.- D([Market n])
B --- E([Outcome 1])
B --- F([Outcome 2])
C --- G([Outcome 1])
C --- H([Outcome 2])
-
Event — represents a proposition or question such as “How many Fed rate cuts in 2025?”.
- Identified by a human-readable
slug(e.g.how-many-fed-rate-cuts-in-2025) and an eventid(e.g.16085).
- Identified by a human-readable
-
Market — represents a specific option for the related event (e.g. 1 rate cut in 2025). An Event has 1 or more corresponding Markets. (e.g. 9 options in this case - {0, 1, 2, ..., 7, 8 or more} rate cuts in 2025)
- Identified by a
condition id(e.g.0x8e9b6942b4dac3117dadfacac2edb390b6d62d59c14152774bb5fcd983fc134efor 1 rate cut in 2025), a human-readableslug(e.g.'will-1-fed-rate-cut-happen-in-2025') and a marketid(e.g.516724).
- Identified by a
-
Outcome — represents a binary option related to a market. (most commonly
Yes/No, but can be e.g.Paris Saint-Germain/Inter Milanin the case of a match where draws are not possible)- Identified by a
token id(e.g.15353185604353847122370324954202969073036867278400776447048296624042585335546for theYesoutcome in the 1 rate cut in 2025 market)
- Identified by a
-
The different APIs represent Events/Markets differently (e.g. Event, QueryEvent / ClobMarket, GammaMarket, RewardsMarket) but they all use to the same underlying identifiers.
Tokens
- Tokens are the blockchain implementation of Outcomes - tradable digital assets on the Polygon blockchain that users buy, hold and sell on Polygon.
- This helps ensure the logic of binary outcome prediction markets through smart contracts (e.g. collateralization, token prices going to $1.00 or $0.00 after resolution, splits/merges).
Splits and Merges
- Holding 1
Yesshare + 1Noshare in a Market (e.g.'will-1-fed-rate-cut-happen-in-2025') covers the entire universe of possibilities and guarantees a $1.00 payout regardless of outcome. This mathematical relationship enables Polymarket's core mechanisms: splitting (1 USDC → 1Yes+ 1No) and merging (1Yes+ 1No→ 1 USDC) at any point before resolution. - Splits are the only way tokens are created. Either a user splits USDC into equal shares of the complementary tokens or Polymarket automatically splits USDC when it matches an
Yesbuy order at e.g. 30¢ with aNobuy order at 70¢.
Unified Order Book
- Polymarket uses traditional exchange mechanics - a Central Limit Order Book (CLOB), where users place buy and sell orders that get matched by price and time priority.
- However, because the
YesandNooutcomes form a complete probability universe, certain orders become mathematically equivalent - allowing the matching engine to find trades as exemplified above. - This unified structure means every BUY order for
Outcome 1at price X is simultaneously visible as a SELL order forOutcome 2at price (100¢ - X), creating deeper liquidity and tighter spreads than separate order books would allow.
Negative Risk and Conversions
- If the Markets in and Event collectively cover a complete universe of possibilities (e.g. {0, 1, 2, ..., 7, 8 or more} rate cuts in 2025) and only one winner is possible, two collections of positions (made up of tokens and USDC) become mathematically equivalent and the Event is said to support negative risk.
- e.g. Hold 1
Notoken in the 0 rate cuts in 2025. This is equivalent to holding 1Yestoken in each of the other Markets {1, 2, ..., 7, 8 or more}.
- e.g. Hold 1
- An interesting consequence is that holding
Notokens in more than one Market is equivalent toYestokens and some USDC.- e.g. Hold 1
Notoken on each of {0, 1, 2, ..., 7, 8 or more} rate cuts in 2025. Because only one winner is possible, this guarantees that 8 out of the 9 Markets resolve toNo. This is equivalent to a position of 8 USDC. - e.g. Hold 1
Notoken on each of {0, 1} rate cuts in 2025. This is equivalent to 1Yestoken in {2, ..., 7, 8 or more} and 1 USDC.
- e.g. Hold 1
- Polymarket allows for the one way (for capital efficiency) conversion from
Notokens to a collection ofYestokens and USDC before resolution through a smart contract.
Clients overview
PolymarketReadOnlyClobClient
Read-only order book related operations.
- Order book
- get one or more order books, best price, spread, midpoint, and last trade price by
token_id
- get one or more order books, best price, spread, midpoint, and last trade price by
- Miscellaneous
- get crypto outcomes by
slugfor up/down markets - get recent price history by
token_idin the last 1h, 6h, 1d, 1w, 1m - get price history by
token_idin a start/end interval - get all price history by
token_idin 2-minute increments - get
ClobMarketbycondition_id - get all
ClobMarkets
- get crypto outcomes by
PolymarketClobClient
Order book related operations.
- Authentication
private_keyaddresssignature_typeis optional and can be derived from the address- signature_type=0 for EOAs (Externally Owned Accounts)
- signature_type=1 for Email/Magic wallets
- signature_type=2 for Safe/Gnosis wallets
- All operations from
PolymarketReadOnlyClobClient - Orders
- create and post limit or market orders
- cancel one or more orders by
order_id - get active orders
- send heartbeat to keep orders alive
- Trades
- get trade history for a user with filtering by
condition_id,token_id,trade_id, and time window
- get trade history for a user with filtering by
- Rewards
- check if one or more orders are scoring for liquidity rewards by
order_id - get daily earned rewards
- check if a market offers rewards by
condition_idwithget_market_rewards() - get all active markets that offer rewards, sorted and filtered by multiple criteria, with
get_reward_markets()
- check if one or more orders are scoring for liquidity rewards by
- Miscellaneous
- get USDC balance
- get token balance by
token_id
PolymarketGammaClient
Market and event related operations.
- Market
- get
GammaMarketbymarket_id - get
GammaMarketbyslug - get
GammaMarketswith pagination and filtering byslug,market_id,token_id,condition_id,tag_id, active/closed/archived status, liquidity window, volume window, start date window, end date window, and ordering - get tags for a market by
market_id
- get
- Event
- get
Eventbyevent_id - get
Eventbyslug - get
Eventswith pagination and filtering byslug,event_id,tag_id, active/closed/archived status, liquidity window, volume window, start date window, end date window, and ordering - get all
Eventsgiven some filtration - search
Events,Tags, andProfilesby text query, tags, status, recurrence, and multiple sort modes - grok an event summary by event
slug - grok an election market explanation by candidate name and election title
- get tags for an event by
event_id
- get
- Tag
- get
Tagswith pagination, ordered by any tag field - get all
Tags - get
Tagbytag_id - get
Tagrelations bytag_idorslug - get tags related to a tag by
tag_idorslug
- get
- Sport
- get
Teamswith pagination, filtered byleague,name, andabbreviation - get all
Teamsgiven some filtration - get
Sportswith pagination, filtered byname - get sports metadata
- get
- Series
- get
Serieswith pagination, filtered byslugand closed status, and ordered by any series field - get all
Seriesgiven some filtration
- get
- Comments
- get comments by
parent_entity_typeandparent_entity_idwith pagination, ordered by any comment field - get comments by
comment_id, returning all comments in a thread - get comments by user base address with pagination, ordered by any comment field
- get comments by
- Miscellaneous
- get public profile by user address
PolymarketDataClient
Portfolio related operations.
- Positions
- get positions with pagination by user address, filtered by
condition_id, position size, redeemability, mergeability, and title
- get positions with pagination by user address, filtered by
- Trades
- get trades with pagination, filtered by
condition_id, user address, side, taker-only status, cash amount, and token amount
- get trades with pagination, filtered by
- Activity
- get activity with pagination by user address, filtered by type,
condition_id, time window, side, and sort order
- get activity with pagination by user address, filtered by type,
- Holders
- get top holders by
condition_id
- get top holders by
- Value
- get positions value by user address and
condition_ids condition_ids is Nonemeans total value of positionscondition_ids is strmeans value of positions on one marketcondition_ids is list[str]means sum of values of positions on multiple markets
- get positions value by user address and
- Closed positions
- get closed positions, filtered by
condition_id
- get closed positions, filtered by
- Miscellaneous
- get total number of markets traded by user address
- get open interest for a list of
condition_ids - get live volume for an event by
event_id - get pnl timeseries by user address for a period (
1d,1w,1m,all) with frequency (1h,3h,12h,1d) - get overall pnl/volume by user address for a recent window (
1d,7d,30d,all) - get user rank on the profit/volume leaderboards by user address for a recent window (
1d,7d,30d,all) - get top users on the profit/volume leaderboards for a recent window (
1d,7d,30d,all)
PolymarketWeb3Client
Blockchain operations that pay gas.
- Authentication
private_keysignature_type
- Supported wallet types
EOA(signature_type=0)- Email/Magic wallets (
signature_type=1) - Safe/Gnosis wallets (
signature_type=2)
- Setup and deployment
- set approvals for all needed USDC and conditional token spenders
- Safe/Gnosis wallet holders need to run
deploy_safe()before setting approvals
- Balance
- get POL balance by user address
- get USDC balance by user address
- get token balance by
token_idand user address
- Transfers
- transfer USDC to another address with recipient address and amount
- transfer token to another address with
token_id, recipient address, and amount
- Token/USDC conversions
- split USDC into complementary tokens with
condition_id, amount, andneg_risk - merge complementary tokens into USDC with
condition_id, amount, andneg_risk - redeem token into USDC with
condition_id, amounts array of [Yesshares,Noshares], andneg_risk - convert one or more
Notokens in a negative risk event into a collection of USDC andYestokens on the other markets in the event
- split USDC into complementary tokens with
PolymarketGaslessWeb3Client
Relayed blockchain operations that do not pay gas.
- Authentication
private_keysignature_type- requires
relayer_api_key- get one here - the client derives
RELAYER_API_KEY_ADDRESSfrom the wallet automatically
- Supported wallet types
- Email/Magic wallets (
signature_type=1) - Safe/Gnosis wallets (
signature_type=2)
- Email/Magic wallets (
- Available operations
- balance methods from
PolymarketWeb3Client(read only) - split / merge / convert / redeem (gasless)
- balance methods from
PolymarketWebsocketsClient
Real-time data subscriptions.
- Market socket
- subscribe with a
token_idslist - receive order book summary, price change, tick size change, last trade price, best bid/ask price change, market created, and market resolved events
- subscribe with a
- User socket
- subscribe with
ApiCreds - receive order events (
live,canceled,matched) - receive trade events (
matched,mined,confirmed,retrying,failed)
- subscribe with
- Live data socket
- subscribe with any combination described here
- receive comment/reaction events (
created,removed) - receive
trades/orders_matchedevents filtered by eventslugor marketslug - receive crypto/equity prices
- receive RFQ events (
created,edited,canceled,expired)
- Sports socket
- receive sports game snapshots for game start, score change, period change, and game end
PolymarketGraphQLClient / AsyncPolymarketGraphQLClient
Goldsky-hosted subgraph queries.
- Endpoints
activity_subgraphfpmm_subgraphopen_interest_subgraphorderbook_subgraphpnl_subgraphpositions_subgraphsports_oracle_subgraphwallet_subgraph
- Queries
query()takes a GraphQL query string and returns the raw JSON
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file polymarket_apis-0.5.7.tar.gz.
File metadata
- Download URL: polymarket_apis-0.5.7.tar.gz
- Upload date:
- Size: 254.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
27c6fae34e0e772af010a3448920cacfb9e859ce4ebf724a1eba69e1a07c9e8f
|
|
| MD5 |
b1e2970bb4bb7f7a4d66f56e45d237c4
|
|
| BLAKE2b-256 |
42f8ed07c4ed4edb2d5a5526010a6b674d2bdfdb86fa29d0d88ab26c1076fe09
|
File details
Details for the file polymarket_apis-0.5.7-py3-none-any.whl.
File metadata
- Download URL: polymarket_apis-0.5.7-py3-none-any.whl
- Upload date:
- Size: 80.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.10.7 {"installer":{"name":"uv","version":"0.10.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
41b6ac8267003ea13e4808978ba3543fb69f1f145a77e38d489c13a9dde72d7d
|
|
| MD5 |
21405ff96dce6cdb80692ab2ab8da38c
|
|
| BLAKE2b-256 |
b902c8fd6db632e2385ebef501b17227a75c360b3a3927b77422ab982b30e88e
|