NautilusTrader
Integrations

Polymarket

Founded in 2020, Polymarket is the world’s largest decentralized prediction market platform, enabling traders to speculate on the outcomes of world events by buying and selling binary option contracts using cryptocurrency.

NautilusTrader provides a venue integration for data and execution via Polymarket's Central Limit Order Book (CLOB) API.

Today the repository exposes two Polymarket implementations:

  • The Python adapter in nautilus_trader.adapters.polymarket, which uses the official Python CLOB client library.
  • The Rust-native adapter surface in nautilus_trader.polymarket, which NautilusTrader is consolidating toward.

The two implementations overlap heavily, but they do not yet behave identically in every area. This guide calls out the current differences where they matter.

NautilusTrader supports multiple Polymarket signature types for order signing, which gives flexibility for different wallet configurations while NautilusTrader handles signing and order preparation.

Installation

To install NautilusTrader with Polymarket support:

uv pip install "nautilus_trader[polymarket]"

To build from source with all extras (including Polymarket):

uv sync --all-extras

Examples

You can find live example scripts here.

Binary options

A binary option is a type of financial exotic option contract in which traders bet on the outcome of a yes-or-no proposition. If the prediction is correct, the trader receives a fixed payout; otherwise, they receive nothing.

All assets traded on Polymarket are quoted and settled in USDC.e (PoS), see below for more information.

Polymarket documentation

Polymarket offers resources for different audiences:

  • Polymarket Learn: Educational content and guides for users to understand the platform and how to engage with it.
  • Polymarket CLOB API: Technical documentation for developers interacting with the Polymarket CLOB API.

Overview

This guide assumes a trader is setting up for both live market data feeds and trade execution. The Polymarket integration adapter includes multiple components, which can be used together or separately depending on the use case.

  • PolymarketWebSocketClient: Low-level WebSocket API connectivity (built on top of the Nautilus WebSocketClient written in Rust).
  • PolymarketInstrumentProvider: Instrument parsing and loading functionality for BinaryOption instruments.
  • PolymarketDataClient: A market data feed manager.
  • PolymarketExecutionClient: A trade execution gateway.
  • PolymarketLiveDataClientFactory: Factory for Polymarket data clients (used by the trading node builder).
  • PolymarketLiveExecClientFactory: Factory for Polymarket execution clients (used by the trading node builder).

Most users will define a configuration for a live trading node (as below), and won't need to work with these lower-level components directly.

Python and Rust implementations

The current docs cover both the Python adapter and the Rust-native adapter surface. The table below shows the main differences that affect behavior today.

AreaPython adapterRust adapterNotes
Public package pathnautilus_trader.adapters.polymarketnautilus_trader.polymarketRust is the consolidation target.
Order signingUses py-clob-clientNative Rust signingPython signing is slower.
Post‑only ordersSupported for GTC and GTD onlySupported for GTC and GTD onlyBoth reject post‑only with IOC or FOK.
Batch submitUses POST /orders for batchable SubmitOrderList requestsUses POST /orders for batchable SubmitOrderList requestsBoth batch only independent limit orders.
Batch cancelUses DELETE /ordersUses DELETE /ordersBoth align with official Polymarket docs.
Market unsubscribeSends dynamic WebSocket unsubscribe messagesSends dynamic WebSocket unsubscribe messagesBoth support subscribe and unsubscribe.
Data client configCredentials, subscription buffering, quote handling, provider configBase URLs, timeouts, filters, new‑market discoveryConfig surfaces differ materially.
Exec client configCredentials, retries, raw WS logging, experimental trade‑based order recoveryCredentials, retries, account IDs, native timeoutsRust does not expose every Python‑only option.

USDC.e (PoS)

USDC.e is a bridged version of USDC from Ethereum to the Polygon network, operating on Polygon's Proof of Stake (PoS) chain. This enables faster, more cost-efficient transactions on Polygon while maintaining backing by USDC on Ethereum.

The contract address is 0x2791bca1f2de4661ed88a30c99a7a9449aa84174 on the Polygon blockchain. More information can be found in this blog.

Wallets and accounts

To interact with Polymarket via NautilusTrader, you'll need a Polygon-compatible wallet (such as MetaMask).

Signature types

Polymarket supports multiple signature types for order signing and verification:

