Polymarket¶
Polymarket decentralized prediction market integration adapter.
This subpackage provides instrument providers, data and execution client configurations, factories, constants, and credential helpers for connecting to and interacting with the Polymarket Central Limit Order Book (CLOB) API.
For convenience, the most commonly used symbols are re-exported at the subpackage’s
top level, so downstream code can simply import from nautilus_trader.adapters.polymarket.
- class PolymarketDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
PolymarketDataClientinstances.- Parameters:
instrument_config (PolymarketInstrumentProviderConfig, optional) – The Polymarket instrument provider config.
venue (Venue, default POLYMARKET_VENUE) – The venue for the client.
private_key (str, optional) – The private key for the wallet on the Polygon network. If
Nonethen will source the POLYMARKET_PK environment variable.signature_type (int, default 0 (EOA)) – The Polymarket signature type: - 0: EOA (Externally Owned Account) - 1: Email/Magic Wallet Proxy - 2: Browser Wallet Proxy
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC. If
Nonethen will source the POLYMARKET_FUNDER environment variable.api_key (str, optional) – The Polymarket API key. If
Nonethen will source the POLYMARKET_API_KEY environment variable.api_secret (str, optional) – The Polymarket API secret. If
Nonethen will source the POLYMARKET_API_SECRET environment variable.passphrase (str, optional) – The Polymarket API passphrase. If
Nonethen will source the POLYMARKET_PASSPHRASE environment variable.base_url_http (str, optional) – The HTTP client custom endpoint override.
base_url_ws (str, optional) – The WebSocket client custom endpoint override.
ws_connection_initial_delay_secs (PositiveFloat, default 5) – The delay (seconds) prior to the first websocket connection to allow initial subscriptions to arrive.
ws_connection_delay_secs (PositiveFloat, default 0.1) – The delay (seconds) prior to making a new websocket connection to allow non-initial subscriptions to arrive.
ws_max_subscriptions_per_connection (PositiveInt, default 200) – The maximum number of subscriptions per WebSocket connection (Polymarket limit is 500).
update_instruments_interval_mins (PositiveInt or None, default 60) – The interval (minutes) between updating Polymarket instruments.
compute_effective_deltas (bool, default False) – If True, computes effective deltas by comparing old and new order book states, reducing snapshot size. This takes ~1 millisecond, so is not recommended for latency-sensitive strategies.
drop_quotes_missing_side (bool, default True) – If True, drops QuoteTick messages when bid or ask prices are missing (can occur near market resolution). If False, uses boundary prices (0.001/0.999) with zero volume for missing sides.
- instrument_config: PolymarketInstrumentProviderConfig | None¶
- private_key: str | None¶
- signature_type: int¶
- funder: str | None¶
- api_key: str | None¶
- api_secret: str | None¶
- passphrase: str | None¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- ws_connection_initial_delay_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- ws_connection_delay_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- ws_max_subscriptions_per_connection: Annotated[int, msgspec.Meta(gt=0)]¶
- update_instruments_interval_mins: Annotated[int, msgspec.Meta(gt=0)] | None¶
- compute_effective_deltas: bool¶
- drop_quotes_missing_side: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- handle_revised_bars: bool¶
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class PolymarketDataLoader¶
Bases:
objectProvides a data loader for historical Polymarket market data.
This loader fetches data from: - Polymarket Gamma API (market and event information) - Polymarket CLOB API (market details) - Polymarket Data API (historical trades)
If no http_client is provided, the loader creates one with a default rate limit of 100 requests per minute, matching Polymarket’s public endpoint limit.
- Parameters:
instrument (BinaryOption) – The binary option instrument to load data for.
token_id (str, optional) – The Polymarket token ID for this instrument.
condition_id (str, optional) – The Polymarket condition ID for this instrument’s market.
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for requests. If not provided, a new client will be created.
- async classmethod from_market_slug(slug: str, token_index: int = 0, http_client: HttpClient | None = None) PolymarketDataLoader¶
Create a loader by fetching market data from Polymarket APIs.
- Parameters:
slug (str) – The market slug to search for.
token_index (int, default 0) – The index of the token to use (0 for first outcome, 1 for second).
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for requests. If not provided, a new client will be created.
- Return type:
- Raises:
ValueError – If market with slug is not found or has no tokens.
RuntimeError – If HTTP requests fail.
- async classmethod from_event_slug(slug: str, token_index: int = 0, http_client: HttpClient | None = None) list[PolymarketDataLoader]¶
Create loaders for all markets in an event.
This is useful for events that contain multiple related markets, such as temperature bucket markets where each bucket is a separate market.
- Parameters:
slug (str) – The event slug to fetch.
token_index (int, default 0) – The index of the token to use (0 for first outcome, 1 for second).
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for requests. If not provided, a new client will be created.
- Returns:
List of loaders, one for each market in the event.
- Return type:
list[PolymarketDataLoader]
- Raises:
ValueError – If event with slug is not found, has no markets, or token_index is out of range.
- async static query_market_by_slug(slug: str, http_client: HttpClient | None = None) dict[str, Any]¶
Query market data by slug without requiring a loader instance.
- Parameters:
slug (str) – The market slug to fetch.
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for the request.
- Returns:
Market data dictionary.
- Return type:
dict[str, Any]
- Raises:
ValueError – If market with the given slug is not found.
RuntimeError – If HTTP request fails.
- async static query_market_details(condition_id: str, http_client: HttpClient | None = None) dict[str, Any]¶
Query detailed market information without requiring a loader instance.
- Parameters:
condition_id (str) – The market condition ID.
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for the request.
- Returns:
Detailed market information.
- Return type:
dict[str, Any]
- Raises:
RuntimeError – If HTTP request fails.
- async static query_event_by_slug(slug: str, http_client: HttpClient | None = None) dict[str, Any]¶
Query event data by slug without requiring a loader instance.
- Parameters:
slug (str) – The event slug to fetch.
http_client (nautilus_pyo3.HttpClient, optional) – The HTTP client to use for the request.
- Returns:
Event data dictionary containing ‘markets’ array and event metadata.
- Return type:
dict[str, Any]
- Raises:
ValueError – If event with the given slug is not found.
RuntimeError – If HTTP request fails.
- property instrument: BinaryOption¶
Return the instrument for this loader.
- property token_id: str | None¶
Return the token ID for this loader.
- property condition_id: str | None¶
Return the condition ID for this loader.
- async load_trades(start: Timestamp | None = None, end: Timestamp | None = None) list[TradeTick]¶
Load trade ticks from the Polymarket Data API.
This is a convenience method that fetches and parses historical trades using the loader’s stored condition_id and token_id.
- Parameters:
start (pd.Timestamp, optional) – Start time filter (client-side). If
None, no lower bound.end (pd.Timestamp, optional) – End time filter (client-side). If
None, no upper bound.
- Returns:
Parsed trade ticks sorted chronologically, ready for backtesting.
- Return type:
list[TradeTick]
- Raises:
ValueError – If condition_id or token_id was not provided during initialization.
- async fetch_event_by_slug(slug: str) dict[str, Any]¶
Fetch an event by slug from the Polymarket Gamma API.
Events contain multiple markets (e.g., temperature bucket markets are grouped under a single event like “highest-temperature-in-nyc-on-january-26”).
- Parameters:
slug (str) – The event slug to fetch.
- Returns:
Event data dictionary containing ‘markets’ array and event metadata.
- Return type:
dict[str, Any]
- Raises:
ValueError – If event with the given slug is not found.
RuntimeError – If HTTP requests fail.
- async fetch_events(active: bool = True, closed: bool = False, archived: bool = False, limit: int = 100, offset: int = 0) list[dict[str, Any]]¶
Fetch events from Polymarket Gamma API.
- Parameters:
active (bool, default True) – Filter for active events.
closed (bool, default False) – Include closed events.
archived (bool, default False) – Include archived events.
limit (int, default 100) – Maximum number of events to return.
offset (int, default 0) – Offset for pagination.
- Returns:
List of event data dictionaries.
- Return type:
list[dict[str, Any]]
- async get_event_markets(slug: str) list[dict[str, Any]]¶
Get all markets within an event by slug.
This is a convenience method that fetches an event and extracts its markets.
- Parameters:
slug (str) – The event slug to fetch markets from.
- Returns:
List of market dictionaries within the event.
- Return type:
list[dict[str, Any]]
- Raises:
ValueError – If event with the given slug is not found.
- async fetch_markets(active: bool = True, closed: bool = False, archived: bool = False, limit: int = 100, offset: int = 0) list[dict]¶
Fetch markets from Polymarket Gamma API.
- Parameters:
active (bool, default True) – Filter for active markets.
closed (bool, default False) – Include closed markets.
archived (bool, default False) – Include archived markets.
limit (int, default 100) – Maximum number of markets to return.
offset (int, default 0) – Offset for pagination.
- Returns:
List of market data dictionaries.
- Return type:
list[dict]
- async fetch_market_by_slug(slug: str) dict[str, Any]¶
Fetch a single market by slug using the Polymarket Gamma API slug endpoint.
- Parameters:
slug (str) – The market slug to fetch.
- Returns:
Market data dictionary.
- Return type:
dict[str, Any]
- Raises:
ValueError – If market with the given slug is not found.
RuntimeError – If HTTP requests fail.
- async find_market_by_slug(slug: str) dict[str, Any]¶
Find a specific market by slug.
- Parameters:
slug (str) – The market slug to search for.
- Returns:
Market data dictionary.
- Return type:
dict[str, Any]
- Raises:
ValueError – If market with the given slug is not found.
- async fetch_market_details(condition_id: str) dict[str, Any]¶
Fetch detailed market information from Polymarket CLOB API.
- Parameters:
condition_id (str) – The market condition ID.
- Returns:
Detailed market information.
- Return type:
dict[str, Any]
- async fetch_trades(condition_id: str, limit: int = 10000) list[dict[str, Any]]¶
Fetch trades from the Polymarket Data API.
- Parameters:
condition_id (str) – The market condition ID.
limit (int, default 10_000) – Number of trades per request (max 10,000).
- Returns:
List of trade dictionaries (newest first).
- Return type:
list[dict[str, Any]]
Notes
This method automatically handles pagination using offset-based requests. The API caps offset at 10,000, so a maximum of ~20,000 trades can be fetched per condition.
- class PolymarketExecClientConfig¶
Bases:
LiveExecClientConfigConfiguration for
PolymarketExecutionClientinstances.- Parameters:
instrument_config (PolymarketInstrumentProviderConfig, optional) – The Polymarket instrument provider config.
venue (Venue, default POLYMARKET_VENUE) – The venue for the client.
private_key (str, optional) – The private key for the wallet on the Polygon network. If
Nonethen will source the POLYMARKET_PK environment variable.signature_type (int, default 0 (EOA)) – The Polymarket signature type: - 0: EOA (Externally Owned Account) - 1: Email/Magic Wallet Proxy - 2: Browser Wallet Proxy
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC. If
Nonethen will source the POLYMARKET_FUNDER environment variable.api_key (str, optional) – The Polymarket API key. If
Nonethen will source the POLYMARKET_API_KEY environment variable.api_secret (str, optional) – The Polymarket API secret. If
Nonethen will source the POLYMARKET_API_SECRET environment variable.passphrase (str, optional) – The Polymarket API passphrase. If
Nonethen will source the POLYMARKET_PASSPHRASE environment variable.base_url_http (str, optional) – The HTTP client custom endpoint override.
base_url_ws (str, optional) – The WebSocket client custom endpoint override.
ws_max_subscriptions_per_connection (PositiveInt, default 200) – The maximum number of subscriptions per WebSocket connection (Polymarket limit is 500).
max_retries (PositiveInt, optional) – The maximum number of times a submit or cancel order request will be retried.
retry_delay_initial_ms (PositiveInt, optional) – The initial delay (milliseconds) between retries. Short delays with frequent retries may result in account bans.
retry_delay_max_ms (PositiveInt, optional) – The maximum delay (milliseconds) between retries.
generate_order_history_from_trades (bool, default False) – If True, uses trades history to generate reports for orders which are no longer active. The Polymarket API only returns active orders and trades. This feature is experimental and is not currently recommended (leave set to False).
log_raw_ws_messages (bool, default False) – If raw websocket messages should be logged with INFO level. Note: there will be a performance penalty parsing the JSON without an efficient msgspec decoder.
ack_timeout_secs (PositiveFloat, default 5.0) – The timeout (seconds) to wait for order/trade acknowledgment from cache.
use_data_api (bool, default False) – Determines which API to use for fetching user positions: - True: Data API (experimental) - efficient for large workloads, fewer API calls - False: CLOB API (stable, default) - balance/allowance endpoint, one request per instrument
- instrument_config: PolymarketInstrumentProviderConfig | None¶
- private_key: str | None¶
- signature_type: int¶
- funder: str | None¶
- api_key: str | None¶
- api_secret: str | None¶
- passphrase: str | None¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- ws_max_subscriptions_per_connection: Annotated[int, msgspec.Meta(gt=0)]¶
- max_retries: Annotated[int, msgspec.Meta(gt=0)] | None¶
- retry_delay_initial_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- retry_delay_max_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- generate_order_history_from_trades: bool¶
- log_raw_ws_messages: bool¶
- ack_timeout_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- use_data_api: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class PolymarketInstrumentProvider¶
Bases:
InstrumentProviderProvides Nautilus instrument definitions from Polymarket.
- Parameters:
client (ClobClient) – The Polymarket CLOB HTTP client.
clock (LiveClock) – The clock instance.
config (PolymarketInstrumentProviderConfig, optional) – The instrument provider configuration, by default None.
http_client (HttpClient, optional) – The HTTP client for Gamma API requests.
- async load_all_async(filters: dict | None = None) None¶
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
- async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_async(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- add(instrument: Instrument) None¶
Add the given instrument to the provider.
- Parameters:
instrument (Instrument) – The instrument to add.
- add_bulk(instruments: list[Instrument]) None¶
Add the given instruments bulk to the provider.
- Parameters:
instruments (list[Instrument]) – The instruments to add.
- add_currency(currency: Currency) None¶
Add the given currency to the provider.
- Parameters:
currency (Currency) – The currency to add.
- property count: int¶
Return the count of instruments held by the provider.
- Return type:
int
- currencies() dict[str, Currency]¶
Return all currencies held by the instrument provider.
- Return type:
dict[str, Currency]
- currency(code: str) Currency | None¶
Return the currency with the given code (if found).
- Parameters:
code (str) – The currency code.
- Return type:
Currency or
None- Raises:
ValueError – If code is not a valid string.
- find(instrument_id: InstrumentId) Instrument | None¶
Return the instrument for the given instrument ID (if found).
- Parameters:
instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None
- get_all() dict[InstrumentId, Instrument]¶
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type:
dict[InstrumentId, Instrument]
- async initialize(reload: bool = False) None¶
Initialize the instrument provider.
- Parameters:
reload (bool, default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
- list_all() list[Instrument]¶
Return all loaded instruments.
- Return type:
list[Instrument]
- load(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_all(filters: dict | None = None) None¶
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters:
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- class PolymarketLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides a Polymarket live data client factory.
- static create(loop: AbstractEventLoop, name: str, config: PolymarketDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) PolymarketDataClient¶
Create a new Polymarket data client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (PolymarketDataClientConfig) – The client configuration.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the instrument provider.
- Return type:
- class PolymarketLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides a Polymarket live execution client factory.
- static create(loop: AbstractEventLoop, name: str, config: PolymarketExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) PolymarketExecutionClient¶
Create a new Polymarket execution client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (PolymarketExecClientConfig) – The client configuration.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the instrument provider.
- Return type:
- get_polymarket_http_client(api_key: str | None = None, api_secret: str | None = None, passphrase: str | None = None, base_url: str | None = None, chain_id: int = 137, signature_type: int = 0, private_key: str | None = None, funder: str | None = None) ClobClient¶
Cache and return a Polymarket CLOB client.
If a cached client with matching parameters already exists, the cached client will be returned.
- Parameters:
api_key (str, optional) – The API key for the client.
api_secret (str, optional) – The API secret for the client.
passphrase (str, optional) – The passphrase for the client.
base_url (str, optional) – The base URL for the API endpoints.
chain_id (int, default POLYGON) – The chain ID for the client.
signature_type (int, default 0 (EOA)) – The Polymarket signature type.
private_key (str, optional) – The private key for the wallet on the Polygon network.
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC.
- Return type:
ClobClient
- get_polymarket_instrument_id(condition_id: str, token_id: str | int) InstrumentId¶
- get_polymarket_instrument_provider(client: ClobClient, clock: LiveClock, config: PolymarketInstrumentProviderConfig | None) PolymarketInstrumentProvider¶
Cache and return a Polymarket instrument provider.
If a cached provider already exists, then that provider will be returned.
- Parameters:
client (py_clob_client.client.ClobClient) – The client for the instrument provider.
clock (LiveClock) – The clock for the instrument provider.
config (PolymarketInstrumentProviderConfig, optional) – The configuration for the instrument provider.
- Return type:
- parse_polymarket_instrument(market_info: dict[str, Any], token_id: str, outcome: str, ts_init: int | None = None) BinaryOption¶
Config¶
- class PolymarketDataClientConfig¶
Bases:
LiveDataClientConfigConfiguration for
PolymarketDataClientinstances.- Parameters:
instrument_config (PolymarketInstrumentProviderConfig, optional) – The Polymarket instrument provider config.
venue (Venue, default POLYMARKET_VENUE) – The venue for the client.
private_key (str, optional) – The private key for the wallet on the Polygon network. If
Nonethen will source the POLYMARKET_PK environment variable.signature_type (int, default 0 (EOA)) – The Polymarket signature type: - 0: EOA (Externally Owned Account) - 1: Email/Magic Wallet Proxy - 2: Browser Wallet Proxy
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC. If
Nonethen will source the POLYMARKET_FUNDER environment variable.api_key (str, optional) – The Polymarket API key. If
Nonethen will source the POLYMARKET_API_KEY environment variable.api_secret (str, optional) – The Polymarket API secret. If
Nonethen will source the POLYMARKET_API_SECRET environment variable.passphrase (str, optional) – The Polymarket API passphrase. If
Nonethen will source the POLYMARKET_PASSPHRASE environment variable.base_url_http (str, optional) – The HTTP client custom endpoint override.
base_url_ws (str, optional) – The WebSocket client custom endpoint override.
ws_connection_initial_delay_secs (PositiveFloat, default 5) – The delay (seconds) prior to the first websocket connection to allow initial subscriptions to arrive.
ws_connection_delay_secs (PositiveFloat, default 0.1) – The delay (seconds) prior to making a new websocket connection to allow non-initial subscriptions to arrive.
ws_max_subscriptions_per_connection (PositiveInt, default 200) – The maximum number of subscriptions per WebSocket connection (Polymarket limit is 500).
update_instruments_interval_mins (PositiveInt or None, default 60) – The interval (minutes) between updating Polymarket instruments.
compute_effective_deltas (bool, default False) – If True, computes effective deltas by comparing old and new order book states, reducing snapshot size. This takes ~1 millisecond, so is not recommended for latency-sensitive strategies.
drop_quotes_missing_side (bool, default True) – If True, drops QuoteTick messages when bid or ask prices are missing (can occur near market resolution). If False, uses boundary prices (0.001/0.999) with zero volume for missing sides.
- instrument_config: PolymarketInstrumentProviderConfig | None¶
- private_key: str | None¶
- signature_type: int¶
- funder: str | None¶
- api_key: str | None¶
- api_secret: str | None¶
- passphrase: str | None¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- ws_connection_initial_delay_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- ws_connection_delay_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- ws_max_subscriptions_per_connection: Annotated[int, msgspec.Meta(gt=0)]¶
- update_instruments_interval_mins: Annotated[int, msgspec.Meta(gt=0)] | None¶
- compute_effective_deltas: bool¶
- drop_quotes_missing_side: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- handle_revised_bars: bool¶
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class PolymarketExecClientConfig¶
Bases:
LiveExecClientConfigConfiguration for
PolymarketExecutionClientinstances.- Parameters:
instrument_config (PolymarketInstrumentProviderConfig, optional) – The Polymarket instrument provider config.
venue (Venue, default POLYMARKET_VENUE) – The venue for the client.
private_key (str, optional) – The private key for the wallet on the Polygon network. If
Nonethen will source the POLYMARKET_PK environment variable.signature_type (int, default 0 (EOA)) – The Polymarket signature type: - 0: EOA (Externally Owned Account) - 1: Email/Magic Wallet Proxy - 2: Browser Wallet Proxy
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC. If
Nonethen will source the POLYMARKET_FUNDER environment variable.api_key (str, optional) – The Polymarket API key. If
Nonethen will source the POLYMARKET_API_KEY environment variable.api_secret (str, optional) – The Polymarket API secret. If
Nonethen will source the POLYMARKET_API_SECRET environment variable.passphrase (str, optional) – The Polymarket API passphrase. If
Nonethen will source the POLYMARKET_PASSPHRASE environment variable.base_url_http (str, optional) – The HTTP client custom endpoint override.
base_url_ws (str, optional) – The WebSocket client custom endpoint override.
ws_max_subscriptions_per_connection (PositiveInt, default 200) – The maximum number of subscriptions per WebSocket connection (Polymarket limit is 500).
max_retries (PositiveInt, optional) – The maximum number of times a submit or cancel order request will be retried.
retry_delay_initial_ms (PositiveInt, optional) – The initial delay (milliseconds) between retries. Short delays with frequent retries may result in account bans.
retry_delay_max_ms (PositiveInt, optional) – The maximum delay (milliseconds) between retries.
generate_order_history_from_trades (bool, default False) – If True, uses trades history to generate reports for orders which are no longer active. The Polymarket API only returns active orders and trades. This feature is experimental and is not currently recommended (leave set to False).
log_raw_ws_messages (bool, default False) – If raw websocket messages should be logged with INFO level. Note: there will be a performance penalty parsing the JSON without an efficient msgspec decoder.
ack_timeout_secs (PositiveFloat, default 5.0) – The timeout (seconds) to wait for order/trade acknowledgment from cache.
use_data_api (bool, default False) – Determines which API to use for fetching user positions: - True: Data API (experimental) - efficient for large workloads, fewer API calls - False: CLOB API (stable, default) - balance/allowance endpoint, one request per instrument
- instrument_config: PolymarketInstrumentProviderConfig | None¶
- private_key: str | None¶
- signature_type: int¶
- funder: str | None¶
- api_key: str | None¶
- api_secret: str | None¶
- passphrase: str | None¶
- base_url_http: str | None¶
- base_url_ws: str | None¶
- ws_max_subscriptions_per_connection: Annotated[int, msgspec.Meta(gt=0)]¶
- max_retries: Annotated[int, msgspec.Meta(gt=0)] | None¶
- retry_delay_initial_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- retry_delay_max_ms: Annotated[int, msgspec.Meta(gt=0)] | None¶
- generate_order_history_from_trades: bool¶
- log_raw_ws_messages: bool¶
- ack_timeout_secs: Annotated[float, msgspec.Meta(gt=0.0)]¶
- use_data_api: bool¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- instrument_provider: InstrumentProviderConfig¶
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- routing: RoutingConfig¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
Factories¶
- get_polymarket_http_client(api_key: str | None = None, api_secret: str | None = None, passphrase: str | None = None, base_url: str | None = None, chain_id: int = 137, signature_type: int = 0, private_key: str | None = None, funder: str | None = None) ClobClient¶
Cache and return a Polymarket CLOB client.
If a cached client with matching parameters already exists, the cached client will be returned.
- Parameters:
api_key (str, optional) – The API key for the client.
api_secret (str, optional) – The API secret for the client.
passphrase (str, optional) – The passphrase for the client.
base_url (str, optional) – The base URL for the API endpoints.
chain_id (int, default POLYGON) – The chain ID for the client.
signature_type (int, default 0 (EOA)) – The Polymarket signature type.
private_key (str, optional) – The private key for the wallet on the Polygon network.
funder (str, optional) – The wallet address (public key) on the Polygon network used for funding USDC.
- Return type:
ClobClient
- get_polymarket_instrument_provider(client: ClobClient, clock: LiveClock, config: PolymarketInstrumentProviderConfig | None) PolymarketInstrumentProvider¶
Cache and return a Polymarket instrument provider.
If a cached provider already exists, then that provider will be returned.
- Parameters:
client (py_clob_client.client.ClobClient) – The client for the instrument provider.
clock (LiveClock) – The clock for the instrument provider.
config (PolymarketInstrumentProviderConfig, optional) – The configuration for the instrument provider.
- Return type:
- class PolymarketLiveDataClientFactory¶
Bases:
LiveDataClientFactoryProvides a Polymarket live data client factory.
- static create(loop: AbstractEventLoop, name: str, config: PolymarketDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) PolymarketDataClient¶
Create a new Polymarket data client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (PolymarketDataClientConfig) – The client configuration.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the instrument provider.
- Return type:
- class PolymarketLiveExecClientFactory¶
Bases:
LiveExecClientFactoryProvides a Polymarket live execution client factory.
- static create(loop: AbstractEventLoop, name: str, config: PolymarketExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) PolymarketExecutionClient¶
Create a new Polymarket execution client.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
name (str) – The custom client ID.
config (PolymarketExecClientConfig) – The client configuration.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the instrument provider.
- Return type:
Enums¶
- class PolymarketEventType¶
Bases:
Enum- PLACEMENT = 'PLACEMENT'¶
- UPDATE = 'UPDATE'¶
- CANCELLATION = 'CANCELLATION'¶
- TRADE = 'TRADE'¶
Providers¶
- class PolymarketInstrumentProviderConfig¶
Bases:
InstrumentProviderConfigConfiguration for
PolymarketInstrumentProviderinstances.- Parameters:
event_slug_builder (str, optional) –
A fully qualified path to a callable that returns a list of event slugs to fetch. The callable should have signature: () -> list[str].
When set, the provider will call this function on each initialization/refresh cycle to dynamically generate event slugs, then fetch only those specific events from the Gamma API. This is much more efficient for niche markets with predictable slug patterns (e.g., temperature markets, UpDown crypto markets).
Example: “myproject.slugs:build_temperature_slugs”
- event_slug_builder: str | None¶
- dict() dict[str, Any]¶
Return a dictionary representation of the configuration.
- Return type:
dict[str, Any]
- filter_callable: str | None¶
- filters: dict[str, Any] | None¶
- classmethod fully_qualified_name() str¶
Return the fully qualified name for the NautilusConfig class.
- Return type:
str
References
- property id: str¶
Return the hashed identifier for the configuration.
- Return type:
str
- json() bytes¶
Return serialized JSON encoded bytes.
- Return type:
bytes
- json_primitives() dict[str, Any]¶
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type:
dict[str, Any]
- classmethod json_schema() dict[str, Any]¶
Generate a JSON schema for this configuration class.
- Return type:
dict[str, Any]
- load_all: bool¶
- load_ids: frozenset[InstrumentId] | None¶
- log_warnings: bool¶
- classmethod parse(raw: bytes | str) Any¶
Return a decoded object of the given cls.
- Parameters:
cls (type) – The type to decode to.
raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type:
Any
- use_gamma_markets: bool¶
- validate() bool¶
Return whether the configuration can be represented as valid JSON.
- Return type:
bool
- class PolymarketInstrumentProvider¶
Bases:
InstrumentProviderProvides Nautilus instrument definitions from Polymarket.
- Parameters:
client (ClobClient) – The Polymarket CLOB HTTP client.
clock (LiveClock) – The clock instance.
config (PolymarketInstrumentProviderConfig, optional) – The instrument provider configuration, by default None.
http_client (HttpClient, optional) – The HTTP client for Gamma API requests.
- async load_all_async(filters: dict | None = None) None¶
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
- async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
The default implementation calls
load_all_async(since many venue APIs only support bulk fetches) and then filters the provider to retain only the requested instruments plus any previously loaded ones.Subclasses with per-instrument fetch capability should override this method.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- async load_async(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
The default implementation delegates to
load_ids_async. Subclasses with per-instrument fetch capability should override this method.- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- add(instrument: Instrument) None¶
Add the given instrument to the provider.
- Parameters:
instrument (Instrument) – The instrument to add.
- add_bulk(instruments: list[Instrument]) None¶
Add the given instruments bulk to the provider.
- Parameters:
instruments (list[Instrument]) – The instruments to add.
- add_currency(currency: Currency) None¶
Add the given currency to the provider.
- Parameters:
currency (Currency) – The currency to add.
- property count: int¶
Return the count of instruments held by the provider.
- Return type:
int
- currencies() dict[str, Currency]¶
Return all currencies held by the instrument provider.
- Return type:
dict[str, Currency]
- currency(code: str) Currency | None¶
Return the currency with the given code (if found).
- Parameters:
code (str) – The currency code.
- Return type:
Currency or
None- Raises:
ValueError – If code is not a valid string.
- find(instrument_id: InstrumentId) Instrument | None¶
Return the instrument for the given instrument ID (if found).
- Parameters:
instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None
- get_all() dict[InstrumentId, Instrument]¶
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type:
dict[InstrumentId, Instrument]
- async initialize(reload: bool = False) None¶
Initialize the instrument provider.
- Parameters:
reload (bool, default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
- list_all() list[Instrument]¶
Return all loaded instruments.
- Return type:
list[Instrument]
- load(instrument_id: InstrumentId, filters: dict | None = None) None¶
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
instrument_id (InstrumentId) – The instrument ID to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_all(filters: dict | None = None) None¶
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters:
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
- load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) None¶
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
instrument_ids (list[InstrumentId]) – The instrument IDs to load.
filters (frozendict[str, Any] or dict[str, Any], optional) – The venue specific instrument loading filters to apply.
Data¶
- class PolymarketDataClient¶
Bases:
LiveMarketDataClientProvides a data client for Polymarket, a decentralized predication market.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
http_client (py_clob_client.client.ClobClient) – The Polymarket HTTP client.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
instrument_provider (PolymarketInstrumentProvider) – The instrument provider.
config (PolymarketDataClientConfig) – The configuration for the client.
name (str, optional) – The custom client ID.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task | None¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (LogColor, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- id¶
The components ID.
- Returns:
ComponentId
- is_connected¶
If the client is connected.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- request(self, RequestData request) void¶
Request data for the given data type.
- Parameters:
request (RequestData) – The message for the data request.
- request_bars(self, RequestBars request) void¶
Request historical Bar data. To load historical data from a catalog, you can pass a list[DataCatalogConfig] to the TradingNodeConfig or the BacktestEngineConfig.
- Parameters:
request (RequestBars) – The message for the data request.
- request_funding_rates(self, RequestFundingRates request) void¶
Request historical FundingRateUpdate data.
- Parameters:
request (RequestFundingRates) – The message for the data request.
- request_instrument(self, RequestInstrument request) void¶
Request Instrument data for the given instrument ID.
- Parameters:
request (RequestInstrument) – The message for the data request.
- request_instruments(self, RequestInstruments request) void¶
Request all Instrument data for the given venue.
- Parameters:
request (RequestInstruments) – The message for the data request.
- request_order_book_deltas(self, RequestOrderBookDeltas request) void¶
Request historical OrderBookDeltas data.
- Parameters:
request (RequestOrderBookDeltas) – The message for the data request.
- request_order_book_depth(request: RequestOrderBookDepth) None¶
- request_order_book_snapshot(self, RequestOrderBookSnapshot request) void¶
Request order book snapshot data.
- Parameters:
request (RequestOrderBookSnapshot) – The message for the data request.
- request_quote_ticks(self, RequestQuoteTicks request) void¶
Request historical QuoteTick data.
- Parameters:
request (RequestQuoteTicks) – The message for the data request.
- request_trade_ticks(self, RequestTradeTicks request) void¶
Request historical TradeTick data.
- Parameters:
request (RequestTradeTicks) – The message for the data request.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- resume(self) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- async run_after_delay(delay: float, coro: Coroutine) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- subscribe(self, SubscribeData command) void¶
Subscribe to data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_bars(self, SubscribeBars command) void¶
Subscribe to Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_funding_rates(self, SubscribeFundingRates command) void¶
Subscribe to FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_index_prices(self, SubscribeIndexPrices command) void¶
Subscribe to IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument(self, SubscribeInstrument command) void¶
Subscribe to the Instrument with the given instrument ID.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_close(self, SubscribeInstrumentClose command) void¶
Subscribe to InstrumentClose updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instrument_status(self, SubscribeInstrumentStatus command) void¶
Subscribe to InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_instruments(self, SubscribeInstruments command) void¶
Subscribe to all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_mark_prices(self, SubscribeMarkPrices command) void¶
Subscribe to MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_deltas(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional, default None) – The maximum depth for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_order_book_depth(self, SubscribeOrderBook command) void¶
Subscribe to OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
depth (int, optional) – The maximum depth for the order book (defaults to 10).
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_quote_ticks(self, SubscribeQuoteTicks command) void¶
Subscribe to QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribe_trade_ticks(self, SubscribeTradeTicks command) void¶
Subscribe to TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- subscribed_custom_data(self) list¶
Return the custom data types subscribed to.
- Return type:
list[DataType]
- subscribed_funding_rates(self) list¶
Return the funding rate update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_index_prices(self) list¶
Return the index price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_close(self) list¶
Return the instrument closes subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instrument_status(self) list¶
Return the status update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_instruments(self) list¶
Return the instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_mark_prices(self) list¶
Return the mark price update instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_deltas(self) list¶
Return the order book delta instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_order_book_depth(self) list¶
Return the order book depth instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_quote_ticks(self) list¶
Return the quote tick instruments subscribed to.
- Return type:
list[InstrumentId]
- subscribed_trade_ticks(self) list¶
Return the trade tick instruments subscribed to.
- Return type:
list[InstrumentId]
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe(self, UnsubscribeData command) void¶
Unsubscribe from data for the given data type.
- Parameters:
data_type (DataType) – The data type for the subscription.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_bars(self, UnsubscribeBars command) void¶
Unsubscribe from Bar data for the given bar type.
- Parameters:
bar_type (BarType) – The bar type to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_funding_rates(self, UnsubscribeFundingRates command) void¶
Unsubscribe from FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_index_prices(self, UnsubscribeIndexPrices command) void¶
Unsubscribe from IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument(self, UnsubscribeInstrument command) void¶
Unsubscribe from Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_close(self, UnsubscribeInstrumentClose command) void¶
Unsubscribe from InstrumentClose data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instrument_status(self, UnsubscribeInstrumentStatus command) void¶
Unsubscribe from InstrumentStatus data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_instruments(self, UnsubscribeInstruments command) void¶
Unsubscribe from all Instrument data.
- Parameters:
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_mark_prices(self, UnsubscribeMarkPrices command) void¶
Unsubscribe from MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_deltas(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDeltas data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_order_book_depth(self, UnsubscribeOrderBook command) void¶
Unsubscribe from OrderBookDepth10 data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_quote_ticks(self, UnsubscribeQuoteTicks command) void¶
Unsubscribe from QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- unsubscribe_trade_ticks(self, UnsubscribeTradeTicks command) void¶
Unsubscribe from TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
params (dict[str, Any], optional) – Additional params for the subscription.
- venue¶
The clients venue ID (if applicable).
- Returns:
Venue or
None
Execution¶
- class PolymarketExecutionClient¶
Bases:
LiveExecutionClientProvides an execution client for Polymarket, a decentralized predication market.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop for the client.
http_client (py_clob_client.client.ClobClient) – The Polymarket HTTP client.
msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (LiveClock) – The clock for the client.
instrument_provider (PolymarketInstrumentProvider) – The instrument provider.
config (PolymarketExecClientConfig) – The configuration for the client.
name (str, optional) – The custom client ID.
- PROCESSED_TRADES_LIMIT = 10000¶
- async generate_order_status_reports(command: GenerateOrderStatusReports) list[OrderStatusReport]¶
Generate a list of `OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
- Parameters:
command (GenerateOrderStatusReports) – The command for generating the reports.
- Return type:
list[OrderStatusReport]
- async generate_order_status_report(command: GenerateOrderStatusReport) OrderStatusReport | None¶
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns
None.- Parameters:
command (GenerateOrderStatusReport) – The command to generate the report.
- Return type:
OrderStatusReport or
None- Raises:
ValueError – If both the client_order_id and venue_order_id are
None.
- async generate_fill_reports(command: GenerateFillReports) list[FillReport]¶
Generate a list of `FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
- Parameters:
command (GenerateFillReports) – The command for generating the reports.
- Return type:
list[FillReport]
- async generate_position_status_reports(command: GeneratePositionStatusReports) list[PositionStatusReport]¶
Generate a list of `PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
- Parameters:
command (GeneratePositionStatusReports) – The command for generating the position status reports.
- Return type:
list[PositionStatusReport]
- account_id¶
The clients account ID.
- Returns:
AccountId or
None
- account_type¶
The clients account type.
- Returns:
AccountType
- base_currency¶
The clients account base currency (None for multi-currency accounts).
- Returns:
Currency or
None
- batch_cancel_orders(self, BatchCancelOrders command) void¶
Batch cancel orders for the instrument ID contained in the given command.
- Parameters:
command (BatchCancelOrders) – The command to execute.
- cancel_all_orders(self, CancelAllOrders command) void¶
Cancel all orders for the instrument ID contained in the given command.
- Parameters:
command (CancelAllOrders) – The command to execute.
- cancel_order(self, CancelOrder command) void¶
Cancel the order with the client order ID contained in the given command.
- Parameters:
command (CancelOrder) – The command to execute.
- async cancel_pending_tasks(timeout_secs: float = 5.0) None¶
Cancel all pending tasks and await their cancellation.
- Parameters:
timeout_secs (float, default 5.0) – The timeout in seconds to wait for tasks to cancel.
- connect() None¶
Connect the client.
- create_task(coro: Coroutine, log_msg: str | None = None, actions: Callable | None = None, success_msg: str | None = None, success_color: LogColor = <LogColor.NORMAL: 0>) Task¶
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
coro (Coroutine) – The coroutine to run.
log_msg (str, optional) – The log message for the task.
actions (Callable, optional) – The actions callback to run when the coroutine is done.
success_msg (str, optional) – The log message to write on actions success.
success_color (str, default
NORMAL) – The log message color for actions success.
- Return type:
asyncio.Task
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- disconnect() None¶
Disconnect the client.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None) void¶
Generate an AccountState event and publish on the message bus.
- Parameters:
balances (list[AccountBalance]) – The account balances.
margins (list[MarginBalance]) – The margin balances.
reported (bool) – If the balances are reported directly from the exchange.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
info (dict [str, object]) – The additional implementation specific account information.
- async generate_mass_status(lookback_mins: int | None = None) ExecutionMassStatus | None¶
Generate an ExecutionMassStatus report.
- Parameters:
lookback_mins (int, optional) – The maximum lookback for querying closed orders, trades and positions.
- Return type:
ExecutionMassStatus or
None
- generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderAccepted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.
- generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order cancel rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
- generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderCanceled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.
- generate_order_denied(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderDenied event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
reason (str) – The order denied reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order denied event occurred.
- generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderExpired event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.
- generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event, dict info=None) void¶
Generate an OrderFilled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
trade_id (TradeId) – The trade ID.
venue_position_id (PositionId or
None) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNoneand the execution engine OMS will handle position ID resolution.order_side (OrderSide {
BUY,SELL}) – The execution order side.order_type (OrderType) – The execution order type.
last_qty (Quantity) – The fill quantity for this execution.
last_px (Price) – The fill price for this execution (not average price).
quote_currency (Currency) – The currency of the price.
commission (Money) – The fill commission.
liquidity_side (LiquiditySide {
NO_LIQUIDITY_SIDE,MAKER,TAKER}) – The execution liquidity side.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.
info (dict[str, object], optional) – The additional fill information.
- generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order update rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.
- generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event, bool due_post_only=False) void¶
Generate an OrderRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
reason (datetime) – The order rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.
due_post_only (bool, default False) – If the order was rejected because it was post-only and would execute immediately as a taker.
- generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) void¶
Generate an OrderSubmitted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.
- generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderTriggered event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.
- generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False) void¶
Generate an OrderUpdated event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
quantity (Quantity) – The orders current quantity.
price (Price) – The orders current price.
trigger_price (Price or
None) – The orders current trigger price.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update event occurred.
venue_order_id_modified (bool) – If the ID was modified for this event.
- get_account(self) Account¶
Return the account for the client (if registered).
- Return type:
Account or
None
- id¶
The components ID.
- Returns:
ComponentId
- is_connected¶
If the client is connected.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- modify_order(self, ModifyOrder command) void¶
Modify the order with parameters contained in the command.
- Parameters:
command (ModifyOrder) – The command to execute.
- oms_type¶
The venues order management system type.
- Returns:
OmsType
- query_account(self, QueryAccount command) void¶
Query the account specified by the command which will generate an AccountState event.
- Parameters:
command (QueryAccount) – The command to execute.
- query_order(self, QueryOrder command) void¶
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
- Parameters:
command (QueryOrder) – The command to execute.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- resume(self) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- async run_after_delay(delay: float, coro: Coroutine) None¶
Run the given coroutine after a delay.
- Parameters:
delay (float) – The delay (seconds) before running the coroutine.
coro (Coroutine) – The coroutine to run after the initial delay.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- submit_order(self, SubmitOrder command) void¶
Submit the order contained in the given command for execution.
- Parameters:
command (SubmitOrder) – The command to execute.
- submit_order_list(self, SubmitOrderList command) void¶
Submit the order list contained in the given command for execution.
- Parameters:
command (SubmitOrderList) – The command to execute.
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- venue¶
The clients venue ID (if not a routing client).
- Returns:
Venue or
None