Polymarket US Python SDK
Project description
Polymarket US Python SDK
Official Python SDK for the Polymarket US API.
Installation
pip install polymarket-us
Usage
Public Endpoints (No Authentication)
from polymarket_us import PolymarketUS
client = PolymarketUS()
# Get events with pagination
events = client.events.list({"limit": 10, "offset": 0, "active": True})
next_page = client.events.list({"limit": 10, "offset": 10, "active": True})
# Get a specific event
event = client.events.retrieve(123)
event_by_slug = client.events.retrieve_by_slug("super-bowl-2025")
# Get markets
markets = client.markets.list()
market = client.markets.retrieve_by_slug("btc-100k")
# Get order book
book = client.markets.book("btc-100k")
# Get best bid/offer
bbo = client.markets.bbo("btc-100k")
# Search
results = client.search.query({"query": "bitcoin"})
# Series and sports
series = client.series.list()
sports = client.sports.list()
Authenticated Endpoints (Trading)
import os
from polymarket_us import PolymarketUS
client = PolymarketUS(
key_id=os.environ["POLYMARKET_KEY_ID"],
secret_key=os.environ["POLYMARKET_SECRET_KEY"],
)
# Create an order
order = client.orders.create({
"marketSlug": "btc-100k-2025",
"intent": "ORDER_INTENT_BUY_LONG",
"type": "ORDER_TYPE_LIMIT",
"price": {"value": "0.55", "currency": "USD"},
"quantity": 100,
"tif": "TIME_IN_FORCE_GOOD_TILL_CANCEL",
})
# Get open orders
open_orders = client.orders.list()
# Cancel an order
client.orders.cancel(order["id"], {"marketSlug": "btc-100k-2025"})
# Cancel all orders
client.orders.cancel_all()
# Get positions
positions = client.portfolio.positions()
# Get activity history
activities = client.portfolio.activities()
# Get account balances
balances = client.account.balances()
client.close()
Async Usage
import asyncio
import os
from polymarket_us import AsyncPolymarketUS
async def main():
async with AsyncPolymarketUS(
key_id=os.environ["POLYMARKET_KEY_ID"],
secret_key=os.environ["POLYMARKET_SECRET_KEY"],
) as client:
# Concurrent requests
events, markets = await asyncio.gather(
client.events.list({"limit": 10}),
client.markets.list({"limit": 10}),
)
print(f"Found {len(events['events'])} events")
print(f"Found {len(markets['markets'])} markets")
asyncio.run(main())
Authentication
Polymarket US uses Ed25519 signature authentication. Generate API keys at polymarket.us/developer.
The SDK automatically signs requests with your credentials:
client = PolymarketUS(
key_id="your-api-key-id", # UUID
secret_key="your-secret-key", # Base64-encoded Ed25519 private key
)
Error Handling
from polymarket_us import (
PolymarketUS,
APIConnectionError,
APITimeoutError,
AuthenticationError,
BadRequestError,
NotFoundError,
RateLimitError,
)
try:
client.orders.create({...})
except AuthenticationError as e:
print(f"Invalid credentials: {e.message}")
except BadRequestError as e:
print(f"Invalid order parameters: {e.message}")
except RateLimitError as e:
print(f"Rate limit exceeded: {e.message}")
except NotFoundError as e:
print(f"Resource not found: {e.message}")
except APITimeoutError:
print("Request timed out")
except APIConnectionError as e:
print(f"Connection error: {e.message}")
Configuration
client = PolymarketUS(
key_id="your-key-id",
secret_key="your-secret-key",
timeout=30.0, # Request timeout in seconds (default: 30.0)
)
WebSocket (Real-Time Data)
Note: WebSocket connections are async-only due to their event-driven nature. Use
asyncio.run()when working with the sync client, or useAsyncPolymarketUSdirectly.
import asyncio
import os
from polymarket_us import PolymarketUS
async def main():
client = PolymarketUS(
key_id=os.environ["POLYMARKET_KEY_ID"],
secret_key=os.environ["POLYMARKET_SECRET_KEY"],
)
# Private WebSocket (orders, positions, balances)
private_ws = client.ws.private()
def on_order_snapshot(data):
print(f"Open orders: {data['orderSubscriptionSnapshot']['orders']}")
def on_order_update(data):
print(f"Order execution: {data['orderSubscriptionUpdate']['execution']}")
private_ws.on("order_snapshot", on_order_snapshot)
private_ws.on("order_update", on_order_update)
private_ws.on("error", lambda e: print(f"Error: {e}"))
await private_ws.connect()
await private_ws.subscribe("order-sub-1", "SUBSCRIPTION_TYPE_ORDER")
await private_ws.subscribe("pos-sub-1", "SUBSCRIPTION_TYPE_POSITION")
await private_ws.subscribe("balance-sub-1", "SUBSCRIPTION_TYPE_ACCOUNT_BALANCE")
# Markets WebSocket (order book, trades)
markets_ws = client.ws.markets()
markets_ws.on("market_data", lambda d: print(f"Book: {d['marketData']}"))
markets_ws.on("trade", lambda d: print(f"Trade: {d['trade']}"))
await markets_ws.connect()
await markets_ws.subscribe("md-sub-1", "SUBSCRIPTION_TYPE_MARKET_DATA", ["btc-100k-2025"])
await markets_ws.subscribe("trade-sub-1", "SUBSCRIPTION_TYPE_TRADE", ["btc-100k-2025"])
# Keep running
await asyncio.sleep(60)
await private_ws.close()
await markets_ws.close()
asyncio.run(main())
API Reference
Events
| Method | Description |
|---|---|
events.list(params?) |
List events with filtering |
events.retrieve(id) |
Get event by ID |
events.retrieve_by_slug(slug) |
Get event by slug |
Markets
| Method | Description |
|---|---|
markets.list(params?) |
List markets with filtering |
markets.retrieve(id) |
Get market by ID |
markets.retrieve_by_slug(slug) |
Get market by slug |
markets.book(slug) |
Get order book |
markets.bbo(slug) |
Get best bid/offer |
markets.settlement(slug) |
Get settlement price |
Orders (Authenticated)
| Method | Description |
|---|---|
orders.create(params) |
Create a new order |
orders.list(params?) |
Get open orders |
orders.retrieve(order_id) |
Get order by ID |
orders.cancel(order_id, params) |
Cancel an order |
orders.modify(order_id, params) |
Modify an order |
orders.cancel_all(params?) |
Cancel all open orders |
orders.preview(params) |
Preview an order |
orders.close_position(params) |
Close a position |
Portfolio (Authenticated)
| Method | Description |
|---|---|
portfolio.positions(params?) |
Get trading positions |
portfolio.activities(params?) |
Get activity history |
Account (Authenticated)
| Method | Description |
|---|---|
account.balances() |
Get account balances |
Series
| Method | Description |
|---|---|
series.list(params?) |
List series |
series.retrieve(id) |
Get series by ID |
Sports
| Method | Description |
|---|---|
sports.list() |
List sports |
sports.teams(params?) |
Get teams for provider |
Search
| Method | Description |
|---|---|
search.query(params?) |
Search events (includes nested markets) |
WebSocket (Authenticated, Async-Only)
| Method | Description |
|---|---|
ws.private() |
Create private WebSocket connection |
ws.markets() |
Create markets WebSocket connection |
WebSocket methods (connect(), subscribe(), close()) are async and must be awaited.
Private WebSocket Events:
order_snapshot- Initial orders snapshotorder_update- Order execution updatesposition_snapshot- Initial positions snapshotposition_update- Position changesaccount_balance_snapshot- Initial balanceaccount_balance_update- Balance changesheartbeat- Connection keepaliveerror- Error eventsclose- Connection closed
Markets WebSocket Events:
market_data- Full order book updatesmarket_data_lite- Lightweight price datatrade- Trade notificationsheartbeat- Connection keepaliveerror- Error eventsclose- Connection closed
Requirements
- Python 3.10+
Development
# Install dev dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run linting
ruff check .
# Run type checking
mypy polymarket_us
License
MIT
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_us-0.1.2.tar.gz.
File metadata
- Download URL: polymarket_us-0.1.2.tar.gz
- Upload date:
- Size: 66.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
84759749177d26ee80d1dbb73fe0588c65887a3de02b1ae9bed452e207181805
|
|
| MD5 |
95ea88a7623f068fd4dd32d61c85e596
|
|
| BLAKE2b-256 |
c665509c9fc5ace30efcfdb52439e492f54f19d2ca321fcbe5c376d79a334c90
|
File details
Details for the file polymarket_us-0.1.2-py3-none-any.whl.
File metadata
- Download URL: polymarket_us-0.1.2-py3-none-any.whl
- Upload date:
- Size: 29.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a64cf2b8505c223ec7e11bd6e2106a4274477a52dbee0f702fde93a831ea6b2b
|
|
| MD5 |
21e7ecaeb78464539b4c483b7e26f4fd
|
|
| BLAKE2b-256 |
6961a0cdd22556386c4af2924293caede9f6a7600b0a286d416c6d288e6aa67f
|