Signature TypeWallet TypeDescriptionUse Case
0EOA (Externally Owned Account)Standard EIP712 signatures from wallets with direct private key control.Default. Direct wallet connections (MetaMask, hardware wallets, etc.).
1Email/Magic Wallet ProxySmart contract wallet for email‑based accounts (Magic Link). Only the email‑associated address can execute functions.Polymarket Proxy associated with Email/Magic accounts. Requires funder address.
2Browser Wallet ProxyModified Gnosis Safe (1-of-1 multisig) for browser wallets.Polymarket Proxy associated with browser wallets. Enables UI verification. Requires funder address.

See also: Proxy wallet in the Polymarket documentation for more details about signature types and proxy wallet infrastructure.

NautilusTrader defaults to signature type 0 (EOA) but can be configured to use any of the supported signature types via the signature_type configuration parameter.

A single wallet address is supported per trader instance when using environment variables, or multiple wallets could be configured with multiple PolymarketExecutionClient instances.

Ensure your wallet is funded with USDC.e, otherwise you will encounter the "not enough balance / allowance" API error when submitting orders.

Setting allowances for Polymarket contracts

Before you can start trading, you need to ensure that your wallet has allowances set for Polymarket's smart contracts. You can do this by running the provided script located at nautilus_trader/adapters/polymarket/scripts/set_allowances.py.

This script is adapted from a gist created by @poly-rodr.

You only need to run this script once per EOA wallet that you intend to use for trading on Polymarket.

This script automates the process of approving the necessary allowances for the Polymarket contracts. It sets approvals for the USDC token and Conditional Token Framework (CTF) contract to allow the Polymarket CLOB Exchange to interact with your funds.

Before running the script, ensure the following prerequisites are met:

  • Install the web3 Python package: uv pip install "web3==7.12.1".
  • Have a Polygon-compatible wallet funded with some POL (used for gas fees).
  • Set the following environment variables in your shell:
    • POLYGON_PRIVATE_KEY: Your private key for the Polygon-compatible wallet.
    • POLYGON_PUBLIC_KEY: Your public key for the Polygon-compatible wallet.

Once you have these in place, the script will:

  • Approve the maximum possible amount of USDC (using the MAX_INT value) for the Polymarket USDC token contract.
  • Set the approval for the CTF contract, allowing it to interact with your account for trading purposes.

You can also adjust the approval amount in the script instead of using MAX_INT, with the amount specified in fractional units of USDC.e, though this has not been tested.

Ensure that your private key and public key are correctly stored in the environment variables before running the script. Here's an example of how to set the variables in your terminal session:

export POLYGON_PRIVATE_KEY="YOUR_PRIVATE_KEY"
export POLYGON_PUBLIC_KEY="YOUR_PUBLIC_KEY"

Run the script using:

python nautilus_trader/adapters/polymarket/scripts/set_allowances.py

Script breakdown

