Skip to content
All library documents

Polymarket Trading Integration: Wallets, Orders, and Data Limits

Article NautilusTrader

Summary

This technical guide explains how NautilusTrader connects to Polymarket’s central limit order book for binary outcome tokens. It outlines market data and execution components, wallet signature types, pUSD collateral, allowance setup, session keys, and Deposit Wallet position operations. Its operational guidance distinguishes direct EOA approvals from smart wallet approval flows and describes refreshing and checking allowance data before relying on it.

The guide also documents practical data and lifecycle limits: the condition feed has an approximate three-year retention horizon, pagination can cap returned history, and end-only trade queries may require traversing many newer pages. Cached instruments are retired after the venue confirms closure, while scheduled end dates alone do not establish that trading has stopped. These details help inform integration and backtest design, but the document is adapter documentation rather than a trading strategy or evidence of market edge; feed retention and venue behavior constrain what can be observed.

Key ideas

  • Polymarket outcome tokens are represented as binary option instruments, with pUSD used as collateral.
  • Wallet signature type determines the account setup and approval process.
  • Allowance evidence should be decoded strictly before it is used to establish approval status.
  • Trade history is constrained by pagination and the venue’s approximate three-year retention window.
  • A scheduled market end date does not by itself confirm that trading has stopped.

Tags

Full text
# Polymarket


# Polymarket

Founded in 2020, Polymarket is a decentralized prediction market platform where traders speculate
on event outcomes by buying and selling outcome tokens.

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

The adapter is implemented in Rust and exposed to Python at `nautilus_trader.adapters.polymarket`. Thus, data,
execution, signing, and WebSocket operations have the same behavior from Rust and Python.

The adapter handles order preparation and signing for several wallet configurations. This guide
covers market data, trade execution, session key administration, and Deposit Wallet position operations.

The adapter supports market data and resolution for Conditional Tokens Framework (CTF) markets with
protocol `v1` and Protocol V2 markets with protocol `v2`. Execution and account reconciliation support both
protocols. Deposit Wallet split, merge, and redeem support both protocols. Market protocol is separate
from CLOB service version `2` and the `CTFExchangeV2` signed order structure.

