polymarket-us
Unofficial Rust SDK for the Polymarket US Retail API.
Features
- Resource-based API — Organized into focused clients (
client.markets(),client.orders(),client.events(), etc.) - Ed25519 request signing — Automatic X-PM-* authentication headers
- Typed async REST client — Markets, events, orders, portfolio, account, and search endpoints
- Async WebSocket streaming — Separate market-data and private account sockets, with automatic reconnect and keepalive
- Order book & pricing data — Get order books, best bid/offer, settlement prices
- Builder-based configuration — Base URLs, timeouts, custom HTTP client
- Automatic retries — Exponential backoff with jitter on idempotent requests, honouring
Retry-After;POSTis never retried, so orders can't be duplicated - rustls throughout — No OpenSSL dependency
Installation
Or in Cargo.toml:
[]
= "0.6"
= { = "1", = ["macros", "rt-multi-thread"] }
Requires Rust 1.86 or newer. TLS is provided by rustls, so no OpenSSL installation is needed. Root certificates come from the platform verifier, which means the trust store the rest of the machine already uses — no bundled root set to go stale.
Authentication
Authenticated endpoints require:
POLYMARKET_US_KEY_IDPOLYMARKET_US_SECRET_KEY
POLYMARKET_US_SECRET_KEY must be Base64 that decodes to either:
- 64 bytes (keypair format, first 32 bytes are used as signing seed), or
- 32 bytes (raw Ed25519 seed).
Example:
Quick start
use ;
async
Resource-Based API
The SDK is organized into focused resource clients for better discoverability and maintainability:
Markets
Market discovery, order books, and pricing data.
// List markets
let markets = client.markets.list.await?;
// List with filters
let query = ;
let page = client.markets.list_with_query.await?;
// Order book and pricing
let book = client.markets.order_book.await?;
let bbo = client.markets.bbo.await?; // Best bid/offer
let settlement = client.markets.settlement_price.await?;
Events
Event-level metadata and context.
// List all events
let events = client.events.list.await?;
// Get event by ID or slug
let event = client.events.retrieve.await?;
let event = client.events.retrieve_by_slug.await?;
Orders
Complete order lifecycle management. All operations are authenticated.
use types;
let order_req = PlaceOrderRequest ;
// Place order
let order = client.orders.create.await?;
// Get open orders
let open = client.orders.open.await?;
// Modify, cancel, preview
client.orders.modify.await?;
client.orders.cancel.await?;
let estimate = client.orders.preview.await?;
// Close position
client.orders.close_position.await?;
Account
Account balances and buying power (authenticated).
let balances = client.account.balances.await?;
for balance in balances.balances
Portfolio
Holdings and activity history (authenticated).
// Get positions
let positions = client.portfolio.positions.await?;
// Get activity with pagination
let query = ;
let activities = client.portfolio.activities.await?;
Search
Full-text search across markets and events.
let query = ;
let results = client.search.search.await?;
// Search specific resource
let markets = client.search.markets.await?;
let events = client.search.events.await?;
Advanced market queries
Use list_with_query() for filters, cursors, and pagination:
use ;
use Serialize;
async
If your account tier requires authenticated access for some filters, use
list_authenticated_with_query(), which takes the same query argument.
Streaming
The venue splits its WebSocket surface across two sockets on the API host (not the gateway host used for public REST traffic), and the SDK mirrors that split rather than multiplexing them:
| Data | Endpoint | Client | Subscriptions |
|---|---|---|---|
| Books, trades, best-bid/offer | wss://api.polymarket.us/v1/ws/markets |
MarketStreamClient |
MarketSubscription |
| Orders, positions, balances | wss://api.polymarket.us/v1/ws/private |
PrivateStreamClient |
PrivateSubscription |
Because the two subscription families are distinct types, subscribing to an order feed on the market socket is a compile error rather than a server rejection.
Wire format
A subscription serializes to the server's subscribe envelope:
and unsubscribing echoes the same requestId:
MarketSubscription::frame() / PrivateSubscription::frame() return exactly
what will be sent, which is the quickest way to check a subscription against the
docs. Note that the endpoint rejects a frame it cannot parse — including one
carrying a field it does not define — so the SDK sends only the three documented
fields. insert_extra adds more when the docs call for it.
Subscription types map to SubscriptionType, whose wire form is the
fully-qualified enum name:
| Constructor | subscriptionType |
|---|---|
MarketSubscription::market_data(slugs) |
SUBSCRIPTION_TYPE_MARKET_DATA |
MarketSubscription::market_data_lite(slugs) |
SUBSCRIPTION_TYPE_MARKET_DATA_LITE |
MarketSubscription::trades(slugs) |
SUBSCRIPTION_TYPE_TRADE |
PrivateSubscription::orders() |
SUBSCRIPTION_TYPE_ORDER |
PrivateSubscription::positions() |
SUBSCRIPTION_TYPE_POSITION |
PrivateSubscription::account_balances() |
SUBSCRIPTION_TYPE_ACCOUNT_BALANCE |
A type the SDK does not model yet can still be used via custom(), which sends
the string verbatim.
Market data
use ;
async
Private account events
private_stream() fails with MissingAuth if the client has no credentials,
since the endpoint rejects an unauthenticated upgrade.
use ;
async
Staying connected
Both streams reconnect automatically and replay their subscriptions each time.
A connection that goes quiet for StreamConnectConfig::idle_timeout (60s by
default) is torn down and reconnected. This matters because a TCP connection can
die without a FIN or RST — common behind NAT and load balancers — in which case
the socket never reports an error and the stream would otherwise wait forever.
Feeding that check is keepalive_interval (20s by default): the SDK pings the
server, and the pong counts as traffic. That distinction is what keeps a market
with nothing to report from being mistaken for a dead socket. Pass None to
either to switch it off.
use Duration;
use StreamConnectConfig;
let config = default
.with_idle_timeout
.with_keepalive_interval;
Inbound events arrive as StreamMessageKind::Data(StreamDataEvent::…):
MarketData, MarketDataLite, OrderBookDelta, Trade, OrderSnapshot,
OrderUpdate, PositionSnapshot, PositionUpdate, BalanceSnapshot,
BalanceUpdate, Heartbeat, and Other for anything not yet modelled.
StreamMessage::request_id carries the requestId the server echoed, matching
the subscription that produced it.
Endpoint coverage
Markets (client.markets()):
list()— List all marketslist_with_query(q)— List markets with filters/paginationlist_authenticated()— Authenticated market listinglist_authenticated_with_query(q)— Authenticated with filtersorder_book(symbol)— Get market order bookbbo(symbol)— Get best bid/offersettlement_price(symbol)— Get settlement price
Events (client.events()):
list()— List all eventslist_with_query(q)— List events with filtersretrieve(id)— Get event by IDretrieve_by_slug(slug)— Get event by slug
Orders (client.orders()):
create(req)— Create orderplace(req)— Place order (alternative endpoint)place_batch(req)— Place multiple orders atomicallyopen(q)— Get open ordersretrieve(id)— Get order by IDcancel(id, params)— Cancel ordercancel_trading(id)— Cancel via trading endpointcancel_all(params)— Cancel all ordersmodify(id, req)— Modify open orderpreview(req)— Preview order estimateclose_position(req)— Close position
Account (client.account()):
balances()— Get account balances and buying power
Portfolio (client.portfolio()):
positions()— Get positionsactivities(q)— Get activity with pagination
Search (client.search()):
search(q)— Full-text search across markets/eventsmarkets(q)— Search marketsevents(q)— Search events
Streaming (client.market_stream() / client.private_stream()):
- Two endpoint-specific clients mirroring the server's
/v1/ws/marketsand/v1/ws/privatesplit - Typed subscription types via
SubscriptionType, withcustom()for unmodelled ones - Dynamic
subscribe(...)/unsubscribe(...)byrequestId - Automatic reconnect with subscription replay, keepalive pings, and idle-connection teardown
Migrating to 0.5
The streaming API in 0.4 did not work against the live venue. It sent a flat
frame — {"channel": "market_data", "trackingId": ..., "symbol": ...} — that the
server never parsed as a subscribe request, so every subscription came back as
{"error":"invalid_message"}. It also derived its URL from the gateway host,
which does not serve WebSockets. 0.5 replaces that layer; there is no compatible
upgrade path, but the mapping is mechanical.
One client became two, matching the server's own split:
// 0.4 — one client, one socket, derived from the gateway host
let stream = client.streaming;
// 0.5 — wss://api.polymarket.us/v1/ws/markets
let markets = client.market_stream;
// 0.5 — wss://api.polymarket.us/v1/ws/private
let private = client.private_stream?;
StreamSubscription became MarketSubscription and PrivateSubscription,
and takes market slugs rather than a symbol:
// 0.4
market_data
trades
order_snapshot
order_update
position_snapshot // and position_update()
balance_snapshot // and balance_update()
// 0.5
market_data
trades
orders
positions
account_balances
The snapshot/update split is gone from the subscribe side — the server has one
subscription type per family — but survives on the receive side, where
StreamDataEvent::OrderSnapshot and OrderUpdate are still distinct.
Everything else that changed:
SubscriptionChannelbecameSubscriptionType, and its wire form is the fully-qualified enum name (SUBSCRIPTION_TYPE_TRADE, nottrade). Unmodelled types go throughMarketSubscription::custom/PrivateSubscription::custom.tracking_idbecamerequest_idthroughout, matching the wire field.StreamMessage::tracking_idis nowStreamMessage::request_id, andunsubscribetakes therequestIdthe subscription was created with.ManagedStreambecameMarketStreamandPrivateStream. Each accepts only its own endpoint's subscription type, so the two sockets cannot be crossed.StreamSubscription::heartbeat()is gone. There is no heartbeat subscription type; keeping the connection warm is now the SDK's job, viaStreamConnectConfig::keepalive_interval. If you subscribed to the heartbeat purely to feedidle_timeout, drop the subscription — that is handled.responses_debouncedis gone from bothStreamSubscriptionandStreamConnectConfig. It is not part of the documented subscribe object, and sending an undefined field risks the sameinvalid_messagerejection.StreamConnectConfig::tracking_idbecamesession_id, and is explicitly local — it identifies the connection in control events and is never sent.PolymarketUsStreamClient::from_gateway_base_urlis gone. The sockets are not on the gateway host.MarketStreamClient::with_base_urlandPrivateStreamClient::with_base_urltake an explicit override for staging or local servers.
Migrating to 0.4
The flat legacy methods deprecated in 0.3.0 have been removed. Each maps to a resource client:
// Removed in 0.4
let markets = client.markets_list.await?;
let balances = client.account_balances.await?;
let order = client.place_order.await?;
// Use instead
let markets = client.markets.list.await?;
let balances = client.account.balances.await?;
let order = client.orders.place.await?;
The general rule: client.<resource>_<verb>() becomes client.<resource>().<verb>().
Three other breaking changes:
UsAuthreturnsPolymarketUsError, notanyhow::Error.UsAuth::from_env()andUsAuth::from_parts()now returnResult<UsAuth, PolymarketUsError>, so credential failures can be matched on like every other SDK error. Bad Base64 or a wrong key length surfaces asPolymarketUsError::InvalidCredentials. If you were using?inside ananyhow::Resultfunction, no change is needed.UsMarket::market_sidesisVec<MarketSide>, previouslyVec<serde_json::Value>. Unmodelled keys are preserved inMarketSide::extra.LeagueandTeamwere removed. They were unreachable placeholders that no endpoint returned; they will return with the endpoints that populate them.
Configuration
use ;
use Duration;
Error handling
use ;
async
Retries, Correlation IDs, and Rate Limits
Automatic Retries
GET and DELETE requests are automatically retried with exponential backoff and jitter.
POST requests (order creation, placement, etc.) are never retried automatically to
prevent duplicate submissions.
use ;
use Duration;
// Default: 3 retries, 200ms initial backoff, 10s cap, 25% jitter
let client = builder.build?;
// Aggressive retry for high-availability workflows
let client = builder
.retry
.build?;
// Disable retries entirely
let client = builder
.retry
.build?;
// Fine-grained control
let client = builder
.retry
.build?;
Retries occur on:
- HTTP 429 (respects
Retry-Afterheader if present) - HTTP 500, 502, 503, 504
- Transport-level errors (connection refused, timeout)
Correlation IDs
Every request automatically includes an X-Correlation-ID header (pmrs-{uuid_v4}) for
tracing requests across your logs and Polymarket support conversations.
// Custom prefix — useful to distinguish SDK requests by service/environment
let client = builder
.correlation_id_prefix
.build?;
// Sends: X-Correlation-ID: my-service-prod-550e8400-e29b-41d4-a716-446655440000
Rate Limit Awareness
When Polymarket returns a 429, the Retry-After header is parsed and surfaced in the
RateLimited error variant so your application can react precisely:
match client.markets.list.await
For idempotent endpoints, the SDK already honors this automatically — the Retry-After
duration is used directly instead of the configured backoff.
Testing
The SDK includes comprehensive unit tests for all resource clients and type serialization/deserialization:
# Run all tests
# Run with output
# Run specific test module
# Run a single test
Current test coverage includes:
- ✅ Resource client creation and type checking (6 resources × 2 tests = 12 tests)
- ✅ Request/Response serialization for all order types (typed enums + wire compatibility)
- ✅ Type deserialization for markets, events, positions, balances
- ✅ Streaming wire format, endpoint routing, event parsing, and keepalive/idle behaviour
- ✅ Gateway quirks in market deserialization (double-encoded
outcomes/outcomePrices) - ✅ Retry/backoff policy tests and builder configuration tests
Total: 93 tests plus 6 doc tests, all passing
Acknowledgements
Initial implementation originated in the DRADIS project and was extracted into this crate.
- Project link:
https://github.com/mbordash/DRADIS - Attribution is kept for provenance and maintenance history.