The script performs the following actions:

  • Connects to the Polygon network via an RPC URL (https://polygon-rpc.com/).
  • Signs and sends a transaction to approve the maximum USDC allowance for Polymarket contracts.
  • Sets approval for the CTF contract to manage Conditional Tokens on your behalf.
  • Repeats the approval process for specific addresses like the Polymarket CLOB Exchange and Neg Risk adapter.

This allows Polymarket to interact with your funds when executing trades and ensures smooth integration with the CLOB Exchange.

API keys

To trade with Polymarket, you'll need to generate API credentials. Follow these steps:

  1. Ensure the following environment variables are set:

    • POLYMARKET_PK: Your private key for signing transactions.
    • POLYMARKET_FUNDER: The wallet address (public key) on the Polygon network used for funding trades on Polymarket.
  2. Run the script using:

    python nautilus_trader/adapters/polymarket/scripts/create_api_key.py

The script will generate and print API credentials, which you should save to the following environment variables:

  • POLYMARKET_API_KEY
  • POLYMARKET_API_SECRET
  • POLYMARKET_PASSPHRASE

These can then be used for Polymarket client configurations:

  • PolymarketDataClientConfig
  • PolymarketExecClientConfig

Configuration

When setting up NautilusTrader to work with Polymarket, it’s crucial to properly configure the necessary parameters, particularly the private key.

Key parameters:

  • private_key: The private key for your wallet used to sign orders. The interpretation depends on your signature_type configuration. If not explicitly provided in the configuration, it will automatically source the POLYMARKET_PK environment variable.
  • funder: The USDC.e funding wallet address used for funding trades. If not provided, will source the POLYMARKET_FUNDER environment variable.
  • API credentials: You will need to provide the following API credentials to interact with the Polymarket CLOB:
    • api_key: If not provided, will source the POLYMARKET_API_KEY environment variable.
    • api_secret: If not provided, will source the POLYMARKET_API_SECRET environment variable.
    • passphrase: If not provided, will source the POLYMARKET_PASSPHRASE environment variable.
  • auto_load_missing_instruments (default True): Controls whether subscribe and request commands for an instrument that is not already in the cache trigger an ad-hoc load via the Gamma API. When disabled, subscribing to an uncached instrument returns an error. See Runtime instrument loading.
  • auto_load_debounce_ms (default 100): The window (milliseconds) over which concurrent auto-load requests are coalesced into a single batched Gamma call.

We recommend using environment variables to manage your credentials.

Orders capability

Polymarket operates as a prediction market with a more limited set of order types and instructions compared to traditional exchanges.

Order types

Order TypeBinary OptionsNotes
MARKETBUY orders require quote quantity, SELL orders require base quantity.
LIMIT
STOP_MARKET-Not supported by Polymarket.
STOP_LIMIT-Not supported by Polymarket.
MARKET_IF_TOUCHED-Not supported by Polymarket.
LIMIT_IF_TOUCHED-Not supported by Polymarket.
TRAILING_STOP_MARKET-Not supported by Polymarket.

Quantity semantics

Polymarket interprets order quantities differently depending on the order type and side:

  • Limit orders interpret quantity as the number of conditional tokens (base units).
  • Market SELL orders also use base-unit quantities.
  • Market BUY orders interpret quantity as quote notional in USDC.e.

As a result, a market buy order submitted with a base-denominated quantity will execute far more size than intended.

When submitting market BUY orders, set quote_quantity=True on the order. The adapter converts the quote amount (USDC.e) to base units (shares) using the crossing price from the order book before submitting to the CLOB. The Polymarket execution client denies base-denominated market buys to prevent unintended fills.

# Market BUY with quote quantity (spend $10 USDC)
order = strategy.order_factory.market(
    instrument_id=instrument_id,
    order_side=OrderSide.BUY,
    quantity=instrument.make_qty(10.0),
    quote_quantity=True,  # Interpret as USDC.e notional
)
strategy.submit_order(order)

Execution instructions

InstructionBinary OptionsNotes
post_onlySupported for limit orders with GTC or GTD only.
reduce_only-Not supported by Polymarket.

Time-in-force options

Time in forceBinary OptionsNotes
GTCGood Till Canceled.
GTDGood Till Date.
FOKFill or Kill.
IOCImmediate or Cancel (maps to FAK).

FAK (Fill and Kill) is Polymarket's terminology for Immediate or Cancel (IOC) semantics.

Advanced order features

FeatureBinary OptionsNotes
Order modification-Cancellation functionality only.
Bracket/OCO orders-Not supported by Polymarket.
Iceberg orders-Not supported by Polymarket.

Batch operations

OperationBinary OptionsNotes
Batch SubmitBoth adapters use POST /orders for independent limit‑order batches.
Batch Modify-Not supported by Polymarket.
Batch CancelBoth adapters use DELETE /orders.

Position management

FeatureBinary OptionsNotes
Query positionsCurrent user positions from the Polymarket Data API.
Position mode-Binary outcome positions only.
Leverage control-No leverage available.
Margin mode-No margin trading.

Order querying

FeatureBinary OptionsNotes
Query open ordersActive orders only.
Query order historyLimited historical data.
Order status updatesReal‑time order state changes.
Trade historyExecution and fill reports.

Contingent orders

FeatureBinary OptionsNotes
Order lists-Independent order batches exist, but linked contingency semantics do not.
OCO orders-Not supported by Polymarket.
Bracket orders-Not supported by Polymarket.
Conditional orders-Not supported by Polymarket.

Precision limits

Polymarket enforces different precision constraints based on tick size and order type.

Binary Option instruments typically support up to 6 decimal places for amounts (with 0.0001 tick size), but market orders have stricter precision requirements:

  • FOK (Fill-or-Kill) market orders:

    • Sell orders: maker amount limited to 2 decimal places.
    • Taker amount: limited to 4 decimal places.
    • The product size × price must not exceed 2 decimal places.
  • Regular GTC orders: More flexible precision based on market tick size.

Tick size precision hierarchy

Tick SizePrice DecimalsSize DecimalsAmount Decimals
0.1123
0.01224
0.001325
0.0001426
  • The tick size precision hierarchy is defined in the py-clob-client ROUNDING_CONFIG.
  • FOK market order precision limits (2 decimals for maker amount) are based on API error responses documented in issue #121.
  • Tick sizes can change dynamically during market conditions, particularly when markets become one-sided.

Trades

Trades on Polymarket can have the following statuses:

  • MATCHED: Trade has been matched and sent to the executor service by the operator. The executor service submits the trade as a transaction to the Exchange contract.
  • MINED: Trade is observed to be mined into the chain, and no finality threshold is established.
  • CONFIRMED: Trade has achieved strong probabilistic finality and was successful.
  • RETRYING: Trade transaction has failed (revert or reorg) and is being retried/resubmitted by the operator.
  • FAILED: Trade has failed and is not being retried.

Once a trade is initially matched, subsequent trade status updates will be received via the WebSocket. NautilusTrader records the initial trade details in the info field of the OrderFilled event, with additional trade events stored in the cache as JSON under a custom key to retain this information.

Fees

Polymarket uses the formula fee = C * feeRate * p * (1 - p) where C is shares traded and p is the share price. Fees peak at p = 0.50 and decrease symmetrically toward the extremes. Only takers pay fees; makers pay zero.

CategoryTaker feeRate
Crypto0.072
Sports0.03
Finance / Politics / Mentions / Tech0.04
Economics / Culture / Weather / Other0.05
Geopolitics0.00

Fees are rounded to 5 decimal places (0.00001 USDC minimum). Fees are collected in shares on buy orders and USDC on sell orders.

For the latest rates, see Polymarket's Fees documentation.

Reconciliation

The Polymarket API returns either all active (open) orders or specific orders when queried by the Polymarket order ID (venue_order_id). The execution reconciliation procedure for Polymarket is as follows:

  • Generate order reports for all instruments with active (open) orders, as reported by Polymarket.
  • Generate position reports from current user positions reported by Polymarket's Data API.
  • Compare these reports with Nautilus execution state.
  • Generate missing orders to bring Nautilus execution state in line with positions reported by Polymarket.

Note: Polymarket does not directly provide data for orders which are no longer active. The Python adapter exposes an experimental generate_order_history_from_trades option to fill some of this gap from trade history. The Rust adapter does not expose the same option today.

An optional execution client configuration, generate_order_history_from_trades, is currently under development. It is not recommended for production use at this time.

WebSockets

The PolymarketWebSocketClient is built on top of the high-performance Nautilus WebSocketClient base class, written in Rust.

Data

The data adapter buffers the initial market subscriptions during the connection window and then subscribes dynamically as new instruments are requested. The client manages multiple WebSocket connections internally when the subscription count grows past the configured per-connection cap.

Runtime instrument loading

Polymarket lists thousands of active markets and new markets appear throughout the day, so preloading the full universe at startup is rarely practical. The data adapter auto-loads missing instruments on demand so that strategies can subscribe to markets that are not in the cache:

  • When a strategy issues subscribe_quote_ticks, subscribe_trade_ticks, subscribe_order_book_deltas, or request_instrument for an instrument that is not cached, the adapter registers the request and waits auto_load_debounce_ms (default 100 ms) so that concurrent requests coalesce.
  • It then issues a single batched Gamma API call. Batches larger than the Gamma condition_ids query ceiling (about 100) are split across multiple calls and merged.
  • Once the instruments are loaded, they are published to the data engine (populating the cache) and the deferred subscriptions open their WebSocket subscriptions atomically. A strategy that unsubscribes while the auto-load is in flight does not see a spurious subscription opened.

The feature is enabled by default. Disable it by setting auto_load_missing_instruments=False on PolymarketDataClientConfig. To preload a known set of markets at startup instead, supply load_ids or event_slug_builder on PolymarketInstrumentProviderConfig.

Execution

The execution adapter keeps a user channel connection for order and trade events and manages market subscriptions as needed for instruments seen during trading.

Both the Python and Rust adapters support dynamic WebSocket subscribe and unsubscribe operations.

Subscription limits

Polymarket enforces a maximum of 500 instruments per WebSocket connection (undocumented limitation).

When you attempt to subscribe to 501 or more instruments on a single WebSocket connection:

  • You will not receive the initial order book snapshot for each instrument.
  • You will only receive subsequent order book updates.

NautilusTrader automatically manages WebSocket connections to handle this limitation:

  • The adapter defaults to 200 instrument subscriptions per connection (configurable via ws_max_subscriptions_per_connection).
  • When the subscription count exceeds this limit, additional WebSocket connections are created automatically.
  • This ensures you receive complete order book data (including initial snapshots) for all subscribed instruments.

If you need to subscribe to a large number of instruments (e.g., 5000+), the adapter will automatically distribute these subscriptions across multiple WebSocket connections. You can tune the per-connection limit up to 500 via ws_max_subscriptions_per_connection.

Rate limiting

Polymarket enforces rate limits via Cloudflare throttling. When limits are exceeded, the API returns HTTP 429 responses.

REST limits

Polymarket changes these quotas over time. As of 2026-04-17, the official limits are:

EndpointBurst (10s)Sustained (10 min)Notes
CLOB general9,000-Aggregate across CLOB endpoints.
CLOB POST /order3,50036,000Single‑order submit.
CLOB POST /orders1,00015,000Batch submit (up to 15 orders per request).
CLOB DELETE /order3,00030,000Single‑order cancel.
CLOB DELETE /orders1,00015,000Batch cancel.
CLOB GET /balance-allowance200-Balance and allowance queries.
CLOB API key endpoints100-Key management.
Gamma /markets300-Market metadata.
Gamma /events500-Event metadata.
Data /trades200-Trade history.
Data /positions150-Current positions.

WebSocket limits

The WebSocket quotas are not part of the published REST rate-limits table. The adapter ships a configurable per-connection subscription cap (ws_max_subscriptions_per_connection) defaulting to 200; Polymarket previously documented an upper bound of 500 per connection.

Exceeding Polymarket rate limits triggers Cloudflare throttling. Requests are queued using sliding windows rather than rejected immediately, but sustained overshoot can result in HTTP 429 responses or temporary blocking.

Data loader rate limiting

The PolymarketDataLoader includes built-in rate limiting when using the default HTTP client. Requests are automatically throttled to 100 requests per minute by default. That is a NautilusTrader default, not Polymarket's current published limit. The current Rust HTTP clients also ship with conservative 100 requests per minute quotas.

When fetching large date ranges across multiple markets:

  • Multiple loaders sharing the same http_client instance will coordinate rate limiting automatically.
  • For higher throughput, pass a custom http_client with adjusted quotas.
  • The loader does not implement automatic retry on 429 errors, so implement backoff if needed.

For the latest rate limit details, see the official Polymarket documentation: https://docs.polymarket.com/api-reference/rate-limits

Limitations and considerations

The following limitations are currently known:

  • Python order signing via py-clob-client is slow and can take around one second per order.
  • Reduce-only orders are not supported.
  • Batch submit (POST /orders) accepts at most 15 orders per request; the adapter splits larger SubmitOrderList commands into sequential 15-order chunks.

Configuration

The Python adapter (nautilus_trader.adapters.polymarket) and the Rust-native adapter (nautilus_trader.polymarket) expose different config surfaces. The tables below document both adapters in full.

Data client options (Python v1)

Class: PolymarketDataClientConfig in nautilus_trader.adapters.polymarket.config.

OptionDefaultDescription
venuePOLYMARKETVenue identifier registered for the data client.
private_keyNoneWallet private key; sourced from POLYMARKET_PK when omitted.
signature_type0Signature scheme (0 = EOA, 1 = email proxy, 2 = browser wallet proxy).
funderNoneUSDC.e funding wallet; sourced from POLYMARKET_FUNDER when omitted.
api_keyNoneAPI key; sourced from POLYMARKET_API_KEY when omitted.
api_secretNoneAPI secret; sourced from POLYMARKET_API_SECRET when omitted.
passphraseNoneAPI passphrase; sourced from POLYMARKET_PASSPHRASE when omitted.
base_url_httpNoneOverride for the REST base URL.
base_url_wsNoneOverride for the WebSocket base URL.
ws_connection_initial_delay_secs5Delay (seconds) before the first WebSocket connection to buffer subscriptions.
ws_connection_delay_secs0.1Delay (seconds) between subsequent WebSocket connection attempts.
ws_max_subscriptions_per_connection200Maximum instrument subscriptions per WebSocket connection (Polymarket limit is 500).
update_instruments_interval_mins60Interval (minutes) between instrument catalogue refreshes.
compute_effective_deltasFalseCompute effective order book deltas for bandwidth savings.
drop_quotes_missing_sideTrueDrop quotes with missing bid/ask prices instead of substituting boundary values.
instrument_configNoneOptional PolymarketInstrumentProviderConfig for instrument loading.

Execution client options (Python v1)

Class: PolymarketExecClientConfig in nautilus_trader.adapters.polymarket.config.

OptionDefaultDescription
venuePOLYMARKETVenue identifier registered for the execution client.
private_keyNoneWallet private key; sourced from POLYMARKET_PK when omitted.
signature_type0Signature scheme (0 = EOA, 1 = email proxy, 2 = browser wallet proxy).
funderNoneUSDC.e funding wallet; sourced from POLYMARKET_FUNDER when omitted.
api_keyNoneAPI key; sourced from POLYMARKET_API_KEY when omitted.
api_secretNoneAPI secret; sourced from POLYMARKET_API_SECRET when omitted.
passphraseNoneAPI passphrase; sourced from POLYMARKET_PASSPHRASE when omitted.
base_url_httpNoneOverride for the REST base URL.
base_url_wsNoneOverride for the WebSocket base URL.
base_url_data_apiNoneOverride for the Data API base URL (default https://data-api.polymarket.com).
ws_max_subscriptions_per_connection200Maximum instrument subscriptions per WebSocket connection (Polymarket limit is 500).
max_retriesNoneMaximum retry attempts for submit/cancel requests.
retry_delay_initial_msNoneInitial delay (milliseconds) between retries.
retry_delay_max_msNoneMaximum delay (milliseconds) between retries.
ack_timeout_secs5.0Timeout (seconds) to wait for order/trade acknowledgment from cache.
generate_order_history_from_tradesFalseGenerate synthetic order history from trade reports when True (experimental).
log_raw_ws_messagesFalseLog raw WebSocket payloads at INFO level when True.
instrument_configNoneOptional PolymarketInstrumentProviderConfig for instrument loading.

Data client options (Rust v2)

Struct: PolymarketDataClientConfig in crates/adapters/polymarket/src/config.rs.

OptionDefaultDescription
base_url_httpNone (official CLOB endpoint)Override for the CLOB REST base URL.
base_url_wsNone (official CLOB endpoint)Override for the CLOB WebSocket base URL.
base_url_gammaNone (official Gamma endpoint)Override for the Gamma API base URL.
base_url_data_apiNone (https://data-api.polymarket.com)Override for the Data API base URL.
http_timeout_secs60HTTP request timeout (seconds).
ws_timeout_secs30WebSocket connect/idle timeout (seconds).
ws_max_subscriptions200Maximum instrument subscriptions per WebSocket connection.
update_instruments_interval_mins60Interval (minutes) between instrument catalogue refreshes.
subscribe_new_marketsfalseSubscribe to new‑market discovery events via WebSocket when true.
filters[]Instrument filters applied during loading and discovery.
new_market_filterNoneOptional filter applied to newly discovered markets before emission.

The Rust data client config does not accept account credentials; authentication is handled by the execution client. Subscription buffering (ws_connection_initial_delay_secs) and quote handling (compute_effective_deltas, drop_quotes_missing_side) are Python-only today.

Execution client options (Rust v2)

Struct: PolymarketExecClientConfig in crates/adapters/polymarket/src/config.rs.

OptionDefaultDescription
trader_iddefault TraderIdTrader identifier the client registers under.
account_idPOLYMARKET-001Account identifier for this execution client.
private_keyNone (POLYMARKET_PK env)Wallet private key for EIP-712 signing.
api_keyNone (POLYMARKET_API_KEY env)CLOB API key (L2 auth).
api_secretNone (POLYMARKET_API_SECRET env)CLOB API secret (L2 auth).
passphraseNone (POLYMARKET_PASSPHRASE env)CLOB API passphrase (L2 auth).
funderNone (POLYMARKET_FUNDER env)USDC funding wallet.
signature_typeEoaSignature scheme (Eoa, PolyProxy, PolyGnosisSafe).
base_url_httpNone (official CLOB endpoint)Override for the CLOB REST base URL.
base_url_wsNone (official CLOB endpoint)Override for the CLOB WebSocket base URL.
base_url_data_apiNone (https://data-api.polymarket.com)Override for the Data API base URL.
http_timeout_secs60HTTP request timeout (seconds).
max_retries3Maximum retry attempts for single‑order submit/cancel requests.
retry_delay_initial_ms1000Initial delay (milliseconds) between retries.
retry_delay_max_ms10000Maximum delay (milliseconds) between retries.
ack_timeout_secs5Timeout (seconds) waiting for WebSocket order/trade acknowledgment.

The Rust execution client does not expose generate_order_history_from_trades, log_raw_ws_messages, ws_max_subscriptions_per_connection, or instrument_config. Batch submissions via POST /orders deliberately skip retry regardless of max_retries; the single-order path still retries on transient failures.

Instrument provider configuration options

The instrument provider config is passed via the instrument_config parameter on the data client config.

OptionDefaultDescription
load_allFalseLoad all venue instruments on start. Auto‑set to True when event_slug_builder is provided.
event_slug_builderNoneFully qualified path to a callable returning event slugs (e.g., "mymodule:build_slugs").

Event slug builder

The event_slug_builder feature enables efficient loading of niche markets without downloading the full venue catalogue. Instead of loading everything, you provide a function that returns event slugs for the specific markets you need.

from nautilus_trader.adapters.polymarket.providers import PolymarketInstrumentProviderConfig

# Configure with a slug builder function
instrument_config = PolymarketInstrumentProviderConfig(
    event_slug_builder="myproject.slugs:build_temperature_slugs",
)

The callable must have signature () -> list[str] and return a list of event slugs:

# myproject/slugs.py
from datetime import UTC, datetime, timedelta

def build_temperature_slugs() -> list[str]:
    """Build slugs for NYC temperature markets."""
    slugs = []
    today = datetime.now(tz=UTC).date()

    for i in range(7):
        date = today + timedelta(days=i)
        slug = f"highest-temperature-in-nyc-on-{date.strftime('%B-%d').lower()}"
        slugs.append(slug)

    return slugs

See examples/live/polymarket/slug_builders.py for more examples including crypto UpDown markets.

Historical data loading

The PolymarketDataLoader provides methods for fetching and parsing historical market data for research and backtesting purposes. The loader integrates with multiple Polymarket APIs to provide the required data.

All data fetching methods are asynchronous and must be called with await. The loader can optionally accept an http_client parameter for dependency injection (useful for testing).

Data sources

The loader fetches data from three primary sources:

  1. Polymarket Gamma API - Market metadata, instrument details, and active market listings.
  2. Polymarket CLOB API - Market details for instrument construction.
  3. Polymarket Data API - Historical trades and current user positions.

The current loader does not expose helpers for CLOB price history timeseries or order book history snapshots.

Method naming conventions

The loader provides two ways to access the Polymarket APIs:

PrefixTypeUse case
query_*Static methodsAPI exploration without an instrument. No loader instance needed.
fetch_*Instance methodsData fetching with a configured loader. Uses the loader's HTTP client.

Use query_* when you want to explore markets, discover events, or fetch metadata before committing to a specific instrument:

# No loader needed - just query the API directly
market = await PolymarketDataLoader.query_market_by_slug("some-market")
event = await PolymarketDataLoader.query_event_by_slug("some-event")

Use fetch_* when you have a loader instance and want to fetch data using its configured HTTP client (for coordinated rate limiting across multiple calls):

loader = await PolymarketDataLoader.from_market_slug("some-market")

# All fetch calls share the loader's HTTP client
markets = await loader.fetch_markets(active=True, limit=100)
events = await loader.fetch_events(active=True)
details = await loader.fetch_market_details(condition_id)

Finding markets

Use the provided utility scripts to discover active markets:

# List all active markets
python nautilus_trader/adapters/polymarket/scripts/active_markets.py

# List BTC and ETH UpDown markets specifically
python nautilus_trader/adapters/polymarket/scripts/list_updown_markets.py

Basic usage

The recommended way to create a loader is using the factory classmethods, which handle all the API calls and instrument creation automatically:

import asyncio

from nautilus_trader.adapters.polymarket import PolymarketDataLoader

async def main():
    # Create loader from market slug (recommended)
    loader = await PolymarketDataLoader.from_market_slug("gta-vi-released-before-june-2026")

    # Loader is ready to use with instrument and token_id set
    print(loader.instrument)
    print(loader.token_id)

asyncio.run(main())

For events with multiple markets (e.g., temperature buckets), use from_event_slug:

# Returns a list of loaders, one per market in the event
loaders = await PolymarketDataLoader.from_event_slug("highest-temperature-in-nyc-on-january-26")

Discovering markets and events

Use fetch_markets() and fetch_events() to discover available markets programmatically:

loader = await PolymarketDataLoader.from_market_slug("any-market")

# List active markets
markets = await loader.fetch_markets(active=True, closed=False, limit=100)
for market in markets:
    print(f"{market['slug']}: {market['question']}")

# List active events
events = await loader.fetch_events(active=True, limit=50)
for event in events:
    print(f"{event['slug']}: {event['title']}")

# Get all markets within a specific event
event_markets = await loader.get_event_markets("highest-temperature-in-nyc-on-january-26")

For quick exploration without creating a loader, use the static query_* methods (see Method naming conventions above).

Fetching trade history

The load_trades() convenience method fetches and parses historical trades in one step:

import pandas as pd

# Load all available trades
trades = await loader.load_trades()

# Or filter by time range (client-side filtering)
end = pd.Timestamp.now(tz="UTC")
start = end - pd.Timedelta(hours=24)

trades = await loader.load_trades(
    start=start,
    end=end,
)

Alternatively, you can fetch and parse separately using the lower-level methods:

condition_id = loader.condition_id

# Fetch raw trades from the Polymarket Data API
raw_trades = await loader.fetch_trades(condition_id=condition_id)

# Parse to NautilusTrader TradeTicks
trades = loader.parse_trades(raw_trades)

Trade data is sourced from the Polymarket Data API, which provides real execution data including price, size, side, and on-chain transaction hash.

Complete backtest example

A complete working example is available at examples/backtest/polymarket_simple_quoter.py:

import asyncio
from decimal import Decimal

from nautilus_trader.adapters.polymarket import POLYMARKET_VENUE
from nautilus_trader.adapters.polymarket import PolymarketDataLoader
from nautilus_trader.backtest.config import BacktestEngineConfig
from nautilus_trader.backtest.engine import BacktestEngine
from nautilus_trader.examples.strategies.ema_cross_long_only import EMACrossLongOnly
from nautilus_trader.examples.strategies.ema_cross_long_only import EMACrossLongOnlyConfig
from nautilus_trader.model.currencies import USDC_POS
from nautilus_trader.model.data import BarType
from nautilus_trader.model.enums import AccountType
from nautilus_trader.model.enums import OmsType
from nautilus_trader.model.identifiers import TraderId
from nautilus_trader.model.objects import Money

async def run_backtest():
    # Initialize loader and fetch market data
    loader = await PolymarketDataLoader.from_market_slug("gta-vi-released-before-june-2026")
    instrument = loader.instrument

    # Load historical trades from the Polymarket Data API
    trades = await loader.load_trades()

    # Configure and run backtest
    config = BacktestEngineConfig(trader_id=TraderId("BACKTESTER-001"))
    engine = BacktestEngine(config=config)

    engine.add_venue(
        venue=POLYMARKET_VENUE,
        oms_type=OmsType.NETTING,
        account_type=AccountType.CASH,
        base_currency=USDC_POS,
        starting_balances=[Money(10_000, USDC_POS)],
    )

    engine.add_instrument(instrument)
    engine.add_data(trades)

    bar_type = BarType.from_str(f"{instrument.id}-100-TICK-LAST-INTERNAL")
    strategy_config = EMACrossLongOnlyConfig(
        instrument_id=instrument.id,
        bar_type=bar_type,
        trade_size=Decimal("20"),
    )

    strategy = EMACrossLongOnly(config=strategy_config)
    engine.add_strategy(strategy=strategy)
    engine.run()

    # Display results
    print(engine.trader.generate_account_report(POLYMARKET_VENUE))

# Run the backtest
asyncio.run(run_backtest())

Run the complete example:

python examples/backtest/polymarket_simple_quoter.py

Helper functions

The adapter provides utility functions for working with Polymarket identifiers:

from nautilus_trader.adapters.polymarket import get_polymarket_instrument_id

# Create NautilusTrader InstrumentId from Polymarket identifiers
instrument_id = get_polymarket_instrument_id(
    condition_id="0xcccb7e7613a087c132b69cbf3a02bece3fdcb824c1da54ae79acc8d4a562d902",
    token_id="8441400852834915183759801017793514978104486628517653995211751018945988243154"
)

Contributing

For additional features or to contribute to the Polymarket adapter, please see our contributing guide.

On this page