The market's explicit `version` selects `clobTokenIds` (JSON text) for `v1` or `positionIds` (an array of
decimal strings) for `v2`, even when both fields exist. Instrument IDs use
`<condition_id>-<selected_id>.POLYMARKET`. Missing or unknown versions are unsupported: providers skip
them, loaders reject them, and auto-load does not retry them while [waiting for CLOB metadata](#markets-awaiting-clob-metadata). See the
[Protocol V2 migration guide](https://docs.polymarket.com/migrate/polymarket-v2/api-integrations).

Order signatures and locally derived order IDs use the same validated exchange and domain:

| Market protocol | Exchange              | EIP-712 domain version |
| --------------- | --------------------- | ---------------------- |
| `v1`, standard  | CTF Exchange          | `"2"`                  |
| `v1`, neg-risk  | Neg Risk CTF Exchange | `"2"`                  |
| `v2`, either    | `ExchangeV3`          | `"3"`                  |

This selection also applies to Deposit Wallet owner and session signatures. The signed order fields,
CLOB authentication, fixed Nautilus builder attribution, and zero builder fees stay the same.
Combo products remain unsupported for execution and account reports.

## Installation

The Python package includes the Polymarket adapter. No adapter-specific extra is required.

To install the latest pre-release build:

```bash
uv pip install --pre nautilus_trader
```

To build the Python package from source, run from the repository root:

```bash
make build-debug
```

For development wheels and source-build prerequisites, see the
[installation guide](../getting_started/installation.md).

## Setup

For public market data, start with the [data tester](https://github.com/nautechsystems/nautilus_trader/blob/develop/examples/live/polymarket/data_tester.py).
CLOB trading credentials are required only for execution and PolyBolt reference prices.

Before enabling execution:

1. Identify your [wallet type](#signature-types). Set `signature_type` explicitly for a smart wallet
   and use its address as `funder`. For EOA trading, the funder must equal the signing address.
1. Create [CLOB credentials](#clob-credentials) for the signing key. Relayer and Builder keys serve
   different APIs and do not replace the CLOB key, secret, and passphrase.
1. Check the funding wallet's pUSD balance and [trading approvals](#wallets-and-accounts).
1. Put the intended instrument IDs in `load_ids` and share the provider config between data and
   execution clients. Discovery slugs alone do not [scope reconciliation](#instrument-provider-options).
1. Set both the disconnection timeout and post-stop delay at [30 seconds](#orders-capability).
   Leave [order-safety heartbeats](#order-safety-heartbeats) disabled unless the process owns all
   orders under dedicated CLOB credentials.
1. Run an execution tester in dry run first. The maintained execution examples default to dry run
   and retain risk checks. Set `DRY_RUN` to `False` in Python or `false` in Rust only when you intend
   to place real orders.

## Examples

The maintained examples are available in
[`crates/adapters/polymarket/examples`](https://github.com/nautechsystems/nautilus_trader/tree/develop/crates/adapters/polymarket/examples)
for Rust. For Python, use the Rust-native [data tester](https://github.com/nautechsystems/nautilus_trader/blob/develop/examples/live/polymarket/data_tester.py),
[execution tester](https://github.com/nautechsystems/nautilus_trader/blob/develop/examples/live/polymarket/exec_tester.py),
or [Up/Down smoke tester](https://github.com/nautechsystems/nautilus_trader/blob/develop/examples/live/polymarket/updown_smoke_tester.py).
The exec tester configurations apply the
[close precision](#exec-tester-close-residuals) needed for Polymarket market SELL orders.

## Binary options

A [binary option](https://en.wikipedia.org/wiki/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. NautilusTrader represents Polymarket outcome tokens
as `BinaryOption` instruments.

Polymarket uses [pUSD](#pusd) as the collateral token for trading.

## Polymarket documentation

Use these Polymarket resources:

- [Polymarket Learn](https://learn.polymarket.com/): User guides to the platform.
- [Polymarket CLOB API](https://docs.polymarket.com/getting-started/api): Technical
  documentation for developers interacting with the Polymarket CLOB API.

## Overview

Use these Rust components together or separately for live market data and trade execution:

- `PolymarketWebSocketClient`: Low-level WebSocket API connectivity built on the Nautilus Rust
  `WebSocketClient`.
- `PolymarketInstrumentProvider`: Parsing and loading of `BinaryOption` instruments.
- `PolymarketDataClient`: A market data feed manager.
- `PolymarketExecutionClient`: A trade execution gateway.
- `PolymarketDataClientFactory`: Factory for Polymarket data clients (used by the live node
  builder).
- `PolymarketExecutionClientFactory`: Factory for Polymarket execution clients (used by the live
  node builder).
- `PolymarketPositionClient`: CTF and V2 [position operations](#position-operations),
  plus [V2 trading approval submissions](#setting-smart-wallet-allowances) subject to Relayer policy.
- `PolymarketSessionKeyClient`: Owner-operated session authorization, listing, and revocation.

:::note
Python users configure live nodes through the exported configuration and factory classes, and call
position operations through `PolymarketPositionClient` and session administration through
`PolymarketSessionKeyClient`. The direct WebSocket, provider, data client, and execution client types
are Rust-only implementation components.
:::

## pUSD

**pUSD** is the collateral token used for trading on Polymarket. It is a standard ERC-20 token on
Polygon, backed by USDC.

The proxy contract address is
[0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB](https://polygonscan.com/address/0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB)
on Polygon. Direct on-chain funding wraps Polygon USDC.e (bridged USDC) into pUSD
through the [CollateralOnramp](https://docs.polymarket.com/resources/contracts).
The Bridge API can also deposit supported assets from other chains and credit pUSD
after conversion.

## Wallets and accounts

To trade on Polymarket via NautilusTrader, use a Polygon-compatible wallet, such as MetaMask.

### Signature types

Polymarket supports multiple signature types for order signing and verification:

| Signature type | Wallet type                    | Description                                                               | Use case                                                                                       |
| -------------- | ------------------------------ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `0`            | EOA (externally owned account) | Standard EIP-712 signatures from wallets with direct private key control. | **Adapter default.** Allowlisted EOA trading where the funder and signer are the same address. |
| `1`            | Proxy Wallet                   | Legacy smart contract wallet created through email or social login.       | Requires the Proxy Wallet `funder` address.                                                    |
| `2`            | Safe Wallet                    | Legacy Gnosis Safe wallet created with an external browser wallet.        | Requires the Safe Wallet `funder` address.                                                     |
| `3`            | Deposit Wallet                 | ERC-1271 smart wallet used for new Polymarket account wallets.            | Requires the Deposit Wallet `funder`; API credentials stay bound to the signer.                |

:::info
Polymarket uses Deposit Wallets for account wallets deployed on or after May 4, 2026. Direct EOA
trading requires an allowlisted EOA. See the Polymarket
[wallet and authentication guide](https://docs.polymarket.com/trading/wallets-auth) for the account
types and setup flows.
:::

NautilusTrader defaults to signature type 0 (EOA). Set `signature_type` to use another supported
wallet type. Client construction rejects malformed funder addresses, EOA funders that differ from
the signing address, and smart-wallet funders that are absent or equal to the signing address.

Environment variables supply a single wallet address per trader instance. To use multiple wallets,
configure separate execution client instances.

Fund your wallet with pUSD before submitting orders. An unfunded wallet produces the
"not enough balance or allowance" API error.

### Setting EOA allowances

Without arguments, the allowance command submits CTF approvals from the EOA signer. Use this mode
only when the funding wallet is the signer (`PolymarketSignatureType::Eoa`). Fund the EOA with POL for gas, set
`POLYMARKET_PK`, and run:

```bash
cargo run -p nautilus-polymarket --features allowances --bin polymarket-set-allowances
```

The command grants maximum pUSD and CTF approvals to the CTF Exchange, Neg Risk CTF Exchange, and
`NegRiskCtfCollateralAdapter`. It uses `https://polygon.drpc.org` by default. Set `POLYGON_RPC_URL` to use
another Polygon RPC endpoint. Run it again if Polymarket changes the required contracts.

The command grants approvals only. It does not revoke approvals for contracts that are no longer targets.
Treat revocation as a separate on-chain operation. Before submitting it, confirm that no remaining redemption
or settlement flow needs the legacy approval.

### Setting smart-wallet allowances

Do not use the command without arguments for a smart-wallet funder: it approves the EOA's assets.
Proxy and Safe Wallets require their wallet-specific SDK approval payloads.

Use Polymarket's [wallet and authentication flow](https://docs.polymarket.com/trading/wallets-auth)
to submit the approvals from the account wallet. Deposit Wallet approvals use an ordered `WALLET`
batch authorized by the signer and submitted through the Relayer.

V2 trading requires an `ExchangeV3` pUSD allowance covering BUY spend plus fees and `PositionManager`
operator permission for SELL. CTF approvals do not grant V2 permissions.

:::warning
The Relayer requires unlimited ExchangeV3 approvals and rejects the adapter's bounded ExchangeV3
approval requests with HTTP 400. Deposit Wallet V2 trading therefore relies on existing approvals,
such as those granted through Polymarket's wallet flow. The adapter does not fall back to an unlimited approval.

A rejected submission blocks further position operations for that wallet in the same process, even
if the client is recreated. Follow [submission recovery](#recover-an-unknown-submission) before
restarting; a restart does not cancel a signed batch.
:::

The allowance command accepts an explicit pUSD limit:

```bash
cargo run -p nautilus-polymarket --features allowances --bin polymarket-set-allowances -- --v2-pusd-limit 5
```

With `POLYMARKET_FUNDER` different from the signer address, this mode attempts submission from a verified Deposit
Wallet through the Relayer and requires the [Relayer credentials](#relayer-credentials). Wallet
verification refuses Safe and Proxy funders. Otherwise, it submits from the EOA signer.
Callers can also use `PolymarketPositionClient::approve_v2_trading` in Rust or
`PolymarketPositionClient.approve_v2_trading` in Python; both use the same blocked Deposit Wallet route.
The explicit limit is in pUSD and includes fees. These approvals grant neither `Router` nor
`AutoRedeemer` permission.
BUY fills and fees consume this allowance. Calling approval again replaces the remaining limit;
it does not add to it. The adapter sizes market BUYs against the pUSD balance, not the allowance.
Refresh and check the remaining allowance before trading; an exhausted limit causes venue rejection.
[AutoRedeemer permission](https://docs.polymarket.com/migrate/polymarket-v2/contract-integrations#enable-v2-automatic-redemption)
is optional, does not schedule redemption, and is not required to trade.

### Refreshing and verifying allowances

After the approval transaction confirms, refresh the CLOB cache. Rust callers can use
`PolymarketClobHttpClient::update_balance_allowance` with `AssetType::Collateral` for pUSD. Use
`AssetType::Conditional` with a CTF token ID or `AssetType::ConditionalV2` with a V2 position ID.
The V2 wire value is exactly `CONDITIONAL-V2`. Every request also needs the maker's signature type.
The authenticated request maps to
`GET /balance-allowance/update`. Use `PolymarketSignatureType::Poly1271` for a Deposit Wallet.

The balance-allowance endpoint has two decoding paths:

| Path                                              | Used for                                             | Allowance handling                                                                                                                                                             | Meaning of success                                                                 |
| ------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| `PolymarketClobHttpClient::get_balance_allowance` | Reading spender allowance evidence.                  | Requires the plural `allowances` map; rejects a missing map, a non-null legacy singular value, malformed or non-canonical keys, and semantic duplicates such as case variants. | Balance plus an unambiguous map; required targets and amounts still need checking. |
| Internal balance-only projection                  | Account state refresh and market-buy fee adjustment. | Ignores allowance fields; its return type cannot expose or grant approval authority.                                                                                           | Balance only; required CLOB spender approvals remain unproven.                     |

Use the strict path whenever a decision depends on allowance evidence so ambiguous wire data cannot
become approval authority. After refreshing, read with the same asset ID and signature type, and check
the selected exchange's allowance entry. Rust callers can use the public `EXCHANGE_V3`, `CTF_EXCHANGE`,
and `NEG_RISK_CTF_EXCHANGE` constants in `signing::eip712` as spender addresses.
API authentication identifies the signer; the balance and
permissions belong to the maker holding the assets.

### Account balances

#### Balance calculation

Refreshes use the venue-reported pUSD total and calculate locks from local state:

- **Reservations**: Open BUY orders for this account, valued at cached limit prices and remaining quantities.
  Excludes submitted orders awaiting acceptance and orders absent from the execution cache.
- **Unsettled spend**: Known BUY fill notional and commission that the venue total may still include.

SELL orders reserve outcome tokens without locking pUSD. Locked collateral is capped at the total;
free balance equals total minus locked, following the [balance model](../concepts/accounting.md#balance-model).

#### Unsettled BUY spend

Each refresh deducts uncovered BUY spend from free balance.

The **snapshot** is a reference balance and time, set by the first applied refresh. It resets to the venue
total while no BUY spend is pending and can adjust when fills release.

Locks release through either path:

- **Confirmed settlement**: At refresh start, the adapter records confirmed pending fills. If any exist, it
  updates the CLOB balance cache, then reads the venue total. After both requests succeed, it releases only
  recorded fills that remain confirmed, even if credits hide their debit. Stale responses and failed
  refreshes leave locks unchanged.
- **Balance decrease**: Other pending spend releases together once the total's drop from the snapshot covers
  its combined amount. Until then, only uncovered spend stays locked. Confirmed releases are subtracted from
  the observed decrease; the remainder reduces other locks, including on later unchanged refreshes.

**Voids**:

- A void immediately removes its fill's locked spend. Cumulative revisions remove only the increase.
- The voided amount still counts toward the decrease needed to release other open spend. Voids of never-locked
  fills do not raise this threshold.
- When no open spend remains, the next refresh releases the voided amount and updates the snapshot.

**Excluded fills**: No lock applies to:

- Fills first applied from terminal REST evidence, including confirmed fill reports: this evidence is
  admitted only after confirmation.
- Reconciled fills more than 15 seconds older than the snapshot, or received before any snapshot.
- Fills that reconciliation infers from an order or position report: their generated trade IDs never match a
  venue confirmation.

#### Refresh timing

- **Startup**: At connect, the adapter seeds reservations from the execution cache. The initial refresh
  precedes startup reconciliation; discovered orders affect the next refresh.
- **Order events**: Core order events, including reconciled events, update reservations and unsettled spend.
  Account balances change only on refresh, not on each event.
- **Triggers**: Refreshes run at connect, on account queries, after finalized trade updates or user
  `auto_redeem` events, and on user WebSocket reconnect. They do not request open orders.
- **Reconnect and reset**: Transport reconnect preserves unsettled BUY spend; reset clears it.
- **Response ordering**: The adapter discards responses superseded by a newer refresh or invalidated by an
  execution-client reconnect or reset. A user WebSocket reconnect retains in-flight refreshes;
  a newer refresh still wins.

:::warning
**These balances are estimates.** HTTP responses and order events can reflect different times.
They do not guarantee funds are reserved before submission.

Timing effects include:

- **Credits**: Collateral credits, including own SELL settlement, can hide BUY debits. Uncovered spend stays
  locked until one of the release paths above succeeds.
- **Other debits**: An unrelated debit can release spend before the fill drains.
- **Voids**: An amount that never leaves the venue total can keep its shortfall locked while other
  unsettled spend remains open.
- **REST confirmations**: A confirmation inside the drain window can report terminal REST BUY spend as free
  until a later refresh.
- **Inferred fills**: Spend from an inferred BUY fill that the venue total still includes shows as free until
  the total drains.
- **Queued fills**: A refresh applied before a queued fill is processed can leave it locked after the
  total has already drained.

The adapter does not lock matched spend from another client on the same funder, or from a fill it
has not yet received.
:::

## API keys

### CLOB credentials

The execution client requires CLOB L2 credentials. Create or derive them with Polymarket's
[API authentication flow](https://docs.polymarket.com/getting-started/api#authentication). The
adapter provides a command that reads `POLYMARKET_PK` and prints the created or derived credentials:

```bash
cargo run -p nautilus-polymarket --bin polymarket-create-api-key
```

Set the returned values as:

- `POLYMARKET_API_KEY`
- `POLYMARKET_API_SECRET`
- `POLYMARKET_PASSPHRASE`

The credentials authenticate the private-key signer, not a proxy or Deposit Wallet funder. The data
client requires them only for [PolyBolt reference-price subscriptions](#polybolt-reference-prices).

### Relayer credentials

Deposit Wallet approvals, split, merge, and redeem operations require a Relayer API key. Create one under
Settings > API Keys > Relayer API Keys, as described in
[Connect your account](https://docs.polymarket.com/trading/wallets-auth#connect-your-account), then set:

- `POLYMARKET_RELAYER_API_KEY`
- `POLYMARKET_RELAYER_SIGNER_ADDRESS`

`POLYMARKET_RELAYER_SIGNER_ADDRESS` is the signer address shown when the Relayer key is created.
The position client also reads `POLYMARKET_PK` and `POLYMARKET_FUNDER`.

### Builder credentials

Session authorization and revocation require Builder credentials approved for the session-key API.
These are separate from the Relayer API key used for position operations. Follow Polymarket's
[session-key requirements](https://docs.polymarket.com/trading/session-keys), and keep these values
in the owner's administration environment:

- `POLYMARKET_BUILDER_API_KEY`
- `POLYMARKET_BUILDER_API_SECRET`
- `POLYMARKET_BUILDER_PASSPHRASE`

### Deposit Wallet verification

Construction fails when the funder equals the signing address. Before signing, the position client:

- Checks the current and legacy Deposit Wallet addresses predicted by the canonical Polygon factory.
- Requires deployed wallet code and verifies that the signer owns the wallet.
- Reads the signed nonce from the wallet's on-chain counter.

Polygon RPC defaults to `https://polygon.drpc.org`. Pass `base_url_rpc` to the
`PolymarketPositionClient` constructor to use another trusted Polygon endpoint.

## Session keys

Session keys let a separate signer trade for a Deposit Wallet without giving the trading runtime
its owner's private key. The adapter supports CLOB-scoped authorization. See Polymarket's
[session-key documentation](https://docs.polymarket.com/trading/session-keys) for venue eligibility
and Builder approval requirements.

### Administer access

Run `PolymarketSessionKeyClient` in the **owner's administration environment**, using a single
administration process per wallet. Before authorizing a session:

- Supply the owner private key, owner CLOB credentials, Builder credentials, and Deposit Wallet address
  explicitly. The client does not read environment variables itself.
- Generate and securely store the session keypair separately. Pass only its public address to the
  authorization method.

The Python example reads credentials from the administration process's environment and passes them
into the client:

```python
import os

from nautilus_trader.adapters.polymarket import PolymarketSessionKeyClient
from nautilus_trader.adapters.polymarket import PolymarketSessionKeyClientConfig

admin = PolymarketSessionKeyClient(
    PolymarketSessionKeyClientConfig(
        private_key=os.environ["POLYMARKET_PK"],
        api_key=os.environ["POLYMARKET_API_KEY"],
        api_secret=os.environ["POLYMARKET_API_SECRET"],
        passphrase=os.environ["POLYMARKET_PASSPHRASE"],
        builder_api_key=os.environ["POLYMARKET_BUILDER_API_KEY"],
        builder_api_secret=os.environ["POLYMARKET_BUILDER_API_SECRET"],
        builder_passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"],
        funder=os.environ["POLYMARKET_FUNDER"],
    ),
)

# Use the public address derived from the separately stored session private key.
session_address = os.environ["SESSION_ADDRESS"]

# Run these calls from an async function in the administration process.
key = await admin.authorize_session_key(session_address)
keys = await admin.list_session_keys()
```

Optional configuration:

- `base_url_http` overrides the production CLOB endpoint.
- `base_url_relayer` overrides the production Relayer endpoint.
- `proxy_url` configures an HTTP or HTTPS proxy for both clients.

The Rust example provides the same authorization and listing operations:

```bash
cargo run -p nautilus-polymarket --example polymarket-session-keys -- authorize "$SESSION_ADDRESS"
cargo run -p nautilus-polymarket --example polymarket-session-keys -- list
```

Each administration method has a specific completion condition:

| Method                  | Successful return requires                                                      |
| ----------------------- | ------------------------------------------------------------------------------- |
| `authorize_session_key` | On-chain confirmation; registry matches the address, CLOB scope, and expiration |
| `list_session_keys`     | Validated active, unexpired registry entries                                    |
| `revoke_session_key`    | On-chain confirmation; key absent from the active registry                      |

#### Expiration

Authorizations expire after 4,315 hours, matching the official SDK's wire value. Polymarket describes
this period as 180 days, but its raw example and SDK use a value five hours shorter. The returned
`valid_until` is the exact expiration in Unix seconds.

#### Recover an interrupted operation

After an authorization or revocation times out, encounters a transport failure, or is cancelled,
retry with the **same operation, same address, and same client**. The client retains the signed
request and idempotency key and rejects a different mutation until the pending operation resolves.

Keep the client alive until the operation resolves: pending requests are held in memory.
Unresolved-outcome errors include the idempotency key and any known transaction ID for diagnosis.

:::warning
Signed batches have a **600-second deadline**. If an unaccepted request expires, retrying cannot
create a fresh batch, and the client remains blocked. Reconcile the registry and Relayer outcome
before creating a new client. The same reconciliation is required after a process restart.
:::

### Configure session trading

Create or derive CLOB credentials with the **session private key**, using the existing
[CLOB credential workflow](#clob-credentials). Session mode requires:

- Explicit session credentials and `funder`. It does not fall back to owner credentials from the environment.
- `PolymarketSignatureType.Poly1271`. Other wallet signature types are rejected.

:::info
Keep owner and Builder credentials outside the trading runtime.
:::

In this example, `session_private_key` is the separately stored session key, and
`session_api_key`, `session_api_secret`, and `session_passphrase` are its returned CLOB credentials:

```python
from nautilus_trader.adapters.polymarket import PolymarketExecutionClientConfig
from nautilus_trader.adapters.polymarket import PolymarketSignatureType
from nautilus_trader.adapters.polymarket import PolymarketSignerType

execution = PolymarketExecutionClientConfig(
    signer_type=PolymarketSignerType.Session,
    signature_type=PolymarketSignatureType.Poly1271,
    private_key=session_private_key,
    api_key=session_api_key,
    api_secret=session_api_secret,
    passphrase=session_passphrase,
    funder=deposit_wallet_address,
)
```

Existing configurations default to `PolymarketSignerType.Owner`.

#### Reconciliation and restarts

Orders, trades, and notifications are scoped to the session's activity. Reconciliation requires the session
API key to match order ownership. A shared wallet address alone does not establish ownership.

Session cancel-all cancels known order IDs rather than using wallet-wide market cancellation.
Mass status contains session orders and fills but omits wallet-wide positions. Direct position queries
return an error because wallet holdings cannot establish a session's position.

Configure the node accordingly:

- **Position checks**: Set `LiveExecutionEngineConfig.position_check_interval_secs=None` to disable
  periodic position checks for the node.
- **History across restarts**: Configure [cache database persistence](../concepts/cache.md#database-configuration)
  and keep `load_cache=True` to retain order and fill history.

### Revoke or rotate access

Rotate keys from the administration environment. Coordinate outstanding orders and reconciliation
before switching credentials: **a new session does not inherit visibility into an old session's orders**.

To revoke a key, use the administration client created above, from an async function:

```python
await admin.revoke_session_key(session_address)
```

Or run the Rust example:

```bash
cargo run -p nautilus-polymarket --example polymarket-session-keys -- revoke "$SESSION_ADDRESS"
```

:::warning
Expired or revoked permissions cause venue rejections. A live transport connection does not prove
that authorization remains active.
:::

## Position operations

`PolymarketPositionClient` splits pUSD into complete outcome-token sets, merges complete sets back
to pUSD, and redeems resolved CTF and V2 positions. It also exposes [V2 trading approval submissions](#setting-smart-wallet-allowances),
which Relayer policy blocks for bounded Deposit Wallet limits.
The client supports Deposit Wallet (`PolymarketSignatureType::Poly1271`) only. Safe, Proxy, and EOA paths are not available. The client does not deploy wallets, batch
unrelated calls, size a merge to `"max"`, or redeem positions automatically. Combo products are unsupported.

### Inputs and approvals

Each split, merge, or redeem call verifies the public CLOB market's explicit protocol, condition ID,
and `neg_risk` value.
CTF calls use the standard or negative-risk collateral adapter. V2 calls use
[Router and PositionManager](https://docs.polymarket.com/migrate/polymarket-v2/contract-integrations)
with verified binary or negative-risk position IDs. Callers do not supply contract addresses.

- **Condition IDs**: Both protocols require a `0x` prefix. CTF requires a 32-byte value. V2 accepts native
  31-byte IDs or 32-byte IDs with a zero final byte. Nonzero padding is rejected before narrowing.
- **Split and merge amounts**: Positive pUSD decimals exactly representable at six decimal places, with no
  rounding. Amounts use pUSD units, never base units. `"max"` is not accepted.
- **CTF redemption**: `redeem_positions(condition_id)` redeems both binary index sets `[1, 2]` without
  an amount argument.
- **V2 redemption**: `redeem_position(condition_id, outcome_index, amount)` redeems an explicit positive
  share amount exactly representable at six decimal places, with no rounding. The index is the position
  ID's final byte (`0` or `1`), independent of CLOB token-array order. The CTF redeem-both call refuses V2.

`redeem_positions_batch(condition_ids)` prepares a nonempty list of CTF conditions and attempts one
ordered wallet submission. Standard and negative-risk conditions can share a batch. Order and duplicates
are preserved; callers choose the batch size and deduplication policy. No supported numerical maximum is
established. A preparation error submits nothing and logs the failing condition and zero-based index at
WARN, while returning the original error. A V2 condition prevents the entire submission.
Replace the illustrative condition IDs below with actual CTF market IDs.

```rust tab="Rust"
let condition_a = "0x1111111111111111111111111111111111111111111111111111111111111111";
let condition_b = "0x2222222222222222222222222222222222222222222222222222222222222222";
let transaction = client.redeem_positions_batch(&[condition_a, condition_b]).await?;
let outcome = transaction.wait().await?;
```

```python tab="Python"
condition_a = "0x" + "11" * 32
condition_b = "0x" + "22" * 32
transaction = await client.redeem_positions_batch([condition_a, condition_b])
outcome = await transaction.wait()
```

The handle reports one Relayer outcome for the batch. Subcall rollback depends on the effective wallet
implementation; verify its behavior and Relayer acceptance before relying on a batch size or atomicity.
Existing [submission coordination](#submission-coordination) applies, including blockage after rejected
or uncertain submissions. Reducing the batch size does not make resubmission safe. Retain all per-call
intent records for the wallet/nonce when [recovering a submission](#recover-an-unknown-submission);
these logs are not a durable journal.

Split spends the specified pUSD amount and creates that amount of each outcome. Merge consumes the specified
amount of each outcome and returns pUSD. V2 redemption burns only the selected outcome amount and returns
its PositionManager payout. A valid zero losing payout is redeemable; a reverted or unavailable payout
read prevents submission. For negative-risk markets, the payout read can reflect a derived result without
an individual condition-resolution event. Refresh wallet balances after confirmation.

**Approvals are not submitted automatically.** Grant them from the Deposit Wallet before submitting:

| Operation       | CTF collateral adapter approval       | V2 Router approval                 |
| --------------- | ------------------------------------- | ---------------------------------- |
| Split           | Spend the wallet's pUSD.              | Spend the wallet's pUSD.           |
| Merge or redeem | Act as a Conditional Tokens operator. | Act as a PositionManager operator. |

V2 calls check balances and Router permissions on the Deposit Wallet holding the assets before submission.
Merge checks both outcome balances. CTF and ExchangeV3 trading approvals do not authorize Router.
Router pulls inputs from the wallet and returns outputs in the same transaction; no pre-transfer is needed.

Grant Router permissions from the Deposit Wallet through the venue's
[contract integration](https://docs.polymarket.com/migrate/polymarket-v2/contract-integrations).
PositionManager operator approval covers **all V2 holdings**, without a per-position amount limit.
A pUSD approval sets the remaining Router allowance; splits consume it.

The standard collateral adapter is absent from the CTF approval plan in `polymarket-set-allowances`.
The negative-risk adapter is included. The command's default mode submits CTF approvals from the EOA;
its V2 mode requests ExchangeV3 trading permissions, not CTF or Router position-operation approvals.
Use the [wallet and authentication flow](https://docs.polymarket.com/trading/wallets-auth)
to grant CTF position-operation approvals from the Deposit Wallet.

### Submit and wait

The following example shows a split submission. Replace the illustrative condition ID with the
market's actual condition ID before running it.

```python
from decimal import Decimal

from nautilus_trader.adapters.polymarket import PolymarketPositionClient

condition_id = "0x" + "11" * 32
client = PolymarketPositionClient()
transaction = await client.split_position(condition_id, Decimal("1"))
outcome = await transaction.wait()
```

`split_position` and `merge_positions` take a condition ID and a positive pUSD `Decimal` for either protocol.
To redeem V2 shares, set `v2_condition_id` to the market's actual condition ID:

```rust tab="Rust"
use rust_decimal::Decimal;

let transaction = client.redeem_position(v2_condition_id, 1, Decimal::new(25, 2)).await?;
let outcome = transaction.wait().await?;
```

```python tab="Python"
transaction = await client.redeem_position(v2_condition_id, 1, Decimal("0.25"))
outcome = await transaction.wait()
```

`approve_v2_trading` takes an explicit positive pUSD
limit, which the Relayer rejects under the [approval policy](#setting-smart-wallet-allowances).
After a successful Relayer submission, each method returns a `PolymarketPositionTransaction`.
Call `wait()` once to poll until a `PolymarketPositionOutcome` is available.
A second `wait()` on the same Python handle raises. The
handle retains its `transaction_id` after waiting starts, including after cancellation or an error.

### Outcomes and errors

| `PolymarketPositionOutcome.status` | Meaning                             |
| ---------------------------------- | ----------------------------------- |
| `confirmed`                        | Relayer reported `STATE_CONFIRMED`. |
| `failed`                           | Relayer reported `STATE_FAILED`.    |
| `invalid`                          | Relayer reported `STATE_INVALID`.   |

Every outcome exposes `transaction_id`. Confirmed and failed outcomes expose `transaction_hash` when the
Relayer supplies one. Invalid outcomes always return `None`. Failed and invalid outcomes also expose
`error_msg` when the Relayer supplies one.

#### Submit errors

An HTTP rejection raises before a transaction handle exists. A timed-out submit or a success response with no
`transaction_id` also raises. The on-chain outcome is unknown.

The client **does not retry submissions**.

#### Wait timeout

The default is 120 seconds, checked between polling requests. An in-flight request or polling delay can extend
the elapsed time. A timeout raises an error naming the Relayer transaction ID. The terminal state remains
unknown. Python does not expose the Rust wait-timeout or poll-interval setters.

#### Response validation

Relayer redirects are rejected, and polling rejects a response whose transaction ID differs from the
submitted ID.

### Submission coordination

Clients in the same process share submission state for each wallet. A later operation requires a matching
terminal Relayer result and an advanced wallet nonce. A failed or invalid operation that does not advance
the nonce remains blocked.

After signing, the client records a reservation before sending the batch. An HTTP rejection, timeout,
cancellation, or response without a transaction ID then blocks further operations for that wallet, even
if the client is recreated. Failures before that reservation, such as invalid amounts or failed wallet
verification, do not create a new block. An HTTP status alone does not prove that a signed batch cannot
execute.

:::warning
Do not restart and blindly retry an unknown submission. A process restart clears local submission state but
does not cancel a signed transaction. Use a single submitting process per wallet. Coordination does not extend
across processes or external wallet tools.
:::

### Recover an unknown submission

#### Retain the submission record

Enable and retain INFO logs before submitting position operations. Before each submit request, the
client emits a `Deposit Wallet submission` record containing:

- Wallet address, reserved nonce, and signed deadline (Unix seconds).
- Operation, target contract, and value.
- Unsigned calldata identifying the condition and, for split, merge, or V2 redemption, the amount.
  V2 redemption also includes the outcome index.

The record excludes signatures and credentials, but contains trading intent. Restrict access to retained logs.
Keep the transaction ID from the returned handle when available.

:::warning
Logging is not a durable transaction journal. Disabled logging or a process crash can leave no
retained record, preventing safe recovery without further evidence.
:::

#### Reconcile before retrying

1. **Stop submissions.** Include other processes and external wallet tools using the wallet.
1. **Establish whether the operation executed.** Find the submission record and any Relayer
   transaction ID. Match the intended wallet, target, and calldata against finalized on-chain
   transaction receipts and effects. A successful HTTP response, a Relayer failure, or an advanced
   nonce alone does not establish whether the intended operation executed. If it executed, do not
   repeat it.
1. **Keep the wallet blocked while execution remains unknown.** To reconcile by expiry, perform all
   the [expiry checks](#expiry-checks) below. If the nonce advanced, inspect the transaction that
   consumed it instead of assuming failure.
1. **Prove that retrying is safe before restarting.** Establish that the intended operation did not execute.
   Also establish that the original signed batch can no longer execute. If the record is missing, the RPC
   cannot provide consistent finalized state, or contract behavior is unverified, resolve the uncertainty with
   Polymarket before retrying.

#### Expiry checks

The signed deadline is 1,800 seconds after signing by default. Rust callers can change this with
`with_deadline_secs`. Longer deadlines delay expiry-based recovery. A `wait()` timeout does not shorten the
signed deadline or cancel the batch.

First verify that the deployed wallet contract enforces the signed deadline and consumes its nonce
when a batch executes. Then read the wallet's `nonce()` with `eth_call` at a finalized Polygon block
and obtain that same block's timestamp. Require both:

- The nonce is unchanged from the reserved nonce.
- The block timestamp is strictly after the signed deadline.

Elapsed local time is insufficient. An advanced nonce requires inspection of the transaction that consumed it.
It does not establish failure.

The client does not perform these recovery checks or release a reservation automatically. Consult
the [Polymarket contract registry](https://docs.polymarket.com/resources/contracts) when identifying
the deployed contracts and the [JSON-RPC reference](https://ethereum.org/en/developers/docs/apis/json-rpc/)
for block-specific calls.

## Configuration

Configure signing and authentication through these parameters or their environment-variable fallbacks:

| Parameter     | Environment variable    | Purpose                                                      |
| ------------- | ----------------------- | ------------------------------------------------------------ |
| `private_key` | `POLYMARKET_PK`         | Wallet key used to sign orders according to `signature_type` |
| `funder`      | `POLYMARKET_FUNDER`     | pUSD funding wallet address                                  |
| `api_key`     | `POLYMARKET_API_KEY`    | CLOB L2 API key                                              |
| `api_secret`  | `POLYMARKET_API_SECRET` | CLOB L2 API secret                                           |
| `passphrase`  | `POLYMARKET_PASSPHRASE` | CLOB L2 API passphrase                                       |

In owner mode, omit a parameter or pass `None` to read its environment variable. An explicitly supplied
empty or whitespace-only value fails configuration validation; it never selects an environment fallback.
Nonblank overrides apply per field, so keep the private key and CLOB credentials matched. Session
mode requires explicit credentials and a funder. CLOB L2 credentials authenticate the private-key signer. For
`POLY_1271`, the Deposit Wallet remains the `funder`. It is not the L2 authentication address.

:::tip
Use environment variables to supply credentials without embedding them in client configuration code.
:::

Instrument loading also has two common controls:

- `auto_load_missing_instruments` (default `True`): Subscribe and request commands for uncached
  instruments trigger an ad-hoc Gamma API load. When disabled, subscribing to an uncached instrument
  returns an error. See [Runtime instrument loading](#runtime-instrument-loading).
- `auto_load_debounce_ms` (default `100`): Window in milliseconds for coalescing concurrent auto-load
  requests into a single batched Gamma call.

### Troubleshooting setup

| Symptom                        | Check                                      | Action                                                                                                   |
| ------------------------------ | ------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| Blank-override error           | Explicit config value                      | Omit the field or pass `None` for environment fallback.                                                  |
| Authentication rejection       | CLOB key, secret, passphrase, and signer   | Use the three credentials created for the signing key.                                                   |
| Signature rejection            | Wallet type and funder                     | Match `signature_type` to the funding wallet; use the signer address for EOA mode.                       |
| Balance or allowance rejection | Funding wallet and approvals               | Check pUSD, outcome-token balances for sells, and the required spender approvals.                        |
| Empty discovery                | Instrument IDs, slugs, and market protocol | Check that IDs and slugs identify existing protocol `v1` or `v2` markets.                                |
| Unmapped reconciliation record | Execution provider scope                   | Set `load_ids` for the instruments this node should reconcile and share the config with the data client. |

See Polymarket's [error reference](https://docs.polymarket.com/resources/error-codes) for venue errors.

## Data capability

Polymarket supports live `L2_MBP` order book deltas, quotes, trades, and resolution
`InstrumentStatus`/`InstrumentClose` events. Instrument definitions are published by bootstrap,
configured refreshes, on-demand loading, single-instrument requests, new-market discovery, and
tick-size changes.

Implemented data hooks accept compatible instrument lists for subscribe and unsubscribe:

- Intent and reconcile operations run per member.
- Uncached IDs enter the debounced Gamma loader.
- The WebSocket pool sends per token; list delivery does not reduce venue messages.

## Orders capability

Polymarket supports the order types and instructions below.

:::tip
For Polymarket live execution, set both the disconnection timeout and post-stop delay to 30
seconds with `with_timeout_disconnection_secs(30)` and `with_delay_post_stop_secs(30)`. The delay
allows residual order and cancellation events to arrive before disconnection. Execution disconnect
finishes inside that timeout and does not wait out the HTTP timeout for an in-flight command.
:::

A cancel that is still in flight when disconnect finishes leaves the order `PENDING_CANCEL`. The
adapter emits neither `OrderCanceled` nor `OrderCancelRejected`. The venue may or may not have
applied the cancel. Startup reconciliation on the next run resolves it. A strategy cancel does not,
because the order is already pending cancel. Other in-flight submit and modify commands stop on the
same bound, and an unconfirmed one stays unresolved.

### Order types

| Order type             | Binary options | Notes                                                                     |
| ---------------------- | -------------- | ------------------------------------------------------------------------- |
| `MARKET`               | ✓              | **BUY orders require quote quantity**, SELL orders require base quantity. |
| `LIMIT`                | ✓              | BUY orders accept base or quote quantity; SELL orders require base.       |
| `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, side, and
`quote_quantity` setting:

- **Limit orders with `quote_quantity=False`** interpret `quantity` as the number of conditional
  tokens (base units).
- **Limit BUY orders with `quote_quantity=True`** interpret `quantity` as pUSD collateral.
- **Market BUY** orders interpret `quantity` as quote notional in **pUSD**.
- **Market SELL** orders use base-unit quantities.

Quote-sized limit SELL orders are not supported. The adapter denies them before submission. It also
denies any limit order whose base or quote quantity truncates to zero at the two-decimal signing
boundary.

#### Limit BUY example

For limit BUY orders with `quote_quantity=True`:

- The adapter truncates collateral to cents, signs it as the maker amount, and derives shares at
  the market's amount precision.
- It updates the local order to the signed share quantity before processing the venue response.
- The signed amounts must preserve the limit price exactly. Otherwise, the adapter rejects the
  order before HTTP. For example, 10.00 pUSD at 0.33 is not representable, while 9.90 pUSD at
  0.33 produces exactly 30 shares.

To cap a limit BUY by collateral, set `quote_quantity=True`:

```python
# Limit BUY with quote quantity (spend $10 pUSD at a limit price of 0.50)
order = strategy.order_factory.limit(
    instrument_id=instrument_id,
    order_side=OrderSide.BUY,
    quantity=instrument.make_qty(10.0),
    price=instrument.make_price(0.50),
    time_in_force=TimeInForce.GTC,
    quote_quantity=True,
)
strategy.submit_order(order)
```

#### Market BUY example

For market BUY orders, **quote quantity is required**: set `quote_quantity=True`. The adapter converts
the quote amount (pUSD) to the signed base-unit share amount before posting to the CLOB. The
Polymarket execution client denies base-denominated market buys to
prevent unintended fills. A market BUY submitted with a base-denominated quantity can execute far
more size than intended.

```python
# Market BUY with quote quantity (spend $10 pUSD)
order = strategy.order_factory.market(
    instrument_id=instrument_id,
    order_side=OrderSide.BUY,
    quantity=instrument.make_qty(10.0),
    time_in_force=TimeInForce.IOC,  # Maps to Polymarket FAK
    quote_quantity=True,  # Interpret as pUSD notional
)
strategy.submit_order(order)
```

### Execution instructions

| Instruction   | Binary options | Notes                                                |
| ------------- | -------------- | ---------------------------------------------------- |
| `post_only`   | ✓              | Supported for limit orders with `GTC` or `GTD` only. |
| `reduce_only` | -              | *Not supported by Polymarket*.                       |

### Time-in-force options

Polymarket calls the `POST /order` field `orderType`. In NautilusTrader, this maps to
`TimeInForce`. The valid combinations depend on the Nautilus order type:

| Nautilus TIF | Polymarket `orderType` | Nautilus order scope | Notes                                                     |
| ------------ | ---------------------- | -------------------- | --------------------------------------------------------- |
| `GTC`        | `GTC`                  | `LIMIT` only         | Good-Til-Cancelled; rests on the book.                    |
| `GTD`        | `GTD`                  | `LIMIT` only         | Good-Til-Date; rests until expiration, fill, or cancel.   |
| `FOK`        | `FOK`                  | `LIMIT` or `MARKET`  | Fill the full size immediately or cancel the whole order. |
| `IOC`        | `FAK`                  | `LIMIT` or `MARKET`  | Fill available size immediately and cancel the remainder. |

Polymarket uses `FAK` (Fill-And-Kill) for the semantics NautilusTrader calls `IOC` (Immediate or Cancel).
Polymarket docs classify `FOK` and `FAK` as market order types, while `GTC` and `GTD` are limit order types.
For Nautilus `MARKET` orders, the adapter accepts only `IOC` and `FOK`. `GTC` and `GTD` are valid for resting
`LIMIT` orders only.

#### GTD expiry

Set `GTD` expiry at least three minutes after submission. The adapter denies a shorter expiry
before signing. It uses whole Unix seconds and accepts the exact three-minute boundary.

Polymarket reports both a user cancel and a GTD expiry as `CANCELED`. It expires the order one
minute before the supplied expiration, so the minimum effective lifetime is about two minutes. To
request an effective lifetime of N seconds, supply `now + 60 + N`, still subject to the
three-minute minimum.

On the user channel, a `CANCELED` event at or after that one-minute mark becomes `OrderExpired`.
An earlier cancel stays `OrderCanceled`. A REST-recovered cancel also stays `OrderCanceled`. The
open-order payload has an expiration, but no cancel time.

Leave `manage_gtd_expiry` false. The strategy timer fires at the stated expiration and submits a cancel. It
does not emit `OrderExpired`. A user-channel expiry already clears that timer.

If the expiry message was missed, the late cancel does not close the order. Reconciliation still has to. See
[GTD orders](https://docs.polymarket.com/trading/place-orders#limit-orders).

### Minimum order size

Read each market's `min_order_size` from its order book. Active markets commonly report five shares.
Marketable orders can also be rejected below **1 pUSD** in notional value with
`invalid amount for a marketable BUY order … min size: $1`.

The adapter leaves instrument
`min_quantity` unset because quote-sized BUY quantities use pUSD while base-sized orders use
shares. Submit still sends an undersized order for the venue to reject. Modify checks the cached
share minimum before and after cancellation. See [Order modification](#order-modification).

### Advanced order features

| Feature            | Binary options | Notes                                                   |
| ------------------ | -------------- | ------------------------------------------------------- |
| Order modification | ✓              | Adapter-managed cancel-replace for open `LIMIT` orders. |
| Bracket/OCO orders | -              | *Not supported by Polymarket.*                          |
| Iceberg orders     | -              | *Not supported by Polymarket.*                          |

### Order modification

Polymarket has no in-place modify endpoint. The execution client cancels the current venue order,
reconciles its final confirmed fills, and signs a replacement for the remaining quantity.

#### Replacement quantity and identity

`ModifyOrder.quantity` sets the absolute target for the logical order, not the replacement leg.
The replacement keeps the `ClientOrderId` and receives a new `VenueOrderId`.

The logical quantity uses the exact signed base quantity after venue precision normalization,
so it can be slightly lower than the requested target.

#### Size checks

Before canceling, the adapter subtracts filled quantity and quantity voided without reopening from
the target. A replacement below 0.01 shares produces `OrderModifyDenied`.

When cached instrument `info["min_order_size"]` is present, the adapter also emits `OrderModifyDenied` if:

- The value is not a positive decimal string.
- The signed replacement share quantity is below that minimum.
- The signed amounts needed for the minimum check cannot be derived.

A missing key skips the market minimum check. For a `FAK` or `FOK` BUY, the check uses shares
derived from the cent-truncated pUSD budget.

After cancellation, the adapter repeats the size checks on the remaining quantity. It uses the
market minimum captured at modify start, without a fresh order-book read.

Fills during cancellation can leave an undersized remainder. The adapter does not post it: it emits
`OrderModifyRejected`, and the order closes as canceled. A marketable replacement below 1 pUSD also
produces `OrderModifyRejected` after cancellation. These failures are rejections because the cancel leg
was already sent.

#### Ambiguous outcomes

The adapter submits no replacement unless the cancel response, canceled order state, and confirmed
trade totals agree.

- **Ambiguous cancel**: Retains the pending modification for venue reports or reconciliation.
  This includes a response that omits the target from both `canceled` and `not_canceled`.
- **Ambiguous replacement**: Stays in flight under its deterministic signed order hash. A later
  order update, fill, or reconciliation can establish it without a second `OrderAccepted`.
  Later modify and cancel commands remain blocked until then.

Replacement recovery state does not persist across an execution-client process restart.

### Batch operations

| Operation    | Binary options | Notes                                                                                                                               |
| ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Batch submit | ✓              | The adapter uses `POST /orders` for independent limit-order batches (max 15 orders per request). See [Batch submit](#batch-submit). |
| Batch modify | -              | *Not supported by Polymarket*.                                                                                                      |
| Batch cancel | ✓              | The adapter uses `DELETE /orders`. See [Batch cancel](#batch-cancel).                                                               |

#### Batch submit

`SubmitOrderList` commands are routed to Polymarket's `POST /orders` endpoint. The endpoint accepts at most 15
orders per request (`BATCH_ORDER_LIMIT`). Larger lists are split into sequential 15-order chunks.

- Only `LIMIT` orders are batched. `MARKET` orders inside the list are routed to the
  single-order path, which signs a marketable order and submits it with `FAK` or `FOK`
  based on Nautilus `time_in_force`.
- `reduce_only` orders, quote-sized SELL orders, and `post_only` with market TIF (`IOC` or `FOK`)
  are denied before submission.
- A single eligible order falls through to `POST /order` so it keeps the single-order retry semantics. The
  batch path deliberately disables retry because the venue does not expose an idempotency key.
- If the batch response omits a leg, that order stays submitted for reconciliation. The adapter
  registers the signed order's expected hash so later WebSocket events and cancels still resolve to
  the local order. An omitted response cannot prove that the venue rejected the order.

#### Batch cancel

`BatchCancelOrders` commands with resolved venue order IDs use Polymarket's
[`DELETE /orders`](https://docs.polymarket.com/api-reference/trade/cancel-multiple-orders)
endpoint. The adapter sends sequential chunks and chooses each new chunk from the smaller of the
endpoint's 1,000-ID limit and the signer's current cancellation burst. A signer starts with the
Standard 120-token burst, and a tier reported by one response applies to the next new chunk.

Each chunk retries independently with the same order IDs unless a lower reported tier requires smaller chunks.
Confirmed cancellations override conflicting rejection reasons for the same ID.

If a chunk fails, results from earlier completed chunks still apply. For the remaining orders:

- **Failed chunk**: Failures proven not sent emit `OrderCancelDenied`; venue rejections emit
  `OrderCancelRejected`. Ambiguous failures leave cancels in flight.
- **Beyond the failed chunk**: Cancels stay in flight if an earlier, larger attempt included those orders.
- **Never attempted**: Orders receive `OrderCancelDenied` with the actual command ID and a local not-sent reason.

Each batch command retains its own UUID, including repeated targets. An unattempted comma

Shown in full with attribution under the source's licence. Licence: LGPL-3.0

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.