# Overview Source: https://docs.polymarket.com/api-reference/predictions/overview Explore the APIs available for building with Polymarket Predictions. ## APIs Polymarket Predictions comprises several APIs, each responsible for a distinct part of an integration. > [card] Gamma API > > **`https://gamma-api.polymarket.com`** > > Discover events and markets, and retrieve the metadata needed to work with > them. > [card] CLOB API > > **`https://clob.polymarket.com`** > > Read live market state, then place and manage orders. > [card] [Data API](https://data-api.polymarket.com/v2/docs) > > **`https://data-api.polymarket.com`** > > Understand account and market activity after discovery and trading. v2 is > now available, with cursor pagination and a shared response envelope. > [card] Relayer API > > **`https://relayer-v2.polymarket.com`** > > Submit supported wallet transactions without requiring the account to hold > POL for gas. > [card] WebSocket APIs > > **Realtime streams** > > Keep an integration updated with market, account, sports, and RFQ events. > [card] Bridge API > > **`https://bridge.polymarket.com`** > > Fund and withdraw from Polymarket using supported assets. ## Before You Integrate > [card] [Rate Limits](/api-reference/rate-limits) > > Review request limits for each service and endpoint. > [card] [Geographic Restrictions](/api-reference/geoblock) > > Check where order placement is available. # Rate Limits Source: https://docs.polymarket.com/api-reference/rate-limits Cloudflare IP-based request limits for Polymarket APIs The limits on this page are IP-based and enforced using Cloudflare's throttling system. When you exceed the limit for any endpoint, requests are throttled (delayed/queued) rather than immediately rejected. Limits reset on sliding time windows. > [!NOTE] > > CLOB order and cancellation requests also use separate [per-signer > token-bucket limits](/api-reference/trading-rate-limits). *** ## General | Endpoint | Limit | | - | - | | General rate limiting | 15,000 req / 10s | | Health check (`/ok`) | 100 req / 10s | *** ## Gamma API Base URL: `https://gamma-api.polymarket.com` | Endpoint | Limit | | - | - | | General | 4,000 req / 10s | | `/events` | 500 req / 10s | | `/markets` | 300 req / 10s | | `/markets` + `/events` listing | 900 req / 10s | | `/comments` | 200 req / 10s | | `/tags` | 200 req / 10s | | `/public-search` | 350 req / 10s | *** ## Data API Base URL: `https://data-api.polymarket.com` ### v1 | Endpoint | Limit | | - | - | | General | 1,000 req / 10s | | `/trades` | 200 req / 10s | | `/positions` | 150 req / 10s | | `/closed-positions` | 150 req / 10s | | Health check (`/ok`) | 100 req / 10s | ### v2 | Endpoint | Limit | | - | - | | General (all `/v2` endpoints) | 800 req / 10s | | `/v2/trades` | 300 req / 10s | | `/v2/positions`, `/v2/positions/combos` | 200 req / 10s | | `/v2/activity`, `/v2/activity/combos` | 200 req / 10s | | `/v2/prices-history` | 200 req / 10s | | `/v2/status` | 100 req / 10s | *** ## CLOB API Base URL: `https://clob.polymarket.com` ### General | Endpoint | Limit | | - | - | | General | 9,000 req / 10s | | `GET` balance allowance | 200 req / 10s | | `UPDATE` balance allowance | 50 req / 10s | ### Market Data | Endpoint | Limit | | - | - | | `/book` | 1,500 req / 10s | | `/books` | 500 req / 10s | | `/price` | 1,500 req / 10s | | `/prices` | 500 req / 10s | | `/midpoint` | 1,500 req / 10s | | `/midpoints` | 500 req / 10s | | `/prices-history` | 1,000 req / 10s | | Market tick size | 200 req / 10s | ### Ledger | Endpoint | Limit | | - | - | | `/trades`, `/orders`, `/notifications`, `/order` | 900 req / 10s | | `/data/orders` | 500 req / 10s | | `/data/trades` | 500 req / 10s | | `/notifications` | 125 req / 10s | ### Authentication | Endpoint | Limit | | - | - | | API key endpoints | 100 req / 10s | ### Rewards | Endpoint | Limit | | - | - | | `GET /rewards/user/markets` | 200 req / 10s | | `GET /rewards/markets/multi` | 200 req / 10s | | `GET /rewards/markets/current` | 300 req / 10s | | `GET /rebates/current` | 300 req / 10s | ### Trading Cloudflare applies both **burst** limits (short spikes allowed) and **sustained** limits (longer-term average) to trading endpoints. | Endpoint | Burst Limit | Sustained Limit | | - | - | - | | `POST /order` | 5,000 req / 10s | 120,000 req / 10 min | | `DELETE /order` | 5,000 req / 10s | 120,000 req / 10 min | | `POST /orders` | 2,000 req / 10s | 21,000 req / 10 min | | `DELETE /orders` | 2,000 req / 10s | 15,000 req / 10 min | | `DELETE /cancel-all` | 250 req / 10s | 6,000 req / 10 min | | `DELETE /cancel-market-orders` | 1,500 req / 10s | 21,000 req / 10 min | *** ## Bridge API Base URL: `https://bridge.polymarket.com` | Endpoint | Limit | | - | - | | General | 50 req / 10s | *** ## Other | Endpoint | Limit | | - | - | | Relayer `/submit` | 25 req / 1 min | | User PNL API | 200 req / 10s | # Markets & Events Source: https://docs.polymarket.com/concepts/markets-events Understanding the fundamental building blocks of Polymarket Every prediction on Polymarket is organized into **events** and **markets**. An event is the question or topic shown to users, while each market is a resolvable binary condition with Yes and No outcomes. See [Positions & Tokens](/concepts/positions-tokens) to learn how outcome balances are represented. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/event-market.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=4c62bd08a405868307cdd6799b368ca5) ## Markets A **market** is the fundamental tradable unit on Polymarket. Each market represents a resolvable condition with Yes and No outcomes. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/event.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=0c9a264aec9a22ce5a20c4cc7980806d) Every market has: | Identifier | Description | | - | - | | **Condition ID** | Unique identifier for the market's resolvable condition | | **Question ID** | Hash of the market question used for resolution | | **Token IDs** | ERC1155 token IDs that track positions — one for Yes and one for No | > [!NOTE] > > Markets can only be traded via the CLOB if `enableOrderBook` is `true`. Some > markets may exist onchain but not be available for order book trading. ### Market Example A simple market might be: > **"Will Bitcoin reach \$150,000 by December 2026?"** This creates two outcome positions: * **Yes position** - Redeemable for `$1` if Bitcoin reaches `$150k` * **No position** - Redeemable for `$1` if Bitcoin doesn't reach `$150k` ## Events An **event** is a container that groups one or more related markets together. Events provide organizational structure and enable multi-outcome predictions. ### Single-Market Events When an event contains just one market, it creates a simple market pair. The event and market are essentially equivalent. ``` Event: Will Bitcoin reach $100,000 by December 2024? └── Market: Will Bitcoin reach $100,000 by December 2024? (Yes/No) ``` ### Multi-Market Events When an event contains two or more markets, it groups related binary questions under one event. Some multi-market events represent mutually exclusive outcomes. Polymarket links these mutually exclusive markets as a [negative-risk group](/concepts/negative-risk). Exactly one market in the group resolves Yes, while every other market resolves No. ``` Event: Who will win the 2024 Presidential Election? ├── Market: Donald Trump? (Yes/No) ├── Market: Joe Biden? (Yes/No) ├── Market: Kamala Harris? (Yes/No) └── Market: Other? (Yes/No) ``` ## Identifying Markets Every market and event has a unique **slug** that appears in the Polymarket URL: ``` https://polymarket.com/event/fed-decision-in-october └── slug: fed-decision-in-october ``` You can use slugs to fetch specific markets or events from the API: ```bash theme={null} # Fetch event by slug curl "https://gamma-api.polymarket.com/events?slug=fed-decision-in-october" ``` ## Sports Markets Specifically for sports markets, outstanding limit orders are **automatically cancelled** once the game begins, clearing the order book at the official start time. However, game start times can shift — if a game starts earlier than scheduled, orders may not be cleared in time. Always monitor your orders closely around game start times. *** ## Next Steps > [card] [Prices & Orderbook](/concepts/prices-orderbook) > > Learn how prices are determined and how the order book works. > [card] [Fetching Market Data](/market-data/overview) > > Start querying markets and events from the API. # Negative Risk Markets Source: https://docs.polymarket.com/concepts/negative-risk Capital-efficient trading for multi-outcome events **Negative risk** is a mechanism for multi-outcome events where only one outcome can win. It enables capital-efficient trading by allowing positions across all outcomes within an event to be related through a **conversion** operation. ## How It Works In a standard multi-outcome event, each market is independent. If you want to bet against one outcome, you must buy that outcome's No positions—but those No positions have no relationship to the other outcomes. Negative risk changes this. In a neg risk event: * A **No share** in any market can be converted into **1 Yes share in every other market** ### Example Consider an event: "Who will win the 2024 Presidential Election?" with three outcomes: | Outcome | Your Position | | - | - | | Trump | — | | Harris | — | | Other | 1 No | With negative risk, that 1 No on "Other" can be converted into: | Outcome | After Conversion | | - | - | | Trump | 1 Yes | | Harris | 1 Yes | | Other | — | This is capital-efficient because betting against one outcome is economically equivalent to betting *for* all other outcomes. ## Contract Addresses Neg risk markets use different contracts than standard markets: See [Contracts](/resources/contracts) for the contracts used by each position system. ## Augmented Negative Risk Standard negative risk requires the complete set of outcomes to be known at market creation. But sometimes new outcomes emerge after trading begins (e.g., a new candidate enters a race). Augmented negative risk applies to both CTF and Polymarket Protocol V2 markets. **Augmented negative risk** solves this with: | Outcome Type | Description | | - | - | | **Named outcomes** | Known outcomes (e.g., "Trump", "Harris") | | **Additional outcomes** | Outcomes that can become available after the event starts | | **Explicit Other** | Catches any outcome not explicitly named | ### Trading Rules for Augmented Neg Risk > [!WARNING] > > Only trade on **named outcomes**. Placeholder outcomes should be ignored until > they are named or until resolution occurs. The Polymarket UI does not display > unnamed outcomes. * If the correct outcome at resolution is not named, the market resolves to "Other" * The "Other" outcome's definition changes as placeholders are clarified—avoid trading it directly ## Technical Details ### Conversion Mechanics Conversion is atomic. Polymarket Protocol V2 uses the Router and NegRiskModule. CTF uses the Neg Risk Adapter. 1. You hold 1 No position for Outcome A 2. Call the conversion operation for the market's position system 3. You receive 1 Yes position for every other outcome in the event ## Next Steps > [card] [Markets & Events](/concepts/markets-events) > > Understand how multi-market events are structured. > [card] [Positions & Tokens](/concepts/positions-tokens) > > Learn about position operations like split, merge, and redeem. # Order Lifecycle Source: https://docs.polymarket.com/concepts/order-lifecycle Understanding how orders flow from creation to settlement Every trade on Polymarket follows a specific lifecycle. Orders are created offchain, matched by an operator, and settled onchain through smart contracts. This hybrid approach combines the speed of centralized matching with the security of blockchain settlement. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/order-lifecycle.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=4db07008193421bfe359afe44b5f604e) ## How Orders Work All orders on Polymarket are **limit orders**. A limit order specifies the price you're willing to pay (or accept) and the quantity you want to trade. > [!NOTE] > > "Market orders" are simply limit orders with a price set to execute > immediately against the best available resting orders. Orders are **EIP712-signed messages**. When you place an order, you sign a structured message with your private key. This signature authorizes the market's settlement contract to execute the trade on your behalf without taking custody of your funds. ## Order Types | Type | Behavior | Use Case | | - | - | - | | **GTC** | Good Till Cancelled — rests on book until filled or cancelled | Standard limit orders | | **GTD** | Good Till Date — auto-expires at specified time | Time-limited orders | | **FOK** | Fill Or Kill — fill entirely or cancel immediately | All-or-nothing execution | | **FAK** | Fill And Kill — fill what's available, cancel the rest | Partial fills acceptable | ### Post-Only Orders Post-only orders will only rest on the book. If a post-only order would match immediately (cross the spread), it's rejected instead of executed. This guarantees you're always the maker, never the taker. **1. Create and Sign** Your client creates an order object containing: * Outcome token ID (which outcome you're trading) * Side (buy or sell) * Price and size * Expiration time * Timestamp (in milliseconds, used for order uniqueness) You sign this order with your private key, creating an EIP712 signature. **2. Submit to CLOB** The signed order is submitted to the Central Limit Order Book (CLOB) operator. The operator validates: * Signature is valid * You have sufficient balance * You have set the required allowances * Price meets minimum tick size requirements **3. Match or Rest** **If the order is marketable** (your buy price ≥ lowest ask, or your sell price ≤ highest bid), it matches against resting orders. Some markets apply a short taker delay before matching: * **Taker delay:** used on selected crypto and finance up/down markets. The order is held for 250 ms, then validation runs again and the order is matched or placed on the book. The API waits for this hold and returns the final order result. To check a specific market, call the public CLOB endpoint `GET https://clob.polymarket.com/clob-markets/{condition_id}` and look for `itode: true`. * **Sports/game delay:** enabled on configured sports markets around live game conditions. The order waits for the market's configured delay window before matching. During either delay, the order is pending and cannot be canceled. If the market, balance, allowance, or risk checks fail when the delay expires, the order is rejected instead of matching. **If the order is not marketable**, it rests on the book waiting for a counterparty. It remains open until: * Another order matches against it * You cancel it * It expires (GTD orders only) **4. Settlement** When orders match, the operator submits the trade to the blockchain. The market's settlement contract verifies the matched orders and settles their value. Depending on the order sides and available assets, settlement can transfer existing outcome tokens, split pUSD into complete sets, or merge complete sets back into pUSD. Settlement is **atomic**: either the entire trade succeeds or nothing happens. **5. Confirmation** The trade achieves finality on Polygon. Your position balances update and the trade appears in your history. ## Order Statuses When you place an order, it receives one of these statuses: | Status | Description | | - | - | | `live` | Order is resting on the book | | `matched` | Order matched immediately | | `delayed` | Marketable order accepted into an asynchronous delay window on configured seconds-delay markets, such as sports markets | | `unmatched` | Marketable order placed on the book after the delay expired without a match | ## Trade Statuses After matching, trades progress through these statuses: | Status | Terminal | Description | | - | - | - | | `MATCHED` | No | Trade matched, sent to executor for onchain submission | | `MINED` | No | Transaction mined into the blockchain | | `CONFIRMED` | Yes | Trade achieved finality, successful | | `RETRYING` | No | Transaction failed, being retried | | `FAILED` | Yes | Trade failed permanently | ## Maker vs Taker | Role | Description | When | | - | - | - | | **Maker** | Adds liquidity to the book | Your order rests and is later matched | | **Taker** | Removes liquidity from the book | Your order matches immediately against resting orders | Price improvement always benefits the taker. If you place a buy order at `$0.55` and it matches against a resting sell at `$0.52`, you pay `$0.52`. ## Cancellation You can cancel orders at any time before they're matched via the CLOB API, except while a marketable order is in a pending delay window. Partial fills cannot be cancelled: only the unfilled portion of an order can be cancelled. ## Requirements Before placing orders, ensure: | Requirement | Description | | - | - | | **Balance** | Sufficient pUSD for buys or outcome tokens for sells | | **Allowance** | Approve the market's settlement route to transfer your assets | | **API Credentials** | Valid API key for authenticated endpoints | > [!NOTE] > > Order size is limited by your available balance minus any amounts reserved by existing open orders. > > $$ > \text{maxOrderSize} = \text{balance} - \sum(\text{openOrderSize} - \text{filledAmount}) > $$ ## Next Steps > [card] [Resolution](/concepts/resolution) > > Learn how markets are resolved and winning positions redeemed. > [card] [Trading Guide](/trading/quickstart) > > Start placing orders with our step-by-step guide. # Positions & Tokens Source: https://docs.polymarket.com/concepts/positions-tokens Understanding outcome tokens and how positions work on Polymarket Every prediction on Polymarket is represented by **outcome tokens**. When you trade, you buy and sell these tokens. Your **position** is your balance for an outcome in a market. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/token-lifecycle.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=cad279109c43c68c541123c2d348c4c5) ## Outcome Tokens Each binary market has two outcome positions: | Position | Full payout if… | | - | - | | **Yes** | The condition occurs | | **No** | The condition does not occur | > [!NOTE] > > A complete Yes/No set is backed by `1 pUSD` of value. How that backing is held > and released depends on the system that owns the position. ## Positions Ledgers Polymarket markets use one of two onchain ledgers for outcome balances: **PositionManager** for Polymarket Protocol V2 markets and **Conditional Tokens** for CTF markets. Both represent Yes and No outcomes as ERC-1155 balances, and those balances have the same economic meaning to traders. The ledger determines which position identifiers and integration path apply. See the [Migrate to Polymarket Protocol V2 technical guide](/migrate/polymarket-v2/overview) for more technical details. ## Position Management ### Split Convert pUSD into outcome tokens. Splitting `1 pUSD` creates 1 Yes position and 1 No position. ``` 100 pUSD → 100 Yes positions + 100 No positions ``` Use this when you want to: * Create inventory for market making * Obtain both sides of a market ### Trade Buy or sell outcome tokens on the order book. This is how most users acquire positions. * **Buy Yes** at `$0.60` → Pay `$0.60`, receive 1 Yes position * **Sell Yes** at `$0.60` → Give up 1 Yes position, receive `$0.60` You can sell your position at any time before resolution. ### Merge Convert a complete set back into pUSD. Merging requires equal amounts of Yes and No positions. ``` 100 Yes positions + 100 No positions → 100 pUSD ``` Use this when you want to: * Exit a position without trading * Convert accumulated positions back to collateral ### Redeem After a market resolves, exchange positions for pUSD according to the recorded payout. | Outcome | Yes positions | No positions | | - | - | - | | Event occurs | Worth \$1 each | Worth \$0 | | Event doesn't occur | Worth \$0 | Worth \$1 each | ``` 100 winning positions → 100 pUSD ``` A binary market can resolve to a split payout instead of a full `$1` or `$0`, in which case each side redeems for its share. Negative-risk markets never split: exactly one outcome takes the full payout and every other outcome pays nothing. See [Manage Positions](/migrate/polymarket-v2/overview#manage-positions) for operations on both position systems. ### Position Value The value of your position depends on the current market price: ``` Position value = Position balance × Current price ``` If you hold 100 Yes positions and Yes is trading at \$0.75: ``` Position value = 100 × $0.75 = $75 ``` ## Profit and Loss Your profit depends on how the market resolves compared to your entry price. ### Example - Buying Yes at 0.40 | Scenario | Outcome | Return | Profit | | - | - | - | - | | Event occurs | Yes wins | \$1.00 | +\$0.60 per position (150%) | | Event doesn't occur | No wins | \$0.00 | -\$0.40 per position (-100%) | ### Holding Rewards Polymarket pays a **4.00% annualized** Holding Reward based on your total position value in eligible markets. Your total position value is randomly sampled once each hour, and the reward is distributed daily. The rate is variable and subject to change at Polymarket's discretion. ### Example - Selling Before Resolution You can lock in profits or cut losses by selling before the market resolves: * Bought Yes at `$0.40` * Price rises to `$0.70` * Sell at `$0.70` → Profit of `$0.30` per position (75%) # Prices & Orderbook Source: https://docs.polymarket.com/concepts/prices-orderbook How prices work and how the order book enables peer-to-peer trading Polymarket uses a **Central Limit Order Book (CLOB)** for trading. Prices aren't set by Polymarket—they emerge from supply and demand as users trade with each other. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/orderbook.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=119174bcaaeb3b9abbd4c2d94b7bdae6) ## Prices Are Probabilities Every share on Polymarket is priced between `$0.00` and `$1.00`. The price directly represents the market's belief in the probability of that outcome. | Price | Implied Probability | | - | - | | \$0.25 | 25% chance | | \$0.50 | 50% chance | | \$0.75 | 75% chance | > [!NOTE] > > The displayed price is the **midpoint** of the bid-ask spread. If the spread > is wider than \$0.10, the last traded price is shown instead. ### Example If the best bid for "Yes" is `$0.34` and the best ask is `$0.40`: ``` Displayed price = ($0.34 + $0.40) / 2 = $0.37 (37% probability) ``` You won't necessarily trade at `$0.37`—you'll pay the ask (`$0.40`) when buying or receive the bid (`$0.34`) when selling. ## The Order Book The order book is a list of all open buy and sell orders for a market. It has two sides: | Side | Description | | - | - | | Bids | Buy orders—the highest prices traders are willing to pay | | Asks | Sell orders—the lowest prices traders are willing to accept | The **spread** is the gap between the highest bid and lowest ask. Tighter spreads mean more liquid markets. ## Order Types ### Market Orders Execute immediately at the best available price. Use when you want instant execution and are willing to pay the spread. * **Buying**: You pay the lowest ask price * **Selling**: You receive the highest bid price ### Limit Orders Execute only at your specified price or better. Use when you want price control and are willing to wait. * Your order sits in the book until someone trades against it * Orders can **partially fill** as different traders match portions of your order * You can cancel unfilled orders at any time > [!NOTE] > > All orders on Polymarket are technically limit orders. A "market order" is > simply a limit order priced to execute immediately against resting orders. ## How Trades Work Polymarket's CLOB is **hybrid-decentralized**: 1. **Offchain matching** — An operator matches compatible orders 2. **Onchain settlement** — Matched trades settle via smart contracts ```mermaid theme={null} flowchart LR A[Signed orders] --> B[CLOB matching] B --> C[Onchain settlement] C --> D[pUSD and outcome tokens change owners] ``` This design gives you the speed of centralized matching with the security of onchain settlement. You maintain custody of your assets until a matched trade settles atomically. The CLOB is shared across markets, while the settlement route depends on which system owns the outcome tokens: CTF or Polymarket Protocol V2. ## Price Discovery When a new market launches, there's no initial price. The first price emerges when: 1. Someone places a limit order to buy Yes at a price (e.g., `$0.60`) 2. Someone places a limit order to buy No at the complementary price (e.g., `$0.40`) 3. Since `$0.60` + `$0.40` = `$1.00`, the orders match When matched, `1 pUSD` of collateral creates a complete set through the market's owning system. The Yes and No outcome tokens go to their respective buyers. The reverse operation can merge a complete set back into `1 pUSD`. ## Next Steps > [!NOTE] > > Polymarket's orderbook has **no trading size limits** — it matches willing > buyers and sellers of any amount. However, large orders may move the price > significantly. Always check orderbook depth before trading in size. > [card] [Positions & Tokens](/concepts/positions-tokens) > > Learn about outcome tokens and how positions work. > [card] [Order Lifecycle](/concepts/order-lifecycle) > > Understand what happens from order placement to settlement. # Polymarket USD Source: https://docs.polymarket.com/concepts/pusd pUSD — the collateral token used for all trading on Polymarket **pUSD** (Polymarket USD) is the collateral token used for all trading on Polymarket. It's a standard ERC-20 token on Polygon, backed by USDC. The smart contract — which enables the withdrawal functionality — enforces the backing. No algorithmic peg, no fractional reserve. > [!NOTE] > > **Day to day, nothing changes.** You load funds, see a balance, trade, and > withdraw. pUSD is the technical settlement layer underneath the same > experience you're used to. *** ## Why pUSD The protocol settles all trading activity in native USDC, providing a more capital efficient, scalable, and institutionally aligned settlement standard as the platform continues to grow. pUSD is a standard ERC-20 wrapper that represents a USDC claim. Wrapping and unwrapping are enforced onchain by the `CollateralOnramp` and `CollateralOfframp` contracts. *** ## Key facts | | | | - | - | | Token standard | ERC-20 | | Network | Polygon mainnet | | Decimals | 6 | | Backing | USDC (enforced onchain) | | Transferable | Yes — standard ERC-20 | pUSD is designed to function within Polymarket. There are no current plans to list it on external exchanges. See the [Contracts](/resources/contracts) page for all collateral-related contract addresses. *** ## Wrapping — USDC.e → pUSD Use the **CollateralOnramp** to wrap USDC.e into pUSD. ```solidity theme={null} function wrap(address _asset, address _to, uint256 _amount) external ``` **Parameters** * `_asset` — address of the asset being wrapped. Must be USDC.e. * `_to` — recipient of the minted pUSD. Does not have to be `msg.sender`. * `_amount` — amount to wrap, in USDC.e base units (6 decimals). **Requirements** * The caller must first approve the **CollateralOnramp** contract (not the pUSD token) to spend USDC.e. * Reverts with `OnlyUnpaused()` if the admin has paused USDC.e. ### Example ```typescript TypeScript theme={null} import { createWalletClient, createPublicClient, http, parseAbi, parseUnits, } from "viem"; import { polygon } from "viem/chains"; import { privateKeyToAccount } from "viem/accounts"; const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`); const walletClient = createWalletClient({ account, chain: polygon, transport: http() }); const publicClient = createPublicClient({ chain: polygon, transport: http() }); const ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee" as const; const USDCE = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" as const; // USDC.e on Polygon const amount = parseUnits("100", 6); // 100 USDC.e // 1. Approve the Onramp to spend your USDC.e const approveHash = await walletClient.writeContract({ address: USDCE, abi: parseAbi(["function approve(address spender, uint256 amount) returns (bool)"]), functionName: "approve", args: [ONRAMP, amount], }); await publicClient.waitForTransactionReceipt({ hash: approveHash }); // 2. Wrap USDC.e → pUSD const wrapHash = await walletClient.writeContract({ address: ONRAMP, abi: parseAbi(["function wrap(address _asset, address _to, uint256 _amount)"]), functionName: "wrap", args: [USDCE, account.address, amount], }); await publicClient.waitForTransactionReceipt({ hash: wrapHash }); ``` ```python Python theme={null} from web3 import Web3 ONRAMP = "0x93070a847efEf7F70739046A929D47a521F5B8ee" USDCE = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" amount = 100 * 10**6 # 100 USDC.e # 1. Approve the Onramp to spend your USDC.e usdce = w3.eth.contract(address=USDCE, abi=[{ "name": "approve", "type": "function", "inputs": [{"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"type": "bool"}], }]) usdce.functions.approve(ONRAMP, amount).transact({"from": address}) # 2. Wrap USDC.e → pUSD onramp = w3.eth.contract(address=ONRAMP, abi=[{ "name": "wrap", "type": "function", "inputs": [{"name": "_asset", "type": "address"}, {"name": "_to", "type": "address"}, {"name": "_amount", "type": "uint256"}], "outputs": [], }]) onramp.functions.wrap(USDCE, address, amount).transact({"from": address}) ``` *** ## Unwrapping — pUSD → USDC.e Use the **CollateralOfframp** to unwrap pUSD back into USDC.e. ```solidity theme={null} function unwrap(address _asset, address _to, uint256 _amount) external ``` **Parameters** * `_asset` — asset you want to receive. Must be USDC.e. * `_to` — recipient of the underlying asset. * `_amount` — amount of pUSD to unwrap (6 decimals). **Requirements** * The caller must first approve the **CollateralOfframp** contract to spend their pUSD. * Same pause gate as the Onramp. *** ## Next steps > [card] [Contracts](/resources/contracts) > > All Polymarket contract addresses and audits > [card] [Bridge](/trading/bridge/deposit) > > Deposit from other chains — auto-wraps to pUSD # Resolution Source: https://docs.polymarket.com/concepts/resolution How markets are resolved and winning positions redeemed When the outcome of an event becomes known, the market is **resolved**. Resolution determines which outcome won, allowing holders of winning tokens to redeem them for \$1 each. Losing tokens become worthless. Polymarket uses two **Resolution Sources**, UMA for prediction markets and Chainlink TWAP for up-down markets. ## UMA-Resolved Markets Prediction markets use the **UMA Optimistic Oracle** for decentralized, permissionless resolution. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/resolution-lifecycle.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=6726569af3efd6f4fda54528c8eb0d0a) ### Resolution Rules Every market has pre-defined resolution rules that specify: * **Resolution source** — Where the outcome will be determined from (e.g., official announcements, specific websites) * **End date** — When the market is eligible for resolution * **Edge cases** — How ambiguous situations should be handled > [!WARNING] > > Always read the resolution rules before trading. The market title describes > the question, but the **rules** define how it resolves. **1. Proposal** Anyone can propose a resolution by: 1. Selecting the winning outcome 2. Posting a bond (typically \$750 pUSD) 3. Submitting the proposal to the UMA Oracle If the proposal is correct and undisputed, the proposer receives their bond back plus a reward. > [!WARNING] > > If you propose incorrectly or too early, you lose your entire bond. Only > propose if you're confident in the outcome and understand the process. **2. Challenge Period** After a proposal, there's a **2-hour challenge period** where anyone can dispute the outcome. * **If no dispute**: The proposal is accepted and the market resolves * **If disputed**: A new proposal round begins. If the second proposal is also disputed, the resolution escalates to UMA's DVM (Data Verification Mechanism) for a token holder vote. There are three possible resolution flows: 1. **No dispute** — Propose then Resolve (fastest, \~2 hours) 2. **One dispute** — Propose, Challenge, second Propose, Resolve (second proposal accepted) 3. **Two disputes** — Propose, Challenge, second Propose, second Challenge, Resolve via DVM vote **3. Dispute - If Challenged** To dispute a proposal: 1. Post a counter-bond (same amount as proposer, typically \$750) 2. The dispute triggers a new proposal round, or if already in the second round, a debate period During the **24-48 hour debate period**, evidence can be submitted in UMA's Discord channels (`#evidence-rationale` and `#voting-discussion`). **4. UMA Vote** After the debate period, UMA token holders vote on the correct outcome. The voting process takes approximately 48 hours. | Outcome | Result | Bond Distribution | | - | - | - | | **Proposer wins** | Original proposal accepted | Proposer gets bond back + half of disputer's bond | | **Disputer wins** | Proposal rejected, new proposal needed | Disputer gets bond back + half of proposer's bond | | **Too Early** | Event hasn't concluded yet | Disputer gets bond back + half of proposer's bond | | **Unknown/50-50** | Neither outcome applicable (rare) | Market resolves 50/50 — each token redeems for \$0.50; disputer gets bond back + half of proposer's bond | ### Clarifications In rare cases, unforeseen circumstances require clarification of the rules after trading begins. Polymarket may issue an **"Additional context"** update that proposers and voters should consider during resolution. Clarifications: * Cannot change the fundamental intent of the question * Are published onchain via the bulletin board contract * Should be considered by UMA voters when resolving disputes > [!TIP] > > If you believe a clarification is needed, request it in the [Polymarket > Discord](https://discord.com/invite/polymarket) `#market-review` channel. ### Resolution Timeline | Phase | Duration | | - | - | | Challenge period | 2 hours | | Debate period (if disputed) | 24-48 hours | | UMA voting (if disputed) | \~48 hours | **Undisputed resolution**: \~2 hours after proposal **Disputed resolution**: 4-6 days total See [Resolution Contracts](/resources/contracts#resolution-contracts) for UMA contract addresses. ## Chainlink TWAP–Resolved Up-Down Markets Each market specifies an asset pair, a start time, and a duration. For example, a market may ask whether BTC/USD moves Up or Down during a specific one-hour window. The TWAP at the start sets the **price to beat**. When the duration ends, the TWAP at that time sets the **final price**. Both values come from the same **Chainlink TWAP stream**. A **time-weighted average price (TWAP)** represents an asset's average price over a defined lookback window. ![](https://mintcdn.com/polymarket-292d1b1b/_aswwXEhQSghbFEe/images/core-concepts/chainlink-twap-resolution.png?fit=max\&auto=format\&n=_aswwXEhQSghbFEe\&q=85\&s=1a7a30851b1155e88dbf05322a395a41) ### How Resolution Works The market resolves **Up** when the final price is **equal to or greater** than the price to beat, and **Down** when it is **lower**. Because the inputs and comparison are fixed, the same observations always produce the same result without UMA's proposal-and-dispute process. ## After Resolution Once a market resolves: * **Trading stops** — You can no longer buy or sell tokens for this market * **Winning tokens** become redeemable for \$1.00 each * **Losing tokens** become worthless (\$0.00) ## Resources * [UMA Oracle Portal](https://oracle.uma.xyz/) — View and interact with proposals * [UMA Documentation](https://docs.uma.xyz/) — Learn more about the Optimistic Oracle * [Chainlink TWAP Prices](/market-data/chainlink-twap) — Learn how to access Chainlink-computed TWAP prices * [Chainlink TWAP Documentation](https://chain.link/article/twap-and-vwap-pricing-mechanisms) — Learn how time-weighted average pricing works * [Polymarket Discord](https://discord.com/invite/polymarket) — Discuss resolutions and request clarifications # API Source: https://docs.polymarket.com/getting-started/api Build directly with Polymarket REST APIs and WebSocket streams. The Polymarket APIs provide programmatic access to the Polymarket platform. Each API serves a distinct part of an integration. ## Integration Surfaces > [tab] REST APIs > > > [card] Gamma API > > > > **`https://gamma-api.polymarket.com`** > > > > Discover events and markets, and retrieve the metadata needed to work with > > them. > > > [card] CLOB API > > > > **`https://clob.polymarket.com`** > > > > Read prices and order books, then place and manage orders. > > > [card] [Data API](/api-reference/data-api/overview) > > > > **`https://data-api.polymarket.com`** > > > > Analyze positions, activity, and market participation with cursor > > pagination and a shared response envelope. > > > [card] Relayer API > > > > **`https://relayer-v2.polymarket.com`** > > > > Submit wallet transactions without requiring the account to hold POL for > > gas. > [tab] WebSocket APIs > > > [card] [CLOB Market Channel](/api-reference/wss/market) > > > > **`wss://ws-subscriptions-clob.polymarket.com/ws/market`** > > > > Follow public order book, price, and market lifecycle updates. > > > [card] [CLOB User Channel](/api-reference/wss/user) > > > > **`wss://ws-subscriptions-clob.polymarket.com/ws/user`** > > > > Follow authenticated order and trade updates for an account. > > > [card] [RTDS](/market-data/realtime-data) > > > > **`wss://ws-live-data.polymarket.com`** > > > > Stream public reference prices, comments, and trade activity. > > > [card] [Sports WebSocket](/api-reference/wss/sports) > > > > **`wss://sports-api.polymarket.com/ws`** > > > > Follow public live game status and scores. ## When to Use the API Use direct integration when: * Your runtime is not supported by an official SDK. * You need exact control over request signing, headers, retries, or transport. * You need an endpoint or wire format that is not exposed by an SDK yet. The SDKs provide a unified, typed interface across Polymarket and handle common integration concerns such as pagination, errors, and wallet setup. ## Make a Public Request Public market data is available without credentials. For example, list active markets from the Gamma API: ```bash theme={null} curl -G "https://gamma-api.polymarket.com/markets" \ --data-urlencode "closed=false" \ --data-urlencode "limit=5" ``` ## Authentication CLOB authentication has two layers: | Layer | How it works | Purpose | | - | - | - | | L1 | The wallet signs an EIP-712 message | Establish wallet control and create or derive credentials | | L2 | Requests are signed with API credentials using HMAC-SHA256 | Authenticate private CLOB requests | Order placement uses L2 to authenticate the request and a wallet signature to authorize the order itself. To authenticate private CLOB requests, follow these steps: **1. Create L1 Typed Data** Build the `ClobAuth` typed-data payload. ```json clobAuthTypedData theme={null} { "domain": { "name": "ClobAuthDomain", "version": "1", "chainId": 137 }, "types": { "ClobAuth": [ { "name": "address", "type": "address" }, { "name": "timestamp", "type": "string" }, { "name": "nonce", "type": "uint256" }, { "name": "message", "type": "string" } ] }, "primaryType": "ClobAuth", "message": { "address": "", "timestamp": "", "nonce": "", "message": "This message attests that I control the given wallet" } } ``` Provide these values: | Placeholder | Value | | - | - | | `` | Polygon address controlled by the signing private key | | `` | Current Unix timestamp in seconds | | `` | Credential nonce; use `0` unless managing multiple sets | **2. Create a CLOB L1 Signature** Sign `clobAuthTypedData` with the private key that controls ``. This example uses Viem. ```ts theme={null} import { privateKeyToAccount } from "viem/accounts"; const signer = privateKeyToAccount(""); const clobL1Signature = await signer.signTypedData(clobAuthTypedData); ``` The returned `clobL1Signature` is the L1 signature for this payload. **3. Create or Derive CLOB API Credentials** Use the signer address, timestamp, and nonce from Step 1 with the signature from Step 2 to create credentials. If credentials already exist for that address and nonce, derive them instead. ```bash Create theme={null} curl -X POST "https://clob.polymarket.com/auth/api-key" \ -H "POLY_ADDRESS: " \ -H "POLY_SIGNATURE: " \ -H "POLY_TIMESTAMP: " \ -H "POLY_NONCE: " ``` ```bash Derive theme={null} curl "https://clob.polymarket.com/auth/derive-api-key" \ -H "POLY_ADDRESS: " \ -H "POLY_SIGNATURE: " \ -H "POLY_TIMESTAMP: " \ -H "POLY_NONCE: " ``` The response contains the three values used for L2 authentication: ```json Response theme={null} { "apiKey": "", "secret": "", "passphrase": "" } ``` ```json Example theme={null} { "apiKey": "7b1e2d60-6f9a-4dd7-8f3e-21b8f94c77a2", "secret": "Rnl2cWN0Rk5…c1ZzR1E9PQ==", "passphrase": "9fH3kL7m…2qW8xP4r" } ``` Where: * `apiKey` is the unique identifier for the API credentials. * `secret` is the base64-encoded key used to sign L2 requests with HMAC-SHA256. * `passphrase` is the credential value sent in the `POLY_PASSPHRASE` header. **4. Create a CLOB L2 Signature** Whenever you need to authenticate a request, create a new Unix timestamp in seconds. Concatenate the timestamp, uppercase HTTP method, route path, and exact serialized request body, then sign the result with the API credentials `secret`. The example request uses `GET /data/orders`, which has no body: ```text theme={null} clob_request_timestamp = method = "GET" request_path = "/data/orders" message = clob_request_timestamp + method + request_path clob_l2_signature = urlsafeBase64WithPadding( HMAC-SHA256(base64Decode(), message) ) ``` For requests with a body, append the exact serialized body sent over the wire. **5. Send an Authenticated Request** Use the timestamp and L2 signature from Step 4 with the signer address and API credentials from Step 3. This request retrieves the account's open orders. ```bash theme={null} curl "https://clob.polymarket.com/data/orders" \ -H "POLY_ADDRESS: " \ -H "POLY_SIGNATURE: " \ -H "POLY_TIMESTAMP: " \ -H "POLY_API_KEY: " \ -H "POLY_PASSPHRASE: " ``` L2-authenticated CLOB requests use the same five headers: | Header | Value | | - | - | | `POLY_ADDRESS` | Polygon signer address | | `POLY_SIGNATURE` | HMAC-SHA256 signature from Step 4 | | `POLY_TIMESTAMP` | Unix timestamp used to build the signature | | `POLY_API_KEY` | API credentials `apiKey` value | | `POLY_PASSPHRASE` | API credentials `passphrase` value | ## Next Steps > [card] [Read Market Data](/market-data/overview) > > Discover markets and work with prices, order books, and historical data. > [card] [Subscribe to Real-Time Updates](/market-data/realtime-data) > > Stream market and account updates as they happen. > [card] [Place Your First Order](/trading/quickstart) > > Set up an account and complete your first authenticated trade. # Python SDK Source: https://docs.polymarket.com/getting-started/python Get started with the unified Polymarket Python SDK. The `polymarket-client` package is the official Python SDK for building Polymarket integrations. > [card] [GitHub](https://github.com/Polymarket/py-sdk/) > > View the Python SDK source. > [card] [PyPI Package](https://pypi.org/project/polymarket-client/) > > Install `polymarket-client` from PyPI. See the [SDK Changelog](/changelog/sdks#python) for recent Python releases. ## Quickstart **1. Install the SDK** Install the SDK with your preferred package manager. ```bash uv theme={null} uv add polymarket-client ``` ```bash pip theme={null} pip install polymarket-client ``` ```bash poetry theme={null} poetry add polymarket-client ``` **2. Create a Public Client** Create an `AsyncPublicClient` to access publicly available Polymarket data. ```python theme={null} from polymarket import AsyncPublicClient async with AsyncPublicClient() as client: ... ``` **3. Fetch Active Markets** Fetch a page of active markets to discover trading opportunities. ```python theme={null} import asyncio from polymarket import AsyncPublicClient async def main() -> None: async with AsyncPublicClient() as client: pages = client.list_markets(closed=False) first_page = await pages.first_page() for market in first_page.items: # market: Market ... asyncio.run(main()) ``` ## Async and Sync Interfaces Public clients access public data. [Secure clients](#secure-client) add trading and account access. Both client types are available in async and sync forms. | Interface | Public data | Trading and account data | | - | - | - | | Async | `AsyncPublicClient` | `AsyncSecureClient` | | Sync | `PublicClient` | `SecureClient` | Async clients fit services, bots, and applications that already run an event loop. Sync clients are convenient for scripts and notebooks. ```python Async theme={null} from polymarket import AsyncPublicClient async with AsyncPublicClient() as client: pages = client.list_markets(closed=False) first_page = await pages.first_page() ``` ```python Sync theme={null} from polymarket import PublicClient with PublicClient() as client: pages = client.list_markets(closed=False) first_page = pages.first_page() ``` > [!NOTE] > > Some features, including realtime subscriptions, are async-only because they > rely on long-lived streams. ## Pagination SDK list methods use a consistent paginator interface. Iterate over the paginator to retrieve every page, or fetch one page at a time when you need to control pacing. ```python Async theme={null} pages = client.list_markets(closed=False, page_size=10) async for page in pages: for market in page.items: # market: Market ... ``` ```python Sync theme={null} pages = client.list_markets(closed=False, page_size=10) for page in pages: for market in page.items: # market: Market ... ``` When page boundaries do not matter, iterate over every item directly. ```python Async theme={null} async for market in pages.iter_items(): # market: Market ... ``` ```python Sync theme={null} for market in pages.iter_items(): # market: Market ... ``` `page.next_cursor` is an opaque SDK cursor. Store it as-is if you want to resume a scan later, and omit it when starting from the first page. ```python Async theme={null} pages = client.list_markets(closed=False, page_size=10) page = await pages.first_page() if page.next_cursor: second_page = await pages.from_cursor(page.next_cursor).first_page() # second_page.items: tuple[Market, ...] ``` ```python Sync theme={null} pages = client.list_markets(closed=False, page_size=10) page = pages.first_page() if page.next_cursor: second_page = pages.from_cursor(page.next_cursor).first_page() # second_page.items: tuple[Market, ...] ``` ## Types SDK methods return typed models, and their public types are exported from `polymarket`. ```python theme={null} from polymarket import Event, Market, OrderBook, PriceHistoryPoint ``` The SDK also uses distinct types for domain identifiers and EVM addresses. Precision-sensitive values use `decimal.Decimal`, while dates and timestamps use Python's `datetime` types. ```python theme={null} from polymarket import ConditionId, EvmAddress, MarketId, PositionId, TokenId ``` ## Error Handling All SDK exceptions inherit from `PolymarketError`. Catch specific exceptions when your application can respond to them, then catch the base exception as a fallback. ```python theme={null} from polymarket import PolymarketError, RateLimitError, UserInputError pages = client.list_markets(closed=False) try: page = await pages.first_page() # page.items: tuple[Market, ...] except RateLimitError: # Retry later. ... except UserInputError: # Fix the request parameters. ... except PolymarketError: # Handle any other SDK error. raise ``` ## Secure Client Create an `AsyncSecureClient` or `SecureClient` when your integration needs to trade or access account data. The Python SDK creates the signer from a local private key. ```python Async theme={null} import os from polymarket import AsyncSecureClient async with await AsyncSecureClient.create( private_key=os.environ["POLYMARKET_PRIVATE_KEY"], ) as client: ... ``` ```python Sync theme={null} import os from polymarket import SecureClient with SecureClient.create( private_key=os.environ["POLYMARKET_PRIVATE_KEY"], ) as client: ... ``` Continue to [Wallets and Authentication](/trading/wallets-auth) to configure the account wallet and gasless transactions. ## Realtime Subscriptions The Python SDK can combine updates from multiple realtime feeds into a single stream of events. > [!NOTE] > > Realtime subscriptions are available only through `AsyncPublicClient` and > `AsyncSecureClient`. `PublicClient` and `SecureClient` do not implement > `subscribe()`. Call `subscribe()` with one or more subscription specs. Both `AsyncPublicClient` and `AsyncSecureClient` support public streams, while `AsyncSecureClient` also provides private streams for the connected account. ```python Public Client theme={null} from polymarket.streams import MarketSpec, SportsSpec asset_id = "" async with await client.subscribe( [MarketSpec(asset_ids=[asset_id]), SportsSpec()], ) as stream: async for event in stream: # event: # MarketBookEvent # | MarketPriceChangeEvent # | MarketLastTradePriceEvent # | MarketTickSizeChangeEvent # | MarketBestBidAskEvent # | NewMarketEvent # | MarketResolvedEvent # | SportsEvent if should_close: break ``` ```python Secure Client theme={null} from polymarket.streams import MarketSpec, UserSpec asset_id = "" async with await client.subscribe( [MarketSpec(asset_ids=[asset_id]), UserSpec()], ) as stream: async for event in stream: # event: # MarketBookEvent # | MarketPriceChangeEvent # | MarketLastTradePriceEvent # | MarketTickSizeChangeEvent # | MarketBestBidAskEvent # | NewMarketEvent # | MarketResolvedEvent # | UserEvent if should_close: break ``` Narrow `event.topic` before handling a specific event shape. The examples show a few streams; see [Real-Time Data](/market-data/realtime-data), [Real-Time Order Updates](/trading/realtime-order-updates), and [Perps Realtime Updates](/perps/realtime-updates) for feed-specific options. ## DataFrames and Jupyter Convert pages and paginators directly to a [pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html), [Polars DataFrame](https://docs.pola.rs/py-polars/html/reference/dataframe/), or [Apache Arrow Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html). Install the `pandas`, `polars`, or `arrow` package extra for the format you use; the `quant` extra installs all three. ```python Pandas theme={null} pages = client.list_markets(closed=False) df = await pages.to_pandas(limit=100) ``` ```python Polars theme={null} pages = client.list_markets(closed=False) df = await pages.to_polars(limit=100) ``` ```python Arrow theme={null} pages = client.list_markets(closed=False) table = await pages.to_arrow(limit=100) ``` Paginator conversions require an explicit limit. Pass `limit=None` to retrieve every item. Common SDK objects also render as compact cards in [Jupyter](https://docs.jupyter.org/en/stable/) notebooks. Return an object as the last expression in a cell to display it. ```python theme={null} pages = client.list_markets(closed=False) page = await pages.first_page() page.items[0] ``` ## Next Steps > [card] [Read Market Data](/market-data/overview) > > Discover markets and work with prices, order books, and historical data. > [card] [Subscribe to Real-Time Updates](/market-data/realtime-data) > > Stream market and account updates as they happen. > [card] [Place Your First Order](/trading/quickstart) > > Set up an account and complete your first authenticated trade. > [card] [Use Session Keys](/trading/session-keys) > > Grant scoped, time-limited Deposit Wallet access to a separate signer. # SDKs & APIs Source: https://docs.polymarket.com/getting-started/sdks-apis Choose how to integrate with Polymarket. Choose the interface that best fits your application. Use an SDK for a unified, typed integration, or work with the APIs directly when you need lower-level control. > [card] [TypeScript SDK](/getting-started/typescript) > > Build services, bots, scripts, and applications with `@polymarket/client`. > [card] [Python SDK](/getting-started/python) > > Build services, notebooks, scripts, and data workflows with > `polymarket-client`. > [card] [API](/getting-started/api) > > Build directly against Polymarket REST APIs and WebSocket streams. > [!NOTE] > > A unified Rust SDK is in development. For now, see the [Rust migration > guide](/migrate/clob-sdk-to-unified-sdk#rust). ## Compare Options | | TypeScript SDK | Python SDK | API | | - | - | - | - | | Best for | Node.js applications, bots, and services | Services, scripts, and notebooks | Unsupported runtimes and low-level control | | Data models | Typed models | Typed models | Raw JSON | | Polymarket surfaces | One client interface | One client interface | Service-specific APIs | | Authentication and signing | SDK helpers | SDK helpers | Implement directly | | Pagination | Consistent paginator | Consistent paginator | Varies by API | | Realtime | SDK subscriptions | SDK subscriptions | Connect to each WebSocket surface | ## Existing Integrations Already using an earlier Polymarket SDK? Follow the [SDK migration guide](/migrate/clob-sdk-to-unified-sdk) to update your integration. # TypeScript SDK Source: https://docs.polymarket.com/getting-started/typescript Get started with the unified Polymarket TypeScript SDK. The `@polymarket/client` NPM package is the official TypeScript SDK for building Polymarket integrations. With this SDK client you can fetch market data, subscribe to real-time data, submit orders, redeem positions and many other actions. > [card] [GitHub](https://github.com/Polymarket/ts-sdk) > > View the TypeScript SDK source. > [card] [NPM Package](https://www.npmjs.com/package/@polymarket/client) > > Install `@polymarket/client@latest`. See the [SDK Changelog](/changelog/sdks#typescript) for recent TypeScript releases. ## Quickstart **1. Install the SDK** Install the SDK with your preferred package manager. ```bash npm theme={null} npm install @polymarket/client@latest ``` ```bash bun theme={null} bun add @polymarket/client@latest ``` ```bash pnpm theme={null} pnpm add @polymarket/client@latest ``` ```bash yarn theme={null} yarn add @polymarket/client@latest ``` **2. Create a Public Client** Create a `PublicClient` to access publicly available Polymarket data. ```ts theme={null} import { createPublicClient } from "@polymarket/client"; const client = createPublicClient(); ``` **3. Fetch Active Markets** Fetch a page of active markets to discover trading opportunities. ```ts theme={null} const pages = client.listMarkets({ closed: false, pageSize: 5, }); const firstPage = await pages.firstPage(); for (const market of firstPage.items) { // market: Market } ``` ## Pagination SDK list methods use a consistent paginator interface. Iterate with `for await` to retrieve every page, or fetch one page at a time when you need to control pacing. Creating a paginator is synchronous. `firstPage()` returns a promise that resolves to a page, and `for await` retrieves pages asynchronously. ```ts theme={null} const pages = client.listMarkets({ closed: false, pageSize: 10, }); for await (const page of pages) { for (const market of page.items) { // market: Market } } ``` `page.nextCursor` is an opaque SDK cursor. Store it as-is if you want to resume a scan later, and omit it when starting from the first page. ```ts theme={null} const pages = client.listMarkets({ closed: false, pageSize: 10, }); const page = await pages.firstPage(); if (page.nextCursor) { const secondPage = await pages.from(page.nextCursor).firstPage(); // secondPage.items: Market[] } ``` ## Types SDK methods return typed responses, and their public types are exported from `@polymarket/client`. ```ts theme={null} import type { Event, Market, OrderBook, PriceHistoryPoint, } from "@polymarket/client"; ``` The SDK also uses branded types for identifiers, decimal values, timestamps, and EVM addresses so TypeScript can distinguish values that would otherwise all be strings. ```ts theme={null} import type { ConditionId, DecimalString, EvmAddress, IsoDateTimeString, MarketId, PositionId, TokenId, } from "@polymarket/client"; ``` ## Error Handling Each SDK action exposes a matching error guard. Use it to handle documented errors for that action and rethrow anything unexpected. ```ts theme={null} import { ListMarketsError } from "@polymarket/client"; try { const page = await client.listMarkets({ closed: false }).firstPage(); // page.items: Market[] } catch (error) { if (!ListMarketsError.isError(error)) { throw error; } switch (error.name) { case "RateLimitError": // Retry later. break; case "UserInputError": // Fix the request parameters. break; } } ``` ## Wallet Integrations Create a `SecureClient` when your integration needs to trade or access account data. Pass the signer adapter for your wallet library to `createSecureClient()`. > [tab] Viem > > Install the Viem adapter alongside the SDK. > > ```bash npm theme={null} > npm install @polymarket/client@latest viem > ``` > > ```bash bun theme={null} > bun add @polymarket/client@latest viem > ``` > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest viem > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest viem > ``` > > Create the signer directly from a private key: > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > }); > ``` > > If your application already has a Viem `WalletClient` instance, adapt it with > `signerFrom()`: > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { signerFrom } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: signerFrom(walletClient), > }); > ``` > [tab] Privy > > Install the Privy adapter and server SDK alongside the Polymarket SDK. > > ```bash npm theme={null} > npm install @polymarket/client@latest @privy-io/node > ``` > > ```bash bun theme={null} > bun add @polymarket/client@latest @privy-io/node > ``` > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest @privy-io/node > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest @privy-io/node > ``` > > Create the signer from your Privy client and wallet ID: > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { signerFrom } from "@polymarket/client/privy"; > import { PrivyClient } from "@privy-io/node"; > > const privy = new PrivyClient({ > appId: process.env.PRIVY_APP_ID!, > appSecret: process.env.PRIVY_APP_SECRET!, > }); > > const client = await createSecureClient({ > signer: signerFrom({ > privy, > walletId: process.env.PRIVY_WALLET_ID!, > }), > }); > ``` > [tab] Ethers v5 > > Install the Ethers v5 adapter and its aliased dependency alongside the SDK. > > ```bash npm theme={null} > npm install @polymarket/client@latest ethers-v5@npm:ethers@^5.8.0 > ``` > > ```bash bun theme={null} > bun add @polymarket/client@latest ethers-v5@npm:ethers@^5.8.0 > ``` > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest ethers-v5@npm:ethers@^5.8.0 > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest ethers-v5@npm:ethers@^5.8.0 > ``` > > Create the signer from an Ethers v5 wallet: > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { signerFrom } from "@polymarket/client/ethers-v5"; > import { ethers } from "ethers-v5"; > > const provider = new ethers.providers.JsonRpcProvider( > process.env.POLYGON_RPC_URL, > ); > const wallet = new ethers.Wallet(process.env.POLYMARKET_PRIVATE_KEY!, provider); > > const client = await createSecureClient({ > signer: signerFrom(wallet), > }); > ``` Continue to [Wallets and Authentication](/trading/wallets-auth) to configure the account wallet and gasless transactions. ## Realtime Subscriptions The SDK can combine updates from multiple realtime feeds into a single stream of events. Call `subscribe()` with one or more subscription specs. Public streams are available on both `PublicClient` and `SecureClient`. A `SecureClient` also provides private streams for the connected account. ```ts Public Client theme={null} const assetId = ""; const stream = await client.subscribe([ { topic: "market", assetIds: [assetId] }, { topic: "sports" }, ]); for await (const event of stream) { // event: // | MarketBookEvent // | MarketPriceChangeEvent // | MarketLastTradePriceEvent // | MarketTickSizeChangeEvent // | SportsEvent if (shouldClose) { await stream.close(); break; } } ``` ```ts Secure Client theme={null} const assetId = ""; const stream = await client.subscribe([ { topic: "market", assetIds: [assetId] }, { topic: "user" }, ]); for await (const event of stream) { // event: // | MarketBookEvent // | MarketPriceChangeEvent // | MarketLastTradePriceEvent // | MarketTickSizeChangeEvent // | UserEvent if (shouldClose) { await stream.close(); break; } } ``` Narrow `event.topic` before handling a specific event shape. The examples show a few streams; see [Real-Time Data](/market-data/realtime-data), [Real-Time Order Updates](/trading/realtime-order-updates), and [Perps Realtime Updates](/perps/realtime-updates) for feed-specific options. ## Next Steps > [card] [Read Market Data](/market-data/overview) > > Discover markets and work with prices, order books, and historical data. > [card] [Subscribe to Real-Time Updates](/market-data/realtime-data) > > Stream market and account updates as they happen. > [card] [Place Your First Order](/trading/quickstart) > > Set up an account and complete your first authenticated trade. > [card] [Use Session Keys](/trading/session-keys) > > Grant scoped, time-limited Deposit Wallet access to a separate signer. # Overview Source: https://docs.polymarket.com/index Build on the world's largest prediction market. Trade, integrate, and access real-time market data with the Polymarket API. 🇺🇸 Looking for Polymarket US documentation? Visit US Docs → [Open](https://docs.polymarket.us) # Polymarket Documentation Build on the world's largest prediction market. APIs, SDKs, and tools for prediction market developers. ## Developer Quickstart Make your first API request in minutes. Learn the basics of the Polymarket platform, fetch market data, place orders, and redeem winning positions. [Place Your First Order →](/trading/quickstart) ```typescript TypeScript theme={null} import { createPublicClient } from "@polymarket/client"; const client = createPublicClient(); const pages = client.listMarkets({ closed: false }); const { items: markets } = await pages.firstPage(); ``` ```python Python theme={null} from polymarket import AsyncPublicClient async with AsyncPublicClient() as client: markets = client.list_markets(closed=False) async for market in markets.iter_items(): print(market.question) ``` ```bash API theme={null} curl -G "https://gamma-api.polymarket.com/markets/keyset" \ --data-urlencode "closed=false" \ --data-urlencode "limit=5" ``` ## Get Familiar with Polymarket Learn how Polymarket works, explore the concepts behind markets and trading, or choose how to integrate. > [card] [Polymarket 101](/polymarket-101) > > Learn how prediction markets work and how to use Polymarket. > [card] [Core Concepts](/concepts/markets-events) > > Understand markets and events, prices and order books, positions, > orders, and resolution. > [card] [SDKs & APIs](/getting-started/sdks-apis) > > Choose the integration approach that best fits your application. [![Banner](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/banner.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=d83f2f21e8474e998d8ba0f45810d978)](https://builders.polymarket.com) ![](/images/icons/medal.svg) ### [Builder Program](https://builders.polymarket.com) Build apps on Polymarket and earn rewards for driving volume ![](/images/icons/quiz.svg) ### [Help Desk](https://help.polymarket.com) Get support, report issues, and find answers to common questions ![](/images/icons/sensor.svg) ### [Status](https://status.polymarket.com) Check API uptime, service health, and incident reports # Discover Markets Source: https://docs.polymarket.com/market-data/discover-markets Learn how to find and filter events and markets and explore related metadata. Find the events and markets your integration needs, from a specific Polymarket link to a broader view of what is active. This data is public and does not require authentication. ## Events An event groups one or more markets under a shared question set. A single-market event asks one yes/no question; a multi-market event splits a broader question into individual outcomes, such as one market per candidate in an election. ### Fetch an Event Fetch an event when you already know its identifier. > [tab] TypeScript > > Call `fetchEvent()` on a `PublicClient` or `SecureClient` to fetch an event by ID. > > ```ts theme={null} > const event = await client.fetchEvent({ id: "90177" }); > > // event: Event > ``` > > You can also fetch an event by its Polymarket URL or slug: > > ```ts URL theme={null} > const event = await client.fetchEvent({ > url: "https://polymarket.com/event/will-the-us-confirm-that-aliens-exist-before-2027", > }); > ``` > > ```ts Slug theme={null} > const event = await client.fetchEvent({ > slug: "will-the-us-confirm-that-aliens-exist-before-2027", > }); > ``` > > > [accordion] Output: Event > > > > ```ts Event Type theme={null} > > type Market = { > > id: string; > > version?: ProtocolVersion | null; > > slug?: string | null; > > question?: string | null; > > conditionId: ConditionId | null; > > outcomes: { > > yes: { tokenId: TokenId | null; positionId: PositionId | null }; > > no: { tokenId: TokenId | null; positionId: PositionId | null }; > > }; > > }; > > > > type Event = { > > id: string; > > slug?: string | null; > > title?: string | null; > > markets: Market[]; > > }; > > ``` > > > > ```json Event Example (Polymarket V2) theme={null} > > { > > "id": "", > > "slug": "", > > "title": "", > > "markets": [ > > { > > "id": "1", > > "version": "v2", > > "slug": "", > > "question": "", > > "conditionId": "0x017089ce3ba22aaa0a4cba8250b8c8e1eb0000000000000000000000000000", > > "outcomes": { > > "yes": { > > "tokenId": null, > > "positionId": "651150819117105875331414918119047680898421632356043490229292782433651916800" > > }, > > "no": { > > "tokenId": null, > > "positionId": "651150819117105875331414918119047680898421632356043490229292782433651916801" > > } > > } > > } > > ] > > } > > ``` > > > > ```json Event Example (CTF) theme={null} > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?", > > "markets": [ > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "outcomes": { > > "yes": { > > "tokenId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "positionId": null > > }, > > "no": { > > "tokenId": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "positionId": null > > } > > } > > }, > > "..." > > ] > > } > > ``` > [tab] Python > > Call `get_event()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch an event by ID. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > event = await client.get_event(id="90177") > > # event: Event > ``` > > You can also fetch an event by its Polymarket URL or slug: > > ```python URL theme={null} > event = await client.get_event( > url="https://polymarket.com/event/will-the-us-confirm-that-aliens-exist-before-2027", > ) > ``` > > ```python Slug theme={null} > event = await client.get_event( > slug="will-the-us-confirm-that-aliens-exist-before-2027", > ) > ``` > > > [accordion] Output: Event > > > > ```python Event Type theme={null} > > class MarketOutcome: > > token_id: TokenId | None > > position_id: PositionId | None > > > > class MarketOutcomes: > > yes: MarketOutcome > > no: MarketOutcome > > > > class Market: > > id: str > > version: ProtocolVersion | None > > slug: str | None > > question: str | None > > condition_id: ConditionId | None > > outcomes: MarketOutcomes > > > > class Event: > > id: str > > slug: str | None > > title: str | None > > markets: tuple[Market, ...] > > ``` > > > > ```json Event Example (Polymarket V2) theme={null} > > { > > "id": "", > > "slug": "", > > "title": "", > > "markets": [ > > { > > "id": "1", > > "version": "v2", > > "slug": "", > > "question": "", > > "condition_id": "0x017089ce3ba22aaa0a4cba8250b8c8e1eb0000000000000000000000000000", > > "outcomes": { > > "yes": { > > "token_id": null, > > "position_id": "651150819117105875331414918119047680898421632356043490229292782433651916800" > > }, > > "no": { > > "token_id": null, > > "position_id": "651150819117105875331414918119047680898421632356043490229292782433651916801" > > } > > } > > } > > ] > > } > > ``` > > > > ```json Event Example (CTF) theme={null} > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?", > > "markets": [ > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "outcomes": { > > "yes": { > > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "position_id": null > > }, > > "no": { > > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "position_id": null > > } > > } > > }, > > "..." > > ] > > } > > ``` > [tab] API > > Fetch an event by ID: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/90177" > ``` > > You can also fetch an event by slug: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/slug/will-the-us-confirm-that-aliens-exist-before-2027" > ``` > > > [accordion] Output: Event > > > > ```ts Event Type theme={null} > > type Market = { > > id: string; > > version: string | null; > > slug: string; > > question: string | null; > > conditionId: string | null; > > clobTokenIds: string | null; > > positionIds: string[] | null; > > }; > > > > type Event = { > > id: string; > > slug: string | null; > > title: string | null; > > markets: Market[]; > > }; > > ``` > > > > ```json Event Example (Polymarket V2) theme={null} > > { > > "id": "", > > "slug": "", > > "title": "", > > "markets": [ > > { > > "id": "1", > > "version": "v2", > > "slug": "", > > "question": "", > > "conditionId": "0x017089ce3ba22aaa0a4cba8250b8c8e1eb0000000000000000000000000000", > > "clobTokenIds": null, > > "positionIds": [ > > "651150819117105875331414918119047680898421632356043490229292782433651916800", > > "651150819117105875331414918119047680898421632356043490229292782433651916801" > > ] > > } > > ] > > } > > ``` > > > > ```json Event Example (CTF) theme={null} > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?", > > "markets": [ > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "clobTokenIds": "[\"107505882767731489358349912513945399560393482969656700824895970500493757150417\",\"7305630249804085635496399869905769372294302716159034447326228509068694952392\"]", > > "positionIds": null > > }, > > "..." > > ] > > } > > ``` ### List Events List events when you need a browsable or filterable feed. > [tab] TypeScript > > Call `listEvents()` on a `PublicClient` or `SecureClient` to page through events. > > ```ts theme={null} > const pages = client.listEvents({ closed: false, pageSize: 20 }); > > for await (const page of pages) { > // page.items: Event[] > } > ``` > > > [accordion] Output: Event\[] > > > > ```ts Page Type theme={null} > > type Market = { > > id: string; > > slug?: string | null; > > question?: string | null; > > conditionId: string | null; > > }; > > > > type Event = { > > id: string; > > slug?: string | null; > > title?: string | null; > > markets: Market[]; > > }; > > > > type Page = { > > items: Event[]; > > hasMore: boolean; > > nextCursor?: string; > > }; > > ``` > > > > ```json Page Example theme={null} > > { > > "items": [ > > { > > "id": "16183", > > "slug": "kraken-ipo-in-2025", > > "title": "Kraken IPO by ___ ?", > > "markets": [ > > { > > "id": "516950", > > "slug": "kraken-ipo-in-2025", > > "question": "Kraken IPO in 2025?" > > }, > > "..." > > ] > > }, > > { > > "id": "16263", > > "slug": "macron-out-in-2025", > > "title": "Macron out by...?", > > "markets": ["..."] > > }, > > "..." > > ], > > "hasMore": true, > > "nextCursor": "9YTr9qyfU9571U9_leL7LNSWUI6EXd7rpAqdh-EbPr17InYiOjEsImsiOiJldmVudHMiLCJvaCI6IjRmNTNjZGExOGMyYmFhMGMwMzU0YmI1ZjlhM2VjYmU1ZWQxMmFiNGQ4ZTExYmE4NzNjMmYxMTE2MTIwMmI5NDUiLCJrZXlzIjpbeyJ0Ijoic3RyaW5nIiwidiI6IjI1ODE1In1dfQ" > > } > > ``` > > Filter by tag by passing one or more numeric tag IDs: > > ```ts theme={null} > const pages = client.listEvents({ > tagIds: [745], // numeric ID for the "nba" tag; see Tags below to look these up > closed: false, > }); > > for await (const page of pages) { > // page.items: Event[] > } > ``` > [tab] Python > > Call `list_events()` on an `AsyncPublicClient` or `AsyncSecureClient` to page through events. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > pages = client.list_events(closed=False, page_size=20) > > async for page in pages: > ... # page.items: tuple[Event, ...] > ``` > > > [accordion] Output: Event\[] > > > > ```python Page Type theme={null} > > class Market: > > id: str > > slug: str | None > > question: str | None > > condition_id: str | None > > > > class Event: > > id: str > > slug: str | None > > title: str | None > > markets: tuple[Market, ...] > > > > class Page: > > items: tuple[Event, ...] > > has_more: bool > > next_cursor: str | None > > ``` > > > > ```json Page Example theme={null} > > { > > "items": [ > > { > > "id": "16183", > > "slug": "kraken-ipo-in-2025", > > "title": "Kraken IPO by ___ ?" > > }, > > { > > "id": "16263", > > "slug": "macron-out-in-2025", > > "title": "Macron out by...?" > > }, > > "..." > > ], > > "has_more": true, > > "next_cursor": "eyJmIjoiYWQyZjRkNmY4ZDZkIiwiayI6IjlZVHI5cXlmVTk1NzFVOV9sZUw3TE5TV1VJNkVYZDdycEFxZGgtRWJQcjE3SW5ZaU9qRXNJbXNpT2lKbGRtVnVkSE1pTENKdmFDSTZJalJtTlROalpHRXhPR015WW1GaE1HTXdNelUwWW1JMVpqbGhNMlZqWW1VMVpXUXhNbUZpTkdRNFpURXhZbUU0TnpOak1tWXhNVEUyTVRJd01tSTVORFVpTENKclpYbHpJanBiZXlKMElqb2ljM1J5YVc1bklpd2lkaUk2SWpJMU9ERTFJbjFkZlEiLCJwIjoiL2V2ZW50cy9rZXlzZXQiLCJzdmMiOiJnYW1tYSIsInYiOjF9" > > } > > ``` > > Filter by tag by passing a numeric tag ID: > > ```python theme={null} > pages = client.list_events( > tag_ids=[745], # numeric ID for the "nba" tag; see Tags below to look these up > closed=False, > ) > > async for page in pages: > ... # page.items: tuple[Event, ...] > ``` > [tab] API > > List active events: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?closed=false&limit=20" > ``` > > > [accordion] Output: Events Page > > > > ```json Example theme={null} > > { > > "events": [ > > { > > "id": "16183", > > "slug": "kraken-ipo-in-2025", > > "title": "Kraken IPO by ___ ?" > > }, > > "..." > > ], > > "next_cursor": "9YTr9qyfU9571U9_leL7LNSWUI6EXd7rpAqdh-EbPr17InYiOjEsImsiOiJldmVudHMiLCJvaCI6IjRmNTNjZGExOGMyYmFhMGMwMzU0YmI1ZjlhM2VjYmU1ZWQxMmFiNGQ4ZTExYmE4NzNjMmYxMTE2MTIwMmI5NDUiLCJrZXlzIjpbeyJ0Ijoic3RyaW5nIiwidiI6IjI1ODE1In1dfQ" > > } > > ``` > > Pass `next_cursor` as `after_cursor` to fetch the next page: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?closed=false&limit=20&after_cursor=" > ``` > > Filter by tag with `tag_id`: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?tag_id=745&closed=false&limit=20" > ``` > > On `GET /events` and `GET /events/keyset`, omitting `closed` returns open and closed events. `closed=true` selects closed events and `closed=false` selects open events. `closed=any` (case-insensitive) also includes both states, with no identifier filter required. ### Filter Events by Protocol Select events for the position system your integration handles. > [tab] TypeScript > > Call `listEvents()` on an existing `PublicClient` or `SecureClient`. > If needed, [create a Public Client](/getting-started/typescript#create-a-public-client) first. > > ```ts theme={null} > import { ProtocolVersion } from "@polymarket/client"; > > const pages = client.listEvents({ > version: ProtocolVersion.V2, > closed: false, > pageSize: 20, > }); > > for await (const page of pages) { > // page.items: Event[] > } > ``` > > Use `ProtocolVersion.V2` for Polymarket Protocol V2 events or > `ProtocolVersion.V1` for CTF events. To include both, pass > `version: [ProtocolVersion.V1, ProtocolVersion.V2]`. Arrays accept one or > two values. Omission uses the current server default of CTF events (v1). > The paginator keeps the > filter on subsequent pages. When resuming with `cursor`, pass the same > `version`. > [tab] Python > > Call `list_events()` on an existing `AsyncPublicClient` or > `AsyncSecureClient`. If needed, > [create a Public Client](/getting-started/python#create-a-public-client) first. > Sync clients expose the same option. > > ```python theme={null} > pages = client.list_events(version="v2", closed=False, page_size=20) > > async for page in pages: > # page.items: tuple[Event, ...] > pass > ``` > > Use `version="v2"` for Polymarket Protocol V2 events or `version="v1"` > for CTF events. To include both, pass `version=["v1", "v2"]`. The option > accepts a string, a `ProtocolVersion` enum value, or a sequence of one or > two values. Omission or `None` uses the current server default of CTF > events (v1). The paginator keeps the filter on subsequent pages. To resume, > create `pages` with the same `version` and other filters, then continue > with the paginator returned by `pages.from_cursor(saved_cursor)`. > [tab] API > > List Polymarket Protocol V2 events: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?version=v2&closed=false&limit=20" > ``` > > Illustrative response (fields trimmed): > > > [accordion] Output: Events Page > > > > ```json theme={null} > > { > > "events": [ > > { > > "id": "12345", > > "slug": "example-v2-event", > > "title": "Example Protocol V2 Event" > > } > > ], > > "next_cursor": "" > > } > > ``` > > Use `version=v1` for CTF events. Repeat the parameter as > `version=v1&version=v2` to include both. Each value must be `v1` or `v2`, > with at most two values. Omission uses the current server default of CTF > events (v1). > Continue with `next_cursor` as `after_cursor`, keeping the same `version` > and other filters: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?version=v2&closed=false&limit=20&after_cursor=" > ``` ## Markets A market is a single yes/no question with two outcome IDs, one for YES and one for NO. ### Fetch a Market Fetch a market when you already know its identifier. > [tab] TypeScript > > Call `fetchMarket()` on a `PublicClient` or `SecureClient` to fetch a market by ID. > > ```ts theme={null} > const market = await client.fetchMarket({ id: "703257" }); > > // market: Market > ``` > > You can also fetch a market by its Polymarket URL or slug: > > ```ts URL theme={null} > const market = await client.fetchMarket({ > url: "https://polymarket.com/market/will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > }); > ``` > > ```ts Slug theme={null} > const market = await client.fetchMarket({ > slug: "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > }); > ``` > > > [accordion] Output: Market > > > > ```ts Market Type theme={null} > > type Market = { > > id: string; > > version?: ProtocolVersion | null; > > slug?: string | null; > > question?: string | null; > > conditionId: ConditionId | null; > > outcomes: { > > yes: { tokenId: TokenId | null; positionId: PositionId | null }; > > no: { tokenId: TokenId | null; positionId: PositionId | null }; > > }; > > }; > > ``` > > > > ```json Market Example theme={null} > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "outcomes": { > > "yes": { > > "tokenId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "positionId": null > > }, > > "no": { > > "tokenId": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "positionId": null > > } > > } > > } > > ``` > [tab] Python > > Call `get_market()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch a market by ID. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > market = await client.get_market(id="703257") > > # market: Market > ``` > > You can also fetch a market by its Polymarket URL or slug: > > ```python URL theme={null} > market = await client.get_market( > url="https://polymarket.com/market/will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > ) > ``` > > ```python Slug theme={null} > market = await client.get_market( > slug="will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > ) > ``` > > > [accordion] Output: Market > > > > ```python Market Type theme={null} > > class MarketOutcome: > > token_id: TokenId | None > > position_id: PositionId | None > > > > class MarketOutcomes: > > yes: MarketOutcome > > no: MarketOutcome > > > > class Market: > > id: str > > version: ProtocolVersion | None > > slug: str | None > > question: str | None > > condition_id: ConditionId | None > > outcomes: MarketOutcomes > > ``` > > > > ```json Market Example theme={null} > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "outcomes": { > > "yes": { > > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "position_id": null > > }, > > "no": { > > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "position_id": null > > } > > } > > } > > ``` > [tab] API > > Fetch a market by ID: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/703257" > ``` > > You can also fetch a market by slug: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/slug/will-the-us-confirm-that-aliens-exist-before-2027-789-924-249" > ``` > > > [accordion] Output: Market > > > > ```json Example theme={null} > > { > > "id": "703257", > > "version": "v1", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > > "question": "Will the US confirm that aliens exist before 2027?", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "clobTokenIds": "[\"107505882767731489358349912513945399560393482969656700824895970500493757150417\",\"7305630249804085635496399869905769372294302716159034447326228509068694952392\"]", > > "positionIds": null > > } > > ``` ### List Markets List markets when you need a filterable feed, such as browsing by tag, sport, or liquidity. > [tab] TypeScript > > Call `listMarkets()` on a `PublicClient` or `SecureClient` to page through markets. > > ```ts theme={null} > const pages = client.listMarkets({ > tagId: 745, // numeric ID for the "nba" tag; see Tags below to look these up > closed: false, > pageSize: 20, > }); > > for await (const page of pages) { > // page.items: Market[] > } > ``` > > > [accordion] Output: Market\[] > > > > ```json Example theme={null} > > [ > > { > > "id": "741099", > > "slug": "will-lebron-james-retire-before-next-nba-season", > > "question": "Will LeBron James retire before next NBA season?", > > "conditionId": "0x73057b771600660ac6e659c5b831587fd3bdd378e63f359731aa3e1538577fb0" > > }, > > { > > "id": "1747460", > > "slug": "will-giannis-antetokounmpo-play-for-the-atlanta-hawks-in-2026-27", > > "question": "Will Giannis Antetokounmpo play for the Atlanta Hawks in 2026-27?", > > "conditionId": "0xff2715084bb2cf20d9b88b74ef809c3317b1e99f6c006faee9b83bc85aa0fc99" > > }, > > "..." > > ] > > ``` > [tab] Python > > Call `list_markets()` on an `AsyncPublicClient` or `AsyncSecureClient` to page through markets. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > pages = client.list_markets( > tag_id=745, # numeric ID for the "nba" tag; see Tags below to look these up > closed=False, > page_size=20, > ) > > async for page in pages: > ... # page.items: tuple[Market, ...] > ``` > > > [accordion] Output: Market\[] > > > > ```json Example theme={null} > > [ > > { > > "id": "741099", > > "slug": "will-lebron-james-retire-before-next-nba-season", > > "question": "Will LeBron James retire before next NBA season?", > > "condition_id": "0x73057b771600660ac6e659c5b831587fd3bdd378e63f359731aa3e1538577fb0" > > }, > > { > > "id": "1747460", > > "slug": "will-giannis-antetokounmpo-play-for-the-atlanta-hawks-in-2026-27", > > "question": "Will Giannis Antetokounmpo play for the Atlanta Hawks in 2026-27?", > > "condition_id": "0xff2715084bb2cf20d9b88b74ef809c3317b1e99f6c006faee9b83bc85aa0fc99" > > }, > > "..." > > ] > > ``` > [tab] API > > List active markets by tag: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/keyset?tag_id=745&closed=false&limit=20" > ``` > > > [accordion] Output: Markets Page > > > > ```json Example theme={null} > > { > > "markets": [ > > { > > "id": "540817", > > "slug": "new-rhianna-album-before-gta-vi-926", > > "question": "New Rihanna Album before GTA VI?", > > "conditionId": "0x1fad72fae204143ff1c3035e99e7c0f65ea8d5cd9bd1070987bd1a3316f772be" > > }, > > "..." > > ], > > "next_cursor": "8ejWEAtEdA8gG05m-tRMeLtBDl1Wbw1fUbXVfm0eYSZ7InYiOjEsImsiOiJtYXJrZXRzIiwib2giOiI0ZjUzY2RhMThjMmJhYTBjMDM1NGJiNWY5YTNlY2JlNWVkMTJhYjRkOGUxMWJhODczYzJmMTExNjEyMDJiOTQ1Iiwia2V5cyI6W3sidCI6InN0cmluZyIsInYiOiI1NTg5NDAifV19" > > } > > ``` > > Pass `next_cursor` as `after_cursor` to fetch the next page: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/keyset?tag_id=745&closed=false&limit=20&after_cursor=" > ``` > > To look up markets without knowing whether they are open or closed, pass an identifier and `closed=any`: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/keyset?id=540817&closed=any&limit=20" > ``` > > On `GET /markets` and `GET /markets/keyset`, omitted `closed` and `closed=false` return open markets; `closed=true` selects closed markets. `closed=any` (case-insensitive) removes that filter and requires at least one of `id`, `slug`, `clob_token_ids`, `position_ids`, `condition_ids`, `request_ids`, `onchain_event_ids`, or `question_ids`. Each identifier filter accepts at most 100 values. Other filters still apply. > > `closed=any` without an identifier, including a request with only `tag_id`, returns HTTP 422. An invalid `closed` value also returns HTTP 422. After you choose a market, continue to [Market Details](/market-data/market-details) to select its outcome IDs and trading fields. ### Find Markets by Oracle Request Use a known oracle request or on-chain event to find related Polymarket Protocol V2 markets, or filter by their resolution state when building a settlement view. > [tab] TypeScript > > Call `listMarkets()` on a `PublicClient` or `SecureClient`. Start with the > resolution state you want to follow. > > ```ts theme={null} > import { MarketResolutionStatus, ProtocolVersion } from "@polymarket/client"; > > const pages = client.listMarkets({ > version: ProtocolVersion.V2, > resolutionStatus: MarketResolutionStatus.Active, > }); > > for await (const page of pages) { > for (const market of page.items) { > console.log( > market.resolution.requestId, > market.resolution.onchainEventId, > market.resolution.resolutionStatus, > ); > } > } > ``` > > To query both protocols, omit the resolution-state filter and pass > `version: [ProtocolVersion.V1, ProtocolVersion.V2]`. > `version` accepts one value or an array of one or two values. Omission uses the > current server default of CTF markets (v1). Keep the same selection when resuming > a cursor. > > `requestId` is the bytes32 oracle key. `onchainEventId` is the parent bytes32 > on-chain event ID with its bottom three bytes zero. Both, and `resolutionStatus`, > can be `null` or absent when metadata is unavailable. > > To narrow a subsequent read, pass `requestIds: [requestId]` or > `onchainEventIds: [onchainEventId]` when you have a returned non-null ID. Each > filter accepts at most 100 values and is retained across pages. > [tab] Python > > Call `list_markets()` on an `AsyncPublicClient` or `AsyncSecureClient`. > The synchronous clients provide the same filters. > > ```python theme={null} > pages = client.list_markets(version="v2", resolution_status="active") > > async for page in pages: > for market in page.items: > print( > market.resolution.request_id, > market.resolution.onchain_event_id, > market.resolution.resolution_status, > ) > ``` > > To query both protocols, omit the resolution-state filter and pass > `version=["v1", "v2"]`. `version` accepts one > string or enum value, or a sequence of one or two values. Omission or `None` uses > the current server default of CTF markets (v1). Keep the same selection when > resuming with `pages.from_cursor(saved_cursor)`. > > `request_id` is the bytes32 oracle key. `onchain_event_id` is the parent bytes32 > on-chain event ID with its bottom three bytes zero. Both, and > `resolution_status`, are `None` when metadata is unavailable. > > To narrow a subsequent read, pass `request_ids=[request_id]` or > `onchain_event_ids=[onchain_event_id]` when you have a returned non-`None` ID. > Each filter accepts at most 100 values and is retained across pages. > [tab] API > > Filter the market collection by protocol version and resolution state. > > ```bash theme={null} > curl -G "https://gamma-api.polymarket.com/markets/keyset" \ > --data-urlencode "version=v2" \ > --data-urlencode "resolution_status=active" > ``` > > Illustrative response (fields trimmed): > > > [accordion] Output: Markets Page > > > > ```json theme={null} > > { > > "markets": [ > > { > > "id": "12345", > > "slug": "example-v2-market", > > "question": "Will Team A win?", > > "version": "v2", > > "requestId": "0xcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd00", > > "onchainEventId": "0xababababababababababababababababababababababababababababab000000", > > "resolutionStatus": "active" > > } > > ], > > "next_cursor": "" > > } > > ``` > > Omit `resolution_status` and repeat `version` as `version=v1&version=v2` to > query both protocols. Each > value must be `v1` or `v2`, with at most two values. Omission uses the current > server default of CTF markets (v1). Keep the same selection when continuing with > `after_cursor`. > > Response markets can include `requestId`, `onchainEventId`, and > `resolutionStatus`. `requestId` is the bytes32 oracle key. `onchainEventId` is > the parent bytes32 on-chain event ID with its bottom three bytes zero. > > Filter by a known ID with `request_ids=` or > `onchain_event_ids=`. Repeat the query parameter for multiple > IDs, up to 100 per filter, and preserve these filters when continuing with > `after_cursor`. The resolution states are `inactive` (drafted, not deployed on chain), `active` (deployed, unresolved), and `resolved`. This state belongs to Polymarket Protocol V2 markets. CTF markets retain their UMA resolution status. An oracle request identifies one binary or incremental neg-risk market by its condition ID, or an atomic neg-risk event by its on-chain event ID. Markets in one on-chain event share the parent event ID. ## Series A series groups a recurring set of events under one theme. For example, a weekly Fed rate-decision series has one event per meeting, and a season-long league series has one event per matchup. ### Fetch a Series Fetch a series by ID. > [tab] TypeScript > > Call `fetchSeries()` on a `PublicClient` or `SecureClient` to fetch a series by ID. > > ```ts theme={null} > const series = await client.fetchSeries({ id: "1" }); > > // series: Series > ``` > > > [accordion] Output: Series > > > > ```json Example theme={null} > > { > > "id": "1", > > "slug": "nfl", > > "title": "NFL", > > "recurrence": "weekly", > > "closed": false > > } > > ``` > [tab] Python > > Call `get_series()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch a series by ID. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > series = await client.get_series("1") > > # series: Series > ``` > > > [accordion] Output: Series > > > > ```json Example theme={null} > > { > > "id": "1", > > "slug": "nfl", > > "title": "NFL", > > "recurrence": "weekly", > > "closed": false > > } > > ``` > [tab] API > > Fetch a series by ID: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/series/1" > ``` > > > [accordion] Output: Series > > > > ```json Example theme={null} > > { > > "id": "1", > > "slug": "nfl", > > "title": "NFL", > > "recurrence": "weekly", > > "closed": false > > } > > ``` ### List Series > [tab] TypeScript > > Call `listSeries()` on a `PublicClient` or `SecureClient` to page through series. > > ```ts theme={null} > const pages = client.listSeries({ > recurrence: "weekly", > closed: false, > pageSize: 20, > }); > > for await (const page of pages) { > // page.items: Series[] > } > ``` > > > [accordion] Output: Series\[] > > > > ```json Example theme={null} > > [ > > { "id": "1", "slug": "nfl", "title": "NFL" }, > > { "id": "2", "slug": "nba", "title": "NBA" }, > > { "id": "3", "slug": "mlb", "title": "MLB" }, > > "..." > > ] > > ``` > [tab] Python > > Call `list_series()` on an `AsyncPublicClient` or `AsyncSecureClient` to page through series. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > pages = client.list_series( > recurrence="weekly", > closed=False, > page_size=20, > ) > > async for page in pages: > ... # page.items: tuple[Series, ...] > ``` > > > [accordion] Output: Series\[] > > > > ```json Example theme={null} > > [ > > { "id": "1", "slug": "nfl", "title": "NFL" }, > > { "id": "2", "slug": "nba", "title": "NBA" }, > > { "id": "3", "slug": "mlb", "title": "MLB" }, > > "..." > > ] > > ``` > [tab] API > > List active weekly series: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/series?recurrence=weekly&closed=false&limit=20" > ``` > > > [accordion] Output: Series\[] > > > > ```json Example theme={null} > > [ > > { "id": "1", "slug": "nfl", "title": "NFL" }, > > { "id": "2", "slug": "nba", "title": "NBA" }, > > { "id": "3", "slug": "mlb", "title": "MLB" }, > > "..." > > ] > > ``` ## Sports Sports metadata maps a sport to its Polymarket tags and market types. Use it to browse sports markets by league, look up the valid market types for filtering, find events associated with a game, or resolve team rosters. ### List Sports > [tab] TypeScript > > Call `listSports()` on a `PublicClient` or `SecureClient` to list supported sports. > > ```ts theme={null} > const sports = await client.listSports(); > > // sports: SportsMetadata[] > ``` > > > [accordion] Output: SportsMetadata\[] > > > > ```json Example theme={null} > > [ > > { "id": 1, "sport": "ncaab", "tags": "1,100149,100639" }, > > { "id": 2, "sport": "epl", "tags": "1,82,306,100639,100350" }, > > { "id": 3, "sport": "lal", "tags": "1,780,100639,100350" } > > ] > > ``` > [tab] Python > > Call `get_sports()` on an `AsyncPublicClient` or `AsyncSecureClient` to list supported sports. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > sports = await client.get_sports() > > # sports: tuple[SportsMetadata, ...] > ``` > > > [accordion] Output: SportsMetadata\[] > > > > ```json Example theme={null} > > [ > > { "id": 1, "sport": "ncaab", "tags": "1,100149,100639" }, > > { "id": 2, "sport": "epl", "tags": "1,82,306,100639,100350" }, > > { "id": 3, "sport": "lal", "tags": "1,780,100639,100350" } > > ] > > ``` > [tab] API > > List supported sports: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/sports" > ``` > > > [accordion] Output: SportsMetadata\[] > > > > ```json Example theme={null} > > [ > > { "sport": "ncaab", "tags": "1,100149,100639" }, > > { "sport": "epl", "tags": "1,82,306,100639,100350" }, > > { "sport": "lal", "tags": "1,780,100639,100350" } > > ] > > ``` ### Sports Market Types Every sports market carries a market type that tells you which line it prices: a moneyline (which team wins), a spread (win by how much), or a total (over/under a combined score). Fetch the valid values, then pass one or more of them when listing markets to filter. > [tab] TypeScript > > Call `fetchSportsMarketTypes()` on a `PublicClient` or `SecureClient` to list the > supported market types. When present, a market reports its type in > `sports.sportsMarketType`. > > ```ts theme={null} > const { marketTypes } = await client.fetchSportsMarketTypes(); > > // marketTypes: string[] > ``` > > > [accordion] Output: string\[] > > > > ```json Example theme={null} > > { > > "marketTypes": ["moneyline", "spreads", "totals"] > > } > > ``` > > Filter markets by type: > > ```ts theme={null} > const pages = client.listMarkets({ > sportsMarketTypes: ["spreads"], > closed: false, > pageSize: 20, > }); > > for await (const page of pages) { > // page.items: Market[] > } > ``` > [tab] Python > > Call `get_sports_market_types()` on an `AsyncPublicClient` or > `AsyncSecureClient` to list the supported market types. The synchronous > `PublicClient` and `SecureClient` provide the same method. Each market > reports its type in `sports.sports_market_type` when present. > > ```python theme={null} > market_types = await client.get_sports_market_types() > > # market_types.market_types: tuple[str, ...] | None > ``` > > > [accordion] Output: string\[] > > > > ```json Example theme={null} > > { > > "market_types": ["moneyline", "spreads", "totals"] > > } > > ``` > > Filter markets by type: > > ```python theme={null} > pages = client.list_markets( > sports_market_types=["spreads"], > closed=False, > page_size=20, > ) > > async for page in pages: > ... # page.items: tuple[Market, ...] > ``` > [tab] API > > List supported sports market types. When present, a market reports its type in > `sportsMarketType`: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/sports/market-types" > ``` > > > [accordion] Output: string\[] > > > > ```json Example theme={null} > > { > > "marketTypes": ["moneyline", "spreads", "totals"] > > } > > ``` > > Filter markets by type: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/keyset?sports_market_types=spreads&closed=false&limit=20" > ``` ### List Events for a Game A sports game's markets can be split across a main event and companion events. Depending on the game, companion events may cover player props, half-time and second-half results, exact score, or additional lines grouped under a more-markets event. Their slugs extend the main event's slug with a suffix such as `-player-props`, `-halftime-result`, or `-more-markets`. Append a known suffix when you need one companion event. To discover current companion events, use the listing workflow instead of guessing each suffix. > [tab] TypeScript > > Call `fetchEvent()` on a `PublicClient` or `SecureClient`. To fetch only the > more-markets event, append `-more-markets` to the main event's slug. > > ```ts theme={null} > const mainSlug = "mls-chi-vwh-2026-07-16"; > > const moreMarkets = await client.fetchEvent({ > slug: `${mainSlug}-more-markets`, > }); > ``` > > To list the game's current events, fetch the main event and read `sports.gameId`, then > pass it to `listEvents()`. Not every event has a game ID, so check it before filtering. > > ```ts theme={null} > const mainSlug = "mls-chi-vwh-2026-07-16"; > const game = await client.fetchEvent({ slug: mainSlug }); > const gameId = game.sports.gameId; > > if (gameId == null) { > throw new Error("Event does not have a game ID"); > } > > const pages = client.listEvents({ gameIds: [gameId], pageSize: 20 }); > > for await (const page of pages) { > // page.items: Event[] > } > ``` > > > [accordion] Output: Event Page > > > > ```json Example theme={null} > > { > > "items": [ > > { > > "id": "662915", > > "slug": "mls-chi-vwh-2026-07-16", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC" > > }, > > { > > "id": "662970", > > "slug": "mls-chi-vwh-2026-07-16-halftime-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Halftime Result" > > }, > > { > > "id": "662972", > > "slug": "mls-chi-vwh-2026-07-16-second-half-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Second Half Result" > > }, > > { > > "id": "662974", > > "slug": "mls-chi-vwh-2026-07-16-exact-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Exact Score" > > }, > > { > > "id": "662976", > > "slug": "mls-chi-vwh-2026-07-16-first-to-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - First Team to Score" > > }, > > { > > "id": "663131", > > "slug": "mls-chi-vwh-2026-07-16-more-markets", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - More Markets" > > } > > ], > > "hasMore": false > > } > > ``` > > When present, `market.sports.sportsMarketType` identifies lines in the more-markets > event such as `first_half_totals`, `both_teams_to_score`, and `soccer_team_totals`. > [tab] Python > > Call `get_event()` on an `AsyncPublicClient` or `AsyncSecureClient`. To fetch only the > more-markets event, append `-more-markets` to the main event's slug. The synchronous > `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > main_slug = "mls-chi-vwh-2026-07-16" > > more_markets = await client.get_event(slug=f"{main_slug}-more-markets") > ``` > > To list the game's current events, fetch the main event and read `sports.game_id`, then > pass it to `list_events()`. Not every event has a game ID, so check it before filtering. > > ```python theme={null} > main_slug = "mls-chi-vwh-2026-07-16" > game = await client.get_event(slug=main_slug) > game_id = game.sports.game_id > > if game_id is None: > raise ValueError("Event does not have a game ID") > > pages = client.list_events(game_ids=[game_id], page_size=20) > > async for page in pages: > ... # page.items: tuple[Event, ...] > ``` > > > [accordion] Output: Event Page > > > > ```json Example theme={null} > > { > > "items": [ > > { > > "id": "662915", > > "slug": "mls-chi-vwh-2026-07-16", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC" > > }, > > { > > "id": "662970", > > "slug": "mls-chi-vwh-2026-07-16-halftime-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Halftime Result" > > }, > > { > > "id": "662972", > > "slug": "mls-chi-vwh-2026-07-16-second-half-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Second Half Result" > > }, > > { > > "id": "662974", > > "slug": "mls-chi-vwh-2026-07-16-exact-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Exact Score" > > }, > > { > > "id": "662976", > > "slug": "mls-chi-vwh-2026-07-16-first-to-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - First Team to Score" > > }, > > { > > "id": "663131", > > "slug": "mls-chi-vwh-2026-07-16-more-markets", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - More Markets" > > } > > ], > > "has_more": false > > } > > ``` > > When present, `market.sports.sports_market_type` identifies lines in the more-markets > event such as `first_half_totals`, `both_teams_to_score`, and `soccer_team_totals`. > [tab] API > > To fetch only the more-markets event, append `-more-markets` to the main event's slug: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/slug/mls-chi-vwh-2026-07-16-more-markets" > ``` > > To list the game's current events, fetch the main event and read its `gameId`: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/slug/mls-chi-vwh-2026-07-16" > ``` > > Pass the ID as `game_id`: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/keyset?game_id=90104306&limit=20" > ``` > > > [accordion] Output: Events Page > > > > ```json Example theme={null} > > { > > "events": [ > > { > > "id": "662915", > > "slug": "mls-chi-vwh-2026-07-16", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC", > > "gameId": 90104306 > > }, > > { > > "id": "662970", > > "slug": "mls-chi-vwh-2026-07-16-halftime-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Halftime Result", > > "gameId": 90104306 > > }, > > { > > "id": "662972", > > "slug": "mls-chi-vwh-2026-07-16-second-half-result", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Second Half Result", > > "gameId": 90104306 > > }, > > { > > "id": "662974", > > "slug": "mls-chi-vwh-2026-07-16-exact-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - Exact Score", > > "gameId": 90104306 > > }, > > { > > "id": "662976", > > "slug": "mls-chi-vwh-2026-07-16-first-to-score", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - First Team to Score", > > "gameId": 90104306 > > }, > > { > > "id": "663131", > > "slug": "mls-chi-vwh-2026-07-16-more-markets", > > "title": "Chicago Fire FC vs. Vancouver Whitecaps FC - More Markets", > > "gameId": 90104306 > > } > > ] > > } > > ``` > > If the response includes `next_cursor`, pass it as `after_cursor` in the next request. > When present, `market.sportsMarketType` identifies lines in the more-markets event such > as `first_half_totals`, `both_teams_to_score`, and `soccer_team_totals`. ### Identify Home and Away Teams Sports event responses identify which team is designated home and which is designated away. Use this value when aligning Polymarket data with an external sports feed. > [tab] TypeScript > > Use `PublicClient.fetchEvent()` or `SecureClient.fetchEvent()` to identify the teams. > > ```ts theme={null} > import { TeamOrdering } from "@polymarket/client"; > > const event = await client.fetchEvent({ > slug: "fl1-psg-ren-2026-08-23", > }); > const homeTeam = event.sports.teams.find( > (team) => team.ordering === TeamOrdering.Home, > ); > const awayTeam = event.sports.teams.find( > (team) => team.ordering === TeamOrdering.Away, > ); > ``` > > > [accordion] Output: Team > > > > ```json theme={null} > > { > > "id": 114315, > > "name": "Paris Saint-Germain FC", > > "league": "fl1", > > "abbreviation": "psg", > > "ordering": "home" > > } > > ``` > > Each `Team.ordering` value is `TeamOrdering.Home`, `TeamOrdering.Away`, or `null`. > [tab] Python > > Use `AsyncPublicClient.get_event()` or `AsyncSecureClient.get_event()` to identify the teams. > > ```python theme={null} > from polymarket import TeamOrdering > > > event = await client.get_event(slug="fl1-psg-ren-2026-08-23") > home_team = next( > (team for team in event.sports.teams if team.ordering is TeamOrdering.HOME), > None, > ) > away_team = next( > (team for team in event.sports.teams if team.ordering is TeamOrdering.AWAY), > None, > ) > ``` > > > [accordion] Output: Team > > > > ```json theme={null} > > { > > "id": 114315, > > "name": "Paris Saint-Germain FC", > > "league": "fl1", > > "abbreviation": "psg", > > "ordering": "home" > > } > > ``` > > Each `Team.ordering` value is `TeamOrdering.HOME`, `TeamOrdering.AWAY`, or `None`. > [tab] API > > Fetch the event by slug to identify its home and away teams. > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/slug/fl1-psg-ren-2026-08-23" > ``` > > > [accordion] Output: Event > > > > ```jsonc theme={null} > > { > > "slug": "fl1-psg-ren-2026-08-23", > > "title": "Paris Saint-Germain FC vs. Stade Rennais FC 1901", > > // … > > "teams": [ > > { > > "id": 114315, > > "name": "Paris Saint-Germain FC", > > // … > > "ordering": "home", > > }, > > { > > "id": 114317, > > "name": "Stade Rennais FC 1901", > > // … > > "ordering": "away", > > }, > > ], > > } > > ``` > > Read `ordering` from each entry in the event's top-level `teams` field. Its > value is `"home"`, `"away"`, or `null`. > [!WARNING] > > Home and away assignments can change after markets are created, especially > when games are rescheduled or moved. If you plan to submit quotes in Combos, > check [Common Footguns](/trading/combos/market-makers#common-footguns). ### List Teams > [tab] TypeScript > > Call `listTeams()` on a `PublicClient` or `SecureClient` to page through teams. > > ```ts theme={null} > const pages = client.listTeams({ league: ["nba"], pageSize: 20 }); > > for await (const page of pages) { > // page.items: Team[] > } > ``` > > > [accordion] Output: Team\[] > > > > ```json Example theme={null} > > [ > > { > > "id": 114168, > > "name": "Candace's Rising Stars", > > "league": "nba", > > "abbreviation": "crs" > > }, > > { > > "id": 114166, > > "name": "Chuck's Global Stars", > > "league": "nba", > > "abbreviation": "cgs" > > }, > > "..." > > ] > > ``` > [tab] Python > > Call `list_teams()` on an `AsyncPublicClient` or `AsyncSecureClient` to page > through teams. The synchronous `PublicClient` and `SecureClient` provide the > same method. > > ```python theme={null} > pages = client.list_teams(league="nba", page_size=20) > > async for page in pages: > ... # page.items: tuple[Team, ...] > ``` > > > [accordion] Output: Team\[] > > > > ```json Example theme={null} > > [ > > { > > "id": 114168, > > "name": "Candace's Rising Stars", > > "league": "nba", > > "abbreviation": "crs" > > }, > > { > > "id": 114166, > > "name": "Chuck's Global Stars", > > "league": "nba", > > "abbreviation": "cgs" > > }, > > "..." > > ] > > ``` > [tab] API > > List teams in a league: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/teams?league=nba&limit=20" > ``` > > > [accordion] Output: Team\[] > > > > ```json Example theme={null} > > [ > > { > > "id": 114168, > > "name": "Candace's Rising Stars", > > "league": "nba", > > "abbreviation": "crs" > > }, > > "..." > > ] > > ``` ## Search Search returns matching events, tags, and profiles for a free-text query in one call. Use it for a search bar or a "jump to market" input. > [tab] TypeScript > > Call `search()` on a `PublicClient` or `SecureClient` to search Polymarket. > > ```ts theme={null} > const pages = client.search({ q: "aliens", pageSize: 10 }); > > for await (const page of pages) { > // page.items.events: Event[] > // page.items.tags: SearchTag[] > // page.items.profiles: Profile[] > } > ``` > > > [accordion] Output: SearchResults > > > > ```ts SearchResults Type theme={null} > > type Event = { > > id: string; > > slug?: string | null; > > title?: string | null; > > }; > > > > type SearchTag = { > > id: string; > > label?: string | null; > > slug?: string | null; > > eventCount?: number | null; > > }; > > > > type Profile = { > > pseudonym?: string | null; > > wallet?: string | null; > > }; > > > > type SearchResults = { > > events: Event[]; > > tags: SearchTag[]; > > profiles: Profile[]; > > }; > > ``` > > > > ```json SearchResults Example theme={null} > > { > > "events": [ > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?" > > }, > > "..." > > ], > > "tags": [], > > "profiles": [] > > } > > ``` > [tab] Python > > Call `search()` on an `AsyncPublicClient` or `AsyncSecureClient` to search > Polymarket. The synchronous `PublicClient` and `SecureClient` provide the > same method. > > ```python theme={null} > pages = client.search(q="aliens", page_size=10) > > async for page in pages: > for search_results in page.items: > # search_results.events: tuple[Event, ...] > # search_results.tags: tuple[SearchTag, ...] > # search_results.profiles: tuple[Profile, ...] > ... > ``` > > > [accordion] Output: SearchResults > > > > ```python SearchResults Type theme={null} > > class Event: > > id: str > > slug: str | None > > title: str | None > > > > class SearchTag: > > id: str > > label: str | None > > slug: str | None > > event_count: int | None > > > > class Profile: > > pseudonym: str | None > > wallet: str | None > > > > class SearchResults: > > events: tuple[Event, ...] > > tags: tuple[SearchTag, ...] > > profiles: tuple[Profile, ...] > > ``` > > > > ```json SearchResults Example theme={null} > > { > > "events": [ > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?" > > }, > > "..." > > ], > > "tags": [], > > "profiles": [] > > } > > ``` > [tab] API > > Search Polymarket: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/public-search?q=aliens" > ``` > > > [accordion] Output: Search > > > > ```json Example theme={null} > > { > > "events": [ > > { > > "id": "90177", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "title": "Will the US confirm that aliens exist by...?" > > }, > > "..." > > ], > > "tags": [], > > "profiles": [], > > "pagination": { > > "hasMore": true, > > "totalResults": 28 > > } > > } > > ``` ## Tags Tags group events and markets by categories, leagues, people, and themes. Each tag can link to multiple ranked related tags, forming a directed graph rather than a strict tree. Use these relationships to expand discovery from one topic to adjacent topics. ### List Tags Browse the available tags, for example to build a category filter. > [tab] TypeScript > > Call `listTags()` on a `PublicClient` or `SecureClient` to page through tags. > > ```ts theme={null} > const pages = client.listTags({ pageSize: 20 }); > > for await (const page of pages) { > // page.items: Tag[] > } > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [ > > { > > "id": "101867", > > "slug": "product-marekt-fit", > > "label": "product marekt fit" > > }, > > { "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }, > > "..." > > ] > > ``` > [tab] Python > > Call `list_tags()` on an `AsyncPublicClient` or `AsyncSecureClient` to page > through tags. The synchronous `PublicClient` and `SecureClient` provide the > same method. > > ```python theme={null} > pages = client.list_tags(page_size=20) > > async for page in pages: > ... # page.items: tuple[Tag, ...] > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [ > > { > > "id": "101867", > > "slug": "product-marekt-fit", > > "label": "product marekt fit" > > }, > > { "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }, > > "..." > > ] > > ``` > [tab] API > > List tags: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/tags?limit=20" > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [ > > { > > "id": "101867", > > "slug": "product-marekt-fit", > > "label": "product marekt fit" > > }, > > { "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }, > > "..." > > ] > > ``` ### Fetch a Tag Fetch a tag by slug to resolve its numeric ID. You'll need that ID for the `tagId`/`tagIds` filters used earlier in Events and Markets. > [tab] TypeScript > > Call `fetchTag()` on a `PublicClient` or `SecureClient` to fetch a tag by slug. > > ```ts theme={null} > const nba = await client.fetchTag({ slug: "nba" }); > > // nba: Tag > ``` > > > [accordion] Output: Tag > > > > ```json Example theme={null} > > { "id": "745", "slug": "nba", "label": "NBA" } > > ``` > [tab] Python > > Call `get_tag()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch a > tag by slug. The synchronous `PublicClient` and `SecureClient` provide the > same method. > > ```python theme={null} > nba = await client.get_tag(slug="nba") > > # nba: Tag > ``` > > > [accordion] Output: Tag > > > > ```json Example theme={null} > > { "id": "745", "slug": "nba", "label": "NBA" } > > ``` > [tab] API > > Fetch a tag by slug: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/tags/slug/nba" > ``` > > > [accordion] Output: Tag > > > > ```json Example theme={null} > > { "id": "745", "slug": "nba", "label": "NBA" } > > ``` ### Fetch Tag Relationships Get the relationship records that link a tag to related tags, useful for building "you might also like" surfaces. Each record is a lightweight pointer (a rank and the two numeric tag IDs), not a full tag object. > [tab] TypeScript > > Call `fetchRelatedTags()` on a `PublicClient` or `SecureClient` to fetch a tag's > relationship records. > > ```ts theme={null} > const relatedTags = await client.fetchRelatedTags({ slug: "nba" }); > > // relatedTags: RelatedTag[] > ``` > > > [accordion] Output: RelatedTag\[] > > > > ```json Example theme={null} > > [{ "id": "58212", "tagId": 745, "relatedTagId": 1512, "rank": 1 }] > > ``` > [tab] Python > > Call `get_related_tags()` on an `AsyncPublicClient` or `AsyncSecureClient` > to fetch a tag's relationship records. The synchronous `PublicClient` and > `SecureClient` provide the same method. > > ```python theme={null} > related_tags = await client.get_related_tags(slug="nba") > > # related_tags: tuple[RelatedTag, ...] > ``` > > > [accordion] Output: RelatedTag\[] > > > > ```json Example theme={null} > > [{ "id": "58212", "tag_id": 745, "related_tag_id": 1512, "rank": 1 }] > > ``` > [tab] API > > Fetch a tag's relationship records: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/tags/slug/nba/related-tags" > ``` > > > [accordion] Output: RelatedTag\[] > > > > ```json Example theme={null} > > [{ "id": "58212", "tagID": 745, "relatedTagID": 1512, "rank": 1 }] > > ``` ### Fetch Related Tags Get the full `Tag` objects for a tag's related tags in one call, skipping the extra round trip to fetch each related tag by ID. > [tab] TypeScript > > Call `fetchRelatedTagResources()` on a `PublicClient` or `SecureClient` to fetch the > related tag objects. > > ```ts theme={null} > const relatedTagObjects = await client.fetchRelatedTagResources({ > slug: "nba", > status: "active", > }); > > // relatedTagObjects: Tag[] > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [{ "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }] > > ``` > [tab] Python > > Call `get_related_tag_resources()` on an `AsyncPublicClient` or > `AsyncSecureClient` to fetch the related tag objects. The synchronous > `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > related_tag_objects = await client.get_related_tag_resources( > slug="nba", > status="active", > ) > > # related_tag_objects: tuple[Tag, ...] > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [{ "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }] > > ``` > [tab] API > > Fetch the related tag objects: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/tags/slug/nba/related-tags/tags" > ``` > > > [accordion] Output: Tag\[] > > > > ```json Example theme={null} > > [{ "id": "1512", "slug": "caitlin-clark", "label": "caitlin clark" }] > > ``` # Market Details Source: https://docs.polymarket.com/market-data/market-details Understand the structure and state of a Polymarket market. The market object represents a prediction market. Alongside its question and outcomes, it describes the market's current state and provides the information an integration needs to read prices, follow activity, or trade. The examples below assume you already have a market object. To find or fetch one, see [Discover Markets](/market-data/discover-markets). > [tab] TypeScript > > Let's say you fetched a market with `fetchMarket()` on a `PublicClient` or > `SecureClient`: > > ```ts theme={null} > const market = await client.fetchMarket({ > slug: "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > }); > // market: Market > ``` > [tab] Python > > Let's say you fetched a market with `get_market()` on an > `AsyncPublicClient` or `AsyncSecureClient`: > > ```python theme={null} > market = await client.get_market( > slug="will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > ) > # market: Market > ``` > [tab] API > > Let's say you fetched a market from the Gamma API: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/markets/slug/will-the-us-confirm-that-aliens-exist-before-2027-789-924-249" > ``` ## Market Identifiers A market has three identifiers, each used in a different context: | Identifier | Use it for | | - | - | | Market ID | Fetching a known market by its Gamma ID. | | Market slug | Fetching a known market or linking to its human-readable page. | | Condition ID | Public analytics, positions, and some trading or lifecycle workflows. | > [tab] TypeScript > > Read the identifiers from the market object: > > ```ts theme={null} > const marketId = market.id; > const slug = market.slug; > const conditionId = market.conditionId; > ``` > [tab] Python > > Read the identifiers from the market object: > > ```python theme={null} > market_id = market.id > slug = market.slug > condition_id = market.condition_id > ``` > [tab] API > > Read the identifiers from the Gamma response: > > ```json theme={null} > { > "id": "703257", > "slug": "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75" > } > ``` ## Market Outcomes Each market has YES and NO outcomes. Its position system determines which outcome ID to use for order book reads and trading. > [tab] TypeScript > > Read both outcomes from `market.outcomes`: > > ```ts theme={null} > const yes = market.outcomes.yes; > const no = market.outcomes.no; > ``` > > Each outcome can carry a CTF token ID, a Polymarket Protocol V2 Position > ID, or both: > > ```ts theme={null} > type MarketOutcome = { > label: string; > tokenId: TokenId | null; > positionId: PositionId | null; > price: DecimalString | null; > }; > > type MarketOutcomes = { > yes: MarketOutcome; > no: MarketOutcome; > }; > ``` > > Select the trading identifier by market version: > > ```ts theme={null} > const yesAssetId = market.version === "v2" ? yes.positionId : yes.tokenId; > ``` > [tab] Python > > Read both outcomes from `market.outcomes`: > > ```python theme={null} > yes = market.outcomes.yes > no = market.outcomes.no > ``` > > Each outcome can carry a CTF token ID, a Polymarket Protocol V2 Position > ID, or both: > > ```python theme={null} > class MarketOutcome: > label: str > token_id: TokenId | None > position_id: PositionId | None > price: Decimal | None > > class MarketOutcomes: > yes: MarketOutcome > no: MarketOutcome > ``` > > Select the trading identifier by market version: > > ```python theme={null} > yes_asset_id = yes.position_id if market.version == "v2" else yes.token_id > if yes_asset_id is None: > raise ValueError("Market outcome ID not found.") > ``` > [tab] API > > Gamma returns the market outcomes and their identifiers: > > ```json theme={null} > { > "version": "v2", > "outcomes": "[\"Yes\", \"No\"]", > "outcomePrices": "[\"0.085\", \"0.915\"]", > "clobTokenIds": null, > "positionIds": [ > "651150819117105875331414918119047680898421632356043490229292782433651916800", > "651150819117105875331414918119047680898421632356043490229292782433651916801" > ] > } > ``` > > Outcome labels and prices are JSON-encoded strings. Parse them into arrays; > entries at the same index describe the same outcome. > > ```js theme={null} > const labels = JSON.parse(market.outcomes); > const prices = JSON.parse(market.outcomePrices); > ``` > > Use `market.version` to select the identifiers: `positionIds` is already an > array for Polymarket Protocol V2 (`v2`); parse `clobTokenIds` for CTF (`v1`). > Both fields can be populated, so their presence does not select the protocol. > > ```js Polymarket V2 theme={null} > const assetIds = market.positionIds; > ``` > > ```js CTF theme={null} > const assetIds = JSON.parse(market.clobTokenIds); > ``` > > Combine labels, prices, and identifiers by index. For these binary markets, > index `0` is YES and index `1` is NO. > > ```js theme={null} > const outcomes = labels.map((label, index) => ({ > label, > price: prices[index], > assetId: assetIds[index], > })); > ``` > > These examples assume outcome identifiers are available. If the selected > field is absent, the IDs are not yet available. Treat versions other than > `v1` and `v2` as unsupported. ## Market Status Market status tells you whether a market is currently available for trading. Check it before relying on live prices or submitting an order, since a market may exist before its order book opens and remain discoverable after it closes. It also indicates whether the market belongs to a [negative-risk group](/concepts/negative-risk), where only one of several mutually exclusive markets can resolve YES. > [tab] TypeScript > > Read market status from `market.state`: > > ```ts theme={null} > const state = market.state; > // state: MarketState > ``` > > `MarketState` groups the market's operational state and timing: > > ```ts MarketState Type theme={null} > type MarketState = { > active?: boolean | null; > closed?: boolean | null; > archived?: boolean | null; > acceptingOrders?: boolean | null; > enableOrderBook?: boolean | null; > negRisk?: boolean | null; > startDate?: IsoDateTimeString | null; > endDate?: IsoDateTimeString | null; > closedTime?: IsoDateTimeString | null; > }; > ``` > > ```json MarketState Example theme={null} > { > "active": true, > "closed": false, > "archived": false, > "acceptingOrders": true, > "enableOrderBook": true, > "negRisk": false, > "startDate": "2024-03-15T00:00:00Z", > "endDate": "2027-01-01T00:00:00Z", > "closedTime": null > } > ``` > > Use its status fields to check whether the market is ready for trading: > > ```ts theme={null} > const isTradeReady = state.active && !state.closed && state.acceptingOrders; > ``` > [tab] Python > > Read market status from `market.state`: > > ```python theme={null} > state = market.state > # state: MarketState > ``` > > `MarketState` groups the market's operational state and timing: > > ```python MarketState Type theme={null} > class MarketState: > active: bool | None > closed: bool | None > archived: bool | None > accepting_orders: bool | None > enable_order_book: bool | None > neg_risk: bool | None > start_date: datetime | None > end_date: datetime | None > closed_time: datetime | None > ``` > > ```json MarketState Example theme={null} > { > "active": true, > "closed": false, > "archived": false, > "accepting_orders": true, > "enable_order_book": true, > "neg_risk": false, > "start_date": "2024-03-15T00:00:00Z", > "end_date": "2027-01-01T00:00:00Z", > "closed_time": null > } > ``` > > Use its status fields to check whether the market is ready for trading: > > ```python theme={null} > is_trade_ready = ( > state.active > and not state.closed > and state.accepting_orders > ) > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "active": true, > "closed": false, > "acceptingOrders": true, > "negRisk": false, > "restricted": false, > "archived": false > } > ``` | Field | Type | Description | | - | - | - | | `active` | boolean | Market is deployed and not archived. | | `closed` | boolean | Market has resolved or been closed, so no further trading is possible. | | `acceptingOrders` | boolean | Order book is open for new limit and market orders. | | `negRisk` | boolean | Market belongs to a [negative-risk group](/concepts/negative-risk). | | `restricted` | boolean | Market is geo-restricted for some jurisdictions. | | `archived` | boolean | Market is archived and read-only: no trading, no resolution updates. | ### Identify Augmented Negative Risk Negative-risk membership is a market-level property, but augmented negative risk is configured on the event. After confirming that the market's `negRisk` value is `true`, fetch its event and check that augmented negative risk is enabled: > [tab] TypeScript > > Fetch the event referenced by the market, then check its trading > configuration: > > ```ts theme={null} > const event = await client.fetchEvent({ > id: market.events[0].id, > }); > > const isAugmentedNegativeRisk = > event.trading.enableNegRisk === true && > event.trading.negRiskAugmented === true; > ``` > [tab] Python > > Fetch the event referenced by the market, then check its trading > configuration: > > ```python theme={null} > event = await client.get_event(id=market.events[0].id) > > is_augmented_negative_risk = ( > event.trading.enable_neg_risk is True > and event.trading.neg_risk_augmented is True > ) > ``` > [tab] API > > Read the event ID from the market's `events` array, then fetch that event: > > ```bash theme={null} > curl "https://gamma-api.polymarket.com/events/$EVENT_ID" > ``` > > An event uses augmented negative risk when both fields are `true`: > > ```json theme={null} > { > "enableNegRisk": true, > "negRiskAugmented": true > } > ``` See [Augmented Negative Risk](/concepts/negative-risk#augmented-negative-risk) for how named outcomes, placeholders, and Other behave. ## Trading Constraints Every market enforces a minimum price increment, also known as the **tick size**, and a minimum order size. The minimum price increment defines the grid of prices you can submit; an order price must be a multiple of the active value. Orders smaller than the minimum order size are rejected. | Minimum price increment | Step size | Example prices | | - | - | - | | `0.1` | 10¢ | `0.1`, `0.5`, `0.9` | | `0.01` | 1¢ | `0.01`, `0.50`, `0.99` | | `0.005` | 0.5¢ | `0.005`, `0.500`, `0.995` | | `0.0025` | 0.25¢ | `0.0025`, `0.5000`, `0.9975` | | `0.001` | 0.1¢ | `0.001`, `0.500`, `0.999` | | `0.0001` | 0.01¢ | `0.0001`, `0.5000`, `0.9999` | > [!NOTE] > > The `0.0025` (0.25¢) increment applies only to World Cup *to advance*, > *moneyline*, *spreads*, and *totals* markets. Always read the active value > from the market rather than assuming a fixed increment. Read the active constraints for a market in your integration: > [tab] TypeScript > > Read the market's trading constraints: > > ```ts theme={null} > const minimumTickSize = market.trading.minimumTickSize; > const minimumOrderSize = market.trading.minimumOrderSize; > > // minimumTickSize: TickSizeValue | null > // minimumOrderSize: DecimalString | null > // minimum USDC notional; orders smaller than this are rejected > ``` > > The SDK groups these constraints in `MarketTrading`: > > ```ts MarketTrading Type theme={null} > type MarketTrading = { > minimumTickSize?: TickSizeValue | null; > minimumOrderSize?: DecimalString | null; > }; > ``` > > ```json MarketTrading Example theme={null} > { > "minimumTickSize": 0.01, > "minimumOrderSize": "5" > } > ``` > [tab] Python > > Read the market's trading constraints: > > ```python theme={null} > minimum_tick_size = market.trading.minimum_tick_size > minimum_order_size = market.trading.minimum_order_size > > # minimum_tick_size: Decimal | None > # minimum_order_size: Decimal | None > # minimum USDC notional per order > ``` > > The SDK groups these constraints in `MarketTrading`: > > ```python MarketTrading Type theme={null} > class MarketTrading: > minimum_tick_size: Decimal | None > minimum_order_size: Decimal | None > ``` > > ```json MarketTrading Example theme={null} > { > "minimum_tick_size": 0.01, > "minimum_order_size": "5" > } > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "orderPriceMinTickSize": 0.01, > "orderMinSize": 5 > } > ``` > > Where: > > | Field | Type | Description | > | - | - | - | > | `orderPriceMinTickSize` | number | Minimum price increment for limit orders. Prices must be multiples of this value. | > | `orderMinSize` | number | Minimum order size in USDC. The CLOB rejects orders below this threshold. | ## Trading Fees Some markets charge trading fees. The fee schedule determines how fees vary with price, which side pays them, and what share is returned to makers. > [tab] TypeScript > > Read the market's fee configuration: > > ```ts theme={null} > const feesEnabled = market.trading.feesEnabled; > const feeSchedule = market.trading.feeSchedule; > > // feesEnabled: boolean | null > // feeSchedule: { > // rate: DecimalString; base rate used in the fee calculation > // exponent: number; exponent applied to the price component > // takerOnly: boolean; fees charged to taker side only > // rebateRate: DecimalString; maker rebate as fraction of taker fee > // } | null > ``` > > The SDK exposes this configuration through `MarketTrading` and > `FeeSchedule`: > > ```ts MarketTrading Type theme={null} > type FeeSchedule = { > rate: DecimalString; > exponent: number; > takerOnly: boolean; > rebateRate: DecimalString; > }; > > type MarketTrading = { > feesEnabled?: boolean | null; > feeSchedule?: FeeSchedule | null; > }; > ``` > > ```json MarketTrading Example theme={null} > { > "feesEnabled": true, > "feeSchedule": { > "rate": "0.04", > "exponent": 1, > "takerOnly": true, > "rebateRate": "0.25" > } > } > ``` > [tab] Python > > Read the market's fee configuration: > > ```python theme={null} > fees_enabled = market.trading.fees_enabled > fee_schedule = market.trading.fee_schedule > > # fees_enabled: bool | None > # fee_schedule.rate: Decimal base rate used in the fee calculation > # fee_schedule.exponent: int | float exponent applied to the price component > # fee_schedule.taker_only: bool taker-only flag > # fee_schedule.rebate_rate: Decimal maker rebate fraction > ``` > > The SDK exposes this configuration through `MarketTrading` and > `FeeSchedule`: > > ```python MarketTrading Type theme={null} > class FeeSchedule: > rate: Decimal > exponent: int | float > taker_only: bool > rebate_rate: Decimal > > class MarketTrading: > fees_enabled: bool | None > fee_schedule: FeeSchedule | None > ``` > > ```json MarketTrading Example theme={null} > { > "fees_enabled": true, > "fee_schedule": { > "rate": 0.04, > "exponent": 1, > "taker_only": true, > "rebate_rate": 0.25 > } > } > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "feesEnabled": true, > "feeSchedule": { > "rate": 0.04, > "exponent": 1, > "takerOnly": true, > "rebateRate": 0.25 > } > } > ``` > > Where: > > | Field | Type | Description | > | - | - | - | > | `feesEnabled` | boolean | Whether fees are active for this market. | > | `feeSchedule.rate` | number | Base rate used in the fee calculation. | > | `feeSchedule.exponent` | number | Exponent applied to the price component of the fee curve. | > | `feeSchedule.takerOnly` | boolean | When `true`, fees are charged to the taker side only, and makers pay no fee. | > | `feeSchedule.rebateRate` | number | Fraction of taker fees rebated back to the resting maker. Example: `0.25` = 25% rebate. | ## Liquidity Reward Settings Liquidity reward settings determine which resting orders can qualify for incentives and how much funding is available. An order must meet the market's minimum qualifying size and remain within its maximum qualifying spread. See [Liquidity Rewards](/programs/liquidity-rewards) for the scoring methodology. > [tab] TypeScript > > Read liquidity reward settings from `market.rewards`: > > ```ts theme={null} > const minimumSize = market.rewards.rewardsMinSize; > const maximumSpread = market.rewards.rewardsMaxSpread; > const allocations = market.rewards.clobRewards; > > // minimumSize: DecimalString | null > // maximumSpread: number | null > // allocations: ClobRewards[] | null > ``` > > The SDK exposes the market configuration through `MarketRewards` and each > dated allocation through `ClobRewards`: > > ```ts ClobRewards Type theme={null} > type MarketRewards = { > clobRewards?: ClobRewards[] | null; > rewardsMinSize?: DecimalString | null; > rewardsMaxSpread?: number | null; > holdingRewardsEnabled?: boolean | null; > }; > > type ClobRewards = { > id: ClobRewardId; > conditionId: ConditionId; > assetAddress: string; > rewardsAmount: DecimalString; > rewardsDailyRate: DecimalString; > startDate: IsoCalendarDateString; > endDate: IsoCalendarDateString | null; > }; > ``` > > ```json ClobRewards Example theme={null} > { > "rewardsMinSize": "100", > "rewardsMaxSpread": 3, > "clobRewards": [ > { > "id": "", > "conditionId": "", > "assetAddress": "", > "rewardsAmount": "10000", > "rewardsDailyRate": "100", > "startDate": "2026-07-01", > "endDate": "2026-07-31" > } > ] > } > ``` > [tab] Python > > Read liquidity reward settings from `market.rewards`: > > ```python theme={null} > minimum_size = market.rewards.rewards_min_size > maximum_spread = market.rewards.rewards_max_spread > allocations = market.rewards.clob_rewards > > # minimum_size: Decimal | None > # maximum_spread: float | None > # allocations: tuple[ClobReward, ...] | None > ``` > > The SDK exposes the market configuration through `MarketRewards` and each > dated allocation through `ClobReward`: > > ```python ClobReward Type theme={null} > class MarketRewards: > clob_rewards: tuple[ClobReward, ...] | None > rewards_min_size: Decimal | None > rewards_max_spread: float | None > holding_rewards_enabled: bool | None > > class ClobReward: > id: ClobRewardId > condition_id: ConditionId > asset_address: str > rewards_amount: Decimal > rewards_daily_rate: Decimal > start_date: date > end_date: date | None > ``` > > ```json ClobReward Example theme={null} > { > "rewards_min_size": 100, > "rewards_max_spread": 3, > "clob_rewards": [ > { > "id": "", > "condition_id": "", > "asset_address": "", > "rewards_amount": 10000, > "rewards_daily_rate": 100, > "start_date": "2026-07-01", > "end_date": "2026-07-31" > } > ] > } > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "rewardsMinSize": 100, > "rewardsMaxSpread": 3, > "clobRewards": [ > { > "id": "", > "conditionId": "", > "assetAddress": "", > "rewardsAmount": 10000, > "rewardsDailyRate": 100, > "startDate": "2026-07-01", > "endDate": "2026-07-31" > } > ] > } > ``` > > Where: > > | Field | Type | Description | > | - | - | - | > | `rewardsMinSize` | number | Minimum order size, in shares, that can qualify for rewards. | > | `rewardsMaxSpread` | number | Maximum qualifying distance from the midpoint, in cents. | > | `clobRewards` | array | Dated reward allocations configured for the market. | > | `clobRewards[].rewardsAmount` | number | Total reward amount configured for the allocation. | > | `clobRewards[].rewardsDailyRate` | number | Reward amount available per day during the allocation. | > | `clobRewards[].startDate` | string | Date when the allocation begins. | > | `clobRewards[].endDate` | string | Date when the allocation ends, or `null` when it has no end date. | ## Market Timing Market timing places a market within its expected schedule. Markets include start and end dates, while sports markets may also include the scheduled start time of the game. > [tab] TypeScript > > Read timing data from the market's state, trading configuration, and sports > metadata: > > ```ts theme={null} > const startDate = market.state.startDate; > const endDate = market.state.endDate; > const secondsDelay = market.trading.secondsDelay; > const gameStartTime = market.sports.gameStartTime; > > // startDate: IsoDateTimeString | null > // endDate: IsoDateTimeString | null > // secondsDelay: number | null > // gameStartTime: IsoDateTimeString | null > ``` > > The SDK groups these values by their role: > > ```ts MarketSportsMetadata Type theme={null} > type MarketState = { > startDate?: IsoDateTimeString | null; > endDate?: IsoDateTimeString | null; > }; > > type MarketTrading = { > secondsDelay?: number | null; > }; > > type MarketSportsMetadata = { > gameStartTime?: IsoDateTimeString | null; > }; > ``` > > ```json MarketSportsMetadata Example theme={null} > { > "state": { > "startDate": "2024-03-15T00:00:00Z", > "endDate": "2027-01-01T00:00:00Z" > }, > "trading": { > "secondsDelay": 0 > }, > "sports": { > "gameStartTime": null > } > } > ``` > [tab] Python > > Read timing data from the market's state, trading configuration, and sports > metadata: > > ```python theme={null} > start_date = market.state.start_date > end_date = market.state.end_date > seconds_delay = market.trading.seconds_delay > game_start_time = market.sports.game_start_time > > # start_date: datetime | None > # end_date: datetime | None > # seconds_delay: int | None > # game_start_time: datetime | None > ``` > > The SDK groups these values by their role: > > ```python MarketSportsMetadata Type theme={null} > class MarketState: > start_date: datetime | None > end_date: datetime | None > > class MarketTrading: > seconds_delay: int | None > > class MarketSportsMetadata: > game_start_time: datetime | None > ``` > > ```json MarketSportsMetadata Example theme={null} > { > "state": { > "start_date": "2024-03-15T00:00:00Z", > "end_date": "2027-01-01T00:00:00Z" > }, > "trading": { > "seconds_delay": 0 > }, > "sports": { > "game_start_time": null > } > } > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "startDateIso": "2024-03-15T00:00:00Z", > "endDateIso": "2027-01-01T00:00:00Z", > "gameStartTime": null, > "secondsDelay": 0 > } > ``` > > Where: > > | Field | Type | Description | > | - | - | - | > | `startDateIso` | string | Market start date in ISO 8601 format. | > | `endDateIso` | string | Market end date in ISO 8601 format. | > | `gameStartTime` | string | Scheduled start time of the underlying game for a sports market. | > | `secondsDelay` | integer | Delay, in seconds, before a newly placed marketable order can match. | See [Place Orders](/trading/place-orders#place-a-market-order) for the implications of trading on a market with a configured delay. ## Liquidity and Activity Liquidity, volume, and recent price activity describe how actively a market trades. Use them to compare markets or monitor changes over time. > [tab] TypeScript > > Read the market's liquidity, volume, and price summary: > > ```ts theme={null} > const liquidity = market.metrics.liquidity; > const volume24hr = market.metrics.volume24hr; > const lastTradePrice = market.prices.lastTradePrice; > const bestBid = market.prices.bestBid; > const bestAsk = market.prices.bestAsk; > const spread = market.prices.spread; > const oneDayPriceChange = market.prices.oneDayPriceChange; > > // liquidity: DecimalString | null > // volume24hr: DecimalString | null > // lastTradePrice: DecimalString | null > // bestBid: DecimalString | null > // bestAsk: DecimalString | null > // spread: DecimalString | null > // oneDayPriceChange: DecimalString | null > ``` > > The SDK groups liquidity and volume in `MarketMetrics`, and price activity in > `MarketPrices`: > > ```ts MarketPrices Type theme={null} > type MarketMetrics = { > liquidity?: DecimalString | null; > volume24hr?: DecimalString | null; > }; > > type MarketPrices = { > bestBid?: DecimalString | null; > bestAsk?: DecimalString | null; > lastTradePrice?: DecimalString | null; > spread?: DecimalString | null; > oneDayPriceChange?: DecimalString | null; > }; > ``` > > ```json MarketPrices Example theme={null} > { > "metrics": { > "liquidity": "150248.32", > "volume24hr": "5842.3" > }, > "prices": { > "lastTradePrice": "0.085", > "bestBid": "0.08", > "bestAsk": "0.09", > "spread": "0.01", > "oneDayPriceChange": "-0.003" > } > } > ``` > [tab] Python > > Read the market's liquidity, volume, and price summary: > > ```python theme={null} > liquidity = market.metrics.liquidity > volume_24hr = market.metrics.volume_24hr > last_trade_price = market.prices.last_trade_price > best_bid = market.prices.best_bid > best_ask = market.prices.best_ask > spread = market.prices.spread > one_day_price_change = market.prices.one_day_price_change > ``` > > The SDK groups liquidity and volume in `MarketMetrics`, and price activity in > `MarketPrices`: > > ```python MarketPrices Type theme={null} > class MarketMetrics: > liquidity: Decimal | None > volume_24hr: Decimal | None > > class MarketPrices: > best_bid: Decimal | None > best_ask: Decimal | None > last_trade_price: Decimal | None > spread: Decimal | None > one_day_price_change: Decimal | None > ``` > > ```json MarketPrices Example theme={null} > { > "metrics": { > "liquidity": "150248.32", > "volume_24hr": "5842.3" > }, > "prices": { > "last_trade_price": "0.085", > "best_bid": "0.08", > "best_ask": "0.09", > "spread": "0.01", > "one_day_price_change": "-0.003" > } > } > ``` > [tab] API > > Read the corresponding fields from the Gamma response: > > ```json theme={null} > { > "liquidity": "150248.32", > "volume24hr": 5842.3, > "lastTradePrice": 0.085, > "bestBid": 0.08, > "bestAsk": 0.09, > "spread": 0.01, > "oneDayPriceChange": -0.003 > } > ``` > > Where: > > | Field | Type | Description | > | - | - | - | > | `liquidity` | string | Reported market liquidity. | > | `volume24hr` | number | Trading volume over the past 24 hours. | > | `lastTradePrice` | number | Most recent traded price reported for the market. | > | `bestBid` | number | Highest resting bid reported for the market. | > | `bestAsk` | number | Lowest resting ask reported for the market. | > | `spread` | number | Difference between the best ask and best bid. | > | `oneDayPriceChange` | number | Change in the reported market price over the past 24 hours. | # Overview Source: https://docs.polymarket.com/market-data/overview Learn how Polymarket organizes market data and where to begin. Market data starts with identifying the event, market, or outcome your application cares about. The pages in this section take you from that choice to the data your application needs. ## Understand the Data Model On Polymarket, an event groups one or more markets. Each market is a tradable question with YES and NO outcomes, and each outcome has its own ID. Use the ID for the outcome whose price or order book you want to read. ![](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/event.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=0c9a264aec9a22ce5a20c4cc7980806d) **1. Discover an event** Browse active events, search by topic, or fetch an event directly from its Polymarket URL. **2. Select a market** Inspect the event's markets and choose the specific question your app cares about. **3. Choose an outcome** Choose YES or NO and keep its ID. You'll use it to read prices, access the order book, and place orders. **4. Read or stream data** Use the identifiers you've collected to retrieve or stream the market data your application needs. ## Choose a Workflow If you are new to Polymarket market data, start with [Discover Markets](/market-data/discover-markets). > [card] [Discover Markets](/market-data/discover-markets) > > Find the events and markets your application cares about. > [card] [Get Market Details](/market-data/market-details) > > Understand a market's outcomes, status, trading constraints, fees, and other > properties. > [card] [Prices and Order Books](/market-data/prices-order-books) > > Understand current pricing and liquidity, or inspect how prices have > changed. > [card] [Analytics](/market-data/public-analytics) > > Analyze market activity and compare trader and builder performance. > [card] [Real-Time Data](/market-data/realtime-data) > > Keep your application current as markets and related data change. > [card] [Chainlink TWAP Prices](/market-data/realtime-data#twap-prices) > > Stream Chainlink-computed 60-second time-weighted crypto prices. # Prices and Order Books Source: https://docs.polymarket.com/market-data/prices-order-books Learn how prices and order books represent trading activity on Polymarket. Each Polymarket outcome has an outcome token traded on the CLOB. Its price reflects what traders are willing to pay, while its order book shows the resting bids and asks. The examples below assume you already have a market object from which to read the outcome IDs. To find or fetch one, see [**Discover Markets**](/market-data/discover-markets). > [tab] TypeScript > > The unified SDK uses `assetId` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Select both outcome IDs from the market: > > ```ts theme={null} > const yesAssetId = > market.version === "v2" > ? market.outcomes.yes.positionId > : market.outcomes.yes.tokenId; > if (yesAssetId === null) { > throw new Error("Market outcome ID not found."); > } > const noAssetId = > market.version === "v2" > ? market.outcomes.no.positionId > : market.outcomes.no.tokenId; > if (noAssetId === null) { > throw new Error("Market outcome ID not found."); > } > ``` > [tab] Python > > The unified SDK uses `asset_id` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Select both outcome IDs from the market: > > ```python theme={null} > yes_asset_id = ( > market.outcomes.yes.position_id > if market.version == "v2" > else market.outcomes.yes.token_id > ) > if yes_asset_id is None: > raise ValueError("Market outcome ID not found.") > no_asset_id = ( > market.outcomes.no.position_id > if market.version == "v2" > else market.outcomes.no.token_id > ) > if no_asset_id is None: > raise ValueError("Market outcome ID not found.") > ``` > [tab] API > > Gamma returns `positionIds` as a JSON array. Use `version` to select it for > Polymarket Protocol V2 markets or parse the JSON-encoded `clobTokenIds` for > CTF markets: > > ```json theme={null} > { > "version": "v2", > "positionIds": [ > "651150819117105875331414918119047680898421632356043490229292782433651916800", > "651150819117105875331414918119047680898421632356043490229292782433651916801" > ] > } > ``` > > Select the outcome you want to read: > > ```bash theme={null} > TOKEN_ID="" > ``` ## Order Book Retrieve the resting bids and asks for one outcome. Bids are ordered by ascending price and asks by descending price, so the best bid and ask are the last entries in their respective arrays. Each response also includes a `hash` for the order-book state. Compare it with the previous response's hash to determine whether the book changed between reads. ### Fetch an Order Book > [tab] TypeScript > > Call `fetchOrderBook()` on a `PublicClient` or `SecureClient` to fetch an outcome's > order book. > > ```ts theme={null} > const book = await client.fetchOrderBook({ assetId: yesAssetId }); > > // book: OrderBook > ``` > > The returned `OrderBook` describes its price levels and the market details > needed to interpret them: > > ```ts OrderBook Type theme={null} > type OrderBookLevel = { > price: DecimalString; > size: DecimalString; > }; > > type OrderBook = { > conditionId: ConditionId; > assetId: ClobAssetId; > timestamp?: EpochMilliseconds | null; > bids: OrderBookLevel[]; > asks: OrderBookLevel[]; > minOrderSize: DecimalString; > tickSize: DecimalString; > negRisk: boolean; > lastTradePrice?: DecimalString | null; > hash: OrderBookHash; > }; > ``` > > ```json OrderBook Example theme={null} > { > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "timestamp": 1782753404902, > "bids": [ > { "price": "0.01", "size": "2116131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "93442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ], > "minOrderSize": "5", > "tickSize": "0.01", > "negRisk": false, > "lastTradePrice": "0.090", > "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" > } > ``` > [tab] Python > > Call `get_order_book()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch an outcome's order book. The synchronous `PublicClient` and > `SecureClient` provide the same method. > > ```python theme={null} > book = await client.get_order_book(asset_id=yes_asset_id) > > # book: OrderBook > ``` > > The returned `OrderBook` describes its price levels and the market details > needed to interpret them: > > ```python OrderBook Type theme={null} > class OrderBookLevel: > price: Decimal > size: Decimal > > class OrderBook: > condition_id: ConditionId > asset_id: ClobAssetId > timestamp: datetime | None > bids: tuple[OrderBookLevel, ...] > asks: tuple[OrderBookLevel, ...] > min_order_size: Decimal > tick_size: Decimal > neg_risk: bool > last_trade_price: Decimal | None > hash: str > ``` > > ```json OrderBook Example theme={null} > { > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "timestamp": "2026-06-29T17:16:44.902000+00:00", > "bids": [ > { "price": "0.01", "size": "2116131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "93442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": false, > "last_trade_price": "0.090", > "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" > } > ``` > [tab] API > > Fetch an outcome's order book: > > ```bash theme={null} > curl "https://clob.polymarket.com/book?token_id=$TOKEN_ID" > ``` > > Alongside its price levels, the response includes the trading constraints > needed to validate an order: > > ```json theme={null} > { > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "timestamp": "1782753357257", > "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", > "bids": [ > { "price": "0.01", "size": "2151131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "218442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": false, > "last_trade_price": "0.090" > } > ``` ### Fetch Multiple Order Books Batch order-book reads return the resting bids and asks for several outcomes in one request. > [!NOTE] > > Maximum 500 items per request. > [tab] TypeScript > > Call `fetchOrderBooks()` on a `PublicClient` or `SecureClient` to fetch several order > books in one request. > > ```ts theme={null} > const books = await client.fetchOrderBooks([ > { assetId: yesAssetId }, > { assetId: noAssetId }, > ]); > > // books: OrderBook[] > ``` > > Each item uses the `OrderBook` shape described above: > > ```json theme={null} > [ > { > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "bids": [ > { "price": "0.01", "size": "2116131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "93442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ] > }, > { > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "bids": [ > { "price": "0.01", "size": "93442.27" }, > { "price": "0.02", "size": "13229.55" }, > { "price": "0.03", "size": "4338.7" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "2116131.59" }, > { "price": "0.98", "size": "139963.89" }, > { "price": "0.97", "size": "208169.44" }, > "..." > ] > } > ] > ``` > [tab] Python > > Call `get_order_books()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch several order books in one request. The synchronous `PublicClient` > and `SecureClient` provide the same method. > > ```python theme={null} > books = await client.get_order_books(asset_ids=[yes_asset_id, no_asset_id]) > > # books: tuple[OrderBook, ...] > ``` > > Each item uses the `OrderBook` shape described above: > > ```json theme={null} > [ > { > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "bids": [ > { "price": "0.01", "size": "2116131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "93442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ] > }, > { > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "bids": [ > { "price": "0.01", "size": "93442.27" }, > { "price": "0.02", "size": "13229.55" }, > { "price": "0.03", "size": "4338.7" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "2116131.59" }, > { "price": "0.98", "size": "139963.89" }, > { "price": "0.97", "size": "208169.44" }, > "..." > ] > } > ] > ``` > [tab] API > > Fetch several order books in one request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/books" \ > -H "Content-Type: application/json" \ > --data '[{"token_id":""},{"token_id":""}]' > ``` > > The response contains one order book for each requested outcome identifier: > > ```json theme={null} > [ > { > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "timestamp": "1782753357257", > "hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", > "bids": [ > { "price": "0.01", "size": "2151131.59" }, > { "price": "0.02", "size": "139963.89" }, > { "price": "0.03", "size": "208169.44" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "218442.27" }, > { "price": "0.98", "size": "13229.55" }, > { "price": "0.97", "size": "4338.7" }, > "..." > ], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": false, > "last_trade_price": "0.090" > }, > { > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > "timestamp": "1782753357257", > "hash": "f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5", > "bids": [ > { "price": "0.01", "size": "218442.27" }, > { "price": "0.02", "size": "13229.55" }, > { "price": "0.03", "size": "4338.7" }, > "..." > ], > "asks": [ > { "price": "0.99", "size": "2151131.59" }, > { "price": "0.98", "size": "139963.89" }, > { "price": "0.97", "size": "208169.44" }, > "..." > ], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": true, > "last_trade_price": "0.910" > } > ] > ``` ## Best Market Price Read the best available execution price for an outcome and side. `BUY` returns the lowest ask, which is the price you would pay to buy. `SELL` returns the highest bid, which is the price you would receive when selling. ### Fetch a Price > [tab] TypeScript > > Call `fetchPrice()` on a `PublicClient` or `SecureClient` to fetch the best price for > one side. For a `BUY`, the method returns the lowest ask. > > ```ts theme={null} > import { OrderSide } from "@polymarket/client"; > > const price = await client.fetchPrice({ > assetId: yesAssetId, > side: OrderSide.BUY, > }); > > // price: DecimalString > ``` > > The method returns the price as a decimal string: > > ```json theme={null} > "0.08" > ``` > [tab] Python > > Call `get_price()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch > the best price for one side. For a `BUY`, the method returns the lowest ask. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > price = await client.get_price(asset_id=yes_asset_id, side="BUY") > > # price: Decimal > ``` > > The method returns the price as a `Decimal`: > > ```python theme={null} > Decimal("0.08") > ``` > [tab] API > > Fetch the lowest ask available to a buyer: > > ```bash theme={null} > curl "https://clob.polymarket.com/price?token_id=$TOKEN_ID&side=BUY" > ``` > > The response contains the price as a decimal string: > > ```json theme={null} > { "price": "0.08" } > ``` ### Fetch Multiple Prices Batch price reads return the best market price for several outcome-and-side pairs in one request. Use them when the same view or calculation needs more than one outcome. > [!NOTE] > > Maximum 500 items per request. > [tab] TypeScript > > Call `fetchPrices()` on a `PublicClient` or `SecureClient` to fetch several prices in > one request. > > ```ts theme={null} > import { OrderSide } from "@polymarket/client"; > > const prices = await client.fetchPrices([ > { assetId: yesAssetId, side: OrderSide.BUY }, > { assetId: noAssetId, side: OrderSide.BUY }, > ]); > > // prices: Prices (map of assetId -> side -> price) > ``` > > `Prices` maps each outcome identifier to the requested side and price: > > ```ts Prices Type theme={null} > type Prices = Record>>; > ``` > > ```json Prices Example theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": { > "BUY": "0.08" > }, > "7305630249804085635496399869905769372294302716159034447326228509068694952392": { > "BUY": "0.91" > } > } > ``` > [tab] Python > > Call `get_prices()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch several prices in one request. The synchronous `PublicClient` and > `SecureClient` provide the same method. > > ```python theme={null} > from polymarket import PriceRequest > > prices = await client.get_prices( > requests=[ > PriceRequest(asset_id=yes_asset_id, side="BUY"), > PriceRequest(asset_id=no_asset_id, side="BUY"), > ], > ) > > # prices: dict[ClobAssetId, dict[OrderSide, Decimal]] > ``` > > The result maps each outcome identifier to the requested side and price: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": { > "BUY": "0.08" > }, > "7305630249804085635496399869905769372294302716159034447326228509068694952392": { > "BUY": "0.91" > } > } > ``` > [tab] API > > Fetch several prices in one request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/prices" \ > -H "Content-Type: application/json" \ > --data '[{"token_id":"","side":"BUY"},{"token_id":"","side":"BUY"}]' > ``` > > The response maps each outcome identifier to the requested side and price: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": { > "BUY": 0.08 > }, > "7305630249804085635496399869905769372294302716159034447326228509068694952392": { > "BUY": 0.91 > } > } > ``` ## Midpoint Price The midpoint is the average of the best bid and best ask. It provides a reference price between the two sides of the order book. ### Fetch a Midpoint > [tab] TypeScript > > Call `fetchMidpoint()` on a `PublicClient` or `SecureClient` to fetch the midpoint. > > ```ts theme={null} > const midpoint = await client.fetchMidpoint({ assetId: yesAssetId }); > > // midpoint: DecimalString > ``` > > The method returns the midpoint as a decimal string: > > ```json theme={null} > "0.085" > ``` > [tab] Python > > Call `get_midpoint()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch the midpoint. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > midpoint = await client.get_midpoint(asset_id=yes_asset_id) > > # midpoint: Decimal > ``` > > The method returns the midpoint as a `Decimal`: > > ```python theme={null} > Decimal("0.085") > ``` > [tab] API > > Fetch the midpoint: > > ```bash theme={null} > curl "https://clob.polymarket.com/midpoint?token_id=$TOKEN_ID" > ``` > > The response contains the midpoint as a decimal string: > > ```json theme={null} > { "mid": "0.085" } > ``` ### Fetch Multiple Midpoints Fetch midpoint prices for several outcomes in one request. > [!NOTE] > > Maximum 500 items per request. > [tab] TypeScript > > Call `fetchMidpoints()` on a `PublicClient` or `SecureClient` to fetch several > midpoints. > > ```ts theme={null} > const midpoints = await client.fetchMidpoints([ > { assetId: yesAssetId }, > { assetId: noAssetId }, > ]); > > // midpoints: Midpoints > ``` > > `Midpoints` maps each outcome identifier to its midpoint: > > ```ts Midpoints Type theme={null} > type Midpoints = Record; > ``` > > ```json Midpoints Example theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.085", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.915" > } > ``` > [tab] Python > > Call `get_midpoints()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch several midpoints. The synchronous `PublicClient` and `SecureClient` > provide the same method. > > ```python theme={null} > midpoints = await client.get_midpoints(asset_ids=[yes_asset_id, no_asset_id]) > > # midpoints: dict[ClobAssetId, Decimal] > ``` > > The result maps each outcome identifier to its midpoint: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.085", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.915" > } > ``` > [tab] API > > Fetch several midpoints in one request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/midpoints" \ > -H "Content-Type: application/json" \ > --data '[{"token_id":""},{"token_id":""}]' > ``` > > The response maps each outcome identifier to its midpoint: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.085", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.915" > } > ``` ## Spread The spread is the difference between the best ask and best bid. A narrower spread indicates that the two sides of the order book are closer together. ### Fetch a Spread > [tab] TypeScript > > Call `fetchSpread()` on a `PublicClient` or `SecureClient` to fetch the spread. > > ```ts theme={null} > const spread = await client.fetchSpread({ assetId: yesAssetId }); > > // spread: DecimalString > ``` > > The method returns the spread as a decimal string: > > ```json theme={null} > "0.01" > ``` > [tab] Python > > Call `get_spread()` on an `AsyncPublicClient` or `AsyncSecureClient` to fetch > the spread. The synchronous `PublicClient` and `SecureClient` provide the > same method. > > ```python theme={null} > spread = await client.get_spread(asset_id=yes_asset_id) > > # spread: Decimal > ``` > > The method returns the spread as a `Decimal`: > > ```python theme={null} > Decimal("0.01") > ``` > [tab] API > > Fetch the spread: > > ```bash theme={null} > curl "https://clob.polymarket.com/spread?token_id=$TOKEN_ID" > ``` > > The response contains the spread as a decimal string: > > ```json theme={null} > { "spread": "0.01" } > ``` ### Fetch Multiple Spreads Batch spread reads return the bid-ask spread for several outcomes in one request. > [!NOTE] > > Maximum 500 items per request. > [tab] TypeScript > > Call `fetchSpreads()` on a `PublicClient` or `SecureClient` to fetch several spreads > in one request. > > ```ts theme={null} > const spreads = await client.fetchSpreads([ > { assetId: yesAssetId }, > { assetId: noAssetId }, > ]); > > // spreads: Spreads > ``` > > The result maps each outcome identifier to its spread: > > ```ts Spreads Type theme={null} > type Spreads = Record; > ``` > > ```json Spreads Example theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.01", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.02" > } > ``` > [tab] Python > > Call `get_spreads()` on an `AsyncPublicClient` or `AsyncSecureClient` to > fetch several spreads in one request. The synchronous `PublicClient` and > `SecureClient` provide the same method. > > ```python theme={null} > spreads = await client.get_spreads(asset_ids=[yes_asset_id, no_asset_id]) > > # spreads: dict[ClobAssetId, Decimal] > ``` > > The result maps each outcome identifier to its spread: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.01", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.02" > } > ``` > [tab] API > > Fetch several spreads in one request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/spreads" \ > -H "Content-Type: application/json" \ > --data '[{"token_id":""},{"token_id":""}]' > ``` > > The response maps each outcome identifier to its spread: > > ```json theme={null} > { > "107505882767731489358349912513945399560393482969656700824895970500493757150417": "0.01", > "7305630249804085635496399869905769372294302716159034447326228509068694952392": "0.02" > } > ``` ## Last Trade Price Use the last trade price to see where an outcome most recently traded. ### Fetch a Last Trade Price > [tab] TypeScript > > Call `fetchLastTradePrice()` on a `PublicClient` or `SecureClient` to fetch the last > trade. > > ```ts theme={null} > const lastTrade = await client.fetchLastTradePrice({ assetId: yesAssetId }); > > // lastTrade: LastTradePrice | null > ``` > > `LastTradePrice` pairs the traded price with its order side: > > ```ts LastTradePrice Type theme={null} > type LastTradePrice = { > price: DecimalString; > side: OrderSide; > }; > ``` > > ```json LastTradePrice Example theme={null} > { > "price": "0.08", > "side": "SELL" > } > ``` > > When a token has never traded, `fetchLastTradePrice()` returns `null` > instead of a `LastTradePrice` object: > > ```json theme={null} > null > ``` > [tab] Python > > Call `get_last_trade_price()` on an `AsyncPublicClient` or > `AsyncSecureClient` to fetch the last trade. The synchronous `PublicClient` > and `SecureClient` provide the same method. > > ```python theme={null} > last_trade = await client.get_last_trade_price(asset_id=yes_asset_id) > > # last_trade: LastTradePrice | None > ``` > > `LastTradePrice` pairs the traded price with its order side: > > ```python LastTradePrice Type theme={null} > class LastTradePrice: > price: Decimal > side: OrderSide > ``` > > ```json LastTradePrice Example theme={null} > { > "price": "0.08", > "side": "SELL" > } > ``` > > When a token has never traded, `get_last_trade_price()` returns `None` > instead of a `LastTradePrice` object: > > ```python theme={null} > None > ``` > [tab] API > > Fetch the last trade: > > ```bash theme={null} > curl "https://clob.polymarket.com/last-trade-price?token_id=$TOKEN_ID" > ``` > > The response contains the traded price and side: > > ```json theme={null} > { > "price": "0.08", > "side": "SELL" > } > ``` > > When a token has never traded and its order book is empty, the API returns > the `"0.5"` placeholder and an empty `side` string: > > ```json theme={null} > { > "price": "0.5", > "side": "" > } > ``` ### Fetch Multiple Last Trade Prices Fetch the most recent matched trade for several outcomes in one request. > [!NOTE] > > Maximum 500 items per request. > [tab] TypeScript > > Call `fetchLastTradePrices()` on a `PublicClient` or `SecureClient` to fetch several > last trades. > > ```ts theme={null} > const lastTrades = await client.fetchLastTradePrices([ > { assetId: yesAssetId }, > { assetId: noAssetId }, > ]); > > // lastTrades: LastTradePriceForAsset[] > ``` > > Each `LastTradePriceForAsset` identifies the outcome alongside its traded > price and side: > > ```ts LastTradePriceForAsset Type theme={null} > type LastTradePriceForAsset = { > assetId: ClobAssetId; > price: DecimalString; > side: OrderSide; > }; > ``` > > ```json LastTradePriceForAsset Example theme={null} > [ > { > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "price": "0.08", > "side": "SELL" > }, > { > "assetId": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > "price": "0.91", > "side": "BUY" > } > ] > ``` > [tab] Python > > Call `get_last_trade_prices()` on an `AsyncPublicClient` or > `AsyncSecureClient` to fetch several last trades. The synchronous > `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > last_trades = await client.get_last_trade_prices( > asset_ids=[yes_asset_id, no_asset_id] > ) > > # last_trades: tuple[LastTradePriceForAsset, ...] > ``` > > Each `LastTradePriceForAsset` identifies the outcome alongside its traded > price and side: > > ```python LastTradePriceForAsset Type theme={null} > class LastTradePriceForAsset: > asset_id: ClobAssetId > price: Decimal > side: OrderSide > ``` > > ```json LastTradePriceForAsset Example theme={null} > [ > { > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "price": "0.08", > "side": "SELL" > }, > { > "asset_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > "price": "0.91", > "side": "BUY" > } > ] > ``` > [tab] API > > Fetch several last trade prices in one request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/last-trades-prices" \ > -H "Content-Type: application/json" \ > --data '[{"token_id":""},{"token_id":""}]' > ``` > > The response identifies each outcome alongside its traded price and side: > > ```json theme={null} > [ > { > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "price": "0.08", > "side": "SELL" > }, > { > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > "price": "0.91", > "side": "BUY" > } > ] > ``` Outcomes that have never traded are omitted from the batch response. ## Price History Read historical prices for an outcome token over a selected time period. > [tab] TypeScript > > Call `listPriceHistory()` on a `PublicClient` or `SecureClient`. Choose a > relative window, an explicit time range, or a point in time. > > ```ts Relative Window theme={null} > import { PriceHistoryInterval } from "@polymarket/client"; > > const pages = client.listPriceHistory({ > assetId: yesAssetId, > interval: PriceHistoryInterval.OneDay, > bucketSeconds: 3600, > }); > > for await (const page of pages) { > // page.items: PriceHistoryPoint[] > } > ``` > > ```ts Absolute Range theme={null} > const pages = client.listPriceHistory({ > assetId: yesAssetId, > start: 1788278400, > end: 1788364800, > bucketSeconds: 3600, > }); > > for await (const page of pages) { > // page.items: PriceHistoryPoint[] > } > ``` > > ```ts Point In Time theme={null} > const pages = client.listPriceHistory({ > assetId: yesAssetId, > asOf: 1788364800, > }); > const observation = await pages.firstPage(); > > // observation.items: PriceHistoryPoint[] (at most one item) > ``` > > Each `PriceHistoryPoint` carries the observation time in epoch > milliseconds, the price as a decimal string, and the window it was > observed in: > > > [accordion] Output: PriceHistoryPoint > > > > ```ts PriceHistoryPoint Type theme={null} > > type PriceHistoryPoint = { > > /** Observation time as Unix epoch milliseconds. */ > > timestamp: EpochMilliseconds; > > /** Observed price, normalized to a decimal string. */ > > price: DecimalString; > > /** Width of the observation window in seconds; zero identifies an exact tick. */ > > resolutionSeconds: number; > > }; > > ``` > > > > ```json PriceHistoryPoint Example theme={null} > > [ > > { "timestamp": 1788354000000, "price": "0.255", "resolutionSeconds": 3600 }, > > { "timestamp": 1788357600000, "price": "0.255", "resolutionSeconds": 3600 }, > > { "timestamp": 1788361200000, "price": "0.255", "resolutionSeconds": 3600 } > > ] > > ``` > > Points are oldest first. The final observation can fall between bucket > boundaries. Read `resolutionSeconds` instead of assuming uniform spacing. > > > [accordion] History Windows and Resolution > > > > * Explicit `start`/`end` ranges span at most 15 days. `start` is inclusive and `end` exclusive. > > * `PriceHistoryInterval.Max` returns full history at 12-hour buckets by default. Explicit `bucketSeconds` values of 10800 or 43200 also cover full history. Finer widths return only the last 30 days. > > * `bucketSeconds` accepts 60 to 86400 seconds, with a floor of 600 for `max`/`1m` and 300 for `1w`. Omit it to let the server choose a width for the span and available history. > > * One-minute data lasts at least 7 days, five-minute at least 60 days, and thirty-minute at least 90 days (floors, not exact horizons). Three-hour and twelve-hour data is permanent. Explicitly requesting a resolution the store cannot fill returns an empty or sparse page with `resolution_seconds` echoing the requested grid; omit `bucket_seconds` to always get the densest series that exists. > [tab] Python > > Call `list_price_history()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > Choose a relative window, an explicit time range, or a point in time. > > ```python Relative Window theme={null} > pages = client.list_price_history( > asset_id=yes_asset_id, > interval="1d", > bucket_seconds=3600, > ) > > async for page in pages: > # page.items: tuple[PriceHistoryPoint, ...] > pass > ``` > > ```python Absolute Range theme={null} > pages = client.list_price_history( > asset_id=yes_asset_id, > start=1788278400, > end=1788364800, > bucket_seconds=3600, > ) > > async for page in pages: > # page.items: tuple[PriceHistoryPoint, ...] > pass > ``` > > ```python Point in Time theme={null} > pages = client.list_price_history( > asset_id=yes_asset_id, > as_of=1788364800, > ) > page = await pages.first_page() > observation = page.items[0] if page.items else None > > # observation: PriceHistoryPoint | None > ``` > > > [accordion] Output: PriceHistoryPoint > > > > ```python PriceHistoryPoint Type theme={null} > > class PriceHistoryPoint: > > timestamp: datetime > > price: Decimal > > resolution_seconds: int > > ``` > > > > ```json PriceHistoryPoint Example theme={null} > > { > > "timestamp": "2026-09-07T17:04:00Z", > > "price": "0.955", > > "resolution_seconds": 60 > > } > > ``` > > Points are ordered oldest first. `timestamp` is a timezone-aware `datetime` and `price` is a `Decimal`. `resolution_seconds` is the observation window in seconds, with zero for an exact tick. > > > [accordion] History Windows and Resolution > > > > * Explicit ranges span at most 15 days. `start` is inclusive and `end` is exclusive. > > * Choose exactly one of `interval`, `start`, or `as_of`. An `as_of` request cannot set `bucket_seconds` or `page_size`. > > * `bucket_seconds` accepts 60 to 86400 seconds. The minimum is 600 for `max`, `all`, and `1m`, and 300 for `1w`. Omit it to let the service choose the resolution. > > * Use `interval="max"` without `bucket_seconds` for full history at the default resolution. > [tab] API > > Pass `token_id` and exactly one time form: `interval` for a relative > window, `start` (with optional `end`, epoch seconds, at most 15 days) for > an absolute range, or `as_of` for a point-in-time read. `bucket_seconds` > sets the bucket width in seconds; deeper pages come from `?cursor=`. > > ```bash Relative Window theme={null} > curl "https://data-api.polymarket.com/v2/prices-history?token_id=$TOKEN_ID&interval=1d&bucket_seconds=3600" > ``` > > ```bash Absolute Range theme={null} > curl "https://data-api.polymarket.com/v2/prices-history?token_id=$TOKEN_ID&start=1788278400&end=1788364800&bucket_seconds=3600" > ``` > > ```bash Point In Time theme={null} > curl "https://data-api.polymarket.com/v2/prices-history?token_id=$TOKEN_ID&as_of=1788364800" > ``` > > The response contains the price points under `data`, oldest first, with > the cursor pagination object: > > ```json theme={null} > { > "data": [ > { "timestamp": 1788354000, "price": 0.255, "resolution_seconds": 3600 }, > { "timestamp": 1788357600, "price": 0.255, "resolution_seconds": 3600 }, > { "timestamp": 1788361200, "price": 0.255, "resolution_seconds": 3600 } > ], > "pagination": { > "limit": 3, > "has_more": true, > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJwcmljZXNfaGlzdG9yeSI…" > } > } > ``` > > Points are oldest first. The final observation can fall between bucket > boundaries. Read `resolution_seconds` instead of assuming uniform spacing. > > > [accordion] History Windows and Resolution > > > > * Explicit `start`/`end` ranges span at most 15 days. `start` is inclusive and `end` exclusive. > > * `max` returns full history at 12-hour buckets by default. Explicit `bucket_seconds` values of 10800 or 43200 also cover full history. Finer widths return only the last 30 days. > > * `bucket_seconds` accepts 60 to 86400 seconds, with a floor of 600 for `max`/`1m` and 300 for `1w`. Omit it to let the server choose a width for the span and available history. > > * One-minute data lasts at least 7 days, five-minute at least 60 days, and thirty-minute at least 90 days (floors, not exact horizons). Three-hour and twelve-hour data is permanent. Explicitly requesting a resolution the store cannot fill returns an empty or sparse page with `resolution_seconds` echoing the requested grid; omit `bucket_seconds` to always get the densest series that exists. # Analytics Source: https://docs.polymarket.com/market-data/public-analytics Understand activity and performance across Polymarket. Use these reads to understand where trading activity is concentrated and how traders and integrations perform over time. ## Market Activity The examples below assume you already have a market object. To find or fetch one, see [**Discover Markets**](/market-data/discover-markets). > [tab] TypeScript > > Given a market, read its condition and event IDs: > > ```ts theme={null} > const conditionId = market.conditionId; > const eventId = market.events[0].id; > ``` > [tab] Python > > Given a market, read its condition and event IDs: > > ```python theme={null} > condition_id = market.condition_id > event_id = market.events[0].id > ``` > [tab] API > > Given a market object, its condition and event IDs are available in these > fields: > > ```json theme={null} > { > "conditionId": "", > "events": [{ "id": "" }] > } > ``` > > Assign the identifiers for the requests below: > > ```bash theme={null} > CONDITION_ID="" > EVENT_ID="" > ``` ### Recent Trades Review the trades recently matched in a market, including their side, price, size, outcome, wallet, and timestamp. Trades are always returned in descending timestamp order (newest first). > [tab] TypeScript > > Call `listTrades()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > const pages = client.listTrades({ conditionId: [conditionId], pageSize: 1 }); > > for await (const page of pages) { > // page.items: Trade[] > } > ``` > > > [accordion] Output: Trade\[] > > > > ```ts Trade Type theme={null} > > type Trade = { > > wallet: EvmAddress; > > side: OrderSide; > > assetId: TokenId | PositionId; > > conditionId: ConditionId; > > size: DecimalString; > > price: DecimalString; > > timestamp: EpochMilliseconds; > > transactionHash: TxHash; > > title?: string; > > slug?: string; > > icon?: string; > > eventSlug?: string; > > outcome?: string; > > outcomeIndex?: number; > > name?: string; > > pseudonym?: string; > > bio?: string; > > profileImage?: string; > > profileImageOptimized?: string; > > }; > > ``` > > > > ```json Trade Example theme={null} > > [ > > { > > "side": "SELL", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "size": "42.62", > > "price": "0.91", > > "timestamp": 1782752879000, > > "title": "Will the US confirm that aliens exist before 2027?", > > "outcome": "No", > > "wallet": "0x50a0cebecfb81dbcbfa6d38f82040343f1e3d95f", > > "assetId": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "transactionHash": "0x4f3d2c1b0a9876543210fedcba9876543210fedcba9876543210fedcba987654" > > } > > ] > > ``` > [tab] Python > > Call `list_trades()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_trades(condition_id=[condition_id], page_size=1) > > async for page in pages: > # page.items: tuple[Trade, ...] > pass > ``` > > > [accordion] Output: Trade > > > > ```python Trade Type theme={null} > > class Trade: > > wallet: EvmAddress > > asset_id: ClobAssetId > > condition_id: ConditionId > > side: OrderSide > > size: Decimal > > price: Decimal > > timestamp: datetime > > transaction_hash: TransactionHash > > title: str | None > > slug: str | None > > icon: str | None > > event_slug: str | None > > outcome: str | None > > outcome_index: int | None > > name: str | None > > pseudonym: str | None > > bio: str | None > > profile_image: str | None > > profile_image_optimized: str | None > > ``` > > > > ```json Trade Example theme={null} > > { > > "wallet": "0x84cfffc3f16dcc353094de30d4a45226eccd2f63", > > "asset_id": "100621704916396384184205224105871827982844371725320616822883322969092312254616", > > "condition_id": "0xc8a2f17f42fa8493ebae503abec9d51efa7b57c3cc59a7b88933bffaa3618387", > > "side": "BUY", > > "size": "78.55", > > "price": "0.62", > > "timestamp": "2026-09-08T17:03:34Z", > > "transaction_hash": "0x8b2fd0c7480cd78bd9f57e8b935cf10c6635d2c479c66ea26d358e1425f44a95", > > "title": "Will Real Madrid CF win on 2026-09-08?", > > "slug": "ucl-rma-int-2026-09-08-rma", > > "icon": "https://polymarket-upload.s3.us-east-2.amazonaws.com/champions-league-pic-QIUFsL8vaDdq.png", > > "event_slug": null, > > "outcome": "Yes", > > "outcome_index": null, > > "name": "mooseborzoi", > > "pseudonym": "Agitated-Bricklaying", > > "bio": null, > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-7634413-4dea3150-84ad-4278-9e45-d96e51769b7e.png", > > "profile_image_optimized": null > > } > > ``` > > `size` is in shares and `price` is in USDC per share. To read a wallet's full trade history, pass `user=address, full_history=True`. Do not combine `full_history` with `start` or `end`. > [tab] API > > List recent trades for a market: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/trades?condition=$CONDITION_ID&limit=1" > ``` > > The response contains the recent trades (row fields trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "proxy_wallet": "0xc6a5ceb4083f9209c31c45dc86f5714583f552e3", > > "side": "SELL", > > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "size": 6.96, > > "price": 0.962, > > "timestamp": 1788204232, > > "transaction_hash": "0x6929c40832394d64d84a0a9170c4174f9d9f18de23f82de05a750fdbf7350ca9", > > "title": "Will the US confirm that aliens exist before 2027?", > > "outcome": "No" > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJ0cmFkZXMi…" > > } > > } > > ``` ### Open Interest Measure the value currently held in outstanding positions for one or more markets. > [tab] TypeScript > > Call `fetchOpenInterest()` on a `PublicClient` or `SecureClient`. Pass up > to 20 condition IDs, or omit `conditionIds` for the single global figure > (served as `conditionId: null`). > > ```ts theme={null} > const openInterest = await client.fetchOpenInterest({ > conditionIds: [conditionId], > }); > > // openInterest: OpenInterest[] > ``` > > > [accordion] Output: OpenInterest\[] > > > > ```ts OpenInterest Type theme={null} > > type OpenInterest = { > > conditionId: ConditionId | null; > > value: DecimalString; > > }; > > ``` > > > > ```json OpenInterest Example theme={null} > > [ > > { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "value": "7484304.679057" > > } > > ] > > ``` > [tab] Python > > Call `get_open_interests()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > open_interest = await client.get_open_interests() > > # open_interest: tuple[OpenInterest, ...] > ``` > > > [accordion] Output: OpenInterest > > > > ```python OpenInterest Type theme={null} > > class OpenInterest: > > condition_id: ConditionId | None > > value: Decimal > > ``` > > > > ```json OpenInterest Example theme={null} > > { > > "condition_id": null, > > "value": "356037494.1056115" > > } > > ``` > > The result is a tuple of `OpenInterest` rows. Global open interest has `condition_id=None`. Pass `condition_ids=[condition_id]` to read a market’s open interest. Values are in USDC. > [tab] API > > Fetch open interest for a market: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/oi?condition=$CONDITION_ID" > ``` > > The response contains open interest by market: > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "value": 7113116.142022 > > } > > ] > > } > > ``` ### Market Holders Find the largest public holders for each outcome in a market. > [tab] TypeScript > > Call `listMarketHolders()` on a `PublicClient` or `SecureClient` and walk > the cursor pages. `pageSize` applies separately to each outcome token, so > merge groups by `assetId` across pages. Set `includePnl: true` (one > condition ID, page size at most 100) to add position economics to every > holder row. > > ```ts theme={null} > const pages = client.listMarketHolders({ > conditionIds: [conditionId], > pageSize: 1, > }); > > for await (const page of pages) { > // page.items: MetaHolder[] > } > ``` > > > [accordion] Output: MetaHolder\[] > > > > ```ts MetaHolder Type theme={null} > > type Holder = { > > wallet: EvmAddress; > > assetId: TokenId | PositionId; > > /** Net holding in shares; per-side gross when `includePnl` is set. */ > > amount: DecimalString; > > outcomeIndex: number | null; > > verified: boolean; > > name: string | null; > > pseudonym: string | null; > > bio: string | null; > > displayUsernamePublic: boolean; > > profileImage: string | null; > > profileImageOptimized: string | null; > > avgPrice?: DecimalString | null; > > entryCostUsdc?: DecimalString | null; > > currentPrice?: DecimalString | null; > > currentValue?: DecimalString | null; > > realizedPnl?: DecimalString | null; > > unrealizedPnl?: DecimalString | null; > > totalPnl?: DecimalString | null; > > }; > > > > type MetaHolder = { > > assetId: TokenId | PositionId; > > /** Holders for this outcome, ordered by amount descending. */ > > holders: Holder[]; > > }; > > ``` > > > > ```json MetaHolder Example theme={null} > > [ > > { > > "assetId": "92338023949892178944669766466918011858071833335063600591564160751176113496073", > > "holders": [ > > { > > "wallet": "0x1b5ca5e84705cd14ca9953b57434094cac726c0f", > > "amount": "1878.77239", > > "outcomeIndex": 0, > > "verified": false, > > "name": null > > } > > ] > > } > > ] > > ``` > [tab] Python > > Call `list_market_holders()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_market_holders(condition_ids=[condition_id], page_size=1) > > async for page in pages: > # page.items: tuple[MetaHolder, ...] > pass > ``` > > `page_size` applies separately to each outcome asset. Merge groups across pages by `asset_id`. Set `include_pnl=True` to include position economics for one condition, with a page size of at most 100. > > > [accordion] Output: MetaHolder > > > > ```python Holder Type theme={null} > > class Holder: > > wallet: EvmAddress > > asset_id: ClobAssetId > > amount: Decimal > > outcome_index: int | None > > display_username_public: bool > > verified: bool > > name: str | None > > pseudonym: str | None > > bio: str | None > > profile_image: str | None > > profile_image_optimized: str | None > > avg_price: Decimal | None > > entry_cost_usdc: Decimal | None > > current_price: Decimal | None > > current_value: Decimal | None > > realized_pnl: Decimal | None > > unrealized_pnl: Decimal | None > > total_pnl: Decimal | None > > ``` > > > > ```python MetaHolder Type theme={null} > > class MetaHolder: > > asset_id: ClobAssetId > > holders: tuple[Holder, ...] > > ``` > > > > ```json MetaHolder Example theme={null} > > { > > "asset_id": "92338023949892178944669766466918011858071833335063600591564160751176113496073", > > "holders": [ > > { > > "wallet": "0x1b5ca5e84705cd14ca9953b57434094cac726c0f", > > "asset_id": "92338023949892178944669766466918011858071833335063600591564160751176113496073", > > "amount": "1878.77239", > > "outcome_index": 0, > > "display_username_public": false, > > "verified": false, > > "name": null, > > "pseudonym": null, > > "bio": null, > > "profile_image": null, > > "profile_image_optimized": null, > > "avg_price": "0.2794", > > "entry_cost_usdc": "524.991", > > "current_price": "1.0", > > "current_value": "1878.7723", > > "realized_pnl": "0.0001", > > "unrealized_pnl": "1353.7812", > > "total_pnl": "1353.7813" > > } > > ] > > } > > ``` > [tab] API > > List the largest holders for a market: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/holders?condition=$CONDITION_ID&limit=1" > ``` > > The response groups holders by outcome (holder fields trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "holders": [ > > { > > "proxy_wallet": "0xcd09c7f5132a160b41578a79a9e3453da7aeda63", > > "amount": 550253.927993, > > "outcome_index": 0, > > "name": "ShayaEredyon" > > } > > ] > > }, > > { > > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "holders": [ > > { > > "proxy_wallet": "0xa2cd4ccda9a1f95949df7a3355c4c2daa0642ba0", > > "amount": 1455975.51944, > > "outcome_index": 1, > > "name": "0xA2cd4CcdA9A1f95949DF7A3355C4c2DAa0642Ba0-1729178570395" > > } > > ] > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJob2xkZXJzIi…" > > } > > } > > ``` ### Event Live Volume Summarize activity across an event and break the volume down by market. > [tab] TypeScript > > Call `fetchEventLiveVolume()` on a `PublicClient` or `SecureClient`. Pass > one or more event IDs; a list spans events and returns one combined > result. > > ```ts theme={null} > const liveVolume = await client.fetchEventLiveVolume({ > eventIds: [eventId], > }); > > // liveVolume: LiveVolume > ``` > > > [accordion] Output: LiveVolume > > > > ```ts LiveVolume Type theme={null} > > type MarketLiveVolume = { > > /** Condition ID of the market, or `null` when the source row is unidentified. */ > > conditionId: ConditionId | null; > > /** Cumulative one-side taker volume in shares. */ > > takerVolume: DecimalString; > > }; > > > > type LiveVolume = { > > /** Sum of every returned market's taker volume, in shares. */ > > takerVolumeTotal: DecimalString; > > /** Markets ordered by taker volume descending. */ > > markets: MarketLiveVolume[]; > > }; > > ``` > > > > ```json LiveVolume Example theme={null} > > { > > "takerVolumeTotal": "698627.625937", > > "markets": [ > > { > > "conditionId": "0x435620fa180dbedb59d34f164d82a447304436b57e87850ca3d1ab2070667006", > > "takerVolume": "631069.486412" > > }, > > { > > "conditionId": "0xce67b495c754cd29548e0381d18e9b4701446fa9e32c29d7eec3e7e72ad55152", > > "takerVolume": "67558.139525" > > } > > ] > > } > > ``` > [tab] Python > > Call `get_event_live_volume()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > live_volume = await client.get_event_live_volume(event_ids=[int(event_id)]) > > # live_volume: LiveVolume > ``` > > > [accordion] Output: LiveVolume > > > > ```python MarketLiveVolume Type theme={null} > > class MarketLiveVolume: > > condition_id: ConditionId | None > > taker_volume: Decimal > > ``` > > > > ```python LiveVolume Type theme={null} > > class LiveVolume: > > taker_volume_total: Decimal > > markets: tuple[MarketLiveVolume, ...] > > ``` > > > > ```json LiveVolume Example theme={null} > > { > > "taker_volume_total": "4439931.266595", > > "markets": [ > > { > > "condition_id": "0xe7f239d76b59c4e614f0bdb80467026da833083e38a31a27fde8e0907417ea12", > > "taker_volume": "1057493.399838" > > }, > > { > > "condition_id": "0x4d162a40c3e3f458b0e0017485d7f9e6ead0cdd0573e38b26e0d5420525ccfa4", > > "taker_volume": "780331.374022" > > }, > > { > > "condition_id": "0xc8929e80e74ae959b3ed9b9e1c5e0903ad38e02e1339462e3acf8b49bbca35a9", > > "taker_volume": "588112.023677" > > }, > > { > > "condition_id": "0x02507350fc2b81c3af36c659a805adbda9b0a81e63a27b29cb273cdd7dbc072e", > > "taker_volume": "576353.148052" > > }, > > { > > "condition_id": "0x626d0441b078eefbe2c49047960e7a3b6b4512c235507a2528ccc0f95f2474a6", > > "taker_volume": "507319.025175" > > }, > > { > > "condition_id": "0xb4022c0b2718eca7ad27195f2d48f06527fa000269d188e1d3001ff8bbc16956", > > "taker_volume": "479549.81298" > > }, > > { > > "condition_id": "0xc60022fe066abd6f96c375adb09f38d92c4931f09c10b805354581b4e5465e93", > > "taker_volume": "313649.055908" > > }, > > { > > "condition_id": "0x4092815fea8f91e60586882d45fa2f61bfca8a36d595f47fdea9eec5d2893025", > > "taker_volume": "137123.426943" > > } > > ] > > } > > ``` > > Pass one or more integer event IDs to get a combined result. `taker_volume_total` is total taker volume in shares. `markets` contains the per-market breakdown. > [tab] API > > Fetch live volume for an event: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/live-volume?event_id=$EVENT_ID" > ``` > > The response contains the event's total taker volume and its market > breakdown (additional rows trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": { > > "taker_volume_total": 65834357.807271, > > "conditions": [ > > { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "taker_volume": 37828643.727694 > > }, > > { > > "condition_id": "0xa7962b12241616d83dcb8c70fc33aa0f48b1ec46a3ad6a23db21d3885dedc4cb", > > "taker_volume": 11161362.976257 > > } > > ] > > } > > } > > ``` > > Markets are ordered by taker volume, largest first. ### Market Resolution Check a market's resolution progress. > [tab] TypeScript > > Call `fetchResolutions()` on an existing `PublicClient` or `SecureClient`. > If needed, [create a Public Client](/getting-started/typescript#create-a-public-client) first. > > ```ts theme={null} > const resolutions = await client.fetchResolutions({ > conditionIds: [conditionId], > }); > > for (const resolution of resolutions) { > console.log( > resolution.status, > resolution.transactionHash, > resolution.logIndex, > ); > } > > // resolutions: Resolution[] > ``` > > Each row includes its `status` and `lastUpdatedAt`. `payouts` is present > when published. No matching resolution returns an empty array. > > For UMA question lifecycle rows, `transactionHash` identifies the latest > lifecycle transaction, while `logIndex` is the initial `RequestPrice` event's > log index. They can belong to different transactions. Do not combine them as > a log locator. > > This rule does not apply uniformly to every row. V2 condition-only rows can > return `null` for both fields. CTF condition-resolution fallback rows instead > carry the paired transaction and log index of the condition-resolution event. > > Settlement estimates use these optional fields on `Resolution`: > > | Field | Type | > | - | - | > | `expectedSettlementTime` | `IsoDateTimeString` or `undefined` | > | `settlementTimeBasis` | `ResolutionSettlementTimeBasis` or `undefined` | > > `expectedSettlementTime` is an ISO datetime string in UTC. The fields are > omitted when no estimate is available. Import `ResolutionSettlementTimeBasis` > from `@polymarket/client` to interpret the estimate: > > | Enum member | Estimate | > | - | - | > | `ManagedProposalExpiration` | End of the managed UMA proposal's challenge window | > | `ProposalExpiration` | End of the ordinary UMA proposal's challenge window | > | `DvmRoundEstimate` | Earliest end of the UMA voting round the dispute can settle in | > | `Liveness` | Proposal time plus the Polymarket v2 oracle's liveness window | > [tab] Python > > Call `get_resolutions()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > If needed, [create a Public Client](/getting-started/python#create-a-public-client) first. > > ```python theme={null} > resolutions = await client.get_resolutions(condition_ids=[condition_id]) > > for resolution in resolutions: > print(resolution.status, resolution.transaction_hash, resolution.log_index) > > # resolutions: tuple[Resolution, ...] > ``` > > Each row includes `status` and `last_updated_at`. `payouts` contains the published payouts when available. No matching resolution returns an empty tuple. > > For UMA question lifecycle rows, `transaction_hash` identifies the latest > lifecycle transaction, while `log_index` is the initial `RequestPrice` event's > log index. They can belong to different transactions. Do not combine them as > a log locator. > > This rule does not apply uniformly to every row. V2 condition-only rows can > return `None` for both fields. CTF condition-resolution fallback rows instead > carry the paired transaction and log index of the condition-resolution event. > > Settlement estimates use these fields on `Resolution`: > > | Field | Type | > | - | - | > | `expected_settlement_time` | `datetime` or `None` | > | `settlement_time_basis` | `ResolutionSettlementTimeBasis` or `None` | > > `expected_settlement_time` is a timezone-aware UTC `datetime`. The fields are > `None` when no estimate is available. Import `ResolutionSettlementTimeBasis` > from `polymarket` to interpret the estimate: > > | Enum member | Estimate | > | - | - | > | `MANAGED_PROPOSAL_EXPIRATION` | End of the managed UMA proposal's challenge window | > | `PROPOSAL_EXPIRATION` | End of the ordinary UMA proposal's challenge window | > | `DVM_ROUND_ESTIMATE` | Earliest end of the UMA voting round the dispute can settle in | > | `LIVENESS` | Proposal time plus the Polymarket v2 oracle's liveness window | > [tab] API > > Fetch resolution progress for the market: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/resolutions?condition=$CONDITION_ID" > ``` > > Illustrative response (fields trimmed): > > > [accordion] Output: Resolutions > > > > ```json theme={null} > > { > > "data": [ > > { > > "condition_id": "0x02507350fc2b81c3af36c659a805adbda9b0a81e63a27b29cb273cdd7dbc072e", > > "status": "resolved", > > "transaction_hash": "0x1fc7a1df48dcac15859af515ebd77183c3487591181469a60dbf115b705f005a", > > "log_index": "170", > > "last_update_timestamp": "1785355919" > > } > > ] > > } > > ``` > > `data` contains resolution rows with `status` and `last_update_timestamp`, or > an empty list when no resolution matches. While a market waits on its oracle, > a row can carry the settlement estimate fields described below. > > For UMA question lifecycle rows, `transaction_hash` identifies the latest > lifecycle transaction, while `log_index` is the initial `RequestPrice` event's > log index as a numeric string. They can belong to different transactions. > Do not combine them as a log locator. > > V2 condition-only rows can return empty strings for both fields when provenance > is unavailable. CTF condition-resolution fallback rows instead return the > paired transaction and log index of the condition-resolution event. > > A row that is waiting on an oracle can carry `expected_settlement_time` > (RFC3339 UTC) and `settlement_time_basis`. Both are omitted whenever no > estimate applies, including settled markets and proposals under extended > review. > > | `settlement_time_basis` | Row state | `expected_settlement_time` | > | - | - | - | > | `managed_proposal_expiration` | UMA proposal on the managed oracle, still in its challenge window | End of the challenge window | > | `proposal_expiration` | UMA proposal on the ordinary oracle, still in its challenge window | End of the challenge window | > | `dvm_round_estimate` | UMA proposal under dispute | Earliest end of the UMA voting round the dispute can settle in | > | `liveness` | Proposal on Polymarket's v2 oracle | Proposal time plus its liveness window | #### Settlement Estimates Treat an estimate as the earliest time the market can settle, not as a deadline. A disputed vote can roll into a later voting round, and a proposal's liveness window can already have elapsed while it awaits finalization. No estimate is available for settled markets, proposals under extended review, or markets that are still initialized or active. ### Token Lookup Find the market and outcome for a token, or list all tokens of a condition in one read. > [tab] TypeScript > > Call `fetchTokenReferences()` on an existing `PublicClient` or `SecureClient`. > If needed, [create a Public Client](/getting-started/typescript#create-a-public-client) first. > > ```ts theme={null} > const assetId = > "107505882767731489358349912513945399560393482969656700824895970500493757150417"; > const references = await client.fetchTokenReferences({ assetIds: [assetId] }); > > for (const reference of references) { > console.log(reference.assetId, reference.outcome, reference.outcomeIndex); > } > > // references: TokenReference[] > ``` > > > [accordion] Output: TokenReference\[] > > > > ```ts TokenReference Type theme={null} > > type TokenReference = { > > assetId: ClobAssetId; > > conditionId: ConditionId; > > structuralConditionId: ConditionId | null; > > module: TokenModule; > > outcomeIndex: number; > > clobIndex: number | null; > > outcome: string | null; > > oppositeAssetId: ClobAssetId | null; > > resolved: boolean; > > finalPrice: DecimalString | null; > > title: string | null; > > marketSlug: string | null; > > closed: boolean | null; > > negRisk: boolean | null; > > negRiskMarketId: ConditionId | null; > > questionIndex: number | null; > > eventId: EventId | null; > > eventSlug: string | null; > > }; > > ``` > > `finalPrice` is the settled payout as a decimal string, or `null` when > unavailable. Settlement data can take up to a minute to update. > > To look up a condition instead, supply only `conditionIds`: > > ```ts theme={null} > const references = await client.fetchTokenReferences({ > conditionIds: [conditionId], > }); > ``` > > Pass up to 50 `assetIds` or 10 `conditionIds`, not both. Results are not > paginated. Unknown asset IDs are omitted. > [tab] Python > > Call `get_token_references()` on an existing `AsyncPublicClient` or > `AsyncSecureClient`. If needed, > [create a Public Client](/getting-started/python#create-a-public-client) first. > Sync clients expose the same method. > > ```python theme={null} > asset_id = "107505882767731489358349912513945399560393482969656700824895970500493757150417" > references = await client.get_token_references(asset_ids=[asset_id]) > > for reference in references: > print(reference.asset_id, reference.outcome, reference.outcome_index) > > # references: tuple[TokenReference, ...] > ``` > > > [accordion] Output: TokenReference > > > > ```python TokenReference Type theme={null} > > class TokenReference(BaseModel): > > asset_id: ClobAssetId > > condition_id: ConditionId > > structural_condition_id: ConditionId | None > > module: TokenModule > > outcome_index: int > > clob_index: int | None > > outcome: str | None > > opposite_asset_id: ClobAssetId | None > > resolved: bool > > final_price: Decimal | None > > title: str | None > > market_slug: str | None > > closed: bool | None > > neg_risk: bool | None > > neg_risk_market_id: ConditionId | None > > question_index: int | None > > event_id: EventId | None > > event_slug: str | None > > ``` > > `final_price` is the settled payout as a `Decimal`, or `None` when > unavailable. Settlement data can take up to a minute to update. > > To look up a condition instead, supply only `condition_ids`: > > ```python theme={null} > references = await client.get_token_references(condition_ids=[condition_id]) > ``` > > Pass up to 50 `asset_ids` or 10 `condition_ids`, not both. Results are not > paginated. Unknown asset IDs are omitted. > [tab] API > > Look up tokens by ID: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/tokens?token_id=$TOKEN_ID,$OTHER_TOKEN_ID" > ``` > > Example response: > > > [accordion] Output: Token References > > > > ```json theme={null} > > { > > "data": [ > > { > > "token_id": "123", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "structural_condition_id": null, > > "module": "v1_ctf", > > "outcome_index": 1, > > "clob_index": 0, > > "outcome": "Yes", > > "opposite_token_id": "124", > > "resolved": true, > > "final_price": 0.5, > > "title": "Example Market", > > "market_slug": "example-market", > > "closed": true, > > "neg_risk": false, > > "neg_risk_market_id": null, > > "question_index": null, > > "event_id": 1234, > > "event_slug": "example-event" > > } > > ] > > } > > ``` > > To list all tokens for a condition: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/tokens?condition=$NEG_RISK_MARKET_ID" > ``` > > Use `token_id` (up to 50 IDs) or `condition` (up to 10 IDs), not both. > Separate multiple IDs with commas. Results are not paginated. Unknown token > IDs are omitted. ## Trader Leaderboard Compare trader volume and profit and loss over a selected period. > [tab] TypeScript > > Call `listTraderLeaderboard()` on a `PublicClient` or `SecureClient`. > `window` defaults to one day, `category` to overall, and `sortBy` to PnL. > Tied traders share a rank and the next rank skips. > > ```ts theme={null} > import { LeaderboardWindow, TraderLeaderboardSort } from "@polymarket/client"; > > const pages = client.listTraderLeaderboard({ > window: LeaderboardWindow.Day, > sortBy: TraderLeaderboardSort.Pnl, > pageSize: 1, > }); > > for await (const page of pages) { > // page.items: TraderLeaderboardEntry[] > } > ``` > > > [accordion] Output: TraderLeaderboardEntry\[] > > > > ```ts TraderLeaderboardEntry Type theme={null} > > type TraderLeaderboardEntry = { > > /** Competition rank; ties share a rank and the next rank skips. */ > > rank: number; > > wallet: EvmAddress; > > /** PnL in USD for the selected window. */ > > pnl: DecimalString; > > /** Both-sides traded volume in shares. */ > > volume: DecimalString; > > userName: string | null; > > profileImage: string | null; > > xUsername: string | null; > > verified: boolean; > > }; > > ``` > > > > ```json TraderLeaderboardEntry Example theme={null} > > [ > > { > > "rank": 1, > > "wallet": "0xfe787d2da716d60e8acff57fb87eb13cd4d10319", > > "pnl": "372027.33333288063", > > "volume": "3036239.1641930016", > > "userName": "ferrariChampions2026", > > "verified": false > > } > > ] > > ``` > > Call `fetchTraderLeaderboardStanding()` on a `PublicClient` or > `SecureClient` to read one wallet's standing on both boards. > > ```ts theme={null} > const standing = await client.fetchTraderLeaderboardStanding({ > user: wallet, > window: LeaderboardWindow.Day, > }); > > // standing: TraderLeaderboardStanding | null > ``` > > When called on a `SecureClient`, `user` can be omitted and defaults to the > authenticated account's wallet. > > > [accordion] Output: TraderLeaderboardStanding > > > > ```ts TraderLeaderboardStanding Type theme={null} > > type TraderLeaderboardStanding = { > > wallet: EvmAddress; > > pnl: DecimalString; > > volume: DecimalString; > > pnlRank: number | null; > > volumeRank: number | null; > > userName: string | null; > > profileImage: string | null; > > xUsername: string | null; > > verified: boolean; > > }; > > ``` > > > > ```json TraderLeaderboardStanding Example theme={null} > > { > > "wallet": "0xfe787d2da716d60e8acff57fb87eb13cd4d10319", > > "pnl": "420711.02199365385", > > "volume": "3920263.4910460007", > > "pnlRank": 1, > > "volumeRank": 1, > > "userName": "ferrariChampions2026", > > "profileImage": null, > > "xUsername": null, > > "verified": false > > } > > ``` > > A `null` rank means the wallet is unranked on that board. > [tab] Python > > Call `list_trader_leaderboard()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_trader_leaderboard(window="day", sort_by="PNL", page_size=1) > > async for page in pages: > # page.items: tuple[TraderLeaderboardEntry, ...] > pass > ``` > > > [accordion] Output: TraderLeaderboardEntry > > > > ```python TraderLeaderboardEntry Type theme={null} > > class TraderLeaderboardEntry: > > rank: int > > wallet: EvmAddress > > pnl: Decimal > > volume: Decimal > > user_name: str | None > > profile_image: str | None > > x_username: str | None > > verified: bool > > ``` > > > > ```json TraderLeaderboardEntry Example theme={null} > > { > > "rank": 1, > > "wallet": "0x31e5d54aded22aa7cd80dbe9e33102abe2504879", > > "pnl": "966725.5781960003", > > "volume": "1491184.383039", > > "user_name": "Noprajsk", > > "profile_image": null, > > "x_username": null, > > "verified": false > > } > > ``` > > `pnl` is in USDC and `volume` is in shares. Tied traders share a rank and the next rank skips. > > Call `get_trader_leaderboard_standing()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > standing = await client.get_trader_leaderboard_standing( > user="0x983eedfbd75803602e4a6e6ea9aab6dc6b9c6748", > window="day", > ) > > # standing: TraderLeaderboardStanding | None > ``` > > > [accordion] Output: TraderLeaderboardStanding > > > > ```python TraderLeaderboardStanding Type theme={null} > > class TraderLeaderboardStanding: > > wallet: EvmAddress > > pnl: Decimal > > volume: Decimal > > user_name: str | None > > profile_image: str | None > > x_username: str | None > > verified: bool > > pnl_rank: int | None > > volume_rank: int | None > > ``` > > > > ```json TraderLeaderboardStanding Example theme={null} > > { > > "wallet": "0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b", > > "pnl": "957.4473660823187", > > "volume": "64431.760178000004", > > "user_name": "Car", > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-501613-aa434e55-7732-41b1-9650-83a9d1d716ef.png", > > "x_username": "CarOnPolymarket", > > "verified": true, > > "pnl_rank": 1045, > > "volume_rank": 424 > > } > > ``` > > `None` means no standing is available. A `None` rank means the wallet is unranked on that board. Secure clients default `user` to the authenticated wallet. > [tab] API > > List the trader leaderboard for a time period. The board ranks by PnL by > default; pass `sort_by=VOLUME` for the volume board: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/leaderboard?time_period=day&limit=1" > ``` > > The response contains the ranked traders (row fields trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "rank": 1, > > "user_id": "0x34dd4a4b70eaf79a17878f7938263c801d4dfd83", > > "user_name": "vito3corleone", > > "pnl": 470760.47323424, > > "volume": 1485869.23, > > "verified": false > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJsZWFkZXJib2FyZCI…" > > } > > } > > ``` ## Biggest Winners Compare individual winning positions by their profit at resolution. > [tab] TypeScript > > Call `listBiggestWinners()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > import { LeaderboardWindow } from "@polymarket/client"; > > const pages = client.listBiggestWinners({ > window: LeaderboardWindow.Day, > pageSize: 10, > }); > > for await (const page of pages) { > // page.items: BiggestWinner[] > } > ``` > > `window` selects the resolution period. Each row is one position. Check > `kind` before using `eventId`, which is `null` for Combos. > [tab] Python > > Call `list_biggest_winners()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_biggest_winners(window="day", page_size=10) > > async for page in pages: > # page.items: tuple[MarketBiggestWinner | ComboBiggestWinner, ...] > pass > ``` > > `window` selects the resolution period. Each row is one winning position. Check `kind` before accessing market-specific fields. `MarketBiggestWinner` identifies the asset with `asset_id` and includes `event_id`. `ComboBiggestWinner` uses `position_id`. > [tab] API > > List the largest wins resolved in the last day: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/biggest-winners?time_period=day&limit=10" > ``` > > `data` contains one row per winning position. Continue with > `pagination.next_cursor` as `cursor` until it is `null`. ## Builder Analytics Evaluate the reach of a builder integration through its attributed trading activity. ### Builder Leaderboard Compare builders by attributed volume and active users. > [tab] TypeScript > > Call `listBuilderLeaderboard()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > import { LeaderboardWindow } from "@polymarket/client"; > > const pages = client.listBuilderLeaderboard({ > window: LeaderboardWindow.Day, > pageSize: 1, > }); > > for await (const page of pages) { > // page.items: BuilderStanding[] > } > ``` > > > [accordion] Output: BuilderStanding\[] > > > > ```ts BuilderStanding Type theme={null} > > type BuilderStanding = { > > rank: number; > > /** Display name; use `builderCode` as the stable identifier. */ > > builderName: string; > > builderCode: BuilderCode; > > profileImage?: string; > > verified: boolean; > > /** Builder-attributed volume in shares. */ > > volume: DecimalString; > > activeUsers: number; > > }; > > ``` > > > > ```json BuilderStanding Example theme={null} > > [ > > { > > "rank": 1, > > "builderName": "betmoar", > > "builderCode": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "verified": true, > > "volume": "1994518.4590840002", > > "activeUsers": 150 > > } > > ] > > ``` > [tab] Python > > Call `list_builder_leaderboard()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_builder_leaderboard(window="day", page_size=1) > > async for page in pages: > # page.items: tuple[BuilderStanding, ...] > pass > ``` > > > [accordion] Output: BuilderStanding > > > > ```python BuilderStanding Type theme={null} > > class BuilderStanding: > > rank: int > > builder_name: str > > builder_code: HexString > > profile_image: str | None > > verified: bool > > volume: Decimal > > active_users: int > > ``` > > > > ```json BuilderStanding Example theme={null} > > { > > "rank": 1, > > "builder_name": "betmoar", > > "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/betmoar_2.png", > > "verified": true, > > "volume": "3420022.424486001", > > "active_users": 165 > > } > > ``` > > Use `builder_code` as the stable identifier. `volume` is builder-attributed trading volume in shares. > [tab] API > > List the builder leaderboard for a time period: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/builders/leaderboard?time_period=day&limit=1" > ``` > > The response contains the ranked builders (row fields trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "rank": 1, > > "builder_name": "betmoar", > > "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "verified": true, > > "volume": 3001409.090169, > > "active_users": 160 > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJidWlsZGVyc19sZWFkZXJib2FyZCI…" > > } > > } > > ``` ### Builder Volume Track attributed builder volume and active users over time. > [tab] TypeScript > > Call `fetchBuilderVolume()` on a `PublicClient` or `SecureClient`. > `interval` picks the bucket width and `bucketLimit` counts the most recent > complete buckets (at most 90); every builder active in a bucket gets one > row. > > ```ts theme={null} > import { BuilderVolumeInterval } from "@polymarket/client"; > > const builderVolume = await client.fetchBuilderVolume({ > interval: BuilderVolumeInterval.Day, > bucketLimit: 1, > }); > > // builderVolume: BuilderVolumePoint[] > ``` > > > [accordion] Output: BuilderVolumePoint\[] > > > > ```ts BuilderVolumePoint Type theme={null} > > type BuilderVolumePoint = { > > /** UTC start date of the volume bucket. */ > > bucketDate: IsoCalendarDateString; > > /** Builder rank within this bucket. */ > > rank: number; > > /** Display name; use `builderCode` as the stable identifier. */ > > builderName: string; > > builderCode: BuilderCode; > > profileImage?: string; > > verified: boolean; > > /** Builder-attributed volume in shares for this bucket. */ > > volume: DecimalString; > > activeUsers: number; > > }; > > ``` > > > > ```json BuilderVolumePoint Example theme={null} > > [ > > { > > "bucketDate": "2026-09-03", > > "rank": 1, > > "builderName": "betmoar", > > "builderCode": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "verified": true, > > "volume": "1990330.1396780002", > > "activeUsers": 150 > > } > > ] > > ``` > [tab] Python > > Call `get_builder_volumes()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > builder_volume = await client.get_builder_volumes(interval="day", bucket_limit=1) > > # builder_volume: tuple[BuilderVolumePoint, ...] > ``` > > > [accordion] Output: BuilderVolumePoint > > > > ```python BuilderVolumePoint Type theme={null} > > class BuilderVolumePoint: > > rank: int > > builder_name: str > > builder_code: HexString > > profile_image: str | None > > verified: bool > > volume: Decimal > > active_users: int > > bucket_date: date > > ``` > > > > ```json BuilderVolumePoint Example theme={null} > > { > > "rank": 1, > > "builder_name": "betmoar", > > "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/betmoar_2.png", > > "verified": true, > > "volume": "3419926.8151110006", > > "active_users": 165, > > "bucket_date": "2026-09-08" > > } > > ``` > > The result is a tuple of calendar buckets. `bucket_limit` counts dates, not rows, and accepts at most 90. Each active builder has a row for that date. `volume` is in shares. > [tab] API > > Fetch builder volume over time. Each row is one builder's volume in one > time bucket, with the builder's rank within that bucket; `limit` counts > the most recent buckets: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/builders/volume?interval=day&limit=1" > ``` > > The response contains builder activity by time bucket (row fields and > additional rows trimmed for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "date": "2026-08-31", > > "rank": 1, > > "builder_name": "betmoar", > > "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", > > "verified": true, > > "volume": 2961462.652905, > > "active_users": 160 > > }, > > { > > "date": "2026-08-31", > > "rank": 2, > > "builder_name": "traderline", > > "builder_code": "0x6b0e773fada0a2ec67c956b25a737d353a534ea33db56c717ba7854346c67984", > > "verified": true, > > "volume": 2445464.426092, > > "active_users": 112 > > } > > ] > > } > > ``` # Real-Time Data Source: https://docs.polymarket.com/market-data/realtime-data Keep market data current with Polymarket's real-time feeds. Use Polymarket's real-time feeds to react as market conditions and related data change. They keep the public market data your application depends on current without repeated polling. For authenticated order and trade updates, see [Real-Time Order Updates](/trading/realtime-order-updates). ## Market Stream Use the market stream to keep your application in sync with changes to a market's order book and trading state. > [tab] TypeScript > > The unified SDK uses `assetId` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Given a `PublicClient` or `SecureClient`, subscribe to the `market` topic with one or > more outcome IDs: > > ```ts theme={null} > const assetId = ""; > > const stream = await client.subscribe([ > { > topic: "market", > assetIds: [assetId], > }, > ]); > > for await (const event of stream) { > switch (event.type) { > case "book": > // event: MarketBookEvent > break; > case "price_change": > // event: MarketPriceChangeEvent > break; > case "last_trade_price": > // event: MarketLastTradePriceEvent > break; > case "tick_size_change": > // event: MarketTickSizeChangeEvent > break; > } > } > ``` > > > [accordion] Standard Market Events > > > > #### Order Book > > > > ```ts MarketBookEvent Type theme={null} > > type OrderBookLevel = { > > price: DecimalString; > > size: DecimalString; > > }; > > > > type MarketBookEvent = { > > topic: "market"; > > type: "book"; > > payload: { > > conditionId: ConditionId; > > assetId: ClobAssetId; > > bids: OrderBookLevel[]; > > asks: OrderBookLevel[]; > > hash?: string | null; > > timestamp?: string | null; > > minOrderSize?: DecimalString | null; > > tickSize?: DecimalString | null; > > negRisk?: boolean | null; > > lastTradePrice?: DecimalString | null; > > }; > > }; > > ``` > > > > ```json MarketBookEvent Example theme={null} > > { > > "topic": "market", > > "type": "book", > > "payload": { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "bids": [{ "price": "0.08", "size": "33343.4" }], > > "asks": [{ "price": "0.09", "size": "163939.58" }], > > "hash": "0xabc123…", > > "timestamp": "1782753357257" > > } > > } > > ``` > > > > #### Price Change > > > > ```ts MarketPriceChangeEvent Type theme={null} > > type PriceChange = { > > assetId: ClobAssetId; > > price: DecimalString; > > size: DecimalString; > > side: OrderSide; > > hash?: string | null; > > bestBid?: DecimalString | null; > > bestAsk?: DecimalString | null; > > }; > > > > type MarketPriceChangeEvent = { > > topic: "market"; > > type: "price_change"; > > payload: { > > conditionId: ConditionId; > > priceChanges: PriceChange[]; > > timestamp?: string | null; > > }; > > }; > > ``` > > > > ```json MarketPriceChangeEvent Example theme={null} > > { > > "topic": "market", > > "type": "price_change", > > "payload": { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "priceChanges": [ > > { > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "33343.4", > > "side": "BUY", > > "hash": "56621a121a47ed9333273e21c83b660cff37ae50", > > "bestBid": "0.08", > > "bestAsk": "0.09" > > } > > ], > > "timestamp": "1782753357257" > > } > > } > > ``` > > > > #### Last Trade Price > > > > ```ts MarketLastTradePriceEvent Type theme={null} > > type MarketLastTradePriceEvent = { > > topic: "market"; > > type: "last_trade_price"; > > payload: { > > conditionId: ConditionId; > > assetId: ClobAssetId; > > price: DecimalString; > > size?: DecimalString | null; > > feeRateBps?: DecimalString | null; > > side: OrderSide; > > timestamp?: string | null; > > transactionHash?: string | null; > > }; > > }; > > ``` > > > > ```json MarketLastTradePriceEvent Example theme={null} > > { > > "topic": "market", > > "type": "last_trade_price", > > "payload": { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "219.217767", > > "feeRateBps": "0", > > "side": "SELL", > > "timestamp": "1782753357257", > > "transactionHash": "0xeeefff…" > > } > > } > > ``` > > > > #### Tick Size Change > > > > ```ts MarketTickSizeChangeEvent Type theme={null} > > type MarketTickSizeChangeEvent = { > > topic: "market"; > > type: "tick_size_change"; > > payload: { > > conditionId: ConditionId; > > assetId: ClobAssetId; > > oldTickSize?: DecimalString | null; > > newTickSize: DecimalString; > > timestamp?: string | null; > > }; > > }; > > ``` > > > > ```json MarketTickSizeChangeEvent Example theme={null} > > { > > "topic": "market", > > "type": "tick_size_change", > > "payload": { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "oldTickSize": "0.01", > > "newTickSize": "0.001", > > "timestamp": "1782753357257" > > } > > } > > ``` > > Enable `customFeatureEnabled` to include top-of-book and market lifecycle > updates: > > ```ts theme={null} > const stream = await client.subscribe([ > { > topic: "market", > assetIds: [assetId], > customFeatureEnabled: true, > }, > ]); > > for await (const event of stream) { > switch (event.type) { > case "book": > // event: MarketBookEvent > break; > case "price_change": > // event: MarketPriceChangeEvent > break; > case "last_trade_price": > // event: MarketLastTradePriceEvent > break; > case "tick_size_change": > // event: MarketTickSizeChangeEvent > break; > case "best_bid_ask": > // event: MarketBestBidAskEvent > break; > case "new_market": > // event: NewMarketEvent > break; > case "market_resolved": > // event: MarketResolvedEvent > break; > } > } > ``` > > > [accordion] Additional Market Events > > > > #### Best Bid and Ask > > > > ```ts MarketBestBidAskEvent Type theme={null} > > type MarketBestBidAskEvent = { > > topic: "market"; > > type: "best_bid_ask"; > > payload: { > > conditionId: ConditionId; > > assetId: ClobAssetId; > > bestBid?: DecimalString | null; > > bestAsk?: DecimalString | null; > > spread?: DecimalString | null; > > timestamp?: string | null; > > }; > > }; > > ``` > > > > ```json MarketBestBidAskEvent Example theme={null} > > { > > "topic": "market", > > "type": "best_bid_ask", > > "payload": { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "bestBid": "0.08", > > "bestAsk": "0.09", > > "spread": "0.01", > > "timestamp": "1782753357257" > > } > > } > > ``` > > > > #### New Market > > > > ```ts NewMarketEvent Type theme={null} > > type NewMarketEvent = { > > topic: "market"; > > type: "new_market"; > > payload: { > > id: string; > > question?: string | null; > > market: string; > > slug?: string | null; > > description?: string | null; > > assetIds?: ClobAssetId[] | null; > > outcomes?: string[] | null; > > eventMessage?: { > > id: string; > > ticker?: string | null; > > slug?: string | null; > > title?: string | null; > > description?: string | null; > > } | null; > > timestamp?: string | null; > > tags?: string[] | null; > > conditionId?: ConditionId | null; > > active?: boolean | null; > > clobTokenIds?: string[] | null; > > sportsMarketType?: string | null; > > line?: DecimalString | null; > > gameStartTime?: IsoDateTimeString | null; > > orderPriceMinTickSize?: DecimalString | null; > > groupItemTitle?: string | null; > > takerBaseFee?: DecimalString | null; > > feesEnabled?: boolean | null; > > feeSchedule?: unknown; > > }; > > }; > > ``` > > > > ```json NewMarketEvent Example theme={null} > > { > > "topic": "market", > > "type": "new_market", > > "payload": { > > "id": "123456", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "question": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "assetIds": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "outcomes": ["Yes", "No"], > > "active": true, > > "timestamp": "1782753357257" > > } > > } > > ``` > > > > #### Market Resolved > > > > ```ts MarketResolvedEvent Type theme={null} > > type MarketResolvedEvent = { > > topic: "market"; > > type: "market_resolved"; > > payload: { > > id: string; > > conditionId: ConditionId; > > assetIds?: ClobAssetId[] | null; > > winningAssetId?: ClobAssetId | null; > > winningOutcome?: string | null; > > eventMessage?: { > > id: string; > > ticker?: string | null; > > slug?: string | null; > > title?: string | null; > > description?: string | null; > > } | null; > > timestamp?: string | null; > > tags?: string[] | null; > > }; > > }; > > ``` > > > > ```json MarketResolvedEvent Example theme={null} > > { > > "topic": "market", > > "type": "market_resolved", > > "payload": { > > "id": "123456", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetIds": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "winningAssetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "winningOutcome": "Yes", > > "timestamp": "1782753357257" > > } > > } > > ``` > [tab] Python > > The unified SDK uses `asset_id` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Given an `AsyncPublicClient` or `AsyncSecureClient`, subscribe to the market > stream with a `MarketSpec` containing one or more outcome IDs: > > ```python theme={null} > from polymarket.streams import MarketSpec > > asset_id = "" > > async with await client.subscribe( > MarketSpec(asset_ids=[asset_id]), > ) as stream: > async for event in stream: > if event.type == "book": > ... # event: MarketBookEvent > elif event.type == "price_change": > ... # event: MarketPriceChangeEvent > elif event.type == "last_trade_price": > ... # event: MarketLastTradePriceEvent > elif event.type == "tick_size_change": > ... # event: MarketTickSizeChangeEvent > ``` > > > [accordion] Standard Market Events > > > > #### Order Book > > > > ```python MarketBookEvent Type theme={null} > > class OrderBookLevel: > > price: Decimal > > size: Decimal > > > > class MarketBookPayload: > > condition_id: ConditionId > > asset_id: ClobAssetId > > bids: tuple[OrderBookLevel, ...] > > asks: tuple[OrderBookLevel, ...] > > hash: str | None > > timestamp: datetime | None > > min_order_size: Decimal | None > > tick_size: Decimal | None > > neg_risk: bool | None > > last_trade_price: Decimal | None > > > > class MarketBookEvent: > > topic: Literal["market"] > > type: Literal["book"] > > payload: MarketBookPayload > > ``` > > > > ```json MarketBookEvent Example theme={null} > > { > > "topic": "market", > > "type": "book", > > "payload": { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "bids": [{ "price": "0.08", "size": "33343.4" }], > > "asks": [{ "price": "0.09", "size": "163939.58" }], > > "hash": "0xabc123…", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### Price Change > > > > ```python MarketPriceChangeEvent Type theme={null} > > class PriceChange: > > asset_id: ClobAssetId > > price: Decimal > > size: Decimal > > side: Literal["BUY", "SELL"] > > hash: str | None > > best_bid: Decimal | None > > best_ask: Decimal | None > > > > class MarketPriceChangePayload: > > condition_id: ConditionId > > price_changes: tuple[PriceChange, ...] > > timestamp: datetime | None > > > > class MarketPriceChangeEvent: > > topic: Literal["market"] > > type: Literal["price_change"] > > payload: MarketPriceChangePayload > > ``` > > > > ```json MarketPriceChangeEvent Example theme={null} > > { > > "topic": "market", > > "type": "price_change", > > "payload": { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "price_changes": [ > > { > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "33343.4", > > "side": "BUY", > > "hash": "56621a121a47ed9333273e21c83b660cff37ae50", > > "best_bid": "0.08", > > "best_ask": "0.09" > > } > > ], > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### Last Trade Price > > > > ```python MarketLastTradePriceEvent Type theme={null} > > class MarketLastTradePricePayload: > > condition_id: ConditionId > > asset_id: ClobAssetId > > price: Decimal > > size: Decimal | None > > side: Literal["BUY", "SELL"] > > fee_rate_bps: Decimal | None > > transaction_hash: str | None > > timestamp: datetime | None > > > > class MarketLastTradePriceEvent: > > topic: Literal["market"] > > type: Literal["last_trade_price"] > > payload: MarketLastTradePricePayload > > ``` > > > > ```json MarketLastTradePriceEvent Example theme={null} > > { > > "topic": "market", > > "type": "last_trade_price", > > "payload": { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "219.217767", > > "side": "SELL", > > "fee_rate_bps": "0", > > "transaction_hash": "0xeeefff…", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### Tick Size Change > > > > ```python MarketTickSizeChangeEvent Type theme={null} > > class MarketTickSizeChangePayload: > > condition_id: ConditionId > > asset_id: ClobAssetId > > old_tick_size: Decimal | None > > new_tick_size: Decimal > > timestamp: datetime | None > > > > class MarketTickSizeChangeEvent: > > topic: Literal["market"] > > type: Literal["tick_size_change"] > > payload: MarketTickSizeChangePayload > > ``` > > > > ```json MarketTickSizeChangeEvent Example theme={null} > > { > > "topic": "market", > > "type": "tick_size_change", > > "payload": { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "old_tick_size": "0.01", > > "new_tick_size": "0.001", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > Enable `custom_feature_enabled` to include top-of-book and market lifecycle > updates: > > ```python theme={null} > async with await client.subscribe( > MarketSpec(asset_ids=[asset_id], custom_feature_enabled=True), > ) as stream: > async for event in stream: > if event.type == "book": > ... # event: MarketBookEvent > elif event.type == "price_change": > ... # event: MarketPriceChangeEvent > elif event.type == "last_trade_price": > ... # event: MarketLastTradePriceEvent > elif event.type == "tick_size_change": > ... # event: MarketTickSizeChangeEvent > elif event.type == "best_bid_ask": > ... # event: MarketBestBidAskEvent > elif event.type == "new_market": > ... # event: NewMarketEvent > elif event.type == "market_resolved": > ... # event: MarketResolvedEvent > ``` > > > [accordion] Additional Market Events > > > > #### Best Bid and Ask > > > > ```python MarketBestBidAskEvent Type theme={null} > > class MarketBestBidAskPayload: > > condition_id: ConditionId > > asset_id: ClobAssetId > > best_bid: Decimal | None > > best_ask: Decimal | None > > spread: Decimal | None > > timestamp: datetime | None > > > > class MarketBestBidAskEvent: > > topic: Literal["market"] > > type: Literal["best_bid_ask"] > > payload: MarketBestBidAskPayload > > ``` > > > > ```json MarketBestBidAskEvent Example theme={null} > > { > > "topic": "market", > > "type": "best_bid_ask", > > "payload": { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "best_bid": "0.08", > > "best_ask": "0.09", > > "spread": "0.01", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### New Market > > > > ```python NewMarketEvent Type theme={null} > > class MarketEventMessage: > > id: str > > ticker: str | None > > slug: str | None > > title: str | None > > description: str | None > > > > class NewMarketPayload: > > id: str > > market: str > > question: str | None > > slug: str | None > > description: str | None > > asset_ids: tuple[ClobAssetId, ...] | None > > outcomes: tuple[str, ...] | None > > event_message: MarketEventMessage | None > > timestamp: datetime | None > > tags: tuple[str, ...] | None > > condition_id: ConditionId | None > > active: bool | None > > clob_token_ids: tuple[str, ...] | None > > sports_market_type: str | None > > line: Decimal | None > > game_start_time: datetime | None > > order_price_min_tick_size: Decimal | None > > group_item_title: str | None > > taker_base_fee: Decimal | None > > fees_enabled: bool | None > > fee_schedule: object | None > > > > class NewMarketEvent: > > topic: Literal["market"] > > type: Literal["new_market"] > > payload: NewMarketPayload > > ``` > > > > ```json NewMarketEvent Example theme={null} > > { > > "topic": "market", > > "type": "new_market", > > "payload": { > > "id": "123456", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "question": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "asset_ids": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "outcomes": ["Yes", "No"], > > "active": true, > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### Market Resolved > > > > ```python MarketResolvedEvent Type theme={null} > > class MarketResolvedPayload: > > id: str > > condition_id: ConditionId > > asset_ids: tuple[ClobAssetId, ...] | None > > winning_asset_id: ClobAssetId | None > > winning_outcome: str | None > > event_message: MarketEventMessage | None > > timestamp: datetime | None > > tags: tuple[str, ...] | None > > > > class MarketResolvedEvent: > > topic: Literal["market"] > > type: Literal["market_resolved"] > > payload: MarketResolvedPayload > > ``` > > > > ```json MarketResolvedEvent Example theme={null} > > { > > "topic": "market", > > "type": "market_resolved", > > "payload": { > > "id": "123456", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_ids": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "winning_asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "winning_outcome": "Yes", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > [tab] API > > Connect to the market WebSocket: > > ```text theme={null} > wss://ws-subscriptions-clob.polymarket.com/ws/market > ``` > > > [!NOTE] > > > > The market WebSocket uses an application-level heartbeat. Send the text frame > > `PING` every 10 seconds; the server replies with `PONG`. > > Once connected, send a `market` subscription frame with one or more outcome > IDs: > > ```json theme={null} > { > "assets_ids": [""], > "type": "market" > } > ``` > > > [accordion] Standard Market Events > > > > #### Order Book > > > > ```json theme={null} > > { > > "event_type": "book", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "timestamp": "1782753357257", > > "hash": "0xabc123…", > > "bids": [ > > { "price": "0.08", "size": "33343.4" }, > > { "price": "0.09", "size": "163939.58" } > > ], > > "asks": [ > > { "price": "0.99", "size": "218442.27" }, > > { "price": "0.98", "size": "13229.55" } > > ] > > } > > ``` > > > > #### Price Change > > > > ```json theme={null} > > { > > "event_type": "price_change", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "price_changes": [ > > { > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "33343.4", > > "side": "BUY", > > "hash": "56621a121a47ed9333273e21c83b660cff37ae50", > > "best_bid": "0.08", > > "best_ask": "0.09" > > } > > ], > > "timestamp": "1782753357257" > > } > > ``` > > > > #### Last Trade Price > > > > ```json theme={null} > > { > > "event_type": "last_trade_price", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "price": "0.08", > > "size": "219.217767", > > "fee_rate_bps": "0", > > "side": "SELL", > > "timestamp": "1782753357257", > > "transaction_hash": "0xeeefff…" > > } > > ``` > > > > #### Tick Size Change > > > > ```json theme={null} > > { > > "event_type": "tick_size_change", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "old_tick_size": "0.01", > > "new_tick_size": "0.001", > > "timestamp": "1782753357257" > > } > > ``` > > Enable `custom_feature_enabled` to include top-of-book and market lifecycle > updates: > > ```json theme={null} > { > "assets_ids": [""], > "type": "market", > "custom_feature_enabled": true > } > ``` > > > [accordion] Additional Market Events > > > > #### Best Bid and Ask > > > > ```json theme={null} > > { > > "event_type": "best_bid_ask", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "best_bid": "0.08", > > "best_ask": "0.09", > > "spread": "0.01", > > "timestamp": "1782753357257" > > } > > ``` > > > > #### New Market > > > > ```json theme={null} > > { > > "event_type": "new_market", > > "id": "123456", > > "question": "Will the US confirm that aliens exist before 2027?", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "assets_ids": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "outcomes": ["Yes", "No"], > > "timestamp": "1782753357257" > > } > > ``` > > > > #### Market Resolved > > > > ```json theme={null} > > { > > "event_type": "market_resolved", > > "id": "123456", > > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assets_ids": [ > > "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "7305630249804085635496399869905769372294302716159034447326228509068694952392" > > ], > > "winning_asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "winning_outcome": "Yes", > > "timestamp": "1782753357257" > > } > > ``` > > You can add or remove outcome IDs without opening a new connection: > > ```json Subscribe theme={null} > { > "assets_ids": [""], > "operation": "subscribe" > } > ``` > > ```json Unsubscribe theme={null} > { > "assets_ids": [""], > "operation": "unsubscribe" > } > ``` > > These frames update only the outcome set for the current market-stream > connection. > > `"initial_dump": false` only skips snapshots on the opening `market` frame. A > subsequent `subscribe` frame ignores it and always sends a `book` snapshot for > each outcome ID it adds. ## Sports Stream Use the sports stream to keep live game information current alongside sports markets. Updates arrive when a game goes live, its score or period changes, or it ends. NFL and CFB updates can also reflect possession changes. > [!WARNING] > > Sports data is provided for informational purposes only. It may be delayed, > contain errors, or omit recent events. Polymarket does not provide trading or > investment advice, and this data should not be used as the basis for a trading > decision. > [tab] TypeScript > > Given a `PublicClient` or `SecureClient`, subscribe to the `sports` topic to receive > every game update: > > ```ts theme={null} > const stream = await client.subscribe([{ topic: "sports" }]); > > for await (const event of stream) { > // event: SportsEvent > } > ``` > > > [accordion] Sports Event > > > > ```ts SportsEvent Type theme={null} > > type SportsEvent = { > > topic: "sports"; > > type: "sport_result"; > > payload: { > > gameId: number; > > sportradarGameId?: string | null; > > slug?: string | null; > > leagueAbbreviation: string; > > homeTeam?: string | null; > > awayTeam?: string | null; > > status: string; > > live: boolean; > > ended: boolean; > > score: string; > > period?: string | null; > > elapsed?: string | null; > > finishedAt?: IsoDateTimeString | null; > > turn?: string | null; > > }; > > }; > > ``` > > > > ```json SportsEvent Example theme={null} > > { > > "topic": "sports", > > "type": "sport_result", > > "payload": { > > "gameId": 5127839, > > "leagueAbbreviation": "NBA", > > "homeTeam": "Los Angeles Lakers", > > "awayTeam": "Boston Celtics", > > "status": "InProgress", > > "live": true, > > "ended": false, > > "score": "98-94", > > "period": "Q4", > > "elapsed": "05:12" > > } > > } > > ``` > > > > `score` is a combined `"-"` string, not separate home and away > > fields. > [tab] Python > > Given an `AsyncPublicClient` or `AsyncSecureClient`, subscribe with a > `SportsSpec` to receive every game update: > > ```python theme={null} > from polymarket.streams import SportsSpec > > async with await client.subscribe(SportsSpec()) as stream: > async for event in stream: > ... # event: SportsEvent > ``` > > > [accordion] Sports Event > > > > ```python SportsEvent Type theme={null} > > class SportsGameResult: > > game_id: int > > sportradar_game_id: str | None > > slug: str | None > > league_abbreviation: str > > home_team: str | None > > away_team: str | None > > status: str > > live: bool > > ended: bool > > score: str > > period: str | None > > elapsed: str | None > > finished_at: datetime | None > > turn: str | None > > > > class SportsResultEvent: > > topic: Literal["sports"] > > type: Literal["sport_result"] > > payload: SportsGameResult > > > > SportsEvent = SportsResultEvent > > ``` > > > > ```json SportsEvent Example theme={null} > > { > > "topic": "sports", > > "type": "sport_result", > > "payload": { > > "game_id": 5127839, > > "league_abbreviation": "NBA", > > "home_team": "Los Angeles Lakers", > > "away_team": "Boston Celtics", > > "status": "InProgress", > > "live": true, > > "ended": false, > > "score": "98-94", > > "period": "Q4", > > "elapsed": "05:12" > > } > > } > > ``` > > > > `score` is a combined `"-"` string, not separate home and away > > fields. > [tab] API > > Connect to the sports WebSocket: > > ```text theme={null} > wss://sports-api.polymarket.com/ws > ``` > > > [!NOTE] > > > > The sports WebSocket uses an application-level heartbeat. The server sends the > > text frame `ping` every 5 seconds; reply with `pong` within 10 seconds or the > > server closes the connection. > > Once connected, the server starts streaming every game update. No > subscription frame is required. > > > [accordion] Sports Event > > > > ```json theme={null} > > { > > "gameId": 5127839, > > "leagueAbbreviation": "NBA", > > "homeTeam": "Los Angeles Lakers", > > "awayTeam": "Boston Celtics", > > "status": "InProgress", > > "live": true, > > "ended": false, > > "score": "98-94", > > "period": "Q4", > > "elapsed": "05:12" > > } > > ``` > > > > Sports messages have no envelope or event-type field. Each message is the > > game update object itself, and `score` is a combined `"-"` > > string. ### Period Values The meaning and format of a period depend on the sport: | Values | Meaning | | - | - | | `1H`, `2H` | First or second half | | `1Q`, `2Q`, `3Q`, `4Q` | Quarter | | `HT` | Halftime | | `FT` | Full time in regulation | | `FT OT` | Full time after overtime | | `FT NR` | Full time with no result | | `End 1`, `End 2`, … | End of an MLB inning | | `1/3`, `2/3`, `3/3` | Map number in a best-of-three series | | `1/5`, `2/5`, … | Map number in a best-of-five series | ### Game Status Values Status values vary by sport and are case-sensitive: | Sport | Values | | - | - | | NFL | `Scheduled`, `InProgress`, `Final`, `F/OT`, `Suspended`, `Postponed`, `Delayed`, `Canceled`, `Forfeit`, `NotNecessary` | | NHL | `Scheduled`, `InProgress`, `Final`, `F/OT`, `F/SO`, `Suspended`, `Postponed`, `Delayed`, `Canceled`, `Forfeit`, `NotNecessary` | | MLB | `Scheduled`, `InProgress`, `Final`, `Suspended`, `Delayed`, `Postponed`, `Canceled`, `Forfeit`, `NotNecessary` | | NBA and CBB | `Scheduled`, `InProgress`, `Final`, `F/OT`, `Suspended`, `Postponed`, `Delayed`, `Canceled`, `Forfeit`, `NotNecessary` | | CFB | `Scheduled`, `InProgress`, `Final`, `F/OT`, `Suspended`, `Postponed`, `Delayed`, `Canceled`, `Forfeit` | | Soccer | `Scheduled`, `InProgress`, `Break`, `Suspended`, `PenaltyShootout`, `Final`, `Awarded`, `Postponed`, `Canceled` | | Esports | `not_started`, `running`, `finished`, `postponed`, `canceled` | | Tennis | `scheduled`, `inprogress`, `suspended`, `finished`, `postponed`, `cancelled` | ## Reference Prices Stream crypto, equity, and time-weighted average reference prices through Polymarket. Authenticate, select the symbols you need, and process historical prices and live updates. > [!NOTE] > > Reference price subscriptions require authentication. > Existing RTDS integrations should follow the [migration > guide](/migrate/rtds-to-polybolt). > [!WARNING] > > Every reference price subscription must > name its provider, and subscriptions served by Chainlink require your > Chainlink API key. See the [PolyBolt > overview](/api-reference/live-data/overview#send-your-chainlink-api-key) for > the key. Use lowercase symbols. See the [PolyBolt overview](/api-reference/live-data/overview#supported-symbols) for crypto and TWAP lists, and the equity catalog below for equity symbols. ### Historical Snapshot Each new subscription provides a snapshot of the preceding two minutes of prices and live updates. Seed local state from the snapshot, then apply the latest price. Applications that only need live prices can ignore the snapshot. ### Crypto Prices Stream crypto reference prices in USD to keep prices current alongside related markets. > [tab] TypeScript > > Call `client.subscribe` with an authenticated `SecureClient` from `@polymarket/client` 0.11.0 or later, and name the provider with `provider`. See [Wallet Integrations](/getting-started/typescript#wallet-integrations) to create the client. > > ```ts theme={null} > import { PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { > topic: "prices.crypto", > symbols: ["btcusd", "ethusd"], > provider: PriceProvider.Pyth, > }, > ]); > > try { > for await (const event of stream) { > // event: CryptoPriceEvent > if (event.type === "subscribe") { > const history = event.payload.data; > // Seed local state from the snapshot. > } else { > const price = event.payload.value; > const observedAt = event.payload.timestamp; > // Apply the latest price. > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: CryptoPriceEvent > > > > **events: CryptoPriceEvent\[]** > > > > ```ts CryptoPriceEvent Union theme={null} > > type CryptoPriceEvent = > > | { > > topic: "prices.crypto"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > source: PriceSource; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > }; > > } > > | { > > topic: "prices.crypto"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > source: PriceSource; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > receivedAt: EpochMilliseconds | undefined; > > isCarriedForward: boolean | undefined; > > }; > > }; > > ``` > > > > ```json CryptoPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.crypto", > > "type": "subscribe", > > "timestamp": 1788886176000, > > "seq": 1, > > "payload": { > > "symbol": "btcusd", > > "source": "chainlink", > > "data": [ > > { > > "timestamp": 1788886057000, > > "value": "78803.76173179" > > }, > > { > > "timestamp": 1788886058000, > > "value": "78801.86287741" > > }, > > { > > "timestamp": 1788886059000, > > "value": "78798.28703224" > > } > > ] > > } > > }, > > { > > "topic": "prices.crypto", > > "type": "update", > > "timestamp": 1788886177000, > > "seq": 5, > > "payload": { > > "symbol": "btcusd", > > "source": "chainlink", > > "timestamp": 1788886177000, > > "value": "78794.15450441" > > } > > } > > ] > > ``` > > For live prices only, skip events whose `type` is `"subscribe"`. > [tab] Python > > Call `client.subscribe` with an authenticated `AsyncSecureClient` from `polymarket-client` 0.11.0 or later. Complete [Secure Client setup](/getting-started/python#secure-client) first, and run this example inside an async function. > > ```python theme={null} > from polymarket.streams import CryptoPriceSpec > > async with await client.subscribe( > CryptoPriceSpec(symbols=["btcusd", "ethusd"], provider="pyth") > ) as stream: > async for event in stream: > # event: CryptoPriceEvent > if event.type == "subscribe": > history = event.payload.data > # Seed local state from the snapshot. > else: > price = event.payload.value > observed_at = event.payload.timestamp > # Apply the latest price. > ``` > > > [accordion] Output: CryptoPriceEvent > > > > **event: CryptoPriceEvent** > > > > ```python CryptoPriceEvent Union theme={null} > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimePriceSnapshot: > > symbol: str > > source: PriceSource > > data: tuple[RealtimePricePoint, ...] > > > > class RealtimePriceUpdate: > > symbol: str > > source: PriceSource > > timestamp: datetime > > value: Decimal > > received_at: datetime | None > > is_carried_forward: bool | None > > > > class CryptoPriceSnapshotEvent: > > topic: Literal["prices.crypto"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimePriceSnapshot > > > > class CryptoPriceUpdateEvent: > > topic: Literal["prices.crypto"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimePriceUpdate > > > > CryptoPriceEvent = CryptoPriceSnapshotEvent | CryptoPriceUpdateEvent > > ``` > > > > ```json CryptoPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:37Z", > > "seq": 5, > > "topic": "prices.crypto", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:37Z", > > "value": "78794.15450441", > > "symbol": "btcusd", > > "source": "chainlink" > > } > > } > > ``` > > Values are `Decimal`, and timestamps are UTC `datetime` objects. > > For live prices only, skip events whose `type` is `"subscribe"`. > [tab] API > > Connect to PolyBolt and authenticate before subscribing to crypto prices. > > **1. Connect** > > Open a WebSocket connection to: > > ```text theme={null} > wss://ws-live-v2.polymarket.com/ws > ``` > > **2. Authenticate** > > Send your [CLOB API credentials](/getting-started/api#authentication) on the open connection: > > ```json theme={null} > { > "op": "auth", > "rid": "a1", > "auth": { > "apiKey": "", > "secret": "", > "passphrase": "" > } > } > ``` > > **3. Wait for Authentication** > > Wait for the server to confirm authentication before sending a subscription: > > ```json theme={null} > { > "op": "authed", > "rid": "a1" > } > ``` > > **4. Subscribe to Crypto Prices** > > Send this frame on the authenticated connection to subscribe to BTC/USD: > > ```json theme={null} > { > "op": "subscribe", > "rid": "s1", > "subscriptions": [ > { > "channel": "price.crypto", > "filter": { > "symbol": "btcusd", > "provider": "pyth" > } > } > ] > } > ``` ### Equity Prices Stream reference prices for stocks, ETFs, forex pairs, precious metals, and commodities. > [tab] TypeScript > > Call `client.subscribe` to subscribe to the `prices.equity` topic, your chosen symbols and a `provider` with an authenticated `SecureClient`. Import `PriceProvider` from `@polymarket/client`. > > ```ts theme={null} > const stream = await client.subscribe([ > { topic: "prices.equity", symbol: "aapl", provider: PriceProvider.Pyth }, > ]); > > try { > for await (const event of stream) { > // event: EquityPriceEvent > if (event.type === "subscribe") { > const history = event.payload.data; > // Seed local state from the snapshot. > } else { > const price = event.payload.value; > const observedAt = event.payload.timestamp; > // Apply the latest price. > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: EquityPriceEvent > > > > **events: EquityPriceEvent\[]** > > > > ```ts EquityPriceEvent Union theme={null} > > import type { EquityMarketStatus } from "@polymarket/client"; > > > > type EquityPriceEvent = > > | { > > topic: "prices.equity"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > marketStatus?: EquityMarketStatus; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > }; > > } > > | { > > topic: "prices.equity"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > marketStatus?: EquityMarketStatus; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > receivedAt: EpochMilliseconds | undefined; > > isCarriedForward: boolean | undefined; > > }; > > }; > > ``` > > > > ```json EquityPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.equity", > > "type": "subscribe", > > "timestamp": 1788886176400, > > "seq": 1, > > "payload": { > > "symbol": "aapl", > > "marketStatus": "open", > > "data": [ > > { > > "timestamp": 1788886056800, > > "value": "316.11" > > }, > > { > > "timestamp": 1788886057000, > > "value": "316.11" > > }, > > { > > "timestamp": 1788886057200, > > "value": "316.11001" > > } > > ] > > } > > }, > > { > > "topic": "prices.equity", > > "type": "update", > > "timestamp": 1788886176600, > > "seq": 2, > > "payload": { > > "symbol": "aapl", > > "marketStatus": "open", > > "timestamp": 1788886176600, > > "value": "316.1", > > "receivedAt": 1788886176600 > > } > > } > > ] > > ``` > > For live prices only, skip events whose `type` is `"subscribe"`. > [tab] Python > > Call `client.subscribe` to subscribe to the `prices.equity` topic and your chosen symbols with an authenticated `AsyncSecureClient`. > > ```python theme={null} > from polymarket.streams import EquityPriceSpec > > async with await client.subscribe( > EquityPriceSpec(symbol="aapl", provider="pyth") > ) as stream: > async for event in stream: > # event: EquityPriceEvent > if event.type == "subscribe": > history = event.payload.data > # Seed local state from the snapshot. > else: > price = event.payload.value > observed_at = event.payload.timestamp > # Apply the latest price. > ``` > > > [accordion] Output: EquityPriceEvent > > > > **event: EquityPriceEvent** > > > > ```python EquityPriceEvent Union theme={null} > > from polymarket.streams import EquityMarketStatus > > > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimeEquityPriceSnapshot: > > symbol: str > > market_status: EquityMarketStatus | None = None > > data: tuple[RealtimePricePoint, ...] > > > > class RealtimeEquityPriceUpdate: > > symbol: str > > market_status: EquityMarketStatus | None = None > > timestamp: datetime > > value: Decimal > > received_at: datetime | None > > is_carried_forward: bool | None > > > > class EquityPriceSnapshotEvent: > > topic: Literal["prices.equity"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeEquityPriceSnapshot > > > > class EquityPriceUpdateEvent: > > topic: Literal["prices.equity"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeEquityPriceUpdate > > > > EquityPriceEvent = EquityPriceSnapshotEvent | EquityPriceUpdateEvent > > ``` > > > > ```json EquityPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:36.600000Z", > > "seq": 2, > > "topic": "prices.equity", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:36.600000Z", > > "value": "316.1", > > "symbol": "aapl", > > "market_status": "open", > > "received_at": "2026-09-08T16:49:36.600000Z" > > } > > } > > ``` > > Values are `Decimal`, and timestamps are UTC `datetime` objects. > > For live updates only, set `types=["update"]`. Omit `types` or pass an empty list to receive history and updates. Updates may include `received_at` and `is_carried_forward`. > [tab] API > > Reuse the authenticated connection from the [Crypto Prices](#crypto-prices) API example and send this frame to subscribe to AAPL: > > ```json theme={null} > { > "op": "subscribe", > "rid": "s2", > "subscriptions": [ > { > "channel": "price.equity", > "filter": { > "symbol": "aapl", > "provider": "pyth" > } > } > ] > } > ``` #### Supported Equity Symbols | Asset class | Supported symbols | | - | - | | Stocks | `aapl`, `tsla`, `msft`, `googl`, `amzn`, `meta`, `nvda`, `nflx`, `pltr`, `open`, `rklb`, `abnb`, `coin`, `hood`, `spcx`, `intc`, `mstr`, `crcl`, `mu` | | ETFs | `qqq`, `spy`, `ewy`, `vxx` | | Forex | `eurusd`, `gbpusd`, `usdcad`, `usdjpy`, `usdkrw`, `usdchf`, `usdmxn`, `usdzar`, `usdbrl`, `usdnok`, `usdsek`, `usdtry`, `dxy` | | Precious metals | `xauusd`, `xagusd` | | Commodities | `cll`, `hn`, `cc3m` | #### Read the Market Status Use market status to distinguish a closed market from a price that has stopped updating. Status describes the instrument priced by the provider, so two providers can report different states for the same symbol. For example, a Chainlink series can remain open over a weekend while a Pyth series follows the underlying exchange's session hours. | Status | Meaning | | - | - | | `open` | The provider reports that its instrument's market is trading. | | `closed` | The provider reports that its instrument's market is closed. | | `unknown` | The provider cannot determine the market's state. | | Not stated | No status was supplied. Do not assume the market is open. | > [tab] TypeScript > > In SDK 0.14.0 and later, read `payload.marketStatus` on both `subscribe` snapshots > and `update` events. Import `EquityMarketStatus` from `@polymarket/client` and use > an existing authenticated `SecureClient`: > > ```ts theme={null} > import { EquityMarketStatus, PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { topic: "prices.equity", symbol: "aapl", provider: PriceProvider.Pyth }, > ]); > > try { > for await (const event of stream) { > const status = event.payload.marketStatus; > if (status === EquityMarketStatus.Closed) { > console.log(event.payload.symbol, "Market closed"); > } else if (status === EquityMarketStatus.Unknown || status === undefined) { > console.log(event.payload.symbol, "Market state unavailable"); > } > } > } finally { > await stream.close(); > } > ``` > > `EquityMarketStatus.Open`, `.Closed`, and `.Unknown` correspond to the three stated > values. `undefined` means not stated. The same field is available on > `prices.equity.twap`. Subscribe with `{ topic: "prices.equity.twap", symbol: "eurusd", provider: PriceProvider.Chainlink }`. > In a snapshot, status is on `payload`, alongside `data`, rather than on each > historical price point. > [tab] Python > > In SDK 0.14.0 and later, read `payload.market_status` on both `subscribe` snapshots > and `update` events. Import `EquityMarketStatus` from `polymarket.streams` and use > an existing authenticated `AsyncSecureClient`: > > ```python theme={null} > from polymarket.streams import EquityMarketStatus, EquityPriceSpec > > async with await client.subscribe(EquityPriceSpec(symbol="aapl", provider="pyth")) as stream: > async for event in stream: > status = event.payload.market_status > if status == EquityMarketStatus.CLOSED: > print(event.payload.symbol, "Market closed") > elif status is None or status == EquityMarketStatus.UNKNOWN: > print(event.payload.symbol, "Market state unavailable") > ``` > > `EquityMarketStatus.OPEN`, `.CLOSED`, and `.UNKNOWN` correspond to the three stated > values. `None` means not stated. For equity TWAP, import `EquityTwapPriceSpec` from > `polymarket.streams` and pass `EquityTwapPriceSpec(symbol="eurusd", provider="chainlink")`. Its payload > has the same `market_status` field. In a snapshot, read status from `payload`, > rather than from the historical points in `payload.data`. > [tab] API > > Read `payload.market_status` on `price.equity` and `price.equity.twap`. A missing > field means not stated. On an authenticated PolyBolt WebSocket connection, > send this subscription frame: > > ```json Subscribe theme={null} > { > "op": "subscribe", > "rid": "s2", > "subscriptions": [ > { > "channel": "price.equity", > "filter": { "symbol": "aapl", "provider": "pyth" } > } > ] > } > ``` > > These examples show a received status-only spot update and a snapshot with > status at batch level: > > ```json Status-Only Update theme={null} > { > "v": 1, > "channel": "price.equity", > "seq": 41, > "ts": 1792526399800, > "payload": { > "symbol": "aapl", > "value": 262.71, > "full_accuracy_value": "262.71", > "timestamp": 1792526399800, > "received_at": 1792526401200, > "is_carried_forward": true, > "source": "pyth", > "market_status": "closed" > } > } > ``` > > ```json Snapshot theme={null} > { > "v": 1, > "channel": "price.equity", > "seq": 1, > "ts": 1792526399800, > "snapshot": true, > "payload": { > "symbol": "aapl", > "source": "pyth", > "market_status": "closed", > "data": [ > { > "timestamp": 1792526399800, > "value": 262.71, > "full_accuracy_value": "262.71" > } > ] > } > } > ``` > > See the [PolyBolt overview](/api-reference/live-data/overview#read-the-market-status) > for the wire contract and provider behavior. A spot status change can repeat the last price and its timestamp. The update is marked as carried forward (`isCarriedForward` in TypeScript, `is_carried_forward` in Python and the API). **Do not discard an update solely because its price timestamp repeats**: doing so can hide a market close or reopen. Equity TWAP status changes arrive with a new price. While status is closed or unknown, a snapshot can retain a closing price older than the usual two-minute history window. Re-read status and source after every reconnect. SDK cached spot snapshots retain the last stated status when a later update omits it. A status change on an older price does not roll newer history back. An unstated live update still has `undefined` or `None` for its own status. During market hours, prices can update up to five times per second for each feed. ### TWAP Prices A time-weighted average price (TWAP) represents an asset's price across a lookback window. Stream Chainlink-computed crypto TWAPs with a fixed 60-second window through Polymarket. TWAP prices are served by Chainlink only, so pin `chainlink`; they also require your Chainlink API key. > [!NOTE] > > Request a Chainlink API Key using [this form](https://institutional.polymarket.com/request-chainlink-api-key). > [tab] TypeScript > > Call `client.subscribe` to subscribe to the `prices.crypto.twap` topic, your chosen symbols and the Chainlink provider with an authenticated `SecureClient`. Import `PriceProvider` from `@polymarket/client`. > > ```ts theme={null} > const stream = await client.subscribe([ > { > topic: "prices.crypto.twap", > symbols: ["btcusd"], > provider: PriceProvider.Chainlink, > providerApiKey: "", > }, > ]); > > try { > for await (const event of stream) { > // event: CryptoTwapPriceEvent > if (event.type === "subscribe") { > const history = event.payload.data; > // Seed local state from the snapshot. > } else { > const price = event.payload.value; > const observedAt = event.payload.timestamp; > // Apply the latest price. > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: CryptoTwapPriceEvent > > > > **events: CryptoTwapPriceEvent\[]** > > > > ```ts CryptoTwapPriceEvent Union theme={null} > > type CryptoTwapPriceEvent = > > | { > > topic: "prices.crypto.twap"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > windowSeconds: 60; > > }; > > } > > | { > > topic: "prices.crypto.twap"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > windowSeconds: 60; > > }; > > }; > > ``` > > > > ```json CryptoTwapPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.crypto.twap", > > "type": "subscribe", > > "timestamp": 1788886175000, > > "seq": 2, > > "payload": { > > "symbol": "btcusd", > > "data": [ > > { > > "timestamp": 1788886057000, > > "value": "78788.525642908795142144" > > }, > > { > > "timestamp": 1788886058000, > > "value": "78788.786579938813673472" > > }, > > { > > "timestamp": 1788886059000, > > "value": "78789.052518750893375488" > > } > > ], > > "windowSeconds": 60 > > } > > }, > > { > > "topic": "prices.crypto.twap", > > "type": "update", > > "timestamp": 1788886177000, > > "seq": 3, > > "payload": { > > "symbol": "btcusd", > > "timestamp": 1788886177000, > > "value": "78803.715261094101516288", > > "windowSeconds": 60 > > } > > } > > ] > > ``` > > For live prices only, skip events whose `type` is `"subscribe"`. `payload.value` is already an exact decimal string. No E18 conversion is needed. > > Use a canonical symbol such as `btcusd`. The returned `windowSeconds: 60` describes the lookback period, not the update interval. Use `payload.timestamp` to check price freshness. > [tab] Python > > Call `client.subscribe` to subscribe to the `prices.crypto.twap` topic and your chosen symbols with an authenticated `AsyncSecureClient`. > > ```python theme={null} > from polymarket.streams import CryptoTwapPriceSpec > > async with await client.subscribe( > CryptoTwapPriceSpec(symbols=["btcusd"], provider="chainlink", provider_api_key="") > ) as stream: > async for event in stream: > # event: CryptoTwapPriceEvent > if event.type == "subscribe": > history = event.payload.data > # Seed local state from the snapshot. > else: > price = event.payload.value > observed_at = event.payload.timestamp > # Apply the latest price. > ``` > > > [accordion] Output: CryptoTwapPriceEvent > > > > **event: CryptoTwapPriceEvent** > > > > ```python CryptoTwapPriceEvent Union theme={null} > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimeTwapSnapshot: > > symbol: str > > data: tuple[RealtimePricePoint, ...] > > window_seconds: Literal[60] > > > > class RealtimeTwapUpdate: > > symbol: str > > timestamp: datetime > > value: Decimal > > window_seconds: Literal[60] > > > > class CryptoTwapPriceSnapshotEvent: > > topic: Literal["prices.crypto.twap"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeTwapSnapshot > > > > class CryptoTwapPriceUpdateEvent: > > topic: Literal["prices.crypto.twap"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeTwapUpdate > > > > CryptoTwapPriceEvent = CryptoTwapPriceSnapshotEvent | CryptoTwapPriceUpdateEvent > > ``` > > > > ```json CryptoTwapPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:37Z", > > "seq": 3, > > "topic": "prices.crypto.twap", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:37Z", > > "value": "78803.715261094101516288", > > "symbol": "btcusd", > > "window_seconds": 60 > > } > > } > > ``` > > Values are `Decimal`, and timestamps are UTC `datetime` objects. > > `payload.window_seconds` is always `60` and describes the lookback window. Use `payload.value` directly without E18 scaling, and use `payload.timestamp` to check freshness. > [tab] API > > Reuse the authenticated connection from the [Crypto Prices](#crypto-prices) API example and send this frame to subscribe to the 60-second BTC/USD TWAP: > > ```json theme={null} > { > "op": "subscribe", > "rid": "s3", > "subscriptions": [ > { > "channel": "price.crypto.twap", > "filter": { > "symbol": "btcusd", > "window_seconds": 60, > "provider": "chainlink" > } > } > ] > } > ``` ## Comments > [!WARNING] > > Live comment and reaction streaming is being retired without a replacement > streaming channel. Check below for the corresponding fetch method. > [tab] TypeScript > > Create a public client and call `client.listComments()` to list comments for an event. This method does not provide live comment or reaction events. > > ```ts theme={null} > import { > CommentParentEntityType, > createPublicClient, > } from "@polymarket/client"; > > const client = createPublicClient(); > const pages = client.listComments({ > parentEntityId: "18396", > parentEntityType: CommentParentEntityType.Event, > pageSize: 20, > order: "id", > ascending: true, > }); > const page = await pages.firstPage(); > > console.log(page.items); > ``` > > `page.items` contains `Comment` objects. Check `page.hasMore` for more results and continue with `pages.from(page.nextCursor)`. > > > [accordion] Output: Comment > > > > One comment from `page.items`, serialized as JSON with selected fields shown. > > > > ```json theme={null} > > { > > "id": "1020073", > > "body": "@truce @yayyo", > > "parentEntityType": "Event", > > "parentEntityID": "18396", > > "createdAt": "2025-02-12T00:48:05.40822Z", > > "reactionCount": 2 > > } > > ``` > [tab] Python > > Create a public client and call `client.list_comments()` to list comments for an event. This method does not provide live comment or reaction events. > > ```python theme={null} > from polymarket import AsyncPublicClient > > async with AsyncPublicClient() as client: > pages = client.list_comments( > parent_entity_id="18396", > parent_entity_type="Event", > page_size=20, > order="id", > ascending=True, > ) > page = await pages.first_page() > > print(page.items) > ``` > > `page.items` contains `Comment` objects. Check `page.has_more` for more results and continue with `pages.from_cursor(page.next_cursor)`. > > > [accordion] Output: Comment > > > > One comment from `page.items`, serialized as JSON with selected fields shown. > > > > ```json theme={null} > > { > > "id": "1020073", > > "body": "@truce @yayyo", > > "parent_entity_type": "Event", > > "parent_entity_id": "18396", > > "created_at": "2025-02-12T00:48:05.408220Z", > > "reaction_count": 2 > > } > > ``` > [tab] API > > Use `GET /comments` on the Gamma API to list comments for an event. This request does not provide live comment or reaction events. > > ```bash theme={null} > curl --get "https://gamma-api.polymarket.com/comments" \ > --data-urlencode "parent_entity_id=18396" \ > --data-urlencode "parent_entity_type=Event" \ > --data-urlencode "limit=20" \ > --data-urlencode "offset=0" \ > --data-urlencode "order=id" \ > --data-urlencode "ascending=true" > ``` > > The response is an array of comments. > > > [accordion] Output: Comment\[] > > > > First comment in the response, with selected fields shown. > > > > ```json theme={null} > > [ > > { > > "id": "1020073", > > "body": "@truce @yayyo", > > "parentEntityType": "Event", > > "parentEntityID": 18396, > > "createdAt": "2025-02-12T00:48:05.40822Z", > > "reactionCount": 2 > > } > > ] > > ``` ## Reference Price Providers Provider availability depends on the symbol and feed. Use this table when choosing a reference-price source. | Provider | Feeds | Quirks | | - | - | - | | Chainlink | Crypto spot, supported equity spot, and 60-second TWAP | Default wherever it serves the symbol. Requires your Chainlink API key. TWAP feeds are Chainlink-only. Equity products can trade around the clock, so their market status can differ from exchange-session feeds. | | Pyth | Supported crypto and equity spot symbols | Availability varies by symbol. A requested provider that cannot serve the symbol falls back to its default provider. | | Binance | Crypto spot only | Uses canonical symbols such as `btcusd` for USDT spot closes. Not available for equity or TWAP feeds. | | Massive | Equity spot | Can appear as the served source, but cannot be requested explicitly. Its exchange-session market status can differ from continuous-hours products. | A provider preference may be ignored when provider selection is disabled. Check the source returned with snapshots and live updates, including after reconnecting, rather than assuming the requested provider was selected. # Migrate from Legacy SDKs to Unified SDKs Source: https://docs.polymarket.com/migrate/clob-sdk-to-unified-sdk Move an existing Polymarket integration to the unified SDKs. Migrate from the previous CLOB, relayer, and builder-signing clients to the unified SDK. > [tab] TypeScript > > The examples below map previous client capabilities to > `@polymarket/client`. The SDK also covers the Gamma API and Data API. Migrating > direct Gamma and Data calls can simplify application code and give you > normalized, typed models that work seamlessly with the SDK's trading and > account workflows. > > ## Install the Unified SDK > > Remove the previous CLOB, relayer, and builder-signing packages used by your > integration. Then install the unified SDK and your wallet library. > > ```bash npm theme={null} > npm uninstall @polymarket/clob-client-v2 @polymarket/builder-relayer-client @polymarket/builder-signing-sdk > npm install @polymarket/client@latest viem > ``` > > ```bash pnpm theme={null} > pnpm remove @polymarket/clob-client-v2 @polymarket/builder-relayer-client @polymarket/builder-signing-sdk > pnpm add @polymarket/client@latest viem > ``` > > ```bash Yarn theme={null} > yarn remove @polymarket/clob-client-v2 @polymarket/builder-relayer-client @polymarket/builder-signing-sdk > yarn add @polymarket/client@latest viem > ``` > > ```bash Bun theme={null} > bun remove @polymarket/clob-client-v2 @polymarket/builder-relayer-client @polymarket/builder-signing-sdk > bun add @polymarket/client@latest viem > ``` > > > [!NOTE] > > > > The unified SDK includes signer adapters for Viem, Privy, and Ethers v5, so > > you can connect your wallet library without implementing CLOB-specific > > signing. See [Wallet > > Integrations](/getting-started/typescript#wallet-integrations) for setup > > examples. > > ## Client and Wallet Setup > > ### Create a Public Client > > `PublicClient` provides unauthenticated market discovery and data reads. > `createPublicClient` uses production by default and does not require a host or > chain ID. > > ```ts Before theme={null} > import { ClobClient } from "@polymarket/clob-client-v2"; > > const client = new ClobClient({ > host: "https://clob.polymarket.com", > chain: 137, > }); > ``` > > ```ts After theme={null} > import { createPublicClient } from "@polymarket/client"; > > const client = createPublicClient(); > ``` > > ### Create an Authenticated Client > > `SecureClient` adds authenticated trading, account, and wallet actions. > `createSecureClient` derives or creates CLOB credentials, resolves the account > wallet, and configures the correct signing flow. > > ```ts Before theme={null} > import { ClobClient, SignatureTypeV2 } from "@polymarket/clob-client-v2"; > > const tempClient = new ClobClient({ > host: "https://clob.polymarket.com", > chain: 137, > signer, > }); > const credentials = await tempClient.createOrDeriveApiKey(); > > const client = new ClobClient({ > host: "https://clob.polymarket.com", > chain: 137, > signer, > creds: credentials, > signatureType: SignatureTypeV2.POLY_1271, > funderAddress: process.env.POLYMARKET_WALLET_ADDRESS, > }); > ``` > > ```ts After theme={null} > import { type ApiKeyCreds, createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > }); > ``` > > Omit `wallet` to use the default Deposit Wallet flow. > > ### Resume With Existing Credentials > > Read credentials from an authenticated client, store them securely, and pass > them to a new client to resume with the same API key. The signer and wallet must > identify the account that owns the credentials. > > ```ts Before theme={null} > import { ClobClient, SignatureTypeV2 } from "@polymarket/clob-client-v2"; > > const credentials = client.creds; > if (!credentials) throw new Error("Client has no credentials"); > > // Store the credentials securely. > > const resumedClient = new ClobClient({ > host: "https://clob.polymarket.com", > chain: 137, > signer, > creds: credentials, > signatureType: SignatureTypeV2.POLY_1271, > funderAddress: process.env.POLYMARKET_WALLET_ADDRESS, > }); > ``` > > ```ts After theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const credentials = client.credentials; > > // Store the credentials securely. > > const resumedClient = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > // Restore the type if loading from storage erased it. > credentials: credentials as ApiKeyCreds, > }); > ``` > > ### Revoke the Current API Key > > Ending authentication revokes the current API key, invalidates the > `SecureClient`, and returns a `PublicClient`. > > ```ts Before theme={null} > await client.deleteApiKey(); > ``` > > ```ts After theme={null} > const publicClient = await client.endAuthentication(); > ``` > > ### Configure Builder API Keys > > `SecureClient` accepts Builder authorization for gasless wallet actions. > Migrate local or remote Builder signing to the matching helper. > > **Local Builder API key** > > Keep local Builder credentials on the server. The Node.js entrypoint generates > the required HMAC headers. > > ```ts Before theme={null} > import { RelayClient } from "@polymarket/builder-relayer-client"; > import { BuilderConfig } from "@polymarket/builder-signing-sdk"; > > const builderConfig = new BuilderConfig({ > localBuilderCreds: { > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }, > }); > > const relayer = new RelayClient( > "https://relayer-v2.polymarket.com", > 137, > walletClient, > builderConfig, > ); > ``` > > ```ts After theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > **Remote Builder Signing** > > Keep Builder credentials behind your signing endpoint. The client sends the > same `{ method, path, body }` request and applies the same Builder headers, so > the endpoint contract does not change. > > ```ts Before theme={null} > import { RelayClient } from "@polymarket/builder-relayer-client"; > import { BuilderConfig } from "@polymarket/builder-signing-sdk"; > > const builderConfig = new BuilderConfig({ > remoteBuilderConfig: { > url: "https://example.com/api/builder/sign", > token: process.env.BUILDER_SIGNING_TOKEN, > }, > }); > > const relayer = new RelayClient( > "https://relayer-v2.polymarket.com", > 137, > walletClient, > builderConfig, > ); > ``` > > ```ts After theme={null} > import { createSecureClient, remoteBuilderSigning } from "@polymarket/client"; > > const client = await createSecureClient({ > signer, > apiKey: remoteBuilderSigning({ > url: "https://example.com/api/builder/sign", > headers: { > Authorization: `Bearer ${process.env.BUILDER_SIGNING_TOKEN}`, > }, > }), > }); > ``` > > On the signing server, replace `BuilderConfig.generateBuilderHeaders` with > `buildHmacSignature`. Keep your existing caller authentication and > authorization around this handler. > > ```ts Before theme={null} > import { BuilderConfig } from "@polymarket/builder-signing-sdk"; > > const builderConfig = new BuilderConfig({ > localBuilderCreds: { > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }, > }); > > export async function POST(request: Request): Promise { > const { body, method, path } = await request.json(); > const headers = await builderConfig.generateBuilderHeaders( > method, > path, > body, > ); > > return Response.json(headers); > } > ``` > > ```ts After theme={null} > import { buildHmacSignature } from "@polymarket/client"; > > export async function POST(request: Request): Promise { > const { body, method, path } = await request.json(); > const timestamp = Math.floor(Date.now() / 1000); > > return Response.json({ > POLY_BUILDER_API_KEY: process.env.POLYMARKET_BUILDER_API_KEY!, > POLY_BUILDER_PASSPHRASE: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > POLY_BUILDER_SIGNATURE: await buildHmacSignature( > process.env.POLYMARKET_BUILDER_SECRET!, > timestamp, > method, > path, > body, > ), > POLY_BUILDER_TIMESTAMP: `${timestamp}`, > }); > } > ``` > > ### Configure Relayer API Keys > > `SecureClient` configures Relayer API keys directly. Pass the key and its > associated address to `relayerApiKey` when reconnecting an existing account. > > ```ts theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > apiKey: relayerApiKey({ > key: process.env.POLYMARKET_RELAYER_API_KEY!, > address: process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ### Deploy a Deposit Wallet > > Creating a `SecureClient` without a `wallet` derives the signer's Deposit Wallet > address and deploys it when needed. Use one of the Builder authorization > strategies above to authorize the deployment. > > ```ts Before theme={null} > const deployment = await relayer.deployDepositWallet(); > await deployment.wait(); > ``` > > ```ts After theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > > const depositWalletAddress = client.account.wallet; > ``` > > ## Market Discovery > > ### Fetch a Market > > Both `PublicClient` and `SecureClient` provide `fetchMarket` for reads by Gamma > market ID, slug, or Polymarket URL. > > ```ts Before theme={null} > const market = await client.getMarket("CONDITION_ID"); > ``` > > ```ts After theme={null} > const market = await client.fetchMarket({ slug: "MARKET_SLUG" }); > ``` > > If you only have a condition ID, filter `listMarkets` and fetch its first page. > > ```ts theme={null} > const page = await client > .listMarkets({ conditionIds: ["CONDITION_ID"] }) > .firstPage(); > > const market = page.items[0]; > ``` > > ### List Markets > > Both `PublicClient` and `SecureClient` provide `listMarkets`, which returns a > paginator and accepts filters directly. > > ```ts Before theme={null} > const page = await client.getMarkets(); > const markets = page.data; > ``` > > ```ts After theme={null} > const pages = client.listMarkets({ closed: false, pageSize: 20 }); > const page = await pages.firstPage(); > const markets = page.items; > ``` > > `getSimplifiedMarkets` does not need a separate replacement. Unified market > models are normalized for SDK use. Sampling-market reads should migrate to > `listCurrentRewards`, which lists the active reward configurations. > > ```ts Before theme={null} > const markets = await client.getSamplingMarkets(); > const page = await client.getSamplingSimplifiedMarkets(); > ``` > > ```ts After theme={null} > const pages = client.listCurrentRewards(); > const page = await pages.firstPage(); > ``` > > ## Market Data > > ### Read Trading Parameters > > Both `PublicClient` and `SecureClient` return tick size and negative-risk status > on the unified market model. Order methods also resolve them automatically, so > you no longer pass either value when placing an order. > > ```ts Before theme={null} > const tickSize = await client.getTickSize("TOKEN_ID"); > const negRisk = await client.getNegRisk("TOKEN_ID"); > ``` > > ```ts After theme={null} > const market = await client.fetchMarket({ slug: "MARKET_SLUG" }); > const tickSize = market.trading.minimumTickSize; > const negRisk = market.state.negRisk; > ``` > > ### Read CLOB Market Details > > Both `PublicClient` and `SecureClient` return the normalized market model for > public product data. Its trading fields replace the compact CLOB market response > and standalone fee reads. > > ```ts Before theme={null} > const info = await client.getClobMarketInfo("CONDITION_ID"); > const feeRateBps = await client.getFeeRateBps("TOKEN_ID"); > const feeExponent = await client.getFeeExponent("TOKEN_ID"); > ``` > > ```ts After theme={null} > const page = await client > .listMarkets({ conditionIds: ["CONDITION_ID"] }) > .firstPage(); > > const market = page.items[0]; > const feeSchedule = market?.trading.feeSchedule; > ``` > > ### Fetch Order Books > > Both `PublicClient` and `SecureClient` provide single and batch order book reads > with camelCase request fields. > > ```ts Before theme={null} > const book = await client.getOrderBook("TOKEN_ID"); > const books = await client.getOrderBooks([ > { token_id: "TOKEN_ID_1" }, > { token_id: "TOKEN_ID_2" }, > ]); > ``` > > The unified SDK uses `assetId` for an outcome's trading identifier: a token ID > for a CTF market or a position ID for a Polymarket Protocol V2 market. Use the > identifier exposed for that outcome. > > ```ts After theme={null} > const book = await client.fetchOrderBook({ assetId: "ASSET_ID" }); > const books = await client.fetchOrderBooks([ > { assetId: "ASSET_ID_1" }, > { assetId: "ASSET_ID_2" }, > ]); > ``` > > ### Fetch Prices > > Both `PublicClient` and `SecureClient` provide single and batch price reads with > `OrderSide` and camelCase request fields. > > ```ts Before theme={null} > import { Side } from "@polymarket/clob-client-v2"; > > const price = await client.getPrice("TOKEN_ID", Side.BUY); > const prices = await client.getPrices([ > { token_id: "TOKEN_ID_1", side: Side.BUY }, > { token_id: "TOKEN_ID_2", side: Side.SELL }, > ]); > ``` > > ```ts After theme={null} > import { OrderSide } from "@polymarket/client"; > > const price = await client.fetchPrice({ > assetId: "ASSET_ID", > side: OrderSide.BUY, > }); > const prices = await client.fetchPrices([ > { assetId: "ASSET_ID_1", side: OrderSide.BUY }, > { assetId: "ASSET_ID_2", side: OrderSide.SELL }, > ]); > ``` > > ### Fetch Midpoints > > Both `PublicClient` and `SecureClient` provide `fetchMidpoint` and > `fetchMidpoints` for single and batch reads. > > ```ts Before theme={null} > const midpoint = await client.getMidpoint("TOKEN_ID"); > const midpoints = await client.getMidpoints([ > { token_id: "TOKEN_ID_1" }, > { token_id: "TOKEN_ID_2" }, > ]); > ``` > > ```ts After theme={null} > const midpoint = await client.fetchMidpoint({ assetId: "ASSET_ID" }); > const midpoints = await client.fetchMidpoints([ > { assetId: "ASSET_ID_1" }, > { assetId: "ASSET_ID_2" }, > ]); > ``` > > ### Fetch Spreads > > Both `PublicClient` and `SecureClient` provide single and batch spread reads > with the same request pattern. > > ```ts Before theme={null} > const spread = await client.getSpread("TOKEN_ID"); > const spreads = await client.getSpreads([ > { token_id: "TOKEN_ID_1" }, > { token_id: "TOKEN_ID_2" }, > ]); > ``` > > ```ts After theme={null} > const spread = await client.fetchSpread({ assetId: "ASSET_ID" }); > const spreads = await client.fetchSpreads([ > { assetId: "ASSET_ID_1" }, > { assetId: "ASSET_ID_2" }, > ]); > ``` > > ### Fetch Last Trade Prices > > Both `PublicClient` and `SecureClient` provide singular and batch methods for > last-trade prices. > > ```ts Before theme={null} > const lastTrade = await client.getLastTradePrice("TOKEN_ID"); > const lastTrades = await client.getLastTradesPrices([ > { token_id: "TOKEN_ID_1" }, > { token_id: "TOKEN_ID_2" }, > ]); > ``` > > ```ts After theme={null} > const lastTrade = await client.fetchLastTradePrice({ assetId: "ASSET_ID" }); > const lastTrades = await client.fetchLastTradePrices([ > { assetId: "ASSET_ID_1" }, > { assetId: "ASSET_ID_2" }, > ]); > ``` > > ### Fetch Price History > > Both `PublicClient` and `SecureClient` provide a price history paginator. Pass > parameters in one request object; each page contains typed price history points. > > ```ts Before theme={null} > const history = await client.getPricesHistory({ > market: "TOKEN_ID", > interval: "1d", > fidelity: 60, > }); > ``` > > ```ts After theme={null} > import { PriceHistoryInterval } from "@polymarket/client"; > > const pages = client.listPriceHistory({ > assetId: "ASSET_ID", > interval: PriceHistoryInterval.OneDay, > bucketSeconds: 3600, > }); > const page = await pages.firstPage(); > const history = page.items; > ``` > > ### Estimate a Market Order Price > > Both `PublicClient` and `SecureClient` provide market-order price estimates. The > request distinguishes collateral spent for buys from shares sold for sells. > > ```ts Before theme={null} > const price = await client.calculateMarketPrice( > "TOKEN_ID", > Side.BUY, > 100, > OrderType.FAK, > ); > ``` > > ```ts After theme={null} > const price = await client.estimateMarketPrice({ > assetId: "ASSET_ID", > side: OrderSide.BUY, > amount: 100, > }); > ``` > > ### List Recent Market Trades > > Both `PublicClient` and `SecureClient` provide the public trade paginator, which > replaces the previous market-events response. > > ```ts Before theme={null} > const trades = await client.getMarketTradesEvents("CONDITION_ID"); > ``` > > ```ts After theme={null} > const pages = client.listTrades({ conditionId: ["CONDITION_ID"] }); > const page = await pages.firstPage(); > const trades = page.items; > ``` > > ## Orders > > ### Place a Limit Order > > `SecureClient` resolves tick size, negative-risk status, fees, and signing > details before it submits a limit order. > > ```ts Before theme={null} > const response = await client.createAndPostOrder( > { > tokenID: "TOKEN_ID", > price: 0.52, > size: 10, > side: Side.BUY, > }, > { tickSize: "0.01", negRisk: false }, > OrderType.GTC, > ); > ``` > > ```ts After theme={null} > const response = await client.placeLimitOrder({ > assetId: "ASSET_ID", > price: 0.52, > size: 10, > side: OrderSide.BUY, > }); > ``` > > Set `expiration` for a GTD order and `postOnly: true` for a post-only order. > > ### Place a Market Order > > `SecureClient` places market orders. Buys specify collateral to spend, while > sells specify shares to sell. > > ```ts Before theme={null} > const response = await client.createAndPostMarketOrder( > { > tokenID: "TOKEN_ID", > amount: 10, > userUSDCBalance: 10, > side: Side.BUY, > }, > { tickSize: "0.01", negRisk: false }, > OrderType.FAK, > ); > ``` > > ```ts After theme={null} > const response = await client.placeMarketOrder({ > assetId: "ASSET_ID", > amount: 10, > maxSpend: 10, > side: OrderSide.BUY, > orderType: OrderType.FAK, > }); > ``` > > `userUSDCBalance` becomes `maxSpend`. The previous field supplied the account > balance used to adjust the order for fees; the unified SDK instead accepts the > maximum total USD to spend. Set `maxSpend` equal to `amount` when the amount > should include fees, or omit it to pay applicable fees on top. > > ### Sign Without Posting > > `SecureClient` provides order-type-specific creation methods when signing and > submission need to happen separately. > > ```ts Before theme={null} > const signedOrder = await client.createOrder( > { > tokenID: "TOKEN_ID", > price: 0.52, > size: 10, > side: Side.BUY, > }, > { tickSize: "0.01", negRisk: false }, > ); > > const response = await client.postOrder(signedOrder, OrderType.GTC); > ``` > > ```ts After theme={null} > const signedOrder = await client.createLimitOrder({ > assetId: "ASSET_ID", > price: 0.52, > size: 10, > side: OrderSide.BUY, > }); > > const response = await client.postOrder(signedOrder); > ``` > > Use `createMarketOrder` instead when preparing an FAK or FOK market order. > > ### Post Several Orders > > `SecureClient` provides `postOrders`. Order type and post-only behavior are part > of each signed order, so the method accepts the signed orders directly. > > ```ts Before theme={null} > const response = await client.postOrders([ > { order: firstOrder, orderType: OrderType.GTC }, > { order: secondOrder, orderType: OrderType.GTC }, > ]); > ``` > > ```ts After theme={null} > const response = await client.postOrders([firstOrder, secondOrder]); > ``` > > ### Attribute an Order to a Builder > > `SecureClient` attaches the builder code to each order. > > ```ts Before theme={null} > const response = await client.createAndPostOrder( > { > tokenID: "TOKEN_ID", > price: 0.52, > size: 10, > side: Side.BUY, > builderCode: process.env.POLYMARKET_BUILDER_CODE, > }, > { tickSize: "0.01", negRisk: false }, > ); > ``` > > ```ts After theme={null} > const response = await client.placeLimitOrder({ > assetId: "ASSET_ID", > price: 0.52, > size: 10, > side: OrderSide.BUY, > builderCode: process.env.POLYMARKET_BUILDER_CODE, > }); > ``` > > ### Cancel Orders > > `SecureClient` provides the cancel methods. They now accept camelCase request > objects, while `cancelAll` remains parameterless. > > ```ts Before theme={null} > await client.cancelOrder("ORDER_ID"); > await client.cancelOrders(["ORDER_ID_1", "ORDER_ID_2"]); > await client.cancelAll(); > await client.cancelMarketOrders({ > market: "CONDITION_ID", > asset_id: "TOKEN_ID", > }); > ``` > > ```ts After theme={null} > await client.cancelOrder({ orderId: "ORDER_ID" }); > await client.cancelOrders({ orderIds: ["ORDER_ID_1", "ORDER_ID_2"] }); > await client.cancelAll(); > await client.cancelMarketOrders({ > market: "CONDITION_ID", > assetId: "ASSET_ID", > }); > ``` > > ### Fetch an Order > > `SecureClient` fetches an order by ID using a request object. > > ```ts Before theme={null} > const order = await client.getOrder("ORDER_ID"); > ``` > > ```ts After theme={null} > const order = await client.fetchOrder({ orderId: "ORDER_ID" }); > ``` > > ### List Open Orders > > `SecureClient` provides `listOpenOrders`, which returns a paginator. Filters and > response fields use camelCase. When filtering by `assetId` or the deprecated > `tokenId` alias, also supply a nonblank `market` (the market condition ID). > Otherwise, the call throws `UserInputError` before sending a request. > > ```ts Before theme={null} > const orders = await client.getOpenOrders({ > market: "CONDITION_ID", > asset_id: "TOKEN_ID", > }); > ``` > > ```ts After theme={null} > const pages = client.listOpenOrders({ > market: "CONDITION_ID", > assetId: "ASSET_ID", > }); > const orders = []; > for await (const page of pages) { > orders.push(...page.items); > } > ``` > > ### Check Order Scoring > > `SecureClient` provides `fetchOrderScoring` for one order and > `fetchOrdersScoring` for several. > > ```ts Before theme={null} > const scoring = await client.isOrderScoring({ orderId: "ORDER_ID" }); > const batch = await client.areOrdersScoring({ > orderIds: ["ORDER_ID_1", "ORDER_ID_2"], > }); > ``` > > ```ts After theme={null} > const scoring = await client.fetchOrderScoring({ orderId: "ORDER_ID" }); > const batch = await client.fetchOrdersScoring({ > orderIds: ["ORDER_ID_1", "ORDER_ID_2"], > }); > ``` > > ## Account Activity and Balances > > ### List Account Trades > > `SecureClient` replaces both previous account trade-history methods with one > paginator. > > ```ts Before theme={null} > const trades = await client.getTrades({ market: "CONDITION_ID" }); > const page = await client.getTradesPaginated({ market: "CONDITION_ID" }); > ``` > > ```ts After theme={null} > const pages = client.listAccountTrades({ market: "CONDITION_ID" }); > const firstPage = await pages.firstPage(); > > const trades = []; > for await (const page of pages) { > trades.push(...page.items); > } > ``` > > ### List Builder Trades > > Both `PublicClient` and `SecureClient` provide public builder trade history, > filtered by builder code. > > ```ts Before theme={null} > const trades = await client.getBuilderTrades(); > ``` > > ```ts After theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE, > }); > const page = await pages.firstPage(); > const trades = page.items; > ``` > > ### Read and Drop Notifications > > `SecureClient` provides notification methods with action-oriented names and > camelCase request fields. > > ```ts Before theme={null} > const notifications = await client.getNotifications(); > await client.dropNotifications({ ids: [1, 2] }); > ``` > > ```ts After theme={null} > const notifications = await client.fetchNotifications(); > await client.dropNotifications({ ids: ["1", "2"] }); > ``` > > ### Refresh Balances and Allowances > > `SecureClient` manages balances and allowances while placing orders. It detects > a missing allowance, completes the required approval, refreshes the balance and > allowance, and retries the order. > > ```ts Before theme={null} > await client.updateBalanceAllowance({ > asset_type: AssetType.COLLATERAL, > }); > > const balance = await client.getBalanceAllowance({ > asset_type: AssetType.COLLATERAL, > }); > ``` > > ```ts After theme={null} > const response = await client.placeLimitOrder({ > assetId: "ASSET_ID", > price: 0.52, > size: 10, > side: OrderSide.BUY, > }); > ``` > > ## Positions > > The unified methods build and submit the wallet transactions. You no longer > need to encode contract calls or pass transaction arrays to `execute`. > > ### Split a Position > > `SecureClient` splits collateral into a complete set of YES and NO outcome > tokens. > > ```ts Before theme={null} > const splitTx = { > to: CTF_COLLATERAL_ADAPTER_ADDRESS, > data: collateralAdapterInterface.encodeFunctionData("splitPosition", [ > PUSD_ADDRESS, > ethers.constants.HashZero, > conditionId, > [1, 2], > ethers.utils.parseUnits("1", 6), > ]), > value: "0", > }; > > const split = await relayer.execute([splitTx], "Split position"); > await split.wait(); > ``` > > ```ts After theme={null} > const split = await client.splitPosition({ > conditionId, > amount: 1_000_000n, > }); > > await split.wait(); > ``` > > ### Merge Positions > > `SecureClient` merges balanced YES and NO tokens back into collateral. > > ```ts Before theme={null} > const mergeTx = { > to: CTF_COLLATERAL_ADAPTER_ADDRESS, > data: collateralAdapterInterface.encodeFunctionData("mergePositions", [ > PUSD_ADDRESS, > ethers.constants.HashZero, > conditionId, > [1, 2], > ethers.utils.parseUnits("1", 6), > ]), > value: "0", > }; > > const merge = await relayer.execute([mergeTx], "Merge positions"); > await merge.wait(); > ``` > > ```ts After theme={null} > const merge = await client.mergePositions({ > conditionId, > amount: "max", > }); > > await merge.wait(); > ``` > > ### Redeem Resolved Positions > > `SecureClient` redeems winning outcome tokens for collateral after resolution. > > ```ts Before theme={null} > const redeemTx = { > to: CTF_COLLATERAL_ADAPTER_ADDRESS, > data: collateralAdapterInterface.encodeFunctionData("redeemPositions", [ > PUSD_ADDRESS, > ethers.constants.HashZero, > conditionId, > [1, 2], > ]), > value: "0", > }; > > const redeem = await relayer.execute([redeemTx], "Redeem positions"); > await redeem.wait(); > ``` > > ```ts After theme={null} > const redeem = await client.redeemPositions({ conditionId }); > await redeem.wait(); > ``` > > ## Service Status > > Neither `PublicClient` nor `SecureClient` requires these calls. The unified > clients manage request timing internally. > > ```ts Before theme={null} > await client.getOk(); > const timestamp = await client.getServerTime(); > ``` > > ```ts After theme={null} > // No client call is required for request timestamp synchronization. > ``` > [tab] Python > > The examples below map previous client capabilities to `polymarket-client`. > The SDK also covers the Gamma API and Data API. Migrating direct Gamma and > Data calls can simplify application code and give you normalized, typed > models that work seamlessly with the SDK's trading and account workflows. > > Public clients provide unauthenticated market discovery and data reads. > Secure clients add authenticated trading, account, and wallet actions. > Python provides async and sync versions of each, so choose the interface > that matches your application's execution model. > > | Interface | Clients | Best for | > | - | - | - | > | Async | `AsyncPublicClient`, `AsyncSecureClient` | Services, bots, and applications using an event loop | > | Sync | `PublicClient`, `SecureClient` | Scripts, notebooks, and synchronous applications | > > The examples below use the async clients. > > > [!NOTE] > > > > Some features are available only through the async clients due to their > > streaming nature. > > ## Install the Unified SDK > > Remove the previous CLOB, relayer, and builder-signing packages. Then install the > unified SDK. > > ```bash uv theme={null} > uv remove py-clob-client-v2 py-builder-relayer-client py-builder-signing-sdk > uv add polymarket-client > ``` > > ```bash pip theme={null} > pip uninstall -y py-clob-client-v2 py-builder-relayer-client py-builder-signing-sdk > pip install polymarket-client > ``` > > ```bash Poetry theme={null} > poetry remove py-clob-client-v2 py-builder-relayer-client py-builder-signing-sdk > poetry add polymarket-client > ``` > > ## Client and Wallet Setup > > ### Create a Public Client > > `AsyncPublicClient` provides unauthenticated market discovery and data reads. > Production is the default environment. > > ```python Before theme={null} > from py_clob_client_v2.client import ClobClient > > client = ClobClient("https://clob.polymarket.com", chain_id=137) > ``` > > ```python After theme={null} > from polymarket import AsyncPublicClient > > client = AsyncPublicClient() > ``` > > ### Create an Authenticated Client > > `AsyncSecureClient` adds authenticated trading, account, and wallet actions. > `create` derives or creates CLOB credentials, resolves the account wallet, and > configures signing. > > ```python Before theme={null} > import os > > from py_clob_client_v2.client import ClobClient > from py_clob_client_v2.order_utils.model import SignatureTypeV2 > > temporary_client = ClobClient( > "https://clob.polymarket.com", > chain_id=137, > key=os.environ["POLYMARKET_PRIVATE_KEY"], > ) > credentials = temporary_client.create_or_derive_api_key() > > client = ClobClient( > "https://clob.polymarket.com", > chain_id=137, > key=os.environ["POLYMARKET_PRIVATE_KEY"], > creds=credentials, > signature_type=SignatureTypeV2.POLY_1271, > funder=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > ```python After theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > Omit `wallet` to use the default Deposit Wallet flow. > > ### Resume With Existing Credentials > > Read credentials from an authenticated client, store them securely, and pass > them to a new client to resume with the same API key. The private key and wallet > must identify the account that owns the credentials. > > ```python Before theme={null} > import os > > from py_clob_client_v2.client import ClobClient > from py_clob_client_v2.order_utils.model import SignatureTypeV2 > > credentials = client.creds > if credentials is None: > raise RuntimeError("Client has no credentials") > > # Store the credentials securely. > > resumed_client = ClobClient( > "https://clob.polymarket.com", > chain_id=137, > key=os.environ["POLYMARKET_PRIVATE_KEY"], > creds=credentials, > signature_type=SignatureTypeV2.POLY_1271, > funder=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > ```python After theme={null} > import os > > from polymarket import AsyncSecureClient > > credentials = client.credentials > > # Store the credentials securely. > > resumed_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > credentials=credentials, > ) > ``` > > ### Revoke the Current API Key > > Ending authentication revokes the current API key, invalidates the > `AsyncSecureClient`, and returns an `AsyncPublicClient`. > > ```python Before theme={null} > client.delete_api_key() > ``` > > ```python After theme={null} > public_client = await client.end_authentication() > ``` > > ### Configure Builder API Keys > > `AsyncSecureClient` accepts a `BuilderApiKey` for gasless wallet actions. Keep > the key, secret, and passphrase on the server. > > ```python Before theme={null} > import os > > from py_builder_relayer_client.client import RelayClient > from py_builder_signing_sdk.config import BuilderConfig > from py_builder_signing_sdk.sdk_types import BuilderApiKeyCreds > > builder_config = BuilderConfig( > local_builder_creds=BuilderApiKeyCreds( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ) > ) > > relayer = RelayClient( > "https://relayer-v2.polymarket.com", > 137, > os.environ["POLYMARKET_PRIVATE_KEY"], > builder_config, > ) > ``` > > ```python After theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > ### Configure Relayer API Keys > > `AsyncSecureClient` configures Relayer API keys directly. Pass the key and its > associated address when reconnecting an existing account. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ### Deploy a Deposit Wallet > > Creating an `AsyncSecureClient` without a `wallet` derives the signer's Deposit > Wallet address and deploys it when needed. Use Builder authorization to > authorize the deployment. > > ```python Before theme={null} > deployment = relayer.deploy_deposit_wallet() > deployment.wait() > ``` > > ```python After theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > > deposit_wallet_address = client.wallet > ``` > > ## Market Discovery > > ### Fetch a Market > > Both `AsyncPublicClient` and `AsyncSecureClient` provide `get_market` for reads > by Gamma market ID, slug, or Polymarket URL. > > ```python Before theme={null} > market = client.get_market("CONDITION_ID") > ``` > > ```python After theme={null} > market = await client.get_market(slug="MARKET_SLUG") > ``` > > If you only have a condition ID, filter `list_markets` and fetch its first page. > > ```python theme={null} > pages = client.list_markets(condition_ids=["CONDITION_ID"]) > page = await pages.first_page() > market = page.items[0] > ``` > > ### List Markets > > Both `AsyncPublicClient` and `AsyncSecureClient` provide `list_markets`, which > returns an async paginator and accepts filters directly. > > ```python Before theme={null} > page = client.get_markets() > markets = page["data"] > ``` > > ```python After theme={null} > pages = client.list_markets(closed=False, page_size=20) > page = await pages.first_page() > markets = page.items > ``` > > Simplified-market reads do not need a separate replacement. Sampling-market > reads migrate to `list_current_rewards`, which lists active reward > configurations. > > ```python Before theme={null} > markets = client.get_sampling_markets() > page = client.get_sampling_simplified_markets() > ``` > > ```python After theme={null} > pages = client.list_current_rewards() > page = await pages.first_page() > ``` > > ## Market Data > > ### Read Trading Parameters > > Both `AsyncPublicClient` and `AsyncSecureClient` return tick size and > negative-risk status on the market model. Order methods also resolve them > automatically. > > ```python Before theme={null} > tick_size = client.get_tick_size("TOKEN_ID") > neg_risk = client.get_neg_risk("TOKEN_ID") > fee_rate_bps = client.get_fee_rate_bps("TOKEN_ID") > ``` > > ```python After theme={null} > market = await client.get_market(slug="MARKET_SLUG") > tick_size = market.trading.minimum_tick_size > neg_risk = market.state.neg_risk > fee_schedule = market.trading.fee_schedule > ``` > > ### Read CLOB Market Details > > Both `AsyncPublicClient` and `AsyncSecureClient` return the typed market model. > Its trading fields replace the compact CLOB market response. > > ```python Before theme={null} > details = client.get_clob_market_info("CONDITION_ID") > tick_size = details["mts"] > neg_risk = details["nr"] > fee_details = details["fd"] > ``` > > ```python After theme={null} > market = await client.get_market(slug="MARKET_SLUG") > tick_size = market.trading.minimum_tick_size > neg_risk = market.state.neg_risk > fee_schedule = market.trading.fee_schedule > ``` > > ### Fetch Order Books > > Both `AsyncPublicClient` and `AsyncSecureClient` provide single and batch order > book reads. > > ```python Before theme={null} > from py_clob_client_v2 import BookParams > > book = client.get_order_book("TOKEN_ID") > books = client.get_order_books( > [BookParams(token_id="TOKEN_ID_1"), BookParams(token_id="TOKEN_ID_2")] > ) > ``` > > ```python After theme={null} > book = await client.get_order_book(asset_id="ASSET_ID") > books = await client.get_order_books(asset_ids=["ASSET_ID_1", "ASSET_ID_2"]) > ``` > > ### Fetch Prices > > Both `AsyncPublicClient` and `AsyncSecureClient` provide single and batch price > reads with typed requests. > > ```python Before theme={null} > from py_clob_client_v2 import BookParams, Side > > price = client.get_price("TOKEN_ID", Side.BUY) > prices = client.get_prices( > [ > BookParams(token_id="TOKEN_ID_1", side=Side.BUY), > BookParams(token_id="TOKEN_ID_2", side=Side.SELL), > ] > ) > ``` > > ```python After theme={null} > from polymarket import PriceRequest > > price = await client.get_price(asset_id="ASSET_ID", side="BUY") > prices = await client.get_prices( > requests=[ > PriceRequest(asset_id="ASSET_ID_1", side="BUY"), > PriceRequest(asset_id="ASSET_ID_2", side="SELL"), > ] > ) > ``` > > ### Fetch Midpoints > > Both `AsyncPublicClient` and `AsyncSecureClient` provide single and batch > midpoint reads. > > ```python Before theme={null} > from py_clob_client_v2 import BookParams > > midpoint = client.get_midpoint("TOKEN_ID") > midpoints = client.get_midpoints( > [BookParams(token_id="TOKEN_ID_1"), BookParams(token_id="TOKEN_ID_2")] > ) > ``` > > ```python After theme={null} > midpoint = await client.get_midpoint(asset_id="ASSET_ID") > midpoints = await client.get_midpoints(asset_ids=["ASSET_ID_1", "ASSET_ID_2"]) > ``` > > ### Fetch Spreads > > Both `AsyncPublicClient` and `AsyncSecureClient` provide single and batch spread > reads. > > ```python Before theme={null} > from py_clob_client_v2 import BookParams > > spread = client.get_spread("TOKEN_ID") > spreads = client.get_spreads( > [BookParams(token_id="TOKEN_ID_1"), BookParams(token_id="TOKEN_ID_2")] > ) > ``` > > ```python After theme={null} > spread = await client.get_spread(asset_id="ASSET_ID") > spreads = await client.get_spreads(asset_ids=["ASSET_ID_1", "ASSET_ID_2"]) > ``` > > ### Fetch Last Trade Prices > > Both `AsyncPublicClient` and `AsyncSecureClient` provide singular and batch > methods for last-trade prices. > > ```python Before theme={null} > from py_clob_client_v2 import BookParams > > last_trade = client.get_last_trade_price("TOKEN_ID") > last_trades = client.get_last_trades_prices( > [BookParams(token_id="TOKEN_ID_1"), BookParams(token_id="TOKEN_ID_2")] > ) > ``` > > ```python After theme={null} > last_trade = await client.get_last_trade_price(asset_id="ASSET_ID") > last_trades = await client.get_last_trade_prices( > asset_ids=["ASSET_ID_1", "ASSET_ID_2"] > ) > ``` > > ### Fetch Price History > > Both `AsyncPublicClient` and `AsyncSecureClient` provide a price history > paginator. Pass parameters as keyword arguments; each page contains typed points. > > ```python Before theme={null} > from py_clob_client_v2 import PricesHistoryParams > > history = client.get_prices_history( > PricesHistoryParams(market="TOKEN_ID", interval="1d", fidelity=60) > ) > ``` > > ```python After theme={null} > pages = client.list_price_history( > asset_id="ASSET_ID", > interval="1d", > bucket_seconds=3600, > ) > page = await pages.first_page() > history = page.items > ``` > > ### Estimate a Market Order Price > > Both `AsyncPublicClient` and `AsyncSecureClient` provide market-order price > estimates. Buys specify collateral spent, while sells specify shares sold. > > ```python Before theme={null} > from py_clob_client_v2 import OrderType, Side > > buy_price = client.calculate_market_price( > "TOKEN_ID", Side.BUY, 10, OrderType.FOK > ) > sell_price = client.calculate_market_price( > "TOKEN_ID", Side.SELL, 5, OrderType.FOK > ) > ``` > > ```python After theme={null} > buy_price = await client.estimate_market_price( > asset_id="ASSET_ID", side="BUY", amount=10, order_type="FOK" > ) > sell_price = await client.estimate_market_price( > asset_id="ASSET_ID", side="SELL", shares=5, order_type="FOK" > ) > ``` > > ### List Recent Market Trades > > Both `AsyncPublicClient` and `AsyncSecureClient` provide the public trade > paginator, which replaces the previous market-events response. > > ```python Before theme={null} > trades = client.get_market_trades_events("CONDITION_ID") > ``` > > ```python After theme={null} > pages = client.list_trades(condition_id=["CONDITION_ID"]) > page = await pages.first_page() > trades = page.items > ``` > > ## Orders > > ### Place a Limit Order > > `AsyncSecureClient` resolves tick size, negative-risk status, fees, and signing > details before submitting a limit order. > > ```python Before theme={null} > from py_clob_client_v2 import OrderArgs, Side > > response = client.create_and_post_order( > OrderArgs( > token_id="TOKEN_ID", > price=0.52, > size=10, > side=Side.BUY, > ) > ) > ``` > > ```python After theme={null} > response = await client.place_limit_order( > asset_id="ASSET_ID", > price=0.52, > size=10, > side="BUY", > ) > ``` > > ### Place a Market Order > > `AsyncSecureClient` places market orders. Buys specify collateral to spend, > while sells specify shares to sell. > > ```python Before theme={null} > from py_clob_client_v2 import MarketOrderArgs, OrderType, Side > > response = client.create_and_post_market_order( > MarketOrderArgs( > token_id="TOKEN_ID", > amount=10, > user_usdc_balance=10, > side=Side.BUY, > ), > order_type=OrderType.FOK, > ) > ``` > > ```python After theme={null} > response = await client.place_market_order( > asset_id="ASSET_ID", > side="BUY", > amount=10, > max_spend=10, > order_type="FOK", > ) > ``` > > `user_usdc_balance` becomes `max_spend`. The previous field supplied the > account balance used to adjust the order for fees; the unified SDK instead > accepts the maximum total USD to spend. Set `max_spend` equal to `amount` when > the amount should include fees, or omit it to pay applicable fees on top. > > ### Sign Without Posting > > `AsyncSecureClient` provides order-type-specific creation methods when signing > and submission need to happen separately. > > ```python Before theme={null} > from py_clob_client_v2 import MarketOrderArgs, OrderArgs, Side > > limit_order = client.create_order( > OrderArgs(token_id="TOKEN_ID", price=0.52, size=10, side=Side.BUY) > ) > market_order = client.create_market_order( > MarketOrderArgs(token_id="TOKEN_ID", amount=10, side=Side.BUY) > ) > ``` > > ```python After theme={null} > limit_order = await client.create_limit_order( > asset_id="ASSET_ID", > price=0.52, > size=10, > side="BUY", > ) > market_order = await client.create_market_order( > asset_id="ASSET_ID", > side="BUY", > amount=10, > ) > ``` > > ### Post Several Orders > > `AsyncSecureClient` provides `post_orders`. Order type and post-only behavior > are part of each signed order, so the method accepts signed orders directly. > > ```python Before theme={null} > from py_clob_client_v2 import OrderType, PostOrdersV2Args > > responses = client.post_orders( > [ > PostOrdersV2Args(order=first_order, orderType=OrderType.GTC), > PostOrdersV2Args(order=second_order, orderType=OrderType.GTC), > ] > ) > ``` > > ```python After theme={null} > responses = await client.post_orders([first_order, second_order]) > ``` > > ### Attribute an Order to a Builder > > `AsyncSecureClient` attaches the builder code to each order. > > ```python Before theme={null} > from py_clob_client_v2 import OrderArgs, Side > > response = client.create_and_post_order( > OrderArgs( > token_id="TOKEN_ID", > price=0.52, > size=10, > side=Side.BUY, > builder_code="BUILDER_CODE", > ) > ) > ``` > > ```python After theme={null} > response = await client.place_limit_order( > asset_id="ASSET_ID", > price=0.52, > size=10, > side="BUY", > builder_code="BUILDER_CODE", > ) > ``` > > ### Cancel Orders > > `AsyncSecureClient` provides explicit methods for cancelling one order, > several orders, all orders, or orders for a market. > > ```python Before theme={null} > from py_clob_client_v2 import OrderMarketCancelParams, OrderPayload > > client.cancel_order(OrderPayload(orderID="ORDER_ID")) > client.cancel_orders(["ORDER_ID_1", "ORDER_ID_2"]) > client.cancel_market_orders(OrderMarketCancelParams(market="CONDITION_ID")) > client.cancel_all() > ``` > > ```python After theme={null} > await client.cancel_order(order_id="ORDER_ID") > await client.cancel_orders(order_ids=["ORDER_ID_1", "ORDER_ID_2"]) > await client.cancel_market_orders(market="CONDITION_ID") > await client.cancel_all() > ``` > > ### Fetch an Order > > `AsyncSecureClient` fetches an order by ID using a keyword argument. > > ```python Before theme={null} > order = client.get_order("ORDER_ID") > ``` > > ```python After theme={null} > order = await client.get_order(order_id="ORDER_ID") > ``` > > ### List Open Orders > > `AsyncSecureClient` provides `list_open_orders`, which returns an async > paginator. When filtering by `asset_id` or the deprecated `token_id` alias, > also supply a nonblank `market` (the market condition ID). Otherwise, the > paginator raises `UserInputError` when it fetches a page. The synchronous > `SecureClient` has the same requirement. > > ```python Before theme={null} > from py_clob_client_v2 import OpenOrderParams > > orders = client.get_open_orders( > OpenOrderParams(market="CONDITION_ID", asset_id="TOKEN_ID") > ) > ``` > > ```python After theme={null} > pages = client.list_open_orders(market="CONDITION_ID", asset_id="ASSET_ID") > orders = [order async for order in pages.iter_items()] > ``` > > ### Check Order Scoring > > `AsyncSecureClient` provides `get_order_scoring` for one order and > `get_orders_scoring` for several. > > ```python Before theme={null} > from py_clob_client_v2 import OrderScoringParams, OrdersScoringParams > > scoring = client.is_order_scoring(OrderScoringParams(orderId="ORDER_ID")) > batch = client.are_orders_scoring( > OrdersScoringParams(orderIds=["ORDER_ID_1", "ORDER_ID_2"]) > ) > ``` > > ```python After theme={null} > scoring = await client.get_order_scoring(order_id="ORDER_ID") > batch = await client.get_orders_scoring( > order_ids=["ORDER_ID_1", "ORDER_ID_2"] > ) > ``` > > ## Account Activity and Balances > > ### List Account Trades > > `AsyncSecureClient` replaces both previous account trade-history methods with one > async paginator. > > ```python Before theme={null} > from py_clob_client_v2 import TradeParams > > trades = client.get_trades(TradeParams(market="CONDITION_ID")) > page = client.get_trades_paginated(TradeParams(market="CONDITION_ID")) > ``` > > ```python After theme={null} > pages = client.list_account_trades(market="CONDITION_ID") > first_page = await pages.first_page() > > trades = [trade async for trade in pages.iter_items()] > ``` > > ### List Builder Trades > > Both `AsyncPublicClient` and `AsyncSecureClient` provide public builder trade > history, filtered by builder code. > > ```python Before theme={null} > from py_clob_client_v2 import BuilderTradeParams > > page = client.get_builder_trades( > BuilderTradeParams(builder_code="BUILDER_CODE") > ) > trades = page["trades"] > ``` > > ```python After theme={null} > pages = client.list_builder_trades(builder_code="BUILDER_CODE") > page = await pages.first_page() > trades = page.items > ``` > > ### Read and Drop Notifications > > `AsyncSecureClient` provides notification methods with keyword arguments and > typed responses. > > ```python Before theme={null} > from py_clob_client_v2 import DropNotificationParams > > notifications = client.get_notifications() > client.drop_notifications(DropNotificationParams(ids=[1, 2])) > ``` > > ```python After theme={null} > notifications = await client.get_notifications() > await client.drop_notifications(ids=["1", "2"]) > ``` > > ### Refresh Balances and Allowances > > `AsyncSecureClient` reads balances and manages missing allowances while placing > orders. It completes the required approval, refreshes the allowance, and > retries the order. > > ```python Before theme={null} > from py_clob_client_v2 import AssetType, BalanceAllowanceParams > > params = BalanceAllowanceParams(asset_type=AssetType.COLLATERAL) > client.update_balance_allowance(params) > balance = client.get_balance_allowance(params) > ``` > > ```python After theme={null} > balance = await client.get_balance_allowance(asset_type="COLLATERAL") > response = await client.place_limit_order( > asset_id="ASSET_ID", > price=0.52, > size=10, > side="BUY", > ) > ``` > > ## Positions > > The unified methods build and submit wallet transactions. You no longer need to > encode contract calls or pass transaction arrays to `execute`. > > ### Split a Position > > `AsyncSecureClient` splits collateral into a complete set of YES and NO outcome > tokens. > > ```python Before theme={null} > from py_builder_relayer_client.models import Transaction > > split_tx = Transaction( > to=CTF_COLLATERAL_ADAPTER_ADDRESS, > data=collateral_adapter.encode_abi( > "splitPosition", > args=[PUSD_ADDRESS, bytes(32), CONDITION_ID, [1, 2], 1_000_000], > ), > value="0", > ) > > split = relayer.execute([split_tx], "Split position") > split.wait() > ``` > > ```python After theme={null} > split = await client.split_position( > condition_id="CONDITION_ID", > amount=1_000_000, > ) > await split.wait() > ``` > > ### Merge Positions > > `AsyncSecureClient` merges balanced YES and NO tokens back into collateral. > > ```python Before theme={null} > from py_builder_relayer_client.models import Transaction > > merge_tx = Transaction( > to=CTF_COLLATERAL_ADAPTER_ADDRESS, > data=collateral_adapter.encode_abi( > "mergePositions", > args=[PUSD_ADDRESS, bytes(32), CONDITION_ID, [1, 2], 1_000_000], > ), > value="0", > ) > > merge = relayer.execute([merge_tx], "Merge positions") > merge.wait() > ``` > > ```python After theme={null} > merge = await client.merge_positions( > condition_id="CONDITION_ID", > amount="max", > ) > await merge.wait() > ``` > > ### Redeem Resolved Positions > > `AsyncSecureClient` redeems winning outcome tokens for collateral after > resolution. > > ```python Before theme={null} > from py_builder_relayer_client.models import Transaction > > redeem_tx = Transaction( > to=CTF_COLLATERAL_ADAPTER_ADDRESS, > data=collateral_adapter.encode_abi( > "redeemPositions", > args=[PUSD_ADDRESS, bytes(32), CONDITION_ID, [1, 2]], > ), > value="0", > ) > > redeem = relayer.execute([redeem_tx], "Redeem positions") > redeem.wait() > ``` > > ```python After theme={null} > redeem = await client.redeem_positions(condition_id="CONDITION_ID") > await redeem.wait() > ``` > > ## Service Status > > Neither `AsyncPublicClient` nor `AsyncSecureClient` requires these calls. The > unified clients manage request timing internally. > > ```python Before theme={null} > client.get_ok() > timestamp = client.get_server_time() > ``` > > ```python After theme={null} > # No client call is required for request timestamp synchronization. > ``` > [tab] Rust > > A unified Rust SDK is in progress. Until it is available, use > `polymarket_client_sdk_v2` `0.7.0`, the current Rust SDK. > > See the [GitHub repository](https://github.com/Polymarket/rs-clob-client-v2) and > the [`polymarket_client_sdk_v2` package on crates.io](https://crates.io/crates/polymarket_client_sdk_v2) > for the complete API and examples. > > ## Install the Rust SDK > > Enable the `clob` feature for authentication and trading: > > ```bash theme={null} > cargo add polymarket_client_sdk_v2@0.7.0 --features clob > ``` > > ## Trade From a Deposit Wallet > > The Rust SDK supports the CLOB order path for an existing Deposit Wallet. It > does not include a client for deploying Deposit Wallets or submitting wallet > batches; use the Direct API workflows for those actions. > > Pass the deployed Deposit Wallet as the funder and use > `SignatureType::Poly1271` when authenticating. This example refreshes the > collateral allowance cache, then places a GTC limit buy: > > ```rust theme={null} > use std::str::FromStr as _; > > use alloy::signers::Signer as _; > use alloy::signers::local::LocalSigner; > use polymarket_client_sdk_v2::clob::types::request::UpdateBalanceAllowanceRequest; > use polymarket_client_sdk_v2::clob::types::{ > AssetType, OrderType, Side, SignatureType, > }; > use polymarket_client_sdk_v2::clob::{Client, Config}; > use polymarket_client_sdk_v2::types::{Address, Decimal, U256}; > use polymarket_client_sdk_v2::{POLYGON, PRIVATE_KEY_VAR}; > > #[tokio::main] > async fn main() -> anyhow::Result<()> { > let host = "https://clob-v2.polymarket.com"; > let signer = LocalSigner::from_str(&std::env::var(PRIVATE_KEY_VAR)?)? > .with_chain_id(Some(POLYGON)); > let deposit_wallet = Address::from_str(&std::env::var("DEPOSIT_WALLET")?)?; > > let client = Client::new(host, Config::default())? > .authentication_builder(&signer) > .funder(deposit_wallet) > .signature_type(SignatureType::Poly1271) > .authenticate() > .await?; > > client > .update_balance_allowance( > UpdateBalanceAllowanceRequest::builder() > .asset_type(AssetType::Collateral) > .build(), > ) > .await?; > > let response = client > .limit_order() > .token_id(U256::from_str(&std::env::var("TOKEN_ID")?)?) > .side(Side::Buy) > .price(Decimal::from_str("0.40")?) > .size(Decimal::from_str("100")?) > .order_type(OrderType::GTC) > .build_sign_and_post(&signer) > .await?; > > println!("order_id={} status={}", response.order_id, response.status); > Ok(()) > } > ``` > > ## Handle Matching Engine Restarts > > Rebuild and re-sign an order before each retry because `SignedOrder` is > consumed when it is submitted. Treat HTTP `425` as temporary and retry with > exponential backoff: > > ```rust theme={null} > use polymarket_client_sdk_v2::error::{Kind, StatusCode}; > > let mut delay = std::time::Duration::from_secs(1); > > for _ in 0..10 { > let order = client.limit_order() > .token_id(token_id).price(price).size(size).side(side) > .build().await?; > let signed = client.sign(&signer, order).await?; > > match client.post_order(signed).await { > Ok(response) => return Ok(response), > Err(err) if err.kind() == Kind::Status => { > if let Some(status) = err.downcast_ref::() { > if status.status_code == StatusCode::from_u16(425).unwrap() { > eprintln!("Engine restarting, retrying in {delay:?}..."); > tokio::time::sleep(delay).await; > delay = (delay * 2).min(std::time::Duration::from_secs(30)); > continue; > } > } > return Err(err); > } > Err(err) => return Err(err), > } > } > ``` > > See [Matching Engine Restarts](/trading/matching-engine) for the restart window, > post-only period, and restricted-mode responses. # Migrate from Data API v1 to v2 Source: https://docs.polymarket.com/migrate/data-api-v1-to-v2 Move an integration from the original Data API routes to their v2 counterparts: the route mapping, the contract changes, and the accounting snapshot retirement. Data API v2 replaces the original per-route contracts with one shared contract across every read. You can migrate one call site at a time, but new integrations should start on v2 directly. Use `https://data-api.polymarket.com` with the `/v2` prefix for v2 routes. > [!WARNING] > > **Data API v1 retires on November 2, 2026.** Move your integration to the > v2 routes in the mapping below. ## What Changed **Response envelope.** v1 routes return bare arrays or objects. Every v2 response wraps its payload in `data`, and paginated routes add a `pagination` object. A documented miss is `data: null` or an empty list, never an error. **Pagination.** v1 pages with `limit`/`offset`, and `offset` stops at 10,000 rows. v2 pages with an opaque cursor: follow `pagination.next_cursor` until it is `null`, with no offset arithmetic to manage, and the feed routes stay consistent while new rows arrive. See [Paginate With Cursors](/api-reference/data-api/overview#paginate-with-cursors). **Field casing.** v1 responses are `camelCase` (`proxyWallet`, `conditionId`). v2 responses are `snake_case` (`proxy_wallet`, `condition_id`). Request parameters accept both spellings on v2. **Market selection.** v1 selects markets with the `market` parameter. v2 unifies on `condition` (aliases `condition_id`, `conditionId`), taking at most 20 distinct comma-separated condition ids. `event_id` filtering carries over. **Rejected v1 parameters.** v2 returns HTTP `400` for obsolete `market`, `market_id`, `marketId`, and `offset` parameters rather than ignoring them. Replace market filters with `condition`, `condition_id`, or `conditionId`. Remove `offset` even when it is `0`: use `cursor` for paginated reads and omit pagination parameters for nonpaginated reads. **Position lifecycle.** v2 folds three v1 routes into one: `GET /v2/positions` serves the whole lifecycle behind a `status` filter (`OPEN`, `REDEEMABLE`, `REDEEMABLE_LOST`, `MERGEABLE`, `CLOSED`) with `redeemable` and `mergeable` flags on every row, replacing the separate `/closed-positions` and `/v1/market-positions` routes. `REDEEMABLE_LOST` narrows to still-held losing positions, and `MERGEABLE` to live complementary pairs a wallet can merge back to collateral. ## Route Mapping | v1 route | v2 route | Notes | | - | - | - | | `GET /positions` | `GET /v2/positions` | `status` defaults to open positions. `market` becomes `condition` | | `GET /closed-positions` | `GET /v2/positions?status=CLOSED` | Folded into the unified lifecycle | | `GET /v1/market-positions` | `GET /v2/positions?condition=…` | Market-anchored listing through the same route | | `GET /trades` | `GET /v2/trades` | | | `GET /activity` | `GET /v2/activity` | | | `GET /v1/activity/combos` | `GET /v2/activity/combos` | | | `GET /v1/positions/combos` | `GET /v2/positions/combos` | | | `GET /value` | `GET /v2/value` | | | `GET /traded` | `GET /v2/user-stats` | `data.trades` is the distinct-market count. Unknown users return `data: null` | | `GET /holders` | `GET /v2/holders` | Optional `include_pnl=true` adds entry and PnL economics per holder | | `GET /oi` | `GET /v2/oi` | | | `GET /live-volume` | `GET /v2/live-volume` | | | `GET /v1/leaderboard` | `GET /v2/leaderboard` | | | `GET /v1/builders/leaderboard` | `GET /v2/builders/leaderboard` | | | `GET /v1/builders/volume` | `GET /v2/builders/volume` | | | | `GET /v2/approvals` | | Each v2 endpoint page documents its full parameter set and row shape; several routes accept filters their v1 counterparts did not. ## New in v2 v2 adds these reads. User stats also covers the existing traded-market count: | Route | Returns | | - | - | | `GET /v2/user-pnl` | A user's PnL series | | `GET /v2/user-stats` | A user's profile stats | | `GET /v2/user-volume` | A user's trading volume | | `GET /v2/biggest-winners` | The biggest wins | | `GET /v2/prices-history` | A token's price history | | `GET /v2/resolutions` | Resolution state | | `GET /v2/tokens` | Token lookup by token id or condition | | `GET /v2/status` | Data freshness | ## Accounting Snapshot Retirement `GET /v1/accounting/snapshot` retires with Data API v1 on November 2, 2026. There is no v2 counterpart for its ZIP archive of CSVs. Remove calls to this route; the v2 portfolio, position, and activity reads are not an equivalent accounting export. ## SDK Migration to Data API V2 Data API v2 is supported starting with version `0.10.0` in both official SDKs: the TypeScript package `@polymarket/client` and the Python package `polymarket-client`. Review the [TypeScript SDK changelog](/changelog/sdks#typescript) or [Python SDK changelog](/changelog/sdks#python) for the breaking changes, renamed methods, response fields, and pagination behavior to update when migrating. # Polymarket Protocol V2 API Migration Source: https://docs.polymarket.com/migrate/polymarket-v2/api-integrations Add Polymarket Protocol V2 trading to an existing direct API integration while retaining CTF market support. Add V2 trading to an API integration already using pUSD and the CTFExchangeV2 order format. Keep your CTF trading path and CLOB authentication. ## Migrate Trading **1. Select the Trading ID** Given a Gamma market, use its `version` to choose the desired outcome's trading ID. For example, retrieve a market with: ```bash Fetch a Market theme={null} curl "https://gamma-api.polymarket.com/markets/" ``` Choose the ID field by `version`, even when both fields are present: | `version` | Outcome IDs | Response Format | | - | - | - | | `"v2"` | `positionIds` | Array of decimal strings | | `"v1"` | `clobTokenIds` | JSON-encoded array of decimal strings | Decode `outcomes` from JSON text. Select the ID at the intended outcome's index, decoding `clobTokenIds` first for V1. Reject missing or unsupported versions, unmatched outcomes, and missing or non-decimal IDs. Keep the selected ID as a decimal string, referred to as `` below. **2. Approve V2 Trading** V2 orders settle through ExchangeV3. Use the Polygon addresses for ExchangeV3, pUSD, and PositionManager from [Contract Addresses](/resources/contracts). Grant these approvals from the maker (the EOA or smart wallet holding the funds) and wait for confirmation: | Action | Approval | | - | - | | BUY | On pUSD: `approve(EXCHANGE_V3, amount)`. Cover collateral spend, including fees. | | SELL | On PositionManager: `setApprovalForAll(EXCHANGE_V3, true)`. | Existing CTF permissions do not grant these approvals. **3. Refresh Balances and Allowances** After confirmation, refresh the CLOB cache with your existing CLOB L2 authentication and the maker's signature type: ```bash V2 Position theme={null} curl -G "https://clob.polymarket.com/balance-allowance/update" \ -H "POLY_ADDRESS: " \ -H "POLY_SIGNATURE: " \ -H "POLY_TIMESTAMP: " \ -H "POLY_API_KEY: " \ -H "POLY_PASSPHRASE: " \ --data-urlencode "asset_type=CONDITIONAL-V2" \ --data-urlencode "token_id=" \ --data-urlencode "signature_type=" ``` ```bash pUSD theme={null} curl -G "https://clob.polymarket.com/balance-allowance/update" \ -H "POLY_ADDRESS: " \ -H "POLY_SIGNATURE: " \ -H "POLY_TIMESTAMP: " \ -H "POLY_API_KEY: " \ -H "POLY_PASSPHRASE: " \ --data-urlencode "asset_type=COLLATERAL" \ --data-urlencode "signature_type=" ``` Read `/balance-allowance` with the same parameters and a fresh L2 signature for that path. Check its `allowances` entry for ExchangeV3. `CONDITIONAL-V2` selects V2 positions; `COLLATERAL` selects pUSD. Keep `CONDITIONAL` for CTF positions. **4. Sign and Submit the V2 Order** Replace the order's EIP-712 domain with this Polygon configuration: ```json V2 Order Domain theme={null} { "name": "Polymarket CTF Exchange", "version": "3", "chainId": 137, "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" } ``` Keep the CTFExchangeV2 signed order structure, set `order.tokenId` to the V2 position ID, and re-sign. Submit through your existing order flow. CTF orders retain their exchange and domain version `"2"`. ## Verify the Migration Verify BUY and SELL fills and balances on both a V2 market and a CTF market. ## Track Resolution Through Gamma If you monitor resolution through Gamma, read the V2 market response: ```json V2 Market Resolution theme={null} { "version": "v2", "resolutionStatus": "resolved" } ``` For V2, `resolutionStatus` is `inactive`, `active`, or `resolved`. For V1, keep using `umaResolutionStatus`. ## Check Identifiers and Subscriptions Fetch the order book using the asset ID selected earlier: ```bash Fetch the Order Book theme={null} curl "https://clob.polymarket.com/book?token_id=" ``` Use the same asset ID for prices, orders, and market subscriptions (`assets_ids`). User-stream `markets` and market-wide cancellation use the market's condition ID. ## Update Custom Fill Calculations If you calculate fills yourself, use integer base units and the maker's signed amounts for each maker fill: ```text Counter-Asset Amount theme={null} counterAmount = floor(makerAssetFill × takerAmount / makerAmount) ``` `makerAssetFill` is collateral for a BUY and shares for a SELL. ExchangeV3 reduces a BUY's remaining collateral budget by the amount actually spent. CLOB GTC/GTD BUY targets are shares; FOK/FAK BUY targets are collateral. Reconcile fills and fees separately: BUY fees add to collateral spend; SELL fees are deducted from proceeds. # Polymarket Protocol V2 Contract Migration Source: https://docs.polymarket.com/migrate/polymarket-v2/contract-integrations Add Polymarket Protocol V2 position operations to an existing pUSD contract integration. Add Polymarket Protocol V2 support to an existing pUSD-based binary or neg-risk contract integration. Keep CTF support for V1 markets and holdings: updating the integration does not convert existing CTF balances. ## Update Position Operations V2 positions use a separate ledger. Update balance handling and permissions before replacing position calls. **1. Use PositionManager for V2 Positions** Configure PositionManager and Router using their [Polygon Contract Addresses](/resources/contracts). Use PositionManager for V2 balances and transfers, with `uint256` position IDs. Retain CTF token IDs for V1 markets. > [!WARNING] > > Protocol mints and unsafe transfers do not invoke ERC-1155 receiver > callbacks. Account for these balance changes explicitly if the receiving > contract relies on callbacks. **2. Approve Router** Grant these permissions from the account or contract holding the assets. Existing CTF approvals do not carry over. | Operation | Approval | | - | - | | Split | On pUSD: `approve(ROUTER, amount)` | | Merge or redeem | On PositionManager: `setApprovalForAll(ROUTER, true)` | **3. Replace Split, Merge, and Redemption Calls** Replace legacy calls with these V2 Router ABI signatures: ```text Router ABI theme={null} function split(bytes31 conditionId, uint256 amount) function merge(bytes31 conditionId, uint256 amount) function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount) ``` | Input | V2 value | | - | - | | `conditionId` | V2 `bytes31` condition ID. For a padded V2 `bytes32` value, validate its final byte is zero before narrowing. | | `amount` | Six-decimal base units: `1_000_000` is one pUSD or one share. Merge spends this amount of each outcome. | | `outcomeIndex` | Redemption uses `0` for YES or `1` for NO, replacing CTF index sets `1` and `2`. Supply an explicit amount. | Router pulls assets from the caller and returns outputs to that caller in one transaction. Do not pre-transfer assets to a module in a separate transaction. ## Update Payout Reads and Indexing Read redemption proceeds through PositionManager: ```text PositionManager ABI theme={null} function getPayout(uint256 positionId, uint256 amount) view returns (uint256) ``` The result is the pUSD payout in base units for the specified amount. Unresolved positions can revert; zero is a valid losing payout. Index PositionManager transfers and module events: * Split burns pUSD; merge and redemption mint pUSD. * Attribute operations using transfer owners and recipients. A module event's `initiator` is the immediate caller. * Avoid counting Router and module events as separate operations. V2 neg-risk results can be derived without individual `ConditionResolved` events. Refresh on `RemainingConditionsDerivableAsNo` and `SyntheticConditionDerivableAsYes`, then read the module's `getResult` or PositionManager's `getPayout`. ## Update V2 Trading For BUY orders, approve ExchangeV3 to spend pUSD, including fees. For SELL orders, approve ExchangeV3 as a PositionManager operator. Sign V2 orders against ExchangeV3 with EIP-712 domain version `"3"`; see the [API Migration Guide](/migrate/polymarket-v2/api-integrations). ## Enable V2 Automatic Redemption If using AutoRedeemer, submit this approval from the account or contract holding V2 positions. Use the configured PositionManager contract and AutoRedeemer address: ```solidity theme={null} positionManager.setApprovalForAll(AUTO_REDEEMER, true); ``` An authorized operator can redeem each submitted position's full balance, returning pUSD to the same holder. Account for these changes; approval alone does not schedule redemption. # Migrate to Polymarket Protocol V2 Source: https://docs.polymarket.com/migrate/polymarket-v2/overview Add V2 markets to an existing SDK, API, or smart-contract integration. > [!TIP] > > **App and website users:** No technical migration is required. Complete any > approval prompts shown in the app. Polymarket Protocol V2 introduces new position tokens and contracts for trading, position operations, and resolution. Follow the guide for your integration while retaining CTF support. Existing CTF holdings are not converted. ## Rollout Timeline New markets begin trading on Polymarket Protocol V2 in phases. Existing CTF markets keep their current contracts for trading, settlement, and redemption. All dates are in **2026**, and times are **Eastern Time (ET)**. Prepare your V2 integration before market creation: some markets are created 24 hours before the planned trading dates below. | Phase and Trading Start | Markets | | - | - | | **Phase 1** Monday, November 23, at 8:30 AM | BNB, DOGE, HYPE, SOL, XRP, and ZEC Up/Down, each at 5-minute and 15-minute intervals. Also NYC highest temperature, Warsaw highest temperature, and Munich lowest temperature. | | **Phase 2** Tuesday, November 24 | BTC and ETH Up/Down at 5-minute, 15-minute, and 4-hour intervals; other crypto, remaining weather, commodities, finance, and minor sports. | | **Phase 3** Tuesday, December 1 | Soccer, American football (NFL and college football), basketball (including NBA and college basketball), tennis, esports, and social count. | Later phases depend on successful trading and settlement, correct reward scoring, and sufficient liquidity in the preceding phase. No cutovers are scheduled for Thanksgiving on November 26. Thanksgiving week's NFL and college football games remain on CTF. ## What Changes * **Market identifiers:** Integrations select V2 position IDs or CTF token IDs using the market's version. * **Trading:** V2 orders use ExchangeV3, signing domain version `"3"`, and new approval targets. CLOB balance and allowance requests for V2 positions use `CONDITIONAL-V2`. * **Position operations:** V2 balances live in PositionManager. V2 split, merge, and redemption use Router, with updated calls and payout handling. ## Migration Guides How does your integration connect to Polymarket? Select all that apply. For integrations already using pUSD and the CTFExchangeV2 order format, collateral, wallets, CLOB credentials, and endpoints stay the same. # Polymarket Protocol V2 SDK Migration Source: https://docs.polymarket.com/migrate/polymarket-v2/sdk-integrations Add Polymarket Protocol V2 markets to an existing pUSD trading integration using the Polymarket SDKs. Update your integration to trade on Polymarket Protocol V2 markets while keeping support for existing CTF markets. Before you start: * If you use a standalone CLOB SDK, complete the [unified SDK migration](/migrate/clob-sdk-to-unified-sdk) first to update client setup. * If upgrading from before 0.10.0 and using portfolio or history reads, also apply the [Data API v2 migration](/migrate/data-api-v1-to-v2#sdk-migration-to-data-api-v2). **1. Upgrade the SDK** > [tab] TypeScript > > Upgrade `@polymarket/client` to the latest release (0.12.0 or later) using your preferred > package manager. > > ```bash npm theme={null} > npm install @polymarket/client@latest > ``` > > ```bash bun theme={null} > bun add @polymarket/client@latest > ``` > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest > ``` > [tab] Python > > Upgrade `polymarket-client` to the latest release (0.12.0 or later) using your preferred > package manager. Requires Python 3.11 or later. > > ```bash uv theme={null} > uv add --upgrade-package polymarket-client "polymarket-client>=0.12.0" > ``` > > ```bash pip theme={null} > python -m pip install --upgrade "polymarket-client>=0.12.0" > ``` > > ```bash poetry theme={null} > poetry add polymarket-client@latest > ``` **2. Ensure Trading Approvals** > [tab] TypeScript > > Keep calling `setupTradingApprovals()` on your `SecureClient`. It also > approves the contracts required for Polymarket Protocol V2. > Gasless wallets need a configured > [Relayer or Builder API key](/trading/wallets-auth#set-up-trading-approvals). > > ```ts theme={null} > await client.setupTradingApprovals(); > ``` > [tab] Python > > Keep calling `setup_trading_approvals()` on your `AsyncSecureClient`. > It also approves the contracts required for Polymarket Protocol V2. > Gasless wallets need a configured > [Relayer or Builder API key](/trading/wallets-auth#set-up-trading-approvals). > > ```python theme={null} > await client.setup_trading_approvals() > ``` **3. Select the Trading ID** > [tab] TypeScript > > Given a `market`, for example returned by `fetchMarket()`, check its > `version`: use the desired outcome's `positionId` for V2 or `tokenId` > for V1. This example selects YES: > > ```ts theme={null} > const outcome = market.outcomes.yes; > const assetId = > market.version === ProtocolVersion.V2 ? outcome.positionId : outcome.tokenId; > ``` > [tab] Python > > Given a `market`, for example returned by `get_market()`, check its > `version`: use the desired outcome's `position_id` for V2 or `token_id` > for V1. This example selects YES: > > ```python theme={null} > outcome = market.outcomes.yes > asset_id = outcome.position_id if market.version == ProtocolVersion.V2 else outcome.token_id > ``` **4. Trade as Usual** > [tab] TypeScript > > Use the selected `assetId`: > > ```ts theme={null} > import { OrderSide } from "@polymarket/client"; > > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.50", > size: "10", > }); > ``` > > Use the selected ID for order books, prices, and market subscriptions too. > [tab] Python > > Use the selected `asset_id`: > > ```python theme={null} > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.50", > size="10", > ) > ``` > > Use the selected ID for order books, prices, and market subscriptions too. ## Verify the Migration Verify BUY and SELL fills and balances on both a V2 market and a CTF market. ## Read Balances and Allowances > [tab] TypeScript > > Read balances and allowances using the asset ID selected earlier: > > ```ts theme={null} > import { AssetType, ProtocolVersion } from "@polymarket/client"; > import { fetchBalanceAllowance } from "@polymarket/client/actions"; > > const { balance, allowances } = await fetchBalanceAllowance(client, { > assetId, > assetType: > market.version === ProtocolVersion.V2 > ? AssetType.CONDITIONAL_V2 > : AssetType.CONDITIONAL, > }); > > console.log(balance, allowances); > ``` > > Balances and allowances are returned in base units. Allowances are keyed > by spender address. To refresh before reading, import `updateBalanceAllowance` > from `@polymarket/client/actions` and pass `client` followed by the same > parameters. > [tab] Python > > Read balances and allowances using the asset ID selected earlier: > > ```python theme={null} > from polymarket import ProtocolVersion > > result = await client.get_balance_allowance( > asset_id=asset_id, > asset_type=( > "CONDITIONAL-V2" > if market.version == ProtocolVersion.V2 > else "CONDITIONAL" > ), > ) > > print(result.balance, result.allowances) > ``` > > Balances and allowances are returned in base units. Allowances are keyed > by spender address. ## Update Resolution Reads If your integration tracks V2 market resolution: > [tab] TypeScript > > Call `fetchResolutions` for the selected market: > > ```ts theme={null} > if (!market.conditionId) throw new Error("Missing condition ID"); > > const resolutions = await client.fetchResolutions({ > conditionIds: [market.conditionId], > }); > ``` > > Use payouts only from a row whose `status` is `"resolved"`. > [tab] Python > > Call `get_resolutions` for the selected market: > > ```python theme={null} > if not market.condition_id: > raise ValueError("Missing condition ID") > > resolutions = await client.get_resolutions(condition_ids=[market.condition_id]) > ``` > > Use payouts only from a row whose `status` is `"resolved"`. # Migrate from RTDS to PolyBolt Source: https://docs.polymarket.com/migrate/rtds-to-polybolt Migrate price subscriptions from RTDS to PolyBolt Move reference-price subscriptions to PolyBolt while keeping your event-driven price workflow. Reference prices require authentication. > [!WARNING] > > Every PolyBolt price subscription must > name its provider, and subscriptions served by Chainlink require your > Chainlink API key. See [Send Your Chainlink API > Key](/api-reference/live-data/overview#send-your-chainlink-api-key). ## Migrate an API Integration Update the connection, authentication, and subscription frames. See the [Live Data Channel](/api-reference/wss/polybolt) for the full protocol. ### What Changes | RTDS | PolyBolt | | - | - | | `wss://ws-live-data.polymarket.com` | `wss://ws-live-v2.polymarket.com/ws` | | Text frame `PING` every 5 s | Nothing to send. The server pings every 25 s (optional `{"op":"ping"}`) | | `{"action":"subscribe","subscriptions":[{"topic","type","filters"}]}` | `{"op":"subscribe","subscriptions":[{"channel","filter"}]}`. `filter` is a JSON object, not a string | | Source-named price and TWAP topics | Channels `price.crypto`, `price.crypto.twap`, `price.equity` (see the mapping below) | | `{"topic","type","timestamp","payload"}` per message | `{"v":1,"channel","seq","ts","snapshot"?,"dropped"?,"payload"}`. Channel-specific payloads | | Silence for a quiet symbol | One snapshot frame per subscription (`snapshot: true`), possibly empty | | No sequence | Dense per-channel `seq` and a `dropped` counter | | Public | Reference-price channels require CLOB API credentials via `{"op":"auth"}` | | No limits | 64 subscriptions, 20 subscribe frames/s, 64 KB frames, 8 auth frames. Breaches close `4008` | | Raw `1006` closes | `4001` auth, `4002` slow consumer, `4003` draining, `4008` policy | ### Topic Mapping | RTDS topic | RTDS filter | PolyBolt channel | PolyBolt filter | Notes | | - | - | - | - | - | | `crypto_prices` (Binance) | `btcusdt` | `price.crypto` | `{ "symbol": "btcusd", "provider": "binance" }` | Request Binance with the canonical `btcusd` symbol. | | `crypto_prices_chainlink` | `{"symbol":"btc/usd"}` | `price.crypto` | `{"symbol":"btcusd","provider":"chainlink"}` | Source stays Chainlink. Use `btcusd` instead of `btc/usd`. | | `crypto_prices_twap_sixty` | `{"symbol":"btc/usd"}` | `price.crypto.twap` | `{"symbol":"btcusd","window_seconds":60,"provider":"chainlink"}` | 60-second Chainlink TWAP | | `crypto_prices_twap_thirty` | `{"symbol":"btc/usd"}` | None | None | No PolyBolt replacement for the 30-second window | | `equity_prices` | `{"symbol":"AAPL"}` | `price.equity` | `{"symbol":"aapl","provider":"pyth"}` | Same catalog, lowercase: stocks, ETFs, forex, metals and the commodities `cll`, `hn`, `cc3m` | > [!WARNING] > > Crypto spot and TWAP subscriptions now use lowercase symbols ending in `usd`, > not `usdt`. Update `btcusdt` or `btc/usd` to `btcusd`, and apply the same > format to every crypto symbol you subscribe to. Live price payloads contain `symbol`, `value`, `full_accuracy_value`, `timestamp`, and `source`, the vendor that produced the price. Name the vendor with `provider` in every filter ([Pin a Price Provider](/api-reference/live-data/overview#pin-a-price-provider)). Equity updates may also include `received_at` and `is_carried_forward`, and equity payloads carry `market_status` (`open`, `closed` or `unknown`), which legacy RTDS never sent ([Read the Market Status](/api-reference/live-data/overview#read-the-market-status)). TWAP uses `window_seconds`. Prefer the exact decimal `full_accuracy_value` over the float `value`. Legacy TWAP frames used `window_s` and an E18 fixed-point price. Do not apply that E18 conversion to PolyBolt's decimal string. ### Before and After ```json RTDS theme={null} { "action": "subscribe", "subscriptions": [ { "topic": "crypto_prices", "type": "update", "filters": "btcusdt" } ] } ``` ```json PolyBolt theme={null} { "op": "auth", "auth": { "apiKey": "", "secret": "", "passphrase": "" } } { "op": "subscribe", "subscriptions": [ { "channel": "price.crypto", "filter": { "symbol": "btcusd", "provider": "binance" } } ] } ``` ### Client Checklist 1. Point at `wss://ws-live-v2.polymarket.com/ws` and delete the `PING` text heartbeat. 2. Send `{"op":"auth", ...}` with CLOB API credentials before subscribing to price channels. 3. Batch subscriptions per connection. Stay at or below 64 active pairs. 4. Seed local state from the snapshot, then apply live updates. Compare `seq` only within the same connection and channel. 5. Handle `4003` with one jittered reconnect, `4008` as a bug, and resubscribe after every reconnect. ## Comments Retirement The live comments stream is being retired without a replacement streaming channel. See [Comments](/market-data/realtime-data#comments) for supported comment-listing options. ## Activity on RTDS Keep using RTDS for the `activity` topic. It has no PolyBolt channel. ## Migrate SDKs to PolyBolt ### Migrate a 60-Second TWAP Subscription > [tab] TypeScript > > PolyBolt support starts in `@polymarket/client` version `0.11.0`. > Migrate a BTC/USD 60-second TWAP subscription with `createSecureClient`. Deprecated RTDS price topics are planned for removal one month after the `0.11.0` release. > > > [accordion] Before: RTDS > > > > ```ts theme={null} > > import { createPublicClient } from "@polymarket/client"; > > > > const client = createPublicClient(); > > const stream = await client.subscribe([ > > { > > topic: "prices.crypto.chainlink.twap", > > symbols: ["btc/usd"], > > windowSeconds: 60, > > }, > > ]); > > > > try { > > for await (const event of stream) { > > if (event.type === "update") { > > const price = event.payload.value; > > } > > } > > } finally { > > await stream.close(); > > } > > ``` > > **1. Create an Authenticated Client** > > Set `POLYMARKET_PRIVATE_KEY`. This example uses the signer's EOA address and the default production configuration. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const signer = privateKey(process.env.POLYMARKET_PRIVATE_KEY); > const client = await createSecureClient({ > signer, > wallet: await signer.getAddress(), > }); > ``` > > **2. Subscribe to Prices** > > Change the topic from `prices.crypto.chainlink.twap` to `prices.crypto.twap`, provide an explicit `symbols` list and set `provider: PriceProvider.Chainlink`. Change `btc/usd` to `btcusd` and remove `windowSeconds` from the subscription input. The new topic always uses a 60-second window. > > ```ts theme={null} > import { PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { > topic: "prices.crypto.twap", > symbols: ["btcusd"], > provider: PriceProvider.Chainlink, > providerApiKey: "", > }, > ]); > > try { > for await (const event of stream) { > // event: CryptoTwapPriceEvent > if (event.type === "subscribe") { > const history = event.payload.data; > // Seed local state from the snapshot. > } else { > const price = event.payload.value; > const observedAt = event.payload.timestamp; > // Apply the latest price. > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: CryptoTwapPriceEvent > > > > **events: CryptoTwapPriceEvent\[]** > > > > ```ts CryptoTwapPriceEvent Union theme={null} > > type CryptoTwapPriceEvent = > > | { > > topic: "prices.crypto.twap"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > windowSeconds: 60; > > }; > > } > > | { > > topic: "prices.crypto.twap"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > windowSeconds: 60; > > }; > > }; > > ``` > > > > ```json CryptoTwapPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.crypto.twap", > > "type": "subscribe", > > "timestamp": 1788886175000, > > "seq": 2, > > "payload": { > > "symbol": "btcusd", > > "data": [ > > { > > "timestamp": 1788886057000, > > "value": "78788.525642908795142144" > > }, > > { > > "timestamp": 1788886058000, > > "value": "78788.786579938813673472" > > }, > > { > > "timestamp": 1788886059000, > > "value": "78789.052518750893375488" > > } > > ], > > "windowSeconds": 60 > > } > > }, > > { > > "topic": "prices.crypto.twap", > > "type": "update", > > "timestamp": 1788886177000, > > "seq": 3, > > "payload": { > > "symbol": "btcusd", > > "timestamp": 1788886177000, > > "value": "78803.715261094101516288", > > "windowSeconds": 60 > > } > > } > > ] > > ``` > > Returned events still include `windowSeconds: 60`. There is no PolyBolt replacement for the deprecated 30-second TWAP workflow. > > `subscribe()` waits for server acceptance. Snapshot events provide `payload.data` for initialization. Updates retain `symbol`, `timestamp`, decimal-string `value`, and `windowSeconds`. > > The new crypto topics require explicit lowercase USD symbols such as `btcusd`. Inputs such as `btc/usd`, `btcusdt`, and `BTCUSD` fail with `UserInputError`. The SDK does not rewrite them. > [tab] Python > > Migrate a BTC/USD 60-second TWAP subscription with `AsyncSecureClient.subscribe`. Run the following steps inside an async function. > > > [!NOTE] > > > > PolyBolt support starts in `polymarket-client` version `0.11.0`. The legacy > > RTDS price specs are deprecated. > > > [accordion] Before: RTDS > > > > The legacy subscription passed these specs to `AsyncPublicClient.subscribe` or `AsyncSecureClient.subscribe`: > > > > ```python theme={null} > > from polymarket.streams import CryptoPricesChainlinkTwapSpec > > > > spec = CryptoPricesChainlinkTwapSpec(symbols=["btc/usd"], window_seconds=60) > > ``` > > **1. Create an Authenticated Client** > > Set `POLYMARKET_PRIVATE_KEY` to your signer private key. This example uses the signer's EOA address. `AsyncSecureClient.create` derives or retrieves API credentials. > > ```python theme={null} > import os > > from eth_account import Account > from polymarket import AsyncSecureClient > > private_key = os.environ["POLYMARKET_PRIVATE_KEY"] > client = await AsyncSecureClient.create( > private_key=private_key, > wallet=Account.from_key(private_key).address, > ) > ``` > > **2. Subscribe to Prices** > > Subscribe to BTC/USD with `CryptoTwapPriceSpec` and `provider="chainlink"`. The async context manager closes the subscription when the block exits. > > ```python theme={null} > from polymarket.streams import CryptoTwapPriceSpec > > async with await client.subscribe( > CryptoTwapPriceSpec(symbols=["btcusd"], provider="chainlink", provider_api_key="") > ) as stream: > async for event in stream: > # event: CryptoTwapPriceEvent > if event.type == "subscribe": > history = event.payload.data > # Seed local state from the snapshot. > else: > price = event.payload.value > observed_at = event.payload.timestamp > # Apply the latest price. > ``` > > > [accordion] Output: CryptoTwapPriceEvent > > > > **event: CryptoTwapPriceEvent** > > > > ```python CryptoTwapPriceEvent Union theme={null} > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimeTwapSnapshot: > > symbol: str > > data: tuple[RealtimePricePoint, ...] > > window_seconds: Literal[60] > > > > class RealtimeTwapUpdate: > > symbol: str > > timestamp: datetime > > value: Decimal > > window_seconds: Literal[60] > > > > class CryptoTwapPriceSnapshotEvent: > > topic: Literal["prices.crypto.twap"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeTwapSnapshot > > > > class CryptoTwapPriceUpdateEvent: > > topic: Literal["prices.crypto.twap"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeTwapUpdate > > > > CryptoTwapPriceEvent = CryptoTwapPriceSnapshotEvent | CryptoTwapPriceUpdateEvent > > ``` > > > > ```json CryptoTwapPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:37Z", > > "seq": 3, > > "topic": "prices.crypto.twap", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:37Z", > > "value": "78803.715261094101516288", > > "symbol": "btcusd", > > "window_seconds": 60 > > } > > } > > ``` > > `subscribe()` waits for server acceptance. The SDK handles authentication, heartbeats, reconnects, and distributing filters beyond 64 per connection. Handle errors from both subscription creation and iteration. Acceptance times out after 30 seconds. `seq` belongs to one channel on one connection and resets after reconnecting. > > Crypto symbols must be explicit lowercase USD pairs such as `btcusd`. `btc/usd`, `btcusdt`, and `BTCUSD` raise `UserInputError`. ### Migrate Crypto Spot Prices > [tab] TypeScript > > Use the authenticated `client` created above. Change the symbol suffix from `usdt` to `usd`, for example `btcusdt` to `btcusd`. Remove any slash separators, for example `btc/usd` to `btcusd`. The new topic requires explicit lowercase USD symbols. > > Set `provider: PriceProvider.Binance` to request Binance prices. `provider` is required. Check `event.payload.source` for the provider actually served. > > > [accordion] Before: RTDS > > > > ```ts theme={null} > > import { createPublicClient } from "@polymarket/client"; > > > > const client = createPublicClient(); > > const stream = await client.subscribe([ > > { topic: "prices.crypto.chainlink", symbols: ["btc/usd"] }, > > { topic: "prices.crypto.binance", symbols: ["btcusdt"] }, > > ]); > > > > try { > > for await (const event of stream) { > > if (event.type === "update") { > > const price = event.payload.value; > > } > > } > > } finally { > > await stream.close(); > > } > > ``` > > Replace the legacy subscription with: > > ```ts theme={null} > import { PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { > topic: "prices.crypto", > symbols: ["btcusd"], > provider: PriceProvider.Binance, > }, > ]); > try { > for await (const event of stream) { > if (event.type === "subscribe") { > const history = event.payload.data; // Snapshot of historical prices. > } else { > const price = event.payload.value; > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: CryptoPriceEvent > > > > **events: CryptoPriceEvent\[]** > > > > ```ts CryptoPriceEvent Union theme={null} > > type CryptoPriceEvent = > > | { > > topic: "prices.crypto"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > }; > > } > > | { > > topic: "prices.crypto"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > receivedAt: EpochMilliseconds | undefined; > > isCarriedForward: boolean | undefined; > > }; > > }; > > ``` > > > > ```json CryptoPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.crypto", > > "type": "subscribe", > > "timestamp": 1788886176000, > > "seq": 1, > > "payload": { > > "symbol": "btcusd", > > "data": [ > > { > > "timestamp": 1788886057000, > > "value": "78803.76173179" > > }, > > { > > "timestamp": 1788886058000, > > "value": "78801.86287741" > > }, > > { > > "timestamp": 1788886059000, > > "value": "78798.28703224" > > } > > ] > > } > > }, > > { > > "topic": "prices.crypto", > > "type": "update", > > "timestamp": 1788886177000, > > "seq": 5, > > "payload": { > > "symbol": "btcusd", > > "timestamp": 1788886177000, > > "value": "78794.15450441" > > } > > } > > ] > > ``` > [tab] Python > > Use the authenticated `client` created above, then call `client.subscribe`. > > > [accordion] Before: RTDS > > > > The legacy subscription passed these specs to `AsyncPublicClient.subscribe` or `AsyncSecureClient.subscribe`: > > > > ```python theme={null} > > from polymarket.streams import CryptoPricesSpec > > > > specs = [ > > CryptoPricesSpec(topic="prices.crypto.chainlink", symbols=["btc/usd"]), > > CryptoPricesSpec(topic="prices.crypto.binance", symbols=["btcusdt"]), > > ] > > ``` > > Replace `CryptoPricesSpec` with `CryptoPriceSpec`. Set `provider="binance"` to request Binance prices. `provider` is required. Check `event.payload.source` for the provider actually served. > > Replace the legacy call with this subscription: > > ```python theme={null} > from polymarket.streams import CryptoPriceSpec > > async with await client.subscribe( > CryptoPriceSpec(symbols=["btcusd"], provider="binance") > ) as stream: > async for event in stream: > # event: CryptoPriceEvent > if event.type == "subscribe": > history = event.payload.data # Snapshot of historical prices. > else: > price = event.payload.value > observed_at = event.payload.timestamp > ``` > > > [accordion] Output: CryptoPriceEvent > > > > **event: CryptoPriceEvent** > > > > ```python CryptoPriceEvent Union theme={null} > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimePriceSnapshot: > > symbol: str > > data: tuple[RealtimePricePoint, ...] > > > > class RealtimePriceUpdate: > > symbol: str > > timestamp: datetime > > value: Decimal > > received_at: datetime | None > > is_carried_forward: bool | None > > > > class CryptoPriceSnapshotEvent: > > topic: Literal["prices.crypto"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimePriceSnapshot > > > > class CryptoPriceUpdateEvent: > > topic: Literal["prices.crypto"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimePriceUpdate > > > > CryptoPriceEvent = CryptoPriceSnapshotEvent | CryptoPriceUpdateEvent > > ``` > > > > ```json CryptoPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:37Z", > > "seq": 5, > > "topic": "prices.crypto", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:37Z", > > "value": "78794.15450441", > > "symbol": "btcusd" > > } > > } > > ``` > > `subscribe` events provide a tuple of historical price points in `payload.data`. `update` events provide the latest price. Values are `Decimal`, and timestamps are UTC `datetime` objects. > > Choose explicit lowercase USD symbols such as `btcusd`. For live prices only, skip events whose `type` is `"subscribe"`. ### Migrate Equity Prices > [tab] TypeScript > > Use the authenticated `client` created above. Preserve `symbol` and `types` when changing the topic. > > > [accordion] Before: RTDS > > > > ```ts theme={null} > > import { createPublicClient } from "@polymarket/client"; > > > > const client = createPublicClient(); > > const stream = await client.subscribe([ > > { topic: "prices.equity.pyth", symbol: "aapl", types: ["update"] }, > > ]); > > > > try { > > for await (const event of stream) { > > if (event.type === "update") { > > const price = event.payload.value; > > } > > } > > } finally { > > await stream.close(); > > } > > ``` > > Replace the legacy subscription with: > > ```ts theme={null} > import { PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { > topic: "prices.equity", > symbol: "aapl", > types: ["update"], > provider: PriceProvider.Pyth, > }, > ]); > try { > for await (const event of stream) { > if (event.type === "update") { > const price = event.payload.value; > } > } > } finally { > await stream.close(); > } > ``` > > > [accordion] Output: EquityPriceEvent > > > > **events: EquityPriceEvent\[]** > > > > ```ts EquityPriceEvent Union theme={null} > > import type { EquityMarketStatus } from "@polymarket/client"; > > > > type EquityPriceEvent = > > | { > > topic: "prices.equity"; > > type: "subscribe"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > marketStatus?: EquityMarketStatus; > > data: { timestamp: EpochMilliseconds; value: DecimalString }[]; > > }; > > } > > | { > > topic: "prices.equity"; > > type: "update"; > > timestamp: EpochMilliseconds; > > seq?: number; > > dropped?: number; > > payload: { > > symbol: string; > > marketStatus?: EquityMarketStatus; > > timestamp: EpochMilliseconds; > > value: DecimalString; > > receivedAt: EpochMilliseconds | undefined; > > isCarriedForward: boolean | undefined; > > }; > > }; > > ``` > > > > ```json EquityPriceEvent Example theme={null} > > [ > > { > > "topic": "prices.equity", > > "type": "subscribe", > > "timestamp": 1788886176400, > > "seq": 1, > > "payload": { > > "symbol": "aapl", > > "marketStatus": "open", > > "data": [ > > { > > "timestamp": 1788886056800, > > "value": "316.11" > > }, > > { > > "timestamp": 1788886057000, > > "value": "316.11" > > }, > > { > > "timestamp": 1788886057200, > > "value": "316.11001" > > } > > ] > > } > > }, > > { > > "topic": "prices.equity", > > "type": "update", > > "timestamp": 1788886176600, > > "seq": 2, > > "payload": { > > "symbol": "aapl", > > "marketStatus": "open", > > "timestamp": 1788886176600, > > "value": "316.1", > > "receivedAt": 1788886176600 > > } > > } > > ] > > ``` > > `types: ["update"]` keeps this stream limited to live updates. Omit `types` to receive history snapshots too. > [tab] Python > > Use the authenticated `client` created above, then call `client.subscribe`. > > > [accordion] Before: RTDS > > > > The legacy subscription passed these specs to `AsyncPublicClient.subscribe` or `AsyncSecureClient.subscribe`: > > > > ```python theme={null} > > from polymarket.streams import EquityPricesSpec > > > > spec = EquityPricesSpec(symbol="AAPL", types=["update"]) > > ``` > > Replace `EquityPricesSpec` with `EquityPriceSpec`, preserving `symbol` and `types`, and set `provider="pyth"` to keep the Pyth source. Symbols are trimmed and lowercased. `types=["update"]` keeps live updates only. Omit `types` to receive history snapshots too. > > Replace the legacy call with this subscription: > > ```python theme={null} > from polymarket.streams import EquityPriceSpec > > async with await client.subscribe( > EquityPriceSpec(symbol="aapl", types=["update"], provider="pyth") > ) as stream: > async for event in stream: > # event: EquityPriceEvent > if event.type == "update": > price = event.payload.value > observed_at = event.payload.timestamp > ``` > > > [accordion] Output: EquityPriceEvent > > > > **event: EquityPriceEvent** > > > > ```python EquityPriceEvent Union theme={null} > > from polymarket.streams import EquityMarketStatus > > > > class RealtimePricePoint: > > timestamp: datetime > > value: Decimal > > > > class RealtimeEquityPriceSnapshot: > > symbol: str > > market_status: EquityMarketStatus | None = None > > data: tuple[RealtimePricePoint, ...] > > > > class RealtimeEquityPriceUpdate: > > symbol: str > > market_status: EquityMarketStatus | None = None > > timestamp: datetime > > value: Decimal > > received_at: datetime | None > > is_carried_forward: bool | None > > > > class EquityPriceSnapshotEvent: > > topic: Literal["prices.equity"] > > type: Literal["subscribe"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeEquityPriceSnapshot > > > > class EquityPriceUpdateEvent: > > topic: Literal["prices.equity"] > > type: Literal["update"] > > timestamp: datetime > > seq: int | None > > dropped: int | None > > payload: RealtimeEquityPriceUpdate > > > > EquityPriceEvent = EquityPriceSnapshotEvent | EquityPriceUpdateEvent > > ``` > > > > ```json EquityPriceEvent Example theme={null} > > { > > "timestamp": "2026-09-08T16:49:36.600000Z", > > "seq": 2, > > "topic": "prices.equity", > > "type": "update", > > "payload": { > > "timestamp": "2026-09-08T16:49:36.600000Z", > > "value": "316.1", > > "symbol": "aapl", > > "market_status": "open", > > "received_at": "2026-09-08T16:49:36.600000Z" > > } > > } > > ``` > > `subscribe` events provide a tuple of historical price points in `payload.data`. `update` events provide the latest price. Values are `Decimal`, and timestamps are UTC `datetime` objects. > > Updates may include `received_at` and `is_carried_forward`. Read [market status](/market-data/realtime-data#read-the-market-status) on snapshots and live updates to distinguish closed markets from stalled prices. Both SDKs expose this field from version 0.14.0. # Connect to NEX Source: https://docs.polymarket.com/nex/connect Connect through PrivateLink or an allowlisted public IP. After [approval](/nex/get-access), use either connection below. For the best latency results, use PrivateLink in NEX's AWS London zone. ## Set Up Your Connection > [tab] AWS PrivateLink > > **1. Create an Endpoint** > > We'll allowlist your 12-digit AWS account ID and send the service name. > Create an IPv4 Interface VPC endpoint in `eu-west-2`, AZ ID `euw2-az1` only. > Allow TCP `443` from your clients in its security group and disable Private > DNS (`private_dns_enabled = false`). Check the AZ ID: names such as > `eu-west-2a` vary across accounts. Another AZ will not provide failover. > > **2. Get the Connection Approved** > > Send us the endpoint ID (`vpce-…`). Wait for approval and status `available`. > > **3. Set Up DNS** > > In a private hosted zone attached to your VPC, point these CNAMEs to your > endpoint DNS name: > > * `nex.preprod.defi.euw2.polymarket.sh` > * `nex-ws.preprod.defi.euw2.polymarket.sh` > > Preserve the service hostname in TLS SNI and the HTTP `Host` header if > connecting through endpoint DNS directly. > > **4. Check Connectivity** > > Run from a client inside your connected VPC after setting up DNS: > > ```bash theme={null} > curl -i https://nex.preprod.defi.euw2.polymarket.sh/health > ``` > > Expect HTTP `200`. > > AWS bills endpoint usage to your account. > [tab] Public IP Allowlisting > > **1. Send Your Outbound IPs** > > Send each stable public IPv4 address your clients use, individually (`/32`). > For clients behind NAT, use the NAT gateway's public addresses. Wait for our > approval before connecting. > > **2. Map the Service Hostnames** > > Map the trading and WebSocket hostnames to `51.24.102.79` in your resolver > or hosts file. Their default DNS does not select the public connection. > Allow outbound TCP `443` and keep the hostname in TLS SNI and HTTP `Host`. > > **3. Check Connectivity** > > Run from an allowlisted client. This selects the public address while > preserving the hostname for TLS and routing: > > ```bash theme={null} > curl -i \ > --connect-to nex.preprod.defi.euw2.polymarket.sh:443:51.24.102.79:443 \ > https://nex.preprod.defi.euw2.polymarket.sh/health > ``` > > Expect HTTP `200`. ## Service Addresses | Service | Base URL | | - | - | | Trading API | `https://nex.preprod.defi.euw2.polymarket.sh` | | WebSocket feeds | `wss://nex-ws.preprod.defi.euw2.polymarket.sh` | | Markets (Gamma) | `https://gamma-api-preprod.polymarket.dev` | | Relayer | `https://relayer-preprod.polymarket.dev` | Gamma and the relayer require `x-client-id` and `x-client-secret` headers. We'll send the credentials privately after approval. These are separate from your trading credentials. # Get Access Source: https://docs.polymarket.com/nex/get-access Request access, choose a connection and get test funds. [Submit the access form](https://docs.google.com/forms/d/e/1FAIpQLScpqt2izLI3YvRiY9Up6kcqzBcIgWmx-Y7GdkXcwiiNOYRz4g/viewform) with your name, email, team and what you'd like to run on NEX. Choose a connection: * **Public access:** list each stable outbound IPv4 address your clients use. If you use a NAT gateway, send its public IPs. We allowlist individual `/32` addresses. * **PrivateLink:** send your 12-digit AWS account ID and confirm you can create an endpoint in `eu-west-2` (London), AZ ID `euw2-az1`. This is the recommended path for the best latency results. Add a Telegram or Signal contact for a direct chat with the NEX team. If you know your expected requests per second and WebSocket connection count, include those too. ## Test Funds Include your Amoy trading address so we can arrange test pUSD. For a Deposit Wallet, send the Deposit Wallet address, which can differ from your signer. If you need help setting one up, tell us in the form. We'll email your connection instructions and credentials after approval, then help with account setup, funds and trading approvals. For PrivateLink, we'll also approve the endpoint you create. > [card] [Connect to NEX](/nex/connect) > > Set up your connection after access is approved. # NEX Sandbox Source: https://docs.polymarket.com/nex/overview Early access to Polymarket's new exchange. NEX is Polymarket's new exchange, built from the ground up in Rust. The sandbox gives you early access to run your strategies with your existing trading stack. ## Why NEX The current CLOB grew quickly and accumulated a lot of technical debt. We've made it faster and increased its capacity, but fixing one part can still cause problems elsewhere. We need an exchange we can keep improving as volume grows. NEX rebuilds the matching engine and WebSocket stack so we can address those problems in the core design. > [!TIP] > > NEX is a drop-in replacement for the CLOB API, with no breaking changes. Use > your existing integration with the sandbox configuration and credentials. ## Early Results We're running production traffic through NEX in shadow mode. The initial results show faster order processing and higher capacity than the current CLOB. > [card] Over 200× Faster > > Place-order processing in early shadow tests. > [card] 10× More Capacity > > 100k commands/s sustained and 150k commands/s in bursts. ## Try the Beta The sandbox runs on Polygon Amoy (`80002`) with test pUSD and bot-provided liquidity. Its books are separate from production. This is an early beta, and we'll be actively updating it as we fix issues and improve performance. We're aiming to release NEX before the end of 2026. [Request access](/nex/get-access) through public IP allowlisting or AWS PrivateLink. For the best latency results, use PrivateLink in AWS London, in the same zone as NEX. We'll help with setup and test funds through your onboarding chat. After approval, [connect to NEX](/nex/connect), then [start trading](/nex/start-trading). # Start Trading Source: https://docs.polymarket.com/nex/start-trading Connect your trading stack and place a sandbox order. Complete [connection setup](/nex/connect) first. We'll arrange test pUSD, credentials and approvals during onboarding. ## Configure Your Integration > [tab] API > > NEX is a drop-in replacement for the CLOB API. > > **1. Switch the Base URL** > > | Environment | Base URL | > | - | - | > | Production | `https://clob.polymarket.com` | > | NEX Sandbox | `https://nex.preprod.defi.euw2.polymarket.sh` | > > Keep your existing routes, payloads and response handling. > > **2. Use Sandbox Signing and Credentials** > > Sign for Polygon Amoy (`80002`) using the Amoy exchange contracts > configured during onboarding. Authenticate with your sandbox trading > credentials. Use an EOA or Deposit Wallet; Safe and Proxy Wallets are > unavailable. EOAs need Amoy POL for their own approval transactions. > > **3. Check the API** > > ```bash theme={null} > curl -i https://nex.preprod.defi.euw2.polymarket.sh/health > ``` > > Expect HTTP `200`. > [tab] TypeScript > > Use the latest stable release of every Polymarket SDK in your stack, including > separate trading and relayer packages. Set `NEX_CLOB_URL` to > `https://nex.preprod.defi.euw2.polymarket.sh`. You'll also need an Amoy RPC URL > and your sandbox signer's private key. > > This example uses your signer's address (EOA) as the trading account on Amoy. > > > [!NOTE] > > > > The sandbox supports EOAs and Deposit Wallets; Safe and Proxy Wallets are > > unavailable. EOAs need Amoy POL for their own approval transactions. Use your > > Deposit Wallet address for funding if you trade through one. > > **1. Update the SDK** > > Requires Node.js 24 or later. > > ```bash theme={null} > npm install @polymarket/client@latest viem > ``` > > **2. Create the Client** > > Set `GAMMA_CLIENT_ID` and `GAMMA_CLIENT_SECRET` to the Gamma credentials > sent after approval. > > ```typescript theme={null} > import { createSecureClient, forkEnvironmentConfig } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > import { http } from "viem"; > import { polygonAmoy } from "viem/chains"; > > const rpcUrl = process.env.AMOY_RPC_URL!; > const signer = privateKey(process.env.POLYMARKET_PRIVATE_KEY, { > chain: polygonAmoy, > transport: http(rpcUrl), > }); > > const amoy = forkEnvironmentConfig({ > name: "amoy", > chainId: polygonAmoy.id, > rpc: rpcUrl, > clob: { rest: process.env.NEX_CLOB_URL! }, > gamma: { > rest: "https://gamma-api-preprod.polymarket.dev", > headers: { > "x-client-id": process.env.GAMMA_CLIENT_ID!, > "x-client-secret": process.env.GAMMA_CLIENT_SECRET!, > }, > }, > }); > > const client = await createSecureClient({ > signer, > wallet: await signer.getAddress(), > environment: amoy, > }); > ``` > > See the [TypeScript SDK guide](/getting-started/typescript) for the rest of > the client API. > [tab] Python > > Use the latest stable release of every Polymarket SDK in your stack, including > separate trading and relayer packages. Set `NEX_CLOB_URL` to > `https://nex.preprod.defi.euw2.polymarket.sh`. You'll also need an Amoy RPC URL > and your sandbox signer's private key. > > This example uses your signer's address (EOA) as the trading account on Amoy. > > > [!NOTE] > > > > The sandbox supports EOAs and Deposit Wallets; Safe and Proxy Wallets are > > unavailable. EOAs need Amoy POL for their own approval transactions. Use your > > Deposit Wallet address for funding if you trade through one. > > **1. Update the SDK** > > Requires Python 3.11 or later. > > ```bash theme={null} > python -m pip install --upgrade polymarket-client eth-account httpx > ``` > > **2. Create the Client** > > Amoy currently uses the SDK team's internal environment helper. Run > this setup inside your existing async application. > > ```python theme={null} > import os > from dataclasses import replace > > from eth_account import Account > from polymarket import AsyncSecureClient > from polymarket._internal.environment import PRODUCTION_CONFIG, create_environment > > private_key = os.environ["POLYMARKET_PRIVATE_KEY"] > eoa_address = Account.from_key(private_key).address > > amoy = create_environment( > name="amoy", > config=replace( > PRODUCTION_CONFIG, > chain_id=80002, > rpc_url=os.environ["AMOY_RPC_URL"], > clob_url=os.environ["NEX_CLOB_URL"].rstrip("/"), > gamma_url="https://gamma-api-preprod.polymarket.dev", > exchange_v3="0xe3333700cA9d93003F00f0F71f8515005F6c00Aa", > position_manager="0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > ), > ) > > client = await AsyncSecureClient.create( > private_key=private_key, > wallet=eoa_address, > environment=amoy, > ) > ``` > > For synchronous code, import `SecureClient` instead and call > `SecureClient.create` without `await`. > > See the [Python SDK guide](/getting-started/python) for the rest of the > client API. > [accordion] Legacy Clients > > Set `NEX_CLOB_URL` to the NEX base URL above. These examples use an EOA; > complete your existing authentication flow before trading. For a Deposit > Wallet, retain its signing configuration. > > > [tab] TypeScript > > > > `@polymarket/clob-client-v2` is deprecated. Prefer `@polymarket/client` > > for new integrations. > > > > ```bash theme={null} > > npm install @polymarket/clob-client-v2@latest > > ``` > > > > Use your existing signer, configured for Amoy: > > > > ```typescript theme={null} > > import { Chain, ClobClient } from "@polymarket/clob-client-v2"; > > > > const client = new ClobClient({ > > host: process.env.NEX_CLOB_URL!, > > chain: Chain.AMOY, > > signer, > > }); > > ``` > > > [tab] Python > > > > `py-clob-client-v2` is deprecated. Prefer `polymarket-client` for new > > integrations. > > > > ```bash theme={null} > > python -m pip install --upgrade py-clob-client-v2 > > ``` > > > > ```python theme={null} > > import os > > from py_clob_client_v2 import ClobClient > > > > client = ClobClient( > > host=os.environ["NEX_CLOB_URL"], > > chain_id=80002, > > key=os.environ["POLYMARKET_PRIVATE_KEY"], > > ) > > ``` > > > [tab] Rust > > > > The Rust CLOB SDK remains supported. The unified Rust SDK is in progress. > > > > ```bash theme={null} > > cargo add polymarket_client_sdk_v2 --features clob > > ``` > > > > ```rust theme={null} > > use polymarket_client_sdk_v2::clob::{Client, Config}; > > > > let host = std::env::var("NEX_CLOB_URL")?; > > let client = Client::new(&host, Config::default())?; > > ``` > > > > This creates an unauthenticated client. Configure your trading signer > > for Amoy (`80002`) and continue with your existing authentication flow. > > See the [SDK migration guide](/migrate/clob-sdk-to-unified-sdk) to move an > existing TypeScript or Python integration to the unified SDK. ## Find a Market Choose an outcome from a sandbox market, then read its order book. > [tab] API > > Use the Gamma credentials we sent privately to list sandbox markets: > > ```bash theme={null} > curl --fail-with-body -G \ > "https://gamma-api-preprod.polymarket.dev/markets" \ > --header "x-client-id: $GAMMA_CLIENT_ID" \ > --header "x-client-secret: $GAMMA_CLIENT_SECRET" \ > --data-urlencode "closed=false" \ > --data-urlencode "limit=5" > ``` > > Choose an outcome from the response. Use its position ID for Polymarket V2 or > its token ID for CTF. Set `NEX_ASSET_ID` to that identifier, then read its book: > > ```bash theme={null} > curl --fail-with-body -G \ > "https://nex.preprod.defi.euw2.polymarket.sh/book" \ > --data-urlencode "token_id=$NEX_ASSET_ID" > ``` > > See [List Markets](/api-reference/markets/list-markets) and > [Get Order Book](/api-reference/market-data/get-order-book) for response schemas. > [tab] TypeScript > > Call `listMarkets()` to find Polymarket Protocol V2 markets with the > Gamma credentials configured above. > > ```typescript theme={null} > import { ProtocolVersion } from "@polymarket/client"; > > const pages = client.listMarkets({ > closed: false, > version: ProtocolVersion.V2, > pageSize: 5, > }); > const page = await pages.firstPage(); > > for (const market of page.items) { > console.log(market.id, market.question, market.version); > } > ``` > > Select YES in a market accepting orders, then call `fetchOrderBook()` with > its position ID: > > ```typescript theme={null} > const market = page.items.find((market) => market.state.acceptingOrders); > if (!market) throw new Error("None of these markets is accepting orders."); > > const assetId = market.outcomes.yes.positionId; > if (!assetId) throw new Error("No trading identifier for this outcome."); > > const book = await client.fetchOrderBook({ assetId }); > console.log(book.tickSize, book.minOrderSize); > ``` > [tab] Python > > The Python SDK cannot yet attach Gamma's sandbox headers. Fetch > Polymarket Protocol V2 market data with HTTPX using the Gamma credentials > sent after approval, then > parse the binary markets with the SDK's `Market` model: > > ```python theme={null} > import json > > import httpx > from polymarket import Market > > async with httpx.AsyncClient() as gamma: > response = await gamma.get( > "https://gamma-api-preprod.polymarket.dev/markets/keyset", > headers={ > "x-client-id": os.environ["GAMMA_CLIENT_ID"], > "x-client-secret": os.environ["GAMMA_CLIENT_SECRET"], > }, > params=[ > ("closed", "false"), > ("version", "v2"), > ("limit", "5"), > ], > ) > response.raise_for_status() > markets = [] > for item in response.json()["markets"]: > outcomes = item.get("outcomes") or [] > if isinstance(outcomes, str): > outcomes = json.loads(outcomes) > if len(outcomes) == 2: > markets.append(Market.parse_response(item)) > > for market in markets: > print(market.id, market.question, market.version) > ``` > > Select YES in a market accepting orders and read its book with > `get_order_book()`: > > ```python theme={null} > market = next((market for market in markets if market.state.accepting_orders), None) > if market is None: > raise ValueError("None of these markets is accepting orders.") > > asset_id = market.outcomes.yes.position_id > if asset_id is None: > raise ValueError("No trading identifier for this outcome.") > > book = await client.get_order_book(asset_id=asset_id) > print(book.tick_size, book.min_order_size) > ``` ## Place and Track an Order Place a small limit order, read it back, then cancel the remaining quantity. A resting order can fill before you cancel it. > [tab] API > > Use your sandbox credentials and the Amoy signing configuration validated > during onboarding. > > **1. Place an Order** > > Submit a small limit order. Follow the market's tick size and minimum > order size. See [Post a New Order](/api-reference/trade/post-a-new-order). > > **2. Read It Back** > > [Fetch the order by ID](/api-reference/trade/get-single-order-by-id). > > **3. Cancel the Remaining Quantity** > > See [Manage Orders](/trading/manage-orders) for cancellation requests. > [tab] TypeScript > > Use the authenticated `client`, `assetId` and `book` from the steps above. > The example uses the book's minimum size and a buy price of one tick. > > **1. Place an Order** > > ```typescript theme={null} > import { OrderSide } from "@polymarket/client"; > > const result = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: book.tickSize, > size: book.minOrderSize, > postOnly: true, > }); > > if (!result.ok) throw new Error(result.message); > console.log(result.orderId); > ``` > > **2. Read It Back** > > ```typescript theme={null} > const order = await client.fetchOrder({ orderId: result.orderId }); > console.log(order.status); > ``` > > **3. Cancel the Remaining Quantity** > > ```typescript theme={null} > const cancellation = await client.cancelOrder({ orderId: result.orderId }); > console.log(cancellation.canceled, cancellation.notCanceled); > ``` > [tab] Python > > Use the authenticated `client`, `asset_id` and `book` from the steps above. > The example uses the book's minimum size and a buy price of one tick. > > **1. Place an Order** > > ```python theme={null} > result = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price=book.tick_size, > size=book.min_order_size, > post_only=True, > ) > > if not result.ok: > raise RuntimeError(result.message) > print(result.order_id) > ``` > > **2. Read It Back** > > ```python theme={null} > order = await client.get_order(order_id=result.order_id) > print(order.status) > ``` > > **3. Cancel the Remaining Quantity** > > ```python theme={null} > cancellation = await client.cancel_order(order_id=result.order_id) > print(cancellation.canceled, cancellation.not_canceled) > ``` Order reads return open orders. If it fills before you read it back, follow updates on the [user feed](/nex/websocket-feeds). A match happens before settlement; follow settlement before checking your position. # WebSocket Feeds Source: https://docs.polymarket.com/nex/websocket-feeds Subscribe to order books, prices and your own orders and fills. Complete [connection setup](/nex/connect), then append a path below to `wss://nex-ws.preprod.defi.euw2.polymarket.sh`. | Feed | Path | Connection Limit | | - | - | - | | Original market | `/ws/market` | No application connection limit | | Original user | `/ws/user` | No application connection limit | | subs-v2 market | `/beta/ws/market` | 50 per IP | | subs-v2 user | `/beta/ws/user` | 20 per IP and 10 per API key; both apply | Public clients behind the same NAT share its per-IP allowance. ## Market Feed Send this after connecting. Replace `OUTCOME_ID` with the identifier from your [sandbox market](/nex/start-trading#find-a-market). ```json theme={null} { "type": "market", "assets_ids": ["OUTCOME_ID"] } ``` You'll receive a book snapshot followed by updates. See the [Market Channel reference](/api-reference/wss/market) for event schemas. ## User Feed Send your sandbox trading credentials after connecting. Replace the credential values below; Gamma credentials do not authenticate this feed. ```json theme={null} { "type": "user", "auth": { "apiKey": "YOUR_API_KEY", "secret": "YOUR_API_SECRET", "passphrase": "YOUR_API_PASSPHRASE" } } ``` Add `markets` with condition IDs to filter activity by market. See the [User Channel reference](/api-reference/wss/user). ## Heartbeats and Reconnects Send the text `PING` every 10 seconds; expect `PONG`. Idle connections close, so send activity at least once a minute. After disconnecting, reconnect with backoff and resubscribe. Rebuild your book from the new snapshot and reconcile account activity with authenticated reads. # Institutional Overview Source: https://docs.polymarket.com/partners/overview Settle trades matched on your platform as positions in Polymarket's prediction markets. Polymarket's institutional integration is for trading platforms that match counterparties themselves, such as request for quote (RFQ) venues. Your platform runs price discovery, and Polymarket settles each agreed trade as positions in its prediction markets. It is a separate integration from building on the order book: to place orders on the order book, start with [Trading](/trading/overview). ## Request for Quote (RFQ) Trades On the order book, prices are discovered by matching orders as they arrive. With an RFQ trade, price discovery happens on your platform instead: two counterparties agree on a price and size there, and your platform submits the agreed trade to Polymarket. Polymarket executes it on Polygon as one matched pair of signed orders, which never rest on the order book. Each counterparty authorizes only its own side, with a session key for its Polymarket Deposit Wallet. Your platform identifies itself with a partner API key, which does not authorize moving funds. ### Same Markets and Positions as the Order Book RFQ trades settle in the same prediction markets as the order book: * **Markets:** an RFQ trade runs on a Polymarket market found through the public Gamma API, and its price is checked against that market's order book midpoint. * **Positions:** each counterparty receives standard Polymarket positions. They can be held, sold on the order book, or redeemed when the market resolves. * **Liquidity:** your platform can use RFQ trades and the order book together to find the best price and liquidity for a market. ## Get Access Access is by invitation. To request access, email [institutional@polymarket.com](mailto:institutional@polymarket.com). Polymarket issues your API key during onboarding, together with access to a testing environment. For questions about RFQ trade fees and guardrails, email [blocks@polymarket.com](mailto:blocks@polymarket.com). ## Next Steps > [card] [RFQ Trades Guide](/partners/rfq-trades) > > Find a market, then validate, sign, submit, and track an RFQ trade. > [card] [API Reference](/api-reference/rfq-trades/overview) > > Review the base URLs, authentication, and every request. # RFQ Trades Partner API Source: https://docs.polymarket.com/partners/rfq-trades Settle trades that two counterparties agreed on your platform as one matched pair of signed Polymarket orders. The Request for Quote (RFQ) Trades Partner API lets your platform settle trades that two counterparties negotiated off Polymarket. Each side is a standard Polymarket exchange order signed for that counterparty, your platform submits the signed pair in one request, and Polymarket executes it on Polygon. The orders never rest on the order book. See the [Institutional Overview](/partners/overview) for how RFQ trades relate to the order book. > [!NOTE] > > Access is by invitation. Polymarket issues your API key during partner > onboarding. To request access, email > [institutional@polymarket.com](mailto:institutional@polymarket.com). ## How an RFQ Trade Works Your platform authenticates every request with its partner API key. Each counterparty authorizes only its own side: it gives your platform a [session key](#session-keys) for its Polymarket [Deposit Wallet](/trading/wallets-auth#wallet-types), and your platform signs that counterparty's orders with it. ```mermaid theme={null} sequenceDiagram autonumber participant Parties as Counterparties participant Partner as Your Platform participant Gamma as Gamma API participant RFQ as RFQ Trades API participant Chain as Polygon Parties->>Partner: Share a session key and Deposit Wallet address (once) Partner->>Gamma: Find a tradable market Partner->>RFQ: Validate the agreed terms Partner->>RFQ: Prepare both orders RFQ-->>Partner: Unsigned orders and fees Partner->>Partner: Sign each order with its counterparty's session key Partner->>RFQ: Submit the signed pair RFQ-->>Partner: Trade accepted as PENDING RFQ->>Chain: Execute the matched orders RFQ-->>Partner: FILLED or REJECTED ``` 1. [**Find a market**](#find-markets) through the public Gamma API. 2. [**Validate the terms**](#validate-the-terms) (optional). One request runs the market, price, account, and guardrail checks and reports all of them. 3. [**Prepare the orders**](#prepare-the-orders) (optional). Polymarket builds both unsigned orders, their signing payloads, and the fee each side pays. 4. [**Sign the orders.**](#sign-the-orders) Your platform signs each order with its counterparty's session key. 5. [**Submit the trade.**](#submit-the-trade) This is the only request that creates a trade. 6. [**Track the trade**](#track-the-trade) until it reaches `FILLED` or `REJECTED`, by polling or over the WebSocket stream. ### Operations Every RFQ trade is one of three operations, determined by the sides of the two orders. The collateral is [pUSD](/concepts/pusd), Polymarket's USDC-backed ERC-20 token on Polygon. | Operation | Orders | What happens on-chain | Party keys | | - | - | - | - | | `split` | Two buys: one YES, one NO, for the same number of shares | Both sides pay pUSD. A complete set is minted and split between them. | `yes`, `no` | | `merge` | Two sells: one YES, one NO, for the same number of shares | Both sides deliver shares. The set is merged and the pUSD is split between them. | `yes`, `no` | | `trade` | One buy and one sell of the same outcome token, at equal amounts | Shares move from the seller to the buyer against pUSD at the agreed price. | `buyer`, `seller` | Requests and responses key each side by these party keys. For example, the `fees` returned for a `split` are keyed `yes` and `no`. ### Base URL | Environment | Base URL | | - | - | | Production | `https://external-rfq-partner.polymarket.com` | | Testing | Shared during onboarding, together with test API keys for that environment | ### Conventions * **Amounts** (`shares`, `makerAmount`, `takerAmount`, fees) are base-10 integer strings in 6-decimal units. `"1000000"` is one share or one pUSD. * **Prices and tolerances** are decimal strings, such as `"0.65"`. * **Times** are RFC 3339 UTC strings, except order timestamps, which are Unix seconds. * **Request bodies are decoded strictly.** An unknown field returns `400`. * **Every error from the API uses one envelope.** See [Errors](#errors). Every request and response is specified in the [API Reference](#api-reference). ## Authentication Every request is signed with your partner API key. Polymarket identifies your platform from the key and never from the request body, so a request can only read and create your own trades. The key does not authorize moving funds: each counterparty authorizes its own side through its [order signature](#sign-the-orders). Every request except `GET /v1/time` carries three headers: | Header | Value | | - | - | | `RFQ-Key-Id` | ``, the public half of your API key | | `RFQ-Timestamp` | ``, the current Unix time in seconds | | `RFQ-Signature` | ``, the request signature, created with your API `secret` | Create a new timestamp for each request, within 30 seconds of server time. Then sign the timestamp, the uppercase HTTP method, the path, and the exact serialized body you send: ```text theme={null} message = + + + rfq_signature = urlsafeBase64WithPadding( HMAC-SHA256(base64UrlDecode(), message) ) ``` For a `GET`, the body is empty. The examples on this page use these placeholders. See [Authentication](/api-reference/rfq-trades/authentication) for TypeScript and Python signing helpers, a test vector, and the WebSocket handshake. ## Find Markets Find markets through the public Gamma API at `https://gamma-api.polymarket.com`. It needs no API key. To list, page, and search events and fetch a market, see [Discover Markets](/market-data/discover-markets). Discovery data does not need to be perfectly fresh: Polymarket re-checks the market and its on-chain state on every RFQ trade request. ### Check That a Market Is Tradable Trade only markets where all of these hold: ```javascript theme={null} market.active && !market.closed && !market.archived && market.acceptingOrders && market.enableOrderBook && (!market.umaResolutionStatus || market.umaResolutionStatus === "initialized"); ``` Any other `umaResolutionStatus`, such as `proposed`, `disputed`, or `resolved`, means a CTF market has entered resolution and its outcome may already be known. Skip it even though the other flags can still be `true` at that point. Polymarket Protocol V2 markets don't set `umaResolutionStatus`. ### Read the Trading Identity An RFQ trade request references the market and its outcome tokens with these fields: | Field | Use | | - | - | | `id` | The `marketId` of an RFQ trade request | | `version` | `"v2"` for a Polymarket Protocol V2 market, absent for CTF. Selects which token ID field to read. | | `positionIds` | Polymarket V2: the YES and NO position IDs. Each order's `tokenId` is one of them. | | `clobTokenIds` | CTF: the YES and NO outcome token IDs. Each order's `tokenId` is one of them. | | `negRisk` | CTF: selects the exchange contract the orders are signed against. Prepare applies it for you. | Index `0` of `positionIds` or `clobTokenIds` is always the `yes` side and index `1` the `no` side, in `outcomes` order, even when the outcomes are names such as `["Lakers", "Celtics"]`. `clobTokenIds`, `outcomes`, and `outcomePrices` are JSON-encoded strings, such as `"[\"1234…\", \"5678…\"]"`. Parse them before use. `orderPriceMinTickSize` and `orderMinSize` are order book conventions. RFQ trades never enter the book, so they are not enforced, but staying within them is recommended. An RFQ trade price can have at most 6 decimals. ### Price a Trade The public CLOB API at `https://clob.polymarket.com` gives the current order book, prices, and midpoints for quoting, by outcome token ID. See [Market Data](/market-data/overview). Every RFQ trade price must sit inside a [price band](#price-band) around the CLOB midpoint. Read the current band for both outcome tokens before you quote: ```bash theme={null} curl "https://external-rfq-partner.polymarket.com/v1/markets/253591/price-band" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " ``` Sign the request with the method `GET`, the path `/v1/markets/253591/price-band`, and an empty body. The response body gives the band of each outcome token at the default tolerance: ```json theme={null} { "marketId": "253591", "tolerance": "0.5", "outcomes": { "yes": { "tokenId": "", "mark": "0.62", "lower": "0.31", "upper": "0.93", "source": "clob_midpoint" }, "no": { "tokenId": "", "mark": "0.38", "lower": "0.19", "upper": "0.57", "source": "clob_midpoint" } }, "readAt": "2026-07-24T12:34:56Z" } ``` `mark` is the token's CLOB midpoint, and a price on that token must sit between `lower` and `upper`. See [Price Band](#price-band) for how the band is computed. ## Settle a Trade Once two counterparties agree on a market, an operation, a price, and a size, settle the trade with the requests below. Only the submission creates a trade. Every request carries the three [authentication headers](#authentication). **1. Describe the Terms** First, describe the agreed trade as terms. Validate and prepare both take the terms as their request body: ```json split theme={null} { "marketId": "253591", "operation": "split", "price": "0.65", "shares": "1500000000", "parties": { "yes": { "maker": "", "signatureType": 3 }, "no": { "maker": "", "signatureType": 3 } } } ``` ```json trade theme={null} { "marketId": "253591", "operation": "trade", "token": "yes", "price": "0.65", "shares": "1500000000", "parties": { "buyer": { "maker": "", "signatureType": 3 }, "seller": { "maker": "", "signatureType": 3 } } } ``` Where: * `marketId` is the Gamma market `id`. * `operation` is `split`, `merge`, or `trade`. See [Operations](#operations). * `price` is the YES price for a `split` or `merge`, and the traded token's price for a `trade`. * `shares` is the number of shares on each side, in 6-decimal units. `"1500000000"` is 1,500 shares. * `parties` holds each counterparty's Deposit Wallet address as `maker`, with `signatureType` `3`. > [accordion] All Term Fields > > | Field | Notes | > | - | - | > | `marketId` | The Gamma market `id`. | > | `operation` | `split`, `merge`, or `trade`. See [Operations](#operations). | > | `token` | `trade` only: the outcome token that changes hands, `yes` or `no`. | > | `price` | The agreed price in (0, 1), with at most 6 decimals. For `split` and `merge` it is the YES price. For `trade` it is the price of the traded token. `price × shares` must be a whole number of base units, because it becomes the pUSD amount. | > | `shares` | The number of shares on each side, in 6-decimal units. `"1500000000"` is 1,500 shares. | > | `parties` | Keyed `yes` and `no` for `split` and `merge`, and `buyer` and `seller` for `trade`. | > | `priceTolerance` | Optional. Tightens the [price band](#price-band), such as `"0.05"` for ±5% of the mark. Pass the same value on every request for the trade. | > > Each party describes one counterparty's account: > > | Field | Notes | > | - | - | > | `maker` | The counterparty's Deposit Wallet address, which pays and receives for this side. The counterparty shares it with its session key. | > | `signatureType` | `3`, for a Deposit Wallet. Prepare refuses any other value. | > | `signer` | Optional, and best omitted. For a Deposit Wallet it defaults to, and must equal, `maker`. | > | `role` | Optional. `maker` or `taker`: the fee rate this side pays. Set it on both parties or on neither. Without it, the `yes` side of a `split` or `merge` and the `buyer` of a `trade` pay the taker rate. | **2. Validate the Terms** Next, optionally check the terms before anyone signs. Validate runs the market, price, account, and guardrail checks a submission would run, reports all of them, and stores nothing: ```bash theme={null} curl -X POST "https://external-rfq-partner.polymarket.com/v1/rfq-trades/validate" \ -H "Content-Type: application/json" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " \ --data '{ "marketId": "253591", "operation": "split", "price": "0.65", "shares": "1500000000", "parties": { "yes": { "maker": "", "signatureType": 3 }, "no": { "maker": "", "signatureType": 3 } } }' ``` Sign the request with the method `POST`, the path `/v1/rfq-trades/validate`, and the exact body you send. A completed validation returns `200`, even when a check fails. A `4xx` means the request itself was malformed. The response body reports every check: ```json theme={null} { "valid": false, "checks": { "market": { "status": "pass" }, "price": { "status": "pass", "band": { "mark": "0.62", "lower": "0.31", "upper": "0.93" } }, "parties": { "yes": { "status": "pass" }, "no": { "status": "fail", "reason": "insufficient_balance", "detail": "balance 12000000 < required …" } }, "guardrails": [ { "id": "taker_notional", "status": "pass" }, { "id": "price_deviation", "status": "pass" }, { "id": "transaction_notional", "status": "pass" }, { "id": "counterparty_notional", "status": "pass" } ] }, "checkedAt": "2026-07-24T12:34:56Z" } ``` Where: * `valid` is `true` when the market, both parties, and every guardrail pass, and the price check doesn't fail. `parties` is keyed like the request. * A check that could not run reports `"status": "missing"`. It is not a pass. A `missing` price check alone leaves `valid` unchanged, because the `price_deviation` [guardrail](#guardrails) decides whether a trade without a midpoint is blocked. * When the market check fails because the market can't be found, the other checks are left out of `checks`. * `price.band` is the band of the first order's token: YES for `split` and `merge`, the traded token for `trade`. Read both tokens' bands from the [price band request](#price-a-trade). * `guardrails` lists every [guardrail](#guardrails) with its result. * Each `reason` is listed under [Rejection Reasons](#rejection-reasons). The result is a point-in-time preview. Balances and bands keep moving, and the same checks run again when the trade is submitted. Signatures and session keys are checked only on submission. **3. Prepare the Orders** Then, send the same terms to prepare. Polymarket builds both unsigned orders, with fresh salts and timestamps, and the fee each side will pay: ```bash theme={null} curl -X POST "https://external-rfq-partner.polymarket.com/v1/rfq-trades/prepare" \ -H "Content-Type: application/json" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " \ --data '{ "marketId": "253591", "operation": "split", "price": "0.65", "shares": "1500000000", "parties": { "yes": { "maker": "", "signatureType": 3 }, "no": { "maker": "", "signatureType": 3 } } }' ``` Sign the request with the method `POST`, the path `/v1/rfq-trades/prepare`, and the exact body you send. The response body holds one prepared order per party, keyed like `parties`. This excerpt shows the `yes` order. `orders.no` has the same fields for the NO side: ```json theme={null} { "orders": { "yes": { "order": { "salt": "", "maker": "", "signer": "", "tokenId": "", "makerAmount": "975000000", "takerAmount": "1500000000", "side": 0, "signatureType": 3, "timestamp": "1784896496", "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", "builder": "" }, "typedData": { "primaryType": "TypedDataSign", "domain": { "name": "Polymarket CTF Exchange", "version": "3", "chainId": 137, "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" }, "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" } ], "TypedDataSign": [ { "name": "contents", "type": "Order" }, { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" }, { "name": "salt", "type": "bytes32" } ], "Order": [ { "name": "salt", "type": "uint256" }, { "name": "maker", "type": "address" }, { "name": "signer", "type": "address" }, { "name": "tokenId", "type": "uint256" }, { "name": "makerAmount", "type": "uint256" }, { "name": "takerAmount", "type": "uint256" }, { "name": "side", "type": "uint8" }, { "name": "signatureType", "type": "uint8" }, { "name": "timestamp", "type": "uint256" }, { "name": "metadata", "type": "bytes32" }, { "name": "builder", "type": "bytes32" } ] }, "message": { "contents": { "salt": "", "maker": "", "signer": "", "tokenId": "", "makerAmount": "975000000", "takerAmount": "1500000000", "side": 0, "signatureType": 3, "timestamp": "1784896496", "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", "builder": "" }, "name": "DepositWallet", "version": "1", "chainId": 137, "verifyingContract": "", "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" } }, "role": "taker", "digest": "", "signatureSuffix": "" } }, "fees": { "yes": "", "no": "" }, "expiresAt": "2026-07-24T12:44:56Z" } ``` Where: * `order` is the unsigned order. Submit it unchanged. * `typedData`, `digest`, and `signatureSuffix` are what the counterparty's session key signs in the next step. * `role` is the fee role the order was quoted under. Send it back with the order on submission. * `fees` is the fee each side will pay, in pUSD base units. * After `expiresAt`, about 10 minutes after the order timestamp, a submission of these orders is refused as `stale_order`. Prepare again and have both sides re-sign. Prepare also stamps the [builder code](/trading/place-orders#attach-your-builder-code) Polymarket configured for your platform on both orders. It refuses terms that fail the market, price band, or guardrail checks with `422`. It doesn't check accounts or funds, so the counterparties don't need to be funded yet. Each call returns new orders, so prepare again rather than retrying with the old ones. **4. Sign the Orders** Each side of the trade is authorized by its own counterparty, not by your platform. Sign each prepared order with the [session key](#session-keys) its counterparty gave you: 1. Sign the order's `typedData` exactly as returned, with `eth_signTypedData_v4` or an equivalent library call. The result is a 65-byte ECDSA signature that recovers to the session key over the returned `digest`. 2. Append the returned `signatureSuffix` to the 65-byte signature. 3. ABI-encode the session key's address (as `bytes32`), 32 zero bytes, and the signature from the previous step (as `bytes`), then append the 32-byte marker `0x6492…6492` (`6492` repeated 16 times). This envelope tells the Deposit Wallet which session key signed. ```typescript TypeScript theme={null} import { concat, encodeAbiParameters, pad, type Hex, type TypedDataDefinition, } from "viem"; import { privateKeyToAccount } from "viem/accounts"; const SESSION_SIGNER_MAGIC: Hex = `0x${"6492".repeat(16)}`; type PreparedOrder = { typedData: TypedDataDefinition; signatureSuffix: Hex; }; async function signPreparedOrder( sessionKey: Hex, prepared: PreparedOrder, ): Promise { const account = privateKeyToAccount(sessionKey); const rawSignature = await account.signTypedData(prepared.typedData); const inner = concat([rawSignature, prepared.signatureSuffix]); return concat([ encodeAbiParameters( [{ type: "bytes32" }, { type: "bytes32" }, { type: "bytes" }], [pad(account.address, { size: 32 }), pad("0x", { size: 32 }), inner], ), SESSION_SIGNER_MAGIC, ]); } ``` ```python Python theme={null} from eth_abi import encode from eth_account import Account from eth_account.messages import encode_typed_data SESSION_SIGNER_MAGIC = bytes.fromhex("6492" * 16) def sign_prepared_order(session_key: str, prepared: dict) -> str: account = Account.from_key(session_key) signed = account.sign_message( encode_typed_data(full_message=prepared["typedData"]) ) inner = signed.signature + bytes.fromhex(prepared["signatureSuffix"][2:]) signer_word = bytes(12) + bytes.fromhex(account.address[2:]) envelope = encode( ["bytes32", "bytes32", "bytes"], [signer_word, bytes(32), inner] ) return "0x" + (envelope + SESSION_SIGNER_MAGIC).hex() ``` The result is the order's `signature`. A signature that skips the suffix or the envelope, or that signs the plain `Order` instead of `typedData`, is refused as `invalid_order`. See [Signing Details](#signing-details) for the wrapper and its domains. **5. Submit the Trade** Next, submit both signed orders. Each order is the prepared `order`, unchanged, plus its `signature` and `role`. Set `idempotencyKey` to your own reference for the trade: ```bash theme={null} curl -X POST "https://external-rfq-partner.polymarket.com/v1/rfq-trades" \ -H "Content-Type: application/json" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " \ --data '{ "marketId": "253591", "idempotencyKey": "your-trade-ref-123", "orders": [ { "salt": "", "maker": "", "signer": "", "tokenId": "", "makerAmount": "975000000", "takerAmount": "1500000000", "side": 0, "signatureType": 3, "timestamp": "1784896496", "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", "builder": "", "signature": "", "role": "taker" }, { "salt": "", "maker": "", "signer": "", "tokenId": "", "makerAmount": "525000000", "takerAmount": "1500000000", "side": 0, "signatureType": 3, "timestamp": "1784896496", "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", "builder": "", "signature": "", "role": "maker" } ] }' ``` Sign the request with the method `POST`, the path `/v1/rfq-trades`, and the exact body you send. Where: * `idempotencyKey` is required: your own reference for the trade, up to 128 bytes. See [Idempotency](#idempotency). * `orders` holds exactly two signed orders, in any order. The operation and each side are derived from the orders' sides and token IDs. * `priceTolerance` is optional: the same value you validated and prepared with. Do not send fee amounts. Polymarket computes the fees, and a non-zero `takerFeeAmount` or `makerFeeAmount` is refused as `fee_not_accepted`. **6. Check the Response** Then, check the HTTP status. A `201 Created` response means the trade was accepted as `PENDING`. A `422` response means the trade was refused, and no trade was created: ```json Success theme={null} { "tradeId": "6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d", "status": "PENDING", "fees": { "yes": "", "no": "" }, "createdAt": "2026-07-24T12:34:56Z" } ``` ```json Failure theme={null} { "error": { "code": "validation_failed", "message": "stale_order (taker): order timestamp is 12m0s old (max 10m0s)", "retryable": false, "details": { "reason": "stale_order", "party": "taker" } } } ``` Keep the `tradeId` to track the trade. On a failure, `details.reason` is one of the [rejection reasons](#rejection-reasons). A `201` is not a fill: some checks run again just before execution. See [Acceptance Is Not Execution](#acceptance-is-not-execution). **7. Track the Trade** Finally, read the trade by its `tradeId` until it is final: ```bash theme={null} curl "https://external-rfq-partner.polymarket.com/v1/rfq-trades/6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " ``` Sign the request with the method `GET`, the path `/v1/rfq-trades/6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d`, and an empty body. The response body is the trade's current status, and the source of truth for its outcome: ```json theme={null} { "tradeId": "6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d", "idempotencyKey": "your-trade-ref-123", "status": "FILLED", "transactionHash": "", "createdAt": "2026-07-24T12:34:56Z", "filledAt": "2026-07-24T12:35:12Z" } ``` `status` is one of: | Status | Meaning | | - | - | | `PENDING` | Accepted and not yet final. `transactionHash` is set once the transaction is mined, before the fill is confirmed. | | `FILLED` | Executed on-chain. `transactionHash` and `filledAt` are set. | | `REJECTED` | Refused or failed. `failureReason` says why. The trade will not execute. | On `REJECTED`, `failureReason` is one of the [rejection reasons](#rejection-reasons), or an execution error code such as `execution_failed` when the trade could not execute. A trade ID that is unknown, or belongs to another partner, returns `404`. To avoid polling, open the [trade status stream](#trade-status-stream). ## Session Keys A session key is an ECDSA key pair that a counterparty authorizes for its Polymarket Deposit Wallet. The counterparty creates it on Polymarket with the `EXTERNAL_RFQ_INTEGRATION` scope and shares it with your platform, together with its Deposit Wallet address, which is the `maker` of its orders. Your platform then signs RFQ trades on the counterparty's behalf. The key is shown only once: to replace a lost key, the counterparty deletes it and creates a new one. See [Session Keys](/trading/session-keys) for how authorization works. * **Scoped to RFQ trades.** A key with only the `EXTERNAL_RFQ_INTEGRATION` scope cannot place CLOB orders, deposit, or withdraw. A signature from a key that isn't authorized for RFQ trades is refused as `invalid_order`. * **Revocable.** The counterparty can revoke the key at any time. A signature from a revoked or expired key is refused as `invalid_order`. * **Invisible in the order.** Both `maker` and `signer` are the Deposit Wallet address. The session key appears only inside the signature. ### Signing Details Deposit wallets verify signatures through ERC-1271 and expect Solady's ERC-7739 `TypedDataSign` wrapper: the order is bound to the wallet's own domain, nested under the exchange's domain. A plain order signature fails the wallet's `isValidSignature` check. > [accordion] The wrapper and its domains > > ```text theme={null} > Outer domain (the exchange): > name: "Polymarket CTF Exchange" > version: "3" for Polymarket V2 markets, "2" for CTF markets > chainId: 137 > verifyingContract: 0xe3333700cA9d93003F00f0F71f8515005F6c00Aa (Polymarket V2 markets) > 0xE111180000d2663C0091e4f400237545B87B996B (CTF markets) > 0xe2222d279d744050d28e00520010520000310F59 (CTF negRisk markets) > > Inner domain (the deposit wallet): > name: "DepositWallet" > version: "1" > chainId: 137 > verifyingContract: the maker's deposit wallet address > salt: 0x0000000000000000000000000000000000000000000000000000000000000000 > > Wrapper type: > TypedDataSign(Order contents,string name,string version,uint256 chainId, > address verifyingContract,bytes32 salt) > > Contents type: > Order(uint256 salt,address maker,address signer,uint256 tokenId, > uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType, > uint256 timestamp,bytes32 metadata,bytes32 builder) > > signatureSuffix: > exchangeDomainSeparator || contentsHash > || orderTypeString || uint16(len(orderTypeString)) > > Session-key envelope: > abi.encode(bytes32(sessionKeyAddress), bytes32(0), rawSignature || signatureSuffix) > || 0x6492649264926492649264926492649264926492649264926492649264926492 > ``` > > The market's `version` selects the outer domain, and for a CTF market its > `negRisk` flag selects the verifying contract. Prepare applies both, which is > why signing the returned `typedData` is the reliable path. ## Trade Submission ### Acceptance Is Not Execution A `201` means the trade was accepted for execution, not that it will fill. * **Checked at submission.** The request shape, the order rules and timestamps, the market's status, and the size [guardrails](#guardrails). A failure returns `422` and creates no trade. * **Checked just before execution.** Signatures, accounts and funds, the price band, the price guardrail, and a fresh market check. A failure ends the trade as `REJECTED` with a `failureReason`. Follow every trade to `FILLED` or `REJECTED`. To learn the verdict before anyone signs, validate first. Trades that share a counterparty wallet execute one at a time, so a trade can wait while an earlier trade on the same wallet settles. A trade that still can't execute about 10 minutes after submission, because it is queued or a dependency is down, ends `REJECTED` with `execution_failed`. ### Idempotency `idempotencyKey` is scoped to your platform, across all of its API keys. Submitting a key you have already used returns `201` for the original trade, with its current `status` and `transactionHash`, and the header `Idempotency-Replayed: true`. This makes a submission safe to retry after a timeout or a retryable error. Only the key identifies the trade, and the body is not compared on replay, so never reuse a key for a different trade. A submission refused with `422` creates no trade, so its key stays free. A trade that ends `REJECTED` keeps its key. ### Order Rules Prepared orders already follow these rules. If you build orders yourself instead of preparing them, follow them too. A broken rule is refused as `invalid_order` unless noted: * The two orders belong to different accounts. * `maker` and `signer` are both the Deposit Wallet address, and `signatureType` is `3`. * `salt` is a positive base-10 integer, used once per maker. A trade rejected by the checks just before execution frees its salts again. See [Rejection Reasons](#rejection-reasons). * `timestamp` is in Unix seconds. An order more than 10 minutes old is refused as `stale_order`, and one more than 1 minute in the future as `invalid_order`. * `metadata` is zero, and `makerAmount` and `takerAmount` are positive. * `builder` is your builder code, or zero if you don't have one. * `makerAmount` is what the order gives and `takerAmount` what it receives: a buy gives pUSD for shares, and a sell gives shares for pUSD. A buy's price is `makerAmount / takerAmount`, and a sell's is `takerAmount / makerAmount`. * For `split`, both orders buy the same number of shares, and their pUSD together covers at least those shares. For `merge`, both orders sell the same number of shares, and together ask for at most that much pUSD. * For `trade`, both orders carry the same token and are exact mirror images: the same shares and the same pUSD amount, at a price of at most 1. A pair that merely crosses is refused rather than settled at one side's price. For the order fields themselves, see [Place Orders](/trading/place-orders). ## Trade Status Stream To avoid polling, open the WebSocket at `wss://external-rfq-partner.polymarket.com/v1/ws/rfq-trades`, [authenticated on the upgrade request](/api-reference/rfq-trades/authentication#authenticate-the-websocket). On connect it sends one `trade_update` per trade still `PENDING`, then one each time a trade moves, such as when it is accepted, mined, filled, or rejected. Each frame carries the same object as the `GET`: ```json theme={null} { "type": "trade_update", "trade": { "tradeId": "6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d", "idempotencyKey": "your-trade-ref-123", "status": "FILLED", "transactionHash": "", "createdAt": "2026-07-24T12:34:56Z", "filledAt": "2026-07-24T12:35:12Z" } } ``` A frame can repeat a status you have already seen, and a trade's first frame can arrive before the submission's response. Match frames to your trades by `tradeId` or `idempotencyKey`. The stream is a latency optimization, not a ledger: delivery is lossy by design. A connection that falls behind drops frames without being closed, and a trade that finished while you were disconnected is not sent again. `GET` any trade that has stayed `PENDING` longer than you expect, and every trade you still hold as `PENDING` after a reconnect. For any trade whose outcome matters, the `GET` is the source of truth. The server pings every 45 seconds and closes a connection that hasn't answered within 60 seconds. ## Fees Email [blocks@polymarket.com](mailto:blocks@polymarket.com) for details on RFQ trade fees. ## Checks and Limits Every RFQ trade must pass the same checks: the market, the price, each counterparty's account, and a set of guardrails. Validate reports them without refusing anything, while prepare and submit refuse a trade that fails one. | Request | Checks run | When a check fails | | - | - | - | | Validate | All of them | `200` with `valid: false` and the failing check under `checks` | | Prepare | All except accounts and funds | `422` with `details.reason` set, or `details.field` for a malformed request | | Submit | All, in two stages | `422` for the checks that run at submission. A check that runs just before execution ends the trade `REJECTED` with `failureReason` set. See [Acceptance Is Not Execution](#acceptance-is-not-execution). | ### Market The market must be [tradable](#check-that-a-market-is-tradable) and at least 30 seconds from its end time. Otherwise the trade is refused as `market_not_tradable`. ### Price Band Each order's price must sit inside a band around the CLOB midpoint, its **mark**, of the outcome token that order prices: ```text theme={null} band = mark ± mark × T ``` `T` is `0.5` by default. Pass `priceTolerance` to tighten it, such as `"0.05"` for ±5% of the mark. A tolerance wider than the default is refused. Out of band, the trade is refused as `price_out_of_band`. Both orders are checked, each against its own token. For a `split` at `0.65`, the YES order is judged at `0.65` against the YES mark and the NO order at `0.35` against the NO mark. Because the band is relative, it is narrowest on the cheaper token, so price your quotes against both bands. [Price a Trade](#price-a-trade) shows how to read both tokens' current bands. When no midpoint can be read, the band's `source` is `unavailable` and its `mark`, `lower`, and `upper` are omitted. The band check then reports `missing` and does not block the trade, but a market that has no order book is refused as `price_mark_missing`. If the midpoint can't be read because the CLOB is unreachable, validate and prepare return `502`, and a submitted trade waits until it can be read. ### Accounts and Funds Each counterparty's account must: * Be a registered Polymarket account (`unknown_account`). * Not be restricted from trading (`account_restricted`). An account limited to closing positions can sell but not buy. * Pass sanctions screening, for both the account and the signing key (`ofac_blocked`). * Hold the funds for its side (`insufficient_balance`): pUSD for its `makerAmount` plus its fee for a buy, or the outcome tokens it sells for a sell. * Have approved the exchange contracts to spend those funds. On a CTF market the spender is the Standard Exchange, or the Neg Risk Exchange and Neg Risk Adapter for a `negRisk` market. On a Polymarket V2 market it is the Polymarket V2 Exchange, for both pUSD and PositionManager outcome tokens. See [Set Up Trading Approvals](/trading/wallets-auth#set-up-trading-approvals) for the approvals and contract addresses. Only a buyer's pUSD approval on a CTF market is checked ahead of execution (`insufficient_allowance`). A seller's missing outcome token approval, and any funding problem on a Polymarket V2 market, fail the trade at execution with an execution error such as `execution_failed`, so confirm both sides' approvals before you submit. ### Guardrails Every RFQ trade is also checked against guardrails, such as limits on its size and on how far its price sits from the midpoint. Email [blocks@polymarket.com](mailto:blocks@polymarket.com) for details on the guardrails that apply to your platform. ## Errors Every error uses one envelope: ```json theme={null} { "error": { "code": "validation_failed", "message": "stale_order (taker): order timestamp is 12m0s old (max 10m0s)", "retryable": false, "details": { "reason": "stale_order", "party": "taker" } } } ``` * `code` is the error class. Several HTTP statuses share one, as the table below shows. * `message` is human-readable, for logs. * `retryable` is `true` when the same request may be sent again as is. For a submission, retry with the same `idempotencyKey`. * `details.reason` is the machine-readable [rejection reason](#rejection-reasons), when the request was rejected. * `details.party` is the side at fault, by fee role (`taker` or `maker`), and `details.field` the request field at fault, such as `orders[0].salt`, when there is one. | HTTP | `code` | When | | - | - | - | | `400` | `validation_failed` | The body isn't valid JSON, has an unknown field or a value of the wrong type, or a path parameter is malformed. | | `401` | `authentication_failed` | Missing or invalid authentication. See [Authentication Errors](/api-reference/rfq-trades/authentication#authentication-errors). | | `404` | `not_found` | No such trade for your platform. Another partner's trade is a `404` too, never a `403`. | | `413` | `validation_failed` | The body is over 64 KiB. | | `422` | `validation_failed` | The request was rejected. `details.reason` says why, or only `details.field` is set when a required field is missing or invalid. | | `500` | `internal` | An unexpected server error. | | `502` | `dependency_unavailable` | A dependency failed. Retry when `retryable` is `true`. | | `503` | `dependency_unavailable` | WebSocket only: the stream is not available. Poll `GET /v1/rfq-trades/{tradeId}` instead. | A method and path pair that is not one of the API's requests is refused by Polymarket's edge network before it reaches the API, with `404` and a plain `{"error": "not found"}` body instead of the envelope. ### Rejection Reasons The same reasons appear in `details.reason`, in validate's `checks`, and in a rejected trade's `failureReason`. New reasons may be added, so treat an unknown one as a rejection. After a `422`, fix the request and submit again: no trade was created, so the same `idempotencyKey` still works. After a `REJECTED` trade, submit with a new `idempotencyKey`: reusing the rejected trade's key returns that trade. A trade rejected by the checks just before execution frees its orders' salts, so once the cause is fixed, such as a counterparty funding its account, the same signed orders can be submitted again until they are 10 minutes old. Otherwise, prepare again and have both sides re-sign. Until signed orders go stale, treat them as live even after their trade is rejected. | `reason` | Meaning | What to do | | - | - | - | | `invalid_order` | An order breaks a rule, its timestamp is in the future, or its signature does not verify. | Fix the order or prepare again, then sign again. | | `token_market_mismatch` | The orders' token IDs don't belong to the market or don't fit the operation. | Rebuild against the market's `positionIds` or `clobTokenIds`, or prepare again. | | `stale_order` | An order's timestamp is more than 10 minutes old. | Prepare again and have both sides re-sign. | | `fee_not_accepted` | The submission set its own fee amounts. | Omit `takerFeeAmount` and `makerFeeAmount`. | | `market_not_tradable` | The market doesn't exist, isn't tradable, or is too close to its end time. | Choose another market. | | `price_out_of_band` | A price is outside the [price band](#price-band). | Requote inside the band, prepare again, and re-sign. | | `price_deviation_exceeded` | A price is too far from its token's midpoint. | Requote closer to the midpoint. | | `price_mark_missing` | The market has no CLOB midpoint to check the price against. | Wait until the market has a two-sided order book. | | `taker_notional_below_minimum` | The taker's side is below the minimum trade size. | Increase the size. | | `transaction_notional_exceeded` | The trade is above the maximum trade size. | Reduce the size. | | `counterparty_notional_exceeded` | A wallet, or your platform, would pass its trading volume limit. | Reduce the size, or retry later. | | `unknown_account` | A `maker` is not a known Polymarket account. | The counterparty must create a Polymarket account first. | | `account_restricted` | A counterparty is restricted from trading. | Do not retry. | | `ofac_blocked` | A counterparty's account or signing key failed sanctions screening. | Do not retry. | | `insufficient_balance` | A buyer lacks the pUSD for its side plus its fee, or a seller lacks the outcome tokens it sells. | Retry after the account is funded. | | `insufficient_allowance` | A counterparty hasn't approved the exchange contracts to spend its funds. | Retry after the approvals are set. | | `dependency_unavailable` | A check could not reach a dependency. | Retry. | A rejected trade's `failureReason` can also be `execution_failed`, or another execution error code, when the trade could not execute: it waited about 10 minutes without executing, for example because its funds couldn't be held or a dependency was down, or the exchange refused the matched orders. Prepare again before retrying. ## API Reference Each request and response is generated from the API specification in the [Institutional API reference](/api-reference/rfq-trades/overview): | Request | Description | | - | - | | [`POST /v1/rfq-trades/validate`](/api-reference/rfq-trades/validate) | Run the checks without storing anything | | [`POST /v1/rfq-trades/prepare`](/api-reference/rfq-trades/prepare) | Build both unsigned orders and their fees | | [`POST /v1/rfq-trades`](/api-reference/rfq-trades/submit) | Submit both signed orders | | [`GET /v1/rfq-trades/{tradeId}`](/api-reference/rfq-trades/get-trade) | Read a trade's status | | [`WSS /v1/ws/rfq-trades`](/api-reference/wss/rfq-trades) | Stream status changes | | [`GET /v1/markets/{marketId}/price-band`](/api-reference/rfq-trades/price-band) | Read a market's price band | | [`GET /v1/time`](/api-reference/rfq-trades/server-time) | Read the server clock, with no authentication | # Account Management Source: https://docs.polymarket.com/perps/account-management Monitor balances, positions, and account history Use account reads to turn Perps activity into a reliable local view of account health, trading history, and performance. > [!NOTE] > > Owner account reads use an [authenticated > session](/perps/authenticated-sessions). Position snapshots also support > public reads. ## Review Account Health Start with the account's current collateral and exposure when showing portfolio health or checking whether a trade fits the account's risk state. ### Balances Use balances to show collateral by asset and account value. > [tab] TypeScript > > ```ts theme={null} > const balances = await session.fetchBalances(); > ``` > > Use this shape to render collateral balances and account value by asset. > > > [accordion] Output: PerpsBalance\[] > > > > ```ts PerpsBalance Type theme={null} > > type PerpsBalance = { > > asset: string; > > balance: string; > > value: string; > > }; > > > > type Output = PerpsBalance[]; > > ``` > > > > ```json PerpsBalance Example theme={null} > > [ > > { > > "asset": "pUSD", > > "balance": "1000", > > "value": "1000" > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > balances = await session.fetch_balances() > ``` > > Use this shape to render collateral balances and account value by asset. > > > [accordion] Output: tuple\[PerpsBalance, ...] > > > > ```json theme={null} > > [ > > { > > "asset": "pUSD", > > "balance": "1000", > > "value": "1000" > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/balances" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > Use this shape to render collateral balances and account value by asset. > > > [accordion] Output: Balances > > > > ```json theme={null} > > [ > > { > > "asset": "pUSD", > > "balance": "1000", > > "value": "1000" > > } > > ] > > ``` ### Portfolio Use the portfolio to show open positions, margin usage, withdrawable collateral, and liquidation state. > [tab] TypeScript > > ```ts theme={null} > const portfolio = await session.fetchPortfolio(); > ``` > > Use this shape to render positions, margin usage, and liquidation state. > > > [accordion] Output: PerpsPortfolio > > > > ```ts PerpsPortfolio Type theme={null} > > type PerpsPortfolio = { > > positions: Array<{ > > instrumentId: number; > > symbol: string; > > size: string; > > entryPrice: string; > > leverage: number; > > cross: boolean; > > initialMargin: string; > > maintenanceMargin: string; > > positionValue: string; > > liquidationPrice: string; > > unrealizedPnl: string; > > returnOnEquity: string; > > cumulativeFunding: string; > > adlIndex: 0 | 1 | 2 | 3; > > }>; > > margin: { > > totalAccountValue: string; > > availableOrderMargin: string; > > totalInitialMargin: string; > > totalMaintenanceMargin: string; > > totalPositionValue: string; > > }; > > withdrawable: string; > > inLiquidation: boolean; > > feeTier: number; > > timestamp: number; > > }; > > > > type Output = PerpsPortfolio; > > ``` > > > > ```json PerpsPortfolio Example theme={null} > > { > > "positions": [ > > { > > "instrumentId": 1, > > "symbol": "BTC-PERP", > > "size": "0.01", > > "entryPrice": "65000", > > "leverage": 5, > > "cross": false, > > "initialMargin": "130", > > "maintenanceMargin": "65", > > "positionValue": "650", > > "liquidationPrice": "52000", > > "unrealizedPnl": "0", > > "returnOnEquity": "0", > > "cumulativeFunding": "0", > > "adlIndex": 0 > > } > > ], > > "margin": { > > "totalAccountValue": "1000", > > "availableOrderMargin": "870", > > "totalInitialMargin": "130", > > "totalMaintenanceMargin": "65", > > "totalPositionValue": "650" > > }, > > "withdrawable": "870", > > "inLiquidation": false, > > "feeTier": 0, > > "timestamp": 1767000000000 > > } > > ``` > > `margin.availableOrderMargin` is the exact decimal amount available to margin > new orders after positions, open orders, and pending account operations. > `feeTier` is the zero-based index into the fee schedule's tiers. > `positions[].adlIndex` ranges from `0` to `3`. Higher values indicate higher > auto-deleveraging risk. The same fields appear in session `"portfolio"` events. > [tab] Python > > ```python theme={null} > portfolio = await session.fetch_portfolio() > ``` > > Use this shape to render positions, margin usage, and liquidation state. > > > [accordion] Output: PerpsPortfolio > > > > ```json theme={null} > > { > > "positions": [ > > { > > "instrument_id": 1, > > "symbol": "BTC-PERP", > > "size": "0.01", > > "entry_price": "65000", > > "leverage": 5, > > "cross": false, > > "initial_margin": "130", > > "maintenance_margin": "65", > > "position_value": "650", > > "liquidation_price": "52000", > > "unrealized_pnl": "0", > > "return_on_equity": "0", > > "cumulative_funding": "0", > > "adl_index": 0 > > } > > ], > > "margin": { > > "total_account_value": "1000", > > "available_order_margin": "870", > > "total_initial_margin": "130", > > "total_maintenance_margin": "65", > > "total_position_value": "650" > > }, > > "withdrawable": "870", > > "in_liquidation": false, > > "fee_tier": 0, > > "timestamp": "2025-12-29T09:20:00Z" > > } > > ``` > > `margin.available_order_margin` is a `Decimal` amount available to margin new > orders after positions, open orders, and pending account operations. > `fee_tier` is the zero-based index into the fee schedule's tiers. > `positions[].adl_index` ranges from `0` to `3`. Higher values indicate higher > auto-deleveraging risk. The same fields appear in session `"portfolio"` events. > The example serializes `Decimal` values as strings and the UTC `datetime` as ISO 8601. > [tab] API > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > Use this shape to render positions, margin usage, and liquidation state. > > > [accordion] Output: Portfolio > > > > ```json theme={null} > > { > > "positions": [ > > { > > "instrument_id": 1, > > "symbol": "BTC-PERP", > > "size": "0.01", > > "entry_price": "65000", > > "leverage": 5, > > "cross": false, > > "initial_margin": "130", > > "maintenance_margin": "65", > > "position_value": "650", > > "liquidation_price": "52000", > > "unrealized_pnl": "0", > > "return_on_equity": "0", > > "cumulative_funding": "0", > > "adl_index": 0 > > } > > ], > > "margin": { > > "total_account_value": "1000", > > "available_order_margin": "870", > > "total_initial_margin": "130", > > "total_maintenance_margin": "65", > > "total_position_value": "650" > > }, > > "withdrawable": "870", > > "in_liquidation": false, > > "fee_tier": 0, > > "timestamp": 1767000000000 > > } > > ``` > > `positions[].adl_index` ranges from `0` to `3`. Higher values indicate higher > auto-deleveraging risk. These fields are also present in private `portfolio` > WebSocket snapshots. > > `margin.available_order_margin` is the collateral available to margin new > orders, after existing positions, open orders, and any orders, isolated-margin > additions, withdrawals, or transfers still being processed. > > `fee_tier` is the account's current fee tier: a zero-based index into the > `tiers` of the fee schedule from [Trading Fees](/perps/trading#trading-fees). > Accounts without a current tier assignment report `0`. ### Account Stats Use account stats to review trailing 7-day trading activity such as volume and maker share. Stats are cached by UTC day and may be stale by up to 24 hours. See [Fee Metrics](/perps/learn-about-trading/fees#fee-metrics) for what each metric means. > [tab] TypeScript > > ```ts theme={null} > const stats = await session.fetchStats(); > ``` > > Use this shape to render trailing 7-day volume and maker-share activity. > > > [accordion] Output: PerpsAccountStats > > > > ```ts PerpsAccountStats Type theme={null} > > type PerpsAccountStats = { > > volume7d: string; > > takerVolume7d: string; > > makerVolume7d: string; > > accountMakerShare7d: string; > > entityMakerShare7d?: string; > > entityId?: number; > > entityName?: string; > > }; > > ``` > > > > ```json PerpsAccountStats Example theme={null} > > { > > "volume7d": "5000000", > > "takerVolume7d": "3500000", > > "makerVolume7d": "1500000", > > "accountMakerShare7d": "0.35", > > "entityMakerShare7d": "0.40", > > "entityId": 42, > > "entityName": "desk" > > } > > ``` > [tab] Python > > ```python theme={null} > stats = await session.fetch_stats() > ``` > > Use this shape to render trailing 7-day volume and maker-share activity. > > > [accordion] Output: PerpsAccountStats > > > > ```json theme={null} > > { > > "volume_7d": "5000000", > > "taker_volume_7d": "3500000", > > "maker_volume_7d": "1500000", > > "account_maker_share_7d": "0.35", > > "entity_maker_share_7d": "0.40", > > "entity_id": 42, > > "entity_name": "desk" > > } > > ``` > [tab] API > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/stats" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > Use this shape to render trailing 7-day volume and maker-share activity. > > > [accordion] Output: Account Stats > > > > ```json theme={null} > > { > > "volume_7d": "5000000", > > "taker_volume_7d": "3500000", > > "maker_volume_7d": "1500000", > > "account_maker_share_7d": "0.35", > > "entity_maker_share_7d": "0.40", > > "entity_id": 42, > > "entity_name": "desk" > > } > > ``` ## Reconcile Orders and Fills Use order state and fills to connect submitted orders with resting liquidity, executions, fees, and exposure changes. ### Open Orders Use open orders to show what is still resting on the book. > [tab] TypeScript > > ```ts theme={null} > const openOrders = await session.fetchOpenOrders({ > instrumentId: instrument.id, > }); > ``` > > Use this shape to render resting orders that can still fill or be canceled. > > > [accordion] Output: PerpsOrder\[] > > > > ```json theme={null} > > [ > > { > > "id": 1234567890, > > "instrumentId": 1, > > "buy": true, > > "price": "65000", > > "quantity": "0.01", > > "timeInForce": "gtc", > > "postOnly": false, > > "status": "open", > > "restingQuantity": "0.01", > > "filledQuantity": "0", > > "createdTimestamp": 1767000010000, > > "updatedTimestamp": 1767000010000 > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > open_orders = await session.fetch_open_orders( > instrument_id=instrument.id, > ) > ``` > > Use this shape to render resting orders that can still fill or be canceled. > > > [accordion] Output: tuple\[PerpsOrder, ...] > > > > ```json theme={null} > > [ > > { > > "id": 1234567890, > > "instrument_id": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "time_in_force": "gtc", > > "post_only": false, > > "status": "open", > > "resting_quantity": "0.01", > > "filled_quantity": "0", > > "created_at": 1767000010000, > > "updated_at": 1767000010000 > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/open-orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > Use this shape to render resting orders that can still fill or be canceled. > > > [accordion] Output: Open Orders > > > > ```json theme={null} > > [ > > { > > "order_id": 1234567890, > > "instrument_id": 1, > > "buy": true, > > "price": "65000", > > "quantity": "0.01", > > "tif": "gtc", > > "post_only": false, > > "ro": false, > > "status": "open", > > "resting_quantity": "0.01", > > "filled_quantity": "0", > > "created_timestamp": 1767000010000, > > "updated_timestamp": 1767000010000 > > } > > ] > > ``` ### Orders Use orders to inspect the latest known state for submitted orders. > [tab] TypeScript > > ```ts theme={null} > const orders = await session.fetchOrders({ > instrumentId: instrument.id, > }); > ``` > > Use this shape to reconcile submitted orders with their latest known state. > > > [accordion] Output: PerpsOrder\[] > > > > ```json theme={null} > > [ > > { > > "id": 1234567890, > > "instrumentId": 1, > > "buy": true, > > "price": "65000", > > "quantity": "0.01", > > "timeInForce": "ioc", > > "postOnly": false, > > "status": "filled", > > "restingQuantity": "0", > > "filledQuantity": "0.01", > > "createdTimestamp": 1767000010000, > > "updatedTimestamp": 1767000010500 > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > orders = await session.fetch_orders( > instrument_id=instrument.id, > ) > ``` > > Use this shape to reconcile submitted orders with their latest known state. > > > [accordion] Output: tuple\[PerpsOrder, ...] > > > > ```json theme={null} > > [ > > { > > "id": 1234567890, > > "instrument_id": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "time_in_force": "ioc", > > "post_only": false, > > "status": "filled", > > "resting_quantity": "0", > > "filled_quantity": "0.01", > > "created_at": 1767000010000, > > "updated_at": 1767000010500 > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > Use this shape to reconcile submitted orders with their latest known state. > > > [accordion] Output: Orders > > > > ```json theme={null} > > [ > > { > > "order_id": 1234567890, > > "instrument_id": 1, > > "buy": true, > > "price": "65000", > > "quantity": "0.01", > > "tif": "ioc", > > "post_only": false, > > "ro": false, > > "status": "filled", > > "resting_quantity": "0", > > "filled_quantity": "0.01", > > "created_timestamp": 1767000010000, > > "updated_timestamp": 1767000010500 > > } > > ] > > ``` ### Fills Use fills to reconcile executions, fees, realized PnL, and exposure changes. > [tab] TypeScript > > ```ts theme={null} > const pages = session.listFills({ > instrumentId: 1, > start: Date.now() - 24 * 60 * 60 * 1000, > end: Date.now(), > }); > > for await (const page of pages) { > // page.items: PerpsAccountFill[] > } > ``` > > Each page returns execution records you can use to reconcile fees, PnL, and exposure. > > > [accordion] Output: PerpsAccountFill\[] > > > > ```json theme={null} > > [ > > { > > "tradeId": 987654321, > > "orderId": 1234567890, > > "instrumentId": 1, > > "side": "long", > > "price": "65000", > > "quantity": "0.01", > > "taker": true, > > "fee": "0.26", > > "feeAsset": "pUSD", > > "previousSize": "0", > > "previousEntryPrice": "0", > > "pnl": "0", > > "liquidation": false, > > "adl": false, > > "settlement": false, > > "timestamp": 1767000010500, > > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > > } > > ] > > ``` > > `instrumentId` accepts an integer from `0` through `4294967295`. Omit it to read all > instruments. Keep the same filter while paging. `adl` identifies an > auto-deleveraging fill and is separate from the liquidation flag. > > For a backstop liquidation, the optional details object has this shape: > > ```json PerpsLiquidationDetails Example theme={null} > { > "mark": "65000.00", > "method": "backstop" > } > ``` > > When present, `liquidationDetails` contains `mark`, `method`, and an optional > `liquidatedUser` address. `mark` is the decimal string mark price captured when the > liquidation was issued. The fill's `price` remains its accounting execution > price. `method` is `"backstop"` or `"market"`. Only backstop fills currently > include these details. The same data is available in private fill updates. > > `settlement: true` identifies a position close at the final instrument-settlement > price. The same flag is available on each fill in a session `"fill"` event > payload; it defaults to `false` on older responses. > [tab] Python > > ```python theme={null} > from datetime import datetime, timedelta, timezone > > end = datetime.now(timezone.utc) > start = end - timedelta(days=1) > > pages = session.list_fills(instrument_id=1, start=start, end=end) > > async for page in pages: > # page.items: tuple[PerpsFill, ...] > pass > ``` > > Each page returns execution records you can use to reconcile fees, PnL, and exposure. > > > [accordion] Output: tuple\[PerpsFill, ...] > > > > ```json theme={null} > > [ > > { > > "trade_id": 987654321, > > "order_id": 1234567890, > > "instrument_id": 1, > > "side": "long", > > "price": "65000", > > "quantity": "0.01", > > "taker": true, > > "fee": "0.26", > > "fee_asset": "pUSD", > > "previous_size": "0", > > "previous_entry_price": "0", > > "pnl": "0", > > "liquidation": false, > > "adl": false, > > "settlement": false, > > "timestamp": "2025-12-29T09:20:10.500000Z", > > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > > } > > ] > > ``` > > `instrument_id` accepts an integer from `0` through `4294967295`. Omit it to read all > instruments. Keep the same filter while paging. `adl` identifies an > auto-deleveraging fill and is separate from the liquidation flag. > > For a backstop liquidation, the optional details object has this shape: > > ```json PerpsLiquidationDetails Example theme={null} > { > "mark": "65000.00", > "method": "backstop" > } > ``` > > When present, `liquidation_details` contains `mark`, `method`, and an optional > `liquidated_user` address. `mark` is the `Decimal` mark price captured when the > liquidation was issued. The fill's `price` remains its accounting execution > price. `method` is `"backstop"` or `"market"`. Only backstop fills currently > include these details. The same data is available in private fill updates. > > `settlement=True` identifies a position close at the final instrument-settlement > price. The same flag is available on each `PerpsFill` in a session `"fill"` event > payload; it defaults to `False` on older responses. Fill timestamps are UTC > `datetime` values; the JSON above shows their serialization. > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/fills" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "start_timestamp=1766913600000" \ > --data-urlencode "end_timestamp=1767000000000" \ > --data-urlencode "instrument_id=1" > ``` > > Use the response's `more` field to continue fetching older or newer records. > Pass `instrument_id` to narrow the pages to one instrument's fills. > > Each page returns execution records you can use to reconcile fees, PnL, and exposure. > > > [accordion] Output: Fills > > > > ```json theme={null} > > { > > "data": [ > > { > > "trade_id": 987654321, > > "order_id": 1234567890, > > "instrument_id": 1, > > "side": "long", > > "price": "65000", > > "quantity": "0.01", > > "taker": true, > > "fee": "0.26", > > "fee_asset": "pUSD", > > "previous_size": "0", > > "previous_entry_price": "0", > > "pnl": "0", > > "liquidation": false, > > "settlement": false, > > "adl": false, > > "timestamp": 1767000010500, > > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > > } > > ], > > "more": false > > } > > ``` > > `instrument_id` accepts an integer from `0` through `4294967295`. Omit it to read all > instruments. Keep the same filter while paging. `adl` identifies an > auto-deleveraging fill and is separate from the liquidation flag. > > For a backstop liquidation, the optional details object has this shape: > > ```json LiquidationDetails Example theme={null} > { > "mark": "65000.00", > "method": "backstop" > } > ``` > > When present, `liquidation_details` contains `mark`, `method`, and an optional > `liquidated_user` address. `mark` is the decimal string mark price captured when the > liquidation was issued. The fill's `price` remains its accounting execution > price. `method` is `"backstop"` or `"market"`. Only backstop fills currently > include these details. The same data is available in private fill updates. > > `settlement: true` identifies a position close at the final instrument-settlement > price. The same flag appears on each entry in `data` on the private `fills` > WebSocket channel. Settlement fills carry no fees or liquidation penalties. Reconcile them as position closures, separately from ordinary market executions and ADL. ## Inspect Position Snapshots Inspect a position now or immediately after a selected fill. Each snapshot covers one position cycle, from opening until the position becomes flat or changes side. Select up to 20 active instruments and 4 historical fills in one request, with at least one selection. Results keep the selection order within each group. > [tab] TypeScript > > Use the existing authenticated `session` to read your own positions. The example > selects instrument `1`; replace it with the instrument you want to inspect. > > ```ts theme={null} > import { PerpsPositionSnapshotStatus } from "@polymarket/client"; > > const snapshots = await session.fetchPositionSnapshots({ > activeInstrumentIds: [1], > }); > > for (const item of snapshots.active) { > if (item.status === PerpsPositionSnapshotStatus.Ok) { > console.log(item.snapshot.pnl, item.snapshot.leverage); > } > } > ``` > > > [accordion] Output: PerpsPositionSnapshots > > > > A successful active selection returns: > > > > ```json theme={null} > > { > > "historyAsOfAt": 1767000010500, > > "active": [ > > { > > "instrumentId": 1, > > "status": "ok", > > "snapshot": { > > "positionCycleId": "opaque:cycle", > > "side": "long", > > "startedAt": 1767000000000, > > "asOfAt": 1767000010500, > > "isClosed": false, > > "sizeAfter": "1", > > "entryPrice": "100", > > "asOfPrice": "110", > > "pnl": "10", > > "pnlPercent": "50", > > "leverage": 5, > > "chart": { > > "candles": [ > > { > > "position": 0, > > "open": 100, > > "high": 110, > > "low": 100, > > "close": 110 > > } > > ], > > "markers": [ > > { > > "position": 0, > > "kind": "increase" > > } > > ] > > } > > } > > } > > ], > > "history": [] > > } > > ``` > > > > For `Ok`, `snapshot` is a `PerpsPositionSnapshot`. Financial values such as `pnl` > > use `DecimalString`; timestamps are Unix milliseconds. `pnlPercent` and `leverage` > > can be `null`. > > To inspect the fill shown in the Fills example, add `historyFills`. Keep the > original decimal trade ID as a string; do not round it through a JavaScript number. > > ```ts theme={null} > import type { PerpsPositionSnapshotFill } from "@polymarket/client"; > > const fill: PerpsPositionSnapshotFill = { > instrumentId: 1, > tradeId: "987654321", > timestamp: 1767000010500, > }; > const historical = await session.fetchPositionSnapshots({ > historyFills: [fill], > }); > // historical.history preserves selection order and includes canonical string tradeId. > ``` > > For a public read, call `client.fetchPerpsPositionSnapshots({ address, > activeInstrumentIds: [1] })` with a `createPublicClient()` instance and the > registered account's address. This method does not add session credentials, > including when inherited by a secure client. > [tab] Python > > Use the existing authenticated `session` to read your own positions. The example > selects instrument `1`; replace it with the instrument you want to inspect. > > ```python theme={null} > snapshots = await session.fetch_position_snapshots(active_instrument_ids=(1,)) > > for item in snapshots.active: > if item.status == "ok": > print(item.snapshot.pnl, item.snapshot.leverage) > ``` > > > [accordion] Output: PerpsPositionSnapshots > > > > A successful active selection, serialized with > > `snapshots.model_dump(mode="json")`, returns: > > > > ```json theme={null} > > { > > "history_as_of_at": "2025-12-29T09:20:10.500000Z", > > "active": [ > > { > > "instrument_id": 1, > > "trade_id": null, > > "status": "ok", > > "snapshot": { > > "position_cycle_id": "opaque:cycle", > > "side": "long", > > "started_at": "2025-12-29T09:20:00Z", > > "as_of_at": "2025-12-29T09:20:10.500000Z", > > "is_closed": false, > > "size_after": "1", > > "entry_price": "100", > > "as_of_price": "110", > > "pnl": "10", > > "pnl_percent": "50", > > "leverage": 5, > > "chart": { > > "candles": [ > > { > > "position": 0.0, > > "open": 100.0, > > "high": 110.0, > > "low": 100.0, > > "close": 110.0 > > } > > ], > > "markers": [ > > { > > "position": 0.0, > > "kind": "increase" > > } > > ] > > } > > } > > } > > ], > > "history": [] > > } > > ``` > > > > For `status="ok"`, `snapshot` is a `PerpsPositionSnapshot`. Financial values such > > as `pnl` are `Decimal`; timestamps, including `history_as_of_at`, are UTC > > `datetime` values. `pnl_percent` and `leverage` can be `None`. > > To inspect the fill shown in the Fills example, select its instrument, decimal > trade ID, and original timestamp. `timestamp` accepts an aware `datetime` with > whole milliseconds or an integer Unix millisecond timestamp. > > ```python theme={null} > from polymarket import PerpsPositionSnapshotFill > > fill = PerpsPositionSnapshotFill( > instrument_id=1, > trade_id="987654321", > timestamp=1767000010500, > ) > historical = await session.fetch_position_snapshots(history_fills=(fill,)) > # historical.history preserves selection order and includes canonical string trade_id. > ``` > > For a public read, use > `await client.fetch_perps_position_snapshots(address=address, active_instrument_ids=(1,))` > with an `AsyncPublicClient` and the registered account's address. This method does > not add session credentials, including when inherited by an async secure client. > [tab] API > > Send a `POST` to `/v1/info/position-snapshots`. Supply your registered account > address and owner credentials for private leverage and PnL percentage. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/info/position-snapshots" \ > -H "Content-Type: application/json" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > -d '{"address":"","active_instrument_ids":[1]}' > ``` > > > [accordion] Output: Position Snapshots > > > > A successful active selection returns: > > > > ```json theme={null} > > { > > "history_as_of_at": 1767000010500, > > "active": [ > > { > > "instrument_id": 1, > > "status": "ok", > > "snapshot": { > > "position_cycle_id": "opaque:cycle", > > "side": "long", > > "started_at": 1767000000000, > > "as_of_at": 1767000010500, > > "is_closed": false, > > "size_after": "1", > > "entry_price": "100", > > "as_of_price": "110", > > "pnl": "10", > > "pnl_percent": "50", > > "leverage": 5, > > "chart": { > > "candles": [ > > { > > "position": 0, > > "open": 100, > > "high": 110, > > "low": 100, > > "close": 110 > > } > > ], > > "markers": [ > > { > > "position": 0, > > "kind": "increase" > > } > > ] > > } > > } > > } > > ], > > "history": [] > > } > > ``` > > > > Only `status: "ok"` includes `snapshot`. Financial values such as `pnl` are decimal > > strings; timestamps are Unix milliseconds. `pnl_percent` and `leverage` can be `null`. > > For historical selections, add `history_fills` containing `instrument_id`, > `trade_id` as a decimal string, and `timestamp` in Unix milliseconds. IDs can span > the full UInt64 range; returned IDs omit leading zeroes. Duplicate instruments or > fill identities and explicit `null` arrays return HTTP 400. Unknown accounts also > return HTTP 400. Each fill timestamp must be at most `18446744073709`. > > Omit both credential headers for a public read. Invalid supplied credentials > return HTTP 401; credentials for another account do not reveal the selected > account's private values. HTTP 503 indicates admission or shared dependency > failure; retry with backoff. ### Interpret a Snapshot While a cycle remains open, PnL is gross unrealized profit or loss on its remaining size. After it closes, PnL is the gross realized total for that cycle. Both exclude fees, funding, and previous cycles. A fill that closes or flips a position returns the closed cycle; the new cycle appears in the active selection or its later fills. Leverage and PnL percentage are visible only to the authenticated owner. Historical leverage uses the value captured at the selected fill and can remain unavailable. PnL percentage uses nominal entry margin, so it can differ from portfolio return on equity. Chart candles and markers use numeric coordinates and approximate prices; the selected minute's candle includes the whole minute's aggregate. ### Handle Unavailable Selections Only successful selections contain a snapshot. The completed-history horizon indicates how far the serving gateway has processed history; gateways can report different horizons. Handle each selection independently instead of discarding the whole batch when one selection is unavailable. | Status | Next Action | | - | - | | `ok` | Use the snapshot. | | `not_found` | No current position or owned fill was found within the reported horizon; check the selection and horizon. | | `history_pending` | Retry with backoff while history catches up or historical reconstruction becomes available. | | `history_limit` | The available reconstruction window does not include the cycle's opening fill. | | `resource_limit` | Reconstruction exceeded a row, memory, or chart bound. | | `temporarily_unavailable` | Retry with backoff after a deadline, pricing, or dependency failure. | | `unavailable` | The cycle cannot be reconstructed safely, for example after a self-match or an unsupported position adjustment. | Reconstruction limits and unsafe-accounting results are not signals to poll indefinitely. ## Reconcile Funding and Transfers Funding, deposits, and withdrawals explain collateral changes that did not come from order fills. Use [Fund Your Account](/perps/fund-your-account) for deposit and withdrawal submission workflows. ### Funding Payments Use funding payments to explain periodic funding debits or credits for a market. > [tab] TypeScript > > ```ts theme={null} > const fundingPayments = session.listFundingPayments({ > instrumentId: instrument.id, > }); > > for await (const page of fundingPayments) { > // page.items: PerpsAccountFundingPayment[] > } > ``` > > Each page returns funding records you can use to explain non-trade PnL changes. > Each record has a unique `id` for storing or deduplicating funding payments. > > > [accordion] Output: PerpsAccountFundingPayment\[] > > > > ```json theme={null} > > [ > > { > > "id": 3055723280187747, > > "instrumentId": 1, > > "size": "0.01", > > "fundingRate": "0.0001", > > "fundingAsset": "pUSD", > > "funding": "0.05", > > "timestamp": 1767000010000 > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > funding_payments = session.list_funding_payments( > instrument_id=instrument.id, > ) > > async for page in funding_payments: > # page.items: tuple[PerpsFundingPayment, ...] > pass > ``` > > Each page returns funding records you can use to explain non-trade PnL changes. > Each record has a unique `id` for storing or deduplicating funding payments. > > > [accordion] Output: tuple\[PerpsFundingPayment, ...] > > > > ```json theme={null} > > [ > > { > > "id": 3055723280187747, > > "instrument_id": 1, > > "size": "0.01", > > "funding_rate": "0.0001", > > "funding_asset": "pUSD", > > "funding": "0.05", > > "timestamp": 1767000010000 > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/funding" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" \ > --data-urlencode "start_timestamp=1766913600000" \ > --data-urlencode "end_timestamp=1767000000000" > ``` > > Use the response's `more` field to continue fetching older or newer records. > > Each page returns funding records you can use to explain non-trade PnL changes. > Each record has a unique `id` for storing or deduplicating funding payments. > > > [accordion] Output: Funding Payments > > > > ```json theme={null} > > { > > "data": [ > > { > > "id": 3055723280187747, > > "instrument_id": 1, > > "size": "0.01", > > "funding_rate": "0.0001", > > "funding_asset": "pUSD", > > "funding": "0.05", > > "timestamp": 1767000010000 > > } > > ], > > "more": false > > } > > ``` ### Deposits Use deposits to reconcile collateral added to the Perps account. > [tab] TypeScript > > ```ts theme={null} > const deposits = session.listDeposits(); > > for await (const page of deposits) { > // page.items: PerpsDeposit[] > } > ``` > > Each page returns deposits you can match against collateral arriving in the account. > > > [accordion] Output: PerpsDeposit\[] > > > > ```json theme={null} > > [ > > { > > "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", > > "asset": "pUSD", > > "amount": "100", > > "status": "confirmed", > > "from": "0x1234567890abcdef1234567890abcdef12345678", > > "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", > > "confirmations": 12, > > "requiredConfirmations": 12, > > "createdTimestamp": 1767000010000, > > "confirmedTimestamp": 1767000030000 > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > deposits = session.list_deposits() > > async for page in deposits: > # page.items: tuple[PerpsDeposit, ...] > pass > ``` > > Each page returns deposits you can match against collateral arriving in the account. > > > [accordion] Output: tuple\[PerpsDeposit, ...] > > > > ```json theme={null} > > [ > > { > > "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", > > "asset": "pUSD", > > "amount": "100", > > "status": "confirmed", > > "from_address": "0x1234567890abcdef1234567890abcdef12345678", > > "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", > > "confirmations": 12, > > "required_confirmations": 12, > > "created_at": 1767000010000, > > "confirmed_at": 1767000030000 > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/deposits" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "start_timestamp=1766913600000" \ > --data-urlencode "end_timestamp=1767000000000" > ``` > > Use the response's `more` field to continue fetching older or newer records. > > Each page returns deposits you can match against collateral arriving in the account. > > > [accordion] Output: Deposits > > > > ```json theme={null} > > { > > "data": [ > > { > > "hash": "0x2222222222222222222222222222222222222222222222222222222222222222", > > "asset": "pUSD", > > "amount": "100", > > "status": "confirmed", > > "from": "0x1234567890abcdef1234567890abcdef12345678", > > "to": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd", > > "confirmations": 12, > > "required_confirmations": 12, > > "created_timestamp": 1767000010000, > > "confirmed_timestamp": 1767000030000 > > } > > ], > > "more": false > > } > > ``` ### Withdrawals Use withdrawals to reconcile collateral leaving the Perps account. > [tab] TypeScript > > ```ts theme={null} > const withdrawals = session.listWithdrawals(); > > for await (const page of withdrawals) { > // page.items: PerpsWithdrawal[] > } > ``` > > Each page returns withdrawals you can match against collateral leaving the account. > > > [accordion] Output: PerpsWithdrawal\[] > > > > ```json theme={null} > > [ > > { > > "withdrawalId": 1234567891, > > "asset": "pUSD", > > "amount": "50", > > "fee": "1.5", > > "status": "confirmed", > > "to": "0x1234567890abcdef1234567890abcdef12345678", > > "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", > > "confirmations": 12, > > "requiredConfirmations": 12, > > "createdTimestamp": 1767000010000, > > "confirmedTimestamp": 1767000030000 > > } > > ] > > ``` > > Branch on `status` using the `PerpsKnownWithdrawalStatus` enum. > > | `status` | Meaning | > | - | - | > | `PerpsKnownWithdrawalStatus.Pending` | The withdrawal was accepted and is awaiting on-chain confirmation. | > | `PerpsKnownWithdrawalStatus.Confirmed` | The on-chain transaction reached the required confirmations and the funds were sent to the destination. | > | `PerpsKnownWithdrawalStatus.Removed` | A chain reorganization removed the on-chain transaction after it was observed. | > | `PerpsKnownWithdrawalStatus.Failed` | The withdrawal could not be executed on-chain and was reverted; the amount was credited back to the account. | > > The status set can grow between SDK releases. `status` is typed > `PerpsWithdrawalStatus`, so a status added after your release arrives as a > plain string instead of failing the response parse. > [tab] Python > > ```python theme={null} > withdrawals = session.list_withdrawals() > > async for page in withdrawals: > # page.items: tuple[PerpsWithdrawal, ...] > pass > ``` > > Each page returns withdrawals you can match against collateral leaving the account. > > > [accordion] Output: tuple\[PerpsWithdrawal, ...] > > > > ```json theme={null} > > [ > > { > > "withdrawal_id": 1234567891, > > "asset": "pUSD", > > "amount": "50", > > "fee": "1.5", > > "status": "confirmed", > > "to": "0x1234567890abcdef1234567890abcdef12345678", > > "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", > > "confirmations": 12, > > "required_confirmations": 12, > > "created_at": 1767000010000, > > "confirmed_at": 1767000030000 > > } > > ] > > ``` > > Branch on `status` using the `PerpsKnownWithdrawalStatus` literals. > > | `status` | Meaning | > | - | - | > | `"pending"` | The withdrawal was accepted and is awaiting on-chain confirmation. | > | `"confirmed"` | The on-chain transaction reached the required confirmations and the funds were sent to the destination. | > | `"removed"` | A chain reorganization removed the on-chain transaction after it was observed. | > | `"failed"` | The withdrawal could not be executed on-chain and was reverted; the amount was credited back to the account. | > > The status set can grow between SDK releases. `status` is typed > `PerpsWithdrawalStatus`, so a status added after your release arrives as a > plain string instead of failing validation. > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "start_timestamp=1766913600000" \ > --data-urlencode "end_timestamp=1767000000000" > ``` > > Use the response's `more` field to continue fetching older or newer records. > > Each page returns withdrawals you can match against collateral leaving the account. > > > [accordion] Output: Withdrawals > > > > ```json theme={null} > > { > > "data": [ > > { > > "withdrawal_id": 1234567891, > > "asset": "pUSD", > > "amount": "50", > > "fee": "1.5", > > "status": "confirmed", > > "to": "0x1234567890abcdef1234567890abcdef12345678", > > "hash": "0x3333333333333333333333333333333333333333333333333333333333333333", > > "confirmations": 12, > > "required_confirmations": 12, > > "created_timestamp": 1767000010000, > > "confirmed_timestamp": 1767000030000 > > } > > ], > > "more": false > > } > > ``` > > | `status` | Meaning | > | - | - | > | `pending` | The withdrawal was accepted and is awaiting on-chain confirmation. | > | `confirmed` | The on-chain transaction reached the required confirmations and the funds were sent to the destination. | > | `removed` | A chain reorganization removed the on-chain transaction after it was observed. | > | `failed` | The withdrawal could not be executed on-chain and was reverted; the amount was credited back to the account. | ## Track Equity and PnL Use equity and PnL history to explain how the account's value changed over time. ### Equity Use equity history to chart account value over time. Each point is the last equity sample in its `interval` bucket, stamped with that sample's own timestamp. A coarser interval lets each 1000-point page cover a longer window before `more` is set. > [tab] TypeScript > > ```ts theme={null} > const equity = session.listEquityHistory({ > interval: "1h", > start: Date.now() - 7 * 24 * 60 * 60 * 1000, > end: Date.now(), > }); > > for await (const page of equity) { > // page.items: PerpsEquityPoint[] > } > ``` > > Each page returns points you can plot as account equity over time. > > > [accordion] Output: PerpsEquityPoint\[] > > > > ```json theme={null} > > [ > > { > > "timestamp": 1767000000000, > > "equity": "1000" > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > from datetime import datetime, timedelta, timezone > > end = datetime.now(timezone.utc) > start = end - timedelta(days=7) > > equity = session.list_equity_history( > interval="1h", > start=start, > end=end, > ) > > async for page in equity: > # page.items: tuple[PerpsEquityPoint, ...] > pass > ``` > > Each page returns points you can plot as account equity over time. > > > [accordion] Output: tuple\[PerpsEquityPoint, ...] > > > > ```json theme={null} > > [ > > { > > "timestamp": 1767000000000, > > "equity": "1000" > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/equity" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "interval=1h" \ > --data-urlencode "start_timestamp=1766395200000" \ > --data-urlencode "end_timestamp=1767000000000" > ``` > > Use the response's `more` field to continue fetching older or newer records. > > Each page returns points you can plot as account equity over time. > > > [accordion] Output: Equity > > > > ```json theme={null} > > { > > "data": [[1767000000000, "1000"]], > > "more": false > > } > > ``` ### PnL Use PnL history to chart account profit and loss over the same interval. Each point is the PnL realized inside its `interval` bucket — not a running total — and buckets in which nothing was realized are omitted, so the series is sparse. > [tab] TypeScript > > ```ts theme={null} > const pnl = session.listPnlHistory({ > interval: "1h", > start: Date.now() - 7 * 24 * 60 * 60 * 1000, > end: Date.now(), > }); > > for await (const page of pnl) { > // page.items: PerpsPnlPoint[] > } > ``` > > Each page returns points you can plot as account PnL over time. > > > [accordion] Output: PerpsPnlPoint\[] > > > > ```json theme={null} > > [ > > { > > "timestamp": 1767000000000, > > "pnl": "12.5" > > } > > ] > > ``` > [tab] Python > > ```python theme={null} > from datetime import datetime, timedelta, timezone > > end = datetime.now(timezone.utc) > start = end - timedelta(days=7) > > pnl = session.list_pnl_history( > interval="1h", > start=start, > end=end, > ) > > async for page in pnl: > # page.items: tuple[PerpsPnlPoint, ...] > pass > ``` > > Each page returns points you can plot as account PnL over time. > > > [accordion] Output: tuple\[PerpsPnlPoint, ...] > > > > ```json theme={null} > > [ > > { > > "timestamp": 1767000000000, > > "pnl": "12.5" > > } > > ] > > ``` > [tab] API > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/pnl" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "interval=1h" \ > --data-urlencode "start_timestamp=1766395200000" \ > --data-urlencode "end_timestamp=1767000000000" > ``` > > Use the response's `more` field to continue fetching older or newer records. > > Each page returns points you can plot as account PnL over time. > > > [accordion] Output: PnL > > > > ```json theme={null} > > { > > "data": [[1767000000000, "12.5"]], > > "more": false > > } > > ``` # Authenticated Sessions Source: https://docs.polymarket.com/perps/authenticated-sessions Set up authenticated access for Perps trading and account data An authenticated session is a two-way authenticated communication channel with the Perps system that allows your app to place orders, read private Perps account data, and receive private real-time updates. ## Check Registration Check whether an address already has a Perps account before setting up private access. This lookup is public and does not create an account or credentials. > [tab] TypeScript > > Use `fetchPerpsRegistration()` on a `PublicClient` or `SecureClient`. This example > creates a public client and checks the account owner's address. > > ```ts theme={null} > import { createPublicClient } from "@polymarket/client"; > > const publicClient = createPublicClient(); > const registered = await publicClient.fetchPerpsRegistration({ > address: "0x1111111111111111111111111111111111111111", > }); > // registered: boolean > ``` > [tab] Python > > Use `fetch_perps_registration()` on an `AsyncPublicClient` or `AsyncSecureClient`. > This example creates a public client and checks the account owner's address. > > ```python theme={null} > from polymarket import AsyncPublicClient > > async with AsyncPublicClient() as public_client: > registered = await public_client.fetch_perps_registration( > address="0x1111111111111111111111111111111111111111" > ) > # registered: bool > ``` > [tab] API > > Send the account owner's address to the public registration endpoint. No > authentication headers are required. > > ```bash theme={null} > curl --get "https://api.perpetuals.polymarket.com/v1/info/registered" \ > --data-urlencode "address=0x1111111111111111111111111111111111111111" > ``` > > An example response for an address without a Perps account is: > > ```json theme={null} > { > "registered": false > } > ``` A positive result means the address has a Perps account. Registration is permanent. A negative result can be cached for up to ten seconds, so a newly registered account may not appear immediately. Registration alone does not confirm that credentials are valid or that the account has collateral available. ## Set Up Perps Access > [tab] TypeScript > > **1. Create a Secure Client** > > Create a `SecureClient` for the Polymarket wallet that owns the Perps account, > using the signer that controls it. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > }); > ``` > > > [!NOTE] > > > > This example uses Viem for wallet signing. See the [TypeScript tooling > > guide](/getting-started/typescript#wallet-integrations) for other wallet > > library integrations. > > **2. Open a Perps Session** > > Open a Perps session. By default, delegated Perps credentials expire after one > week. > > ```ts theme={null} > const session = await client.openPerpsSession(); > ``` > > You can also set the session lifetime and label explicitly. `expiresIn` is > measured in milliseconds. > > ```ts theme={null} > const session = await client.openPerpsSession({ > expiresIn: 7 * 24 * 60 * 60 * 1000, > label: "trading-app", > }); > ``` > [tab] Python > > **1. Create a Secure Client** > > Create an `AsyncSecureClient` for the Polymarket wallet that owns the Perps > account, using the signer that controls it. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > **2. Open a Perps Session** > > Open a Perps session. By default, delegated Perps credentials expire after one > week. > > ```python theme={null} > session = await client.open_perps_session() > ``` > > You can also set the session lifetime and label explicitly. `expires_in` is a > `timedelta`. > > ```python theme={null} > from datetime import timedelta > > session = await client.open_perps_session( > expires_in=timedelta(days=7), > label="trading-app", > ) > ``` > [tab] API > > Start by registering new proxy credentials for an existing Polymarket account. > If you do not have one yet, create an account at > [polymarket.com](https://polymarket.com) first. > > **1. Generate a Proxy Signer** > > Generate a fresh keypair for the proxy signer. Perps uses this key to authorize > trading operations on behalf of the Polymarket account signer, without requiring > the account signer to sign every order. > > Use any secure EVM key-generation flow. > > ```bash Foundry theme={null} > $ cast wallet new > Successfully created new keypair. > Address: > Private key: > ``` > > ```ts Viem theme={null} > import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; > > const privateKey = generatePrivateKey(); > const { address } = privateKeyToAccount(privateKey); > ``` > > Store the private key securely. It will be used to sign Perps trading operations > for the Polymarket account signer. > > **2. Create Proxy Typed Data** > > Create an EIP-712 `CreateProxy` payload. > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137 > }, > "primaryType": "CreateProxy", > "types": { > "CreateProxy": [ > { "name": "addr", "type": "address" }, > { "name": "exp", "type": "uint64" }, > { "name": "salt", "type": "uint64" }, > { "name": "ts", "type": "uint64" } > ] > }, > "message": { > "addr": "", > "exp": 1767225600000, > "salt": 123456789, > "ts": 1767000000000 > } > } > ``` > > Use these values consistently in the typed data and request body. > > | Field | Value | > | - | - | > | `addr` | `` from the previous step. | > | `exp` | Unix timestamp in milliseconds when the proxy signer stops being valid. | > | `ts` | Current Unix timestamp in milliseconds. | > | `salt` | Random integer generated for this signed request. | > > **3. Sign Proxy Typed Data** > > Sign the `CreateProxy` typed data with the signer for the Polymarket account. > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount(""); > > const signature = await account.signTypedData({ > domain: { > name: "Polymarket", > version: "1", > chainId: 137, > }, > primaryType: "CreateProxy", > types: { > CreateProxy: [ > { name: "addr", type: "address" }, > { name: "exp", type: "uint64" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > addr: "", > exp: 1767225600000, > salt: 123456789, > ts: 1767000000000, > }, > }); > ``` > > **4. Authorize the Proxy Signer** > > Authorize the generated proxy signer for your Perps account. > > ```bash theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/proxy" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "createProxy", > "args": { > "owner": "", > "proxy": "", > "expiry": 1767225600000 > } > }, > "sig": "", > "salt": 123456789, > "ts": 1767000000000, > "label": "trading-app" > }' > ``` > > Map the request fields to the values from the previous steps. > > * `owner` is the signer address for the Polymarket account. > * `proxy` is `` from the first step. > * `sig` is `` from the previous step. > * `salt` and `ts` are the same values used in the typed data from step 2. > * `label` is an identifier for this proxy credential instance. > > The response contains the proxy secret. > > ```json theme={null} > { > "secret": "" > } > ``` > > Store the proxy private key, proxy address, proxy secret, and expiry securely. ## Session Lifecycle Open an authenticated session to start trading, read private Perps account data, and receive private real-time updates. > [tab] TypeScript > > **1. Listen for Session Events** > > After opening a Perps session, iterate over it to receive private real-time > updates. > > ```ts theme={null} > const session = await client.openPerpsSession(); > > for await (const event of session) { > switch (event.type) { > case "order": > // Update local order state. > break; > > case "fill": > // Update position, PnL, or execution history. > break; > > case "portfolio": > // Refresh margin, equity, and position views. > break; > } > } > ``` > > This example handles a few common session events. `order` and `fill` are the > core trading updates, while `portfolio` provides periodic account-level snapshots > for margin, equity, positions, and withdrawable balance. > > See [Reconcile Trade State](/perps/trading#reconcile-trade-state) for how to use > these events to keep local trading state in sync. > > **2. Close the Session** > > You can close the session at any time by calling `session.close()`. Closing a > session releases local resources; stored credentials can still be resumed until > they expire. > > ```ts theme={null} > for await (const event of session) { > if (shouldCloseSession) { > await session.close(); > break; > } > > // … > } > ``` > [tab] Python > > **1. Listen for Session Events** > > After opening a Perps session, iterate over it to receive private real-time > updates. > > ```python theme={null} > session = await client.open_perps_session() > > async for event in session: > if event.type == "order": > # Update local order state. > pass > elif event.type == "fill": > # Update position, PnL, or execution history. > pass > elif event.type == "portfolio": > # Refresh margin, equity, and position views. > pass > ``` > > This example handles a few common session events. `order` and `fill` are the > core trading updates, while `portfolio` provides periodic account-level snapshots > for margin, equity, positions, and withdrawable balance. > > See [Reconcile Trade State](/perps/trading#reconcile-trade-state) for how to use > these events to keep local trading state in sync. > > **2. Close the Session** > > You can close the session at any time by calling `session.close()`. Closing a > session releases local resources; stored credentials can still be resumed until > they expire. > > ```python theme={null} > async for event in session: > if should_close_session: > await session.close() > break > > # … > ``` > [tab] API > > **1. Authenticate a WebSocket Connection** > > Connect to the Perps WebSocket production URL. > > ```text theme={null} > wss://ws.perpetuals.polymarket.com/v1/ws > ``` > > After the connection opens, send an authentication frame with the proxy address > and proxy secret. > > ```json theme={null} > { > "id": 1, > "req": "post", > "op": { > "type": "auth", > "args": { > "proxy": "", > "secret": "" > } > } > } > ``` > > Check the authentication response before subscribing to private channels. > > ```json Success theme={null} > { > "id": 1, > "data": { > "status": "ok", > "pod": "gateway-ws-7b68c9d4f5-m2n8p" > } > } > ``` > > ```json Failure theme={null} > { > "id": 1, > "data": { > "status": "err", > "error": "" > } > } > ``` > > A successful acknowledgement includes `pod`, the identity of the gateway pod > serving the connection. Record it with your connection logs so your activity > can be matched against exchange logs. It is correlation metadata only — pods > are not addressable, and a reconnect can land on a different pod. Treat the > field as optional: older pods omit it during a rolling deploy, and failures > never include it. > > **2. Handle Session Events** > > Authenticated WebSocket connections receive private session update frames. These > examples show a few common events: `orders` and `fills` for trading activity, > and `portfolio` for periodic account-level snapshots. > > ```json Order theme={null} > { > "ch": "orders", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": { > "oid": 1234567890, > "iid": 1, > "buy": true, > "p": "65000.00", > "qty": "0.01", > "tif": "gtc", > "po": false, > "status": "open", > "rest": "0.01", > "fill": "0", > "cts": 1767225600000, > "uts": 1767225600000 > } > } > ``` > > ```json Fill theme={null} > { > "ch": "fills", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567891, > "data": { > "tid": 987654321, > "oid": 1234567890, > "iid": 1, > "side": "long", > "p": "65000.00", > "qty": "0.01", > "taker": true, > "fee": "0.26", > "fea": "pUSD", > "psz": "0", > "pep": "0", > "pnl": "0", > "liq": false, > "adl": false, > "ts": 1767225600000 > } > } > ``` > > ```json Portfolio theme={null} > { > "ch": "portfolio", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567892, > "data": { > "positions": [], > "margin": { > "total_account_value": "10.00", > "available_order_margin": "10.00", > "total_initial_margin": "0", > "total_maintenance_margin": "0", > "total_position_value": "0" > }, > "withdrawable": "10.00", > "in_liquidation": false, > "fee_tier": 0, > "timestamp": 1767225600000 > } > } > ``` > > These are examples of common session events, not the full event list. > `ts` is the server send time. `ets` is the newest reflected event time, both in > Unix milliseconds. An `ets` of `0` means the event horizon is unknown. Use `sq` > for sequence-based reconciliation rather than treating send time as event order. > > **3. Keep the Connection Alive** > > Send an application-level ping from the client about every 25 seconds. > > ```json theme={null} > { > "id": 0, > "req": "post", > "op": { > "type": "ping" > } > } > ``` > > The server responds with a pong payload. > > ```json theme={null} > { > "id": 0, > "data": { > "status": "ok", > "ts": 1767225600000, > "sq": 1234567890 > } > } > ``` > > Treat the connection as stale if no messages arrive for about 65 seconds. > > **4. Close the Connection** > > Close the WebSocket connection when the current workflow is finished. Closing the > connection does not revoke the proxy credential. ## Resume a Session Resume a session when stored credentials are still valid and a Perps workflow needs to continue in a new runtime context. > [tab] TypeScript > > Read `session.credentials` after opening a session and store the object in secure > credential storage. > > ```ts theme={null} > const credentials = session.credentials; > // credentials: PerpsCredentials > ``` > > where `PerpsCredentials` is: > > ```ts PerpsCredentials Type theme={null} > type PerpsCredentials = { > proxy: EvmAddress; > privateKey: PrivateKey; > secret: string; > expiresAt: number; > }; > ``` > > ```json PerpsCredentials Example theme={null} > { > "proxy": "0x1111111111111111111111111111111111111111", > "privateKey": "0x2222222222222222222222222222222222222222222222222222222222222222", > "secret": "", > "expiresAt": 1766725200000 > } > ``` > > Pass stored credentials back to `openPerpsSession()` while they are still valid. > The SDK validates them and resumes the session. > > ```ts theme={null} > const session = await client.openPerpsSession({ > credentials, > }); > // session: PerpsSession > ``` > [tab] Python > > Read `session.credentials` after opening a session and store the object in secure > credential storage. > > ```python theme={null} > credentials = session.credentials > # credentials: PerpsCredentials > ``` > > where `PerpsCredentials` is: > > ```python PerpsCredentials Type theme={null} > from polymarket import PerpsCredentials > > # credentials: PerpsCredentials > ``` > > ```json PerpsCredentials Example theme={null} > { > "proxy": "0x1111111111111111111111111111111111111111", > "private_key": "0x2222222222222222222222222222222222222222222222222222222222222222", > "secret": "", > "expires_at": "2026-01-25T18:20:00Z" > } > ``` > > For JSON-backed storage, serialize the model and keep the result encrypted. > > ```python theme={null} > stored_credentials = credentials.model_dump(mode="json") > ``` > > Pass stored credentials back to `open_perps_session()` while they are still > valid. The SDK validates them and resumes the session. > > ```python theme={null} > from polymarket import PerpsCredentials > > credentials = PerpsCredentials.model_validate(stored_credentials) > > session = await client.open_perps_session(credentials=credentials) > # session: PerpsSession > ``` > [tab] API > > Resume an API session by reusing stored proxy credentials while they are still > valid. > > Store the credential material from the setup flow in secure credential storage. > > | Field | Use it to | > | - | - | > | `` | Identify the proxy credential. | > | `` | Sign Perps trading operations. | > | `` | Authenticate private REST and real-time access. | > | `expiry` | Know when to register a new proxy credential. | > > For private REST reads, pass the proxy address and proxy secret as headers. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > For a new WebSocket connection, send the same authentication frame used when the > session was opened. > > ```json theme={null} > { > "id": 1, > "req": "post", > "op": { > "type": "auth", > "args": { > "proxy": "", > "secret": "" > } > } > } > ``` > > If the credential has expired, register a new proxy credential before resuming > private workflows. # Builder Codes Source: https://docs.polymarket.com/perps/builder-codes Earn builder fees for routing orders and building new Polymarket Perps experiences Builder Attribution lets applications earn an additional fee for routing Perps orders with a fee explicitly approved by the trader. The **Builder** operates the application and receives the fee in its Perps account. The **Trader** places orders through that application and approves the Builder fee. ## Quickstart: Place an order with Builder Attribution Use the Trader's [funded Perps account](/perps/fund-your-account) and owner signer to approve the Builder fee once, then place attributed orders. Approval remains valid across sessions until revoked or replaced. Each Builder is identified by its Perps account address. The Builder and Trader must be different accounts. > [tab] TypeScript > > Use `createSecureClient()` from `@polymarket/client` with the Trader's owner > signer. This example uses Viem. See > [Wallet Integrations](/getting-started/typescript#wallet-integrations) for other > signer providers. Set `builderAddress` to the Builder's EVM account address and > `instrumentId` to the instrument selected in [Prepare a Trade](/perps/trading#prepare-a-trade). > > **1. Create a Secure Client** > > Create a `SecureClient` for the Trader. Set `POLYMARKET_WALLET_ADDRESS` to the > Polymarket wallet that owns the Perps account and `PRIVATE_KEY` to its owner's > signing key. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > }); > ``` > > **2. Open a Trader Session** > > Call `client.openPerpsSession()` with the Builder's account address: > > ```ts theme={null} > const session = await client.openPerpsSession({ > builderAttribution: builderAddress, > }); > ``` > > **3. Approve the Builder Fee** > > Call `session.approveBuilderFee` with an explicit `maxFeeRate` before the Trader's > first attributed order. Skip this step if the Trader already has an active approval: > > ```ts theme={null} > await session.approveBuilderFee({ maxFeeRate: "0.001" }); > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```ts PerpsBuilderApproval Type theme={null} > > type PerpsBuilderApproval = { > > trader: EvmAddress; > > builder: EvmAddress; > > maxFeeRate: DecimalString; // Zero revokes consent > > approvalVersion: number; > > timestamp: EpochMilliseconds; > > sequence: number; > > }; > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "maxFeeRate": "0.001", > > "approvalVersion": 1, > > "timestamp": 1767000000000, > > "sequence": 1234567889 > > } > > ``` > > **4. Place an Attributed Order** > > Call `session.placeOrder()` to submit an immediate-or-cancel buy using the > session's Builder: > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const result = await session.placeOrder({ > instrumentId, > side: OrderSide.BUY, > quantity: "0.01", > timeInForce: PerpsTimeInForce.IOC, > }); > ``` > > > [accordion] Output: PlacePerpsOrderResult > > > > ```ts PlacePerpsOrderResult Type theme={null} > > type PlacePerpsOrderResult = { > > order: PerpsOrder; > > }; > > > > type PerpsOrder = { > > id: PerpsOrderId; > > instrumentId: PerpsInstrumentId; > > side: OrderSide; > > price: DecimalString; > > quantity: DecimalString; > > timeInForce: PerpsTimeInForce; > > postOnly: boolean; > > reduceOnly: boolean; > > status: PerpsOrderStatus; > > restingQuantity: DecimalString; > > filledQuantity: DecimalString; > > createdTimestamp: EpochMilliseconds; > > updatedTimestamp: EpochMilliseconds; > > clientOrderId: string | undefined; > > tpSl: PerpsTpSlOrderFields | undefined; > > builder?: PerpsBuilderTerms; > > }; > > > > type PerpsBuilderTerms = { > > address: EvmAddress; > > feeRate: DecimalString; > > }; > > ``` > > > > ```json PlacePerpsOrderResult Example theme={null} > > { > > "order": { > > "id": 67890, > > "instrumentId": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "timeInForce": "ioc", > > "postOnly": false, > > "reduceOnly": false, > > "status": "filled", > > "restingQuantity": "0", > > "filledQuantity": "0.01", > > "createdTimestamp": 1767000010000, > > "updatedTimestamp": 1767000010000, > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "feeRate": "0.001" > > } > > } > > } > > ``` > > The session applies the same terms to single orders, batches, and generated > take-profit and stop-loss exits. Await approval before submitting orders that > should use its terms. > [tab] Python > > Use `AsyncSecureClient` from `polymarket-client` and run the examples inside an async > function. `builder_address` is your enabled Builder's account address. > `instrument_id` identifies the instrument selected in > [Prepare a Trade](/perps/trading#prepare-a-trade). > > **1. Create a Secure Client** > > Create an `AsyncSecureClient` for the Trader. Set `POLYMARKET_WALLET_ADDRESS` > to the Polymarket wallet that owns the Perps account and `PRIVATE_KEY` to its > owner's signing key. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > **2. Open a Trader Session** > > Call `client.open_perps_session()` with the Builder's account address: > > ```python theme={null} > session = await client.open_perps_session(builder_attribution=builder_address) > ``` > > **3. Approve the Builder Fee** > > Call `session.approve_builder_fee` with an explicit `max_fee_rate` before the Trader's > first attributed order. Skip this step if the Trader already has an active approval: > > ```python theme={null} > await session.approve_builder_fee(max_fee_rate="0.001") > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```python PerpsBuilderApproval Type theme={null} > > class PerpsBuilderApproval: > > trader: EvmAddress > > builder: EvmAddress > > max_fee_rate: Decimal # Zero revokes consent > > approval_version: int > > timestamp: datetime > > sequence: int > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "max_fee_rate": "0.001", > > "approval_version": 1, > > "timestamp": "2025-12-29T09:20:00Z", > > "sequence": 1234567889 > > } > > ``` > > **4. Place an Attributed Order** > > Call `session.place_order()` to submit an immediate-or-cancel buy using the > session's Builder: > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument_id, > side="BUY", > quantity="0.01", > time_in_force="ioc", > ) > ``` > > > [accordion] Output: PerpsOrderPlacement > > > > ```python PerpsOrderPlacement Type theme={null} > > class PerpsOrderPlacement: > > order: PerpsOrder > > tp_sl: PerpsPlacedTpSlOrders | None = None > > > > > > class PerpsOrder: > > id: PerpsOrderId > > instrument_id: PerpsInstrumentId > > side: OrderSide > > price: Decimal > > quantity: Decimal > > time_in_force: PerpsTimeInForce > > post_only: bool > > reduce_only: bool > > status: PerpsOrderStatus > > resting_quantity: Decimal > > filled_quantity: Decimal > > created_at: datetime > > updated_at: datetime > > client_order_id: str | None = None > > tp_sl: PerpsTpSlOrderFields | None = None > > builder: PerpsBuilderAttribution | None = None > > > > > > class PerpsBuilderAttribution: > > address: EvmAddress > > fee_rate: Decimal > > ``` > > > > ```json PerpsOrderPlacement Example theme={null} > > { > > "order": { > > "id": 67890, > > "instrument_id": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "time_in_force": "ioc", > > "post_only": false, > > "reduce_only": false, > > "status": "filled", > > "resting_quantity": "0", > > "filled_quantity": "0.01", > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "fee_rate": "0.001" > > }, > > "created_at": "2025-12-29T09:20:10Z", > > "updated_at": "2025-12-29T09:20:10Z" > > } > > } > > ``` > > The session applies the same terms to single orders, batches, and generated > take-profit and stop-loss exits. Await approval before submitting orders that > should use its terms. > [tab] API > > Use the account owner's signer for fee approval and a trading proxy for orders. > Set up proxy credentials through [Authenticated > Sessions](/perps/authenticated-sessions#set-up-perps-access) first. The examples > below use the same signing flow as [Place Orders](/perps/trading#place-orders). > > **1. Read the Saved Approval** > > Fetch the Trader's grant using its proxy credentials: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/builder-approvals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "builder=" > ``` > > ```ts BuilderApprovals Type theme={null} > type BuilderApprovals = { > data: Array<{ > trader: string; > builder: string; > max_fee_rate: string; > approval_version: number; > timestamp: number; > sequence: number; > }>; > }; > ``` > > ```json BuilderApprovals Example theme={null} > { > "data": [] > } > ``` > > The response's `data` array includes revoked grants. Use the saved > `approval_version` plus one, or `1` if no grant exists. > > **2. Build the Approval Operation** > > Read the Builder's configured fee for this approval: > > ```ts theme={null} > const builderAddress = "0x0000000000000000000000000000000000001234"; > const builderStatusResponse = await fetch( > `https://api.perpetuals.polymarket.com/v1/info/builder?address=${builderAddress}`, > ); > const builderStatus = await builderStatusResponse.json(); > const builderFeeRate = builderStatus.max_fee_rate; > ``` > > > [accordion] Output: BuilderStatus > > > > ```ts BuilderStatus Type theme={null} > > type BuilderStatus = { > > address: string; > > registered: boolean; > > enabled: boolean; > > admission_enabled: boolean; > > max_fee_rate: string; > > }; > > ``` > > > > ```json BuilderStatus Example theme={null} > > { > > "address": "0x0000000000000000000000000000000000001234", > > "registered": true, > > "enabled": true, > > "admission_enabled": true, > > "max_fee_rate": "0.001" > > } > > ``` > > Use `builderFeeRate` as `` below and the saved approval > version plus one as `approval_version`. This example uses `1` for the first > grant. The account owner signs these terms: > > ```json theme={null} > { > "type": "approveBuilder", > "args": { > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "", > "approval_version": 1 > } > } > ``` > > **3. Create the Approval Hash** > > MessagePack-encode the compact approval operation, then hash the bytes with > `keccak256`. This example uses `@msgpack/msgpack` and Viem: > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const approvalOperation = [ > "approveBuilder", > [builderAddress, builderFeeRate, 1], > ]; > const approvalHash = keccak256(encode(approvalOperation)); > ``` > > The address, rate, and version must match the structured operation above. > > **4. Create Approval Typed Data** > > Create an EIP-712 `Op` payload using the operation hash: > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137 > }, > "primaryType": "Op", > "types": { > "Op": [ > { > "name": "data", > "type": "bytes32" > }, > { > "name": "salt", > "type": "uint64" > }, > { > "name": "ts", > "type": "uint64" > } > ] > }, > "message": { > "data": "", > "salt": 123456789, > "ts": 1767000000000 > } > } > ``` > > Replace the sample `salt` with a fresh random integer and `ts` with the current > Unix timestamp in milliseconds. Use those same values when signing and submitting > the request. The production signing domain uses `chainId: 137`. > > **5. Sign Approval Typed Data** > > Sign with the account owner's key using Viem. Set `OWNER_PRIVATE_KEY` to that > key before running the example: > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount( > process.env.OWNER_PRIVATE_KEY as `0x${string}`, > ); > const approvalSignature = await account.signTypedData({ > domain: { name: "Polymarket", version: "1", chainId: 137 }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: approvalHash, > salt: 123456789n, > ts: 1767000000000n, > }, > }); > ``` > > **6. Submit the Approval** > > Submit the operation with `approvalSignature` as `` and the > same salt and timestamp used in the signed typed data: > > ```bash Request theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/builder-approvals" \ > -H "Content-Type: application/json" \ > -d '{ > "op": { > "type": "approveBuilder", > "args": { > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "", > "approval_version": 1 > } > }, > "sig": "", > "salt": 123456789, > "ts": 1767000000000 > }' > ``` > > ```ts BuilderApproval Type theme={null} > type BuilderApproval = { > trader: string; > builder: string; > max_fee_rate: string; > approval_version: number; > timestamp: number; > sequence: number; > }; > ``` > > ```json BuilderApproval Example theme={null} > { > "trader": "0x0000000000000000000000000000000000005678", > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "0.001", > "approval_version": 1, > "timestamp": 1767000000000, > "sequence": 1234567889 > } > ``` > > The response contains the committed `approval_version`, `max_fee_rate`, and > `sequence`. Check that its Builder, rate, and version match the request before > placing an order. If the result is unclear, read the saved grant before signing > a replacement. > > **7. Build the Order Operation** > > Choose an instrument, price, and quantity as shown in > [Prepare a Trade](/perps/trading#prepare-a-trade). This example places an > immediate-or-cancel buy with a limit price of `65000` and the Builder fee > approved above: > > ```json theme={null} > { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "ioc", > "po": false, > "c": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "" > } > } > ] > } > ``` > > **8. Create the Order Hash** > > Append the Builder tuple after the existing order fields, then omit undefined > optional entries before MessagePack encoding. Use the same values as the order > operation above: > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const signableOrder = [ > "createOrders", > [ > [ > 1, > true, > "65000", > "0.01", > "ioc", > false, > undefined, // ro > "7f9e4a2b6c8d0e1f1234567890abcdef", > undefined, // tr > undefined, // gtt > [builderAddress, builderFeeRate], > ].filter((value) => value !== undefined), > ], > ]; > const orderHash = keccak256(encode(signableOrder)); > ``` > > **9. Create Order Typed Data** > > Create an EIP-712 `Op` payload using the operation hash: > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137 > }, > "primaryType": "Op", > "types": { > "Op": [ > { > "name": "data", > "type": "bytes32" > }, > { > "name": "salt", > "type": "uint64" > }, > { > "name": "ts", > "type": "uint64" > } > ] > }, > "message": { > "data": "", > "salt": 234567890, > "ts": 1767000010000 > } > } > ``` > > Replace the sample `salt` with a fresh random integer and `ts` with the current > Unix timestamp in milliseconds. Use those same values when signing and submitting > the request. The production signing domain uses `chainId: 137`. > > **10. Sign Order Typed Data** > > Sign with the trading proxy's key using Viem. Set `PROXY_PRIVATE_KEY` to that > key before running the example: > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount( > process.env.PROXY_PRIVATE_KEY as `0x${string}`, > ); > const orderSignature = await account.signTypedData({ > domain: { name: "Polymarket", version: "1", chainId: 137 }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: orderHash, > salt: 234567890n, > ts: 1767000010000n, > }, > }); > ``` > > **11. Submit the Order** > > Submit `orderSignature` as ``, keeping the operation, salt, and > timestamp identical to the signed values: > > ```bash Request theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "Content-Type: application/json" \ > -d '{ > "op": { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "ioc", > "po": false, > "c": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "" > } > } > ] > }, > "sig": "", > "salt": 234567890, > "ts": 1767000010000 > }' > ``` > > ```ts OrderResponse Type theme={null} > type OrderResponse = { > status: "ok"; > oid: number; > coid?: string; > builder?: { > address: string; > fee_rate: string; > }; > } | { > status: "err"; > error: string; > oid?: number; > coid?: string; > }; > ``` > > ```json OrderResponse Example theme={null} > [ > { > "status": "ok", > "oid": 67890, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "0.001" > } > } > ] > ``` > > Check each result in the response array. `status: "ok"` confirms acceptance and > `oid` identifies the order. `status: "err"` includes the rejection in `error`. > Acceptance does not confirm execution. > > **12. Check the Order State** > > Use the returned `oid` to read the order with the Trader's proxy credentials: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "order_id=" > ``` > > ```ts OrderData Type theme={null} > type OrderData = { > order_id: number; > instrument_id: number; > buy: boolean; > price: string; > quantity: string; > tif: "gtc" | "ioc" | "fok"; > post_only: boolean; > ro: boolean; > resting_quantity: string; > filled_quantity: string; > status: string; > created_timestamp: number; > updated_timestamp: number; > client_order_id?: string; > tpsl?: { > kind: "tp" | "sl"; > scope: "order" | "position"; > trp: string; > parent_oid?: number; > armed_qty?: string; > slip_bps?: number; > }; > builder?: { > address: string; > fee_rate: string; > }; > }; > ``` > > ```json OrderData Example theme={null} > [ > { > "order_id": 67890, > "instrument_id": 1, > "buy": true, > "price": "65000", > "quantity": "0.01", > "tif": "ioc", > "post_only": false, > "ro": false, > "status": "filled", > "resting_quantity": "0", > "filled_quantity": "0.01", > "created_timestamp": 1767000010000, > "updated_timestamp": 1767000010000, > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "0.001" > } > } > ] > ``` > > Read `status`, `filled_quantity`, and `resting_quantity` to determine the > execution outcome. Full order reads include the saved `builder` terms. > If the snapshot is not available yet, retry the read or follow private order > updates through [Authenticated Sessions](/perps/authenticated-sessions#session-lifecycle). ## Trader Operations Read and manage the Trader's consent, place attributed orders, and inspect the fees charged on executions. ### Fetch Trader Approval Check whether the Trader has already approved a Builder and the maximum fee they accepted. Read the saved approval before asking for consent again. A revoked approval remains in the account's history with a zero fee limit. > [tab] TypeScript > > Call `session.fetchBuilderApprovals()` on the Trader's existing `PerpsSession`, > filtering by the Builder's account address: > > ```ts theme={null} > const approvals = await session.fetchBuilderApprovals({ > builder: builderAddress, > }); > const approval = approvals[0]; > ``` > > > [accordion] Output: PerpsBuilderApproval\[] > > > > ```ts PerpsBuilderApproval Type theme={null} > > type PerpsBuilderApproval = { > > trader: EvmAddress; > > builder: EvmAddress; > > maxFeeRate: DecimalString; // Zero revokes consent > > approvalVersion: number; > > timestamp: EpochMilliseconds; > > sequence: number; > > }; > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > [ > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "maxFeeRate": "0.001", > > "approvalVersion": 1, > > "timestamp": 1767000000000, > > "sequence": 1234567889 > > } > > ] > > ``` > > An empty array means the Trader has no saved approval for this Builder. > Otherwise, `approval.maxFeeRate` is the approved fee limit as a decimal string. > Zero means consent was revoked. Compare the intended Builder fee with this > limit to decide whether to request approval. `approval.approvalVersion` is the > saved version, including after revocation. > > Omit the `builder` filter to fetch all of the Trader's saved Builder approvals. > [tab] Python > > Call `session.fetch_builder_approvals()` on the Trader's existing `PerpsSession`, > filtering by the Builder's account address: > > ```python theme={null} > approvals = await session.fetch_builder_approvals(builder=builder_address) > approval = approvals[0] if approvals else None > ``` > > > [accordion] Output: tuple\[PerpsBuilderApproval, …] > > > > ```python PerpsBuilderApproval Type theme={null} > > class PerpsBuilderApproval: > > trader: EvmAddress > > builder: EvmAddress > > max_fee_rate: Decimal # Zero revokes consent > > approval_version: int > > timestamp: datetime > > sequence: int > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > [ > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "max_fee_rate": "0.001", > > "approval_version": 1, > > "timestamp": "2025-12-29T09:20:00Z", > > "sequence": 1234567889 > > } > > ] > > ``` > > An empty tuple means the Trader has no saved approval for this Builder. > Otherwise, `approval.max_fee_rate` is the approved fee limit as a `Decimal`. > Zero means consent was revoked. Compare the intended Builder fee with this > limit to decide whether to request approval. `approval.approval_version` is the > saved version, including after revocation. > > Omit the `builder` filter to fetch all of the Trader's saved Builder approvals. > [tab] API > > Fetch the Trader's saved approval for the Builder using the Trader's proxy > credentials: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/builder-approvals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "builder=" > ``` > > ```ts BuilderApprovals Type theme={null} > type BuilderApprovals = { > data: Array<{ > trader: string; > builder: string; > max_fee_rate: string; > approval_version: number; > timestamp: number; > sequence: number; > }>; > }; > ``` > > ```json BuilderApprovals Example theme={null} > { > "data": [ > { > "trader": "0x0000000000000000000000000000000000005678", > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "0.001", > "approval_version": 1, > "timestamp": 1767000000000, > "sequence": 1234567889 > } > ] > } > ``` > > An empty `data` array means the Trader has no saved approval for this Builder. > Otherwise, `max_fee_rate` is the approved fee limit. `"0"` means consent was > revoked. Compare the intended `builder.fee_rate` with this limit to decide > whether to request approval. `approval_version` is the saved version, including > after revocation. Omit the `builder` query parameter to fetch all saved Builder > approvals for the authenticated Trader. > > Check whether the Builder can currently receive attributed orders: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/builder" \ > --data-urlencode "address=" > ``` > > ```ts BuilderStatus Type theme={null} > type BuilderStatus = { > address: string; > registered: boolean; > enabled: boolean; > admission_enabled: boolean; > max_fee_rate: string; > }; > ``` > > ```json BuilderStatus Example theme={null} > { > "address": "0x0000000000000000000000000000000000001234", > "registered": true, > "enabled": true, > "admission_enabled": true, > "max_fee_rate": "0.001" > } > ``` > > Require `registered`, `enabled`, and `admission_enabled` to be `true`. The order's > `builder.fee_rate` must be covered by both the Builder's current configuration > and the Trader's positive approval. Fetching these values does not create or > change consent. The server validates them again when it receives an order. ### Grant Approval Approve the Builder fee once before placing attributed orders. Existing approval remains valid across sessions until revoked or replaced. To approve a changed Builder fee, grant approval again. > [!WARNING] > > The maximum Builder fee is currently 10 basis points (0.1%). This limit may > change in the future. > [tab] TypeScript > > Call `session.approveBuilderFee` on a Trader session opened with > `builderAttribution`. Pass the maximum fee the Trader agrees to authorize: > > ```ts theme={null} > await session.approveBuilderFee({ maxFeeRate: "0.001" }); > ``` > > `maxFeeRate` is required and has no default. This example approves 10 basis points > (0.1%). To select a Builder when the session has none, or approve a different > Builder, also pass its address: > > ```ts theme={null} > await session.approveBuilderFee({ > builderAddress, > maxFeeRate: "0.001", > }); > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```ts PerpsBuilderApproval Type theme={null} > > type PerpsBuilderApproval = { > > trader: EvmAddress; > > builder: EvmAddress; > > maxFeeRate: DecimalString; // Zero revokes consent > > approvalVersion: number; > > timestamp: EpochMilliseconds; > > sequence: number; > > }; > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "maxFeeRate": "0.001", > > "approvalVersion": 1, > > "timestamp": 1767000000000, > > "sequence": 1234567889 > > } > > ``` > > After confirmation, the session refreshes the Builder cap and uses the lower of > that cap and the approved maximum for new orders. > [tab] Python > > Call `session.approve_builder_fee` on a Trader session opened with > `builder_attribution`. Pass the maximum fee the Trader agrees to authorize: > > ```python theme={null} > await session.approve_builder_fee(max_fee_rate="0.001") > ``` > > `max_fee_rate` is required and has no default. This example approves 10 basis points > (0.1%). To select a Builder when the session has none, or approve a different > Builder, also pass its address: > > ```python theme={null} > await session.approve_builder_fee( > builder_address=builder_address, > max_fee_rate="0.001", > ) > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```python PerpsBuilderApproval Type theme={null} > > class PerpsBuilderApproval: > > trader: EvmAddress > > builder: EvmAddress > > max_fee_rate: Decimal # Zero revokes consent > > approval_version: int > > timestamp: datetime > > sequence: int > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "max_fee_rate": "0.001", > > "approval_version": 1, > > "timestamp": "2025-12-29T09:20:00Z", > > "sequence": 1234567889 > > } > > ``` > > After confirmation, the session refreshes the Builder cap and uses the lower of > that cap and the approved maximum for new orders. > [tab] API > > Use the owner-signed `approveBuilder` operation shown in the approval workflow > above. Read the saved grant first and set `approval_version` to its current > version plus one, or `1` for the first grant. Sign and submit the same Builder > address, fee, and version. ### Revoke Approval Revoke permission for new attributed orders. Existing accepted orders, including pending conditional orders, retain their saved fees. Cancel those orders to prevent further charges. > [tab] TypeScript > > Call `session.revokeBuilderFee()` with the Builder's account address: > > ```ts theme={null} > await session.revokeBuilderFee(builderAddress); > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```ts PerpsBuilderApproval Type theme={null} > > type PerpsBuilderApproval = { > > trader: EvmAddress; > > builder: EvmAddress; > > maxFeeRate: DecimalString; // Zero revokes consent > > approvalVersion: number; > > timestamp: EpochMilliseconds; > > sequence: number; > > }; > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "maxFeeRate": "0", > > "approvalVersion": 2, > > "timestamp": 1767000030000, > > "sequence": 1234567891 > > } > > ``` > [tab] Python > > Call `session.revoke_builder_fee()` with the Builder's account address: > > ```python theme={null} > await session.revoke_builder_fee(builder_address) > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```python PerpsBuilderApproval Type theme={null} > > class PerpsBuilderApproval: > > trader: EvmAddress > > builder: EvmAddress > > max_fee_rate: Decimal # Zero revokes consent > > approval_version: int > > timestamp: datetime > > sequence: int > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "max_fee_rate": "0", > > "approval_version": 2, > > "timestamp": "2025-12-29T09:20:30Z", > > "sequence": 1234567891 > > } > > ``` > [tab] API > > Use the Trader account owner's signer to replace the saved approval with a > zero maximum rate. > > **1. Read the Current Version** > > Fetch the latest grant, including its retained version if already revoked: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/builder-approvals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "builder=" > ``` > > ```ts BuilderApprovals Type theme={null} > type BuilderApprovals = { > data: Array<{ > trader: string; > builder: string; > max_fee_rate: string; > approval_version: number; > timestamp: number; > sequence: number; > }>; > }; > ``` > > ```json BuilderApprovals Example theme={null} > { > "data": [ > { > "trader": "0x0000000000000000000000000000000000005678", > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "0.001", > "approval_version": 1, > "timestamp": 1767000000000, > "sequence": 1234567889 > } > ] > } > ``` > > Use the returned `approval_version` plus one in the next step. The example uses `2` for a grant whose current version is `1`. > > **2. Create the Revocation Hash** > > Set the rate to `"0"` and use the next saved version. Hash the compact operation: > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const revocationOperation = [ > "approveBuilder", > ["0x0000000000000000000000000000000000001234", "0", 2], > ]; > const revocationHash = keccak256(encode(revocationOperation)); > ``` > > **3. Create Revocation Typed Data** > > Use the same EIP-712 `Op` structure shown in the approval workflow. Set `data` > to `revocationHash` and generate a new random salt and current Unix-millisecond > timestamp. The next examples use sample values that you must replace in both > the signature and the request. > > **4. Sign Revocation Typed Data** > > Sign with the account owner's key using Viem. Set `OWNER_PRIVATE_KEY` to that > key before running the example: > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount( > process.env.OWNER_PRIVATE_KEY as `0x${string}`, > ); > const revocationSignature = await account.signTypedData({ > domain: { name: "Polymarket", version: "1", chainId: 137 }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: revocationHash, > salt: 456789012n, > ts: 1767000030000n, > }, > }); > ``` > > **5. Submit the Revocation** > > Submit `revocationSignature` as `` with the matching > operation, salt, and timestamp: > > ```bash Request theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/builder-approvals" \ > -H "Content-Type: application/json" \ > -d '{ > "op": { > "type": "approveBuilder", > "args": { > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "0", > "approval_version": 2 > } > }, > "sig": "", > "salt": 456789012, > "ts": 1767000030000 > }' > ``` > > ```ts BuilderApproval Type theme={null} > type BuilderApproval = { > trader: string; > builder: string; > max_fee_rate: string; > approval_version: number; > timestamp: number; > sequence: number; > }; > ``` > > ```json BuilderApproval Example theme={null} > { > "trader": "0x0000000000000000000000000000000000005678", > "builder": "0x0000000000000000000000000000000000001234", > "max_fee_rate": "0", > "approval_version": 2, > "timestamp": 1767000030000, > "sequence": 1234567891 > } > ``` > > Existing orders, including pending conditional orders, keep their saved fees. > Cancel them to prevent further charges. > > Check that the response has `max_fee_rate: "0"` and the version you submitted. > Stale or replayed versions are rejected. If the result is unclear, read the > saved grant before signing another update. ### Place Orders The Trader must have granted fee approval for the Builder before submitting attributed orders. The order's Builder fee must be covered by that approval. These examples place an immediate-or-cancel buy using an existing trading session or signed order. > [tab] TypeScript > > Call `session.placeOrder()` on the Trader's existing `PerpsSession`, opened > with `builderAttribution`. The session uses the selected Builder and its saved > approved fee. Set `instrumentId` to the instrument you want to trade: > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const result = await session.placeOrder({ > instrumentId, > side: OrderSide.BUY, > quantity: "0.01", > timeInForce: PerpsTimeInForce.IOC, > }); > ``` > > > [accordion] Output: PlacePerpsOrderResult > > > > ```ts PlacePerpsOrderResult Type theme={null} > > type PlacePerpsOrderResult = { > > order: PerpsOrder; > > }; > > > > type PerpsOrder = { > > id: PerpsOrderId; > > instrumentId: PerpsInstrumentId; > > side: OrderSide; > > price: DecimalString; > > quantity: DecimalString; > > timeInForce: PerpsTimeInForce; > > postOnly: boolean; > > reduceOnly: boolean; > > status: PerpsOrderStatus; > > restingQuantity: DecimalString; > > filledQuantity: DecimalString; > > createdTimestamp: EpochMilliseconds; > > updatedTimestamp: EpochMilliseconds; > > clientOrderId: string | undefined; > > tpSl: PerpsTpSlOrderFields | undefined; > > builder?: PerpsBuilderTerms; > > }; > > > > type PerpsBuilderTerms = { > > address: EvmAddress; > > feeRate: DecimalString; > > }; > > ``` > > > > ```json PlacePerpsOrderResult Example theme={null} > > { > > "order": { > > "id": 67890, > > "instrumentId": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "timeInForce": "ioc", > > "postOnly": false, > > "reduceOnly": false, > > "status": "filled", > > "restingQuantity": "0", > > "filledQuantity": "0.01", > > "createdTimestamp": 1767000010000, > > "updatedTimestamp": 1767000010000, > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "feeRate": "0.001" > > } > > } > > } > > ``` > [tab] Python > > Call `session.place_order()` on the Trader's existing `PerpsSession`, opened > with `builder_attribution`. The session uses the selected Builder and its saved > approved fee. Set `instrument_id` to the instrument you want to trade: > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument_id, > side="BUY", > quantity="0.01", > time_in_force="ioc", > ) > ``` > > > [accordion] Output: PerpsOrderPlacement > > > > ```python PerpsOrderPlacement Type theme={null} > > class PerpsOrderPlacement: > > order: PerpsOrder > > tp_sl: PerpsPlacedTpSlOrders | None = None > > > > > > class PerpsOrder: > > id: PerpsOrderId > > instrument_id: PerpsInstrumentId > > side: OrderSide > > price: Decimal > > quantity: Decimal > > time_in_force: PerpsTimeInForce > > post_only: bool > > reduce_only: bool > > status: PerpsOrderStatus > > resting_quantity: Decimal > > filled_quantity: Decimal > > created_at: datetime > > updated_at: datetime > > client_order_id: str | None = None > > tp_sl: PerpsTpSlOrderFields | None = None > > builder: PerpsBuilderAttribution | None = None > > > > > > class PerpsBuilderAttribution: > > address: EvmAddress > > fee_rate: Decimal > > ``` > > > > ```json PerpsOrderPlacement Example theme={null} > > { > > "order": { > > "id": 67890, > > "instrument_id": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "time_in_force": "ioc", > > "post_only": false, > > "reduce_only": false, > > "status": "filled", > > "resting_quantity": "0", > > "filled_quantity": "0.01", > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "fee_rate": "0.001" > > }, > > "created_at": "2025-12-29T09:20:10Z", > > "updated_at": "2025-12-29T09:20:10Z" > > } > > } > > ``` > [tab] API > > Submit a signed `createOrders` operation with the Builder's account address and > an approved `fee_rate`. Use the order hashing and trading-proxy signing steps > from the quickstart above. Replace the sample salt and timestamp with fresh > values, then submit the exact operation, salt, and timestamp that you signed: > > ```bash Request theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "Content-Type: application/json" \ > -d '{ > "op": { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "ioc", > "po": false, > "c": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "" > } > } > ] > }, > "sig": "", > "salt": 234567890, > "ts": 1767000010000 > }' > ``` > > ```ts OrderResponse Type theme={null} > type OrderResponse = { > status: "ok"; > oid: number; > coid?: string; > builder?: { > address: string; > fee_rate: string; > }; > } | { > status: "err"; > error: string; > oid?: number; > coid?: string; > }; > ``` > > ```json OrderResponse Example theme={null} > [ > { > "status": "ok", > "oid": 67890, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "0.001" > } > } > ] > ``` > > Check each result in the response array. `status: "ok"` confirms acceptance and > `oid` identifies the order. `status: "err"` includes the rejection in `error`. > Acceptance does not confirm execution. Read the order state or follow private > order updates to determine the execution outcome. ### Display Trader Fees Show the total fee charged for each execution, with exchange and Builder fees as the breakdown. A maker rebate can make the total negative. Do not clamp it to zero. > [tab] TypeScript > > Read fills with `session.listFills()` on the Trader's `PerpsSession`: > > ```ts theme={null} > const pages = session.listFills(); > const page = await pages.firstPage(); > const fills = page.items; > ``` > > Each item in `fills` has this shape. Use `totalFee` to display the total charge. > > > [accordion] Output: PerpsAccountFill > > > > ```ts PerpsAccountFill Type theme={null} > > type PerpsAccountFill = { > > tradeId: PerpsTradeId; > > orderId: PerpsOrderId; > > instrumentId: PerpsInstrumentId; > > side: PerpsSide; // long or short > > price: DecimalString; > > quantity: DecimalString; > > taker: boolean; > > fee: DecimalString; // Exchange fee; negative for a maker rebate > > builderFee: DecimalString; // Non-negative Builder fee > > totalFee: DecimalString; // fee + builderFee; may be negative > > builder?: PerpsBuilderTerms; > > feeAsset: string; // Asset in which all three fees are charged > > previousSize: DecimalString; > > previousEntryPrice: DecimalString; > > pnl: DecimalString; > > liquidation: boolean; > > timestamp: EpochMilliseconds; > > hash: TxHash | undefined; > > }; > > > > type PerpsBuilderTerms = { > > address: EvmAddress; > > feeRate: DecimalString; > > }; > > ``` > > > > ```json PerpsAccountFill Example theme={null} > > { > > "tradeId": 12345, > > "orderId": 67890, > > "instrumentId": 1, > > "side": "long", > > "price": "65000", > > "quantity": "0.01", > > "taker": true, > > "fee": "0.26", > > "builderFee": "0.65", > > "totalFee": "0.91", > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "feeRate": "0.001" > > }, > > "feeAsset": "pUSD", > > "previousSize": "0", > > "previousEntryPrice": "0", > > "pnl": "0", > > "liquidation": false, > > "timestamp": 1767000010000 > > } > > ``` > > Private session fill events expose the same fee fields. > [tab] Python > > Read fills with `session.list_fills()` on the Trader's `PerpsSession`: > > ```python theme={null} > pages = session.list_fills() > page = await pages.first_page() > fills = page.items > ``` > > Each item in `fills` has this shape. Use `total_fee` to display the total charge. > > > [accordion] Output: PerpsFill > > > > ```python PerpsFill Type theme={null} > > class PerpsFill: > > trade_id: PerpsTradeId > > order_id: PerpsOrderId > > instrument_id: PerpsInstrumentId > > side: PerpsSide # long or short > > price: Decimal > > quantity: Decimal > > taker: bool > > fee: Decimal # Exchange fee; negative for a maker rebate > > builder_fee: Decimal # Non-negative Builder fee > > total_fee: Decimal # fee + builder_fee; may be negative > > builder: PerpsBuilderAttribution | None = None > > fee_asset: str # Asset in which all three fees are charged > > previous_size: Decimal > > previous_entry_price: Decimal > > pnl: Decimal > > liquidation: bool > > timestamp: datetime > > hash: str | None = None > > client_order_id: str | None = None > > > > > > class PerpsBuilderAttribution: > > address: EvmAddress > > fee_rate: Decimal > > ``` > > > > ```json PerpsFill Example theme={null} > > { > > "trade_id": 12345, > > "order_id": 67890, > > "instrument_id": 1, > > "side": "long", > > "price": "65000", > > "quantity": "0.01", > > "taker": true, > > "fee": "0.26", > > "builder_fee": "0.65", > > "total_fee": "0.91", > > "builder": { > > "address": "0x0000000000000000000000000000000000001234", > > "fee_rate": "0.001" > > }, > > "fee_asset": "pUSD", > > "previous_size": "0", > > "previous_entry_price": "0", > > "pnl": "0", > > "liquidation": false, > > "timestamp": "2025-12-29T09:20:10Z", > > "hash": null > > } > > ``` > > Private session fill events expose the same fee fields. > [tab] API > > Fetch the Trader's fills with authenticated account access: > > ```bash Request theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/fills" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > ```ts AccountTrades Type theme={null} > type AccountTrades = { > data: Array<{ > trade_id: number; > order_id: number; > instrument_id: number; > side: "long" | "short"; > price: string; > quantity: string; > taker: boolean; > fee: string; // Exchange fee; negative for a maker rebate > fee_asset: string; // Asset in which the fees are charged > previous_size: string; > previous_entry_price: string; > pnl: string; > liquidation: boolean; > adl: boolean; > timestamp: number; > hash: TxHash | undefined; > builder_fee: string; // Non-negative Builder fee > total_fee: string; // fee + builder_fee; may be negative > builder?: { > address: string; > fee_rate: string; > }; > }>; > more: boolean; > cursor?: string; > }; > ``` > > ```json AccountTrades Example theme={null} > { > "data": [ > { > "trade_id": 12345, > "order_id": 67890, > "instrument_id": 1, > "side": "long", > "price": "65000", > "quantity": "0.01", > "taker": true, > "fee": "0.26", > "builder_fee": "0.65", > "total_fee": "0.91", > "fee_asset": "pUSD", > "previous_size": "0", > "previous_entry_price": "0", > "pnl": "0", > "timestamp": 1767000010000, > "liquidation": false, > "adl": false, > "hash": "0x", > "builder": { > "address": "0x0000000000000000000000000000000000001234", > "fee_rate": "0.001" > } > } > ], > "more": false > } > ``` > > Private WebSocket fills use the same fee amount fields and `fea` for the fee asset. #### Rounding and PnL Builder fees apply to eligible maker and taker executions, including voluntary closes. Forced liquidation legs, backstop transfers, and automatic deleveraging are excluded. An ordinary trading counterparty can still pay its saved fee. | Case | Accounting Rule | | - | - | | One execution | Round the Builder fee down to the fee asset's precision: six decimal places for pUSD. | | Multiple executions | Add the individually rounded fees. Two fees of 0.0000019 pUSD produce a total charge of 0.000002 pUSD. Discarded fractions do not carry forward. | | Account net PnL and main PnL leaderboard | Both fee components are already included. Do not subtract them again. | | Raw fill PnL and biggest-win rankings | Values remain before fees. | The [exchange fee schedule](/perps/learn-about-trading/fees) applies separately. Builder fees do not change exchange-fee arithmetic or the precision of fee rates. ## Builder Operations ### Check Builder Availability Check whether a Builder can receive attributed orders. > [tab] TypeScript > > Call `client.fetchPerpsBuilderStatus()` on an existing `SecureClient`. Set > `builderAddress` to the Builder's Perps account address: > > ```ts theme={null} > const status = await client.fetchPerpsBuilderStatus({ > address: builderAddress, > }); > > if (!status.registered || !status.enabled || !status.admissionEnabled) { > throw new Error("Builder fees are unavailable for this account"); > } > ``` > > > [accordion] Output: PerpsBuilderStatus > > > > ```ts PerpsBuilderStatus Type theme={null} > > type PerpsBuilderStatus = { > > address: EvmAddress; > > registered: boolean; > > enabled: boolean; > > admissionEnabled: boolean; > > maxFeeRate: DecimalString; > > }; > > ``` > > > > ```json PerpsBuilderStatus Example theme={null} > > { > > "address": "0x0000000000000000000000000000000000001234", > > "registered": true, > > "enabled": true, > > "admissionEnabled": true, > > "maxFeeRate": "0.001" > > } > > ``` > [tab] Python > > Call `client.fetch_perps_builder_status()` on an existing `AsyncSecureClient`. > Set `builder_address` to the Builder's Perps account address: > > ```python theme={null} > status = await client.fetch_perps_builder_status(address=builder_address) > > if not (status.registered and status.enabled and status.admission_enabled): > raise RuntimeError("Builder fees are unavailable for this account") > ``` > > > [accordion] Output: PerpsBuilderStatus > > > > ```python PerpsBuilderStatus Type theme={null} > > class PerpsBuilderStatus: > > address: EvmAddress > > registered: bool > > enabled: bool > > admission_enabled: bool > > max_fee_rate: Decimal > > ``` > > > > ```json PerpsBuilderStatus Example theme={null} > > { > > "address": "0x0000000000000000000000000000000000001234", > > "registered": true, > > "enabled": true, > > "admission_enabled": true, > > "max_fee_rate": "0.001" > > } > > ``` > [tab] API > > Fetch the Builder's status: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/builder" \ > --data-urlencode "address=" > ``` > > ```ts BuilderStatus Type theme={null} > type BuilderStatus = { > address: string; > registered: boolean; > enabled: boolean; > admission_enabled: boolean; > max_fee_rate: string; > }; > ``` > > ```json BuilderStatus Example theme={null} > { > "address": "0x0000000000000000000000000000000000001234", > "registered": true, > "enabled": true, > "admission_enabled": true, > "max_fee_rate": "0.001" > } > ``` > > The Builder is available when `registered`, `enabled`, and `admission_enabled` > are `true`. ### Reconcile Builder Earnings Builders receive their full additional fee immediately in their Perps account. The credit can be used as collateral or withdrawn under the usual account rules. Earnings history reports settled activity. Use the account balance to determine spendable funds. Authenticate as the Builder account for reporting. The Trader's session used above cannot read another account's earnings. > [tab] TypeScript > > Use `fetchBuilderEarningsSummary()` and `listBuilderEarnings()` on a > `PerpsSession` opened by the Builder's `SecureClient`. Here, `builderSession` > is that session, created through [Authenticated > Sessions](/perps/authenticated-sessions#set-up-perps-access). > > ```ts theme={null} > import type { PerpsBuilderEarning } from "@polymarket/client"; > > const summary = await builderSession.fetchBuilderEarningsSummary(); > const pages = builderSession.listBuilderEarnings(summary.snapshot); > const receipts: PerpsBuilderEarning[] = []; > > for await (const page of pages) { > receipts.push(...page.items); > } > ``` > > `summary.snapshot` fixes `start`, `end`, and `asOfSequence` so every page matches > the summary. To select a window, pass `start` and `end` as Unix milliseconds to > `fetchBuilderEarningsSummary()`. Use `earningId` to deduplicate receipts. > > > [accordion] Output: PerpsBuilderEarning > > > > ```ts PerpsBuilderEarning Type theme={null} > > type PerpsBuilderEarning = { > > earningId: PerpsBuilderEarningId; > > tradeId: PerpsTradeId; > > orderId: PerpsOrderId; > > instrumentId: PerpsInstrumentId; > > trader: EvmAddress; // Main account address > > side: OrderSide; // "BUY" or "SELL" > > liquidityRole: PerpsLiquidityRole; // "maker" or "taker" > > price: DecimalString; > > quantity: DecimalString; > > clientOrderId?: PerpsClientOrderId; > > timestamp: EpochMilliseconds; > > sequence: number; > > notional: DecimalString; > > feeAsset: string; > > fee: DecimalString; // Signed exchange fee in feeAsset > > builderFee: DecimalString; // Non-negative builder fee in feeAsset > > totalFee: DecimalString; // fee + builderFee > > feeRate: DecimalString; // Saved builder rate as a decimal fraction > > }; > > ``` > > > > ```json PerpsBuilderEarning Example theme={null} > > { > > "earningId": "3:12345:1", > > "tradeId": 12345, > > "orderId": 67890, > > "instrumentId": 3, > > "trader": "0x0000000000000000000000000000000000005678", > > "side": "BUY", > > "liquidityRole": "taker", > > "price": "100", > > "quantity": "1", > > "clientOrderId": "7f9e4a2b6c8d0e1f1234567890abcdef", > > "timestamp": 1767000010000, > > "sequence": 1234567890, > > "notional": "100", > > "feeAsset": "pUSD", > > "fee": "0.04", > > "builderFee": "0.1", > > "totalFee": "0.14", > > "feeRate": "0.001" > > } > > ``` > > > [accordion] Output: PerpsBuilderEarningsSummary > > > > ```ts PerpsBuilderEarningsSummary Type theme={null} > > type PerpsBuilderEarningsSummary = { > > assets: PerpsBuilderEarningsAsset[]; > > traderCount: number; // Distinct traders with attributed fills in the snapshot > > activeApprovalCount: number; // Current positive, unrevoked grants, independent of the snapshot > > snapshot: PerpsBuilderEarningsSnapshot; > > }; > > > > type PerpsBuilderEarningsAsset = { > > feeAsset: string; > > fillCount: number; > > notional: DecimalString; > > builderFee: DecimalString; > > }; > > > > type PerpsBuilderEarningsSnapshot = { > > start: EpochMilliseconds; > > end: EpochMilliseconds; > > asOfSequence: number; > > }; > > ``` > > > > ```json PerpsBuilderEarningsSummary Example theme={null} > > { > > "assets": [ > > { > > "feeAsset": "pUSD", > > "fillCount": 1, > > "notional": "100", > > "builderFee": "0.1" > > } > > ], > > "traderCount": 1, > > "activeApprovalCount": 2, > > "snapshot": { > > "start": 1767000000000, > > "end": 1767000060000, > > "asOfSequence": 1234567890 > > } > > } > > ``` > [tab] Python > > Use `fetch_builder_earnings_summary()` and `list_builder_earnings()` on a > `PerpsSession` opened by the Builder's `AsyncSecureClient`. Here, > `builder_session` is that session, created through [Authenticated > Sessions](/perps/authenticated-sessions#set-up-perps-access). > > ```python theme={null} > from polymarket.models.perps import PerpsBuilderEarning > > summary = await builder_session.fetch_builder_earnings_summary() > snapshot = summary.snapshot > pages = builder_session.list_builder_earnings( > start=snapshot.start, > end=snapshot.end, > as_of_sequence=snapshot.as_of_sequence, > ) > receipts: list[PerpsBuilderEarning] = [] > > async for page in pages: > receipts.extend(page.items) > ``` > > `summary.snapshot` fixes the window and indexed cutoff so every page matches > the summary. To select a window, pass `start` and `end` as datetimes or Unix > milliseconds to `fetch_builder_earnings_summary()`. Use `earning_id` to > deduplicate receipts. Each page also retains its `snapshot`, including empty pages. > > > [accordion] Output: PerpsBuilderEarning > > > > ```python PerpsBuilderEarning Type theme={null} > > class PerpsBuilderEarning: > > earning_id: str > > trade_id: PerpsTradeId > > order_id: PerpsOrderId > > instrument_id: PerpsInstrumentId > > trader: EvmAddress # Main account address > > side: OrderSide # BUY or SELL > > liquidity_role: PerpsLiquidityRole # maker or taker > > price: Decimal > > quantity: Decimal > > client_order_id: str | None = None > > timestamp: datetime > > sequence: int > > notional: Decimal > > fee_asset: str > > fee: Decimal # Signed exchange fee in fee_asset > > builder_fee: Decimal # Non-negative builder fee in fee_asset > > total_fee: Decimal # fee + builder_fee > > fee_rate: Decimal # Saved builder rate as a decimal fraction > > ``` > > > > ```json PerpsBuilderEarning Example theme={null} > > { > > "earning_id": "3:12345:1", > > "trade_id": 12345, > > "order_id": 67890, > > "instrument_id": 3, > > "trader": "0x0000000000000000000000000000000000005678", > > "side": "BUY", > > "liquidity_role": "taker", > > "price": "100", > > "quantity": "1", > > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", > > "timestamp": "2025-12-29T09:20:10Z", > > "sequence": 1234567890, > > "notional": "100", > > "fee_asset": "pUSD", > > "fee": "0.04", > > "builder_fee": "0.1", > > "total_fee": "0.14", > > "fee_rate": "0.001" > > } > > ``` > > > [accordion] Output: PerpsBuilderEarningsSummary > > > > ```python PerpsBuilderEarningsSummary Type theme={null} > > class PerpsBuilderEarningsSummary: > > assets: tuple[PerpsBuilderEarningsAsset, ...] > > trader_count: int # Distinct traders with attributed fills in the snapshot > > active_approval_count: int # Current positive, unrevoked grants, independent of the snapshot > > snapshot: PerpsBuilderEarningsSnapshot > > > > > > class PerpsBuilderEarningsAsset: > > fee_asset: str > > fill_count: int > > notional: Decimal > > builder_fee: Decimal > > > > > > class PerpsBuilderEarningsSnapshot: > > start: datetime > > end: datetime > > as_of_sequence: int > > ``` > > > > ```json PerpsBuilderEarningsSummary Example theme={null} > > { > > "assets": [ > > { > > "fee_asset": "pUSD", > > "fill_count": 1, > > "notional": "100", > > "builder_fee": "0.1" > > } > > ], > > "trader_count": 1, > > "active_approval_count": 2, > > "snapshot": { > > "start": "2025-12-29T09:20:00Z", > > "end": "2025-12-29T09:21:00Z", > > "as_of_sequence": 1234567890 > > } > > } > > ``` > [tab] API > > Get the Builder account's proxy address and secret through [Authenticated Sessions](/perps/authenticated-sessions#set-up-perps-access). > Fetch its earnings summary: > > ```bash Request theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/builder-earnings-summary" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > ```ts BuilderEarningsSummary Type theme={null} > type BuilderEarningsSummary = { > data: Array<{ > fee_asset: string; // Asset in which the fees are charged > fill_count: number; > notional: string; > builder_fee: string; // Non-negative Builder fee > }>; > start_timestamp: number; > end_timestamp: number; > as_of_sequence: number; > trader_count: number; > active_approval_count: number; > }; > ``` > > ```json BuilderEarningsSummary Example theme={null} > { > "data": [ > { > "fee_asset": "pUSD", > "fill_count": 2, > "notional": "200", > "builder_fee": "0.2" > } > ], > "start_timestamp": 1767000000000, > "end_timestamp": 1767000060000, > "as_of_sequence": 1234567891, > "trader_count": 1, > "active_approval_count": 2 > } > ``` > > The response contains totals in `data`, plus `start_timestamp`, `end_timestamp`, > `as_of_sequence`, `trader_count`, and `active_approval_count`. Pass the returned > window and cutoff to the receipts request: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/builder-earnings" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "start_timestamp=" \ > --data-urlencode "end_timestamp=" \ > --data-urlencode "as_of_sequence=" > ``` > > ```ts BuilderEarnings Type theme={null} > type BuilderEarnings = { > data: Array<{ > earning_id: string; > trade_id: number; > order_id: number; > instrument_id: number; > side: "maker" | "taker"; > timestamp: number; > sequence: number; > notional: string; > fee_asset: string; // Asset in which the fees are charged > builder_fee: string; // Non-negative Builder fee > fee_rate: string; > trader: string; > buy: boolean; > price: string; > quantity: string; > client_order_id?: string; > fee: string; // Exchange fee; negative for a maker rebate > total_fee: string; // fee + builder_fee; may be negative > }>; > more: boolean; > cursor?: string; > start_timestamp: number; > end_timestamp: number; > as_of_sequence: number; > }; > ``` > > ```json BuilderEarnings Example theme={null} > { > "data": [ > { > "earning_id": "3:12345:1", > "trade_id": 12345, > "order_id": 67890, > "instrument_id": 3, > "trader": "0x0000000000000000000000000000000000005678", > "side": "taker", > "buy": true, > "price": "100", > "quantity": "1", > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", > "timestamp": 1767000010000, > "sequence": 1234567890, > "notional": "100", > "fee_asset": "pUSD", > "fee": "0.04", > "builder_fee": "0.1", > "total_fee": "0.14", > "fee_rate": "0.001" > } > ], > "more": true, > "cursor": "", > "start_timestamp": 1767000000000, > "end_timestamp": 1767000060000, > "as_of_sequence": 1234567891 > } > ``` > > Follow `cursor` while `more` is `true`. The cursor preserves the window and > cutoff. Send it unchanged to the same endpoint: > > ```bash Request theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/builder-earnings" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "cursor=" > ``` > > ```ts BuilderEarnings Type theme={null} > type BuilderEarnings = { > data: Array<{ > earning_id: string; > trade_id: number; > order_id: number; > instrument_id: number; > side: "maker" | "taker"; > timestamp: number; > sequence: number; > notional: string; > fee_asset: string; // Asset in which the fees are charged > builder_fee: string; // Non-negative Builder fee > fee_rate: string; > trader: string; > buy: boolean; > price: string; > quantity: string; > client_order_id?: string; > fee: string; // Exchange fee; negative for a maker rebate > total_fee: string; // fee + builder_fee; may be negative > }>; > more: boolean; > cursor?: string; > start_timestamp: number; > end_timestamp: number; > as_of_sequence: number; > }; > ``` > > ```json BuilderEarnings Example theme={null} > { > "data": [ > { > "earning_id": "3:12346:1", > "trade_id": 12346, > "order_id": 67891, > "instrument_id": 3, > "trader": "0x0000000000000000000000000000000000005678", > "side": "taker", > "buy": true, > "price": "100", > "quantity": "1", > "client_order_id": "8f9e4a2b6c8d0e1f1234567890abcdef", > "timestamp": 1767000020000, > "sequence": 1234567891, > "notional": "100", > "fee_asset": "pUSD", > "fee": "0.04", > "builder_fee": "0.1", > "total_fee": "0.14", > "fee_rate": "0.001" > } > ], > "more": false, > "start_timestamp": 1767000000000, > "end_timestamp": 1767000060000, > "as_of_sequence": 1234567891 > } > ``` > > Use `earning_id` to deduplicate receipts. > > `trader` is the main account address, not its trading proxy. `side` identifies > maker or taker. `buy` identifies direction. Receipts also carry order, trade and > instrument IDs, `fee_rate`, `fee_asset`, `timestamp`, and `sequence`. > `client_order_id` is present when the order supplied one. > > The summary's `data` contains totals by fee asset. `trader_count` counts distinct > accounts with attributed fills in the window and cutoff. `active_approval_count` > counts current positive, unrevoked grants independently of that window. > Timestamps use Unix milliseconds. #### Reporting Rules | Rule | Effect | | - | - | | History window | The default is seven days. Each request supports up to 90 days. Select earlier windows for older earnings. | | Indexed cutoff | Reports include a complete indexed history prefix. They can lag live balance updates. | | Receipt identity | Each attributed fill side has a receipt, even when its fee rounds to zero. Two sides paying the same Builder produce separate receipts. | | Summary counts | Volume and fill counts include zero-fee receipts. Distinct Traders count once across markets, assets, and fill sides. | | Active approvals | Disabling a Builder does not erase its existing grants. | Exchange fee schedules, referral fee totals, and exchange revenue exclude Builder charges. ### Follow Live Builder Fills Use live receipts to update earnings as trades execute. Authenticate as the Builder account, as in the reporting examples above. The feed covers all Traders and markets attributed to that account. > [tab] TypeScript > > Open a session with `includeBuilderFills: true` on the Builder's > `SecureClient`. Here, `builderClient` authenticates the Builder account through > [Authenticated Sessions](/perps/authenticated-sessions#set-up-perps-access). > > ```ts theme={null} > const builderSession = await builderClient.openPerpsSession({ > includeBuilderFills: true, > }); > try { > for await (const event of builderSession) { > if (event.type === "builderFill") { > const receipts = event.payload; > // Persist receipts, deduplicating by earningId. > } else if (event.type === "resync") { > // Reconcile earnings using the recovery workflow below. > } > // Handle other account events here. > } > } finally { > await builderSession.close(); > } > ``` > > `builderFill` is part of `PerpsSessionEvent`, alongside orders, fills, balances, > and `resync` events. There is one session iterator and one connection lifecycle. > `includeBuilderFills` defaults to `false`. Setting `builderAttribution` does > not select whose receipts are delivered. Receipts belong to the authenticated > Builder account. > > > [accordion] Output: PerpsBuilderFillUpdateEvent > > > > ```ts PerpsBuilderFillUpdateEvent Type theme={null} > > type PerpsBuilderFillUpdateEvent = { > > type: "builderFill"; > > channel: "builderFills"; > > timestamp: EpochMilliseconds; > > sequence: number; > > payload: PerpsBuilderEarning[]; > > }; > > ``` > > > > ```json PerpsBuilderFillUpdateEvent Example theme={null} > > { > > "type": "builderFill", > > "channel": "builderFills", > > "timestamp": 1767000010000, > > "sequence": 1234567890, > > "payload": [ > > { > > "earningId": "3:12345:1", > > "tradeId": 12345, > > "orderId": 67890, > > "instrumentId": 3, > > "trader": "0x0000000000000000000000000000000000005678", > > "side": "BUY", > > "liquidityRole": "taker", > > "price": "100", > > "quantity": "1", > > "clientOrderId": "7f9e4a2b6c8d0e1f1234567890abcdef", > > "timestamp": 1767000010000, > > "sequence": 1234567890, > > "notional": "100", > > "feeAsset": "pUSD", > > "fee": "0.04", > > "builderFee": "0.1", > > "totalFee": "0.14", > > "feeRate": "0.001" > > } > > ] > > } > > ``` > [tab] Python > > Open a session with `include_builder_fills=True` on the Builder's > `AsyncSecureClient`. Here, `builder_client` authenticates the Builder account > through [Authenticated Sessions](/perps/authenticated-sessions#set-up-perps-access). > > ```python theme={null} > async with await builder_client.open_perps_session(include_builder_fills=True) as builder_session: > async for event in builder_session: > if event.type == "builder_fill": > receipts = event.payload > # Persist receipts, deduplicating by earning_id. > elif event.type == "resync": > # Reconcile earnings using the recovery workflow below. > pass > # Handle other account events here. > ``` > > `builder_fill` is part of `PerpsSessionEvent`, alongside orders, fills, > balances, and `resync` events. There is one session iterator and one connection > lifecycle. `include_builder_fills` defaults to `False`. Setting > `builder_attribution` does not select whose receipts are delivered. Receipts > belong to the authenticated Builder account. > > > [accordion] Output: PerpsBuilderFillEvent > > > > ```python PerpsBuilderFillEvent Type theme={null} > > class PerpsBuilderFillEvent: > > type: Literal["builder_fill"] = "builder_fill" > > channel: Literal["builderFills"] = "builderFills" > > timestamp: datetime > > sequence: int > > payload: tuple[PerpsBuilderEarning, ...] > > ``` > > > > ```json PerpsBuilderFillEvent Example theme={null} > > { > > "type": "builder_fill", > > "channel": "builderFills", > > "timestamp": "2025-12-29T09:20:10Z", > > "sequence": 1234567890, > > "payload": [ > > { > > "earning_id": "3:12345:1", > > "trade_id": 12345, > > "order_id": 67890, > > "instrument_id": 3, > > "trader": "0x0000000000000000000000000000000000005678", > > "side": "BUY", > > "liquidity_role": "taker", > > "price": "100", > > "quantity": "1", > > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", > > "timestamp": "2025-12-29T09:20:10Z", > > "sequence": 1234567890, > > "notional": "100", > > "fee_asset": "pUSD", > > "fee": "0.04", > > "builder_fee": "0.1", > > "total_fee": "0.14", > > "fee_rate": "0.001" > > } > > ] > > } > > ``` > [tab] API > > Connect and authenticate as the Builder using the credentials from the earnings > reporting example. > > **1. Authenticate the Connection** > > Open a WebSocket connection to `wss://ws.perpetuals.polymarket.com/v1/ws`. > Send the Builder's proxy address and secret in an authentication frame: > > ```json Request theme={null} > { > "id": 1, > "req": "post", > "op": { > "type": "auth", > "args": { > "proxy": "", > "secret": "" > } > } > } > ``` > > ```ts AuthResponse Type theme={null} > type AuthResponse = { > id?: number; > data: { > status: "ok"; > pod?: string; > } | { > status: "err"; > error: string; > }; > }; > ``` > > ```json AuthResponse Example theme={null} > { > "id": 1, > "data": { > "status": "ok" > } > } > ``` > > Wait for the matching response with `data.status: "ok"` before subscribing. > See [Session Lifecycle](/perps/authenticated-sessions#session-lifecycle) for > connection keepalive and authentication errors. > > **2. Subscribe to Receipts** > > Send the subscription frame on the authenticated connection: > > ```json Request theme={null} > { > "id": 2, > "req": "sub", > "chs": [ > "builderFills" > ] > } > ``` > > ```ts BuilderFillsSubscribeResponse Type theme={null} > type BuilderFillsSubscribeResponse = { > id?: number; > data: Array<{ > status: "ok"; > } | { > status: "err"; > error: string; > arts?: number; > ts?: number; > ref?: string; > }>; > }; > ``` > > ```json BuilderFillsSubscribeResponse Example theme={null} > { > "id": 2, > "data": [ > { > "status": "ok" > } > ] > } > ``` > > Updates carry a `data` array with the same receipt fields and `earning_id` > values as history, including zero-fee fills. The channel name cannot select > another Builder's account. See [Builder Fills](/api-reference/wss/perps-builder-fills) > for the message schema. After a disconnect, authenticate and subscribe again. > > > [accordion] Output: BuilderFillsUpdate > > > > ```ts BuilderFillsUpdate Type theme={null} > > type BuilderFillsUpdate = { > > ch: string; > > ts: number; > > ets: number; > > sq: number; > > data: Array<{ > > earning_id: string; > > trade_id: number; > > order_id: number; > > instrument_id: number; > > trader: string; > > buy: boolean; > > price: string; > > quantity: string; > > client_order_id?: string; > > side: "maker" | "taker"; > > timestamp: number; > > sequence: number; > > notional: string; > > fee_asset: string; // Asset in which the fees are charged > > fee: string; // Exchange fee; negative for a maker rebate > > builder_fee: string; // Non-negative Builder fee > > total_fee: string; // fee + builder_fee; may be negative > > fee_rate: string; > > }>; > > }; > > ``` > > > > ```json BuilderFillsUpdate Example theme={null} > > { > > "ch": "builderFills", > > "ts": 1767225600000, > > "ets": 1767225600000, > > "sq": 1234567890, > > "data": [ > > { > > "earning_id": "1:1:0", > > "trade_id": 1, > > "order_id": 1234567890, > > "instrument_id": 1, > > "trader": "0x1234567890abcdef1234567890abcdef12345678", > > "buy": true, > > "price": "100.00", > > "quantity": "10.00", > > "client_order_id": "550e8400e29b41d4a716446655440000", > > "side": "maker", > > "sequence": 1234567890, > > "notional": "1000.00", > > "timestamp": 1767225600000, > > "fee_asset": "pUSD", > > "fee": "0.125", > > "builder_fee": "1.00", > > "total_fee": "1.125", > > "fee_rate": "0.001" > > } > > ] > > } > > ``` #### Recover Missed Receipts The feed has no initial history snapshot or exactly-once delivery guarantee. Its sequence numbers can skip values because other account activity shares the sequence. A gap alone does not prove receipts were lost. Use history to recover missed receipts after connecting or reconnecting: **1. Buffer Live Receipts** Start consuming the live feed and buffer receipts while fetching history. **2. Read Overlapping History** Select a window that starts before your last stored receipt. Fetch every page at the same indexed cutoff, using the reporting workflow above. **3. Merge Receipts** Deduplicate history and buffered receipts by their receipt identity. Keep the identity with your stored record so repeated recovery does not count an execution twice. **4. Check Indexing Progress** History can lag the feed. Repeat the overlapping read with a newer cutoff until indexing covers the interval being recovered. Do not treat the largest sequence on a receipt as the complete indexed cutoff. ### Handle Order Errors If an order is rejected because the Trader has not approved the Builder fee, request approval for that fee before placing another order. The examples below approve 10 basis points (0.1%) after the Trader accepts the fee. > [tab] TypeScript > > `session.placeOrder()` throws `RequestRejectedError` with the message > `builder_approval_required` when approval is missing, revoked, or does not cover > the order's Builder fee. Check `error.message` and call `approveBuilderFee` > with the Builder address and the agreed rate: > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce, RequestRejectedError } from "@polymarket/client"; > > try { > await session.placeOrder({ > instrumentId, > side: OrderSide.BUY, > quantity: "0.01", > timeInForce: PerpsTimeInForce.IOC, > }); > } catch (error) { > if ( > !(error instanceof RequestRejectedError) || > error.message !== "builder_approval_required" > ) { > throw error; > } > > await session.approveBuilderFee({ > builderAddress, > maxFeeRate: "0.001", // 10 bps > }); > } > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```ts PerpsBuilderApproval Type theme={null} > > type PerpsBuilderApproval = { > > trader: EvmAddress; > > builder: EvmAddress; > > maxFeeRate: DecimalString; // Zero revokes consent > > approvalVersion: number; > > timestamp: EpochMilliseconds; > > sequence: number; > > }; > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "maxFeeRate": "0.001", > > "approvalVersion": 1, > > "timestamp": 1767000000000, > > "sequence": 1234567889 > > } > > ``` > > Submit a new order after approval succeeds. For `session.postOrders()`, inspect > each result's `status` and `error` for the same rejection. > [tab] Python > > `session.place_order()` raises `RequestRejectedError` with the message > `builder_approval_required` when approval is missing, revoked, or does not cover > the order's Builder fee. Check `str(error)` and call `approve_builder_fee` > with the Builder address and the agreed rate: > > ```python theme={null} > from polymarket.errors import RequestRejectedError > > try: > await session.place_order( > instrument_id=instrument_id, > side="BUY", > quantity="0.01", > time_in_force="ioc", > ) > except RequestRejectedError as error: > if str(error) != "builder_approval_required": > raise > > await session.approve_builder_fee( > builder_address=builder_address, > max_fee_rate="0.001", # 10 bps > ) > ``` > > > [accordion] Output: PerpsBuilderApproval > > > > ```python PerpsBuilderApproval Type theme={null} > > class PerpsBuilderApproval: > > trader: EvmAddress > > builder: EvmAddress > > max_fee_rate: Decimal # Zero revokes consent > > approval_version: int > > timestamp: datetime > > sequence: int > > ``` > > > > ```json PerpsBuilderApproval Example theme={null} > > { > > "trader": "0x0000000000000000000000000000000000005678", > > "builder": "0x0000000000000000000000000000000000001234", > > "max_fee_rate": "0.001", > > "approval_version": 1, > > "timestamp": "2025-12-29T09:20:00Z", > > "sequence": 1234567889 > > } > > ``` > > Submit a new order after approval succeeds. For `session.post_orders()`, inspect > each result's `status` and `error` for the same rejection. > [tab] API > > Check each order result for `status: "err"` and > `error: "builder_approval_required"`: > > > [accordion] Output: OrderResponse > > > > ```ts OrderResponse Type theme={null} > > type OrderResponse = { > > status: "ok"; > > oid: number; > > coid?: string; > > builder?: { > > address: string; > > fee_rate: string; > > }; > > } | { > > status: "err"; > > error: string; > > oid?: number; > > coid?: string; > > }; > > ``` > > > > ```json OrderResponse Example theme={null} > > [ > > { > > "status": "err", > > "error": "builder_approval_required" > > } > > ] > > ``` > > This means approval is missing, revoked, or does not cover the order's Builder > fee. Use the owner-signed `approveBuilder` operation in the Grant Approval > workflow with the Builder address, the next approval version, and the agreed > `max_fee_rate`. For 10 basis points, use `"0.001"`. Submit a new order after the > approval succeeds. # Concepts Source: https://docs.polymarket.com/perps/concepts Core concepts for Polymarket perpetual markets Perps trading depends on how order fills create or change positions, how prices affect account equity, and how collateral supports trading risk. The concepts below describe the moving parts that determine what an account can trade and when a position is at risk. ## Instruments An instrument identifies a Perps market: a tradable perpetual contract that tracks an underlying asset such as the S\&P 500 Index, gold, or bitcoin. Each instrument carries the information needed to identify the market and the rules for trading it. | Attribute | Meaning | | - | - | | ID | The instrument identifier used in market data and orders | | Symbol | A short market label, such as `SP500-USD`, `GOLD-USD`, or `BTC-USD` | | Underlying asset | The asset or index the market tracks, such as the S\&P 500 Index, gold, or bitcoin | | Collateral asset | The asset used to fund Perps accounts and support open positions. Polymarket Perps use pUSD. | | Trading constraints | Market-specific rules such as price precision, quantity precision, order limits, and leverage. | ## Perps Accounts A Perps account is tied to a signer account. The signer account controls private actions such as trading and withdrawals. The Perps account holds the state created by those actions: collateral, open positions, orders, fills, and history. Later sections explain how those pieces change as orders execute, prices move, and funding payments settle. Perps accounts are funded through onchain collateral deposits. > [!NOTE] > > If you're building on Perps, delegated credentials let your app act for the > Perps account without using the owner key for every private action. See > [Authenticated Sessions](/perps/authenticated-sessions). ## Prices A Perps market has two broad categories of prices: execution prices and calculated prices. Execution prices come from trades in the order book. Calculated prices are produced by Polymarket and used for reference, margin, and liquidation checks. This separation matters because one small or isolated trade should not be able to change an account's risk state or trigger liquidation by itself. | Price | Category | Meaning | Used for | | - | - | - | - | | Traded price | Execution price | The price of an executed order book fill | Trade history and execution records | | Index price | Calculated price | Polymarket's estimate of the underlying asset's fair value | Reference price and price anchoring | | Mark price | Calculated price | The price used to value positions | Unrealized PnL, margin checks, and liquidation risk | Calculated prices are computed from external price feeds. The feed set can change with market sessions, such as regular hours, overnight trading, and weekends, while funding, margin, and liquidation rules stay the same around the clock. See [Market Sessions](/perps/learn-about-trading/market-sessions). ## Orders And Fills Orders are requests to trade in a Perps market. They can execute immediately or rest in the order book until another order matches them. The order book is the list of resting buy and sell orders for a market. A fill is an executed match between orders in that book. > [!NOTE] > > Fills update Perps account state; they are not separate onchain transactions. ```mermaid theme={null} flowchart LR A[Submit order] --> B{Matches now?} B -->|Yes| C[Fill updates account] B -->|No| D[Order rests in book] D --> E[Later fill or cancel] E --> C ``` Limit orders are useful when the trade needs an explicit price. If the order does not fill immediately, it can rest in the book where it can be inspected, modified, or cancelled. ## Trading Positions Once an order fills, it changes the account's position in that market. A position is what the account currently holds: long exposure, short exposure, or no open exposure. | Position | Benefits when | Loses when | | - | - | - | | Long | The tracked asset rises | The tracked asset falls | | Short | The tracked asset falls | The tracked asset rises | A fill that adds to the account's current side increases exposure. A fill against the current side reduces exposure. When the position size reaches zero, the position is closed. If losses exceed what the account can support, the position can also be liquidated. ## Margin And Liquidation Perps accounts use collateral to support open positions. Margin checks compare the account's current value against the collateral required to open, increase, or maintain those positions. Margin checks use these terms: | Term | Meaning | | - | - | | Collateral | Funds available to support positions and withdrawals | | Account equity | The current value of the account after open-position gains, losses, fees, and funding effects | | Initial margin | Collateral required to open or increase a position | | Maintenance margin | Minimum collateral required to keep a position open | | Liquidation | Forced position closing when account equity falls below maintenance margin | Account equity moves as the mark price changes and as account debits or credits settle. It can move up or down even before a position is closed. > [!TIP] > > If you're building on Perps, monitor account equity to decide when to reduce > exposure, add collateral, or stop placing new orders. At a high level, account equity is the account's collateral plus open-position gains or losses, minus amounts owed. ```text theme={null} Account equity = collateral + unrealized PnL - amounts owed ``` If account equity falls below maintenance margin, the account is at risk of liquidation. Liquidation closes exposure to prevent losses from exceeding the account's collateral. ## Funding Payments **Funding payments** help keep a Perps market close to its index price. They are not order-book trades; they are account debits or credits applied to open positions over time. > [!NOTE] > > Funding payments are different from collateral deposits. Deposits add > collateral to a Perps account; funding payments are debits or credits between > long and short positions. | Market state | Typical payment direction | | - | - | | Market trades above index price | Longs pay shorts | | Market trades below index price | Shorts pay longs | A funding payment credited to the account increases account equity. A funding payment owed by the account reduces account equity. The **funding rate** is the rate used to calculate these payments. Public market data shows funding rates over time, while private account history shows the funding payments applied to an account. ## Realtime Account State If you're building on Perps, realtime account state helps your integration keep a local view in sync. Integrations often keep a local view of account state so they can react quickly to fills, risk changes, and collateral movements. Realtime updates help keep that local view in sync. | State change | Why it matters | | - | - | | Order update | A resting order opened, changed, filled, or cancelled | | Fill | A trade executed and changed the account's position or balance | | Portfolio update | Account equity, margin, or position state changed | | Funding payment | A funding debit or credit changed account state | | Deposit or withdrawal | Collateral moved into or out of the account | Realtime streams can reconnect or detect gaps. When that happens, the integration should resync by refetching the account state it depends on before trusting the local view again. # Errors Source: https://docs.polymarket.com/perps/errors Error messages returned by the API and the conditions that trigger them The API returns descriptive error messages when a request is rejected. Use the HTTP status and response body to decide whether to retry or correct the request. ## Service Unavailable The API returns `503 Service Unavailable` for temporary overload or a response timeout on operations that support safe retries. ```json theme={null} { "status": "err", "error": "service_unavailable" } ``` ### Transient Overload (`503`) A `503` does not prove that the request did not execute. A load-shed rejection happens before dispatch, but an engine response timeout can occur after the request was admitted. | Operation | Retry Action | | - | - | | Reads and idempotent state updates, such as setting leverage | Retry with backoff. | | Signed balance changes, such as isolated-margin adjustments, withdrawals, or internal transfers | Resend only the exact original signed request. Do not generate a new signature, salt, or timestamp. | * Honor `Retry-After` when present; its value is a delay in whole seconds. * Batch endpoints return a one-element array for a whole-request rejection. * A `500` with `internal_error` can indicate an unexpected failure or an indeterminate outcome. Follow the operation's recovery guidance before retrying. ### Recover an Isolated-Margin Adjustment For `PATCH /v1/trade/margin`, `amt` is a signed delta, not a replacement balance. After a `503`, retry only the exact original signed payload. A newly signed request is a separate adjustment and can apply the delta again. A `signature_already_used` rejection means the original signed request was ingested; it does not confirm that the adjustment succeeded. Its decision may still be pending or may have rejected the adjustment. `GET /v1/account/portfolio` reports committed state without a per-request outcome. Neither an unchanged balance nor a matching delta proves what happened: the request may still be pending, or another adjustment may explain the change. Do not sign another adjustment for the same account until the original outcome has been confirmed out of band. No public endpoint currently reports that request's terminal outcome. ## Withdrawal and Internal Transfer Errors Returned on `POST /v1/account/withdraw` and `POST /v1/account/internal-transfer` when the Polymarket address book rejects or cannot be reached. | Error | HTTP status | Condition | | - | - | - | | `withdrawal_not_allowlisted` | `403` | The destination is not an active address-book entry, or an enrolled owner attempted a transfer outside their account group. | | `address_book_unavailable` | `503` | The address-book lookup failed before submission. The request was not submitted. Retry with backoff and honor `Retry-After: 1` when present. | Treat `withdrawal_not_allowlisted` as final until the destination is allowlisted. For `address_book_unavailable`, retry with backoff; do not assume the transfer or withdrawal executed. ## Proxy Management Errors Returned on `DELETE /v1/account/proxy` when a trading key self-delete is refused. The owner deleting a different key is unchanged. | Error | HTTP status | Condition | | - | - | - | | `proxy_registration_newer_than_signature` | `422` | Self-delete within 60 seconds of registering or rotating the key. Wait, then sign a fresh request. | | `proxy_registration_timestamp_missing` | `422` | Self-delete for a key with no recorded registration time. The owner can still delete the key. | ## WebSocket Errors These errors appear on authenticated WebSocket connections when a post is refused before or during handling. | Error | Condition | | - | - | | `invalid_request` | The frame failed parsing. The reply keeps a recoverable request `id` when the client supplied one. | | `read_only_key` | The connection authenticated with a proxy labelled `read-only:…` and the post is not `ping` or `auth`. Signed writes are refused on read-only sockets. | | `message_rate_limited` | The connection or IP message budget is exhausted. Refused read-only posts still consume message budget until the limit is reached. | | `open_orders_limit` | Cancel-on-disconnect tracking holds 65,536 order IDs and none can be pruned, so a new create is refused. | See [Rate Limits](/perps/rate-limits) for WebSocket message and connection budgets, including separate limits for read-only keys. ## Take Profit and Stop Loss Errors | Error | Condition | | - | - | | `tp_sl_trigger_past_liquidation` | The trigger price is beyond the position's liquidation price under current margin rules, including after tiered maintenance activates. | ## Stock Split Errors Automatic stock splits stay disabled in production. This identifier is reserved for when that path is enabled. | Error | Condition | | - | - | | `stock_split_unit_mismatch` | An automatic stock split supplied a price outside its expected post-split range. | ## Order Placement Errors | Error | Condition | | - | - | | `invalid signature` | EIP-712 signature verification or timestamp failed | | `signature expired` | Signature older than 5 minutes | | `account not found for proxy` | Signer proxy not linked to any account | | `no orders provided` | Empty order array | | `FOK orders cannot be post-only` | FOK + `post_only=true` | | `IOC orders cannot be post-only` | IOC + `post_only=true` | | `GTC orders require a price` | GTC without price | | `price cannot be zero` | Price = 0 | | `client order id cannot be all zeros` | Client order ID is all zeros | | `price exceeds allowed decimal places` | Too many decimal places in price | | `price exceeds allowed significant figures` | More than 5 significant figures in price | | `quantity must be positive` | Quantity is zero or negative | | `quantity exceeds allowed decimal places` | Too many decimal places in quantity | | `quantity exceeds allowed significant figures` | More than 5 significant figures in quantity | | `command expired` | `exp` is at or before the current server time | An `exp` more than 5 seconds ahead is not an error: the server clamps the command-processing deadline to 5 seconds from arrival. Earlier versions rejected it with `command expiry too far in future`; that error is retired. This deadline does not schedule order cancellation. ## Modify Order Errors Modify Order returns one result per requested order. A rejected modification does not change the live order, although a separately processed fill or cancellation can still change its state. | Error | Condition | | - | - | | `modify_already_pending` | Another modification for the same order is still in progress. | | `modify_no_op` | The requested price and total quantity equal the live order values. | | `modify_limit_reached` | The order has already reached 10,000 successful modifications. | | `modify_would_cross` | The modified order would lock or cross the live opposite best price. | | `duplicate_order_in_batch` | An earlier item in the same batch resolved to the same order ID. | | `order_not_modifiable` | The order is not an eligible standalone resting GTC limit order. | | `order_has_tpsl` | The order is a TP/SL leg or has attached or order-scoped TP/SL. | | `modify_quantity_not_above_filled` | The requested new total quantity is less than or equal to the live cumulative fill. | | `order_unknown` | The client order ID does not resolve to an order owned by the account. | | `order_not_in_orderbook` | The order ID is unknown, terminal, owned by another account, or otherwise not disclosable. | | `order_in_flight` | The order is still in creation or taker delay and is not yet resting. | | `invalid_command` | A per-item price, quantity, or notional validation failed before sequencing. | Shared account, instrument, margin, position, reduce-only, and rate-limit errors can also reject a modification under the same conditions as a new order. ## Builder Code Errors | Error | Condition | | - | - | | `builder_codes_disabled` | New builder-tagged orders are disabled on this venue. | | `builder_not_enabled` | The selected builder is not enabled for new orders. | | `invalid_builder_fee` | The rate is negative, above the 10-basis-point cap, or inconsistent with saved terms. | | `builder_approval_required` | No active approval covers the requested builder rate. | | `builder_approval_version` | The approval version is stale. Read the latest version before signing a replacement. | | `builder_approval_limit` | The account already has 10 positive-rate approvals. Revoke one before adding or reactivating another. | | `builder_order_requires_replacement` | Increasing a tagged order's quantity requires cancel-and-new. | | `builder_to_self` | The trader cannot select its own account as the builder recipient. | | `builder_version_mismatch` | The command producer does not support the activated builder-code schema. | ## Order Cancellation Errors A cancel sent while an order is awaiting risk checks succeeds immediately, unless the account is being liquidated. The canceled order will not enter the order book. A cancel sent while the order's accept is still on its way to the matching engine does not fail: the exchange holds one such cancel, applies it as soon as the accept completes, and answers with the final outcome — success once the order is removed, or `order_already_terminal` if the order filled or was rejected first. If the exchange disables this behavior, is in cancel-only maintenance mode, or the account is being liquidated, such a cancel returns `order_in_flight` instead. | Error | Condition | | - | - | | `order_not_found` | Order doesn't exist | | `order_not_pending_engine` | An earlier cancel for the same order is already queued or in flight | | `order_not_in_orderbook` | Order is not in the active book | | `order_in_flight` | Order is not yet cancellable: in taker delay, the account is being liquidated, or acceptance is in flight while held cancels are disabled or cancel-only mode is active | | `order_already_terminal` | Order filled, was canceled, or was rejected before this cancel | ## Auto-Cancel Errors Returned when arming the auto-cancel switch with `PATCH /v1/trade/auto-cancel`. Disarming skips these checks and is always allowed. A deadline already in the past is rejected earlier with a plain `400` message. | Error | Condition | | - | - | | `auto_cancel_deadline_too_soon` | Deadline is less than 5 seconds in the future | | `auto_cancel_daily_limit_reached` | Account already triggered auto-cancel the maximum number of times this UTC day | | `auto_cancel_in_flight` | A previous trigger is still cancelling the account's open orders | `auto_cancel_in_flight` is transient. Arming succeeds once the engine finishes the earlier cancellation. ## Update Leverage Errors Returned when a leverage or margin-mode update is rejected. Leverage must be positive; a zero leverage is rejected earlier with a plain `400` validation message. A disabled instrument is not rejected merely because it is disabled. | Error | Condition | | - | - | | `instrument_not_found` | The instrument ID has never been listed | | `invalid_leverage` | The requested leverage exceeds the instrument's maximum | | `position_exists` | A margin-mode switch was requested while a position is open in the instrument | | `open_orders_exist` | A margin-mode switch was requested while orders exist in the instrument, including orders awaiting risk approval or execution | | `blp_leverage_locked` | The account is subscribed to the Backstop Liquidity Provider program for the instrument, even if the update re-submits the unchanged pair; unsubscribe before pinning or changing its configuration | ## Market Retirement Errors * `instrument_close_only` — user orders must be reduce-only while this market is in close-only mode. * `instrument_settled` — the market is permanently settled and cannot accept new trading work. * `settlement_price_unavailable` — settlement lacks a complete, fresh 30-minute index-price window. * `settlement_insurance_insufficient` — the insurance fund cannot cover eligible deficits while meeting its remaining obligations. * `settlement_invalid_state` — the current state cannot be settled safely, including less than 30 continuous minutes of close-only, inconsistent exposure, or work above the operation's bound. Investigate before retrying. ### Delisting cancellation statuses Order updates can report these statuses after an operator changes a market: | Status | Meaning | | - | - | | `instrument_close_only` | The order was canceled because it could increase exposure after close-only mode began. | | `instrument_settled` | The order was canceled because the instrument was permanently settled and delisted. | Settlement is an admin action. Clients receive the resulting order and position updates. ## Isolated Margin Adjustment Errors These stable identifiers are returned when an isolated margin adjustment is rejected after sequencing. Gateway signature validation can reject a stale or future-skewed timestamp earlier as `invalid signature`; that request never reaches sequencing. | Error | Condition | | - | - | | `position_not_found` | The target open position does not exist | | `invalid_margin_mode` | The target position is not using isolated margin | | `invalid_margin_amount` | The amount is zero, over-precise, or cannot be represented safely | | `insufficient_margin` | An addition exceeds available, unreserved collateral | | `account_liquidating` | Cross liquidation is active, or the target isolated position is liquidating | | `margin_below_required_initial` | A removal would leave position equity below current required initial margin | | `invalid_margin_signature_timestamp` | Sequencer found the timestamp over five minutes old or one minute ahead | | `signature_already_used` | The exact signed margin request has already been ingested | # FAQ Source: https://docs.polymarket.com/perps/faq Common questions about Polymarket Perps trading, pricing, margin, liquidation, fees, and integration Common questions about Polymarket Perps. ## General > [accordion] What is Polymarket Perps? > > Polymarket Perps is a perpetual futures exchange offering continuous exposure to equities, indices, commodities, and other underlyings. Positions have no expiry. A funding rate keeps the contract price tethered to the underlying's spot price over time. > [accordion] Which instruments can I trade? > > Fetch the current product list, symbols, underlyings, reference feeds, and > leverage settings from [`GET > /v1/info/instruments`](/perps/market-data#fetch-instruments). > [accordion] Is the exchange on-chain or off-chain? > > Hybrid. Order matching, margin, and funding run off-chain for low latency. > Deposits and withdrawals settle on Polygon, and the exchange periodically > posts state-root commitments on-chain so off-chain activity stays verifiable. > [accordion] Does the perp trade 24/7, even when the underlying market is closed? > > Yes. The order book, matching, funding, margin checks, and liquidations all > run continuously. What changes outside of regular hours is the set of external > feeds used to compute Index and Mark. > [accordion] Do Polymarket Perps expire? > > No. Perpetual futures have no expiration date. A Perps position stays open > until you close it or it is force-closed by liquidation. > [accordion] Are perps and perpetual futures the same thing? > > Yes. "Perps" is trader shorthand for "perpetual futures." Both refer to the > same derivative contract: a futures-style instrument with no expiry, anchored > to the underlying's spot price through periodic funding. > [accordion] How are Perps different from Polymarket prediction markets? > > Polymarket's prediction markets settle Yes or No shares at \$1 or \$0 based on a discrete event outcome. Perps are continuous: there is no event resolution and no \$0/\$1 settlement. Instead you take a long or short position whose value moves with the underlying asset's price, subject to funding payments and margin requirements like any perpetual futures contract. ## Trading and Orders > [accordion] What order types are supported? > > Limit and market-style orders are supported with GTC, IOC, and FOK time-in-force values. GTC orders can be tagged post-only, which rejects the order if it would take liquidity. Closing orders can be tagged reduce-only, which prevents the order from increasing exposure. See [Configure Order Behavior](/perps/trading#configure-order-behavior) and [Close a Position](/perps/trading#close-a-position). > [accordion] Why was my order rejected when my balance looks fine? > > Pre-trade margin uses the worst-case position size from your existing exposure plus all resting orders on each side, not just the current position. > > ```text theme={null} > WorstCaseSize = max(|Position + OpenBuys|, |Position - OpenSells|) > ``` > > If `Equity < IM_required` for that worst case, the order is rejected even though current equity is comfortable. > [accordion] What is self-trade prevention? > > Self-trade prevention is on by default for every order and runs in CancelMaker mode: when a taker would match against a resting order on the same account, the conflicting resting maker is canceled and the taker continues matching against other makers. It is not an API setting. There is no way to turn it off or change its mode. Accounts that Polymarket has grouped as one entity count as the same account for this check. See [Self-Trade Prevention](/perps/learn-about-trading/self-trade-prevention). ## Pricing, Mark, Index, and Funding > [accordion] What's the difference between Mark Price, Index Price, and last trade price? > > * Index Price is the protocol's estimate of the underlying's fair value, aggregated from external oracle feeds. > * Mark Price is the price the system uses for margin, PnL, liquidation, and funding. > * Last trade price is the price of the most recent fill on the local book. It is not used for margining. > > See [Prices](/perps/concepts#prices). > [accordion] What happens to Mark when external feeds go down? > > Each Mark candidate degrades gracefully to the Index. If the order book mid is > missing, the candidate falls back to Index. If there are no recent trades or > quotes, the candidate falls back to Index. If external mark feeds are > unavailable, the candidate falls back to Index. In the worst case, all > candidates converge to Index and Mark tracks Index directly. > [accordion] How is funding calculated and when does it settle? > > A premium index is sampled every 5 seconds by walking the book for 1,000 > quote-asset notional on each side. Samples are averaged over a 1-hour charge > window, run through an 8-hour formula with a fixed interest leg and clamp, > divided by 8, and capped at +/-4% per hour. Settlement happens once per > window. Longs pay shorts when the rate is positive, and shorts pay longs when > negative. The protocol takes no cut. > [accordion] Can I see funding pressure between settlements? > > Yes. A rolling 5-second premium sample and its implied 8-hour rate are published continuously through public market data. You can also read funding history with [`GET /v1/info/funding`](/perps/market-data#list-funding-history). ## Margin and Leverage > [accordion] What's the difference between cross and isolated margin? > > * Isolated margin funds each position with a dedicated margin allocation. Liquidation only closes the affected position. > * Cross margin shares account collateral across all cross positions. Unrealized PnL on one position can offset margin on another, but a liquidation evaluates and can unwind the whole cross account. > > The web app opens new positions in isolated mode by default. Cross is opt-in through the API using leverage configuration, and only for instruments that allow it: some markets are isolated-only and reject cross margin. Instrument data shows which margin modes each market supports. See [Update Leverage](/perps/trading#update-leverage) and [Fetch Instruments](/perps/market-data#fetch-instruments). > [accordion] What is the maximum leverage? > > For crypto, SP500, Oil, Gold and Silver we offer up to 20x leverage, RWA in > general up to 10x leverage. > [accordion] What are leverage tiers and why does my margin go up as my position grows? > > Tiers cap the maximum leverage available as position notional grows. Building > a larger position requires lowering your leverage setting, which raises the > initial margin rate on your entire position — the cap is not applied bracket > by bracket. Tiers affect initial margin only; the maintenance margin rate is > flat per market. Fetch live tier values from [`GET > /v1/info/instruments`](/perps/market-data#fetch-instruments). > [accordion] How is maintenance margin set? > > The maintenance margin rate is flat per market: `MMR = 0.5 / max_leverage`, > independent of position size and of your leverage setting — for example, 2.5% > on a 20x market. It equals half the initial margin rate at maximum leverage, > so a max-leverage position is liquidated only after losing roughly half of its > posted margin; at lower leverage the buffer between entry margin and > liquidation is larger. > [accordion] What happens between margin call and liquidation? > > Three states are evaluated continuously. > > | State | Condition | Behavior | > | - | - | - | > | Healthy | `Equity >= IM` | Normal trading | > | Margin call | `MM <= Equity < IM` | Reduce-only: close exposure or deposit collateral | > | Liquidation | `Equity < MM` | System closes the position | > > A deposit during margin call instantly increases equity and can restore healthy status. > [accordion] Can I withdraw collateral while I have an open position? > > Yes, but withdrawals must leave the greater of existing collateral > reservations and 10% of total open-position notional at Mark Price. Orders > awaiting risk checks also reserve margin. A \$100 position at 20x needs \$5 > initial margin but a \$10 withdrawal reserve, excluding fees and other > obligations. See [Withdrawal Margin Requirements](/perps/learn-about-trading/margin#withdrawal-margin-requirements) > for the formula and example. ## Liquidation > [accordion] When am I liquidated? > > Liquidation occurs when account equity falls below maintenance margin. Cross and isolated positions are checked independently: each isolated position has its own equity and maintenance margin, while cross uses the account's combined equity and combined maintenance margin. See [Margin and Liquidation](/perps/concepts#margin-and-liquidation). > [accordion] Why does my liquidation price move when I haven't changed anything? > > For cross positions, the liquidation price depends on available balance: > everything in the cross account that is not this position's own equity. Mark > moves on other cross positions, size changes, or collateral changes can all > shift the liquidation price for every cross position simultaneously. > [accordion] What happens during liquidation? > > The affected scope is flagged and new orders on it are blocked. Cross blocks > the whole account. Isolated blocks just that instrument. The system closes > positions with reduce-only IOC orders, rate-limited per account, re-evaluating > margin between fills. Cross liquidation closes one position at a time across > cycles. If equity recovers above the recovery initial margin, the flag clears. > [accordion] What is the insurance fund and when does it step in? > > When equity falls below two-thirds of maintenance margin, order-book > liquidation is unlikely to recover value, so the system absorbs the position > directly into the insurance-fund account along with its margin. For cross > backstop, the system absorbs all cross positions plus quote balance. > [accordion] Are there extra fees on liquidation fills? > > Yes. While flagged, every fill pays an additional liquidation fee rate on top of the maker or taker rate. > > ```text theme={null} > FillFee = Notional * (MakerOrTakerRate + LiquidationFeeRate) > ``` > > Fetch the live rate per instrument from [`GET /v1/info/instruments`](/perps/market-data#fetch-instruments). ## Fees > [accordion] What are the current maker and taker fees? > > Fees are tiered by trailing 30-day trading volume. New accounts start at the \$0 tier and move up as their volume crosses each threshold. Fee tiers are re-evaluated every UTC day. > > | 30-Day Volume ≥ | Taker | Maker | > | - | - | - | > | \$0 | 0.0400% | 0.0125% | > | \$1M | 0.0370% | 0.0100% | > | \$5M | 0.0350% | 0.0080% | > | \$25M | 0.0300% | 0.0050% | > | \$100M | 0.0270% | 0.0020% | > | \$500M | 0.0250% | 0.0000% | > | \$1B | 0.0200% | -0.0050% | > > Fees are calculated per fill as `abs(Price * Quantity) * Rate`, denominated in the instrument's quote asset (pUSD). Only the top tier earns a maker rebate; lower tiers pay a positive maker fee. See [Fees](/perps/learn-about-trading/fees) and [Trading Fees](/perps/trading#trading-fees). ## API and Integration > [accordion] What's the difference between my main wallet and the proxy? > > Your main wallet signs the one-time create-proxy request and never trades directly. The returned proxy address and secret are what you use day to day: the proxy private key signs trade requests, and the `(proxy, secret)` pair authenticates private REST and WebSocket reads. This isolates the trading key from the wallet that holds funds. See [Set Up Authentication](/perps/authenticated-sessions#set-up-authentication). > [accordion] What address identifies my Perps account? > > Your account is keyed by your EOA base address, the externally-owned account > that signs `createProxy`, not a Safe smart-contract wallet address. Even if > you use a Safe wallet elsewhere on Polymarket, your Perps balances, positions, > and history are all tracked against the underlying EOA. Use that EOA when > looking up your account or referencing it in support requests. > [accordion] How do I avoid clock-skew rejections? > > Each signed request must include a fresh `ts` request timestamp in > milliseconds and `salt`. Reused or stale values are rejected. Sync against > `GET /v1/info/time` and do not sign requests far in the past or future. The > optional `expa` field caps the validity window. > [accordion] How do deposits and withdrawals work? > > Deposits and withdrawals are the only operations that move assets in or out of > the exchange. Both settle on Polygon. Deposits credit equity as soon as the > engine sees them. Withdrawals are signed off-chain and must satisfy the > [withdrawal margin > requirements](/perps/learn-about-trading/margin#withdrawal-margin-requirements), > including the 10% notional floor. See [Fund Your > Account](/perps/fund-your-account). > [accordion] Are there geographic restrictions on order placement? > > Yes. Order placement is not permitted from the United States, Canada, Cuba, Iran, North Korea, Syria, Crimea, Donetsk, or Luhansk. Builders are responsible for verifying user location before submitting orders. ## Sessions > [accordion] What do market sessions actually change? > > Sessions affect which set of external feeds is used to compute Index Price and Mark Price. They do not change funding, margin, leverage tiers, order matching, or liquidation triggers. Those run identically around the clock. > [accordion] What's the difference between Disrupted and Halted? > > * Disrupted means external feeds are unavailable or failing sanity checks. The system falls back to whatever feed set is still healthy. > * Halted means the underlying itself has a trading halt or corporate-action freeze. > > Both are categorizations of feed-source health and only affect Index and Mark sourcing. The perp continues to match orders. # Fund Your Account Source: https://docs.polymarket.com/perps/fund-your-account Deposit, withdraw, and transfer pUSD collateral for Perps trading Fund the Perps account with pUSD before placing orders. Deposits move pUSD from the user's Polymarket wallet into the Perps account. Withdrawals move available pUSD back to the authenticated wallet. Internal transfers move pUSD between two Perps accounts, including between accounts in the same account group. ## Deposit Collateral Deposit pUSD when the account needs collateral for opening or maintaining Perps positions. > [tab] TypeScript > > **1. Create a Secure Client** > > Create a `SecureClient` for the wallet that will fund the Perps account. If you > already have a Polymarket wallet, pass it as `wallet` and include a Relayer API > key so the SDK can submit gasless transactions. If you are creating a wallet > programmatically, use a Builder API key so the SDK can create the Deposit Wallet > for that signer. > > ```ts Existing Account theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > apiKey: relayerApiKey({ > key: process.env.RELAYER_API_KEY!, > address: process.env.RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ```ts New Programmatic Wallet theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.PRIVATE_KEY!), > apiKey: builderApiKey({ > key: process.env.BUILDER_API_KEY!, > secret: process.env.BUILDER_SECRET!, > passphrase: process.env.BUILDER_PASSPHRASE!, > }), > }); > ``` > > **2. Set Up Deposit Approvals** > > Set up the approvals required for Perps collateral deposits. The SDK skips work > that is already complete. > > ```ts theme={null} > await client.setupTradingApprovals(); > ``` > > **3. Deposit Collateral** > > Deposit pUSD from the user's Polymarket wallet into the Perps account. Make sure > the wallet has pUSD before depositing. The minimum Perps deposit is 10 pUSD. > Amounts use raw pUSD base units, so 10 pUSD is `10_000_000n`. > > ```ts theme={null} > const deposit = await client.depositToPerps({ > amount: 10_000_000n, > }); > > const receipt = await deposit.wait(); > // receipt.transactionHash: TxHash > ``` > > `deposit.wait()` confirms that the chain transaction settled. Perps may take a > moment to credit the account after that. > > **4. Verify the Deposit** > > Open a Perps session and read account state after the deposit settles. > > ```ts theme={null} > const session = await client.openPerpsSession(); > > try { > const portfolio = await session.fetchPortfolio(); > const pages = session.listDeposits(); > const deposits = await pages.firstPage(); > } finally { > await session.close(); > } > ``` > > Use `portfolio.withdrawable` to check collateral available for withdrawal and > `deposits.items` to reconcile deposit history. The `withdrawable` value already > accounts for the [10% notional reserve](/perps/learn-about-trading/margin#withdrawal-margin-requirements). > [tab] Python > > **1. Create a Secure Client** > > Create an `AsyncSecureClient` for the wallet that will fund the Perps account. > If you already have a Polymarket wallet, pass it as `wallet` and include a > Relayer API key so the SDK can submit gasless transactions. If you are creating a > wallet programmatically, use a Builder API key so the SDK can create the Deposit > Wallet for that signer. > > ```python Existing Account theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["RELAYER_API_KEY"], > address=os.environ["RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python New Programmatic Wallet theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > api_key=BuilderApiKey( > key=os.environ["BUILDER_API_KEY"], > secret=os.environ["BUILDER_SECRET"], > passphrase=os.environ["BUILDER_PASSPHRASE"], > ), > ) > ``` > > **2. Set Up Deposit Approvals** > > Set up the approvals required for Perps collateral deposits. The SDK skips work > that is already complete. > > ```python theme={null} > await client.setup_trading_approvals() > ``` > > **3. Deposit Collateral** > > Deposit pUSD from the user's Polymarket wallet into the Perps account. Make sure > the wallet has pUSD before depositing. The minimum Perps deposit is 10 pUSD. > Amounts use raw pUSD base units, so 10 pUSD is `10_000_000`. > > ```python theme={null} > deposit = await client.deposit_to_perps(amount=10_000_000) > > receipt = await deposit.wait() > # receipt.transaction_hash: TransactionHash > ``` > > `deposit.wait()` confirms that the chain transaction settled. Perps may take a > moment to credit the account after that. > > **4. Verify the Deposit** > > Open a Perps session and read account state after the deposit settles. > > ```python theme={null} > session = await client.open_perps_session() > > try: > portfolio = await session.fetch_portfolio() > pages = session.list_deposits() > deposits = await pages.first_page() > finally: > await session.close() > ``` > > Use `portfolio.withdrawable` to check collateral available for withdrawal and > `deposits.items` to reconcile deposit history. The `withdrawable` value already > accounts for the [10% notional reserve](/perps/learn-about-trading/margin#withdrawal-margin-requirements). > [tab] API > > **1. Check Deposit Approval** > > Before depositing, the Polymarket wallet must approve the Perps deposit contract > to spend pUSD. If the approval is already in place, skip the approval call. > > ```solidity Approval Call theme={null} > pUSD.approve(PerpsDepositContract, maxUint256) > ``` > > Use these contract addresses when building the approval call. > > | Contract | Address | > | - | - | > | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | Perps deposit contract | `0xDCa4af75705dbB50f62437045afF9921947917d2` | > > > [!NOTE] > > > > The following steps show the Deposit Wallet batch path. If you are trading > > with a Safe or Poly Proxy wallet, use an SDK that handles the wallet-specific > > transaction flow for you. > > **2. Build the Deposit Call** > > Create the Perps deposit call. Deposit amounts use pUSD base units, so 10 pUSD > is `10000000`. > > ```solidity theme={null} > function deposit(address token, uint256 amount, address to); > ``` > > Encode the deposit calldata with these arguments. > > | Argument | Value | > | - | - | > | `token` | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `amount` | `10000000` | > | `to` | Signer address for the Polymarket account. | > > Build the final ordered call list. Include the approval call first only when > approval is needed. > > ```json Without Approval theme={null} > [ > { > "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", > "value": "0", > "data": "" > } > ] > ``` > > ```json With Approval theme={null} > [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", > "value": "0", > "data": "" > } > ] > ``` > > **3. Fetch a Relayer Nonce** > > Fetch a fresh `WALLET` nonce before submitting the Deposit Wallet batch. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the nonce to sign with the batch. > > ```json theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **4. Build the Deposit Wallet Batch** > > Build the EIP-712 `Batch` typed data for the Deposit Wallet. Use the final > ordered call list from the previous step, and omit the approval call when > allowance is already sufficient. Set `deadline` to a Unix timestamp in seconds > after which the relayer should reject the batch. > > ```json theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "primaryType": "Batch", > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", > "value": "0", > "data": "" > } > ] > } > } > ``` > > Sign this typed data with the signer for the Polymarket account. > > **5. Submit the Deposit Transaction** > > Submit the signed batch to the Relayer API. Use the same ordered call list you > signed in the previous step. > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Deposit pUSD to Perps", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xDCa4af75705dbB50f62437045afF9921947917d2", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > The response includes the relayer transaction ID. > > ```json theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **6. Poll the Deposit Transaction** > > Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying > on the deposited collateral. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" > ``` > > ```json theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Perps may take a moment to credit the account after the onchain transaction > settles. Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. ## Withdraw Collateral Withdraw pUSD when the account has available collateral that should return to the authenticated wallet. Withdrawals must satisfy the [withdrawal margin requirements](/perps/learn-about-trading/margin#withdrawal-margin-requirements), including the 10% reserve against open-position notional. Collateral available for trading can therefore exceed collateral available for withdrawal. > [tab] TypeScript > > Request a withdrawal to the authenticated wallet. > Amounts use raw pUSD base units, so 10 pUSD is `10_000_000n`. > > ```ts theme={null} > const withdrawalId = await client.withdrawFromPerps({ > amount: 10_000_000n, > }); > ``` > > The SDK signs the withdrawal request with the Polymarket account signer and > returns the Perps withdrawal ID. > > To track the withdrawal, open a Perps session and list withdrawals. > > ```ts theme={null} > const session = await client.openPerpsSession(); > > try { > const pages = session.listWithdrawals(); > const withdrawals = await pages.firstPage(); > } finally { > await session.close(); > } > ``` > > To narrow the results to a single state, pass a `withdrawalStatus` filter with > a `PerpsKnownWithdrawalStatus` member. The filter accepts one status per > request. For example, list the withdrawals that are still pending: > > ```ts theme={null} > import { PerpsKnownWithdrawalStatus } from "@polymarket/client"; > > const pages = session.listWithdrawals({ > withdrawalStatus: PerpsKnownWithdrawalStatus.Pending, > }); > > for await (const page of pages) { > // page.items: PerpsWithdrawal[] > } > ``` > > For what each status means, see > [Withdrawals](/perps/account-management#withdrawals). > > For more details on authenticated sessions, see [Authenticated > Sessions](/perps/authenticated-sessions). > [tab] Python > > Request a withdrawal to the authenticated wallet. Amounts use raw pUSD base > units, so 10 pUSD is `10_000_000`. > > ```python theme={null} > withdrawal_id = await client.withdraw_from_perps(amount=10_000_000) > ``` > > The SDK signs the withdrawal request with the Polymarket account signer and > returns the Perps withdrawal ID. > > To track the withdrawal, open a Perps session and list withdrawals. > > ```python theme={null} > session = await client.open_perps_session() > > try: > pages = session.list_withdrawals() > withdrawals = await pages.first_page() > finally: > await session.close() > ``` > > To narrow the results to a single state, pass a `withdrawal_status` filter. > The filter accepts one status per request: `"pending"`, `"confirmed"`, > `"removed"`, or `"failed"`. For example, list the withdrawals that are still > pending: > > ```python theme={null} > pages = session.list_withdrawals(withdrawal_status="pending") > > async for page in pages: > # page.items: tuple[PerpsWithdrawal, ...] > pass > ``` > > For what each status means, see > [Withdrawals](/perps/account-management#withdrawals). > > For more details on authenticated sessions, see [Authenticated > Sessions](/perps/authenticated-sessions). > [tab] API > > **1. Build the Withdrawal Operation** > > Create a `withdraw` operation with the account signer, pUSD token, raw token > amount, and destination wallet. For withdrawals, `amount` is the raw pUSD token > amount, so 10 pUSD is `10000000`. > > ```json theme={null} > { > "type": "withdraw", > "args": { > "account": "", > "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "amount": "10000000", > "to": "" > } > } > ``` > > | Field | Value | > | - | - | > | `account` | Signer address for the Polymarket account. | > | `token` | pUSD collateral token address. | > | `amount` | Raw pUSD token amount. | > | `to` | Wallet that receives the withdrawal. | > > **2. Create Withdrawal Typed Data** > > The withdrawal signature uses EIP-712 typed data with `Withdraw` as the primary > type. Use the same `account`, `token`, `amount`, and `to` values from the > withdrawal operation. > > For withdrawals, `ts` is a Unix timestamp in seconds because the onchain contract > validates it against `block.timestamp`. It must match the `ts` value in the > request body. > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137, > "verifyingContract": "0xDCa4af75705dbB50f62437045afF9921947917d2" > }, > "primaryType": "Withdraw", > "types": { > "Withdraw": [ > { "name": "account", "type": "address" }, > { "name": "token", "type": "address" }, > { "name": "amount", "type": "uint256" }, > { "name": "fee", "type": "uint256" }, > { "name": "to", "type": "address" }, > { "name": "salt", "type": "uint64" }, > { "name": "ts", "type": "uint64" } > ] > }, > "message": { > "account": "", > "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "amount": "10000000", > "fee": "0", > "to": "", > "salt": 555555555, > "ts": 1767000014 > } > } > ``` > > | Field | Value | > | - | - | > | `salt` | Random integer generated for this signed request. | > | `ts` | Current Unix timestamp in seconds, not milliseconds. | > > **3. Sign Withdrawal Typed Data** > > Sign the typed data with the Polymarket account signer. The example below uses > Viem. > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount(""); > > const signature = await account.signTypedData({ > domain: { > name: "Polymarket", > version: "1", > chainId: 137, > verifyingContract: "0xDCa4af75705dbB50f62437045afF9921947917d2", > }, > primaryType: "Withdraw", > types: { > Withdraw: [ > { name: "account", type: "address" }, > { name: "token", type: "address" }, > { name: "amount", type: "uint256" }, > { name: "fee", type: "uint256" }, > { name: "to", type: "address" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > account: "", > token: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > amount: 10000000n, > fee: 0n, > to: "", > salt: 555555555n, > ts: 1767000014n, > }, > }); > ``` > > **4. Submit the Withdrawal** > > Submit the signed withdrawal request to `POST /v1/account/withdraw`. Use the > same operation values, `salt`, and `ts` from the typed data. > > ```bash theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/withdraw" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "withdraw", > "args": { > "account": "", > "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "amount": "10000000", > "to": "" > } > }, > "sig": "", > "salt": 555555555, > "ts": 1767000014 > }' > ``` > > The response indicates whether the withdrawal was accepted. > > ```json Success theme={null} > { > "status": "ok", > "withdraw_id": 1234567890 > } > ``` > > ```json Failure theme={null} > { > "status": "err", > "withdraw_id": 1234567890, > "error": "insufficient_balance" > } > ``` > > **5. Track the Withdrawal** > > Use the returned `withdraw_id` to match the withdrawal against history results. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "withdrawal_status=pending" > ``` > > The `withdrawal_status` filter accepts `pending`, `confirmed`, `removed`, or > `failed`. > > For more details on proxy credentials and private account-read headers, see > [Authenticated Sessions](/perps/authenticated-sessions). ## Transfer Between Your Accounts Move pUSD between two Perps accounts with an internal transfer. The transfer settles on the exchange ledger, with no onchain transaction and no fee. The source owner can transfer to another Perps account. Transfers are limited to withdrawable collateral after accounting for pending withdrawals and transfers. > [tab] TypeScript > > Use `client.transferPerpsCollateral()` on the owner-signed `SecureClient` from > [Set Up Perps Access](/perps/authenticated-sessions#set-up-perps-access). > > ```ts theme={null} > const transferId = await client.transferPerpsCollateral({ > recipient: "0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc", > amount: "250.50", > label: "rebalance-001", > }); > console.log(transferId); > ``` > > The result is a `PerpsInternalTransferId`. `amount` is decimal pUSD, and its exact > string is signed unchanged. Choose a recipient distinct from the owner's address. > `label` accepts 1 to 64 UTF-8 bytes and helps identify the transfer in history. > The SDK signs with the owner and attempts the submission once. > [tab] Python > > Use the API tab to submit an internal transfer. To read settled transfers with > Python, use the history workflow in **Reconcile a Transfer** below. > [tab] API > > Sign an internal transfer with the source account owner. When grouped-account > transfers are enabled for your deployment, a registered trading key can also sign: > > | Signer | When it can sign | > | - | - | > | Owner key of the source account | Always, to any destination Perps account. | > | Trading key (proxy) registered to the source account | When enabled and the source and destination belong to the same [account group](/perps/learn-about-trading/self-trade-prevention#account-groups). | > > The trading-key path lets a market maker running several grouped accounts > rebalance collateral from the key its trading system already holds, without > bringing the owner key online. Polymarket assigns account groups per entity; to > group your accounts, contact Polymarket with the list of accounts. A trading key > must be registered to the **source** account. A key registered to a different > member of the group does not qualify, and ungrouped accounts cannot use the > trading-key path. > > Trading keys can only move collateral between members of the same group. They > can never withdraw; withdrawals always require the owner key. > > **1. Build the Transfer Operation** > > Create an `internalTransfer` operation naming the source account, the pUSD > token, the amount and the destination account. > > ```json theme={null} > { > "type": "internalTransfer", > "args": { > "account": "", > "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "amount": "250.5", > "to": "" > } > } > ``` > > | Field | Value | > | - | - | > | `account` | Address of the source Perps account (its owner address). | > | `token` | pUSD collateral token address. | > | `amount` | pUSD amount as a decimal string, for example `"250.5"`. | > | `to` | Address of the destination Perps account (its owner address). | > > > [!WARNING] > > > > Internal transfer amounts are **decimal pUSD**, not raw token base units. > > `"250.5"` moves 250.5 pUSD. Withdrawals are different: their `amount` is raw > > base units. > > **2. Create the Operation Hash** > > Internal transfers use the same `Op` signing scheme as trading operations. Build > the compact operation, MessagePack-encode it, and hash the encoded bytes with > `keccak256`. > > ```ts theme={null} > ["internalTransfer", [account, token, amount, to]]; > ``` > > Use the exact strings you send in the request body, including address casing > and the amount string. Any difference changes the hash and the signature fails. > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const signableOperation = [ > "internalTransfer", > [ > "", > "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "250.5", > "", > ], > ] as const; > > const opHash = keccak256(encode(signableOperation)); > ``` > > **3. Create Transfer Typed Data** > > Create an EIP-712 `Op` typed-data payload with the operation hash. > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137 > }, > "primaryType": "Op", > "types": { > "Op": [ > { "name": "data", "type": "bytes32" }, > { "name": "salt", "type": "uint64" }, > { "name": "ts", "type": "uint64" } > ] > }, > "message": { > "data": "", > "salt": 345678901, > "ts": 1767000020000 > } > } > ``` > > | Field | Value | > | - | - | > | `data` | Operation hash from the previous step. | > | `salt` | Random integer generated for this signed request. | > | `ts` | Current Unix timestamp in milliseconds. | > > **4. Sign Transfer Typed Data** > > Sign with the source account's trading key for a transfer between grouped > accounts, or with the source account's owner key for any transfer. > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount(""); > > const signature = await account.signTypedData({ > domain: { > name: "Polymarket", > version: "1", > chainId: 137, > }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: opHash, > salt: 345678901, > ts: 1767000020000, > }, > }); > ``` > > **5. Submit the Transfer** > > Submit the signed request to `POST /v1/account/internal-transfer`. Use the same > operation values, `salt`, and `ts` from the typed data. `label` is optional, > up to 64 bytes, and sits outside the signed operation. It is returned in both > accounts' transfer history, which helps you reconcile your own rebalancing. > > ```bash theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/internal-transfer" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "internalTransfer", > "args": { > "account": "", > "token": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "amount": "250.5", > "to": "" > } > }, > "sig": "", > "salt": 345678901, > "ts": 1767000020000, > "label": "strategy-rebalance" > }' > ``` > > ```json Success theme={null} > { > "status": "ok", > "transfer_id": 5902406621022238 > } > ``` > > ```json Failure theme={null} > { > "status": "err", > "transfer_id": 5902406621022238, > "error": "insufficient_transfer_balance" > } > ``` > > | Response | Meaning | > | - | - | > | `insufficient_transfer_balance` | The amount, plus pending transfers and withdrawals, exceeds the source account's withdrawable pUSD. | > | `transfer_limit_reached` | The source account already has 10 pending transfers. | > | `transfer_to_self` | The source and destination are the same account. | > | `proxy_expired` | The trading key's expiry has passed. | > | `signer_does_not_match_account` | The signer is neither the source owner nor a trading key registered to the source, or the accounts are not in the same group. | > | HTTP 400 `destination account not found` | The destination address has no Perps account. | > | HTTP 503 `service_unavailable` with `Retry-After: 1` | The gateway could not confirm fresh account-group state. Nothing was submitted, so it is safe to retry. | > > Trading-key transfers can take slightly longer to accept than owner-key > transfers, because the gateway first confirms that its view of the key and the > group is current. This wait is capped at 500 ms. > > If a transfer request times out and you are unsure whether it was accepted, > resend the exact original signed request. Do not generate a new signature, > salt, or timestamp. See [Errors](/perps/errors). Transfers and withdrawals still pending count against the [withdrawable amount](/perps/learn-about-trading/margin#withdrawal-margin-requirements). Each source account can have up to 10 transfers waiting to be processed. If submission times out or returns a server error, the transfer may still have completed. Reconcile settled history before considering another submission. Labels help match records; they do not make transfers idempotent. A missing record does not prove failure, so do not automatically submit a new transfer. ### Reconcile a Transfer Use authenticated account history to locate the collateral movement and compare its recipient, amount, and direction with your intended transfer. > [tab] TypeScript > > Use `session.listInternalTransfers()` with the authenticated session from > [Set Up Perps Access](/perps/authenticated-sessions#set-up-perps-access). > > ```ts theme={null} > const pages = session.listInternalTransfers(); > > for await (const page of pages) { > for (const transfer of page.items) { > if (transfer.label === "rebalance-001") { > console.log( > transfer.transferId, > transfer.amount, > transfer.direction, > transfer.counterparty, > ); > } > } > } > ``` > > Each item is a `PerpsInternalTransfer`. `amount` is a decimal string in pUSD units; > `direction` is `"in"` or `"out"` relative to this account. `counterparty` is the > other account's owner address. > > The default window is the past 90 days. Set `start` and `end` in epoch milliseconds > to choose a window, or pass a returned `nextCursor` as `cursor` to resume it. > The paginator deduplicates overlapping records and raises `UnexpectedResponseError` > if a full millisecond cannot be paged without skipping records. > [tab] Python > > Use `session.list_internal_transfers()` with the authenticated session from > [Set Up Perps Access](/perps/authenticated-sessions#set-up-perps-access). > > ```python theme={null} > pages = session.list_internal_transfers() > > async for page in pages: > for transfer in page.items: > if transfer.label == "rebalance-001": > print( > transfer.transfer_id, > transfer.amount, > transfer.direction, > transfer.counterparty, > ) > ``` > > Each item is a `PerpsInternalTransfer`. `amount` is a `Decimal` in pUSD units; > `direction` is `PerpsInternalTransferDirection.IN` or > `PerpsInternalTransferDirection.OUT`. `counterparty` is the other account's owner > address. > > The default window is the past 90 days. Set `start` and `end` using datetimes or > epoch milliseconds, or pass a returned `next_cursor` as `cursor` to resume its > saved bounds. The paginator deduplicates overlapping records and raises > `UnexpectedResponseError` if a full millisecond cannot be paged without skipping > records. > [tab] API > > List settled transfers using the private account-read headers from > [Authenticated Sessions](/perps/authenticated-sessions). > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/internal-transfers" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "direction=out" > ``` > > > [accordion] Output: Internal Transfer History > > > > ```json theme={null} > > { > > "data": [ > > { > > "transfer_id": 4, > > "type": "transfer", > > "asset": "pUSD", > > "amount": "1.23000000000000000001", > > "direction": "out", > > "counterparty": "0x9965507D1a55bcC2695C58ba16FB37d819B0A4dc", > > "label": "rebalance-001", > > "created_timestamp": 1002 > > } > > ], > > "more": false > > } > > ``` > > The response contains `data` and `more`. Each record includes `transfer_id`, > `amount`, `direction`, `counterparty`, `type`, optional `label`, and > `created_timestamp`. Compare `label` with the value sent during submission. > Use `direction=in` or `direction=out` to narrow the results; omit it for both. > `start_timestamp` and `end_timestamp` accept epoch milliseconds. The API does not > accept a pagination cursor. An interrupted or incomplete history read does not establish whether a transfer failed. Complete reconciliation before deciding whether to submit again. ## Review Funding History Use deposit and withdrawal history to reconcile collateral movements after your integration submits funding requests. See [Authenticated Sessions](/perps/authenticated-sessions) for how to create an authenticated session for private account history reads. > [tab] TypeScript > > List deposit or withdrawal history from an authenticated Perps session. > > ```ts Deposits theme={null} > import type { PerpsDeposit } from "@polymarket/client"; > > const session = await client.openPerpsSession(); > > try { > const deposits: PerpsDeposit[] = []; > const pages = session.listDeposits(); > > for await (const page of pages) { > deposits.push(...page.items); > } > } finally { > await session.close(); > } > ``` > > ```ts Withdrawals theme={null} > import type { PerpsWithdrawal } from "@polymarket/client"; > > const session = await client.openPerpsSession(); > > try { > const withdrawals: PerpsWithdrawal[] = []; > const pages = session.listWithdrawals(); > > for await (const page of pages) { > withdrawals.push(...page.items); > } > } finally { > await session.close(); > } > ``` > [tab] Python > > List deposit or withdrawal history from an authenticated Perps session. > > ```python Deposits theme={null} > session = await client.open_perps_session() > > try: > deposits = [] > pages = session.list_deposits() > > async for page in pages: > deposits.extend(page.items) > finally: > await session.close() > ``` > > ```python Withdrawals theme={null} > session = await client.open_perps_session() > > try: > withdrawals = [] > pages = session.list_withdrawals() > > async for page in pages: > withdrawals.extend(page.items) > finally: > await session.close() > ``` > [tab] API > > List deposit history. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/deposits" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > List withdrawal history. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/withdrawals" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > Use the optional `deposit_status`, `withdrawal_status`, `start_timestamp`, and > `end_timestamp` query parameters when reconciling a specific window. # Architecture Source: https://docs.polymarket.com/perps/learn-about-trading/architecture High-level architecture of the Polymarket Perps exchange Polymarket Perps is a hybrid exchange: matching happens offchain for speed, while custody and settlement live on Polygon. Exchange state is periodically committed onchain so offchain activity remains verifiable. ## Offchain Matching When a trader places an order, the matching engine maintains the order book, applies risk checks, matches orders, and updates balances, positions, margin, and funding offchain. This gives the exchange its latency profile because matching does not wait on block times. Orders are authorized by the trader, so the system can only act on trades the trader approved. ## Onchain Components The following operations are onchain and settle on Polygon: * Deposits move funds from a user's Polymarket wallet into the exchange and credit their Perps account. * Withdrawals move funds out of the exchange back to a user's Polymarket wallet. Deposits and withdrawals are the only way assets enter or leave the exchange. Trading itself does not produce per-trade onchain transactions. ## State Root Commitments The exchange periodically commits its trading state onchain in the form of state root commitments. A state root summarizes the offchain ledger at a point in time, including account balances, and lets observers verify that reported exchange state matches what Polymarket has committed to Polygon. ## Data Flow 1. A trader deposits collateral from their Polymarket wallet into the exchange, crediting their Perps account. 2. The engine credits the deposit and opens the account for trading. 3. The trader authorizes and places orders. 4. The engine matches orders and updates state offchain. 5. The engine publishes state root commitments onchain on a recurring cadence. 6. The trader authorizes a withdrawal, and funds move back to their Polymarket wallet on Polygon. # Fees Source: https://docs.polymarket.com/perps/learn-about-trading/fees Tiered maker and taker trading fees for Polymarket Perps Perps trading fees are tiered by an account's trailing 30-day trading volume. Higher-volume accounts pay lower taker fees, and the top tier earns a maker rebate instead of paying a maker fee. ## Fee Calculation For each fill, the fee is calculated on the notional value of the trade: ```text theme={null} Fee = abs(Price * Quantity) * Rate ``` Fees are denominated in the instrument's quote asset (pUSD). The rate applied to a fill is set by the account's current volume tier. | 30-Day Volume ≥ | Taker | Maker | | - | - | - | | \$0 | 0.0400% | 0.0125% | | \$1M | 0.0370% | 0.0100% | | \$5M | 0.0350% | 0.0080% | | \$25M | 0.0300% | 0.0050% | | \$100M | 0.0270% | 0.0020% | | \$500M | 0.0250% | 0.0000% | | \$1B | 0.0200% | -0.0050% | New accounts start at the \$0 tier and move up as trailing 30-day volume crosses each threshold. Fee tiers are re-evaluated every UTC day. A negative maker fee is a rebate: the maker receives the rebate amount, and the fee recipient's internal ledger is debited by the same amount. > [!NOTE] > > A subset of accounts created during the Perps beta are temporarily on the > top-tier fee schedule regardless of trailing 30-day volume. Standard > volume-based tiering applies to these accounts once the transition period > ends. If you're integrating Perps, read the current fee schedule from [Trading Fees](/perps/trading#trading-fees) and your account's current tier from the [portfolio](/perps/account-management#portfolio). ## Fee Metrics Trailing 7-day activity metrics are available for visibility. They are a rolling view of recent activity and do not, on their own, determine the volume tier used to set fees. | Metric | Meaning | | - | - | | Total volume | Total Perps trading volume | | Taker volume | Perps volume that removed liquidity | | Maker volume | Perps volume that added liquidity | | Account maker share | Account maker volume divided by total exchange volume | | Entity maker share | Entity maker volume divided by total exchange volume, when the account has one | These metrics are cached by UTC day and may be stale by up to 24 hours. If you're integrating Perps, read account metrics from [Account Stats](/perps/account-management#account-stats). ## Fee Accounting Each fill's exchange fee flows through the exchange fee-recipient account on the internal ledger: * Taker fees credit the recipient. * Maker fees credit the recipient at every tier where the maker rate is non-negative. * At the top tier the maker rate is a rebate, so it debits the recipient and credits the maker. ## Builder Fees Orders placed through an enabled builder can carry an additional trader-approved fee of up to 10 basis points. This fee is separate from the exchange schedule above. Use the total fee when displaying a trader's cost. See [Builder Attribution](/perps/builder-codes) for consent, saved order terms, and earnings. # Funding Source: https://docs.polymarket.com/perps/learn-about-trading/funding Funding rate calculation and settlement Unlike futures contracts, perpetuals have no expiry date. Funding is the mechanism that keeps the perpetual price anchored to the underlying's fair value. When the perpetual trades above Index, longs pay shorts. When it trades below Index, shorts pay longs. Funding runs continuously across all sessions, regardless of whether the underlying reference market is open. This keeps the convergence incentive active and prevents positions from being left unanchored from fair value. ## How Funding Works Funding is computed in three stages: 1. A premium index is sampled from the order book every 5 seconds. 2. Samples are averaged over the 1-hour charge window to produce an hourly rate. 3. The rate is settled against every open position at the end of the window. ### Premium Index Every 5 seconds, the protocol takes one snapshot per market of how far the book has drifted from Index. It walks the book for a fixed quote notional on each side. ```text theme={null} bid_impact = VWAP of top bids filling 1,000 quote notional ask_impact = VWAP of top asks filling 1,000 quote notional ``` If one side of the book cannot fill the notional because it is too thin or empty, that side falls back to Index, which zeros its contribution. The impact price difference and premium index are: ```text theme={null} IPD = max(bid_impact - Index, 0) - max(Index - ask_impact, 0) PremiumIndex = IPD / Index ``` A positive premium means the perpetual is trading rich versus Index. A negative premium means it is trading cheap. ### Funding Rate At the end of each charge window, premium samples are averaged, passed through the 8-hour funding formula, divided by 8 to get an hourly rate, and capped. ```text theme={null} mean_P = average of PremiumIndex samples over the window scale = 1.0 for crypto markets; 0.5 otherwise F_8h = scale * (mean_P + clamp(0.0001 - mean_P, +/-0.0005)) FR_hour = clamp(F_8h / 8, +/-0.04) ``` * The 0.01% term is a fixed interest leg per 8 hours. * The +/-0.05% clamp bounds the interest-versus-premium adjustment. * Crypto markets use a 1.0 scale. * Non-crypto markets use a 0.5 scale. * The 4% per hour cap prevents extreme funding during sustained dislocation. ### Payment At the end of each charge window, every open position in the market settles a funding payment proportional to position size and the hourly rate. | Condition | Longs | Shorts | | - | - | - | | Hourly rate > 0, perp rich vs Index | Pay | Receive | | Hourly rate \< 0, perp cheap vs Index | Receive | Pay | Funding is a direct transfer between longs and shorts. The protocol takes no cut. Settlement credits or debits the quote balance, and realized funding is tracked separately from trading PnL. ### Interval The charge window is 1 hour. Samples are averaged over the hour, and the hourly rate is applied once at the end. Between settlements, rolling premium samples and implied rates are published so traders can see funding pressure build in real time. ## Parameters | Parameter | Default | Description | | - | - | - | | Sample interval | 5 seconds | Cadence of premium index samples | | Impact notional | 1,000 quote notional | Quote notional used for impact VWAP | | Interest leg | 0.01% per 8 hours | Fixed component in the 8-hour formula | | Interest clamp | +/-0.05% | Symmetric clamp on interest minus premium | | Funding scale | 1.0 crypto; 0.5 otherwise | Multiplier applied to the 8-hour formula | | Charge window | 1 hour | Interval between funding settlements | | Funding rate cap | 4% per hour | Maximum absolute hourly funding rate | # Index Price Source: https://docs.polymarket.com/perps/learn-about-trading/index-price How the Index Price is computed for Perps Index Price is Polymarket's estimate of the underlying asset's fair value. It is computed from external price feeds, aggregated to resist stale or anomalous inputs, and published every 200 milliseconds per market. ## Feed Sources Index Price can use feeds from external sources such as: * Pyth * Chainlink Data Streams * Hyperliquid ## Feed Selection The system selects different feeds based on the current market session so it can use the most accurate feed set for each market. See [Market Sessions](/perps/learn-about-trading/market-sessions). ## Aggregation Index Price is computed as a weighted average across the selected feeds after dropping stale prices and filtering outliers. This prevents any single stale or anomalous feed from moving the Index. The same aggregation approach is used to build the [C3 candidate in Mark Price](/perps/learn-about-trading/mark-price), using a separate mark feed set. # Liquidation Mechanics Source: https://docs.polymarket.com/perps/learn-about-trading/liquidation-mechanics Detection, execution, insurance-fund backstop, and auto-deleveraging When a trader's equity drops below maintenance margin, the system closes the position before it becomes insolvent. Normal liquidations route through the order book as reduce-only immediate-or-cancel orders. If the breach is severe, the position is absorbed directly by the insurance fund — or, when the fund cannot safely take it on, closed against opposite-side traders through auto-deleveraging. ## Trigger An account or isolated position is at risk when: ```text theme={null} MarginRatio = Equity / MaintenanceMargin ``` Liquidation starts when `MarginRatio < 1.0`, which means `Equity < MM`. Cross and isolated positions are checked independently: * Cross uses the account's cross equity and combined cross maintenance margin. * Isolated evaluates each isolated position using its own equity and maintenance margin. Margin health is re-evaluated continuously, so the system reacts as soon as a new Mark Price, fill, or deposit moves the account across the threshold. ## While Liquidating When liquidation starts, the affected scope is flagged: * Cross liquidation blocks new orders on every market for the account. * Isolated liquidation blocks new orders only on the affected market. Order submissions from the account are rejected while the flag is set. The system also cancels the account's resting orders inside the same scope before it places the first liquidation order: cross liquidation cancels resting orders on every cross-margined market but leaves isolated markets untouched, while isolated liquidation cancels only the orders on the affected market. These cancels race in-flight executions, so a resting order can still fill in the moment between the flag being set and its cancel applying. Any maker or taker fill on an instrument in the account's active liquidation scope reports `liquidation: true` in the account's fill history and `liq: true` on the WebSocket `fills` channel. ## Execution The system closes flagged positions with reduce-only immediate-or-cancel orders. These orders execute immediately against available liquidity and cancel any unfilled quantity. Margin health is re-evaluated between orders, so partial fills that restore the account naturally stop the process. ### Target Selection Cross liquidation closes one position at a time. After each fill settles, the system re-evaluates and picks again from the remaining cross positions, so a trader with multiple cross positions is unwound across several cycles rather than all at once. Isolated liquidation closes the flagged position in full. ### Order Shape Liquidation orders are IOC, reduce-only, and market-priced. They sweep whatever liquidity is resting on the book at the moment they land. There is no protective spread off Mark. ## Recovery When a liquidating account's equity recovers to or above its recovery initial margin, the flag clears and normal order submission resumes. If a position is fully closed during liquidation, the flag is also cleared because the market no longer has a position to liquidate. ## Insurance-Fund Backstop If equity falls far enough below maintenance margin that order-book liquidation is unlikely to recover value, the system skips the order book and absorbs the position into the insurance fund. * Cross backstop absorbs all of the trader's cross positions plus their quote-asset balance into the insurance-fund account. * Isolated backstop absorbs the specific isolated position and its allocated isolated margin. Once absorbed, the insurance fund holds the position and manages it like any other account. The margin that leaves the trader's account with an absorption is recorded as a cash transfer, separate from fills, funding, and deposits. Retrieve it with [Get Account Backstop Transfers](/api-reference/get-account-backstop-transfers) to reconcile balance changes after a backstop liquidation. The backstop only fires when the fund can take the position on and remain healthy itself — its equity after absorbing must stay at or above its own maintenance margin. When it cannot, the system auto-deleverages instead. ## Auto-Deleveraging If a breach is severe enough for the backstop but the insurance fund cannot safely absorb the position, the system force-closes it directly against traders holding the opposite side. This is auto-deleveraging (ADL): no order-book matching, no draw on the insurance fund. An isolated liquidation deleverages the affected market only. A cross liquidation deleverages every open cross position the account holds. ### Counterparty Selection For each affected market, opposite-side positions are ranked by: ```text theme={null} AdlIndex = ProfitRatio * Notional / Equity ``` * `ProfitRatio` is `Mark / Entry` for longs and `Entry / Mark` for shorts. * `Notional / Equity` is effective leverage: position notional at Mark over cross equity for a cross position, or over the position's own equity for an isolated position. The most profitable, most leveraged counterparties rank first. The system works down the queue, reducing each counterparty in turn, until the liquidated position is fully closed. A counterparty position is only ever reduced — never flipped to the other side or increased. Accounts that are themselves liquidating, and the insurance fund, are never selected. While a counterparty is being deleveraged, its new orders on that market are rejected, exactly as during liquidation. The block clears automatically once the deleveraging completes. ### Execution Price * An isolated liquidation deleverages at the liquidated position's bankruptcy price — the price at which its isolated margin is exactly exhausted. * A cross liquidation deleverages at the Mark Price frozen when the liquidation started, not the live mark. Both legs settle at this price, and each side's realized PnL is credited to its quote balance. ### What Counterparties See * The fill arrives on the WebSocket `fills` channel and in trade history with `adl: true`. The `liq` flag marks only the leg whose own position is being liquidated, so it stays `false` on the counterparty leg. * A `position_deleveraged` [notification](/perps/notifications) reports the market, side, size closed, execution price, and realized PnL. ## Fees The liquidating account pays an extra liquidation fee on every fill while flagged, on top of its normal maker or taker rate. ```text theme={null} FillFee = Notional * (MakerOrTakerRate + LiquidationFeeRate) ``` Liquidation fee rates vary by market. If you're integrating Perps, read current values from [Market Data](/perps/market-data#fetch-instruments). Auto-deleveraging fills bypass the order book and carry no fee for either side. # Margin Source: https://docs.polymarket.com/perps/learn-about-trading/margin Initial margin, maintenance margin, equity, margin modes, and withdrawal requirements Margin is the collateral required to open and maintain leveraged positions. It ensures traders have enough collateral to cover potential losses and gives the system a buffer to close positions before they become insolvent. Trading uses two thresholds. **Initial margin (IM)** is the collateral required to open or increase a position. **Maintenance margin (MM)** is the minimum collateral required to keep a position open. When equity drops below maintenance margin, the position is [liquidated](/perps/learn-about-trading/liquidation-mechanics). ## Equity Equity is the real-time value of an account, incorporating all open positions at current Mark Price. ```text theme={null} Equity = Collateral + UnrealizedPnL(Mark) - FeesDue - FundingDue ``` ### Unrealized PnL ```text theme={null} Long PnL = PositionSize * (Mark - EntryPrice) Short PnL = PositionSize * (EntryPrice - Mark) ``` Because equity depends on Mark Price, equity follows live mark updates. See [Mark Price](/perps/learn-about-trading/mark-price). ## Margin Requirements Initial margin is set by your configured leverage: ```text theme={null} IM = Notional / Leverage ``` Leverage tiers cap the leverage available as your position grows — larger positions must run at lower leverage and therefore post proportionally more initial margin. The cap is enforced against your worst-case position notional (position plus resting orders on the heavier side): an order that would grow it into a tier whose `max_leverage` is below your configured leverage is rejected with `invalid_leverage`, and you must lower your leverage setting first. Your configured leverage applies to your entire notional, not bracket by bracket. Fetch each market's tier schedule from [Market Data](/perps/market-data#fetch-instruments). Maintenance margin uses a flat per-market rate, independent of position size, tier, and your leverage setting: ```text theme={null} MM = Notional × MMR where MMR = 0.5 / MaxLeverage ``` `MaxLeverage` is the market's maximum leverage, so on a 20x market `MMR = 2.5%` for every position. MM equals half the initial margin of a position opened at max leverage; at lower leverage your IM is higher but MM stays the same, so the gap between entry requirement and liquidation grows. Margin requirements are static across sessions. ## Default Leverage and Margin Mode Every position uses one of two margin modes. **Cross margin** backs the position with the account's shared free collateral. **Isolated margin** backs the position only with the collateral allocated to it. The exchange may assign your account to a group with shared leverage or margin defaults. Each setting resolves independently for each instrument: | Priority | Leverage | Margin Mode | | - | - | - | | 1 | Your explicit per-instrument setting | Your explicit per-instrument setting | | 2 | Your account group's default, capped at the instrument maximum | Your account group's default; cross resolves to isolated on isolated-only instruments | | 3 | The instrument's maximum leverage | Isolated margin | Group defaults also apply to future listings. An explicit per-instrument setting is retained when group defaults or membership change. Set your preferred leverage and margin mode after the instrument is listed and before placing your first order, using [Update Leverage](/perps/trading#update-leverage). Account configuration reads report the resolved values; an update sets both values explicitly. Setting the current resolved pair explicitly preserves it against later group changes. Before switching between isolated and cross margin: * Close the position in that instrument. * Cancel all orders in that instrument, including orders awaiting risk approval or execution. * Check that the instrument supports the requested margin mode. Leverage changes within the same mode still require sufficient margin and a positive leverage no greater than the instrument maximum. If the account is subscribed to the Backstop Liquidity Provider program for that instrument, unsubscribe before updating either setting, even to re-submit the current pair. ## Margin States An account is always in one of three states. | State | Condition | What Happens | | - | - | - | | Healthy | `Equity >= IM` | Normal trading | | Margin call | `MM <= Equity < IM` | Can only reduce exposure or deposit collateral | | Liquidation | `Equity < MM` | The system begins closing the position | ## Margin Checks ### Pre-Trade Before any order executes, the system verifies the account can afford it: 1. Compute the new position after the order fills. 2. Calculate required initial margin using the market's leverage tiers. 3. Reject the order if equity is below required initial margin. This prevents accounts from entering a margin-call state through new trades. ### Continuous Monitoring The system continuously evaluates accounts: * If equity falls below maintenance margin, liquidation begins. * If equity is between maintenance margin and initial margin, the account may enter reduce-only mode. ## Deposits and Withdrawals Deposits increase equity. A deposit during margin call can restore the account to healthy status immediately. ### Withdrawal Margin Requirements Withdrawals must leave enough collateral to cover existing margin commitments and at least **10% of the total notional value of all open positions**: ```text theme={null} TotalPositionValue = sum(abs(PositionSize) * MarkPrice) WithdrawalMarginRequired = max(CollateralReserved, 0.1 * TotalPositionValue) ``` `TotalPositionValue` includes both cross and isolated positions at current Mark Price. `CollateralReserved` covers cross-position initial margin, isolated collateral allocations, and margin and fee reserves for accepted open orders. For a cross-only account with no open orders, it equals required initial margin. The 10% floor applies to withdrawals, independently of the leverage used to open a position. It does not increase the opening-margin requirement or change the maintenance-margin threshold for liquidation. For example, assume a \$100 position at 20x, no other positions or orders, and no fees, funding, or unrealized PnL: ```text theme={null} InitialMargin = $100 / 20 = $5 WithdrawalMarginRequired = max($5, 0.1 * $100) = $10 ``` With \$20 of collateral, \$10 is available for withdrawal. With only \$5 of collateral, the position can open, but nothing is available for withdrawal. In this example, the floor is stricter than initial margin above 10x leverage; at 10x or below, initial margin already covers the floor. > [accordion] How is the withdrawable balance calculated? > > The account's withdrawal capacity in USD is: > > ```text theme={null} > WithdrawalEquity = CollateralValue + CrossUnrealizedPnL > Withdrawable = max(0, WithdrawalEquity - WithdrawalMarginRequired - PendingOrderMargin) > ``` > > `CollateralValue` is the account's valued collateral. `CrossUnrealizedPnL` > includes only cross positions; isolated unrealized PnL is not added to > withdrawal equity. `PendingOrderMargin` is the additional initial margin > reserved for orders still awaiting risk checks. > > Use the returned `withdrawable` value from [Get Portfolio](/api-reference/get-portfolio) > rather than subtracting initial margin from account equity. A withdrawal is > also limited by the balance of the asset being withdrawn and is checked again > when processed. ## Adjusting Isolated Margin For each position, `initial_margin` reports the collateral currently backing the position. For cross positions, it is the required initial margin based on position size, Mark Price, the applicable risk tier, and configured leverage. For isolated positions, it is the position's current equity: ```text theme={null} InitialMargin = SignedAllocation + UnrealizedPnL - SettledFunding ``` The isolated value is a point-in-time snapshot that changes with Mark Price and funding. The legacy `initial_margin` name is retained for API compatibility; `margin` would describe this value more accurately. A positive margin adjustment moves free account collateral into the isolated allocation. A negative adjustment releases value back to free collateral and may include unrealized profit, so the signed allocation itself can reach zero or become negative. The request is accepted only when the resulting position equity remains at or above current required initial margin. Removing isolated margin releases collateral within the account. This uses the position's initial-margin check above; withdrawing the released collateral from the account must also satisfy the [withdrawal margin requirements](#withdrawal-margin-requirements). Both additions and removals are blocked while the account is in cross liquidation or the target position is in isolated liquidation. An isolated liquidation on a different instrument does not block the request. Cancel-only mode does not gate margin adjustments. # Mark Price Source: https://docs.polymarket.com/perps/learn-about-trading/mark-price How the Mark Price is computed for Perps Mark Price is the price used across the system for margin, unrealized PnL, liquidation triggers, funding premium computation, and risk checks. It is updated every 200 milliseconds. Mark Price is computed as the median of three candidates, each capturing a different view of fair value. ```text theme={null} Mark = median(C1, C2, C3) ``` ## C1: Smoothed Order Book Mid C1 anchors to Index and adjusts gradually based on where the local order book mid is trading relative to it. ```text theme={null} C1 = Index + EMA(Mid - Index) ``` * `Mid = (BestBid + BestAsk) / 2` when both sides of the book exist. * The EMA uses a 150-second window, so C1 moves slowly and resists short-term manipulation. * If the order book mid is unavailable, C1 falls back to Index. ## C2: Local Market Activity C2 reflects what is actually trading on the local book. ```text theme={null} C2 = median(BestBid, BestAsk, LastTrade) ``` * Last trade is only included if it is recent. * Stale trades are excluded so one old print cannot anchor the price. * If no usable values exist, C2 falls back to Index. ## C3: Aggregated External Mark C3 is built from external mark feeds, separate from Index feeds, that provide an independent view of fair value outside the local order book. For each market, the system: 1. Selects active mark feeds from eligible external sources. 2. Drops stale samples. 3. Computes the candidate median and filters outliers beyond the allowed tolerance. 4. Returns the weighted average of the remaining samples. If no valid external mark data is available, C3 falls back to Index. ## Why Three Candidates? Using the median of three independent price signals provides resilience: * C1 is slow-moving and resistant to sudden order book manipulation, but can lag during fast moves. * C2 is responsive to real local trading activity, but can be influenced by thin liquidity. * C3 is independent of the local book, but depends on external feed availability. The median ensures that no single signal can unilaterally move Mark Price. At least two of the three candidates must agree for the mark to shift. ## Finalization After computing `median(C1, C2, C3)`, the raw mark is normalized before being published: * Snapped to the nearest tick size * Rounded to the market's price precision ## Fallback Summary Every input degrades gracefully to [Index Price](/perps/learn-about-trading/index-price). | Condition | Behavior | | - | - | | Index input stale | Falls back to last known market index | | Order book mid unavailable | C1 falls back to Index | | No recent trades or quotes | C2 falls back to Index | | External mark feeds unavailable | C3 falls back to Index | | All inputs missing | Mark tracks Index because all candidates fall back to Index | In the worst case, when there is no local book, no recent trades, and no external mark feeds, all three candidates converge to Index and Mark Price tracks Index directly. # Market Sessions Source: https://docs.polymarket.com/perps/learn-about-trading/market-sessions How session state affects pricing feed selection Perps trade 24/7, but the underlying markets do not. Liquidity and external price feed availability vary by time of day and day of week. Sessions are the system's categorization of these conditions. ## What Sessions Affect Sessions affect one thing: which set of external feeds is used to compute [Index Price](/perps/learn-about-trading/index-price) and the [C3 candidate in Mark Price](/perps/learn-about-trading/mark-price). Each category can use its own feed set. For example, primary venue feeds may be used during regular hours and after-hours venue feeds may be used overnight. If the current category has no dedicated feed set, the system falls back to the overnight feed set. ## What Sessions Do Not Affect Sessions do not change: * Funding * Margin and leverage tiers * Order matching * Liquidation triggers Those systems run identically around the clock. ## Categories * Regular: the underlying is open and primary feeds are available. * Overnight: the underlying is closed but some external feeds may still exist. * Weekend: a calendar-based closed period with thin or absent external data. * Disrupted: external feeds are unavailable or failing sanity checks. * Halted: a trading halt or corporate-action freeze on the underlying. ## How the Category Is Determined Each market has a schedule that defines its time windows and exceptions. The system evaluates the schedule on time boundaries to produce the current category. When the category changes, subsequent Index and Mark updates use the feed set assigned to the new category. # Markets Source: https://docs.polymarket.com/perps/learn-about-trading/markets Listed perpetual markets and trading parameters Polymarket Perps markets track underlying assets across indices, commodities, crypto assets, and equities. Each market has its own trading parameters. ## Instruments Perps markets are represented by instruments, which are the listed perpetual contracts available to trade. Each instrument also includes details that shape how it trades: * Underlying asset * Collateral and quote asset * Price and quantity precision * Tick size * Minimum order size * Risk tiers and leverage caps * Mark, index, and funding configuration > [!NOTE] > > Market parameters can change as markets evolve. Builders should read live > instrument details from [Market Data](/perps/market-data#fetch-instruments) > before submitting orders. ## Price Feeds Each market tracks an underlying market through external price feeds. Those feeds drive the [Index Price](/perps/learn-about-trading/index-price), and the Index Price helps anchor the [Mark Price](/perps/learn-about-trading/mark-price). ## Pre-IPO Markets Pre-IPO perpetuals track a private company's valuation before it lists. Each pre-IPO market has its own specification page covering its price sources, contract terms, and what happens when the company goes public. > [card] [Anthropic (ANT)](/perps/learn-about-trading/markets/pre-ipo-anthropic) > > Specifications and the November 16 rebase to a per-share market. # Anthropic (ANT): Pre-IPO Specifications Source: https://docs.polymarket.com/perps/learn-about-trading/markets/pre-ipo-anthropic Specifications for active Polymarket Pre-IPO perpetual futures markets. ## Overview Pre-IPO Perpetuals are cash-settled, non-expiring contracts that let traders take a view on a private company’s valuation 24/7, without holding shares or accessing gated secondary markets. Positions confer no equity: no voting rights, dividends, information rights, IPO allocation, or claim on the issuer. Because private rounds rarely disclose a reliable share count, contracts are priced by total valuation: \$1 of price equals \$1B in fully diluted value (e.g. 1,650 = \$1.65T). Markets are margined and settled in pUSD. ANT’s reference price comes from Entropy’s Anthropic pre-IPO market on Hyperliquid. On Monday, November 16, 2026, ahead of Anthropic’s expected November 19 IPO, ANT will rebase to a per-share equity perpetual priced from Pyth’s ANT/USD feed, without delisting (see *What Happens Post-IPO?* below). ### How pricing works before the split This section covers ANT until the November 16 rebase, after which it is priced from Pyth as a standard equity perpetual. * **Index price:** Polymarket’s reference price, published every 200 ms. For ANT, this is Entropy’s oracle price for its Anthropic market on Hyperliquid (`io:ANTH`), which blends a 5-minute EMA of Entropy’s order-book mid with an aggregate of private-market sources (other derivatives, private marks, funding rounds, secondary trades), clipped to fixed catastrophic bounds. [Entropy methodology](https://docs.entropy.io/pre-ipo-perp-mechanics/oracle-price) * **Mark price:** Used for PnL, margin, liquidations and TP/SL triggers; updated every 200 ms. It is the median of: (1) the Index adjusted by a 150-second EMA of our book mid’s spread to the Index; (2) the median of our best bid, best ask and last trade; and (3) Entropy’s mark for `io:ANTH`. Unavailable inputs fall back to the Index. [Mark price](/perps/learn-about-trading/mark-price) * **Funding:** Polymarket’s standard funding. Every 5 seconds we sample our book’s premium (impact prices for 1,000 pUSD notional) versus the Index. Hourly, samples are averaged, run through the 8-hour formula with a 0.5 non-crypto scale, divided by 8, and capped at ±4%/hour. Paid hourly, peer-to-peer: longs pay shorts when the perp trades above the Index, and vice versa. [Funding](/perps/learn-about-trading/funding) * **Oracle bounds:** Entropy clips its oracle and mark to fixed catastrophic bounds, which shouldn’t bind normally. They affect ANT only via the Entropy prices we read; our Mark isn’t clipped directly. [Entropy methodology](https://docs.entropy.io/pre-ipo-perp-mechanics/oracle-price) * **Pre-listing window:** Three calendar days before an announced listing, Entropy’s oracle switches to a 1-hour EMA of its mark (bounds still applied). For a November 19 listing, this likely starts early on November 16 (UTC), so it may affect ANT’s Index for several hours before our switch to Pyth that morning. If Entropy rebases or changes its methodology before then, we may move the switch earlier and will give as much notice as possible. ## Specifications | Parameter | Asset | | - | - | | Market | ANT (API symbol `ANT-USD`) | | Status | Live (since October 29, 2026) | | Description | ANT references the fully diluted equity valuation of Anthropic, PBC, quoted in USD with \$1 of price = \$1B of valuation. ANT is currently a pre-IPO market. On Monday, November 16, 2026, it will be rebased via stock split to reference 1 share of Anthropic, PBC Class A common stock (Nasdaq: ANT), quoted in USD and priced from Pyth. Anthropic develops frontier AI models and the Claude family of AI products. | | Quote Unit | \$1 = \$1B fully diluted valuation until the November 16 split; USD per share after | | Collateral | pUSD | | Trading Hours | 24/7 | | Price / Size Precision | 0.1 price; 0.00001 size; \$10 minimum order notional (may change after the split) | | Oracle (until split) | Entropy’s oracle price for its Hyperliquid market `io:ANTH`; Entropy’s mark is one of three Mark price inputs | | Oracle (from split) | Pyth ANT/USD, per-share, 24/7 (ID: 3618). Rebased Nov 11, 22:00 UTC to the fully diluted share count in Anthropic’s amended S-1 (factor 0.94025511). The same feed continues through the IPO, with the Nasdaq price as its leading input once trading opens. | | Initial Price | 1,805.20 (\$1.81T valuation) | | Oracle Bounds (Lower / Upper) | 300 / 4,200 (\$300B / \$4.2T); Entropy’s bounds, removed at the split | | Funding | Standard non-crypto formula (0.5 scale); paid hourly, capped at ±4%/hour | | Margin Mode | Cross & Isolated | | Max Leverage | 10x, tiered by position notional: 10x to \$500K, 5x to \$1M, 3x to \$3M, 2x to \$5M, 1x above | | Maintenance Margin | 5% | | Anticipated Listing Event | IPO on Nasdaq Global Select Market (ticker ANT) | | Anticipated Listing Date | November 19, 2026 (pricing expected November 18) | | Rebase (Stock Split) | Monday, November 16, 2026, \~10:00am ET (target). Ratio = fully diluted share count from the amended S-1 ÷ 1B, announced in advance | | No-IPO Resolution Date | August 18, 2028 ([details](https://docs.entropy.io/pre-ipo-perp-mechanics/no-ipo-resolution)) | ## What Happens Post-IPO? ### Rebasing to share price with a stock split Before the split, ANT is quoted in valuation terms (\$1 = \$1B). On Monday, November 16, Polymarket uses its stock split feature to rebase the market so that it references 1 share of Anthropic Class A common stock, quoted in USD, and switches its price feed from Entropy to Pyth. This happens on the existing market: there is no delisting or relisting, and open positions and history carry over. The split ratio is the fully diluted share count divided by 1 billion, applied exactly (not rounded) and announced in advance. At the split: * Position sizes are multiplied by the ratio and rounded toward zero at the market’s size precision. Any leftover fraction (well under one lot) moves to the insurance fund. * Entry prices and the market price are divided by the ratio. * Position value and unrealized PnL are unchanged apart from that rounding. The conversion realizes no PnL and charges no fee. * Each converted position gets a split-adjustment entry in trade history showing size and entry price before and after. * Charts, mark history and 24h stats, including pre-split history, are shown in per-share terms, so there’s no artificial price drop. Past trades keep their original prices. The fully diluted share count is taken on the same basis as Entropy’s methodology: the total as-converted, fully diluted share count stated in the company’s filing (for Anthropic, the “Total Class A and Class N Common Stock (As-Converted, Fully Diluted)” figure in its amended S-1 filed November 10, 2026), assuming no exercise of the underwriters’ option. Because this count is fully diluted, the implied market cap may differ from the figure shown by public data providers, which typically use shares outstanding. For example, at the top of Anthropic’s \$70–78 range, reported valuations were about \$1.4T fully diluted versus about \$1.02T on shares outstanding. ### The trading pause There will be a brief trading pause while the split is applied. We will announce the time and split ratio in advance. The pause has three phases: 1. **Paused.** All ANT orders, including TP/SL, are cancelled and not restored; new orders are refused. Funding settles up to the pause, then stops. Positions aren’t liquidated via the order book and are converted during this phase. Affected accounts can deposit and add margin but can’t withdraw or remove margin. 2. **Reopening.** Once valid per-share prices are flowing, only post-only limit orders are accepted, for at least 5 minutes, with no fills. Orders must be explicitly marked post-only (API: `po=true`); unmarked orders are rejected even if they wouldn’t cross the book. Market, IOC/FOK, TP/SL and TWAP orders are refused. The timer restarts if a price or health check fails. 3. **Live.** After the minimum window, an operator releases the market once prices are fresh and both sides are quoted within configured spread and depth. Fills and liquidations resume, funding restarts with no catch-up charge, and withdrawal limits clear. Cross-margin emergency takeover and auto-deleveraging can still occur during Paused and Reopening under normal rules. Other markets trade normally throughout. ### Timing for ANT We plan to rebase ANT on **Monday, November 16, 2026, at \~10:00am ET**, about 72 hours before Anthropic’s expected first Nasdaq trade. This allows several days of per-share price discovery and avoids changes during IPO-day volatility. We’ll confirm the exact time and split ratio in advance. | When | What happens | | - | - | | Wed, Nov 11, 22:00 UTC | Pyth rebases its ANT/USD feed (×0.94025511) to the fully diluted share count in Anthropic’s amended S-1. | | By Fri, Nov 13 | Polymarket announces the split ratio and pause time. | | Mon, Nov 16, \~10:00am ET | ANT pauses, positions are converted, the price feed switches from Entropy to Pyth, and the market reopens (post-only, then Live). | | Wed, Nov 18 (expected) | Anthropic prices its IPO. | | Thu, Nov 19 (expected) | ANT begins trading on Nasdaq. | Between the split and the first trade on Nasdaq, ANT is priced from Pyth’s ANT/USD feed, which tracks Anthropic’s pre-IPO per-share value until the listed price is available. If the final prospectus share count differs from the count used for the split, the contract itself is unaffected: after the split ANT references 1 share, and from the opening trade it is priced from the actual Nasdaq share price. ### Oracle switch to Pyth From the split on November 16, ANT is priced from Pyth’s 24/7 ANT/USD feed (ID: 3618), and Entropy is no longer used: Entropy’s bounds no longer apply, and Entropy’s mark is no longer an input to our Mark price. No second switch is needed at the IPO. Pyth keeps the same feed and, once Nasdaq trading opens, uses the listed price as its leading input. From then on ANT behaves as a standard Polymarket equity perpetual, and the feed used for the Index can differ by session (regular hours, overnight, weekend). Funding already uses the standard formula, so it does not change. **Note for market makers:** Entropy keeps its own Anthropic market in valuation units after the IPO (share price × fully diluted shares ÷ 1B). After our split, ANT is quoted per share, so hedging across the two venues needs to apply the split ratio. ### Worked example *Illustrative numbers only.* Suppose the fully diluted share count is 18,000,000,000, so the split ratio is 18. | Moment | Price source | ANT price | Your position | Notional | | - | - | - | - | - | | Before split (Mon, Nov 16) | Entropy (\$B valuation) | 1,701.00 | 10 ANT long | \$17,010 | | After split (pre-IPO) | Pyth (per-share) | 94.50 | 180 ANT long | \$17,010 | | Nasdaq opens at \$80 | Pyth (listed price leads) | 80.00 | 180 ANT long | \$14,400 | After the split, each \$1 move in Anthropic’s share price moves a 1-unit position by \$1, exactly like holding 1 share. ### If the IPO is delayed or withdrawn ANT keeps trading in per-share terms on Pyth’s ANT/USD feed. If a later filing changes Anthropic’s share count, Pyth may rebase its feed again; we will announce in advance how ANT is handled. If the company remains unlisted at the No-IPO Resolution Date, the market settles as described in the table above. # Overview Source: https://docs.polymarket.com/perps/learn-about-trading/overview The market mechanics behind Perps trading Perps markets follow a small set of system rules. This section explains how those rules work so you can anticipate how positions are valued, when they are at risk, and why account balances change. > [card] [Architecture](/perps/learn-about-trading/architecture) > > How offchain matching and onchain settlement fit together. > [card] [Markets](/perps/learn-about-trading/markets) > > Available Perps markets and the parameters that shape trading. > [card] [Fees](/perps/learn-about-trading/fees) > > What each fill costs and how the volume-based fee tiers work. > [card] [Margin](/perps/learn-about-trading/margin) > > Equity, initial margin, maintenance margin, and margin states. > [card] [Liquidation Mechanics](/perps/learn-about-trading/liquidation-mechanics) > > How liquidation is detected, executed, and backstopped. > [card] [Funding](/perps/learn-about-trading/funding) > > How funding rates are computed and settled against open positions. > [card] [Mark Price](/perps/learn-about-trading/mark-price) > > How the price used for margin, PnL, and liquidation is computed. > [card] [Index Price](/perps/learn-about-trading/index-price) > > How the underlying's fair value is sourced and aggregated. > [card] [Market Sessions](/perps/learn-about-trading/market-sessions) > > How session state affects pricing feed selection. > [card] [Geographic Restrictions](/api-reference/perps/geographic-restrictions) > > Where order placement is restricted. # Self-Trade Prevention Source: https://docs.polymarket.com/perps/learn-about-trading/self-trade-prevention How the matching engine stops an account, or a group of accounts run by one entity, from trading with itself Self-trade prevention (STP) stops your orders from filling against your own resting orders. It runs on the matching engine for every order, it is not an order parameter, and it cannot be disabled or changed per order. ## How it works Before a taker matches, the engine checks whether the resting maker it would hit belongs to the same party. Every order submitted through the API runs in **CancelMaker** mode: the conflicting resting order is canceled and the taker keeps matching against the rest of the book. The canceled resting order is reported with status `stp_cancelled`, the same status you see in the order tables under [Trading](/perps/trading). The engine also implements **CancelTaker** and **CancelBoth** modes, which are used internally by the exchange and are not available to API orders. STP acts on resting orders that are eligible to match. A resting order priced outside the instrument's mark-relative price band cannot be matched by anyone, so a crossing order of yours does not cancel it; it stays on the book, keeps its margin reserved, and counts toward your open-order limit until you cancel it or the mark moves back into range. ## Account groups Polymarket can group several accounts that are controlled by one entity, for example a market maker running separate accounts for separate strategies. Groups are assigned by Polymarket on request. There is no public API to create, inspect, or change them, and group membership is never visible to other users or in public endpoints. For STP, **accounts in a group count as the same party**. An order from one member that would match another member's resting order cancels that resting order and continues matching against the rest of the book, exactly as if both orders were on one account. Resting take-profit and stop-loss exits behave like any other resting order of yours: a group-mate's crossing order cancels them just as your own would, and a canceled exit does not re-arm. Grouping changes nothing else about how the accounts trade. Balances, margin, positions, liquidation, rate limits, open-order limits and auto-cancel remain strictly per account. Two things do follow group membership besides STP: * **Default leverage and margin mode.** A group can carry defaults that apply to any member with no explicit per-instrument setting, including future listings. Your own explicit settings always take precedence. See [Margin](/perps/learn-about-trading/margin). * **Internal transfers between members.** A trading key registered to one member can move collateral to another member of the same group, without the owner key. Owner keys are never restricted by groups, and withdrawals always require the owner key. See [Transfer Between Your Accounts](/perps/fund-your-account#transfer-between-your-accounts). When Polymarket changes a group's membership, orders that were being matched at that instant are re-evaluated by the engine against the new membership before any result is published, so a fill or cancellation can never be based on stale membership. You do not see a distinct error for this; the order simply resolves under the new membership. To have accounts grouped, contact Polymarket with the list of accounts that belong to the entity. # Liquidity Rewards Source: https://docs.polymarket.com/perps/liquidity-rewards Earn daily pUSD rewards by providing deep, two-sided liquidity on Perps Every Perps account is automatically considered for daily liquidity rewards. There is no application or participant allowlist: the same eligibility threshold and scoring rules apply to every maker. Rewards are calculated for 24-hour periods from 12:00 UTC to 12:00 UTC. Each period is labeled by its end date, and earned rewards are credited in pUSD to the earning Perps account. ## How Rewards Are Allocated The program distributes **\$75,000 per day**, split evenly across active Perps markets. Each market has one daily pool. Makers with a nonzero score divide that market's entire pool in proportion to their scores. Each newly listed market also gets a **\$1,000** bonus on its first day. A maker's score combines three inputs: ```text theme={null} raw_score = maker_score^0.35 × active_liquidity_score^0.65 × uptime ``` | Input | What it rewards | | - | - | | Maker score | Meaningful maker participation over the trailing seven days | | Active liquidity score | Deep, balanced liquidity close to the midpoint while quoting | | Uptime | Consistent two-sided quoting throughout the reward period | The final reward for an account is its share of all positive raw scores in that market multiplied by the market's daily pool. ## Eligibility And Maker Score An account must represent at least **1% of trailing seven-day maker volume** to qualify. For accounts in a rewards entity, the entity's combined maker share is used. During the first seven days of the program, the lookback begins at the program start rather than reaching into earlier trading. Maker share is capped at 25% before it is converted into the maker score: ```text theme={null} maker_score = log(1 + min(maker_share, 25%) / 1%) / log(1 + 25% / 1%) ``` This gives additional credit for maker participation above the 1% threshold without allowing historical volume to dominate the full calculation. Maker share above 25% receives no additional maker-score credit. Trades between the same account, or between accounts in the same known rewards entity, do not count toward maker share. ## Liquidity Score The order book is sampled repeatedly throughout each reward period. Only resting liquidity within 20 basis points of the midpoint can score. ### Distance Tiers | Distance From Midpoint | Weight | | - | -: | | Within 5 bps | 1.00 | | More than 5 bps and within 10 bps | 0.25 | | More than 10 bps and within 20 bps | 0.10 | | Beyond 20 bps | 0 | The midpoint is the average of the best bid and best ask. Each tier boundary is rounded outward to the next valid price tick, so an order is always evaluated at a valid price for its market. For each account, side, market, and snapshot, resting notional in the same tier is added together. Scored notional is capped at **\$100,000 per tier** before the tier weight is applied. The same \$100,000 cap applies to every market and independently to each side and each of the three distance tiers. It is not one shared cap across an account's entire order book. ```text theme={null} tier_score = min(resting_notional_in_tier, $100,000) × tier_weight ``` ### Two-Sided Liquidity Bid and ask tier scores are added separately, then combined with a harmonic mean: ```text theme={null} snapshot_score = 2 × bid_score × ask_score / (bid_score + ask_score) ``` A snapshot scores only when both sides have nonzero liquidity within 20 bps. The harmonic mean penalizes an imbalanced book and produces a score of zero when either side is absent. ## Uptime Uptime is the share of completed snapshots in which the account had qualifying liquidity on both sides: ```text theme={null} uptime = qualifying_snapshots / completed_snapshots ``` The active liquidity score is the account's average snapshot score across its qualifying snapshots. Keeping liquidity quality and uptime separate means deep quotes receive credit when they are live, while intermittent quoting is still penalized. ## Summary Of Program Parameters | Parameter | Value | | - | - | | Daily program budget | \$75,000 | | New listing bonus | \$1,000 per market, first day | | Reward period | 12:00 UTC to 12:00 UTC | | Maker-share lookback | 7 days | | Eligibility threshold | 1% maker share | | Maker-score cap | 25% maker share | | Maker-score exponent | 0.35 | | Liquidity-score exponent | 0.65 | | Uptime exponent | 1.0 | | Scoring bands | 5, 10, and 20 bps | | Band weights | 1.00, 0.25, and 0.10 | | Credited notional cap | \$100,000 per tier | | Reference price | Midpoint | | Side combination | Harmonic mean | > [!NOTE] > > Polymarket may change program parameters or disqualify activity that is > manipulative, abusive, or otherwise violates the Terms of Service. # Market Data Source: https://docs.polymarket.com/perps/market-data Discover Perps markets and monitor public market activity Use market data to understand what can be traded, where the market is trading now, and how activity has changed over time. > [tab] TypeScript > > The TypeScript examples on this page use a `PublicClient`. The same market-data > methods are also available on `SecureClient` instances. > > ```ts theme={null} > import { createPublicClient } from "@polymarket/client"; > > const client = createPublicClient(); > ``` > [tab] Python > > The Python examples on this page use an `AsyncPublicClient`. The same market-data > methods are also available on `AsyncSecureClient` instances. > > ```python theme={null} > from polymarket import AsyncPublicClient > > client = AsyncPublicClient() > ``` > [tab] API > > Use the Perps REST API production URL. > > ```text theme={null} > https://api.perpetuals.polymarket.com > ``` ## Fetch Instruments Fetch instruments before your integration lets users choose or submit orders for a Perps market. Instrument data gives you the constraints needed to validate that workflow. > [tab] TypeScript > > Fetch instruments with `client.fetchPerpsInstruments()`. > > ```ts theme={null} > const instruments = await client.fetchPerpsInstruments(); > // instruments: PerpsInstrument[] > ``` > > where `PerpsInstrument` is: > > ```ts PerpsInstrument Type theme={null} > type PerpsInstrument = { > id: PerpsInstrumentId; > category: PerpsInstrumentCategory; > symbol: string; > uiLiveTime: EpochMilliseconds | null; > logo: { light: string; dark: string } | undefined; > displaySymbol: string | undefined; > closeOnly: boolean; > settlement: PerpsInstrumentSettlement | undefined; > baseAsset: string; > quoteAsset: string; > fundingInterval: PerpsFundingInterval; > quantityDecimals: number; > priceDecimals: number; > priceBounds: DecimalString; > liquidationFee: DecimalString; > maxOrderCount: number; > minNotional: DecimalString; > maxMarketNotional: DecimalString; > maxLimitNotional: DecimalString; > maxLeverage: number; > isolatedOnly: boolean; > riskTiers: PerpsRiskTier[]; > }; > > type PerpsInstrumentSettlement = { > sequence: number; > timestamp: EpochMilliseconds; > price: DecimalString; > insuranceDebit: DecimalString; > }; > > type PerpsRiskTier = { > lowerBound: DecimalString; > maxLeverage: number; > }; > ``` > > ```json PerpsInstrument Example theme={null} > { > "id": 1, > "category": "crypto", > "symbol": "BTC-PERP", > "uiLiveTime": null, > "logo": { "light": "", "dark": "" }, > "closeOnly": false, > "baseAsset": "BTC", > "quoteAsset": "USD", > "fundingInterval": "1h", > "quantityDecimals": 4, > "priceDecimals": 2, > "priceBounds": "0.1", > "liquidationFee": "0.01", > "maxOrderCount": 200, > "minNotional": "1", > "maxMarketNotional": "100000", > "maxLimitNotional": "1000000", > "maxLeverage": 10, > "isolatedOnly": false, > "riskTiers": [{ "lowerBound": "0", "maxLeverage": 10 }] > } > ``` > > Use `displaySymbol ?? symbol` for a label and keep `id` for trading and storage. > `displaySymbol` is optional and does not change the canonical `symbol`. > `closeOnly: true` requires reduce-only orders. `closeOnly` defaults to `false` when absent from an older response. > > To inspect a retired instrument, filter by its known ID; retired instruments are > omitted from the unfiltered collection. > > ```ts theme={null} > const retired = await client.fetchPerpsInstruments({ instrumentId: 1 }); > ``` > > A retired instrument has a `settlement` record. This is an illustrative record: > > > [accordion] Output: PerpsInstrumentSettlement > > > > ```json PerpsInstrumentSettlement Example theme={null} > > { > > "sequence": 1234567890, > > "timestamp": 1767225600000, > > "price": "65000.00", > > "insuranceDebit": "0" > > } > > ``` > > `settlement.timestamp` is Unix milliseconds. `sequence` is the accepted engine > sequence and must be a safe integer, at most `Number.MAX_SAFE_INTEGER`; the SDK > rejects larger values. `price` and `insuranceDebit` remain exact decimal strings. > `insuranceDebit` is the total quote amount debited from the insurance fund. > An instrument without a record has `settlement: undefined`. > > `PerpsInstrument` includes the market metadata and trading constraints your app > needs before submitting orders. > > | Field | Description | > | - | - | > | `id` | Instrument identifier. | > | `category` | Market category, such as crypto, index, equity, or commodity. | > | `symbol` | Human-readable market symbol. | > | `displaySymbol` | Optional presentation label; falls back to `symbol`. | > | `closeOnly` | Whether new orders must be reduce-only. | > | `settlement` | Permanent retirement record, when present. | > | `baseAsset` | Base asset for the instrument. | > | `quoteAsset` | Quote asset used for prices. | > | `fundingInterval` | Funding interval for the instrument, such as `1h`. | > | `quantityDecimals` | Decimal precision for quantities. | > | `priceDecimals` | Decimal precision for prices. | > | `priceBounds` | Price-bound value for the instrument. | > | `liquidationFee` | Liquidation fee value for the instrument. | > | `maxOrderCount` | Maximum order count for the instrument. | > | `minNotional` | Minimum notional value for orders. | > | `maxMarketNotional` | Maximum notional value for market orders. | > | `maxLimitNotional` | Maximum notional value for limit orders. | > | `maxLeverage` | Maximum leverage allowed for the instrument. | > | `isolatedOnly` | Whether the instrument supports only isolated margin. When `false`, both cross and isolated margin modes are supported. | > | `riskTiers` | Risk tiers for larger position sizes. | > > `uiLiveTime` is advisory interface-display timing in Unix milliseconds, or > `null` when hidden. It does not determine trading availability. If `logo` is > present, use `logo.light` and `logo.dark` for the corresponding interface theme. > Both are strings containing the asset's logo URLs. > [tab] Python > > Fetch instruments with `client.fetch_perps_instruments()`. > > ```python theme={null} > instruments = await client.fetch_perps_instruments() > # instruments: tuple[PerpsInstrument, ...] > ``` > > Filter by a known instrument ID to also retrieve a retired instrument; retired > instruments are omitted from the unfiltered collection. > > ```python theme={null} > instruments = await client.fetch_perps_instruments(instrument_id=1) > ``` > > `PerpsInstrument` includes the market metadata and trading constraints your app > needs before submitting orders. > > ```json PerpsInstrument Example theme={null} > { > "id": 1, > "category": "crypto", > "symbol": "BTC-PERP", > "ui_live_time": null, > "logo": { "light": "", "dark": "" }, > "display_symbol": null, > "close_only": false, > "settlement": null, > "base_asset": "BTC", > "quote_asset": "USD", > "funding_interval": "1h", > "quantity_decimals": 4, > "price_decimals": 2, > "price_bounds": "0.1", > "liquidation_fee": "0.01", > "max_order_count": 200, > "min_notional": "1", > "max_market_notional": "100000", > "max_limit_notional": "1000000", > "max_leverage": 10, > "isolated_only": false, > "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }] > } > ``` > > Use `display_symbol` when it is not `None`, otherwise use `symbol` for the label. > Keep `id` for trading and storage; the canonical `symbol` does not change. > `close_only=True` requires reduce-only orders and defaults to `False` on older responses. > > A retired instrument has a `PerpsInstrumentSettlement` in `settlement`; otherwise > it is `None`. This illustrative JSON serialization shows the record: > > > [accordion] Output: PerpsInstrumentSettlement > > > > ```json PerpsInstrumentSettlement Example theme={null} > > { > > "sequence": 1234567890, > > "timestamp": "2026-01-01T00:00:00Z", > > "price": "65000.00", > > "insurance_debit": "0" > > } > > ``` > > In Python, `sequence` is an exact `int`, `timestamp` is a UTC `datetime`, and > `price` and `insurance_debit` are `Decimal` values. `insurance_debit` is the total > quote amount debited from the insurance fund. > > `PerpsInstrument` exposes these attributes: > > | Attribute | Description | > | - | - | > | `id` | Instrument identifier. | > | `category` | Market category, such as crypto, index, equity, or commodity. | > | `symbol` | Human-readable market symbol. | > | `display_symbol` | Optional presentation label; falls back to `symbol`. | > | `close_only` | Whether new orders must be reduce-only. | > | `settlement` | Permanent retirement record, when present. | > | `base_asset` | Base asset for the instrument. | > | `quote_asset` | Quote asset used for prices. | > | `funding_interval` | Funding interval for the instrument, such as `1h`. | > | `quantity_decimals` | Decimal precision for quantities. | > | `price_decimals` | Decimal precision for prices. | > | `price_bounds` | Price-bound value for the instrument. | > | `liquidation_fee` | Liquidation fee value for the instrument. | > | `max_order_count` | Maximum order count for the instrument. | > | `min_notional` | Minimum notional value for orders. | > | `max_market_notional` | Maximum notional value for market orders. | > | `max_limit_notional` | Maximum notional value for limit orders. | > | `max_leverage` | Maximum leverage allowed for the instrument. | > | `isolated_only` | Whether the instrument supports only isolated margin. When `False`, both cross and isolated margin modes are supported. | > | `risk_tiers` | Risk tiers for larger position sizes. | > | `risk_tiers[].lower_bound` | Lower notional bound for the risk tier. | > | `risk_tiers[].max_leverage` | Maximum leverage allowed for the risk tier. | > > `ui_live_time` is a UTC `datetime` for advisory interface-display timing, or > `None` when hidden. It does not determine trading availability. `logo` is a > `PerpsInstrumentLogo` with `light` and `dark` URL strings, or `None` until a logo > has been uploaded. > [tab] API > > Fetch the available instruments. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/info/instruments" > ``` > > Filter by a known `instrument_id` to also retrieve a retired instrument; retired > instruments are omitted from the unfiltered collection. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/instruments" \ > --data-urlencode "instrument_id=1" > ``` > > The response is an array of instruments. > > ```json theme={null} > [ > { > "instrument_id": 1, > "instrument_type": "perpetual", > "category": "crypto", > "symbol": "BTC-PERP", > "close_only": false, > "base_asset": "BTC", > "quote_asset": "USD", > "funding_interval": "1h", > "quantity_decimals": 4, > "price_decimals": 2, > "price_bounds": "0.1", > "liquidation_fee": "0.01", > "max_order_count": 200, > "min_notional": "1", > "max_market_notional": "100000", > "max_limit_notional": "1000000", > "max_leverage": 10, > "isolated_only": false, > "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }], > "ui_live_time": null, > "logo": { "light": "", "dark": "" } > } > ] > ``` > > Use `display_symbol` when present and fall back to `symbol` for a label. Keep > `instrument_id` for trading and storage; the canonical `symbol` does not change. > `close_only: true` requires reduce-only orders. > > A retired instrument includes `settlement`. This is an illustrative record: > > > [accordion] Output: InstrumentSettlement > > > > ```json InstrumentSettlement Example theme={null} > > { > > "sequence": 1234567890, > > "timestamp": 1767225600000, > > "price": "65000.00", > > "insurance_debit": "0" > > } > > ``` > > `sequence` is the accepted engine sequence and `timestamp` is Unix milliseconds. > `price` and `insurance_debit` are decimal strings; `insurance_debit` is the total > quote amount debited from the insurance fund. Both `settlement` and > `display_symbol` are omitted when unavailable. > > Each instrument object includes the market metadata and trading constraints your > app needs before submitting orders. > > | Field | Description | > | - | - | > | `instrument_id` | Instrument identifier. | > | `instrument_type` | Instrument type. Perps instruments use `perpetual`. | > | `category` | Market category, such as `crypto`, `index`, `equity`, or `commodity`. | > | `symbol` | Human-readable market symbol. | > | `display_symbol` | Optional presentation label; falls back to `symbol`. | > | `close_only` | Whether new orders must be reduce-only. | > | `settlement` | Permanent retirement record, when present. | > | `base_asset` | Base asset for the instrument. | > | `quote_asset` | Quote asset used for prices. | > | `funding_interval` | Funding interval for the instrument, such as `1h`. | > | `quantity_decimals` | Decimal precision for quantities. | > | `price_decimals` | Decimal precision for prices. | > | `price_bounds` | Price-bound value for the instrument. | > | `liquidation_fee` | Liquidation fee value for the instrument. | > | `max_order_count` | Maximum order count for the instrument. | > | `min_notional` | Minimum notional value for orders. | > | `max_market_notional` | Maximum notional value for market orders. | > | `max_limit_notional` | Maximum notional value for limit orders. | > | `max_leverage` | Maximum leverage allowed for the instrument. | > | `isolated_only` | Whether the instrument supports only isolated margin. When `false`, both cross and isolated margin modes are supported. | > | `risk_tiers` | Risk tiers for larger position sizes. | > | `risk_tiers[].lower_bound` | Lower notional bound for the risk tier. | > | `risk_tiers[].max_leverage` | Maximum leverage allowed for the risk tier. | > | `ui_live_time` | Advisory display time in Unix milliseconds, or `null` when hidden from first-party interfaces. | > > > [!NOTE] > > > > Most trading and market-data integrations can ignore `ui_live_time`. It is > > advisory metadata for interface display timing and does not control whether > > the API returns an instrument or whether that instrument can be traded. A > > non-null value indicates when first-party interfaces may display it. > > If `logo` is present, it contains both `light` and `dark` strings with the > asset's logo URLs. The pair is shared by instruments on the same underlying > asset and is omitted until a logo has been uploaded. During close-only operation, pricing, funding, and risk management continue. A settlement record means the instrument has permanently retired: remaining positions close at the final settlement price, and trading cannot resume. The recorded cutoff permanently waives funding that had not already applied; already applied funding remains effective. ## Fetch Tickers Use tickers when you need a lightweight view of where one or more markets are trading now. > [tab] TypeScript > > Fetch one ticker when you already know which instrument your integration is > tracking. > > ```ts theme={null} > const ticker = await client.fetchPerpsTicker({ > instrumentId: instrument.id, > }); > // ticker: PerpsTicker > ``` > > Fetch all tickers to build a market list or refresh a dashboard. > > ```ts theme={null} > const tickers = await client.fetchPerpsTickers(); > // tickers: PerpsTicker[] > ``` > > where `PerpsTicker` is: > > ```ts PerpsTicker Type theme={null} > type PerpsTicker = { > instrumentId: PerpsInstrumentId; > symbol: string; > indexPrice: DecimalString; > markPrice: DecimalString; > lastPrice: DecimalString; > midPrice: DecimalString; > openInterest: DecimalString; > fundingRate: DecimalString; > nextFunding: EpochMilliseconds; > volume24h?: DecimalString; > openPrice?: DecimalString; > timestamp?: EpochMilliseconds; > }; > ``` > > ```json PerpsTicker Example theme={null} > { > "instrumentId": 1, > "symbol": "BTC-PERP", > "indexPrice": "65000.00", > "markPrice": "65012.50", > "lastPrice": "65010.00", > "midPrice": "65011.25", > "openInterest": "125.4", > "fundingRate": "0.0001", > "nextFunding": 1766124000000, > "volume24h": "2450000", > "openPrice": "64250.00", > "timestamp": 1766120400000 > } > ``` > [tab] Python > > Fetch one ticker when you already know which instrument your integration is > tracking. > > ```python theme={null} > ticker = await client.fetch_perps_ticker(instrument_id=instrument.id) > # ticker: PerpsTicker > ``` > > Fetch all tickers to build a market list or refresh a dashboard. > > ```python theme={null} > tickers = await client.fetch_perps_tickers() > # tickers: tuple[PerpsTicker, ...] > ``` > > Use the returned ticker for current price, open interest, and funding state. > > ```json Example theme={null} > { > "instrument_id": 1, > "symbol": "BTC-PERP", > "index_price": "65000.00", > "mark_price": "65012.50", > "last_price": "65010.00", > "mid_price": "65011.25", > "open_interest": "125.4", > "funding_rate": "0.0001", > "next_funding": 1766124000000, > "volume_24h": "2450000", > "open_price": "64250.00", > "timestamp": 1766120400000 > } > ``` > [tab] API > > Fetch all tickers to build a market list or refresh a dashboard. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/info/tickers" > ``` > > Filter by instrument ID when you only need one ticker. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/tickers" \ > --data-urlencode "instrument_id=1" > ``` > > The response is an array of ticker snapshots. > > ```json theme={null} > [ > { > "instrument_id": 1, > "symbol": "BTC-PERP", > "index_price": "65000.00", > "mark_price": "65012.50", > "last_price": "65010.00", > "mid_price": "65011.25", > "open_interest": "125.4", > "funding_rate": "0.0001", > "next_funding": 1766124000000, > "timestamp": 1766120400000 > } > ] > ``` Ticker snapshots are refreshed in the background and may be up to ten seconds old. When the gateway cannot guarantee that bound — for example while its data store is unavailable — the endpoint returns `503 Service Unavailable` rather than stale prices. Treat a `503` as transient and retry with backoff. ## Fetch the Order Book Use the order book before choosing an order price or size. It shows available liquidity at the requested depth. > [tab] TypeScript > > Choose how many price levels to request. Supported depths are `10`, `100`, > `500`, and `1000`. When omitted, the SDK requests `100` levels. > > ```ts theme={null} > // depth: PerpsBookDepth > const depth = 100; > ``` > > Fetch the book for the selected instrument. Bids and asks are returned as price > levels with decimal string prices and quantities. > > ```ts theme={null} > const book = await client.fetchPerpsBook({ > instrumentId: instrument.id, > depth, > }); > > const bestBid = book.bids[0]; > const bestAsk = book.asks[0]; > > // book: PerpsBook > // bestBid: PerpsBookLevel | undefined > // bestAsk: PerpsBookLevel | undefined > ``` > > where `PerpsBook` and `PerpsBookLevel` are: > > ```ts PerpsBook Type theme={null} > type PerpsBook = { > instrumentId: PerpsInstrumentId; > bids: PerpsBookLevel[]; > asks: PerpsBookLevel[]; > timestamp: EpochMilliseconds; > sequence: number; > }; > > type PerpsBookLevel = { > price: DecimalString; > quantity: DecimalString; > }; > ``` > > ```json PerpsBook Example theme={null} > { > "instrumentId": 1, > "bids": [ > { "price": "65010.00", "quantity": "0.75" }, > { "price": "65009.50", "quantity": "1.2" } > ], > "asks": [ > { "price": "65012.50", "quantity": "0.6" }, > { "price": "65013.00", "quantity": "1.1" } > ], > "timestamp": 1766120400000, > "sequence": 123456 > } > ``` > [tab] Python > > Choose how many price levels to request. Supported depths are `10`, `100`, > `500`, and `1000`. When omitted, the SDK requests `100` levels. > > ```python theme={null} > depth = 100 > ``` > > Fetch the book for the selected instrument. Bids and asks are returned as price > levels with decimal string prices and quantities. > > ```python theme={null} > book = await client.fetch_perps_book( > instrument_id=instrument.id, > depth=depth, > ) > > best_bid = book.bids[0] if book.bids else None > best_ask = book.asks[0] if book.asks else None > > # book: PerpsBook > # best_bid: PerpsBookLevel | None > # best_ask: PerpsBookLevel | None > ``` > > Use `book.bids` and `book.asks` for bid and ask price levels. > > ```json Example theme={null} > { > "instrument_id": 1, > "bids": [ > { "price": "65010.00", "quantity": "0.75" }, > { "price": "65009.50", "quantity": "1.2" } > ], > "asks": [ > { "price": "65012.50", "quantity": "0.6" }, > { "price": "65013.00", "quantity": "1.1" } > ], > "timestamp": 1766120400000, > "sequence": 123456 > } > ``` > [tab] API > > Fetch the order book for an instrument. Supported depths are `10`, `100`, `500`, > and `1000`; when omitted, the API uses `100`. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/book" \ > --data-urlencode "instrument_id=1" \ > --data-urlencode "depth=100" > ``` > > The response returns bids and asks as `[price, quantity]` levels. > > ```json theme={null} > { > "instrument_id": 1, > "bids": [ > ["65010.00", "0.75"], > ["65009.50", "1.2"] > ], > "asks": [ > ["65012.50", "0.6"], > ["65013.00", "1.1"] > ], > "timestamp": 1766120400000, > "sequence": 123456 > } > ``` > > Each `bids` and `asks` level is `[price, quantity]`. ## List Candles Use candles when your workflow needs time-bucketed price history for charts, backtests, or trading signals. > [tab] TypeScript > > The SDK paginates candle history. When `start` is omitted, it starts from the > past 24 hours. > > ```ts theme={null} > import { PerpsKlineInterval } from "@polymarket/client"; > > const pages = client.listPerpsCandles({ > instrumentId: instrument.id, > interval: PerpsKlineInterval.OneMinute, > }); > > for await (const page of pages) { > for (const candle of page.items) { > // candle: PerpsCandle > } > } > ``` > > where `PerpsCandle` is: > > ```ts PerpsCandle Type theme={null} > type PerpsCandle = { > timestamp: EpochMilliseconds; > open: DecimalString; > high: DecimalString; > low: DecimalString; > close: DecimalString; > volume: DecimalString; > trades: number; > }; > ``` > > ```json PerpsCandle Example theme={null} > { > "timestamp": 1766120400000, > "open": "65000.00", > "high": "65025.00", > "low": "64980.00", > "close": "65010.00", > "volume": "42.5", > "trades": 18 > } > ``` > [tab] Python > > The SDK paginates candle history. When `start` is omitted, it starts from the > past 24 hours. > > ```python theme={null} > pages = client.list_perps_candles( > instrument_id=instrument.id, > interval="1m", > ) > > async for page in pages: > for candle in page.items: > # candle: PerpsCandle > pass > ``` > > Each candle contains one OHLCV bucket. > > ```json Example theme={null} > { > "timestamp": 1766120400000, > "open": "65000.00", > "high": "65025.00", > "low": "64980.00", > "close": "65010.00", > "volume": "42.5", > "trades": 18 > } > ``` > [tab] API > > Fetch candles for an instrument and interval. `start_timestamp` is required; > `end_timestamp` is optional. The API returns at most 1000 candles per request. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/klines" \ > --data-urlencode "instrument_id=1" \ > --data-urlencode "interval=1m" \ > --data-urlencode "start_timestamp=1766120400000" > ``` > > The response returns candles in `data` and a `more` flag for continuation. > > ```json theme={null} > { > "data": [ > [1766120400000, "65000.00", "65025.00", "64980.00", "65010.00", "42.5", 18] > ], > "more": false > } > ``` > > Each candle is `[timestamp, open, high, low, close, volume, trades]`. ## Fetch Mark Price History Mark price history shows how an instrument's mark price changed over time. Each data point contains the last mark price recorded for an interval, independent of whether trades occurred during that interval. > [tab] API > > Fetch bucketed mark prices for an instrument and interval. `start_timestamp` is > required; `end_timestamp` is optional. The API returns at most 1000 points per > request. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/mark-history" \ > --data-urlencode "instrument_id=1" \ > --data-urlencode "interval=1s" \ > --data-urlencode "start_timestamp=1766120400000" > ``` > > The response returns mark price points in `data` and a `more` flag for > continuation. Only buckets that contain at least one mark update are included. > > ```json theme={null} > { > "data": [ > [1766120400000, "160.00"], > [1766120401000, "160.05"] > ], > "more": false > } > ``` > > Each point is `[bucket_open_time_ms, last_mark_price_in_bucket]`. ## List Trades Use public trades when recent executions matter more than aggregated candles. This is useful for trade tape views and execution analysis. > [tab] TypeScript > > The SDK paginates trade history, including cursor handling and boundary > deduplication. > > ```ts theme={null} > const pages = client.listPerpsTrades({ > instrumentId: instrument.id, > }); > > for await (const page of pages) { > for (const trade of page.items) { > // trade: PerpsPublicTrade > } > } > ``` > > where `PerpsPublicTrade` is: > > ```ts PerpsPublicTrade Type theme={null} > type PerpsPublicTrade = { > tradeId: PerpsTradeId; > instrumentId: PerpsInstrumentId; > side: PerpsSide; > settlement: boolean; > price: DecimalString; > quantity: DecimalString; > timestamp: EpochMilliseconds; > hash?: TxHash; > }; > ``` > > ```json PerpsPublicTrade Example theme={null} > { > "tradeId": 987654, > "instrumentId": 1, > "side": "long", > "settlement": false, > "price": "65010.00", > "quantity": "0.25", > "timestamp": 1766120400000, > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > } > ``` > > `settlement` is `true` for an instrument-settlement close and defaults to `false` > on older responses. > [tab] Python > > The SDK paginates trade history, including cursor handling and boundary > deduplication. > > ```python theme={null} > pages = client.list_perps_trades(instrument_id=instrument.id) > > async for page in pages: > for trade in page.items: > # trade: PerpsTrade > pass > ``` > > Each trade contains one public execution. > > ```json PerpsTrade Example theme={null} > { > "trade_id": 987654, > "instrument_id": 1, > "side": "long", > "settlement": false, > "price": "65010.00", > "quantity": "0.25", > "timestamp": "2025-12-19T05:00:00Z", > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > } > ``` > > `settlement` is `True` for an instrument-settlement close and defaults to `False` > on older responses. `timestamp` is a UTC `datetime`; the JSON above shows its > serialization. > [tab] API > > Fetch recent public trades for an instrument. `start_timestamp` and > `end_timestamp` are optional. The API returns at most 100 trades per request. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/trades" \ > --data-urlencode "instrument_id=1" > ``` > > The response returns trades in `data` and a `more` flag for continuation. > > ```json theme={null} > { > "data": [ > { > "trade_id": 987654, > "instrument_id": 1, > "side": "long", > "settlement": false, > "price": "65010.00", > "quantity": "0.25", > "timestamp": 1766120400000, > "hash": "0x1111111111111111111111111111111111111111111111111111111111111111" > } > ], > "more": false > } > ``` > > `settlement` is `true` for an instrument-settlement close. ## List Funding History Use funding-rate history when estimating carry costs or explaining why Perps prices differ from the index over time. > [tab] TypeScript > > The SDK paginates funding-rate history. > > ```ts theme={null} > const pages = client.listPerpsFundingHistory({ > instrumentId: instrument.id, > }); > > for await (const page of pages) { > for (const fundingRate of page.items) { > // fundingRate: PerpsFundingRate > } > } > ``` > > where `PerpsFundingRate` is: > > ```ts PerpsFundingRate Type theme={null} > type PerpsFundingRate = { > fundingRate: DecimalString; > timestamp: EpochMilliseconds; > }; > ``` > > ```json PerpsFundingRate Example theme={null} > { > "fundingRate": "0.0001", > "timestamp": 1766120400000 > } > ``` > [tab] Python > > The SDK paginates funding-rate history. > > ```python theme={null} > pages = client.list_perps_funding_history(instrument_id=instrument.id) > > async for page in pages: > for funding_rate in page.items: > # funding_rate: PerpsFundingRate > pass > ``` > > Each funding-rate entry contains one historical observation. > > ```json Example theme={null} > { > "funding_rate": "0.0001", > "timestamp": 1766120400000 > } > ``` > [tab] API > > Fetch historical funding rates for an instrument. `start_timestamp` and > `end_timestamp` are optional. The API returns at most 100 funding-rate entries > per request. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/funding" \ > --data-urlencode "instrument_id=1" > ``` > > The response returns funding rates in `data` and a `more` flag for continuation. > > ```json theme={null} > { > "data": [ > { > "funding_rate": "0.0001", > "timestamp": 1766120400000 > } > ], > "more": false > } > ``` # Notifications Source: https://docs.polymarket.com/perps/notifications Show Perps account activity as an in-app notification feed Notifications turn a Perps account's activity into a ready-to-display feed of position changes, canceled orders, and liquidation events. They are the same events that drive the notification bell in the Polymarket app. Read recent notifications to render the feed, then stream the live channel to keep it fresh. Mark notifications read as the user catches up. Notifications summarize activity for display. To reconcile order, fill, and position state, use [Reconcile Trade State](/perps/trading#reconcile-trade-state) instead. > [!NOTE] > > Notifications require an [authenticated > session](/perps/authenticated-sessions). ## Read Notifications Start with a read to render the feed. It returns the account's notifications newest first, together with the unread count for the badge. > [tab] TypeScript > > Fetch the first page of notifications. > > ```ts theme={null} > const page = await session.listNotifications().firstPage(); > // page.items: PerpsNotificationEntry[] > ``` > > Each entry pairs one notification with its read state, and `readAt` stays > `null` until the notification is marked read. The read is paginated, so iterate > it to walk older history. > > ```ts theme={null} > for await (const page of session.listNotifications()) { > // page.items: PerpsNotificationEntry[] > } > ``` > > For the unread badge, fetch the count directly. > > ```ts theme={null} > const unread = await session.fetchUnreadNotificationsCount(); > ``` > > > [accordion] Output: PerpsNotificationEntry\[] > > > > ```ts Type theme={null} > > type PerpsNotificationEntry = { > > notification: PerpsNotification; > > readAt: number | null; > > timestamp: number; > > }; > > ``` > > > > ```json Example theme={null} > > [ > > { > > "notification": { > > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > > "type": "position_opened", > > "instrumentId": 1, > > "side": "long", > > "size": "0.01", > > "avgPrice": "65000", > > "leverage": 5, > > "orderType": "market" > > }, > > "readAt": null, > > "timestamp": 1767225600000 > > } > > ] > > ``` > [tab] Python > > Fetch the first page of notifications. > > ```python theme={null} > page = await session.list_notifications().first_page() > # page.items: tuple[PerpsNotificationEntry, ...] > # page.unread: int > ``` > > Each entry pairs one notification with its read state, and `read_at` stays > `None` until the notification is marked read. The page also carries the > account's `unread` count for the badge. The read is paginated, so iterate it to > walk older history. > > ```python theme={null} > async for page in session.list_notifications(): > # page.items: tuple[PerpsNotificationEntry, ...] > pass > ``` > > > [accordion] Output: tuple\[PerpsNotificationEntry, ...] > > > > ```json theme={null} > > [ > > { > > "notification": { > > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > > "type": "position_opened", > > "instrument_id": 1, > > "side": "long", > > "size": "0.01", > > "avg_price": "65000", > > "leverage": 5, > > "order_type": "market" > > }, > > "read_at": null, > > "timestamp": 1767225600000 > > } > > ] > > ``` > [tab] API > > Fetch the account's notifications, newest first. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/notifications" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "limit=50" > ``` > > Each item pairs one notification with its read state, and `read_at` stays > `null` until the notification is marked read. `unread` counts the account's > unread notifications. While `has_more` is true, pass `next_cursor` back as > `cursor` to fetch the next, older page. > > > [accordion] Output: Notifications > > > > ```json theme={null} > > { > > "items": [ > > { > > "notification": { > > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > > "type": "position_opened", > > "instrument_id": 1, > > "side": "long", > > "size": "0.01", > > "avg_price": "65000", > > "leverage": 5, > > "order_type": "market" > > }, > > "read_at": null, > > "ts": 1767225600000 > > } > > ], > > "unread": 3, > > "durable_source_seq": 1234567890, > > "has_more": true, > > "next_cursor": "eyJ0cyI6MTc2NzIyNTYwMDAwMCwiaWQiOiIwYTVkOGYxZS0zYjJjLTVlNGEtOWY4Yi0xYzJkM2U0ZjVhNmIifQ" > > } > > ``` ## Stream Notifications Subscribe to the live channel to append new notifications and bump the unread badge without polling. > [tab] TypeScript > > Notification events arrive on the session stream alongside the other private > session updates. > > ```ts theme={null} > for await (const event of session) { > if (event.type === "notification") { > // event.payload: PerpsNotification > } > } > ``` > > The stream yields `PerpsNotificationUpdateEvent` objects like this. > > ```ts Type theme={null} > type PerpsNotificationUpdateEvent = { > type: "notification"; > channel: "notifications"; > timestamp: number; > sequence: number; > payload: PerpsNotification; > }; > ``` > > ```json Example theme={null} > { > "type": "notification", > "channel": "notifications", > "timestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrumentId": 1, > "side": "long", > "size": "0.01", > "avgPrice": "65000", > "leverage": 5, > "orderType": "market" > } > } > ``` > [tab] Python > > Notification events arrive on the session stream alongside the other private > session updates. > > ```python theme={null} > async for event in session: > if event.type == "notification": > # event.payload: PerpsNotification > pass > ``` > > The stream yields `PerpsNotificationEvent` objects like this. > > ```json Example theme={null} > { > "type": "notification", > "channel": "notifications", > "timestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "65000", > "leverage": 5, > "order_type": "market" > } > } > ``` > [tab] API > > Authenticate the WebSocket connection first, then subscribe to the > `notifications` channel. > > ```json Subscribe theme={null} > { > "id": 1, > "req": "sub", > "chs": ["notifications"] > } > ``` > > After subscribing, the stream emits notification data frames like this. > > ```json theme={null} > { > "ch": "notifications", > "ts": 1767225600000, > "sq": 1234567890, > "data": { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "65000", > "leverage": 5, > "order_type": "market" > } > } > ``` > > Use `req: "unsub"` with the same `chs` value to unsubscribe. See [Authenticated > Sessions](/perps/authenticated-sessions) for the authentication frame and > connection lifecycle. ## Mark Notifications Read Read state drives the unread count. Mark notifications read when the user views them, either one by one or everything up to the newest one they have seen. Read state is scoped to the account, so a session can only mark its own notifications read. > [tab] TypeScript > > Mark specific notifications read by id, or mark everything up to an entry read. > > ```ts By ids theme={null} > await session.markNotificationsRead({ > ids: [entry.notification.id], > }); > ``` > > ```ts Up to an entry theme={null} > await session.markNotificationsRead({ > upTo: { id: entry.notification.id, timestamp: entry.timestamp }, > }); > ``` > > `upTo` marks the given notification and every earlier one read, inclusive. Pass > the newest entry the user has seen to clear the feed in one call. > [tab] Python > > Mark specific notifications read by id, or mark everything up to an entry read. > > ```python By ids theme={null} > await session.mark_notifications_read(ids=[entry.notification.id]) > ``` > > ```python Up to an entry theme={null} > await session.mark_notifications_read(up_to=entry) > ``` > > `up_to` takes a `PerpsNotificationEntry` and marks it and every earlier > notification read, inclusive. Pass the newest entry the user has seen to clear > the feed in one call. > [tab] API > > Mark specific notifications read by id, or mark everything at or before a > cursor read. > > ```bash By ids theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/notifications/read" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > -H "content-type: application/json" \ > -d '{"ids": ["0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b"]}' > ``` > > ```bash Before a cursor theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/account/notifications/read" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > -H "content-type: application/json" \ > -d '{"before": "eyJ0cyI6MTc2NzIyNTYwMDAwMCwiaWQiOiIwYTVkOGYxZS0zYjJjLTVlNGEtOWY4Yi0xYzJkM2U0ZjVhNmIifQ"}' > ``` > > `before` takes a keyset cursor (base64url-encoded JSON > `{"ts": , "id": ""}`) and marks every notification at > or before it read, inclusive. `next_cursor` values returned by the notifications > read use the same format. > > The response confirms the read markers were accepted. > > ```json theme={null} > { > "status": "ok" > } > ``` ## Backfill Missed Notifications The live channel can miss notifications. A reconnect leaves a gap, and under load the server can drop frames. The notifications read closes these gaps. Pass a sequence lower bound and it returns every notification from that point forward, so the feed catches up with stored history. Anchor the bound at the sequence of the last notification you processed, not at the sequence of the recovery signal. The bound is inclusive and one event can emit several notifications that share one sequence, so the backfill re-covers the boundary. Deduplicate merged results by notification identifier, which is identical across stored history and live updates. Stored history can lag behind live notifications. Retry from the same anchor and read every page on each attempt until stored history covers the missed interval. > [tab] TypeScript > > Track the sequence of the last notification event you processed. When the > session signals a `resync`, run the backfill from that anchor. > > ```ts theme={null} > let lastSequence: number | undefined; > > for await (const event of session) { > if (event.type === "notification") { > // Apply event.payload to the local feed. > lastSequence = event.sequence; > } > > if (event.type === "resync") { > const pages = session.listNotifications({ > sinceSeq: lastSequence, > }); > for await (const page of pages) { > // Merge page.items into the local feed, deduplicated by notification id. > } > } > } > ``` > > Follow-up pages keep the same `sinceSeq` bound automatically. If you have not > processed any notifications yet, leave `sinceSeq` unset and the read returns the > newest notifications. > [tab] Python > > Track the sequence of the last notification event you processed. When the > session signals a `resync`, run the backfill from that anchor. > > ```python theme={null} > last_sequence = None > > async for event in session: > if event.type == "notification": > # Apply event.payload to the local feed. > last_sequence = event.sequence > elif event.type == "resync": > pages = session.list_notifications(since_seq=last_sequence) > async for page in pages: > # Merge page.items into the local feed, deduplicated by notification id. > pass > ``` > > Follow-up pages keep the same `since_seq` bound automatically. If you have not > processed any notifications yet, leave `since_seq` unset and the read returns > the newest notifications. > > A resync with `event.reason == "server"` means the server dropped notification > frames, and its `event.sequence` is the highest sequence among the dropped > notifications. The store can persist those notifications slightly after the > drop signal, so if a page still reports `page.durable_source_seq` below that > target, wait briefly and run the same backfill again. Recovery requires both > reaching that target and draining every page from the original anchor. The > `since_seq` bound and id-based deduplication make retries safe. > [tab] API > > **1. Track the Last Processed Frame** > > Keep the `sq` of the last notifications data frame you processed. When the > server drops frames under load, it sends a `resync` control frame instead. Its > `sq` is the highest sequence among the dropped notifications. > > ```json theme={null} > { > "ch": "notifications", > "ts": 1767225600000, > "sq": 1234568100, > "type": "resync" > } > ``` > > A `resync` frame carries no data. Never anchor the backfill on its `sq`, which > can be later than the dropped notifications and would skip them. > > **2. Backfill From the Anchor** > > Request the notifications read with `since_seq` set to the `sq` of the last > data frame you processed. The bound is inclusive, so deduplicate the results by > notification `id`. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/notifications" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "since_seq=1234567890" > ``` > > While `has_more` is true, pass `next_cursor` back as `cursor` together with the > same `since_seq`, so follow-up pages stay inside the gap window. If you have no > processed data frame to anchor on, use the `durable_source_seq` of your most > recent read instead. If you have neither, fetch the first page without > `since_seq`. > > **3. Confirm the Store Caught Up** > > Each response reports `durable_source_seq`, the highest sequence the store has > persisted for the account. Compare it against the catch-up target: the `resync` > frame's `sq` after a drop, or the `sq` of the first data frame received on the > new connection after a reconnect. Buffer live frames from the moment you > subscribe so you do not lose that target. > > While `durable_source_seq` is below the target, the store has not caught up > yet. Retry the same backfill until it reaches the target and deduplicate the > merged results by notification `id`. ## Notification Types Each notification describes one account event. Auto-deleveraging can close or reduce a profitable position to settle another account's liquidation without an action by the position holder. > [tab] TypeScript > > The `PerpsNotificationType` and `PerpsNotificationOrderType` enums export the > `type` and `orderType` values shown in the examples below. > > | Notification Type | Sent when | > | - | - | > | `PerpsNotificationType.PositionOpened` | A fill opens a new position. | > | `PerpsNotificationType.PositionIncreased` | A fill adds to an existing position. | > | `PerpsNotificationType.PositionReduced` | A fill shrinks a position without closing it. | > | `PerpsNotificationType.PositionClosed` | A fill fully closes a position and realizes its PnL. | > | `PerpsNotificationType.LimitOrderCanceled` | A resting limit order is canceled. | > | `PerpsNotificationType.LiquidationWarning` | A position (isolated margin) or the whole account (cross margin) is approaching liquidation. | > | `PerpsNotificationType.PositionLiquidated` | A liquidation closes part or all of a position. | > | `PerpsNotificationType.PositionDeleveraged` | Auto-deleveraging closes part or all of a profitable position to settle a liquidation on the other side. | > > Fill-driven position notifications can include an `orderType` field that names > the kind of order behind the fill. The field is omitted when the fill cannot > be attributed to an order, so treat it as optional display metadata. > > | Order Type | Meaning | > | - | - | > | `PerpsNotificationOrderType.Market` | An untriggered aggressing order submitted without a limit price. | > | `PerpsNotificationOrderType.Limit` | Any other untriggered order, including fills on a resting maker order. | > | `PerpsNotificationOrderType.TakeProfit` | An order fired by a take-profit trigger, whether it aggressed or rested. | > | `PerpsNotificationOrderType.StopLoss` | An order fired by a stop-loss trigger, whether it aggressed or rested. | > > Each notification type carries the fields shown below. > > ```json Position Opened theme={null} > { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrumentId": 1, > "side": "long", > "size": "0.01", > "avgPrice": "65000", > "leverage": 5, > "orderType": "market" > } > ``` > > ```json Position Closed theme={null} > { > "id": "1b6e9f2a-4c3d-5f5b-8a9c-2d3e4f5a6b7c", > "type": "position_closed", > "instrumentId": 1, > "side": "long", > "size": "0.01", > "avgPrice": "66500", > "pnl": "15", > "orderType": "take_profit" > } > ``` > > ```json Limit Order Canceled theme={null} > { > "id": "2c7fa03b-5d4e-5a6c-9b8d-3e4f5a6b7c8d", > "type": "limit_order_canceled", > "instrumentId": 1, > "side": "long", > "size": "0.01", > "price": "64000" > } > ``` > > ```json Liquidation Warning (Isolated) theme={null} > { > "id": "3d8ab14c-6e5f-5b7d-8c9e-4f5a6b7c8d9e", > "type": "liquidation_warning", > "marginType": "isolated", > "instrumentId": 1, > "markPrice": "53040", > "liquidationPrice": "52000" > } > ``` > > ```json Liquidation Warning (Cross) theme={null} > { > "id": "4e9bc25d-7f6a-5c8e-9d8f-5a6b7c8d9e0f", > "type": "liquidation_warning", > "marginType": "cross", > "markPrice": "53040", > "affectedInstruments": [1, 2] > } > ``` > > ```json Position Liquidated theme={null} > { > "id": "5fa0d36e-8a7b-5d9f-8e9a-6b7c8d9e0f1a", > "type": "position_liquidated", > "instrumentId": 1, > "side": "long", > "sizeClosed": "0.01", > "pnl": "-130", > "marginType": "isolated", > "viaBackstop": false > } > ``` > > Handle auto-deleveraging in the existing `PerpsSession` iterator. The same > `PerpsPositionDeleveragedNotification` is available as `entry.notification` > from `session.listNotifications()`. > > ```ts theme={null} > import { PerpsNotificationType } from "@polymarket/client"; > > for await (const event of session) { > if ( > event.type === "notification" && > event.payload.type === PerpsNotificationType.PositionDeleveraged > ) { > console.log(event.payload.sizeClosed, event.payload.price, event.payload.pnl); > } > } > ``` > > > [accordion] Output: PerpsPositionDeleveragedNotification > > > > ```ts PerpsPositionDeleveragedNotification Type theme={null} > > type PerpsPositionDeleveragedNotification = { > > id: PerpsNotificationId; > > type: PerpsNotificationType.PositionDeleveraged; > > instrumentId: PerpsInstrumentId; > > side: PerpsSide; > > sizeClosed: DecimalString; > > price: DecimalString; > > pnl: DecimalString; > > marginType: PerpsMarginType; > > }; > > ``` > > > > ```json PerpsPositionDeleveragedNotification Example theme={null} > > { > > "id": "6ab1e47f-9b8c-5eaf-8f9b-7c8d9e0f1a2b", > > "type": "position_deleveraged", > > "instrumentId": 1, > > "side": "short", > > "sizeClosed": "0.01", > > "price": "52000", > > "pnl": "130", > > "marginType": "isolated" > > } > > ``` > > `sizeClosed` is the quantity closed or reduced, `price` is the settlement > price, and `pnl` is the realized PnL. All three are decimal strings. > [tab] Python > > The `PerpsNotificationType` and `PerpsNotificationOrderType` type aliases list > the `type` and `order_type` values. > > | `PerpsNotificationType` | Sent when | > | - | - | > | `position_opened` | A fill opens a new position. | > | `position_increased` | A fill adds to an existing position. | > | `position_reduced` | A fill shrinks a position without closing it. | > | `position_closed` | A fill fully closes a position and realizes its PnL. | > | `limit_order_canceled` | A resting limit order is canceled. | > | `liquidation_warning` | A position (isolated margin) or the whole account (cross margin) is approaching liquidation. | > | `position_liquidated` | A liquidation closes part or all of a position. | > | `position_deleveraged` | Auto-deleveraging closes part or all of a profitable position to settle a liquidation on the other side. | > > Fill-driven position notifications can include an `order_type` field that > names the kind of order behind the fill. The field is omitted when the fill > cannot be attributed to an order, so treat it as optional display metadata. > > | `PerpsNotificationOrderType` | Meaning | > | - | - | > | `market` | An untriggered aggressing order submitted without a limit price. | > | `limit` | Any other untriggered order, including fills on a resting maker order. | > | `take_profit` | An order fired by a take-profit trigger, whether it aggressed or rested. | > | `stop_loss` | An order fired by a stop-loss trigger, whether it aggressed or rested. | > > Each notification type carries the fields shown below. > > ```json Position Opened theme={null} > { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "65000", > "leverage": 5, > "order_type": "market" > } > ``` > > ```json Position Closed theme={null} > { > "id": "1b6e9f2a-4c3d-5f5b-8a9c-2d3e4f5a6b7c", > "type": "position_closed", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "66500", > "pnl": "15", > "order_type": "take_profit" > } > ``` > > ```json Limit Order Canceled theme={null} > { > "id": "2c7fa03b-5d4e-5a6c-9b8d-3e4f5a6b7c8d", > "type": "limit_order_canceled", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "price": "64000" > } > ``` > > ```json Liquidation Warning (Isolated) theme={null} > { > "id": "3d8ab14c-6e5f-5b7d-8c9e-4f5a6b7c8d9e", > "type": "liquidation_warning", > "margin_type": "isolated", > "instrument_id": 1, > "mark_price": "53040", > "liquidation_price": "52000" > } > ``` > > ```json Liquidation Warning (Cross) theme={null} > { > "id": "4e9bc25d-7f6a-5c8e-9d8f-5a6b7c8d9e0f", > "type": "liquidation_warning", > "margin_type": "cross", > "mark_price": "53040", > "affected_instruments": [1, 2] > } > ``` > > ```json Position Liquidated theme={null} > { > "id": "5fa0d36e-8a7b-5d9f-8e9a-6b7c8d9e0f1a", > "type": "position_liquidated", > "instrument_id": 1, > "side": "long", > "size_closed": "0.01", > "pnl": "-130", > "margin_type": "isolated", > "via_backstop": false > } > ``` > > Handle auto-deleveraging in the existing `PerpsSession` iterator. The same > `PerpsPositionDeleveragedNotification`, exported from `polymarket.models.perps`, > is available as `entry.notification` from `session.list_notifications()`. > > ```python theme={null} > async for event in session: > if event.type == "notification" and event.payload.type == "position_deleveraged": > print(event.payload.size_closed, event.payload.price, event.payload.pnl) > ``` > > > [accordion] Output: PerpsPositionDeleveragedNotification > > > > ```python PerpsPositionDeleveragedNotification Type theme={null} > > class PerpsPositionDeleveragedNotification: > > id: PerpsNotificationId > > type: Literal["position_deleveraged"] > > instrument_id: PerpsInstrumentId > > side: PerpsSide > > size_closed: Decimal > > price: Decimal > > pnl: Decimal > > margin_type: PerpsMarginType > > ``` > > > > ```python PerpsPositionDeleveragedNotification Example theme={null} > > PerpsPositionDeleveragedNotification( > > id="6ab1e47f-9b8c-5eaf-8f9b-7c8d9e0f1a2b", > > type="position_deleveraged", > > instrument_id=1, > > side="short", > > size_closed=Decimal("0.01"), > > price=Decimal("52000"), > > pnl=Decimal("130"), > > margin_type="isolated", > > ) > > ``` > > `size_closed` is the quantity closed or reduced, `price` is the settlement > price, and `pnl` is the realized PnL. All three are `Decimal` values. > [tab] API > > Notifications report these `type` values. > > | `type` | Sent when | > | - | - | > | `position_opened` | A fill opens a new position. | > | `position_increased` | A fill adds to an existing position. | > | `position_reduced` | A fill shrinks a position without closing it. | > | `position_closed` | A fill fully closes a position and realizes its PnL. | > | `limit_order_canceled` | A resting limit order is canceled. | > | `liquidation_warning` | A position (isolated margin) or the whole account (cross margin) is approaching liquidation. | > | `position_liquidated` | A liquidation closes part or all of a position. | > | `position_deleveraged` | Auto-deleveraging closes part or all of a position to settle a liquidation on the other side. | > > A liquidation that cannot settle on the order book is auto-deleveraged against > a trader on the profitable side. The liquidated account receives > `position_liquidated`; the counterparty, whose position was closed or reduced > without any action of its own, receives `position_deleveraged` with the > settlement `price` and the realized `pnl`. > > Fill-driven position notifications can include an `order_type` field that > names the kind of order behind the fill. The field is omitted when the fill > cannot be attributed to an order, so treat it as optional display metadata. > > | `order_type` | Meaning | > | - | - | > | `market` | An untriggered aggressing order submitted without a limit price. | > | `limit` | Any other untriggered order, including fills on a resting maker order. | > | `take_profit` | An order fired by a take-profit trigger, whether it aggressed or rested. | > | `stop_loss` | An order fired by a stop-loss trigger, whether it aggressed or rested. | > > Each notification type carries the fields shown below. > > ```json Position Opened theme={null} > { > "id": "0a5d8f1e-3b2c-5e4a-9f8b-1c2d3e4f5a6b", > "type": "position_opened", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "65000", > "leverage": 5, > "order_type": "market" > } > ``` > > ```json Position Closed theme={null} > { > "id": "1b6e9f2a-4c3d-5f5b-8a9c-2d3e4f5a6b7c", > "type": "position_closed", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "avg_price": "66500", > "pnl": "15", > "order_type": "take_profit" > } > ``` > > ```json Limit Order Canceled theme={null} > { > "id": "2c7fa03b-5d4e-5a6c-9b8d-3e4f5a6b7c8d", > "type": "limit_order_canceled", > "instrument_id": 1, > "side": "long", > "size": "0.01", > "price": "64000" > } > ``` > > ```json Liquidation Warning (Isolated) theme={null} > { > "id": "3d8ab14c-6e5f-5b7d-8c9e-4f5a6b7c8d9e", > "type": "liquidation_warning", > "margin_type": "isolated", > "instrument_id": 1, > "mark_price": "53040", > "liq_price": "52000" > } > ``` > > ```json Liquidation Warning (Cross) theme={null} > { > "id": "4e9bc25d-7f6a-5c8e-9d8f-5a6b7c8d9e0f", > "type": "liquidation_warning", > "margin_type": "cross", > "instrument_id": null, > "mark_price": "53040", > "affected_instruments": [1, 2] > } > ``` > > ```json Position Liquidated theme={null} > { > "id": "5fa0d36e-8a7b-5d9f-8e9a-6b7c8d9e0f1a", > "type": "position_liquidated", > "instrument_id": 1, > "side": "long", > "size_closed": "0.01", > "pnl": "-130", > "margin_type": "isolated", > "via_backstop": false > } > ``` > > ```json Position Deleveraged theme={null} > { > "id": "6ab1e47f-9b8c-5eaf-8f9b-7c8d9e0f1a2b", > "type": "position_deleveraged", > "instrument_id": 1, > "side": "short", > "size_closed": "0.01", > "price": "52000", > "pnl": "130", > "margin_type": "isolated" > } > ``` # Overview Source: https://docs.polymarket.com/perps/overview Start here for Polymarket perpetual markets Polymarket [Perps](https://polymarket.com/perps) are perpetual contracts that track an underlying asset such as an index, commodity, crypto asset, or equity. Perps trade continuously and do not expire, so traders can open, manage, and close leveraged positions without waiting for a market resolution event. ## How Perps Work A Perps trade starts as an order in the order book. When it fills, it becomes a position whose value changes as the tracked market moves, until the trader closes it or the system closes it because the account can no longer support the risk. > [card] Prices > > A Perps market has a traded price from the order book and reference prices > used by the system. The index price tracks the underlying asset, while the > mark price is used for account equity, margin checks, and liquidation risk. > [card] Trading Positions > > Trading a Perps market creates or changes a position. A long position benefits > when the tracked asset rises, and a short position benefits when it falls. > Orders trade through the order book; fills update the account's position, > balance, and history. > [card] Margin And Liquidation > > Perps require collateral to support open positions. That collateral is the > account's margin: the buffer that covers losses while a position is open. If > account equity falls too far relative to the required margin, the position can > be liquidated to close exposure. > [card] Funding Payments > > Funding payments keep the contract price close to the index price. When a > market trades above its index price, long positions generally pay short > positions. When it trades below its index price, shorts generally pay longs. ## Building on Perps If you are here to see what you can build on top of Polymarket Perps, common use cases include: * Trading bots that react to market signals * Market making systems that quote Perps markets * Portfolio dashboards that track balances and positions * Risk monitors that track margin and liquidation risk * Market data products that analyze books, trades, and funding payments ## Next Steps > [card] [Concepts](/perps/concepts) > > Learn the shared terms used across Perps docs. > [card] [Learn About Trading](/perps/learn-about-trading/overview) > > Understand the market mechanics behind Perps. > [card] [Place Your First Trade](/perps/place-your-first-trade) > > Build a first end-to-end Perps trading flow. # Place Your First Trade Source: https://docs.polymarket.com/perps/place-your-first-trade Learn how to prepare a Perps account and submit a first buy order This guide walks through the shortest safe path to a first Perps trade. You will set up a Perps account, add collateral, and place a small buy order. You need a Polymarket account with pUSD available before you start. Create one at [polymarket.com](https://polymarket.com). > [!NOTE] > > Building directly against the API? Start with [Authenticated > Sessions](/perps/authenticated-sessions), then use [Fund Your > Account](/perps/fund-your-account) and [Trading](/perps/trading). > [tab] TypeScript > > **1. Install the SDK** > > Install the Unified TypeScript SDK with the package manager of your choice. > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest viem > ``` > > ```bash npm theme={null} > npm install @polymarket/client@latest viem > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest viem > ``` > > > [!NOTE] > > > > This page uses Viem for wallet signing. See the [TypeScript tooling > > guide](/getting-started/typescript#wallet-integrations) for other wallet library > > integrations. > > **2. Create a Secure Client** > > Create a `SecureClient` with the wallet and signer that owns the Perps account. > Include a Relayer API key so the SDK can submit gasless transactions. > > ```ts theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > apiKey: relayerApiKey({ > key: process.env.RELAYER_API_KEY!, > address: process.env.RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) from > polymarket.com → Settings → API Keys. > > **3. Fund the Account** > > Set up the approvals required for Perps collateral deposits, then deposit pUSD > from the user's Polymarket wallet into the Perps account. The minimum Perps > deposit is 10 pUSD. Amounts use raw pUSD base units, so 10 pUSD is > `10_000_000n`. > > ```ts theme={null} > await client.setupTradingApprovals(); > > const deposit = await client.depositToPerps({ > amount: 10_000_000n, > }); > > await deposit.wait(); > ``` > > `deposit.wait()` confirms that the chain transaction settled. Perps may take a > moment to credit the account after that. See [Fund Your > Account](/perps/fund-your-account) for the full funding workflow. > > **4. Open a Perps Session** > > Open a Perps session for private reads and trading. > > ```ts theme={null} > const session = await client.openPerpsSession(); > ``` > > **5. Choose a Market** > > Fetch the available Perps instruments and choose the market you want to trade. > > ```ts theme={null} > const instruments = await client.fetchPerpsInstruments(); > const instrument = instruments.find( > (instrument) => instrument.symbol === "SP500-USD", > ); > > if (instrument === undefined) { > throw new Error("Instrument not found."); > } > ``` > > **6. Place the Order** > > Place a long buy order for `1` quantity unit of `SP500-USD` with an explicit > limit price of `100` USD per quantity unit and immediate-or-cancel execution. > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > quantity: "1", > price: "100", > timeInForce: PerpsTimeInForce.IOC, > }); > > // order.id: PerpsOrderId > ``` > > The returned order includes the accepted order state. See > [Trading](/perps/trading) for direction, order behavior, cancellation, and state > reconciliation. > [tab] Python > > **1. Install the SDK** > > Install the Unified Python SDK with the package manager of your choice. > > ```bash uv theme={null} > uv add polymarket-client > ``` > > ```bash pip theme={null} > pip install polymarket-client > ``` > > ```bash poetry theme={null} > poetry add polymarket-client > ``` > > **2. Create a Secure Client** > > Create an `AsyncSecureClient` with the wallet and signer that owns the Perps > account. Include a Relayer API key so the SDK can submit gasless transactions. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["RELAYER_API_KEY"], > address=os.environ["RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) from > polymarket.com → Settings → API Keys. > > **3. Fund the Account** > > Set up the approvals required for Perps collateral deposits, then deposit pUSD > from the user's Polymarket wallet into the Perps account. The minimum Perps > deposit is 10 pUSD. Amounts use raw pUSD base units, so 10 pUSD is `10_000_000`. > > ```python theme={null} > await client.setup_trading_approvals() > > deposit = await client.deposit_to_perps(amount=10_000_000) > > await deposit.wait() > ``` > > `deposit.wait()` confirms that the chain transaction settled. Perps may take a > moment to credit the account after that. See [Fund Your > Account](/perps/fund-your-account) for the full funding workflow. > > **4. Open a Perps Session** > > Open a Perps session for private reads and trading. > > ```python theme={null} > session = await client.open_perps_session() > ``` > > **5. Choose a Market** > > Fetch the available Perps instruments and choose the market you want to trade. > > ```python theme={null} > instruments = await client.fetch_perps_instruments() > instrument = next( > (item for item in instruments if item.symbol == "SP500-USD"), > None, > ) > > if instrument is None: > raise RuntimeError("Instrument not found.") > ``` > > **6. Place the Order** > > Place a long buy order for `1` quantity unit of `SP500-USD` with an explicit > limit price of `100` USD per quantity unit and immediate-or-cancel execution. > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > quantity="1", > price="100", > time_in_force="ioc", > ) > > # result.order.id: PerpsOrderId > ``` > > The returned order includes the accepted order state. See > [Trading](/perps/trading) for direction, order behavior, cancellation, and state > reconciliation. # Realtime Updates Source: https://docs.polymarket.com/perps/realtime-updates Stream public Perps market data Stream public market data as prices, books, trades, candles, tickers, and market statistics change. > [!NOTE] > > Private order, fill, and account-state reconciliation is covered in [Reconcile > Trade State](/perps/trading#reconcile-trade-state). Start with the stream that matches the view you are building. Subscribe to the updates you need, read events while the view is active, then stop the stream when the view no longer needs live data. > [tab] TypeScript > > Subscribe from a `PublicClient` or `SecureClient` and iterate over the merged > event stream. > > ```ts theme={null} > import { createPublicClient } from "@polymarket/client"; > > const client = createPublicClient(); > > const stream = await client.subscribe([ > { topic: "perps.bbo", instrumentId: 1 }, > { topic: "perps.trades", instrumentId: 1 }, > ]); > > for await (const event of stream) { > switch (event.type) { > case "bbo": > // event: PerpsBboEvent > break; > case "trade": > // event: PerpsTradeEvent > break; > } > > if (shouldClose) { > await stream.close(); > } > } > ``` > > The stream yields typed events for each subscription and can be closed when the > live view no longer needs updates. > [tab] Python > > Subscribe from an `AsyncPublicClient` or `AsyncSecureClient` and iterate over > the merged event stream. > > ```python theme={null} > from polymarket import AsyncPublicClient > from polymarket.streams import PerpsBboSpec, PerpsTradesSpec > > client = AsyncPublicClient() > > stream = await client.subscribe( > [ > PerpsBboSpec(instrument_id=1), > PerpsTradesSpec(instrument_id=1), > ] > ) > > async for event in stream: > if event.type == "bbo": > # event: PerpsBboEvent > pass > elif event.type == "trade": > # event: PerpsTradeEvent > pass > > if should_close: > await stream.close() > ``` > > The stream yields typed events for each subscription and can be closed when the > live view no longer needs updates. > [tab] API > > Connect to the Perps WebSocket production URL. > > ```text theme={null} > wss://ws.perpetuals.polymarket.com/v1/ws > ``` > > The example below opens a JavaScript WebSocket client, subscribes to public > market-data updates, then unsubscribes and closes the connection. > > ```ts theme={null} > const ws = new WebSocket("wss://ws.perpetuals.polymarket.com/v1/ws"); > const channels = ["bbo::1", "trades::1", "klines::1::1m"]; > > ws.addEventListener("open", () => { > ws.send( > JSON.stringify({ > id: 1, > req: "sub", > chs: channels, > }), > ); > }); > > ws.addEventListener("message", (event) => { > const message = JSON.parse(event.data); > // message: public market data frame > }); > > function unsubscribeAndClose() { > ws.send( > JSON.stringify({ > id: 2, > req: "unsub", > chs: channels, > }), > ); > ws.close(); > } > ``` > > Use `req: "sub"` to subscribe and `req: "unsub"` with the same `chs` values to > unsubscribe. Each request may include an `id` for request-response matching. ## Best Bid and Offer Use best bid and offer updates for top-of-book quotes. > [tab] TypeScript > > Subscribe to best bid and offer updates for one instrument. > > ```ts theme={null} > const bbo = await client.subscribe([{ topic: "perps.bbo", instrumentId: 1 }]); > > for await (const event of bbo) { > // event: PerpsBboEvent > } > ``` > > After subscribing, the stream yields `PerpsBboEvent` objects like this. > > ```ts PerpsBboEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsBboEvent = { > topic: "perps.bbo"; > type: "bbo"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: { > instrumentId: number; > bidPrice: string; > bidQuantity: string; > askPrice: string; > askQuantity: string; > }; > }; > ``` > > ```json PerpsBboEvent Example theme={null} > { > "topic": "perps.bbo", > "type": "bbo", > "channel": "bbo::1", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "instrumentId": 1, > "bidPrice": "99.50", > "bidQuantity": "10.00", > "askPrice": "100.50", > "askQuantity": "10.00" > } > } > ``` > [tab] Python > > Subscribe to best bid and offer updates for one instrument. > > ```python theme={null} > from polymarket.streams import PerpsBboSpec > > bbo = await client.subscribe(PerpsBboSpec(instrument_id=1)) > > async for event in bbo: > # event: PerpsBboEvent > pass > ``` > > After subscribing, the stream yields `PerpsBboEvent` objects like this. > > ```json Example theme={null} > { > "topic": "perps.bbo", > "type": "bbo", > "channel": "bbo::1", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": { > "instrument_id": 1, > "bid_price": "99.50", > "bid_quantity": "10.00", > "ask_price": "100.50", > "ask_quantity": "10.00" > } > } > ``` > [tab] API > > Subscribe to best bid and offer updates for one instrument. > > ```json Subscribe theme={null} > { > "id": 1, > "req": "sub", > "chs": ["bbo::"] > } > ``` > > After subscribing, the stream emits BBO update frames like this. > > ```json theme={null} > { > "ch": "bbo::1", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": { > "iid": 1, > "bp": "99.50", > "bq": "10.00", > "ap": "100.50", > "aq": "10.00" > } > } > ``` ## Interpret Update Timing Use update timing to understand how recent the exchange's reflected activity is. Keep sequence-based reconciliation separate from timing measurements. > [tab] TypeScript > > `timestamp` is the server send time in Unix milliseconds. `eventTimestamp` is > the newest event reflected in the update as `EpochMilliseconds | null`. > Check for `null` before measuring the time spent inside the exchange after that > event: > > ```ts theme={null} > for await (const event of stream) { > if (event.eventTimestamp !== null) { > const exchangeDelayMs = event.timestamp - event.eventTimestamp; > } > } > ``` > > `eventTimestamp: null` means the event horizon is unknown. Local reconnect or > sequence-gap `"resync"` events have no `eventTimestamp`. Do not substitute their > `timestamp` for an exchange event horizon. Server-originated session updates and > resyncs carry the server's horizon through the same field. > [tab] Python > > `timestamp` is the server send time as a UTC `datetime`. `event_timestamp` is > the newest event reflected in the update as a UTC `datetime`, or `None` when > the server reports an unknown horizon. When present, subtract it from > `timestamp` to measure the time spent inside the exchange after that event. > > Local reconnect or sequence-gap `"resync"` events also have > `event_timestamp=None`. Do not substitute their send or local timestamp for an > exchange event horizon. The same timing fields are available on private session > updates and server resyncs. > [tab] API > > Every update envelope includes `ts` (server send time), `ets` (newest reflected > event), and `sq` (sequence). Both timestamps are Unix milliseconds. For a > nonzero `ets`, `ts - ets` measures the time spent inside the exchange after the > event. `ets: 0` means no event horizon is attested. Treat it as unknown. > > The same envelope applies to private account updates. Request acknowledgements > are a separate response shape and do not acquire update timing merely because > they arrive on the same connection. > > For example, subscribe to BBO updates on the open Perps WebSocket connection: > > ```json Subscribe theme={null} > { > "id": 1, > "req": "sub", > "chs": ["bbo::1"] > } > ``` > > An update can arrive with an unknown event horizon: > > ```json Update theme={null} > { > "ch": "bbo::1", > "ts": 1767225600000, > "ets": 0, > "sq": 1234567890, > "data": { > "iid": 1, > "bp": "99.50", > "bq": "10.00", > "ap": "100.50", > "aq": "10.00" > } > } > ``` > > Here `ets: 0` means unknown. Do not calculate an exchange delay from it. ## Order Book Use order book updates for depth across bid and ask price levels. > [tab] TypeScript > > Subscribe to order book updates for one instrument. > > ```ts theme={null} > const book = await client.subscribe([{ topic: "perps.book", instrumentId: 1 }]); > > for await (const event of book) { > // event: PerpsBookEvent > } > ``` > > After subscribing, the stream yields `PerpsBookEvent` objects like this. > > ```ts PerpsBookEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsBookEvent = { > topic: "perps.book"; > type: "book"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: { > instrumentId: number; > bids: Array<{ price: string; quantity: string }>; > asks: Array<{ price: string; quantity: string }>; > }; > }; > ``` > > ```json PerpsBookEvent Example theme={null} > { > "topic": "perps.book", > "type": "book", > "channel": "book::1", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "instrumentId": 1, > "bids": [{ "price": "100.00", "quantity": "10.00" }], > "asks": [{ "price": "101.00", "quantity": "8.00" }] > } > } > ``` > [tab] Python > > Subscribe to order book updates for one instrument. > > ```python theme={null} > from polymarket.streams import PerpsBookSpec > > book = await client.subscribe(PerpsBookSpec(instrument_id=1)) > > async for event in book: > # event: PerpsBookEvent > pass > ``` > > After subscribing, the stream yields `PerpsBookEvent` objects like this. > > ```json Example theme={null} > { > "topic": "perps.book", > "type": "book", > "channel": "book::1", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": { > "instrument_id": 1, > "bids": [{ "price": "100.00", "quantity": "10.00" }], > "asks": [{ "price": "101.00", "quantity": "8.00" }] > } > } > ``` > [tab] API > > Subscribe to order book updates for one instrument. > > ```json Subscribe theme={null} > { > "id": 2, > "req": "sub", > "chs": ["book::"] > } > ``` > > After subscribing, the stream emits book update frames like this. > > ```json theme={null} > { > "ch": "book::1", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": { > "b": [["100.00", "10.00"]], > "a": [["101.00", "8.00"]] > } > } > ``` ## Trades Use trades to update recent-print lists, last-trade displays, or execution-based analytics. > [tab] TypeScript > > Subscribe to public trade updates for one instrument. > > ```ts theme={null} > const trades = await client.subscribe([ > { topic: "perps.trades", instrumentId: 1 }, > ]); > > for await (const event of trades) { > // event: PerpsTradeEvent > } > ``` > > After subscribing, the stream yields `PerpsTradeEvent` objects like this. > > ```ts PerpsTradeEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsTradeEvent = { > topic: "perps.trades"; > type: "trade"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: Array<{ > tradeId: number; > instrumentId: number; > side: "long" | "short"; > settlement: boolean; > price: string; > quantity: string; > timestamp: number; > hash?: string; > }>; > }; > ``` > > ```json PerpsTradeEvent Example theme={null} > { > "topic": "perps.trades", > "type": "trade", > "channel": "trades::1", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": [ > { > "tradeId": 1, > "instrumentId": 1, > "side": "long", > "price": "100.00", > "quantity": "10.00", > "timestamp": 1767225600000, > "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", > "settlement": false > } > ] > } > ``` > > `payload` contains an array of trades. Each trade exposes `settlement`, which is > `false` for ordinary executions and defaults to `false` on older responses. > [tab] Python > > Subscribe to public trade updates for one instrument. > > ```python theme={null} > from polymarket.streams import PerpsTradesSpec > > trades = await client.subscribe(PerpsTradesSpec(instrument_id=1)) > > async for event in trades: > # event: PerpsTradeEvent > pass > ``` > > After subscribing, the stream yields `PerpsTradeEvent` objects like this. > > ```json PerpsTradeEvent Example theme={null} > { > "topic": "perps.trades", > "type": "trade", > "channel": "trades::1", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": [ > { > "trade_id": 1, > "instrument_id": 1, > "side": "long", > "price": "100.00", > "quantity": "10.00", > "timestamp": "2026-01-01T00:00:00Z", > "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", > "settlement": false > } > ] > } > ``` > > `payload` contains a list of `PerpsTrade` objects. Each trade exposes > `settlement`, which is `False` for ordinary executions and defaults to `False` > on older responses. Timestamps are UTC `datetime` values; the JSON above shows > their serialization. > [tab] API > > Subscribe to public trade updates for one instrument. > > ```json Subscribe theme={null} > { > "id": 3, > "req": "sub", > "chs": ["trades::"] > } > ``` > > After subscribing, the stream emits trade update frames like this. > > ```json theme={null} > { > "ch": "trades::1", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": [ > { > "tid": 1, > "iid": 1, > "side": "long", > "p": "100.00", > "qty": "10.00", > "ts": 1767225600000, > "hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", > "settlement": false > } > ] > } > ``` > > `data` contains an array of trades. Each entry includes `settlement`, which is > `false` for ordinary executions. ## Tickers Use ticker updates for the current mark, index, last price, open interest, and funding state. > [tab] TypeScript > > Subscribe to ticker updates for one instrument or all active instruments. > > ```ts Subscribe to one market theme={null} > const tickers = await client.subscribe([ > { topic: "perps.tickers", instrumentId: 1 }, > ]); > ``` > > ```ts Subscribe to all markets theme={null} > const tickers = await client.subscribe([{ topic: "perps.tickers" }]); > ``` > > ```ts theme={null} > for await (const event of tickers) { > // event: PerpsTickerEvent > } > ``` > > Omit `instrumentId` to subscribe to ticker updates for all active instruments. > > After subscribing, the stream yields `PerpsTickerEvent` objects like this. > > ```ts PerpsTickerEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsTickerEvent = { > topic: "perps.tickers"; > type: "ticker"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: { > instrumentId: number; > indexPrice: string; > markPrice: string; > lastPrice: string; > midPrice: string; > openInterest: string; > fundingRate: string; > nextFunding: number; > }; > }; > ``` > > ```json PerpsTickerEvent Example theme={null} > { > "topic": "perps.tickers", > "type": "ticker", > "channel": "tickers::1", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "instrumentId": 1, > "indexPrice": "100.00", > "markPrice": "100.00", > "lastPrice": "100.00", > "midPrice": "100.00", > "openInterest": "10.00", > "fundingRate": "0.0001", > "nextFunding": 1767225600000 > } > } > ``` > [tab] Python > > Subscribe to ticker updates for one instrument or all active instruments. > > ```python Subscribe to one market theme={null} > from polymarket.streams import PerpsTickersSpec > > tickers = await client.subscribe(PerpsTickersSpec(instrument_id=1)) > ``` > > ```python Subscribe to all markets theme={null} > from polymarket.streams import PerpsTickersSpec > > tickers = await client.subscribe(PerpsTickersSpec()) > ``` > > ```python theme={null} > async for event in tickers: > # event: PerpsTickerEvent > pass > ``` > > Omit `instrument_id` to subscribe to ticker updates for all active instruments. > > After subscribing, the stream yields `PerpsTickerEvent` objects like this. > > ```json Example theme={null} > { > "topic": "perps.tickers", > "type": "ticker", > "channel": "tickers::1", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": { > "instrument_id": 1, > "index_price": "100.00", > "mark_price": "100.00", > "last_price": "100.00", > "mid_price": "100.00", > "open_interest": "10.00", > "funding_rate": "0.0001", > "next_funding": 1767225600000 > } > } > ``` > [tab] API > > Subscribe to ticker updates for one instrument or all active instruments. > > ```json Subscribe to one market theme={null} > { > "id": 4, > "req": "sub", > "chs": ["tickers::"] > } > ``` > > ```json Subscribe to all markets theme={null} > { > "id": 5, > "req": "sub", > "chs": ["tickers::all"] > } > ``` > > After subscribing, the stream emits ticker update frames like this. > > ```json theme={null} > { > "ch": "tickers::1", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": { > "iid": 1, > "idx": "100.00", > "mark": "100.00", > "last": "100.00", > "mid": "100.00", > "oi": "10.00", > "fr": "0.0001", > "nxf": 1767225600000 > } > } > ``` ## Statistics Use statistics for 24-hour volume, opening price, and the rolling kline window. > [tab] TypeScript > > Subscribe to 24-hour statistics for one instrument or all active instruments. > > ```ts Subscribe to one market theme={null} > const statistics = await client.subscribe([ > { topic: "perps.statistics", instrumentId: 1 }, > ]); > ``` > > ```ts Subscribe to all markets theme={null} > const statistics = await client.subscribe([{ topic: "perps.statistics" }]); > ``` > > ```ts theme={null} > for await (const event of statistics) { > // event: PerpsStatisticEvent > } > ``` > > Omit `instrumentId` to subscribe to statistics updates for all active instruments. > > After subscribing, the stream yields `PerpsStatisticEvent` objects like this. > > ```ts PerpsStatisticEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsStatisticEvent = { > topic: "perps.statistics"; > type: "statistic"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: { > instrumentId: number; > volume: string; > openPrice: string; > klines: Array<{ > timestamp: number; > open: string; > high: string; > low: string; > close: string; > volume: string; > trades: number; > }>; > }; > }; > ``` > > ```json PerpsStatisticEvent Example theme={null} > { > "topic": "perps.statistics", > "type": "statistic", > "channel": "statistics::1", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "instrumentId": 1, > "volume": "1000.00", > "openPrice": "100.50", > "klines": [ > { > "timestamp": 1767225600000, > "open": "100.00", > "high": "105.00", > "low": "99.00", > "close": "102.00", > "volume": "500.00", > "trades": 42 > } > ] > } > } > ``` > [tab] Python > > Subscribe to 24-hour statistics for one instrument or all active instruments. > > ```python Subscribe to one market theme={null} > from polymarket.streams import PerpsStatisticsSpec > > statistics = await client.subscribe(PerpsStatisticsSpec(instrument_id=1)) > ``` > > ```python Subscribe to all markets theme={null} > from polymarket.streams import PerpsStatisticsSpec > > statistics = await client.subscribe(PerpsStatisticsSpec()) > ``` > > ```python theme={null} > async for event in statistics: > # event: PerpsStatisticEvent > pass > ``` > > Omit `instrument_id` to subscribe to statistics updates for all active > instruments. > > After subscribing, the stream yields `PerpsStatisticEvent` objects like this. > > ```json Example theme={null} > { > "topic": "perps.statistics", > "type": "statistic", > "channel": "statistics::1", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": { > "instrument_id": 1, > "volume": "1000.00", > "open_price": "100.50", > "klines": [ > { > "timestamp": 1767225600000, > "open": "100.00", > "high": "105.00", > "low": "99.00", > "close": "102.00", > "volume": "500.00", > "trades": 42 > } > ] > } > } > ``` > [tab] API > > Subscribe to 24-hour statistics for one instrument or all active instruments. > > ```json Subscribe to one market theme={null} > { > "id": 6, > "req": "sub", > "chs": ["statistics::"] > } > ``` > > ```json Subscribe to all markets theme={null} > { > "id": 7, > "req": "sub", > "chs": ["statistics::all"] > } > ``` > > After subscribing, the stream emits statistics update frames like this. > > ```json theme={null} > { > "ch": "statistics::1", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": { > "iid": 1, > "vol": "1000.00", > "open": "100.50", > "klines": [ > [1767225600000, "100.00", "105.00", "99.00", "102.00", "500.00", 42] > ] > } > } > ``` ## Candles Use candles to update charts with live OHLCV data. > [tab] TypeScript > > Subscribe to candle updates for one instrument and interval. > > ```ts theme={null} > import { PerpsKlineInterval } from "@polymarket/client"; > > const candles = await client.subscribe([ > { > topic: "perps.candles", > instrumentId: 1, > interval: PerpsKlineInterval.OneMinute, > }, > ]); > > for await (const event of candles) { > // event: PerpsCandleEvent > } > ``` > > The public stream supports `1m`, `5m`, `15m`, `1h`, `4h`, `1d`, and `1w` > candle intervals. > > After subscribing, the stream yields `PerpsCandleEvent` objects like this. > > ```ts PerpsCandleEvent Type theme={null} > import type { EpochMilliseconds } from "@polymarket/client"; > > type PerpsCandleEvent = { > topic: "perps.candles"; > type: "candle"; > channel: string; > timestamp: number; > eventTimestamp: EpochMilliseconds | null; > sequence: number; > payload: { > instrumentId: number; > interval: "1m" | "5m" | "15m" | "1h" | "4h" | "1d" | "1w"; > candles: Array<{ > timestamp: number; > open: string; > high: string; > low: string; > close: string; > volume: string; > trades: number; > }>; > }; > }; > ``` > > ```json PerpsCandleEvent Example theme={null} > { > "topic": "perps.candles", > "type": "candle", > "channel": "klines::1::1m", > "timestamp": 1767225600000, > "eventTimestamp": 1767225600000, > "sequence": 1234567890, > "payload": { > "instrumentId": 1, > "interval": "1m", > "candles": [ > { > "timestamp": 1767225600000, > "open": "100.00", > "high": "105.00", > "low": "99.00", > "close": "102.00", > "volume": "500.00", > "trades": 42 > } > ] > } > } > ``` > [tab] Python > > Subscribe to candle updates for one instrument and interval. > > ```python theme={null} > from polymarket.streams import PerpsCandlesSpec > > candles = await client.subscribe( > PerpsCandlesSpec( > instrument_id=1, > interval="1m", > ) > ) > > async for event in candles: > # event: PerpsCandleEvent > pass > ``` > > The public stream supports `1m`, `5m`, `15m`, `1h`, `4h`, `1d`, and `1w` > candle intervals. > > After subscribing, the stream yields `PerpsCandleEvent` objects like this. > > ```json Example theme={null} > { > "topic": "perps.candles", > "type": "candle", > "channel": "klines::1::1m", > "timestamp": "2026-01-01T00:00:00Z", > "event_timestamp": "2026-01-01T00:00:00Z", > "sequence": 1234567890, > "payload": { > "instrument_id": 1, > "interval": "1m", > "candles": [ > { > "timestamp": 1767225600000, > "open": "100.00", > "high": "105.00", > "low": "99.00", > "close": "102.00", > "volume": "500.00", > "trades": 42 > } > ] > } > } > ``` > [tab] API > > Subscribe to candle updates for one instrument and interval. > > ```json Subscribe theme={null} > { > "id": 8, > "req": "sub", > "chs": ["klines::::1m"] > } > ``` > > The public stream supports `1s`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, > `12h`, `1d`, and `1w` candle intervals. Any other interval is refused in the > subscribe acknowledgement with an `invalid channel` error. > > After subscribing, the stream emits kline update frames like this. > > ```json theme={null} > { > "ch": "klines::1::1m", > "ts": 1767225600000, > "ets": 1767225600000, > "sq": 1234567890, > "data": [[1767225600000, "100.00", "105.00", "99.00", "102.00", "500.00", 42]] > } > ``` # Referral Program Source: https://docs.polymarket.com/perps/referral-program Earn a share of Perps trading fees from traders you refer Refer traders to Polymarket Perps and earn a share of the trading fees they pay. Each account has one Perps referral code. Share your Perps link, and when a new trader opens Perps through it, your code is applied to their account automatically. > [!NOTE] > > The program's mechanics, attribution rules, invite limits, and other terms may change as the Perps referral program expands. ## How It Works Every Perps account has one referral code. Your referral code and your Perps invite code are the same string, so the same link invites traders and credits you for the referral. ```text theme={null} https://polymarket.com/perps?c={code} ``` When someone opens Perps through your link, your code is applied to their account automatically. You start earning on the trading fees they generate after they are attributed to your code. A referral code can be applied only once. An account keeps the first code it is given and cannot switch to a different code later. You also cannot apply your own code. ## Rewards You earn **20% of the trading fees** paid by every Perps trader you refer. There is no cap on how much a single referred trader can earn you. | Detail | Perps referral program | | - | - | | Reward | 20% of trading fees paid by referred Perps traders | | Recipient | The referrer | | Trader bonus | No separate bonus is paid to the trader you invite | | Per-user cap | No cap on how much one referred trader can earn you | | Payout timing | Weekly | ## Invite limits and unlocks Each account can refer up to 25 people before volume-based tiers apply. \ Your code starts with 10 available invites and automatically expands to a total limit of 25 after those 10 invites (with active users) are used. From there, you can unlock a total limit of 100 invites at \$100,000 in combined eligible Perps volume, 250 at \$500,000, and 500 at \$1,000,000. Eligible volume includes your own Perps trading volume and volume generated by your direct referrals after they are attributed to your code. Indirect referrals do not count. The tier numbers are total invite limits, not additional invites. If you use every invite in your current tier, your code cannot accept another referral until you unlock the next tier. The maximum standard limit is 500 invites. ## Payouts Referral earnings are paid out weekly. You can see referral payouts in your Perpetuals portfolio history. ## Find and Track Your Code Your referral code is available from your profile and on Perps market pages, so you can copy and share it while you trade. The Perps referrals dashboard shows: * Invites used and remaining under your current limit * Progress toward the next volume-based invite tier * Total sign-ups, direct-referral trading volume, and referral earnings * Per-referral details, including the trader, registration time, and earnings ## Perps vs. Prediction Market Referrals The Perps referral program is separate from the prediction market referral program. They use different codes and track earnings independently. Referring a Perps trader does not affect your prediction market referrals, and a prediction market referral does not affect your Perps referrals. Each program shows up in its own place. # Trading Source: https://docs.polymarket.com/perps/trading Place, manage, and reconcile Perps orders > [!NOTE] > > Trading workflows require an [authenticated > session](/perps/authenticated-sessions). Perps trading changes account exposure on an instrument. An order expresses what the account wants to do, but exposure only changes when the order fills. An accepted order can rest on the book before it fills. ```mermaid theme={null} flowchart TD A[Submit order] --> B{Accepted?} B -->|No| C[Order rejected] B -->|Yes| D{Filled?} D -->|Rests| E[Open order] D -->|Fills| F[Fill] D -->|Partially fills| F F -->|Remaining quantity| E F --> G[Exposure changes] E --> H[Cancel if needed] ``` Use order state to track accepted, resting, modified, canceled, or rejected orders. Use fills and portfolio state to confirm any exposure change. ## Start an Authenticated Session Open an authenticated session before reading private account state or submitting trading commands. See [Authenticated Sessions](/perps/authenticated-sessions) for the full setup flow. > [tab] TypeScript > > Create a `SecureClient`. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > }); > ``` > > Open the Perps session. > > ```ts theme={null} > const session = await client.openPerpsSession(); > ``` > [tab] Python > > Create an `AsyncSecureClient`. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > Open the Perps session. > > ```python theme={null} > session = await client.open_perps_session() > ``` > [tab] API > > Use proxy credentials for private reads and signed trading commands. > > ```http theme={null} > polymarket-proxy: > polymarket-secret: > ``` ## Prepare a Trade Start by identifying the Perps instrument you want to trade. Instruments define the market and include the constraints used later when building an order. > [tab] TypeScript > > Fetch instruments and select the market you want to trade. > > ```ts theme={null} > const instruments = await client.fetchPerpsInstruments(); > const instrument = instruments.find((item) => item.symbol === "BTC-PERP"); > > if (!instrument) { > throw new Error("Instrument not found"); > } > ``` > > Keep the selected `instrument` available for the next steps. > [tab] Python > > Fetch instruments and select the market you want to trade. > > ```python theme={null} > instruments = await client.fetch_perps_instruments() > instrument = next((item for item in instruments if item.symbol == "BTC-PERP"), None) > > if instrument is None: > raise RuntimeError("Instrument not found") > ``` > > Keep the selected `instrument` available for the next steps. > [tab] API > > Fetch instruments and select the market you want to trade. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/info/instruments" > ``` > > The response is a list of instruments. > > ```json theme={null} > [ > { > "instrument_id": 1, > "instrument_type": "perpetual", > "category": "crypto", > "symbol": "BTC-PERP", > "base_asset": "BTC", > "quote_asset": "USD", > "funding_interval": "1h", > "quantity_decimals": 4, > "price_decimals": 2, > "price_bounds": "0.1", > "liquidation_fee": "0.01", > "max_order_count": 200, > "min_notional": "1", > "max_market_notional": "100000", > "max_limit_notional": "1000000", > "max_leverage": 10, > "isolated_only": false, > "risk_tiers": [{ "lower_bound": "0", "max_leverage": 10 }], > "ui_live_time": null > } > ] > ``` > > Keep the selected instrument for the next steps. ## Choose Direction and Size Before placing an order, decide whether it should open new exposure, increase existing exposure, reduce exposure, or close the position. The effect of a buy or sell depends on the current position. | Current position | Buy order | Sell order | | - | - | - | | No position | Opens long | Opens short | | Long | Increases long | Reduces or closes long | | Short | Reduces or closes short | Increases short | To close a position, submit an order in the opposite direction for the current open position size. > [tab] TypeScript > > Read the portfolio when the order decision depends on current exposure. > > ```ts theme={null} > const portfolio = await session.fetchPortfolio(); > const position = portfolio.positions.find( > (item) => item.instrumentId === instrument.id, > ); > ``` > > Positive `position.size` means the account is long. Negative `position.size` > means the account is short. No matching position means the account has no open > exposure for that instrument. > [tab] Python > > Read the portfolio when the order decision depends on current exposure. > > ```python theme={null} > portfolio = await session.fetch_portfolio() > position = next( > (item for item in portfolio.positions if item.instrument_id == instrument.id), > None, > ) > ``` > > Positive `position.size` means the account is long. Negative `position.size` > means the account is short. No matching position means the account has no open > exposure for that instrument. > [tab] API > > Read the portfolio when the order decision depends on current exposure. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > The response includes current positions. > > ```json theme={null} > { > "positions": [ > { > "instrument_id": 1, > "symbol": "BTC-PERP", > "size": "0.01", > "entry_price": "65000", > "leverage": 5, > "cross": false, > "initial_margin": "130", > "maintenance_margin": "65", > "position_value": "650", > "liquidation_price": "52000", > "unrealized_pnl": "0", > "return_on_equity": "0", > "cumulative_funding": "0" > } > ], > "margin": { > "total_account_value": "1000", > "available_order_margin": "870", > "total_initial_margin": "130", > "total_maintenance_margin": "65", > "total_position_value": "650" > }, > "withdrawable": "870", > "in_liquidation": false, > "fee_tier": 0, > "timestamp": 1767000000000 > } > ``` > > Positive `positions[].size` means the account is long. Negative > `positions[].size` means the account is short. No matching position means the > account has no open exposure for that instrument. ## Place Orders Place an order when the account is ready to express buy or sell intent. Use an explicit limit price when you need price protection. Use immediate-or-cancel execution when the order should fill immediately or cancel any unfilled quantity. > [tab] TypeScript > > **1. Choose a Price** > > Fetch a ticker when you need a lightweight current-price reference. Fetch the > book when the order price depends on spread, depth, or top-of-book liquidity. > > ```ts theme={null} > const ticker = await client.fetchPerpsTicker({ instrumentId: instrument.id }); > const book = await client.fetchPerpsBook({ instrumentId: instrument.id }); > ``` > > Set `price` as pUSD per quantity unit, rounded to `instrument.priceDecimals`. > > **2. Build the Order** > > Create the order request from the direction, price, quantity, and execution > behavior you chose. This example submits an immediate-or-cancel (IOC) buy order > for `0.01` BTC-PERP at `65000` pUSD per quantity unit. > > ```ts theme={null} > import { > OrderSide, > PerpsTimeInForce, > type PlacePerpsOrderRequest, > } from "@polymarket/client"; > > const request: PlacePerpsOrderRequest = { > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.IOC, > }; > ``` > > * `side` sets direction based on how you intend to open, increase, reduce, or > close the position. > * `price` is the price you chose in the first step, in pUSD per quantity unit. > * `quantity` is the number of quantity units. Use no more than > `instrument.quantityDecimals` decimal places. > > Use `clientOrderId` when your integration needs its own identifier for tracking > or canceling the order. > > ```ts theme={null} > const request: PlacePerpsOrderRequest = { > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.IOC, > clientOrderId: "7f9e4a2b6c8d0e1f1234567890abcdef", > }; > ``` > > **3. Submit the Order** > > Submit the request with `placeOrder`. It resolves with the matching private order > update after the order is accepted. > > ```ts theme={null} > const order = await session.placeOrder(request); > ``` > > Use the returned order to track whether the order filled, expired, canceled, or > remains on the book. > > ```ts PerpsOrder Type theme={null} > type PerpsOrder = { > id: PerpsOrderId; > instrumentId: PerpsInstrumentId; > side: OrderSide; > price: string; > quantity: string; > timeInForce: PerpsTimeInForce; > postOnly: boolean; > status: PerpsOrderStatus; > restingQuantity: string; > filledQuantity: string; > createdTimestamp: number; > updatedTimestamp: number; > clientOrderId?: string; > tpSl?: PerpsTpSlOrderFields; > }; > ``` > > ```json PerpsOrder Example theme={null} > { > "id": 1234567890, > "instrumentId": 1, > "side": "BUY", > "price": "65000", > "quantity": "0.01", > "timeInForce": "ioc", > "postOnly": false, > "status": "filled", > "restingQuantity": "0", > "filledQuantity": "0.01", > "createdTimestamp": 1767000010000, > "updatedTimestamp": 1767000010500, > "clientOrderId": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ``` > > For an IOC order, `status` can be one of these values. > > | Status | Description | > | - | - | > | `PerpsOrderStatus.Filled` | The order fully filled. | > | `PerpsOrderStatus.IocNoFill` | The order did not fill. | > | `PerpsOrderStatus.IocExpired` | The order filled partially and the remainder canceled. | > | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | > [tab] Python > > **1. Choose a Price** > > Fetch a ticker when you need a lightweight current-price reference. Fetch the > book when the order price depends on spread, depth, or top-of-book liquidity. > > ```python theme={null} > ticker = await client.fetch_perps_ticker(instrument_id=instrument.id) > book = await client.fetch_perps_book(instrument_id=instrument.id) > ``` > > Set `price` as pUSD per quantity unit, rounded to `instrument.price_decimals`. > > **2. Build the Order** > > Create the order request from the direction, price, quantity, and execution > behavior you chose. This example submits an immediate-or-cancel (IOC) buy order > for `0.01` BTC-PERP at `65000` pUSD per quantity unit. > > ```python theme={null} > request = { > "instrument_id": instrument.id, > "side": "BUY", > "price": "65000", > "quantity": "0.01", > "time_in_force": "ioc", > } > ``` > > * `side` sets direction based on how you intend to open, increase, reduce, or > close the position. > * `price` is the price you chose in the first step, in pUSD per quantity unit. > * `quantity` is the number of quantity units. Use no more than > `instrument.quantity_decimals` decimal places. > > Use `client_order_id` when your integration needs its own identifier for tracking > or canceling the order. > > ```python theme={null} > request = { > "instrument_id": instrument.id, > "side": "BUY", > "price": "65000", > "quantity": "0.01", > "time_in_force": "ioc", > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef", > } > ``` > > **3. Submit the Order** > > Submit the request with `place_order`. It resolves with the matching private > order update after the order is accepted. > > ```python theme={null} > result = await session.place_order(**request) > # result.order: PerpsOrder > ``` > > Use `result.order` to track whether the order filled, expired, canceled, or > remains on the book. > > ```json Example theme={null} > { > "id": 1234567890, > "instrument_id": 1, > "side": "BUY", > "price": "65000", > "quantity": "0.01", > "time_in_force": "ioc", > "post_only": false, > "status": "filled", > "resting_quantity": "0", > "filled_quantity": "0.01", > "created_at": 1767000010000, > "updated_at": 1767000010500, > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ``` > > For an IOC order, `result.order.status` can be one of these values. > > | Status | Description | > | - | - | > | `filled` | The order fully filled. | > | `ioc_no_fill` | The order did not fill. | > | `ioc_expired` | The order filled partially and the remainder canceled. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | > [tab] API > > **1. Choose a Price** > > Fetch current market data when the order price depends on live prices or > available liquidity. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/info/tickers" \ > --data-urlencode "instrument_id=1" > > curl -G "https://api.perpetuals.polymarket.com/v1/info/book" \ > --data-urlencode "instrument_id=1" \ > --data-urlencode "depth=100" > ``` > > Use tickers for a lightweight current-price reference. Use the book when the > order price depends on spread, depth, or top-of-book liquidity. > > Set price as pUSD per quantity unit, rounded to the instrument's > `price_decimals`. > > **2. Build the Order Operation** > > Create a `createOrders` operation from the direction, price, quantity, and > execution behavior you chose. This example submits an immediate-or-cancel (`ioc`) > buy order for `0.01` BTC-PERP at `65000` pUSD per quantity unit. > > | Concept | Field | Notes | > | - | - | - | > | Instrument | `iid` | Instrument identifier. | > | Direction | `buy` | `true` buys, `false` sells. | > | Price | `p` | Price chosen in the first step. | > | Quantity | `qty` | Number of quantity units, with no more than `quantity_decimals` decimal places. | > | Time in force | `tif` | Use `ioc` for this basic order. | > | Client order ID | `c` | Optional identifier your integration can use to track or cancel the order. Must be a 32-character lowercase hex value. | > > ```json theme={null} > { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "ioc", > "c": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ] > } > ``` > > **3. Create the Operation Hash** > > Create the operation hash from the compact signable representation of the order > operation. For `createOrders`, the compact operation is: > > ```ts theme={null} > ["createOrders", [[iid, buy, p, qty, tif, po, ro, c, tr]]]; > ``` > > Omit `undefined` array entries from the compact operation, then > MessagePack-encode it and hash the encoded bytes with `keccak256`. > > The example below uses `@msgpack/msgpack` and Viem. > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const signableOperation = [ > "createOrders", > [ > [ > 1, > true, > "65000", > "0.01", > "ioc", > false, > undefined, > "7f9e4a2b6c8d0e1f1234567890abcdef", > undefined, > ].filter((value) => value !== undefined), > ], > ] as const; > > const opHash = keccak256(encode(signableOperation)); > ``` > > **4. Create Order Typed Data** > > Create an EIP-712 `Op` typed-data payload. > > ```json theme={null} > { > "domain": { > "name": "Polymarket", > "version": "1", > "chainId": 137 > }, > "primaryType": "Op", > "types": { > "Op": [ > { "name": "data", "type": "bytes32" }, > { "name": "salt", "type": "uint64" }, > { "name": "ts", "type": "uint64" } > ] > }, > "message": { > "data": "", > "salt": 234567890, > "ts": 1767000010000 > } > } > ``` > > | Field | Value | > | - | - | > | `data` | Operation hash from the previous step. | > | `salt` | Random integer generated for this signed request. | > | `ts` | Current Unix timestamp in milliseconds. | > > **5. Sign Order Typed Data** > > Sign the `Op` typed data with the proxy signer private key. The example below > uses Viem. > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount(""); > > const signature = await account.signTypedData({ > domain: { > name: "Polymarket", > version: "1", > chainId: 137, > }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: opHash, > salt: 234567890, > ts: 1767000010000, > }, > }); > ``` > > **6. Submit the Order** > > Submit the signed request to `POST /v1/trade/orders`. > > ```bash theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "ioc", > "c": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ] > }, > "sig": "", > "salt": 234567890, > "ts": 1767000010000 > }' > ``` > > The response confirms whether the order request was accepted. Read the order > state separately to see whether it filled, expired, or rests on the book. > > ```json Success theme={null} > [ > { > "status": "ok", > "oid": 1234567890, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ] > ``` > > ```json Failure theme={null} > [ > { > "status": "err", > "error": "insufficient_margin" > } > ] > ``` > > On success, keep `oid` as the order ID. If you supplied `c`, the response also > echoes it as `coid`. > > **7. Read the Order State** > > Fetch the order snapshot by `order_id` or `client_order_id` to see whether the > order filled, expired, or canceled after acceptance. > > ```bash Order ID theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "order_id=1234567890" > ``` > > ```bash Client Order ID theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "client_order_id=7f9e4a2b6c8d0e1f1234567890abcdef" > ``` > > Use the order state fields to reconcile fill quantity, resting quantity, and > status. > > | Field | Meaning | > | - | - | > | `order_id` | Order ID returned as `oid` in the acknowledgement. | > | `instrument_id` | Instrument identifier. | > | `buy` | `true` for buy orders, `false` for sell orders. | > | `price` | pUSD price per quantity unit. | > | `quantity` | Original order quantity. | > | `tif` | Time in force. | > | `post_only` | Whether the order was post-only. | > | `ro` | Whether the order was reduce-only. | > | `status` | Latest known order status. | > | `resting_quantity` | Quantity still resting on the book. | > | `filled_quantity` | Quantity that has filled. | > | `created_timestamp` | Creation timestamp in milliseconds. | > | `updated_timestamp` | Last update timestamp in milliseconds. | > | `client_order_id` | Client order ID, present when supplied in the request. | > > If the order snapshot is not available immediately, retry the read or listen to > the private `orders` WebSocket channel for live updates. > > ```json theme={null} > [ > { > "order_id": 1234567890, > "instrument_id": 1, > "buy": true, > "price": "65000", > "quantity": "0.01", > "tif": "ioc", > "post_only": false, > "ro": false, > "status": "filled", > "resting_quantity": "0", > "filled_quantity": "0.01", > "created_timestamp": 1767000010000, > "updated_timestamp": 1767000010500, > "client_order_id": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > ] > ``` > > After this `ioc` order resolves, `status` is one of these values. > > | Status | Description | > | - | - | > | `filled` | The order fully filled. | > | `ioc_no_fill` | The order did not fill. | > | `ioc_expired` | The order filled partially and the remainder canceled. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | ## Take Profit & Stop Loss Use take-profit and stop-loss (TP/SL) orders to place conditional exits for a position. A take-profit order exits when price moves in your favor. A stop-loss order exits when price moves against you. ### How Triggers Work TP/SL orders watch the mark price, not the last traded price. A trigger fires when the mark price touches the trigger price, then submits a reduce-only order to close exposure. | Position | Take-profit fires when | Stop-loss fires when | | - | - | - | | Long | Mark rises to trigger | Mark falls to trigger | | Short | Mark falls to trigger | Mark rises to trigger | For a long position, take-profit triggers usually sit above the current mark and stop-loss triggers usually sit below it. For a short position, the directions are reversed. ### Market and Limit Closes Choose how the exit should execute after the trigger fires. | Close Type | What Happens | Available For | | - | - | - | | Market | The exit executes immediately against available liquidity. | Bracket orders and positions | | Limit | The exit places a limit order and can remain open until it fills. | Bracket orders only | A resting limit exit does not lock up the position. A more aggressive reduce-only order on the same side (a manual close, or the position's other trigger firing later) takes priority and cancels the resting exit to make room. In particular, a fired stop-loss can displace a resting take-profit exit, so a bracket whose take-profit is already resting keeps a working stop. Closes that execute immediately never cancel a resting exit up front. See [Close a Position](#close-a-position) for the full priority rules. ### Place a Bracket Order A bracket order submits one entry order with up to one take-profit and one stop-loss trigger. The triggers stay dormant until the entry fills in full. If the entry is canceled, rejected, or only partially filled, the triggers are canceled too. A bracket protects the completed entry, not a partial fill. > [!NOTE] > > You cannot attach TP/SL triggers to an order that is already resting on the > book. To protect a position from an existing order, wait for the fill and then > protect the position. > [tab] TypeScript > > Place a GTC entry order with take-profit and stop-loss triggers. > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const result = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.GTC, > takeProfit: { > triggerPrice: "70000", > }, > stopLoss: { > triggerPrice: "62000", > }, > }); > > const entryOrderId = result.order.id; > const takeProfitOrderId = result.tpSl.takeProfit?.orderId; > const stopLossOrderId = result.tpSl.stopLoss?.orderId; > ``` > > `result.order` is the entry order. `result.tpSl` contains the order IDs for the > conditional exits that were accepted with the entry order. > > > [accordion] Output: PlacePerpsOrderWithTpSlResult > > > > ```json theme={null} > > { > > "order": { > > "id": 1234567890, > > "instrumentId": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "timeInForce": "gtc", > > "postOnly": false, > > "status": "open", > > "restingQuantity": "0.01", > > "filledQuantity": "0", > > "createdTimestamp": 1767000010000, > > "updatedTimestamp": 1767000010500 > > }, > > "tpSl": { > > "takeProfit": { "orderId": 1234567891 }, > > "stopLoss": { "orderId": 1234567892 } > > } > > } > > ``` > > Add `limitPrice` to a trigger when the exit should place a limit order at trigger > time. > > ```ts theme={null} > const result = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.GTC, > stopLoss: { > triggerPrice: "62000", > limitPrice: "61900", > }, > }); > ``` > [tab] Python > > Place a GTC entry order with take-profit and stop-loss triggers. > > ```python theme={null} > from polymarket import PerpsTpSlTrigger > > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > price="65000", > quantity="0.01", > time_in_force="gtc", > take_profit=PerpsTpSlTrigger(trigger_price="70000"), > stop_loss=PerpsTpSlTrigger(trigger_price="62000"), > ) > > # result.order.id: PerpsOrderId > # result.tp_sl.take_profit.order_id: PerpsOrderId > # result.tp_sl.stop_loss.order_id: PerpsOrderId > ``` > > `result.order` is the entry order. `result.tp_sl` contains the order IDs for the > conditional exits that were accepted with the entry order. > > > [accordion] Output: PerpsOrderPlacement > > > > ```json theme={null} > > { > > "order": { > > "id": 1234567890, > > "instrument_id": 1, > > "side": "BUY", > > "price": "65000", > > "quantity": "0.01", > > "time_in_force": "gtc", > > "post_only": false, > > "status": "open", > > "resting_quantity": "0.01", > > "filled_quantity": "0", > > "created_at": 1767000010000, > > "updated_at": 1767000010500 > > }, > > "tp_sl": { > > "take_profit": { "order_id": 1234567891 }, > > "stop_loss": { "order_id": 1234567892 } > > } > > } > > ``` > > Add `limit_price` to a trigger when the exit should place a limit order at > trigger time. > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > price="65000", > quantity="0.01", > time_in_force="gtc", > stop_loss=PerpsTpSlTrigger( > trigger_price="62000", > limit_price="61900", > ), > ) > ``` > [tab] API > > Submit the entry order and its TP/SL children in one `createOrders` operation > with `grp` set to `"order"`. > > ```json theme={null} > { > "type": "createOrders", > "grp": "order", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "gtc", > "c": "7f9e4a2b6c8d0e1f1234567890abcdef" > }, > { > "iid": 1, > "buy": false, > "qty": "0.01", > "ro": true, > "tr": { > "market": true, > "trp": "70000", > "tpsl": "tp" > } > }, > { > "iid": 1, > "buy": false, > "qty": "0.01", > "ro": true, > "tr": { > "market": true, > "trp": "62000", > "tpsl": "sl" > } > } > ] > } > ``` > > Use the same signing flow as [Place Orders](#place-orders). For hashing, sign the > compact operation, not the structured JSON body. The TP/SL group is the third > compact element: > > ```ts theme={null} > ["createOrders", [entryOrder, takeProfitOrder, stopLossOrder], "order"]; > ``` > > Then submit the signed request to `POST /v1/trade/orders`. > > ```bash theme={null} > curl -X POST "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "createOrders", > "grp": "order", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "gtc", > "c": "7f9e4a2b6c8d0e1f1234567890abcdef" > }, > { > "iid": 1, > "buy": false, > "qty": "0.01", > "ro": true, > "tr": { > "market": true, > "trp": "70000", > "tpsl": "tp" > } > }, > { > "iid": 1, > "buy": false, > "qty": "0.01", > "ro": true, > "tr": { > "market": true, > "trp": "62000", > "tpsl": "sl" > } > } > ] > }, > "sig": "", > "salt": 234567890, > "ts": 1767000010000 > }' > ``` > > The response returns one acknowledgement per submitted order. > > ```json theme={null} > [ > { > "status": "ok", > "oid": 1234567890, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" > }, > { "status": "ok", "oid": 1234567891 }, > { "status": "ok", "oid": 1234567892 } > ] > ``` > > Set `market` to `true` for market-style trigger execution. For limit trigger > execution, omit `market` and set `p` on the TP/SL child order. ### Protect an Existing Position Add TP/SL orders to a position that is already open. Position TP/SL closes the full position at trigger time, so it does not use a fixed quantity. Position TP/SL has a few placement rules: * The account must already hold a position in the instrument. * The account can have at most one position take-profit and one position stop-loss per instrument. * When the trigger fires, the exit submits immediately. Position TP/SL does not support limit prices. * A position trigger is rejected if the current mark has already crossed it, because it would fire immediately. > [tab] TypeScript > > Place TP/SL orders for the full current position. > > ```ts theme={null} > const result = await session.placePositionTpSl({ > instrumentId: instrument.id, > takeProfit: { > triggerPrice: "70000", > }, > stopLoss: { > triggerPrice: "62000", > }, > }); > > const takeProfitOrderId = result.tpSl.takeProfit?.orderId; > const stopLossOrderId = result.tpSl.stopLoss?.orderId; > ``` > > `placePositionTpSl` sizes the exit at trigger time, so you do not pass a position > side or quantity. > [tab] Python > > Place TP/SL orders for the full current position. > > ```python theme={null} > from polymarket import PerpsPositionTpSlTrigger > > result = await session.place_position_tp_sl( > instrument_id=instrument.id, > take_profit=PerpsPositionTpSlTrigger(trigger_price="70000"), > stop_loss=PerpsPositionTpSlTrigger(trigger_price="62000"), > ) > > # result.take_profit.order_id: PerpsOrderId > # result.stop_loss.order_id: PerpsOrderId > ``` > > `place_position_tp_sl` sizes the exit at trigger time, so you do not pass a > position side or quantity. > [tab] API > > Submit position-scoped TP/SL orders with `grp` set to `"position"`. Use > `qty: "0"` so the engine sizes the exit at trigger time. > > Set `buy` to the side that closes the position: `false` for a long position and > `true` for a short position. > > ```json theme={null} > { > "type": "createOrders", > "grp": "position", > "args": [ > { > "iid": 1, > "buy": false, > "qty": "0", > "ro": true, > "tr": { > "market": true, > "trp": "70000", > "tpsl": "tp" > } > }, > { > "iid": 1, > "buy": false, > "qty": "0", > "ro": true, > "tr": { > "market": true, > "trp": "62000", > "tpsl": "sl" > } > } > ] > } > ``` > > Sign the compact operation, not the structured JSON body. The TP/SL group is the > third compact element: > > ```ts theme={null} > ["createOrders", [takeProfitOrder, stopLossOrder], "position"]; > ``` > > Submit the signed request to `POST /v1/trade/orders` and keep the returned order > IDs for reconciliation. ### Update or Cancel TP/SL TP/SL orders cannot be modified in place. To change a trigger price or execution type, cancel the old trigger and create a replacement. * For position TP/SL, cancel the old trigger before creating another trigger of the same kind for the instrument. * For a bracket whose entry is still resting, cancel the entry and place a new bracket with the updated triggers. * For a bracket whose entry already filled, cancel the armed trigger and create position TP/SL as the replacement. Cancel-then-create is not atomic. Between the cancel and the replacement, the position may be unprotected. ## Configure Order Behavior So far, we have used immediate-or-cancel orders. Next, we’ll look at how to control whether an order rests, fills immediately, or only adds liquidity. ### Good-Til-Canceled Orders Use good-til-canceled orders when the order can rest on the book until it fills or you cancel it. > [tab] TypeScript > > Set `timeInForce` to GTC. > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.GTC, > }); > ``` > > For a GTC order, `order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `PerpsOrderStatus.Open` | The order is resting on the book. | > | `PerpsOrderStatus.Filled` | The order fully filled before resting. | > | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | > > If a GTC order partially fills and rests, inspect `filledQuantity` and > `restingQuantity` on the returned order. > [tab] Python > > Set `time_in_force` to `gtc`. > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > price="65000", > quantity="0.01", > time_in_force="gtc", > ) > > # result.order: PerpsOrder > ``` > > For a GTC order, `result.order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `open` | The order is resting on the book. | > | `filled` | The order fully filled before resting. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | > > If a GTC order partially fills and rests, inspect > `result.order.filled_quantity` and `result.order.resting_quantity`. > [tab] API > > Set `tif` to `"gtc"`. > > ```json theme={null} > { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "gtc" > } > ] > } > ``` > > After the order is accepted, read order state from `GET /v1/account/orders` or > the private `orders` WebSocket channel. For a `gtc` order, `status` can be one > of these values. > > | Status | Meaning | > | - | - | > | `open` | The order is resting on the book. | > | `filled` | The order fully filled before resting. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | > > If a `gtc` order partially fills and rests, inspect `filled_quantity` and > `resting_quantity`. ### Post-Only Orders A post-only order is a special type of good-til-canceled order that only adds liquidity. If it would cross the book and take liquidity, it is rejected instead. > [tab] TypeScript > > Set `postOnly: true` on a GTC order. > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.GTC, > postOnly: true, > }); > ``` > > For a post-only order, `order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `PerpsOrderStatus.Open` | The order was accepted and added to the book. | > | `PerpsOrderStatus.PostOnlyRejected` | The order would have crossed the book and taken liquidity. | > [tab] Python > > Set `post_only=True` on a GTC order. > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > price="65000", > quantity="0.01", > time_in_force="gtc", > post_only=True, > ) > > # result.order: PerpsOrder > ``` > > For a post-only order, `result.order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `open` | The order was accepted and added to the book. | > | `post_only_rejected` | The order would have crossed the book and taken liquidity. | > [tab] API > > Set `po: true` on a `gtc` order. > > ```json theme={null} > { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "gtc", > "po": true > } > ] > } > ``` > > For a post-only order, `status` can be one of these values. > > | Status | Meaning | > | - | - | > | `open` | The order was accepted and added to the book. | > | `post_only_rejected` | The order would have crossed the book and taken liquidity. | ### Fill-Or-Kill Orders Use fill-or-kill orders when the full quantity must fill immediately or cancel. These orders do not rest on the book. > [tab] TypeScript > > Set `timeInForce` to FOK. > > ```ts theme={null} > import { OrderSide, PerpsTimeInForce } from "@polymarket/client"; > > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > price: "65000", > quantity: "0.01", > timeInForce: PerpsTimeInForce.FOK, > }); > ``` > > For a FOK order, `order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `PerpsOrderStatus.Filled` | The full order quantity filled immediately. | > | `PerpsOrderStatus.FokUnfilled` | The full order quantity could not fill immediately, so it canceled. | > | `PerpsOrderStatus.StpCancelled` | The order would have matched your own resting order, so it canceled. | > [tab] Python > > Set `time_in_force` to `fok`. > > ```python theme={null} > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > price="65000", > quantity="0.01", > time_in_force="fok", > ) > > # result.order: PerpsOrder > ``` > > For a FOK order, `result.order.status` can be one of these values. > > | Status | Meaning | > | - | - | > | `filled` | The full order quantity filled immediately. | > | `fok_unfilled` | The full order quantity could not fill immediately, so it canceled. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | > [tab] API > > Set `tif` to `"fok"`. > > ```json theme={null} > { > "type": "createOrders", > "args": [ > { > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "fok" > } > ] > } > ``` > > For a `fok` order, `status` can be one of these values. > > | Status | Meaning | > | - | - | > | `filled` | The full order quantity filled immediately. | > | `fok_unfilled` | The full order quantity could not fill immediately, so it canceled. | > | `stp_cancelled` | The order would have matched your own resting order, so it canceled. | ## Modify Orders Change the price or total quantity of an existing order without canceling it and creating a new one. The order keeps its identity, direction, and other execution constraints. You can modify standalone good-til-canceled (GTC) limit orders that are resting on the book, including partially filled orders. ### Modify an Order > [tab] TypeScript > > SDK support is coming soon. > [tab] Python > > SDK support is coming soon. > [tab] API > > **1. Build and Sign the Modification** > > Choose whether to identify the order by its exchange order ID or client order > ID. Set `p` to the new limit price and `qty` to the new total quantity, including > any quantity that has already filled. > > Use the same proxy-signing flow as [Place Orders](#place-orders). When creating > the operation hash, MessagePack-encode the matching compact operation and hash > the encoded bytes with `keccak256`. > > ```ts Order ID theme={null} > ["modifyOrders", [[1234567890, "100.25", "7"]]]; > ``` > > ```ts Client Order ID theme={null} > ["modifyOrdersCOID", [["7f9e4a2b6c8d0e1f1234567890abcdef", "100.25", "7"]]]; > ``` > > **2. Submit the Modification** > > Send the signed operation to the route that matches the identifier you chose. > > ```bash Order ID theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "modifyOrders", > "args": [ > { > "oid": 1234567890, > "p": "100.25", > "qty": "7" > } > ] > }, > "sig": "", > "salt": 234567894, > "ts": 1767000050000 > }' > ``` > > ```bash Client Order ID theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/orders-coid" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "modifyOrdersCOID", > "args": [ > { > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef", > "p": "100.25", > "qty": "7" > } > ] > }, > "sig": "", > "salt": 234567894, > "ts": 1767000050000 > }' > ``` > > **3. Check the Result** > > The response contains one result per requested order, in request order. A > successful result returns the updated order. In this example, `4` units were > already filled, so changing the total quantity to `7` leaves `3` resting. > > ```json Success theme={null} > [ > { > "status": "ok", > "order": { > "oid": 1234567890, > "iid": 1, > "buy": true, > "p": "100.25", > "qty": "7", > "tif": "gtc", > "po": false, > "ro": false, > "status": "open", > "rest": "3", > "fill": "4", > "cts": 1767000010000, > "uts": 1767000050000, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" > } > } > ] > ``` > > ```json Failure theme={null} > [ > { > "status": "err", > "oid": 1234567890, > "error": "modify_would_cross" > } > ] > ``` > > A rejected result does not change the live order, although separately processed > fills or cancellations still can. See > [Modify Order Errors](/perps/errors#modify-order-errors) for the complete > rejection list. ### Resize a Partially Filled Order The order's cumulative fill is its current total quantity minus its current remaining quantity. The requested new total must be greater than that cumulative fill. On success, the new remaining quantity is: ```text theme={null} new remaining quantity = requested total quantity - cumulative fill ``` For example, suppose an order has a total quantity of `10`, a remaining quantity of `6`, and therefore a cumulative fill of `4`. Modifying the total quantity to `7` leaves `3` resting. A requested total of `4` or less is rejected. The exchange evaluates these values from the live order when it applies the modification. A fill that arrives while the modification is in progress can change the resulting remaining quantity or cause the request to be rejected. ### Check Whether an Order Can Be Modified | Rule | Behavior | | - | - | | Resting order | The order must be a standalone GTC limit order currently resting on the book. | | Order in flight | An order still moving through creation or taker delay is not yet resting and cannot be modified. | | Crossing price | The modified order must remain non-crossing against the live opposite best price when it is applied. | | TP/SL relationship | A TP/SL leg or an order with attached or order-scoped TP/SL cannot be modified. | | Rejected modification | The rejected modification itself does not alter the live order; separately processed activity still can. | ### Understand Queue Priority Queue treatment is determined from the live order state when the modification is applied. | Modification | Queue treatment | | - | - | | Same price and lower total quantity | Keeps its existing queue priority. | | Higher total quantity | Re-enters at the back of the price level. | | Any price change | Re-enters at the back of the price level. | | Same price and same total quantity | Rejected because it makes no change. | ## Cancel Orders Cancel resting orders when they are stale, conflict with updated strategy, or should no longer remain on the book. Canceling a resting order does not close any filled position. ### Cancel Single Orders > [tab] TypeScript > > Cancel stale orders by order ID or by client order ID. > > ```ts Order ID theme={null} > const result = await session.cancelOrder({ > orderId: order.id, > }); > ``` > > ```ts Client Order ID theme={null} > const result = await session.cancelOrder({ > clientOrderId: "7f9e4a2b6c8d0e1f1234567890abcdef", > }); > ``` > > Use `result.status` to confirm whether the cancel request was accepted. > > | Status | Meaning | > | - | - | > | `ok` | The cancel command was accepted. | > | `err` | The cancel command was not accepted. | > > Canceling a working order removes it from the book. > [tab] Python > > Cancel stale orders by order ID or by client order ID. > > ```python Order ID theme={null} > result = await session.cancel_order(order_id=order.id) > # result: PerpsCancelOrderResult > ``` > > ```python Client Order ID theme={null} > result = await session.cancel_order( > client_order_id="7f9e4a2b6c8d0e1f1234567890abcdef" > ) > # result: PerpsCancelOrderResult > ``` > > Use `result.status` to confirm whether the cancel request was accepted. > > | Status | Meaning | > | - | - | > | `ok` | The cancel command was accepted. | > | `err` | The cancel command was not accepted. | > > Canceling a working order removes it from the book. > [tab] API > > Cancel by order ID with `DELETE /v1/trade/orders`. > > Use the same signing flow as [Place Orders](#place-orders) to create > ``. For hashing, sign the compact operation, not the > structured JSON body: > > ```ts theme={null} > ["cancelOrders", [1234567890]]; > ``` > > ```bash theme={null} > curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "cancelOrders", > "args": [1234567890] > }, > "sig": "", > "salt": 234567892, > "ts": 1767000030000 > }' > ``` > > Cancel by client order ID with `DELETE /v1/trade/orders-coid`. For hashing, > the compact operation is: > > ```ts theme={null} > ["cancelOrdersCOID", ["7f9e4a2b6c8d0e1f1234567890abcdef"]]; > ``` > > ```bash theme={null} > curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders-coid" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "cancelOrdersCOID", > "args": ["7f9e4a2b6c8d0e1f1234567890abcdef"] > }, > "sig": "", > "salt": 234567893, > "ts": 1767000040000 > }' > ``` > > The response contains one cancel result per requested order. > > ```json Success theme={null} > [ > { > "status": "ok", > "oid": 1234567890 > } > ] > ``` > > ```json Failure theme={null} > [ > { > "status": "err", > "oid": 1234567890, > "error": "order_not_in_orderbook" > } > ] > ``` > > A rejected result carries a stable `error` identifier, along with the `oid` or > `coid` it applies to. Branch on the identifier: it tells you whether the order is > gone for good or whether the cancel is worth sending again. > > | Error | Description | Retry | > | - | - | - | > | `order_unknown` | The `coid` does not resolve to a live order on your account. Only returned by `DELETE /v1/trade/orders-coid`. | Only while your create is unacknowledged | > | `order_not_in_orderbook` | The order does not exist in exchange state. It already terminated, or it never existed. | No — terminal | > | `order_already_terminal` | The order filled, was canceled, or was rejected before this cancel could remove it. | No — terminal | > | `order_in_flight` | The order exists but is not cancellable yet: held in the taker delay queue, the account is being liquidated, or acceptance is in flight while held cancels are disabled or cancel-only mode is active. | Yes — transient | > | `order_not_pending_engine` | An earlier cancel for the same order is already queued or in flight. The first cancel still stands. | No — wait for the first cancel | > | `order_not_found` | The order became terminal while a resting cancel was in flight, or the take-profit or stop-loss order does not exist. | No — terminal | > > `order_unknown` covers cases that cannot be told apart: the create never > reached the exchange, it reached the exchange but is not visible to this read > yet, or the order terminated long enough ago that its `coid` left the bounded > recently-terminal window — Perps keeps no order history beyond that window, so > an older terminated `coid` looks identical to one that never existed. This > identifier is answered from a cached view of your live orders that can briefly > trail the exchange, so it is not proof the order is absent — while your create > is still unacknowledged, send the cancel again. Once the create has been > acknowledged, reconcile against your order updates and fills instead of > retrying. > > `order_not_in_orderbook` means the exchange evaluated the cancel against its own > state and found no such order, so the result is authoritative. Nothing re-creates > a departed order, so retrying cannot change the outcome. Canceling an `oid` owned > by another account returns this same identifier, so order IDs are not probeable > across accounts. > > `order_already_terminal` is likewise authoritative: the order reached a terminal > state — filled, canceled, or rejected — before this cancel could act, so > retrying cannot succeed. Cancel by `coid` returns it for regular orders that > terminated recently; take-profit and stop-loss `coid`s have no equivalent > lookup and return `order_not_found` instead. > > A cancel that arrives while the order is awaiting risk checks succeeds > immediately, unless the account is being liquidated. The canceled order > will not enter the order book. > > A cancel that arrives while the order's accept is still on its way to the > matching engine does not fail with `order_in_flight`: the exchange holds one > such cancel and applies it as soon as the accept completes. Its response then > reports the real outcome — success once the order is removed, or > `order_already_terminal` if the order filled or was rejected first. Additional > cancels sent while one is held return `order_not_pending_engine`. Orders held > in the taker delay queue keep returning `order_in_flight` until their delay > elapses, and cancels keep returning `order_in_flight` while the account is > being liquidated. If the exchange disables this behavior, an > accepting-order cancel returns `order_in_flight` instead — transient, retry > shortly. > > > [!NOTE] > > > > During maintenance the exchange can enter cancel-only mode: new orders are > > rejected with `cancel_only_mode` while cancels keep working. The mode does not > > purge resting orders, and a cancel reject means the same thing it does at any > > other time — with one exception: while cancel-only mode is on, a cancel for an > > order whose accept is still in flight is not held and returns > > `order_in_flight`. ### Cancel Batches and Handle Retries Cancel a selected group together, then reconcile each outcome in the original request order. An unsuccessful cancellation does not imply the order is still open: it may already have filled or reached another terminal state. > [tab] TypeScript > > Use the authenticated `session` from above with `cancelOrders()`. Supply either > `orderIds` or `clientOrderIds`: > > ```ts theme={null} > const results = await session.cancelOrders({ orderIds: [1, 2] }); > ``` > > > [accordion] Output: PerpsCancelOrderResult\[] > > > > ```json theme={null} > > [ > > { "status": "ok", "orderId": 1 }, > > { "status": "err", "orderId": 2, "error": "order_in_flight" } > > ] > > ``` > > Only `order_in_flight` is retried automatically. Defaults allow four attempts per > order, including the first, and two seconds before starting a retry. Confirmed > results stay in their original positions while only transient rejections are > retried. Exhaustion returns the last rejection. Unknown nonempty error codes > remain strings and are not retried. > > Set `retry: false` for one attempt, or choose bounds explicitly. The same options > apply to `cancelOrder()`: > > ```ts theme={null} > const results = await session.cancelOrders({ > orderIds: [1, 2], > retry: { maxAttempts: 3, maxElapsedMs: 1_000 }, > expiresAt: Date.now() + 1_000, > }); > ``` > > `expiresAt` also stops new retries. These limits do not interrupt an in-flight > command. An optional `signal` prevents the first attempt when already aborted > and stops subsequent retries after the current attempt settles. > > Whole-request failures throw. A first-attempt failure propagates directly; a > later failure throws `PerpsCancelRetryError`: > > ```ts theme={null} > import { PerpsCancelRetryError } from "@polymarket/client"; > > try { > const results = await session.cancelOrders({ orderIds: [1, 2] }); > console.log(results); > } catch (error) { > if (!(error instanceof PerpsCancelRetryError)) throw error; > console.log(error.results, error.pendingIndexes, error.cause); > } > ``` > > `results` contains the last received outcomes. Entries named by `pendingIndexes` > are historical rejections, not results of the failed retry. Reconcile those > orders against current order state and fills before submitting another > cancellation: a lost response may hide a completed cancellation. > [tab] Python > > Use the authenticated `session` from above with `cancel_orders()`. Supply either > `order_ids` or `client_order_ids`: > > ```python theme={null} > results = await session.cancel_orders(order_ids=[1, 2]) > ``` > > > [accordion] Output: tuple of PerpsCancelOrderResult > > > > ```python theme={null} > > ( > > PerpsCancelOrderSuccess(status="ok", order_id=1, client_order_id=None), > > PerpsCancelOrderRejection( > > status="err", > > error=PerpsCancelOrderErrorCode.ORDER_IN_FLIGHT, > > order_id=2, > > client_order_id=None, > > ), > > ) > > ``` > > Only `order_in_flight` is retried automatically. Defaults allow four attempts per > order, including the first, and two seconds before starting a retry. Confirmed > results stay in their original positions while only transient rejections are > retried. Exhaustion returns the last rejection. Known codes use > `PerpsCancelOrderErrorCode`; unknown nonempty codes remain strings and are not > retried. > > Set `retry=False` for one attempt, or choose bounds explicitly. The same options > apply to `cancel_order()`: > > ```python theme={null} > from datetime import datetime, timedelta, timezone > > from polymarket import PerpsCancelRetryOptions > > results = await session.cancel_orders( > order_ids=[1, 2], > retry=PerpsCancelRetryOptions(max_attempts=3, max_elapsed_s=1.0), > expires_at=datetime.now(timezone.utc) + timedelta(seconds=1), > ) > ``` > > `expires_at` also stops new retries and accepts a datetime or epoch milliseconds. > These limits do not interrupt an in-flight command. Cancelling the task raises > `asyncio.CancelledError` and stops retries; it cannot undo a submitted command. > Reconcile the order before submitting another cancellation after task cancellation. > > Whole-request failures raise. A first-attempt failure propagates directly; a > later failure raises `PerpsCancelRetryError`: > > ```python theme={null} > from polymarket import PerpsCancelRetryError > > try: > results = await session.cancel_orders(order_ids=[1, 2]) > print(results) > except PerpsCancelRetryError as error: > print(error.results, error.pending_indexes, error.__cause__) > ``` > > `results` contains the last received outcomes. Entries named by `pending_indexes` > are historical rejections, not results of the failed retry. Reconcile those > orders against current order state and fills before submitting another > cancellation: a lost response may hide a completed cancellation. > [tab] API > > Use the cancellation requests above with multiple identifiers in `op.args`. > Process every returned result before selecting which orders to retry. Retry only > identified `order_in_flight` rejections with a bounded delay and attempt budget; > retain successful outcomes and terminal rejections. > > A single `err` result without `oid` or `coid` rejects the whole request. Do not > interpret it as one order's outcome. If the response is lost or cannot be matched > to the request, reconcile order state and fills before submitting another > cancellation. ### Cancel All Orders Cancel every open order for your account in a single request, for example when pulling quotes during a fast move or shutting down a strategy. Scope the request to one instrument to clear only that book while quotes on other instruments stay live. A successful response confirms the request was accepted, not that every order is already gone: individual orders can still race with fills or other cancels. Confirm the final state from your open orders. > [tab] TypeScript > > Cancel all open orders, or only the open orders on one instrument. > > ```ts All Instruments theme={null} > await session.cancelAllOrders(); > ``` > > ```ts One Instrument theme={null} > await session.cancelAllOrders({ instrumentId: instrument.id }); > ``` > > The call resolves once the request is accepted and throws if it is rejected. > Use `session.fetchOpenOrders()` to confirm the remaining open orders. > [tab] Python > > Cancel all open orders, or only the open orders on one instrument. > > ```python All Instruments theme={null} > await session.cancel_all_orders() > ``` > > ```python One Instrument theme={null} > await session.cancel_all_orders(instrument_id=instrument.id) > ``` > > The call returns once the request is accepted and raises if it is rejected. > Use `session.fetch_open_orders()` to confirm the remaining open orders. > [tab] API > > Cancel all open orders with `DELETE /v1/trade/orders/all`. Use the same > signing flow as [Place Orders](#place-orders) to create ``. > For hashing, sign the compact operation, not the structured JSON body. > > To cancel across all instruments, the compact `args` is an empty array: > > ```ts theme={null} > ["cancelAll", []]; > ``` > > ```bash theme={null} > curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders/all" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "cancelAll", > "args": {} > }, > "sig": "", > "salt": 234567894, > "ts": 1767000050000 > }' > ``` > > To cancel only the open orders on one instrument, the compact `args` holds the > instrument ID, and the JSON body passes it as `iid`: > > ```ts theme={null} > ["cancelAll", [1]]; > ``` > > ```bash theme={null} > curl -X DELETE "https://api.perpetuals.polymarket.com/v1/trade/orders/all" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "cancelAll", > "args": { "iid": 1 } > }, > "sig": "", > "salt": 234567895, > "ts": 1767000060000 > }' > ``` > > The response confirms the request was accepted. > > ```json theme={null} > { "status": "ok" } > ``` ### Auto Cancel Orders Auto-cancel is a dead man's switch for your open orders. Arm it with a future deadline, and the exchange cancels every open order on your account when that deadline passes. Keep re-arming it with a fresh deadline while your integration runs. If the process crashes or loses connectivity, the re-arms stop, the deadline passes, and your resting orders leave the book with no action from you. The switch fires once. After it fires, the schedule clears itself, and orders you place afterwards are unprotected until you arm it again. Arming again replaces the current schedule, and the deadline must be at least five seconds in the future. Accounts can trigger auto-cancel a limited number of times per UTC day, so disarm the switch on graceful shutdown instead of letting it fire. > [tab] TypeScript > > Arm the switch with `session.armAutoCancel` and keep protection active by > re-arming on an interval shorter than the deadline. > > ```ts Arm and Re-Arm theme={null} > await session.armAutoCancel({ cancelAt: Date.now() + 60_000 }); > > const rearm = setInterval(() => { > // A missed re-arm is fail-safe: the armed switch still fires. > session.armAutoCancel({ cancelAt: Date.now() + 60_000 }).catch((error) => { > console.error("auto-cancel re-arm failed", error); > }); > }, 20_000); > ``` > > ```ts Disarm theme={null} > clearInterval(rearm); > await session.disarmAutoCancel(); > ``` > > Arming throws `UserInputError` when `cancelAt` is less than five seconds in > the future, and `AutoCancelDailyLimitError` once the account reaches its daily > trigger limit. Disarming is always allowed. Check the armed deadline and > today's trigger usage with `session.fetchAutoCancelStatus()`. > > ```ts theme={null} > const status = await session.fetchAutoCancelStatus(); > ``` > > | Field | Meaning | > | - | - | > | `deadline` | Armed cancel time in Unix milliseconds, or `null` when nothing is armed. | > | `triggered` | Times the switch fired today. | > | `dailyLimit` | Maximum triggers allowed per UTC day. | > | `nextReset` | When the daily trigger counter resets, in Unix milliseconds. | > [tab] Python > > Arm the switch with `session.arm_auto_cancel` and keep protection active by > re-arming on an interval shorter than the deadline. `cancel_at` accepts a > `datetime` or a Unix timestamp in milliseconds. > > ```python Arm and Re-Arm theme={null} > import asyncio > import logging > from datetime import datetime, timedelta, timezone > > async def keep_armed(): > while True: > await asyncio.sleep(20) > try: > await session.arm_auto_cancel( > cancel_at=datetime.now(timezone.utc) + timedelta(seconds=60) > ) > except Exception: > # A missed re-arm is fail-safe: the armed switch still fires. > logging.exception("auto-cancel re-arm failed") > > await session.arm_auto_cancel( > cancel_at=datetime.now(timezone.utc) + timedelta(seconds=60) > ) > rearm = asyncio.create_task(keep_armed()) > ``` > > ```python Disarm theme={null} > rearm.cancel() > await session.disarm_auto_cancel() > ``` > > Arming raises `UserInputError` when `cancel_at` is less than five seconds in > the future, and `AutoCancelDailyLimitError` once the account reaches its daily > trigger limit. Disarming is always allowed. Check the armed deadline and > today's trigger usage with `session.fetch_auto_cancel_status()`. > > ```python theme={null} > status = await session.fetch_auto_cancel_status() > # status: PerpsAutoCancelStatus > ``` > > | Field | Meaning | > | - | - | > | `deadline` | Armed cancel time as a UTC `datetime`, or `None` when nothing is armed. | > | `triggered` | Times the switch fired today. | > | `daily_limit` | Maximum triggers allowed per UTC day. | > | `next_reset` | When the daily trigger counter resets, as a UTC `datetime`. | > [tab] API > > Arm the switch with `PATCH /v1/trade/auto-cancel`. Use the same signing flow > as [Place Orders](#place-orders) to create ``. For > hashing, sign the compact operation, not the structured JSON body. > > The compact `args` holds the cancel time as a Unix timestamp in milliseconds, > and the JSON body passes it as `time`: > > ```ts theme={null} > ["autoCancel", [1767000130000]]; > ``` > > ```bash theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/auto-cancel" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "autoCancel", > "args": { "time": 1767000130000 } > }, > "sig": "", > "salt": 234567896, > "ts": 1767000070000 > }' > ``` > > The response echoes the armed deadline: > > ```json theme={null} > { "status": "ok", "deadline": 1767000130000 } > ``` > > To clear the schedule without triggering it, send `0` as the time: > > ```ts theme={null} > ["autoCancel", [0]]; > ``` > > ```bash theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/auto-cancel" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "autoCancel", > "args": { "time": 0 } > }, > "sig": "", > "salt": 234567897, > "ts": 1767000080000 > }' > ``` > > A cleared schedule reports a `0` deadline: > > ```json theme={null} > { "status": "ok", "deadline": 0 } > ``` > > Arming is rejected with `auto_cancel_daily_limit_reached` once the account > reaches its daily trigger limit. Clearing is always allowed. Check the armed > deadline and today's trigger usage with `GET /v1/account/auto-cancel`. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/auto-cancel" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > ```json theme={null} > { > "deadline": 1767000130000, > "triggered": 2, > "daily_limit": 1000, > "next_reset": 1767052800000 > } > ``` > > | Field | Meaning | > | - | - | > | `deadline` | Armed cancel time in Unix milliseconds, or `0` when nothing is armed. | > | `triggered` | Times the switch fired today. | > | `daily_limit` | Maximum triggers allowed per UTC day. | > | `next_reset` | When the daily trigger counter resets, in Unix milliseconds. | ## Close a Position Closing a position is a new order in the opposite direction of the open position. Use the full open position size to close. Use a smaller quantity to reduce instead. Mark close orders reduce-only so they cannot flip the account into new exposure if position state changes before execution. Reduce-only is a safeguard, not a sizing shortcut. You still choose the quantity: use the full position size to close or a smaller quantity to reduce. An order that would increase exposure or flip the position is rejected. | Current Position | Reduce-Only Buy | Reduce-Only Sell | | - | - | - | | Long | Rejected | Reduces or closes | | Short | Reduces or closes | Rejected | | No position | Rejected | Rejected | Resting reduce-only orders on the same instrument share the position as a closing budget, but they never block a close that executes immediately. An IOC, FOK, or market-priced reduce-only order is accepted against the full position size. After a fill, the exchange cancels whole resting reduce-only orders on the same side, least aggressive first, until their remaining exposure fits the reduced position. A close that fills nothing leaves them untouched. A reduce-only order that would rest competes on price instead: a lower-priced sell or a higher-priced buy outranks a resting reduce-only order and cancels it in full, least aggressive first, until the new order fits, while an equal or worse price keeps the resting order's claim. Any excess that still does not fit is trimmed from the new order, or the order is rejected. > [tab] TypeScript > > Find the current position by market symbol and parse its decimal size. > > ```ts theme={null} > import Big from "big.js"; > > const portfolio = await session.fetchPortfolio(); > const position = portfolio.positions.find((item) => item.symbol === "BTC-PERP"); > > if (!position) { > throw new Error("No open BTC-PERP position"); > } > > const size = new Big(position.size); > ``` > > Close a long position by selling the full size, or close a short position by > buying the absolute position size. > > ```ts Close Long theme={null} > import { > OrderSide, > PerpsOrderStatus, > PerpsTimeInForce, > } from "@polymarket/client"; > > if (size.gt(0)) { > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.SELL, > quantity: position.size, > timeInForce: PerpsTimeInForce.IOC, > reduceOnly: true, > }); > > if (order.status === PerpsOrderStatus.Filled) { > // The position is fully closed. > } > } > ``` > > ```ts Close Short theme={null} > import { > OrderSide, > PerpsOrderStatus, > PerpsTimeInForce, > } from "@polymarket/client"; > > if (size.lt(0)) { > const order = await session.placeOrder({ > instrumentId: instrument.id, > side: OrderSide.BUY, > quantity: size.abs().toString(), > timeInForce: PerpsTimeInForce.IOC, > reduceOnly: true, > }); > > if (order.status === PerpsOrderStatus.Filled) { > // The position is fully closed. > } > } > ``` > > These examples use an IOC order with no price and only treat the close as > complete when `order.status` is `PerpsOrderStatus.Filled`. Include a price when > you want to limit execution, or use FOK or GTC when the close should follow a > different order behavior. > > For reduce-only orders, also handle these statuses. > > | Status | Meaning | > | - | - | > | `PerpsOrderStatus.ReduceOnlyInvalid` | The order would not reduce the position, or had no priority over resting reduce-only orders already covering it. | > | `PerpsOrderStatus.ReduceOnlyExpired` | A fill shrank the position below the outstanding reduce-only exposure, or a higher-priority reduce-only order displaced this resting order. | > [tab] Python > > Find the current position by market symbol and inspect its decimal size. > > ```python theme={null} > portfolio = await session.fetch_portfolio() > position = next((item for item in portfolio.positions if item.symbol == "BTC-PERP"), None) > > if position is None: > raise RuntimeError("No open BTC-PERP position") > > # position: PerpsPosition > # position.size: Decimal > ``` > > Close a long position by selling the full size, or close a short position by > buying the absolute position size. > > ```python Close Long theme={null} > if position.size > 0: > result = await session.place_order( > instrument_id=instrument.id, > side="SELL", > quantity=position.size, > time_in_force="ioc", > reduce_only=True, > ) > > if result.order.status == "filled": > # The position is fully closed. > pass > ``` > > ```python Close Short theme={null} > if position.size < 0: > result = await session.place_order( > instrument_id=instrument.id, > side="BUY", > quantity=abs(position.size), > time_in_force="ioc", > reduce_only=True, > ) > > if result.order.status == "filled": > # The position is fully closed. > pass > ``` > > These examples use an IOC order with no price and only treat the close as > complete when `result.order.status` is `filled`. Include a price when you want to > limit execution, or use FOK or GTC when the close should follow a different order > behavior. > > For reduce-only orders, also handle these statuses. > > | Status | Meaning | > | - | - | > | `reduce_only_invalid` | The order would not reduce the position, or had no priority over resting reduce-only orders already covering it. | > | `reduce_only_expired` | A fill shrank the position below the outstanding reduce-only exposure, or a higher-priority reduce-only order displaced this resting order. | > [tab] API > > Fetch the portfolio and inspect the position `size` for the instrument. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > Use the sign of `positions[].size` to determine the closing side. A positive > size is a long position. A negative size is a short position. > > ```json Position excerpt theme={null} > { > "positions": [ > { > "instrument_id": 1, > "symbol": "BTC-PERP", > "size": "0.01" > }, > { > "instrument_id": 2, > "symbol": "ETH-PERP", > "size": "-0.5" > } > ] > } > ``` > > Submit a `createOrders` operation in the opposite direction for the full size and > set `ro: true` so the order cannot increase or flip exposure. > > | Current `positions[].size` | Closing order `buy` | Closing order `qty` | Closing order `ro` | > | - | - | - | - | > | Positive | `false` | Current position size. | `true` | > | Negative | `true` | Absolute position size. | `true` | > > Closing can use `ioc`, `gtc`, or `fok` depending on the execution behavior you > want. > > For reduce-only orders, `status` can include these values. > > | Status | Meaning | > | - | - | > | `reduce_only_invalid` | The order would not reduce the position, or had no priority over resting reduce-only orders already covering it. | > | `reduce_only_expired` | A fill shrank the position below the outstanding reduce-only exposure, or a higher-priority reduce-only order displaced this resting order. | ## Update Leverage Leverage controls how much notional exposure a position can carry relative to its margin. Cross margin uses available account collateral for the position; isolated margin keeps collateral allocated to that position. Some instruments support only isolated margin. Validate leverage against the instrument's maximum and current risk tiers before submitting a change. Leverage and margin mode resolve independently for each instrument. An explicit per-instrument setting takes precedence over a default assigned to your exchange-managed account group. Without either, leverage defaults to the instrument's maximum and margin mode to isolated. Account configuration reads report the resolved values; updates set explicit values. Switching margin mode requires no position and no open orders in that instrument, including orders awaiting risk approval or execution. Close the position and cancel all orders before switching. See [Default Leverage and Margin Mode](/perps/learn-about-trading/margin#default-leverage-and-margin-mode) for how inherited settings apply. > [tab] TypeScript > > **1. Read Current Configuration** > > Read the current account configuration before changing leverage. > > ```ts theme={null} > const [config] = await session.fetchAccountConfig({ > instrumentId: instrument.id, > }); > ``` > > `config` includes the current leverage and margin mode for the instrument. > > **2. Update Leverage** > > Update leverage and whether the position uses cross margin. Validate leverage > against `instrument.maxLeverage` and the current `instrument.riskTiers`, and > request `crossMargin: true` only when `instrument.isolatedOnly` is `false`. > > ```ts theme={null} > const result = await session.updateLeverage({ > instrumentId: instrument.id, > leverage: 5, > crossMargin: false, > }); > ``` > > The result includes the effective leverage configuration after the update. > > ```json Example Result theme={null} > { > "status": "ok", > "instrumentId": 1, > "leverage": 5, > "crossMargin": false > } > ``` > [tab] Python > > **1. Read Current Configuration** > > Read the current account configuration before changing leverage. > > ```python theme={null} > configs = await session.fetch_account_config( > instrument_id=instrument.id, > ) > # configs[0]: PerpsAccountConfig > ``` > > Each config includes the current leverage and margin mode for the instrument. > > **2. Update Leverage** > > Update leverage and whether the position uses cross margin. Validate leverage > against `instrument.max_leverage` and the current `instrument.risk_tiers`, and > request `cross_margin=True` only when `instrument.isolated_only` is `False`. > > ```python theme={null} > result = await session.update_leverage( > instrument_id=instrument.id, > leverage=5, > cross_margin=False, > ) > # result: PerpsUpdateLeverageResult > ``` > > The result includes the effective leverage configuration after the update. > > ```json Example Result theme={null} > { > "status": "ok", > "instrument_id": 1, > "leverage": 5, > "cross_margin": false > } > ``` > [tab] API > > **1. Read Current Configuration** > > Read the current account configuration before changing leverage. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/config" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > The account config includes the current `leverage` and margin mode for the > instrument. > > **2. Build the Leverage Operation** > > Create an `updateLeverage` operation with the instrument ID, leverage, and margin > mode. Validate leverage against the instrument's `max_leverage` and current > `risk_tiers`, and set `cross` to `true` only when the instrument reports > `isolated_only: false`. > > ```json theme={null} > { > "type": "updateLeverage", > "args": { > "iid": 1, > "lev": 5, > "cross": false > } > } > ``` > > **3. Create the Operation Hash** > > Create the operation hash from the compact signable representation of the > operation. > > ```ts theme={null} > ["updateLeverage", [iid, lev, cross]]; > ``` > > Omit `undefined` array entries from the compact operation, then > MessagePack-encode it and hash the encoded bytes with `keccak256`. > > ```ts theme={null} > import { encode } from "@msgpack/msgpack"; > import { keccak256 } from "viem"; > > const signableOperation = ["updateLeverage", [1, 5, false]] as const; > > const opHash = keccak256(encode(signableOperation)); > ``` > > **4. Sign Leverage Typed Data** > > Create and sign an EIP-712 `Op` typed-data payload with the proxy signer private > key. > > ```ts Viem theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const account = privateKeyToAccount(""); > > const signature = await account.signTypedData({ > domain: { > name: "Polymarket", > version: "1", > chainId: 137, > }, > primaryType: "Op", > types: { > Op: [ > { name: "data", type: "bytes32" }, > { name: "salt", type: "uint64" }, > { name: "ts", type: "uint64" }, > ], > }, > message: { > data: opHash, > salt: 234567894, > ts: 1767000050000, > }, > }); > ``` > > **5. Submit the Update** > > Submit the signed request to `PATCH /v1/trade/leverage`. > > ```bash theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/leverage" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "updateLeverage", > "args": { > "iid": 1, > "lev": 5, > "cross": false > } > }, > "sig": "", > "salt": 234567894, > "ts": 1767000050000 > }' > ``` > > **6. Read the Confirmed Result** > > The response confirms the effective leverage configuration after the update, or > returns an error if the update is rejected. > > ```json Success theme={null} > { > "status": "ok", > "instrument_id": 1, > "leverage": 5, > "cross": false > } > ``` > > ```json Failure theme={null} > { > "status": "err", > "error": "invalid_leverage" > } > ``` > > A rejected mode switch reports `position_exists` while a position is open, or > `open_orders_exist` while orders remain, including orders awaiting risk approval > or execution. Close the position and cancel all orders before switching. ### Update Multiple Instruments Change leverage and margin mode for up to 100 distinct instruments in one submission. Check each instrument's leverage limits and margin-mode eligibility as described above before submitting the batch. > [tab] TypeScript > > Use `updateLeverages` on the authenticated `PerpsSession` opened earlier. The > following example uses two instrument IDs selected from `fetchPerpsInstruments`. > > ```ts theme={null} > const results = await session.updateLeverages({ > updates: [ > { instrumentId: 1, leverage: 5, crossMargin: false }, > { instrumentId: 2, leverage: 10, crossMargin: true }, > ], > }); > > for (const result of results) { > if (result.status === "err") { > console.error(result.instrumentId, result.error); > } > } > ``` > > The returned array contains a `PerpsUpdateLeverageBatchResult` for each update. > Here is an illustrative mixed result: > > > [accordion] Output: PerpsUpdateLeverageBatchResult > > > > ```json PerpsUpdateLeverageBatchResult Example theme={null} > > [ > > { "status": "ok", "instrumentId": 1, "leverage": 5, "crossMargin": false }, > > { "status": "err", "instrumentId": 2, "error": "internal_error" } > > ] > > ``` > > > > `PerpsUpdateLeverageBatchResult` is the union of `PerpsUpdateLeverageResult` > > and `PerpsUpdateLeverageRejection`, exported from `@polymarket/client`. > > The `status` field distinguishes confirmed settings from per-instrument errors. > > Pass one to 100 updates with unique `instrumentId` values. IDs must be integers > from 0 to 4,294,967,295, and `leverage` must be a positive integer no greater than > 4,294,967,295. The SDK validates the entire batch before signing or sending it; > the instrument's own leverage limit can be lower. > [tab] Python > > Use `update_leverages` on the authenticated `PerpsSession` opened earlier with > `AsyncSecureClient`. The example uses two IDs selected from `fetch_perps_instruments`. > > ```python theme={null} > from polymarket import PerpsLeverageUpdate > > results = await session.update_leverages([ > PerpsLeverageUpdate(instrument_id=1, leverage=5, cross_margin=False), > PerpsLeverageUpdate(instrument_id=2, leverage=10, cross_margin=True), > ]) > > for result in results: > if result.status == "err": > print(result.instrument_id, result.error) > ``` > > The returned tuple contains a `PerpsBatchLeverageResult` for each update. > Here is an illustrative mixed result: > > > [accordion] Output: PerpsBatchLeverageResult > > > > ```json PerpsBatchLeverageResult Example theme={null} > > [ > > { "status": "ok", "instrument_id": 1, "leverage": 5, "cross_margin": false }, > > { "status": "err", "instrument_id": 2, "error": "internal_error" } > > ] > > ``` > > > > `PerpsBatchLeverageResult` is the union of `PerpsUpdateLeverageResult` and > > `PerpsLeverageUpdateRejection`, available from `polymarket.models`. The `status` field > > distinguishes confirmed settings from per-instrument errors. > > Pass one to 100 updates with unique `instrument_id` values. IDs must be integers > from 0 to 4,294,967,295, and `leverage` must be a positive integer no greater than > 4,294,967,295. Invalid inputs raise `UserInputError` before signing or sending; > the instrument's own leverage limit can be lower. > [tab] API > > Submit a signed `updateLeverages` operation to `PATCH /v1/trade/leverage/batch` > using the proxy signer from the session setup above. > > Create the operation hash from this compact representation, preserving the > order of the updates: > > ```json theme={null} > [ > "updateLeverages", > [ > [1, 5, false], > [2, 10, true] > ] > ] > ``` > > MessagePack-encode the compact operation, hash it with `keccak256`, and sign the > EIP-712 `Op` using the signing steps in the preceding single-instrument example. > Use a fresh salt and current millisecond timestamp; the request must contain the > same values used in the signature. The values below illustrate the body shape. > > ```bash theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/leverage/batch" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "updateLeverages", > "args": [ > { "iid": 1, "lev": 5, "cross": false }, > { "iid": 2, "lev": 10, "cross": true } > ] > }, > "sig": "", > "salt": 234567894, > "ts": 1767000050000 > }' > ``` > > A response can contain both accepted and rejected updates: > > ```json Example Response theme={null} > [ > { "status": "ok", "instrument_id": 1, "leverage": 5, "cross": false }, > { "status": "err", "instrument_id": 2, "error": "internal_error" } > ] > ``` > > Each entry includes `instrument_id`; an accepted entry echoes `leverage` and > `cross`, while a rejected entry includes `error`. Send one to 100 updates with > unique `iid` values. Both `iid` and `lev` must fit unsigned 32-bit integers; > choose positive leverage within the instrument's limit. Each update counts > toward the account's action rate limit. Results preserve submission order. Updates are processed sequentially and are not atomic: a rejection does not roll back other accepted updates. Inspect every result before deciding what to retry. An internal error result leaves that instrument's application outcome unknown. A whole-request internal error, timeout, or lost connection can also leave the outcome unknown. Read the current account configuration before retrying affected instruments. The SDKs do not automatically resubmit these batch commands. ## Adjust Isolated Margin Adjust the collateral allocated to an open position when you want to give it more buffer or release collateral that is no longer needed. > [tab] TypeScript > > Use `updateMargin` on the authenticated Perps session. > > ```ts Add Margin theme={null} > await session.updateMargin({ > instrumentId: instrument.id, > amount: "100.00", > }); > ``` > > ```ts Remove Margin theme={null} > await session.updateMargin({ > instrumentId: instrument.id, > amount: "-25.00", > }); > ``` > [tab] Python > > Use `update_margin` on the authenticated Perps session. > > ```python Add Margin theme={null} > await session.update_margin( > instrument_id=instrument.id, > amount="100.00", > ) > ``` > > ```python Remove Margin theme={null} > await session.update_margin( > instrument_id=instrument.id, > amount="-25.00", > ) > ``` > [tab] API > > Submit a signed `updateMargin` operation to `PATCH /v1/trade/margin`. Use the > same signing flow as [Place Orders](#place-orders), and sign this compact > operation for each request: > > ```ts theme={null} > ["updateMargin", [iid, amt]]; > ``` > > ```bash Add Margin theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/margin" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "updateMargin", > "args": { > "iid": 1, > "amt": "100.00" > } > }, > "sig": "", > "salt": 444444444, > "ts": 1767000013000 > }' > ``` > > ```bash Remove Margin theme={null} > curl -X PATCH "https://api.perpetuals.polymarket.com/v1/trade/margin" \ > -H "content-type: application/json" \ > -d '{ > "op": { > "type": "updateMargin", > "args": { > "iid": 1, > "amt": "-25.00" > } > }, > "sig": "", > "salt": 444444445, > "ts": 1767000013001 > }' > ``` > > The response uses the generic `{ "status": "ok" }` or `{ "status": "err", > "error": string }` shape. The amount is a precision-safe decimal string in the instrument's quote asset. A positive value adds isolated margin; a negative value removes it. This workflow applies only to an open position using isolated margin. For allocation and removal constraints, see [Adjusting Isolated Margin](/perps/learn-about-trading/margin#adjusting-isolated-margin). ## Reconcile Trade State Keep local trading state in sync by starting from a local snapshot, applying live updates, and reconciling again whenever the session tells you state may have been missed. TP/SL orders appear alongside regular orders in open-order and order-history reads. Track their lifecycle in addition to the position and fills they protect. | Lifecycle State | Meaning | | - | - | | Dormant | Waiting for a bracket entry order to fill in full. | | Armed | Watching the mark price for the trigger. | | Triggered | Fired and submitted the closing order. | | Canceled | Removed by you, by parent cancellation, or by auto-cancel. | | Cleared | Removed because the protected position closed or changed sides. | > [tab] TypeScript > > **1. Fetch a Startup Snapshot** > > Fetch a snapshot when the session starts. > > ```ts theme={null} > async function fetchTradingSnapshot() { > const [balances, openOrders, orders, fills, portfolio] = await Promise.all([ > session.fetchBalances(), > session.fetchOpenOrders({ instrumentId: instrument.id }), > session.fetchOrders({ instrumentId: instrument.id }), > session.listFills().firstPage(), > session.fetchPortfolio(), > ]); > > return { balances, openOrders, orders, fills, portfolio }; > } > > let snapshot = await fetchTradingSnapshot(); > ``` > > **2. Apply Live Events** > > Then apply trading live events while the session is open. > > ```ts theme={null} > for await (const event of session) { > switch (event.type) { > case "balance": { > // event.payload: PerpsBalance > break; > } > > case "order": { > // event.payload: PerpsOrder > break; > } > > case "fill": { > // event.payload: PerpsAccountFill > break; > } > > case "portfolio": { > // event.payload.positions contains current exposure. > break; > } > > case "tpsl": { > // event.payload: PerpsTpSlUpdateEvent["payload"] > break; > } > } > } > ``` > > **3. Reconcile on Resync** > > When `event.type` is `"resync"`, use account reads as the first step to > reconcile local state before applying more local assumptions. > > ```ts theme={null} > if (event.type === "resync") { > snapshot = await fetchTradingSnapshot(); > } > ``` > [tab] Python > > **1. Fetch a Startup Snapshot** > > Fetch a snapshot when the session starts. > > ```python theme={null} > import asyncio > > > async def fetch_trading_snapshot(): > balances, open_orders, orders, fills, portfolio = await asyncio.gather( > session.fetch_balances(), > session.fetch_open_orders(instrument_id=instrument.id), > session.fetch_orders(instrument_id=instrument.id), > session.list_fills().first_page(), > session.fetch_portfolio(), > ) > > return { > "balances": balances, > "open_orders": open_orders, > "orders": orders, > "fills": fills, > "portfolio": portfolio, > } > > > snapshot = await fetch_trading_snapshot() > ``` > > **2. Apply Live Events** > > Then apply trading live events while the session is open. > > ```python theme={null} > async for event in session: > if event.type == "balance": > # event.payload: PerpsBalance > pass > elif event.type == "order": > # event.payload: PerpsOrder > pass > elif event.type == "fill": > # event.payload: PerpsFill > pass > elif event.type == "portfolio": > # event.payload.positions contains current exposure. > pass > elif event.type == "tpsl": > # event.payload: PerpsTpSlUpdate > pass > ``` > > **3. Reconcile on Resync** > > When `event.type` is `"resync"`, use account reads as the first step to > reconcile local state before applying more local assumptions. > > ```python theme={null} > if event.type == "resync": > snapshot = await fetch_trading_snapshot() > ``` > [tab] API > > **1. Fetch a Startup Snapshot** > > Use account reads to build the local startup snapshot. > > ```bash Balances theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/balances" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > ```bash Open Orders theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/open-orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > ```bash Orders theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > ```bash Fills theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/fills" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > ```bash Portfolio theme={null} > curl "https://api.perpetuals.polymarket.com/v1/account/portfolio" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " > ``` > > **2. Apply Live Events** > > Then use the authenticated WebSocket session for live updates. Private WebSocket > frames can include balances, orders, fills, portfolio, and TP/SL updates. See > [Authenticated Sessions](/perps/authenticated-sessions) for the session > lifecycle. > > ```json Balance theme={null} > { > "ch": "balances", > "data": { > "asset": "pUSD", > "balance": "1000", > "value": "1000" > }, > "sq": 1, > "ts": 1767000010000 > } > ``` > > ```json Order theme={null} > { > "ch": "orders", > "data": { > "oid": 1234567890, > "iid": 1, > "buy": true, > "p": "65000", > "qty": "0.01", > "tif": "gtc", > "po": false, > "status": "open", > "rest": "0.01", > "fill": "0", > "cts": 1767000010000, > "uts": 1767000010000, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" > }, > "sq": 2, > "ts": 1767000010000 > } > ``` > > ```json Fill theme={null} > { > "ch": "fills", > "data": { > "tid": 987654321, > "oid": 1234567890, > "iid": 1, > "side": "long", > "p": "65000", > "qty": "0.01", > "taker": true, > "fee": "0.26", > "fea": "pUSD", > "psz": "0", > "pep": "0", > "pnl": "0", > "liq": false, > "adl": false, > "ts": 1767000010500, > "coid": "7f9e4a2b6c8d0e1f1234567890abcdef" > }, > "sq": 3, > "ts": 1767000010500 > } > ``` > > ```json Portfolio theme={null} > { > "ch": "portfolio", > "data": { > "positions": [ > { > "instrument_id": 1, > "symbol": "BTC-PERP", > "size": "0.01", > "entry_price": "65000", > "leverage": 5, > "cross": false, > "initial_margin": "130", > "maintenance_margin": "13", > "position_value": "650", > "liquidation_price": "52000", > "unrealized_pnl": "0", > "return_on_equity": "0", > "cumulative_funding": "0" > } > ], > "margin": { > "total_account_value": "1000", > "available_order_margin": "870", > "total_initial_margin": "130", > "total_maintenance_margin": "13", > "total_position_value": "650" > }, > "withdrawable": "870", > "in_liquidation": false, > "fee_tier": 0, > "timestamp": 1767000010500 > }, > "sq": 4, > "ts": 1767000010500 > } > ``` > > ```json TP/SL theme={null} > { > "ch": "tpsl::1", > "data": { > "oid": 1234567891, > "st": "armed" > }, > "sq": 5, > "ts": 1767000010500 > } > ``` > > **3. Detect Sequence Gaps** > > Track the `sq` sequence number for each channel. If a sequence number is skipped > or the connection reconnects, repeat the account reads above before relying on > local state. ### Handle Terminal Order Outcomes An accepted order can still finish without filling in full. Check its final outcome and executed quantity before deciding whether another trade is needed. Instrument retirement, risk checks, and order limits can cancel a remaining quantity after earlier fills. > [tab] TypeScript > > Use `session.fetchOrders` on the authenticated session above to inspect order > history. Private `order` events expose the same `PerpsOrder` status values. > > ```ts theme={null} > import { PerpsOrderStatus } from "@polymarket/client"; > > const orders = await session.fetchOrders({ instrumentId: instrument.id }); > for (const order of orders) { > if (order.status === PerpsOrderStatus.InstrumentSettled) { > console.log(order.id, order.filledQuantity); > } > } > ``` > > These terminal outcomes explain why an order or its remainder stopped. A > nonzero `filledQuantity` still represents executed quantity. > > | Status | Meaning | > | - | - | > | `PerpsOrderStatus.Cancelled` | You canceled the order. | > | `PerpsOrderStatus.AutoCancelled` | An expired [auto-cancel](#auto-cancel-orders) schedule canceled the order. | > | `PerpsOrderStatus.OrderExpired` | The order reached its expiry time and was removed. | > | `PerpsOrderStatus.OrderAlreadyTerminal` | A cancellation found that the order had already finished. | > | `PerpsOrderStatus.SweepCapExceeded` | Matching reached the per-sweep fill limit; the remainder was canceled. | > | `PerpsOrderStatus.RestingOrderLimitExceeded` | The account's resting-order limit prevented the remainder from resting. | > | `PerpsOrderStatus.BelowMinNotional` | The order or remainder could not rest because of minimum-notional or price/notional safety checks. | > | `PerpsOrderStatus.InstrumentDisabled` | Trading was disabled for the instrument. | > | `PerpsOrderStatus.InstrumentCloseOnly` | Close-only mode removed an order that could increase exposure. | > | `PerpsOrderStatus.InstrumentSettled` | The instrument permanently settled and remaining orders were canceled. | > | `PerpsOrderStatus.InsufficientMarginAtFill` | A fill-time check found insufficient initial margin. | > | `PerpsOrderStatus.MarkPriceUnavailable` | A fill-time check could not price opening exposure without a fresh mark. | > | `PerpsOrderStatus.ZeroQuantity` | The order had zero quantity. | > | `PerpsOrderStatus.DuplicateOrder` | An order with the same ID already exists. | > | `PerpsOrderStatus.OrderNotFound` | The referenced order was not on the book. | > [tab] Python > > Use `session.fetch_orders` on the authenticated async session above to inspect > order history. Private `order` events expose the same `PerpsOrder` status values. > > ```python theme={null} > orders = await session.fetch_orders(instrument_id=instrument.id) > for order in orders: > if order.status == "instrument_settled": > print(order.id, order.filled_quantity) > ``` > > These terminal outcomes explain why an order or its remainder stopped. A > nonzero `filled_quantity` still represents executed quantity. > > | Status | Meaning | > | - | - | > | `cancelled` | You canceled the order. | > | `auto_cancelled` | An expired [auto-cancel](#auto-cancel-orders) schedule canceled the order. | > | `order_expired` | The order reached its expiry time and was removed. | > | `order_already_terminal` | A cancellation found that the order had already finished. | > | `sweep_cap_exceeded` | Matching reached the per-sweep fill limit; the remainder was canceled. | > | `resting_order_limit_exceeded` | The account's resting-order limit prevented the remainder from resting. | > | `below_min_notional` | The order or remainder could not rest because of minimum-notional or price/notional safety checks. | > | `instrument_disabled` | Trading was disabled for the instrument. | > | `instrument_close_only` | Close-only mode removed an order that could increase exposure. | > | `instrument_settled` | The instrument permanently settled and remaining orders were canceled. | > | `insufficient_margin_at_fill` | A fill-time check found insufficient initial margin. | > | `mark_price_unavailable` | A fill-time check could not price opening exposure without a fresh mark. | > | `zero_quantity` | The order had zero quantity. | > | `duplicate_order` | An order with the same ID already exists. | > | `order_not_found` | The referenced order was not on the book. | > [tab] API > > Inspect order history using the authenticated account access established above. > > ```bash theme={null} > curl -G "https://api.perpetuals.polymarket.com/v1/account/orders" \ > -H "polymarket-proxy: " \ > -H "polymarket-secret: " \ > --data-urlencode "instrument_id=1" > ``` > > The response's `status` and private `orders` frames' `data.status` use the values > below. Preserve executed quantity from `filled_quantity` in history and > `data.fill` in private frames, even when the remainder was canceled. > > | Status | Meaning | > | - | - | > | `cancelled` | You canceled the order. | > | `auto_cancelled` | An expired [auto-cancel](#auto-cancel-orders) schedule canceled the order. | > | `order_expired` | The order reached its expiry time and was removed. | > | `order_already_terminal` | A cancellation found that the order had already finished. | > | `sweep_cap_exceeded` | Matching reached the per-sweep fill limit; the remainder was canceled. | > | `resting_order_limit_exceeded` | The account's resting-order limit prevented the remainder from resting. | > | `below_min_notional` | The order or remainder could not rest because of minimum-notional or price/notional safety checks. | > | `instrument_disabled` | Trading was disabled for the instrument. | > | `instrument_close_only` | Close-only mode removed an order that could increase exposure. | > | `instrument_settled` | The instrument permanently settled and remaining orders were canceled. | > | `insufficient_margin_at_fill` | A fill-time check found insufficient initial margin. | > | `mark_price_unavailable` | A fill-time check could not price opening exposure without a fresh mark. | > | `zero_quantity` | The order had zero quantity. | > | `duplicate_order` | An order with the same ID already exists. | > | `order_not_found` | The referenced order was not on the book. | ## Trading Fees Use the fee schedule when you need to display or account for the default maker and taker trading fees. Fee rates are decimal strings, so `"0.0004"` means `0.04%`. Default (`$0` tier) rates apply when an account has no tier assignment. The account's actual rate on each fill depends on its current fee tier. See [Fees](/perps/learn-about-trading/fees) for the tier table. Authenticated portfolio reads report the account's current tier; see [Portfolio](/perps/account-management#portfolio). > [tab] TypeScript > > Fetch the current Perps fee schedule. > > ```ts theme={null} > const fees = await client.fetchPerpsFees(); > // fees: PerpsFeeScheduleEntry[] > ``` > > Each fee entry contains the market category and its default maker and taker fee > rates. > > ```ts theme={null} > type PerpsFeeScheduleEntry = { > category: PerpsInstrumentCategory; > makerFeeRate: DecimalString; > takerFeeRate: DecimalString; > }; > ``` > > `makerFeeRate` applies when an order adds liquidity, such as a resting or > post-only order. `takerFeeRate` applies when an order removes liquidity, such as > an immediately filled IOC order. > [tab] Python > > Fetch the current Perps fee schedule. > > ```python theme={null} > fees = await client.fetch_perps_fees() > # fees: tuple[PerpsFeeScheduleEntry, ...] > ``` > > Each fee entry contains the market category and its default maker and taker fee > rates. > > `maker_fee_rate` applies when an order adds liquidity, such as a resting or > post-only order. `taker_fee_rate` applies when an order removes liquidity, such > as an immediately filled IOC order. > [tab] API > > Fetch the current Perps fee schedule. > > ```bash theme={null} > curl "https://api.perpetuals.polymarket.com/v1/info/fees" > ``` > > The response includes the full tier schedule alongside the default rates. > > > [accordion] Output: FeesInfo > > > > ```json theme={null} > > { > > "fee_schedule": [ > > { > > "instrument_type": "perpetual", > > "category": "equity", > > "taker_fee_rate": "0.0004", > > "maker_fee_rate": "0.000125", > > "tiers": [ > > { > > "min_volume_30d": "0", > > "taker_fee_rate": "0.0004", > > "maker_fee_rate": "0.000125" > > }, > > { > > "min_volume_30d": "1000000", > > "taker_fee_rate": "0.00037", > > "maker_fee_rate": "0.0001" > > }, > > { > > "min_volume_30d": "5000000", > > "taker_fee_rate": "0.00035", > > "maker_fee_rate": "0.00008" > > }, > > { > > "min_volume_30d": "25000000", > > "taker_fee_rate": "0.0003", > > "maker_fee_rate": "0.00005" > > }, > > { > > "min_volume_30d": "100000000", > > "taker_fee_rate": "0.00027", > > "maker_fee_rate": "0.00002" > > }, > > { > > "min_volume_30d": "500000000", > > "taker_fee_rate": "0.00025", > > "maker_fee_rate": "0" > > }, > > { > > "min_volume_30d": "1000000000", > > "taker_fee_rate": "0.0002", > > "maker_fee_rate": "-0.00005" > > } > > ] > > } > > ] > > } > > ``` > > Use the perpetual schedule's `tiers[fee_tier]` entry with the `fee_tier` from > your authenticated [portfolio](/perps/account-management#portfolio) to read > your account's maker and taker rates. The single perpetual schedule applies > to every perpetual market, regardless of the entry's legacy `category` value. > The flat `maker_fee_rate` and `taker_fee_rate` fields report default rates. > > `maker_fee_rate` applies when an order adds liquidity, such as a resting or > post-only order. `taker_fee_rate` applies when an order removes liquidity, such > as an immediately filled `ioc` order. # Trading Competitions Source: https://docs.polymarket.com/perps/trading-competitions Polymarket Perps Trading Competitions ## Timeline Competitions will run ad hoc, announced a few days ahead of going live - traders can track upcoming, live and completed competitions on our [Competitions page](https://polymarket.com/perps/competitions). ## Prizes Each competition has a different prize pool for a number of traders on the final leaderboard, announced prior to the competition beginning. Prizes are credited as pUSD to the winner's Polymarket Perps account within \~1 week of the competition ending. No claim is needed. Live rankings appear on the leaderboard in the [Competitions tab](https://polymarket.com/perps/competitions) of the Polymarket Perps page. Final rankings are confirmed after a review for rule violations, so standings can shift if any accounts are disqualified. Only trades made during the competition window count toward your score. ## Rules & Guidelines > [accordion] 1. Who can enter > > Open to all non-restricted users. No sign-up needed. > > * Eligibility follows Polymarket's restricted-persons policy. > * Any trade on a competition market during the competition window enters you > automatically. > * Only the competition's markets count, and they're announced before the start. > If all markets are in scope, new listings count too. > [accordion] 2. How scoring works > > Score = PnL × √Boosted Volume, on competition markets only. > > * **Volume:** the notional size of every fill on qualifying positions, including > maker and taker fills, closes, and liquidations. > * **PnL:** realized plus unrealized PnL after fees and funding. Funding received > and maker rebates add to PnL. Funding paid and fees subtract from it. > * **Boosts:** boosted markets multiply your volume for scoring (e.g. 3x). Other > markets count at 1x. Boosts never change your PnL. > * **Negative scores:** negative PnL produces a negative score, and negative > scores still rank. > [accordion] 3. Minimum trade volume to rank > > Trade more than the competitions defined minimum notional volume to qualify for > prizes. This minimum volume will be announced before each competition, and vary > by competition. > > * Only volume on competition markets counts toward the minimum. > * Boosts count toward your score but not toward the minimum. > [accordion] 4. Only new positions count > > Positions open at the start are excluded, and so is any trade that adds to them. > > * Any trade in a market where you hold a pre-competition position adds to that > position, so it won't count toward your volume, PnL or the minimum. > * Close the position fully to start counting trades in that market. > * If you flip a pre-competition position (e.g. sell past your long into a > short), only the new position counts, from that point on. > [accordion] 5. Timing and payouts > > Winners are paid in pUSD to their perps account after a \~5-day review. > > * Only trades filled between the start and end time (UTC) count. > * Open positions are scored at the oracle mark price at the end. Closing them > after the end doesn't change your score. > * **Ties:** higher boosted volume wins, then the earliest first trade. > * One prize per user per competition. If more than one of your wallets places, > only the best-ranked one wins. > * No KYC or claim needed. > [accordion] 6. Fair play > > Manipulation of any kind disqualifies all associated accounts. > > * This covers wash trading, self-trading, and multi-accounting. > * Polymarket may change, pause, or end the program, adjust scoring, withhold > prizes, or disqualify anyone at its discretion. [Full Rules](https://docs.google.com/document/d/e/2PACX-1vRoHUTKW0vWtjRcggirQeWhnSrf35HKVKfJ2q3bg-P2p1kRZpDwLe8FqMYzFqVToA/pub) [Start Competing](https://polymarket.com/perps/competitions) Join live or upcoming competitions to earn your share of cash prizes. # Polymarket 101 Source: https://docs.polymarket.com/polymarket-101 An intro to Polymarket - the world's largest prediction market Polymarket is a prediction market platform where users trade on the outcomes of real-world events. Instead of betting against a house, you trade shares with other users in an open, peer-to-peer market. Prices reflect the market's collective belief in the probability of an event occurring. The platform is non-custodial, meaning you always control your funds. All trades are settled through smart contracts on the blockchain, ensuring transparent and trustless operation. ## Self-Custody Polymarket operates on a non-custodial model. You maintain full control of your funds at all times. * Assets are held in your wallet, secured by your private key. * Trades execute automatically through audited smart contracts. * Polymarket never takes possession of your funds. * All trades and positions are recorded onchain and publicly verifiable. * Settlement happens automatically based on market resolution. > [!WARNING] > > Keep your private key safe and never share it with anyone. If you lose your > private key, you lose access to your funds. If you signed up via Magic Link or > have a proxy wallet, recovery may be possible through > [recovery.polymarket.com](https://recovery.polymarket.com). ## How Polymarket Works ![Polymarket Overview](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/polymarket-101.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=059e9831d1c51b99996d9747c0139d49) ### Prices Are Probabilities Every share on Polymarket is priced between `$0.00` and `$1.00`. The price represents the market's belief in the probability of that outcome occurring. For example, if "Yes" shares for an event are trading at `$0.65`, the market believes there's approximately a `65%` chance the event will happen. ### Collateral and Tokens Polymarket uses pUSD (Polymarket USD) as collateral. Every Yes/No pair is fully backed: * `$1 pUSD` creates one Yes share and one No share * Winning shares are redeemable for `$1.00` * Losing shares are worth `$0.00` Shares are represented as ERC-1155 tokens on Polygon. Depending on the market, they are recorded as [Gnosis Conditional Tokens](https://github.com/gnosis/conditional-tokens-contracts/) or Polymarket Protocol V2 positions. Both represent the same Yes and No shares. See [Positions & Tokens](/concepts/positions-tokens) for more details. ### Trading Polymarket uses a peer-to-peer order book (CLOB) for trading. You trade directly with other users, not against the house. * **Buy shares** when you think the market underestimates the probability * **Sell shares** when you think the market overestimates the probability * **Exit anytime** - Sell your position before resolution to lock in profits or cut losses | Action | When to Use | Profit Scenario | | - | - | - | | Buy Yes | You think the probability is too low | Event occurs | | Buy No | You think the probability is too high | Event does not occur | | Sell | Lock in gains or limit losses | Price moves in your favor | ### Resolution When an event concludes, markets using the UMA Optimistic Oracle follow this resolution process: 1. A proposer submits the outcome with a bond 2. There is a challenge period during which the outcome can be disputed 3. If disputed, UMA determines the correct resolution 4. Once finalized, winning shares become redeemable for `$1 pUSD` Polymarket Protocol V2 markets can also use other resolution mechanisms. See [Resolution](/concepts/resolution) for more details. ## Why Blockchain Polymarket is built on **Polygon**, a blockchain network, for several key reasons: * Anyone with an internet connection can participate. * You control your funds, not a centralized entity. * All activity is publicly verifiable onchain. * Polygon enables quick, low-cost transactions. * pUSD is a standard ERC-20 backed by USDC, with backing enforced onchain by the smart contract, so its value stays stable. ## Smart Wallets Polymarket uses smart wallets so users can trade without manually submitting every onchain transaction. New API users use deposit wallets. Existing Safe and Proxy users can continue using their current wallet. Deposit wallets hold the user's pUSD and outcome tokens on Polygon and validate orders through ERC-1271. Safe and Proxy wallets remain supported for existing users and integrations. Using smart wallets allows Polymarket to provide an improved UX where multi-step transactions can be executed atomically and transactions can be relayed by Polymarket's relayer. If you are a developer looking to programmatically access positions accumulated through an existing Polymarket account, continue using that account's current smart wallet type. ### Deployments Each smart-wallet user has their own wallet address. See [Contracts](/resources/contracts) for all deployed factory and trading contract addresses on Polygon. *** ## Getting Started Ready to start trading? > [card] [Trading Quickstart](/trading/quickstart) > > Set up your account and make your first trade. > [card] [Explore Markets](https://polymarket.com) > > Browse active prediction markets on Polymarket. # Builder Fees Source: https://docs.polymarket.com/programs/builders/fees How builders earn fees on orders routed through their applications, and how to integrate. CLOB V2 introduces a fee layer that lets builders earn a fee on every order routed through their application. When a builder attaches their unique **builder code** to an order and that order matches, a **builder fee** is collected alongside any platform fee. Builder fees are flat percentages of trade notional, configured by each builder within enforced limits. They're additive — they stack on top of platform fees, never replace them. > [!NOTE] > > New to the Builder Program? Start with [Builder Program](/programs/builders/overview). This page covers the fee layer specifically. *** ## How It Works ![](https://mintcdn.com/polymarket-292d1b1b/lWwKl4XdsXxYugaA/images/core-concepts/builder-fee.png?fit=max\&auto=format\&n=lWwKl4XdsXxYugaA\&q=85\&s=9287dc95f24f07bcb9f33c4d7d6ed0f2) Builder fees and platform fees are independent. What the user pays depends on the market config and whether a builder code is attached: | Market | Builder code attached | User pays | | - | - | - | | No platform fee | No | Nothing | | No platform fee | Yes | Builder fee only | | Platform fee enabled | No | Platform fee only | | Platform fee enabled | Yes | Platform fee + builder fee | Builder fees never replace platform fees — they're always additive. > [!WARNING] > > Polymarket reserves the right to revoke your ability to charge a builder fee in its sole discretion, for any reason or no reason, including but not limited to instances where fees are determined to have been collected through fraudulent, deceptive, misleading, automated, self-referred, or other non-bona fide trading activity. *** ## Registration Register for a builder code through your Polymarket account. **1. Create a Builder Profile** Open polymarket.com → Settings → [Builders](https://polymarket.com/settings?tab=builder) and set up your builder profile. **2. Set Your Fee Rates** Configure two rates on your profile: * **Taker Fee Rate** — charged on taker orders routed through your app * **Maker Fee Rate** — charged on maker orders routed through your app **3. Copy Your Builder Code** Your profile is assigned a `bytes32` builder code. [Attach it to every order you submit](/trading/place-orders#builder-attribution). ### Fee Rate Limits | Parameter | Default | Maximum | | - | - | - | | Taker fee rate | 0 bps (0%) | 100 bps (1%) | | Maker fee rate | 0 bps (0%) | 50 bps (0.5%) | | Granularity | — | 1 bp (0.01%) | ### Rate Change Policy Fee rate changes are gated so users can see them coming: * **Cooldown.** One rate change per 7 days. * **Advance notice.** Changes take effect 3 days after being scheduled. * **One pending change at a time.** You can't queue multiple changes — wait for the current one to take effect (or cancel it) before scheduling another. *** ## Fee Calculation ### Platform Fees Platform fees use a dynamic per-market formula: ``` platform_fee = C × feeRate × p × (1 - p) ``` Where `C` is the trade size, `p` is the order price, and `feeRate` is a per-market parameter. Platform fees are currently taker-only and are not configurable by builders. ### Builder Fees Builder fees are a flat percentage of notional: ``` builder_fee = notional × builder_fee_rate_bps / 10000 ``` **Example.** A 1,000 pUSD taker buy routed through a builder charging 100 bps (1%) taker fee: ``` builder_fee = 1000 × 100 / 10000 = 10 pUSD ``` The maker and taker sides of a single trade can have different builder codes and different rates. If Builder A (0.3% maker) posts the resting order and Builder B (0.8% taker) submits the matching order, each earns their respective fee from their respective side. ### Balance Checks The account must have enough pUSD to cover the trade and all applicable platform and builder fees. For market buys, [set an all-in spending limit](/trading/place-orders#cap-market-buy-spending) so the order amount is adjusted for fees before signing. *** ## Onchain Attribution Builder attribution is part of the signed order. It works across CTF and Polymarket Protocol V2. For the signing workflow, see [Place a Limit Order](/trading/place-orders#place-a-limit-order). ### Signed Order Struct ``` salt, maker, signer, tokenId, makerAmount, takerAmount, side, signatureType, timestamp, metadata, builder ``` The `builder` field is a `bytes32` matching your registered builder code. Each settlement contract emits `OrderFilled` with the signed `builder` value. Index events from the CTF Exchange, Neg Risk CTF Exchange, and Polymarket Protocol V2 Exchange when reconciling attribution across both position systems. *** ## Fee Processing and Payouts When a user places an order with your `builderCode` attached: 1. The CLOB validates the order and the builder code. 2. At match time, the Fees Service computes the platform and builder fees for each side. 3. The trade settles through the exchange selected for the market, emitting `OrderFilled` events. 4. The Builders Service indexes those events, joins onchain attribution with your builder profile, and accrues your earned fees. Collected builder fees are distributed to the wallet associated with your builder profile. ### Payout Schedule Builder fees are paid out daily. Each payout covers the builder fees earned during the previous UTC day. The minimum builder fee payout is **\$0.10**. If your builder fees for a UTC day total less than this amount, no payout is sent for that day. *** ## Program Policies ### Disabled Codes Polymarket may disable a builder code at any time — for violations of the Builder Program terms, abusive fee practices, or platform integrity concerns. Orders carrying a disabled code will be rejected by the CLOB. ### Public Visibility Builder profiles and fee rates are publicly queryable. This is intentional — it lets users and third parties see what a builder charges before using their app. # Overview Source: https://docs.polymarket.com/programs/builders/overview Build applications that route orders through Polymarket A **builder** is a person, group, or organization that routes orders from users to Polymarket. If you've created a platform that allows users to trade on Polymarket through your system, this program is for you. ## Program Benefits > [card] Gasless Transactions > > All onchain operations are gas-free through our relayer > [card] Order Attribution > > Get credit for orders and compete for grants on the Builder Leaderboard ### What You Get | Benefit | Description | | - | - | | **Relayer Access** | Gas-free wallet deployment, approvals, order execution and position operations | | **Volume Tracking** | All orders attributed to your builder profile | | **Leaderboard** | Public visibility on [builders.polymarket.com](https://builders.polymarket.com) | | **Support** | Telegram channel and engineering support (Verified+) | ## How It Works **1. User Places Order** User places an order through your application. **2. Attach Builder Code** Your app adds your builder code to each order. **3. Submit to CLOB** Order is submitted to Polymarket's CLOB — the builder code is serialized onchain as part of the signed order. **4. Trade Execution** Polymarket matches the order and covers gas fees for onchain operations. **5. Volume Attribution** Volume is credited to your builder account for every matched trade where your code is attached. ## Getting Started **1. Create Builder Profile** Open polymarket.com → Settings → [Builders](https://polymarket.com/settings?tab=builder) and copy your builder code. **2. Attach Your Builder Code** Attach your builder code to every order you submit. See [Builder Attribution](/trading/place-orders#builder-attribution). **3. Enable Gasless Transactions** Use the Polymarket relayer to deploy wallets and [execute gasless transactions](/trading/wallets-auth#execute-gasless-transactions). **4. Track Performance** Monitor your volume on the [Builder Leaderboard](https://builders.polymarket.com). Allow up to **24 hours** for matched volume to appear on the leaderboard. *** ## Next Steps > [card] [Create New Accounts](/trading/wallets-auth#create-new-accounts) > > Create a builder account and the credentials used to provision accounts for > your users. > [card] [Understand Tiers](/programs/builders/tiers) > > Learn about rate limits and how to upgrade. > [card] [Attribute Orders](/trading/place-orders#builder-attribution) > > Configure your client to credit trades to your account. > [card] [Execute Gasless Transactions](/trading/wallets-auth#execute-gasless-transactions) > > Approve tokens, transfer funds, and manage positions without paying gas. # Tiers Source: https://docs.polymarket.com/programs/builders/tiers Rate limits, rewards, and how to upgrade The Builder Program uses a tiered system to manage rate limits while rewarding high-performing integrations. Higher tiers unlock increased limits, weekly rewards, and priority support. ## Feature Definitions | Feature | Description | | - | - | | **Daily Relayer Txn Limit** | Maximum Relayer transactions per day for deposit wallet, Safe, and Proxy wallet operations | | **API Rate Limits** | Rate limits for non-relayer endpoints (CLOB, Gamma, etc.) | | **Gasless Trading** | Gas fees subsidized for supported smart-wallet operations | | **Order Attribution** | Orders tracked and attributed to your Builder profile | | **Builder Fees** | Builders who route orders can charge fees and monetize on flow | | **Leaderboard Visibility** | Visibility on the [Builder Leaderboard](https://builders.polymarket.com/) | | **Telegram Channel** | Private Builders channel for announcements and support | | **Engineering Support** | Direct access to engineering team | | **Marketing Support** | Promotion via official Polymarket social accounts | | **Priority Access** | Early access to new features and products | *** ## Tier Comparison | Feature | Unverified | Verified | Partner | | - | :-: | :-: | :-: | | **Daily Relayer Txn Limit** | 100/day | 10,000/day | Unlimited | | **API Rate Limits** | Standard | Standard | Highest | | **Gasless Trading\*** | Yes | Yes | Yes | | **Order Attribution** | Yes | Yes | Yes | | **Builder Fees** | Yes | Yes | Yes | | **Leaderboard Visibility** | — | Yes | Yes | | **Telegram Channel** | — | Yes | Yes | | **Engineering Support** | — | Standard | Elevated | | **Marketing Support** | — | Standard | Elevated | | **Priority Access** | — | — | Yes | *** ## Unverified > [card] 100 Relay transactions/day > > The default tier for all new builders. Start immediately with no approval > required. **How to get started:** 1. Go to [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) 2. Create a builder profile 3. Click **"+ Create New"** to generate API keys 4. Attach your [builder code](/trading/place-orders#builder-attribution) to CLOB orders for attribution; use a Relayer API key for gasless wallet operations **What's included:** * Gasless trading through deposit wallets for new API users and existing Safe/Proxy wallets * Gas subsidized on all Relayer transactions up to the daily limit * Access to all client libraries and documentation *** ## Verified > [card] 10,000 Relay transactions/day > > For builders who need higher throughput. Requires manual approval. **How to upgrade:** Contact us at [builder@polymarket.com](mailto:builder@polymarket.com) with: * Your Builder API Key * Use case description * Expected volume * Other relevant information (links, docs, decks, etc.) **Unlocks over Unverified:** * 100x daily Relayer transaction limit * Monetize with Builder fees * Leaderboard visibility at [builders.polymarket.com](https://builders.polymarket.com) * Private Telegram channel for announcements and support * Weekly USDC rewards based on volume (subject to approval) * Grants (subject to approval) *** ## Partner > [card] Unlimited Relay transactions/day > > Enterprise tier for high-volume integrations and strategic partners. **Unlocks over Verified:** * Unlimited Relayer transactions * Highest API rate limits * Elevated engineering support * Elevated and coordinated marketing support * Priority access to new features and products *** ## How to Upgrade **1. Build and Launch** Start with the Unverified tier and build your integration. **2. Generate Volume** Route orders through Polymarket and demonstrate consistent usage. **3. Apply for Verification** Email [builder@polymarket.com](mailto:builder@polymarket.com) with your builder key and use case. **4. Get Approved** The Polymarket team reviews applications and responds within a few business days. ## Contact Ready to upgrade or have questions? > [card] [builder@polymarket.com](mailto:builder@polymarket.com) > > Email us with your Builder API Key and use case details. ## FAQ > [accordion] How do I know if I am verified > > Verification is displayed in your [Builder Profile](https://polymarket.com/settings?tab=builder) settings. > [accordion] What happens if I exceed my daily limit > > Relayer requests beyond your daily limit will be rate-limited and return an > error. Consider upgrading to Verified or Partner tier if you're hitting > limits. > [accordion] What if I just need more daily Relay transaction limits for my own wallet > > If you're not routing orders for other users (wallets), you can get unlimited > daily Relay transactions by obtaining a [Relayer API key](https://polymarket.com/settings?tab=api-keys). # Upcoming Fee and Rebate Changes Source: https://docs.polymarket.com/programs/fee-and-rebate-changes-november-2026 Prepare for the Polymarket DeFi fee and rebate changes taking effect November 20, 2026 at 23:59 UTC. > [!NOTE] > > **Effective Friday, November 20, 2026 at 23:59 UTC.** These changes apply to > Polymarket DeFi on [Polymarket.com](https://polymarket.com). The current fee > and rebate rules remain in effect until that time. ## Taker Fees Taker fees will continue to use the same formula: ```text theme={null} fee = shares × feeRate × price × (1 − price) ``` `shares` is the filled quantity, `price` is the fill price in dollars (for example, `0.40` for 40¢), and `feeRate` is the category coefficient below. The coefficients are inputs to the formula, not flat percentages of trade value. > [!NOTE] > > Makers continue to pay no platform trading fee. | Category | Fee Coefficient | | - | - | | Crypto — BTC 5-minute and 15-minute up/down | 0.05 | | Crypto — all other markets | 0.01 | | All sports, including NFL and college football | 0.05 | | Finance | 0.05 | | Tech | 0.05 | | Politics — elections | 0.05 | | Politics — excluding elections and geopolitics | 0.01 | | Economics | 0.01 | | Culture | 0.01 | | Weather | 0.01 | | Mentions | 0.01 | | Geopolitics | 0 | | Combos | 0.05 | | Other / General | 0.05 | Geopolitics remains fee-free. Combos keep their own fee coefficient, regardless of the categories of their underlying legs. ## Taker Rebates The Bronze and Silver tiers will be removed. Accounts with less than \$200,000 in 30-day taker weighted volume will earn no taker rebate. The rebate rate on the Gold taker rebate tier moves to 10%, Platinum to 25%, and Diamond to 40%. Obsidian will stay at 50%, and a new Onyx tier will pay 60%. | Tier | 30-Day Taker Weighted Volume | Rebate on Taker Fees Paid | | - | - | - | | None | Under \$200,000 | 0% | | Gold | \$200,000 to under \$1 million | 10% | | Platinum | \$1 million to under \$4 million | 25% | | Diamond | \$4 million to under \$10 million | 40% | | Obsidian | \$10 million to under \$75 million | 50% | | Onyx (new) | \$75 million and above | 60% | Price weighting stays; category multipliers are removed. Each fee-paying taker fill contributes `shares × price × (1 − price)` to weighted volume. Your taker tier uses the sum over the last 30 days. This differs from dollar trading volume (`shares × price`). Please note that with no category multipliers moving forward, your tier may change even if you trade the same amount. The Gold, Platinum, Diamond, and Obsidian weighted-volume thresholds stay the same. One-time level-up bonuses will end. ## Maker Rebates Tiered maker rebates will replace the daily market-wide rebate pools. Your maker tier will depend on your maker weighted volume over the last 30 days. Each eligible maker fill will earn your tier's percentage of the taker fee it generates. Maker fills count only toward your maker tier; taker fills count only toward your taker tier. | Tier | 30-Day Maker Weighted Volume | Rebate on Taker Fees Generated by Your Fills | | - | - | - | | None | Under \$200,000 | 0% | | Tier 1 | \$200,000 to under \$1 million | 3% | | Tier 2 | \$1 million to under \$4 million | 7% | | Tier 3 | \$4 million to under \$10 million | 10% | | Tier 4 | \$10 million and above | 15% | Maker weighted volume uses the same formula as taker weighted volume. For example, a Tier 4 maker whose eligible fills generate \$100 in taker fees earns \$15 in maker rebates. Combos and fee-free trades earn no maker rebates. [Liquidity rewards](/programs/liquidity-rewards) remain unchanged. Until the changes take effect, refer to the current [Fees](/trading/fees), [Taker Rebate Program](/programs/taker-rebates), and [Maker Rebates Program](/programs/maker-rebates) pages. # Liquidity Rewards Source: https://docs.polymarket.com/programs/liquidity-rewards Earn rewards for providing liquidity on Polymarket By posting resting limit orders, liquidity providers (makers) are automatically eligible for Polymarket's incentive program. Rewards are distributed directly to maker addresses daily at midnight UTC. The program is designed to: * Catalyze liquidity across all markets * Encourage liquidity throughout a market's entire lifecycle * Motivate passive, balanced quoting tight to a market's midpoint * Encourage trading activity * Discourage blatantly exploitative behaviors > [!NOTE] > > The minimum reward payout is **\$1**; amounts below this will not be paid. > [!TIP] > > Each incentivized market defines a minimum qualifying order size, maximum > qualifying spread, and reward allocation. See [Liquidity Reward > Settings](/market-data/market-details#liquidity-reward-settings) to read the > current configuration for a market. *** ## Find Markets to Quote Browse markets and their reward settings before choosing where to provide liquidity. Search narrows the collection. Inspect each returned market's configuration before assuming that rewards are currently available. > [tab] TypeScript > > Call `listRewardMarkets()` using an existing `PublicClient` named `client`. > If needed, [create a public client](/getting-started/typescript#create-a-public-client). > The method is also available on `SecureClient`. > > ```ts theme={null} > import { RewardMarketSort } from "@polymarket/client"; > > const pages = client.listRewardMarkets({ > query: "sports", > orderBy: RewardMarketSort.RatePerDay, > sortDirection: "DESC", > pageSize: 100, > }); > > for await (const page of pages) { > for (const market of page.items) { > console.log( > market.question, > market.rewardsMinSize, > market.rewardsMaxSpread, > ); > for (const config of market.rewardsConfig) { > console.log(config.assetAddress, config.ratePerDay); > } > } > } > ``` > > `RewardMarket` includes the market and event identifiers, token prices, spread, > volume, competitiveness, and reward configurations. Decimal values remain > strings. `rewardsConfig` can be empty. Do not infer an active reward solely from > a market appearing in the collection. > > Use `tagSlugs` for category selection, or `marketId` and > `eventIds` for known markets and events. `minVolume24hr`, `maxVolume24hr`, > `minSpread`, `maxSpread`, `minPrice`, and `maxPrice` narrow numeric ranges. > Minimum bounds are exclusive, maximum bounds inclusive, and zero disables a > bound. A supplied `orderBy` defaults to ascending order unless you set > `sortDirection`. > [tab] Python > > Call `list_reward_markets()` using an existing `AsyncPublicClient` named `client`. > If needed, [create a public client](/getting-started/python#create-a-public-client). > The method is also available on `AsyncSecureClient`. The synchronous clients > provide the same filters. > > ```python theme={null} > pages = client.list_reward_markets( > query="sports", > order_by="rate_per_day", > sort_direction="DESC", > page_size=100, > ) > > async for page in pages: > for market in page.items: > print(market.question, market.rewards_min_size, market.rewards_max_spread) > for config in market.rewards_config: > print(config.asset_address, config.rate_per_day) > ``` > > `RewardMarket` includes the market and event identifiers, token prices, spread, > volume, competitiveness, and reward configurations. Decimal values are > `Decimal` instances. `rewards_config` can be empty. Do not infer an active reward > solely from a market appearing in the collection. > > Use `tag_slugs` for category selection, or `market_id` > and `event_ids` for known markets and events. `min_volume_24hr`, > `max_volume_24hr`, `min_spread`, `max_spread`, `min_price`, and `max_price` narrow > numeric ranges. Minimum bounds are exclusive, maximum bounds inclusive, and > zero disables a bound. A supplied `order_by` defaults to ascending order unless > you set `sort_direction`. > [tab] API > > Search the public reward-market collection without authentication. > > ```bash theme={null} > curl -G "https://clob.polymarket.com/rewards/markets/multi" \ > --data-urlencode "q=sports" \ > --data-urlencode "order_by=rate_per_day" \ > --data-urlencode "position=DESC" \ > --data-urlencode "page_size=100" > ``` > > Illustrative response (fields trimmed): > > > [accordion] Output: Reward Markets Page > > > > ```json theme={null} > > { > > "limit": 100, > > "count": 1, > > "next_cursor": "LTE=", > > "data": [ > > { > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "question": "Will Team A win?", > > "rewards_min_size": 100, > > "rewards_max_spread": 3, > > "rewards_config": [ > > { > > "id": 7, > > "asset_address": "0x9c4E1703476E875070EE25b56A58B008CFb8FA78", > > "start_date": "2026-10-01", > > "end_date": "2026-10-31", > > "rate_per_day": 100, > > "total_rewards": 3100 > > } > > ] > > } > > ] > > } > > ``` > > Read markets from `data`, then pass the returned `next_cursor` with the same > filters for the next page. `next_cursor: "LTE="` marks the end. The default > page size is 100 and the maximum is 500. > > Each market includes `rewards_min_size`, `rewards_max_spread`, and > `rewards_config`. The configuration can be empty. Inspect it before assuming > an active allocation. Repeat `tag_slug` or `event_id` to select multiple tags > or events. Numeric `min_*` bounds are exclusive and `max_*` bounds inclusive. > Zero disables a bound. *** ## Read Daily Earnings Read daily totals for the authenticated account to reconcile liquidity rewards. Choose whether to include sponsored rewards in the total. > [tab] TypeScript > > Call `fetchTotalEarningsForUserForDay()` on a `SecureClient`. > > ```ts theme={null} > const earnings = await client.fetchTotalEarningsForUserForDay({ > date: "2026-10-06", > sponsored: true, > }); > > for (const earning of earnings) { > console.log( > earning.earnings, > earning.nativeEarnings, > earning.sponsoredEarnings, > ); > } > ``` > > `earnings` is the total decimal string for the row's reward asset. With > `sponsored: true`, the total includes native and sponsored rewards. > `nativeEarnings` and `sponsoredEarnings` expose the optional decimal-string > breakdown. An absent breakdown remains `undefined`. A returned zero is `"0"`. > Omitting `sponsored`, or setting it to `false`, requests native rewards only. > [tab] Python > > Call `get_total_earnings_for_user_for_day()` on an `AsyncSecureClient`. > The synchronous `SecureClient` provides the same method. > > ```python theme={null} > earnings = await client.get_total_earnings_for_user_for_day( > date="2026-10-06", > sponsored=True, > ) > > for earning in earnings: > print(earning.earnings, earning.native_earnings, earning.sponsored_earnings) > ``` > > `earnings` is the `Decimal` total for the row's reward asset. With > `sponsored=True`, the total includes native and sponsored rewards. > `native_earnings` and `sponsored_earnings` expose the optional `Decimal` > breakdown. An absent breakdown remains `None`. A returned zero remains zero. > Omitting `sponsored`, or setting it to `False`, requests native rewards only. > [tab] API > > Read daily totals with CLOB L2 authentication for the account: > > ```bash theme={null} > curl -G "https://clob.polymarket.com/rewards/user/total" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data-urlencode "date=2026-10-06" \ > --data-urlencode "maker_address=0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604" \ > --data-urlencode "sponsored=true" > ``` > > Create fresh L2 headers using [API Authentication](/getting-started/api#authentication). > Sign the timestamp, `GET`, and `/rewards/user/total`, with no request body. > > Illustrative response: > > > [accordion] Output: Daily Earnings > > > > ```json theme={null} > > [ > > { > > "date": "2026-10-06T00:00:00Z", > > "asset_address": "0x9c4E1703476E875070EE25b56A58B008CFb8FA78", > > "maker_address": "0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604", > > "earnings": 12.5, > > "native_earnings": 10, > > "sponsored_earnings": 2.5, > > "asset_rate": 1 > > } > > ] > > ``` > > Each response row reports `earnings` as a JSON number. Optional > `native_earnings` and `sponsored_earnings` numbers split the native and sponsored > amounts. With `sponsored=true`, the total includes both. The request defaults to > native rewards only when `sponsored` is omitted or `false`. Group totals by reward asset when reconciling them. Amounts for different assets should not be added without accounting for their exchange rates. *** ## Crypto TWAP Rewards To support liquidity through this transition, Polymarket is adding **\$1M** in liquidity rewards across impacted markets through the month of August. This allocation applies only to crypto **5-minute**, **15-minute**, and **4-hour** markets that settle on TWAP. > [!NOTE] > > This program has ended. The August allocation is no longer active. > [!NOTE] > > The pools below are configured reward caps. Actual payouts depend on eligible > quoting and the scoring methodology on this page. ### 5-Minute Markets — \$550k | Allocation | Amount | | - | - | | BTC | \$300k | | SOL, ETH, HYPE, XRP | \$200k split evenly | | BNB, DOGE | \$50k split evenly | ### 15-Minute Markets — \$350k | Allocation | Amount | | - | - | | BTC | \$225k | | SOL, ETH, HYPE, XRP | \$100k split evenly | | BNB, DOGE | \$25k split evenly | ### 4-Hour Markets — \$100k | Allocation | Amount | | - | - | | BTC | \$50k | | SOL, ETH, HYPE, XRP | \$40k split evenly | | BNB, DOGE | \$10k split evenly | *** ## Methodology Liquidity providers are rewarded based on a formula that rewards participation in markets, boosts two-sided depth (single-sided orders still score), and tighter spread vs the size-cutoff-adjusted midpoint. Each market configures a max spread and min size cutoff within which orders are considered. The average of rewards earned is determined by the relative share of each participant's Qn in market m. ### Minimum Order Age On most markets, an order counts toward rewards as soon as it rests on the book. Markets with a taker delay are the exception. On these markets, a marketable order waits for the delay before it can match, so a resting order counts toward rewards only after it has rested for the same delay. An order cannot earn rewards before a taker could fill it. * **Sports markets with a scheduled game start:** the delay, and so the minimum age, applies only after the game starts. Before the start, orders count as soon as they rest. * **Crypto and finance markets:** the short taker delay on these markets does not set a minimum age. Orders count as soon as they rest. ### Variables | Variable | Description | | - | - | | S | Order position scoring function | | v | Max spread from midpoint (in cents) | | s | Spread from size-cutoff-adjusted midpoint | | b | In-game multiplier | | m | Market | | m' | Market complement (i.e. NO if m = YES) | | n | Trader index | | u | Sample index | | c | Scaling factor (currently 3.0 on all markets) | | Qne | Point total for book one for a sample | | Qno | Point total for book two for a sample | | Spread% | Distance from midpoint (bps or relative) for order n in market m | | BidSize | Share-denominated quantity of bid | | AskSize | Share-denominated quantity of ask | *** ## Equations ### 1. Order Scoring Function Quadratic scoring rule for an order based on position between the adjusted midpoint and the minimum qualifying spread: $S(v,s)= (\frac{v-s}{v})^2 \cdot b$ ### 2. First Market Side Score $Q_{one}= S(v,Spread_{m_1}) \cdot BidSize_{m_1} + S(v,Spread_{m_2}) \cdot BidSize_{m_2} + \dots $ $ + S(v, Spread_{m^\prime_1}) \cdot AskSize_{m^\prime_1} + S(v, Spread_{m^\prime_2}) \cdot AskSize_{m^\prime_2}$ ### 3. Second Market Side Score $Q_{two}= S(v,Spread_{m_1}) \cdot AskSize_{m_1} + S(v,Spread_{m_2}) \cdot AskSize_{m_2} + \dots $ $ + S(v, Spread_{m^\prime_1}) \cdot BidSize_{m^\prime_1} + S(v, Spread_{m^\prime_2}) \cdot BidSize_{m^\prime_2}$ ### 4. Minimum Score Boosts two-sided liquidity by taking the minimum of Qne and Qno, while still rewarding single-sided liquidity at a reduced rate (divided by c). **If midpoint is in range \[0.10, 0.90]** — single-sided liquidity can score: $Q_{\min} = \max(\min({Q_{one}, Q_{two}}), \max(Q_{one}/c, Q_{two}/c))$ **If midpoint is in range \[0, 0.10) or (0.90, 1.0]** — liquidity must be double-sided to score: $Q_{\min} = \min({Q_{one}, Q_{two}})$ ### 5. Normalized Score Qmin of a market maker divided by the sum of all Qmin across market makers in a given sample: $Q_{normal} = \frac{Q_{min}}{\sum_{n=1}^{N}{(Q_{min})_n}}$ ### 6. Epoch Score Sum of all Qnormal for a trader across all samples in an epoch. An epoch is one UTC day; the order book is sampled once per minute at a random offset, so an epoch contains up to 1,440 samples: $Q_{epoch} = \sum_{u=1}^{1,440}{(Q_{normal})_u}$ ### 7. Final Score Normalizes Qepoch by dividing by the sum of all market makers' Qepoch in a given epoch. This value is multiplied by the rewards available for the market to get a trader's reward: $Q_{final}=\frac{Q_{epoch}}{\sum_{n=1}^{N}{(Q_{epoch})_n}}$ *** ## Worked Example Assume an adjusted market midpoint of 0.50 and a max spread config of 3 cents for both m and m'. ### Step 2 - First Side Score A trader has the following open orders: * 100Q bid on m @ 0.49 (spread = 1 cent) * 200Q bid on m @ 0.48 (spread = 2 cents) * 100Q ask on m' @ 0.51 (spread = 1 cent) $$ Q_{ne} = \left( \frac{(3-1)}{3} \right)^2 \cdot 100 + \left( \frac{(3-2)}{3} \right)^2 \cdot 200 + \left( \frac{(3-1)}{3} \right)^2 \cdot 100 $$ Qne is calculated every minute using random sampling. ### Step 3 - Second Side Score The same trader also has: * 100Q bid on m @ 0.485 (spread = 1.5 cents) * 100Q bid on m' @ 0.48 (spread = 2 cents) * 200Q ask on m' @ 0.505 (spread = 0.5 cents) $$ Q_{no} = \left( \frac{(3-1.5)}{3} \right)^2 \cdot 100 + \left( \frac{(3-2)}{3} \right)^2 \cdot 100 + \left( \frac{(3-.5)}{3} \right)^2 \cdot 200 $$ Qno is calculated every minute using random sampling. ### Steps 4-7 4. Take the minimum of Qne and Qno (with single-sided adjustment if midpoint is in \[0.10, 0.90]) 5. Normalize against all other market makers in the sample 6. Sum across all 1,440 samples in the epoch (one UTC day) 7. Normalize again to get final reward share # Maker Rebates Program Source: https://docs.polymarket.com/programs/maker-rebates Earn daily pUSD rebates by providing liquidity on Polymarket > [!NOTE] > > **Upcoming changes — November 20, 2026 at 23:59 UTC.** Polymarket DeFi taker > fees and rebates will change. Maker rebates will move from daily pools to > volume tiers. The current rules below apply until then. [See all fee and > rebate changes](/programs/fee-and-rebate-changes-november-2026). Polymarket charges taker fees across multiple market categories. Fees are determined by the protocol at match time and fund a **Maker Rebates** program that pays daily pUSD rebates to liquidity providers. *** ## Why Maker Rebates Deeper liquidity means tighter spreads, lower price impact, more reliable fills, and greater resilience during volatility. Maker Rebates incentivize **consistent, competitive quoting** so everyone gets a better trading experience. *** ## How Maker Rebates Work * **Paid daily in pUSD:** Rebates are calculated and distributed every day. * **Performance-based:** You earn based on the share of liquidity you provided that actually got taken. ### Eligibility Place orders that add liquidity to the book and get filled (i.e., your liquidity is taken by another trader). > [!NOTE] > > Maker rebates are funded by taker fees, so fills on markets with a 0% taker fee (including markets temporarily made fee-free during a fee holiday) earn **no maker rebate** for as long as the fee is 0. ### Payment Rebates are paid daily in pUSD, directly to your wallet. A minimum accrued rebate of **\$1 pUSD** is required for a payout. *** ## Read Your Rebated Fees Read a maker's rebate amounts for a calendar day to reconcile the program with your accounting. > [tab] TypeScript > > Call `fetchCurrentRebates()` using an existing `PublicClient` named `client`. > If needed, [create a public client](/getting-started/typescript#create-a-public-client). > The method is also available on `SecureClient`. > > ```ts theme={null} > const rebates = await client.fetchCurrentRebates({ > date: "2026-10-06", > makerAddress: "0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604", > }); > > for (const rebate of rebates) { > console.log(rebate.conditionId, rebate.rebatedFeesUsdc); > } > ``` > > Each `RebatedFee` includes `date`, `conditionId`, `assetAddress`, > `makerAddress`, and `rebatedFeesUsdc`. The amount is an exact USDC decimal string. > Keep it as a string or use a decimal library for accounting. The method returns > an empty array when the maker has no rebates for the requested date. > [tab] Python > > Call `get_current_rebates()` using an existing `AsyncPublicClient` named `client`. > If needed, [create a public client](/getting-started/python#create-a-public-client). > The method is also available on `AsyncSecureClient`. The synchronous clients > provide the same method. > > ```python theme={null} > rebates = await client.get_current_rebates( > date="2026-10-06", > maker_address="0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604", > ) > > for rebate in rebates: > print(rebate.condition_id, rebate.rebated_fees_usdc) > ``` > > Each `RebatedFee` includes `date`, `condition_id`, `asset_address`, > `maker_address`, and `rebated_fees_usdc`. The date is a `datetime.date` and the > USDC amount is a `Decimal`. The method returns an empty tuple when the maker > has no rebates for the requested date. > [tab] API > > Request a date and the nonzero maker address without authentication. > > ```bash theme={null} > curl -G "https://clob.polymarket.com/rebates/current" \ > --data-urlencode "date=2026-10-06" \ > --data-urlencode "maker_address=0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604" > ``` > > Illustrative response: > > > [accordion] Output: Maker Rebates > > > > ```json theme={null} > > [ > > { > > "date": "2026-10-06", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_address": "0x9c4E1703476E875070EE25b56A58B008CFb8FA78", > > "maker_address": "0xFeA4cB3dD4ca7CefD3368653B7D6FF9BcDFca604", > > "rebated_fees_usdc": "1.599840" > > } > > ] > > ``` > > For a maker with no rows, the response is: > > ```json theme={null} > null > ``` > > The response is an array when rebates exist, or `null` when there are no rows. > Each entry contains `date`, `condition_id`, > `asset_address`, `maker_address`, and `rebated_fees_usdc`, an exact USDC decimal > string. This read is not paginated. Use a valid `YYYY-MM-DD` calendar date and the maker's nonzero EVM address. The requested date is not restricted to today. *** ## Funding Maker Rebates are funded by taker fees collected in eligible markets. A percentage of these fees are redistributed to makers who keep the markets liquid. The rebate percentage differs by market type. | Category | Maker Rebate | Distribution Method | | - | - | - | | Crypto | 20% | Fee-curve weighted | | Sports | 15% | Fee-curve weighted | | Finance | 25% | Fee-curve weighted | | Politics | 25% | Fee-curve weighted | | Economics | 25% | Fee-curve weighted | | Culture | 25% | Fee-curve weighted | | Weather | 25% | Fee-curve weighted | | Other / General | 25% | Fee-curve weighted | | Mentions | 25% | Fee-curve weighted | | Tech | 25% | Fee-curve weighted | | Geopolitics | — | Fee-free | > [!NOTE] > > Polymarket collects taker fees in eligible markets across all fee-enabled categories. > The rebate percentage is at the sole discretion of Polymarket > and may change over time. *** ## Fee-Curve Weighted Rebates Rebates are distributed using the **same formula as taker fees**. This ensures makers are rewarded proportionally to the fee value their liquidity generates. For each filled maker order: ```text theme={null} fee_equivalent = C × feeRate × p × (1 - p) ``` Where **C** = number of shares traded and **p** = price of the shares. The fee parameters differ by market type: | Category | Taker Fee Rate | Maker Fee Rate | | - | - | - | | Crypto | 0.07 | 0 | | Sports | 0.05 | 0 | | Finance | 0.04 | 0 | | Politics | 0.04 | 0 | | Economics | 0.05 | 0 | | Culture | 0.05 | 0 | | Weather | 0.05 | 0 | | Other / General | 0.05 | 0 | | Mentions | 0.04 | 0 | | Tech | 0.04 | 0 | | Geopolitics | 0 | 0 | Your daily rebate: ```text theme={null} rebate = (your_fee_equivalent / total_fee_equivalent) * rebate_pool ``` Totals are calculated per market, so you only compete with other makers in the same market. *** ## Taker Fee Structure Taker fees are calculated in pUSD and vary based on the share price. The fee amount in pUSD is symmetric around 50% probability — a trade at 30¢ incurs the same dollar fee as a trade at 70¢. [Fee Curves](https://datawrapper.dwcdn.net/dJ74e/) ### Fee Tables (100 Shares) For detailed fee tables for each market category, see the [Fees](/trading/fees) page. ### Fee Precision Fees are rounded to 5 decimal places. The smallest fee charged is 0.00001 pUSD. Anything smaller rounds to zero, so very small trades near the extremes may incur no fee at all. *** ## Which Markets Are Eligible The following market categories have taker fees enabled and are eligible for maker rebates: Crypto, Sports, Finance, Politics, Economics, Culture, Weather, Tech, Mentions, and Other / General. To confirm whether fees apply to a specific market, see [Trading Fees](/market-data/market-details#trading-fees) in Market Details. *** ## FAQ > [accordion] How do I qualify for maker rebates > > Place orders that add liquidity to the book and get filled (i.e., your > liquidity is taken by another trader). > [accordion] When are rebates paid > > Daily, in pUSD. You must accrue at least \$1 in rebates before a payout is issued. > [accordion] How are rebates calculated > > Rebates are proportional to your share of executed maker liquidity in each > eligible market. Totals are calculated per market, so you only compete with > other makers in the same market. > [accordion] Where does the rebate pool come from > > Taker fees collected in eligible markets are allocated to the maker rebate > pool and distributed daily. > [accordion] Which markets have fees enabled > > Crypto, Sports, Finance, Politics, Economics, Culture, Weather, Tech, Mentions, and Other / General markets. # Referral Program Source: https://docs.polymarket.com/programs/referral-program Refer traders to Polymarket and earn daily pUSD rewards > [!NOTE] > > These updated Referral Program terms take effect on **Thursday, May 28, 2026**. Refer traders to Polymarket and earn a share of the net trading fees they generate, paid every day in pUSD. To start earning, you need at least **\$10,000** in lifetime trading volume on Polymarket. *** ## Eligibility * You need **\$10,000** in lifetime trading volume to earn referral rewards. * You can share links before you reach \$10,000, but you only start earning once you cross the threshold. *** ## How to Refer Share any market or profile page using the share button on that page. When someone clicks your link and signs up, they become your referral. * **Direct referral:** someone you personally refer. * **Indirect referral:** someone referred by one of your referrals. For example, if you refer Alice and Alice refers Bob, then Bob is your indirect referral. To count, a new user must sign up within **30 days** of clicking your link. *** ## Rewards You earn a share of the **net** trading fees your referrals generate. | Type | Reward | | - | - | | Direct referral | **10%** of net trading fees | | Indirect referral | **5%** of net trading fees | > [!NOTE] > > Net trading fees are what Polymarket keeps after the referred user's own tier > rebate. The more rebate they earn, the more of their fees go back to them > rather than into your referral reward. ### The Caps Referral rewards are bounded two ways. Rewards on a referral end at whichever of these comes first: 1. **Until Platinum.** Rewards apply on your referral's trades from the moment they sign up through every tier up to and including **Gold**. Once they reach **Platinum**, referral rewards on their trades end. 2. **30 days.** Rewards apply only for the first 30 days after a referral signs up. ### Example You refer a new trader. From their very first trade and through every tier up to **Gold**, you earn **10%** of the net fees from their trades, paid daily. If they trade actively early on, this is when you earn the most. Your rewards on that referral end once they reach **Platinum** or hit 30 days, whichever happens first. *** ## Payouts * Rewards are **paid every day at midnight UTC** in pUSD, straight to your account. * You can watch your referral earnings add up **live**. *** ## Notes * You earn referral rewards based on the **net** trading fees your referrals generate. Net fees are what Polymarket keeps after the referred user's tier rebate. * Rewards on a referral start with their first trade and end at whichever of these comes first: the referral reaches **Platinum**, or **30 days** since their sign-up. * Not all markets have fees. You will not earn from referral activity on free markets, including Geopolitical and world events markets. * A new user must sign up within **30 days** of clicking your link to be attributed to you. * Reward rates, windows, tier caps, and any other terms are set by Polymarket and can change at any time without notice. * Polymarket reserves the right, at its sole discretion, to disqualify referrals and withhold or claw back rewards for activity that breaks our Terms of Service, including but not limited to self-referrals, linked accounts, and inauthentic trading. *** ## FAQ > [accordion] Who can earn referral rewards > > Any Polymarket user with at least \$10,000 in lifetime trading volume. You > can share links before reaching the threshold, but rewards only begin once > you cross it. > [accordion] What is the difference between direct and indirect referrals > > A direct referral is someone you personally refer. An indirect referral is > someone referred by one of your referrals. You earn 10% of net fees from > direct referrals and 5% from indirect referrals. > [accordion] What does net fees mean > > Net fees are what Polymarket keeps after the referred user's own tier > rebate. Your referral reward is a percentage of that net amount. > [accordion] When do my referral rewards stop > > Rewards on a referral start with their first trade and end at whichever of > these comes first: the referral reaches the Platinum tier, or 30 days from > their sign-up. > [accordion] When am I paid > > Rewards are paid once a day at midnight UTC in pUSD, directly to your > account. > [accordion] What is not allowed > > Self-referrals, referring accounts you control, and inauthentic trading are > not allowed. Polymarket may disqualify referrals and claw back rewards for > activity that breaks the Terms of Service. > [accordion] Are third-party integrations using omnibus wallets eligible > > No. Third-party integrations using omnibus wallets are not eligible for the > Referral Program. # Taker Rebate Program Source: https://docs.polymarket.com/programs/taker-rebates Climb the tiers and earn daily pUSD rebates as you trade > [!NOTE] > > **Upcoming changes — November 20, 2026 at 23:59 UTC.** Polymarket DeFi taker > fees and rebates will change. Maker rebates will move from daily pools to > volume tiers. The current rules below apply until then. [See all fee and > rebate changes](/programs/fee-and-rebate-changes-november-2026). Polymarket Tiers reward you for trading as a **taker**. The more taker volume you do, the higher your tier, the bigger the rebate you earn back on every trade you make from that point on. Every **taker** trade earns **Weighted Volume (wV)**. Your tier is based on your Weighted Volume over the last 30 days, and rebates are paid every day in pUSD. There are seven tiers, from **Bronze** to **Obsidian**. Your tier shows on your profile, and the first time you reach a new tier you get a one-time bonus. *** ## How Tiers Work Your tier is set by how much **Weighted Volume (wV)** you earn over the last 30 days. You earn Weighted Volume on your taker trades. Three things decide how much you earn: 1. How big the trade is. 2. The price you bought at. 3. The category. Some categories are worth more (see the table below). The formula: ```text theme={null} wV = Trade Size × (1 − Entry Price) × Category Weight × Bonuses ``` * **Trade Size** is how much you put into the trade (shares × the price you paid), in dollars. * **(1 − Entry Price)** is the upside per share. A share bought at 40¢ can win 60¢, so its upside is `0.60`. * **Category Weight** is set per category (see below). * **Bonuses** are extra multipliers Polymarket may run on certain categories or events. ### Example 1: A Normal Taker Trade You buy 1,000 shares of a Politics market at 40¢, and the order fills right away (a taker trade). * Trade Size = 1,000 × \$0.40 = **\$400** * Upside per share = 1 − 0.40 = **0.60** * Category Weight for Politics = **1.3** * Weighted Volume earned = 400 × 0.60 × 1.3 = **\$312 wV** ### Example 2: Why Price Matters Two trades, both \$50 in size, both in Crypto (weight 2.3): * A trade at 50¢ earns: 50 × 0.50 × 2.3 = **\$57.50 wV** * A trade at 5¢ earns: 50 × 0.95 × 2.3 = **\$109.25 wV** Both trades count, and your Weighted Volume from every trade adds up over 30 days to set your tier. *** ## Category Weights | Category | Weight | | - | - | | Sports | 1.0 | | Politics, Finance, Mentions, Tech | 1.3 | | Economics, Culture, Weather, Other | 1.7 | | Crypto | 2.3 | | Geopolitics | 0 (free to trade, earns no wV) | > [!NOTE] > > Category weights are set by Polymarket and may change over time. > [!NOTE] > > Only taker trades that pay a fee earn Weighted Volume. If a market's taker fee is 0 (including markets temporarily made fee-free during a fee holiday), trades on it earn **no Weighted Volume and no rebate**, regardless of the category weight above. *** ## Tiers and Rebates Once your 30-day Weighted Volume passes a tier's threshold, you unlock that tier's rebate. The higher your tier, the bigger your rebate. Your rebate applies to your trades from the moment you reach the tier, going forward. | Tier | Name | 30-day wV Needed | Rebate | Level-Up Bonus | | :-: | - | - | :-: | :-: | | 0 | None | Under \$2,000 | 0% | None | | 1 | Bronze | \$2,000 | 3% | \$10 | | 2 | Silver | \$20,000 | 8% | \$50 | | 3 | Gold | \$200,000 | 18% | \$250 | | 4 | Platinum | \$1,000,000 | 32% | \$1,500 | | 5 | Diamond | \$4,000,000 | 44% | \$7,500 | | 6 | Obsidian | \$10,000,000 and up | 50% | \$25,000 | ### Example: Your Rebate Starts When You Reach the Tier The day you reach **Gold**, the 18% Gold rebate turns on for every trade you make from then on. If you keep climbing and hit **Diamond**, your rebate moves up to 44%, and again it applies only to your trades going forward. Your tier updates every day based on your last 30 days of Weighted Volume. Moving up takes effect at the next daily update. *** ## Read Tier Upgrade Notifications Read unread account notifications to update your app when a daily snapshot raises the account's taker tier. Authenticate the account whose notifications you want to read. > [tab] TypeScript > > Call `fetchNotifications()` on a `SecureClient` and narrow by the notification > type before reading the payload. > > ```ts theme={null} > import { NotificationType } from "@polymarket/client"; > > const notifications = await client.fetchNotifications(); > > for (const notification of notifications) { > if (notification.type === NotificationType.TAKER_TIER_UPGRADED) { > const { previousTier, tier, rebateBps, snapshotDate } = > notification.payload; > console.log(previousTier, tier, rebateBps, snapshotDate); > } > } > ``` > > `TakerTierUpgradedNotification` has integer `previousTier`, `tier`, and > `rebateBps` in its payload. `snapshotDate` is a `YYYY-MM-DD` string identifying > the UTC day covered by the snapshot. > [tab] Python > > Call `get_notifications()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method. > > ```python theme={null} > from polymarket import NotificationType > > notifications = await client.get_notifications() > > for notification in notifications: > if notification.type == NotificationType.TAKER_TIER_UPGRADED: > payload = notification.payload > print(payload.previous_tier, payload.tier, payload.rebate_bps, payload.snapshot_date) > ``` > > `TakerTierUpgradedNotification` has integer `previous_tier`, `tier`, and > `rebate_bps` in its payload. `snapshot_date` is a `datetime.date` identifying the > UTC day covered by the snapshot. > [tab] API > > Read unread notifications using the account's CLOB L2 credentials. > > ```bash theme={null} > curl "https://clob.polymarket.com/notifications" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > A tier upgrade notification has `type: 11` and this payload: > > ```json theme={null} > { > "previous_tier": 2, > "tier": 3, > "rebate_bps": 1800, > "snapshot_date": "2026-10-06" > } > ``` > > The tier and rebate values are integers. `snapshot_date` identifies the UTC day > covered by the snapshot, rather than the notification's creation time. The rebate rate uses basis points: 1,800 basis points means 18%. Tier upgrades are account notifications; they do not indicate that a rebate payout has occurred. *** ## Rebates * You can watch your rebates add up **live** as you trade, the same way referral earnings work. * Rebates are **paid every day at midnight UTC** in pUSD, straight to your account. * A minimum accrued rebate of **\$1 pUSD** is required for a payout. *** ## Level-Up Bonuses The first time you reach a new tier, you get a one-time bonus in pUSD: | Tier | Bonus | | - | - | | Bronze | \$10 | | Silver | \$50 | | Gold | \$250 | | Platinum | \$1,500 | | Diamond | \$7,500 | | Obsidian | \$25,000 | For example, the first time you climb from Silver to Gold, you get \$250 added to your account, on top of your normal rebates. *** ## Your Tier on Your Profile Your tier shows on your Polymarket profile and on the leaderboards. As you climb from Bronze to Obsidian, your badge updates to match your current tier. *** ## Notes * Only **taker** trades earn Weighted Volume and count toward your tier. Maker trades (resting orders that add liquidity) do not. Makers are rewarded separately through the [Maker Rebates Program](/programs/maker-rebates). * Your rebate applies only to your trades going forward, starting the moment you reach a tier. * Some markets are free to trade, including Geopolitical and world events markets. These markets earn no Weighted Volume and no rebate. * Your tier is based on your **last 30 days** of Weighted Volume and is updated every day at midnight UTC. * Rebates are paid once a day at midnight UTC in pUSD. * Rebate rates, tier thresholds, category weights, level-up bonuses, and any bonus multipliers are set by Polymarket and can change at any time without notice. * Polymarket reserves the right, at its sole discretion, to adjust rebates and tier status for users. * Polymarket reserves the right, at its sole discretion, to adjust or remove rebates and tier status for activity that breaks our Terms of Service, including but not limited to wash trading, self-matching, or other inauthentic trading. *** ## FAQ > [accordion] Do maker trades count toward my tier > > No. Only taker trades earn Weighted Volume and count toward your tier. > Maker fills are rewarded separately through the > [Maker Rebates Program](/programs/maker-rebates). > [accordion] When does my rebate start applying > > Your rebate applies to trades from the moment you reach a tier, going > forward. There is no backfill on earlier trades. > [accordion] When are rebates paid > > Rebates are paid once a day at midnight UTC in pUSD, directly to your > account. You must accrue at least **\$1** in rebates before a payout is > issued. > [accordion] How often does my tier update > > Your tier is recalculated daily based on your last 30 days of Weighted > Volume. Tier changes take effect at the next daily update. > [accordion] What happens if I slow down trading > > Your tier moves down after a short grace period if your 30-day Weighted > Volume drops below your current tier's threshold. > [accordion] Which markets earn Weighted Volume > > All fee-enabled categories earn Weighted Volume at the weight shown in the > table above. Geopolitical and world events markets are free to trade and > earn no Weighted Volume. > [accordion] Are third-party integrations using omnibus wallets eligible > > No. Third-party integrations using omnibus wallets are not eligible for the > Taker Rebate Program. # Data Resources Source: https://docs.polymarket.com/resources/blockchain-data Access Polymarket on-chain activity for data & analytics Polymarket data that lands on the blockchain, such as trades, balances, positions, and redeems, is available through various on-chain analytics platforms and blockchain data providers. Polymarket also provides its own APIs and WebSockets. See the [API Reference](/api-reference/predictions/overview) for more information. Position data spans Conditional Tokens and PositionManager. Use [Onchain Position Data](/resources/onchain-position-data) to select the correct contracts, identifiers, and events before building a query. > [!NOTE] > > Third-party schemas can lag contract upgrades. Check the indexed contract > addresses against the current [Contracts](/resources/contracts) page. The purpose of this page is to serve as a public good for Polymarket builders, researches, and analysts alike. *** ## Data ### Goldsky [Goldsky](https://docs.goldsky.com/chains/polymarket) provides real-time streaming pipelines for Polymarket on-chain activity (i.e. trades, balances, positions, etc...) into your own database/data warehouse. Goldsky also partnered with [ClickHouse](https://clickhouse.com) to create [CryptoHouse](https://crypto.clickhouse.com), where you can query Polymarket on-chain data using SQL. ### Dune [Dune](https://dune.com) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more. Here are a few simple queries to get started: | Query | Description | Link | | - | - | - | | Volume | Notional Volume and Maker & Taker USDC Volume | [View Dune Query](https://dune.com/queries/6545441) | | TVL | USDC locked in Polymarket smart contracts | [View Dune Query](https://dune.com/queries/6588784) | | Open Interest | Estimated market open interest, and over time | [View Dune Query](https://dune.com/queries/6555478) | ### Allium [Allium](https://docs.allium.so/historical-data/predictions) is a blockchain analytics platform that has Polymarket on-chain activity (i.e. trades, balances, positions, etc...). Query Polymarket data using SQL, create custom dashboards, and more. \-- ## Dashboards Third-party blockchain analytics platforms that aggregate and visualize Polymarket data: > [card] [Blockworks](https://blockworks.com/analytics/polymarket) > [card] [Artemis](https://app.artemisanalytics.com/asset/polymarket?from=assets) > [card] [Dune](https://dune.com/discover/content/popular?q=polymarket\&resource-type=dashboards) > [card] [DeFiLlama](https://defillama.com/protocol/polymarket) > [card] [The Block](https://www.theblock.co/data/decentralized-finance/prediction-markets-and-betting) > [card] [Token Terminal](https://tokenterminal.com/explorer/projects/polymarket) > [card] [Allium](https://predictions.allium.so) ### Community Dashboards Community-created Dune dashboards of Polymarket on-chain analytics: | Dashboard | Created By | Link | | - | - | - | | Polymarket Overview | [@datadashboards](https://x.com/datadashboards) | [View Dashboard](https://dune.com/datadashboards/polymarket-overview) | | Polymarket Volume, OI, Markets, Addresses and TVL | [@hildobby](https://x.com/hildobby) | [View Dashboard](https://dune.com/hildobby/polymarket) | | Polymarket Historical Accuracy | [@alexmccullaaa](https://x.com/alexmccullaaa) | [View Dashboard](https://dune.com/alexmccullough/how-accurate-is-polymarket) | | Polymarket Builders Dashboard | [@defioasis](https://x.com/defioasis) | [View Dashboard](https://dune.com/gateresearch/pmbuilders) | # Contracts Source: https://docs.polymarket.com/resources/contracts All Polymarket smart contract addresses, audits, and security resources These contracts are deployed on Polygon mainnet with chain ID `137`. Use the proxy address when a contract has separate proxy and implementation addresses. > [card] [CTF Exchange V2](https://github.com/Polymarket/ctf-exchange-v2) > > Order matching and settlement for CTF markets. > [card] [Polymarket V2 contracts](https://github.com/Polymarket/polymarket-v2-external) > > Position tokens, modules, oracles, and audits for V2 markets. *** ## Core Contracts | Contract | Address | | - | - | | CTF Exchange | [`0xE111180000d2663C0091e4f400237545B87B996B`](https://polygonscan.com/address/0xE111180000d2663C0091e4f400237545B87B996B) | | Neg Risk CTF Exchange | [`0xe2222d279d744050d28e00520010520000310F59`](https://polygonscan.com/address/0xe2222d279d744050d28e00520010520000310F59) | | Neg Risk Adapter (CTF negative-risk approvals) | [`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`](https://polygonscan.com/address/0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296) | | Conditional Tokens (CTF) | [`0x4D97DCd97eC945f40cF65F87097ACe5EA0476045`](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) | | PositionManager Poly v2 | [`0x006F54F7f9A22e0000CC2AB60031000000ae9fEF`](https://polygonscan.com/address/0x006F54F7f9A22e0000CC2AB60031000000ae9fEF) | | Router Poly v2 | [`0x12121212006e4CD160D18e3f00711DA5c3372600`](https://polygonscan.com/address/0x12121212006e4CD160D18e3f00711DA5c3372600) | | BinaryModule Poly v2 | [`0x1000008dD9001B968442c1000017eaE6E0dA00Ba`](https://polygonscan.com/address/0x1000008dD9001B968442c1000017eaE6E0dA00Ba) | | NegRiskModule Poly v2 | [`0x200000900045e3B6259600682756002200028933`](https://polygonscan.com/address/0x200000900045e3B6259600682756002200028933) | | CombinatorialModule Poly v2 | [`0x30000034706C7d8e12009DAB006Be20000c031A8`](https://polygonscan.com/address/0x30000034706C7d8e12009DAB006Be20000c031A8) | | ExchangeV3 Poly v2 | [`0xe3333700cA9d93003F00f0F71f8515005F6c00Aa`](https://polygonscan.com/address/0xe3333700cA9d93003F00f0F71f8515005F6c00Aa) | | AutoRedeemer Poly v2 | [`0xa1200000d0002264C9a1698e001292D00E1b00af`](https://polygonscan.com/address/0xa1200000d0002264C9a1698e001292D00E1b00af) | *** The pUSD collateral system and account wallets support both position systems. The CTF collateral adapters move value between pUSD and the collateral used by CTF. | Contract | Address | | - | - | | pUSD — CollateralToken Poly v2 | [`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`](https://polygonscan.com/address/0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB) | | CollateralOnramp Poly v2 | [`0x93070a847efEf7F70739046A929D47a521F5B8ee`](https://polygonscan.com/address/0x93070a847efEf7F70739046A929D47a521F5B8ee) | | CollateralOfframp Poly v2 | [`0x2957922Eb93258b93368531d39fAcCA3B4dC5854`](https://polygonscan.com/address/0x2957922Eb93258b93368531d39fAcCA3B4dC5854) | | PermissionedRamp Poly v2 | [`0xebC2459Ec962869ca4c0bd1E06368272732BCb08`](https://polygonscan.com/address/0xebC2459Ec962869ca4c0bd1E06368272732BCb08) | | CtfCollateralAdapter | [`0xAdA100Db00Ca00073811820692005400218FcE1f`](https://polygonscan.com/address/0xAdA100Db00Ca00073811820692005400218FcE1f) | | NegRiskCtfCollateralAdapter | [`0xadA2005600Dec949baf300f4C6120000bDB6eAab`](https://polygonscan.com/address/0xadA2005600Dec949baf300f4C6120000bDB6eAab) | | Contract | Address | | - | - | | pUSD CollateralToken proxy | [`0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB`](https://polygonscan.com/address/0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB) | | pUSD CollateralToken implementation | [`0xCe84E053301A82937F90ee2C2c1889cAb1db25dE`](https://polygonscan.com/address/0xCe84E053301A82937F90ee2C2c1889cAb1db25dE) | | CollateralOnramp | [`0x93070a847efEf7F70739046A929D47a521F5B8ee`](https://polygonscan.com/address/0x93070a847efEf7F70739046A929D47a521F5B8ee) | | CollateralOfframp | [`0x2957922Eb93258b93368531d39fAcCA3B4dC5854`](https://polygonscan.com/address/0x2957922Eb93258b93368531d39fAcCA3B4dC5854) | | PermissionedRamp | [`0xebC2459Ec962869ca4c0bd1E06368272732BCb08`](https://polygonscan.com/address/0xebC2459Ec962869ca4c0bd1E06368272732BCb08) | | CtfCollateralAdapter | [`0xAdA100Db00Ca00073811820692005400218FcE1f`](https://polygonscan.com/address/0xAdA100Db00Ca00073811820692005400218FcE1f) | | NegRiskCtfCollateralAdapter | [`0xadA2005600Dec949baf300f4C6120000bDB6eAab`](https://polygonscan.com/address/0xadA2005600Dec949baf300f4C6120000bDB6eAab) | ### Wallet Factory Contracts | Contract | Address | | - | - | | Deposit Wallet Factory | [`0x00000000000Fb5C9ADea0298D729A0CB3823Cc07`](https://polygonscan.com/address/0x00000000000Fb5C9ADea0298D729A0CB3823Cc07) | | Deposit Wallet Beacon | [`0x7A18EDfe055488A3128f01F563e5B479D92ffc3a`](https://polygonscan.com/address/0x7A18EDfe055488A3128f01F563e5B479D92ffc3a) | | Gnosis Safe Factory | [`0xaacfeea03eb1561c4e67d661e40682bd20e3541b`](https://polygonscan.com/address/0xaacfeea03eb1561c4e67d661e40682bd20e3541b) | | Polymarket Proxy Factory | [`0xaB45c5A4B0c941a2F231C04C3f49182e1A254052`](https://polygonscan.com/address/0xaB45c5A4B0c941a2F231C04C3f49182e1A254052) | ## CTF These contracts own and exchange CTF outcome balances. | Contract | Address | | - | - | | Conditional Tokens | [`0x4D97DCd97eC945f40cF65F87097ACe5EA0476045`](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) | | CTF Exchange | [`0xE111180000d2663C0091e4f400237545B87B996B`](https://polygonscan.com/address/0xE111180000d2663C0091e4f400237545B87B996B) | | Neg Risk CTF Exchange | [`0xe2222d279d744050d28e00520010520000310F59`](https://polygonscan.com/address/0xe2222d279d744050d28e00520010520000310F59) | | Neg Risk Adapter (CTF negative-risk approvals) | [`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`](https://polygonscan.com/address/0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296) | The CLOB still checks pUSD and Conditional Tokens approvals for the Neg Risk Adapter on orders in CTF negative-risk markets. Grant them with the other [trading approvals](/trading/wallets-auth#set-up-trading-approvals). This Neg Risk Adapter (`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`) is a different contract from NegRiskCtfCollateralAdapter (`0xadA2005600Dec949baf300f4C6120000bDB6eAab`); approving NegRiskCtfCollateralAdapter does not grant the Neg Risk Adapter approvals. ## Polymarket Protocol V2 Contracts PositionManager owns the ERC-1155 balances. The position ID routes each operation to BinaryModule, NegRiskModule, or CombinatorialModule. | Contract | Proxy | Implementation | | - | - | - | | PositionManager | [`0x006F54F7f9A22e0000CC2AB60031000000ae9fEF`](https://polygonscan.com/address/0x006F54F7f9A22e0000CC2AB60031000000ae9fEF) | [`0xCc5De1e9D14a7AB75E872E23FC9D605518Bac2D0`](https://polygonscan.com/address/0xCc5De1e9D14a7AB75E872E23FC9D605518Bac2D0) | | Exchange | [`0xe3333700cA9d93003F00f0F71f8515005F6c00Aa`](https://polygonscan.com/address/0xe3333700cA9d93003F00f0F71f8515005F6c00Aa) | [`0x641b40ec414a076b9e79E703Fc7BF4EBEC248Bb7`](https://polygonscan.com/address/0x641b40ec414a076b9e79E703Fc7BF4EBEC248Bb7) | | Router | [`0x12121212006e4CD160D18e3f00711DA5c3372600`](https://polygonscan.com/address/0x12121212006e4CD160D18e3f00711DA5c3372600) | [`0x91fA5E2F12a308A13DefdB6aaF80B71DBe9B7696`](https://polygonscan.com/address/0x91fA5E2F12a308A13DefdB6aaF80B71DBe9B7696) | | BinaryModule | [`0x1000008dD9001B968442c1000017eaE6E0dA00Ba`](https://polygonscan.com/address/0x1000008dD9001B968442c1000017eaE6E0dA00Ba) | [`0xf6428c0B5fa9361c0708CDdb95468cf54C56e9A2`](https://polygonscan.com/address/0xf6428c0B5fa9361c0708CDdb95468cf54C56e9A2) | | NegRiskModule | [`0x200000900045e3B6259600682756002200028933`](https://polygonscan.com/address/0x200000900045e3B6259600682756002200028933) | [`0x39a5B01a100edF811f2748aa37B1313715Ded70e`](https://polygonscan.com/address/0x39a5B01a100edF811f2748aa37B1313715Ded70e) | | CombinatorialModule | [`0x30000034706C7d8e12009DAB006Be20000c031A8`](https://polygonscan.com/address/0x30000034706C7d8e12009DAB006Be20000c031A8) | [`0xf96968a44022B17240B42c557693E7C383d2d8a3`](https://polygonscan.com/address/0xf96968a44022B17240B42c557693E7C383d2d8a3) | ## Resolution Contracts | Contract | Address | | - | - | | UMA Adapter | [`0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74`](https://polygonscan.com/address/0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74) | | UMA Optimistic Oracle | [`0xCB1822859cEF82Cd2Eb4E6276C7916e692995130`](https://polygonscan.com/address/0xCB1822859cEF82Cd2Eb4E6276C7916e692995130) | | OracleAggregator Poly v2 | [`0x0A0a0A0A8B00C51b7D810501b03F230028C04a87`](https://polygonscan.com/address/0x0A0a0A0A8B00C51b7D810501b03F230028C04a87) | | OOReporterModule Poly v2 | [`0x000012e0009c84078c4924fba808A41b9f67527f`](https://polygonscan.com/address/0x000012e0009c84078c4924fba808A41b9f67527f) | | ChainlinkReporterModule Poly v2 | [`0xc12EC12E0000326890Ca5560dEf5EB5C22b16814`](https://polygonscan.com/address/0xc12EC12E0000326890Ca5560dEf5EB5C22b16814) | | EOAReporterModule Poly v2 | [`0x8Ef9D6d668798b1f363b305D916F30739d2b0419`](https://polygonscan.com/address/0x8Ef9D6d668798b1f363b305D916F30739d2b0419) | | Contract | Address | | - | - | | UmaCtfAdapter v3.1.0 | [`0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49`](https://polygonscan.com/address/0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49) | | UmaCtfAdapter v2.0.0 | [`0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74`](https://polygonscan.com/address/0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74) | | UmaCtfAdapter v1.0.0 | [`0xCB1822859cEF82Cd2Eb4E6276C7916e692995130`](https://polygonscan.com/address/0xCB1822859cEF82Cd2Eb4E6276C7916e692995130) | ### Polymarket Protocol V2 OracleAggregator receives results from the supported reporter modules and sends the final result to the module that owns the condition. | Contract | Proxy | Implementation | | - | - | - | | OracleAggregator | [`0x0A0a0A0A8B00C51b7D810501b03F230028C04a87`](https://polygonscan.com/address/0x0A0a0A0A8B00C51b7D810501b03F230028C04a87) | [`0x822e8A97AF8005073F2f6E88435D692E33ab6082`](https://polygonscan.com/address/0x822e8A97AF8005073F2f6E88435D692E33ab6082) | | OOReporterModule | [`0x000012e0009c84078c4924fba808A41b9f67527f`](https://polygonscan.com/address/0x000012e0009c84078c4924fba808A41b9f67527f) | [`0xBd49A21677Da630fF5Efec52B7309d0Ada685d81`](https://polygonscan.com/address/0xBd49A21677Da630fF5Efec52B7309d0Ada685d81) | | ChainlinkReporterModule | [`0xc12EC12E0000326890Ca5560dEf5EB5C22b16814`](https://polygonscan.com/address/0xc12EC12E0000326890Ca5560dEf5EB5C22b16814) | [`0x70545d95653a4a7B1c2F47f6a9383E36EaAA55b2`](https://polygonscan.com/address/0x70545d95653a4a7B1c2F47f6a9383E36EaAA55b2) | | EOAReporterModule | [`0x8Ef9D6d668798b1f363b305D916F30739d2b0419`](https://polygonscan.com/address/0x8Ef9D6d668798b1f363b305D916F30739d2b0419) | [`0x5fe0280873f5539da12B6b5b37484E0B0c28Ab14`](https://polygonscan.com/address/0x5fe0280873f5539da12B6b5b37484E0B0c28Ab14) | ## Redemption and Migration | Contract | Proxy | Implementation | | - | - | - | | AutoRedeemer | [`0xa1200000d0002264C9a1698e001292D00E1b00af`](https://polygonscan.com/address/0xa1200000d0002264C9a1698e001292D00E1b00af) | [`0x64860bFD14fCcaAc09cd36f347784a9616AfB66C`](https://polygonscan.com/address/0x64860bFD14fCcaAc09cd36f347784a9616AfB66C) | AutoRedeemer supports resolved balances from Conditional Tokens and PositionManager. CTF-to-PositionManager migration is implemented by the BinaryModule and NegRiskModule addresses listed above. A condition or event must be registered by Polymarket before a holder can migrate its positions. See [Onchain Position Data](/resources/onchain-position-data) for the events and identifiers used to index redemptions and migrations. ## Security ### Audits Polymarket's contracts have been reviewed by multiple independent security firms: | Scope | Auditor | Report | | - | - | - | | v1.2.0 | Cantina | [August 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/v1.2.0%20-%20Cantina%20-%20August%202026.pdf) | | v1.2.0 | Quantstamp | [August 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/v1.2.0%20-%20Quantstamp%20-%20August%202026.pdf) | | Formal Verification | Certora | [August 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Formal%20Verification%20-%20Certora%20-%20August%202026.pdf) | | Oracle Subsystem | Cantina | [July 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Oracle%20Subsystem%20-%20Cantina%20-%20July%202026.pdf) | | Oracle Subsystem | Certora | [July 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Oracle%20Subsystem%20-%20Certora%20-%20July%202026.pdf) | | Combo Collateral Return + CCIP | Cantina | [July 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Combo%20Collateral%20Return%20%2B%20CCIP%20-%20Cantina%20-%20July%202026.pdf) | | Combo Collateral Return + CCIP | Certora | [July 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Combo%20Collateral%20Return%20%2B%20CCIP%20-%20Certora%20-%20July%202026.pdf) | | Combinatorial Module | Cantina | [May 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Combinatorial%20Module%20-%20Cantina%20-%20May%202026.pdf) | | Combinatorial Module | Certora | [May 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Combinatorial%20Module%20-%20Certora%20-%20May%202026.pdf) | | Combinatorial Module | Quantstamp | [May 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Combinatorial%20Module%20-%20Quantstamp%20-%20May%202026.pdf) | | Polymarket V2 | SigmaPrime | [June 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20SigmaPrime%20-%20June%202026.pdf) | | Polymarket V2 | Zellic | [June 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20Zellic%20-%20June%202026.pdf) | | Polymarket V2 | Pashov | [May 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20Pashov%20-%20May%202026.pdf) | | Polymarket V2 | Quantstamp | [May 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20Quantstamp%20-%20May%202026.pdf) | | Polymarket V2 | Cantina | [April 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20Cantina%20-%20April%202026.pdf) | | Polymarket V2 | Certora | [April 2026](https://github.com/Polymarket/polymarket-v2-external/blob/main/audit/Polymarket%20V2%20-%20Certora%20-%20April%202026.pdf) | | CTF Exchange V2 | Quantstamp | [March 2026](https://github.com/Polymarket/ctf-exchange-v2/blob/main/audits/CTF%20Exchange%20V2%20-%20Quantstamp%20-%20March%202026.pdf) | | CTF Exchange V2 | Cantina | [March 2026](https://github.com/Polymarket/ctf-exchange-v2/blob/main/audits/CTF%20Exchange%20V2%20-%20Cantina%20-%20March%202026.pdf) | ### Bug Bounty Security vulnerabilities can be reported through the [Cantina bug bounty program](https://cantina.xyz/bounties/ff945ca2-2a6e-4b83-b1b6-7a0cd3b94bea). # Error Codes Source: https://docs.polymarket.com/resources/error-codes Complete reference for CLOB API error responses All CLOB API errors return a JSON object with a single `error` field: ```json theme={null} { "error": "" } ``` *** ## Global Errors These errors can occur on **any authenticated endpoint**. **401** `Unauthorized` `Unauthorized/Invalid api key` — Your API key is missing, expired, or invalid. Ensure you're sending all required [authentication headers](/getting-started/api#authentication). **401** `Unauthorized` `Invalid L1 Request headers` — Your L1 authentication headers (HMAC signature) are malformed or the signature doesn't match. See [Authentication](/getting-started/api#authentication). **503** `Service Unavailable` `Trading is currently disabled. Check polymarket.com for updates` — The exchange is temporarily paused. No orders (including cancels) are accepted. **429** `Too Many Requests` `Too Many Requests` — You've exceeded the [rate limit](/api-reference/rate-limits). Back off and retry with exponential backoff. *** ## Order Book Errors from the order book endpoints. ### GET book **400** `Bad Request` `Invalid token id` — The `token_id` query parameter is missing or not a valid token ID. **404** `Not Found` `No orderbook exists for the requested token id` ### POST books **400** `Bad Request` `Invalid payload` — The request body is malformed or missing required fields. **400** `Bad Request` `Payload exceeds the limit` — Too many outcome IDs in a single request. Reduce the batch size. *** ## Pricing Errors from price, midpoint, and spread endpoints. ### GET price **400** `Bad Request` `Invalid token id` — The `token_id` parameter is missing or is not a valid outcome ID. **400** `Bad Request` `Invalid side` — The `side` parameter must be `BUY` or `SELL`. **404** `Not Found` `No orderbook exists for the requested token id` ### POST prices **400** `Bad Request` `Invalid payload` — The request body is malformed or missing required fields. **400** `Bad Request` `Invalid side` — The `side` field must be `BUY` or `SELL`. **400** `Bad Request` `Payload exceeds the limit` — Too many outcome IDs in a single request. ### GET midpoint **400** `Bad Request` `Invalid token id` — The `token_id` parameter is missing or is not a valid outcome ID. **404** `Not Found` `No orderbook exists for the requested token id` ### POST midpoints **400** `Bad Request` `Invalid payload` — The request body is malformed or missing required fields. **400** `Bad Request` `Payload exceeds the limit` — Too many outcome IDs in a single request. ### GET spread **400** `Bad Request` `Invalid token id` — The `token_id` parameter is missing or is not a valid outcome ID. **404** `Not Found` `No orderbook exists for the requested token id` ### POST spreads **400** `Bad Request` `Invalid payload` — The request body is malformed or missing required fields. **400** `Bad Request` `Payload exceeds the limit` — Too many outcome IDs in a single request. *** ## Place Orders Errors from order placement endpoints. ### POST order **400** `Bad Request` `Invalid order payload` — The request body is malformed, missing required fields, or contains invalid values. **400** `Bad Request` `the order owner has to be the owner of the API KEY` — The `maker` address in the order doesn't match the address associated with your API key. **400** `Bad Request` `the order signer address has to be the address of the API KEY` **400** `Bad Request` `'{address}' address banned` — This address has been banned from trading. **400** `Bad Request` `'{address}' address in closed only mode` **503** `Service Unavailable` `Trading is currently cancel-only. New orders are not accepted, but cancels are allowed.` — The exchange is in cancel-only mode. You can cancel existing orders but cannot place new orders. **503** `Service Unavailable` `post-only mode: only post-only orders and cancels are allowed` — The exchange is in post-only mode. You can cancel orders and place orders with `postOnly: true`; non-post-only orders are rejected. The response includes `code: "post_only_mode"` and `retry_after_seconds`, and the same retry delay is also sent in the `Retry-After` HTTP header. Example response: ```json theme={null} { "error": "post-only mode: only post-only orders and cancels are allowed", "code": "post_only_mode", "retry_after_seconds": 79 } ``` The retry delay is also sent in the `Retry-After` HTTP header. ### POST orders All errors from `POST /order` apply, plus: **400** `Bad Request` `Too many orders in payload: {N}, max allowed: {M}` — The batch contains more orders than the maximum allowed per request. Per-order errors are returned in the `200` response array, with individual error messages for each failed order. In post-only mode, non-post-only orders in a batch return per-order errors: ```json theme={null} [ { "errorMsg": "post-only mode: only post-only orders and cancels are allowed", "orderID": "", "takingAmount": "", "makingAmount": "", "status": "", "success": true }, { "errorMsg": "post-only mode: only post-only orders and cancels are allowed", "orderID": "", "takingAmount": "", "makingAmount": "", "status": "", "success": true } ] ``` *** ## Order Processing Errors These errors are returned when an order passes initial validation but fails during processing. They appear in the response body of `POST /order` and `POST /orders`. **400** `Bad Request` `invalid post-only order: order crosses book` — A post-only (maker) order would immediately match. Adjust the price so it rests on the book. **400** `Bad Request` `order {id} is invalid. Price ({price}) breaks minimum tick size rule: {tick}` — The order price doesn't align with the market's tick size. Use [`GET /tick-size`](/api-reference/market-data/get-tick-size) to check the valid tick size. **400** `Bad Request` `order {id} is invalid. Size ({size}) lower than the minimum: {min}` — The order size is below the market minimum. **400** `Bad Request` `order {id} is invalid. Duplicated.` **400** `Bad Request` `order {id} crosses the book` **400** `Bad Request` `not enough balance / allowance` — Insufficient pUSD balance or token allowance. Make sure the account holds enough pUSD and grant the trading approvals with [Set Up Trading Approvals](/trading/wallets-auth#set-up-trading-approvals). An allowance error names one missing spender at a time. If it names the Neg Risk Adapter (`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`), the account wallet is missing the adapter approvals required for CTF negative-risk markets. **400** `Bad Request` `invalid expiration` — The order expiration timestamp is in the past or invalid. **400** `Bad Request` `order canceled in the CTF exchange contract` **400** `Bad Request` `order match delayed due to market conditions` **400** `Bad Request` `order couldn't be fully filled. FOK orders are fully filled or killed.` — A Fill-or-Kill order could not be completely filled by available liquidity. The entire order is rejected. **400** `Bad Request` `no orders found to match with FAK order. FAK orders are partially filled or killed if no match is found.` — A Fill-and-Kill order found no matching orders at all. At least one match is required. **400** `Bad Request` `the market is not yet ready to process new orders` **500** `Internal Server Error` `order timed out` — The exchange could not process the order before the request deadline. This typically happens during bursts of concurrent order submissions from the same account. The order was rejected before reaching the order book and can be safely resubmitted. *** ## Matching Engine Errors Internal matching engine errors that may surface during order execution. **425** `Too Early` The matching engine is restarting. Retry with exponential backoff. See [Matching Engine Restarts](/trading/matching-engine) for restart handling. **500** `Internal Server Error` `there are no matching orders` **500** `Internal Server Error` `FOK orders are filled or killed` — A Fill-or-Kill order could not be fully satisfied. **500** `Internal Server Error` `the trade contains rounding issues` **500** `Internal Server Error` `the price of the taker's order has a discrepancy greater than allowed with the worst maker order` *** ## Cancel Orders Errors from order cancellation endpoints. ### DELETE order **400** `Bad Request` `Invalid order payload` — The request body is malformed. **400** `Bad Request` `Invalid orderID` — The provided order ID is not a valid format. ### DELETE orders **400** `Bad Request` `Invalid order payload` — The request body is malformed. **400** `Bad Request` `Too many orders in payload, max allowed: {N}` — Too many order IDs in a single cancellation request. **400** `Bad Request` `Invalid orderID` — One or more order IDs are not valid. ### DELETE cancel-market-orders **400** `Bad Request` `Invalid order payload` — The request body is malformed or contains invalid filter parameters. *** ## Query Orders Errors from order query endpoints. ### GET order by ID **400** `Bad Request` `Invalid orderID` — The order ID in the URL path is not valid. **500** `Internal Server Error` `Internal server error` — An unexpected error occurred while fetching the order. ### GET orders **400** `Bad Request` `invalid order params payload` — The query parameters are malformed or contain invalid values. **500** `Internal Server Error` `Internal server error` — An unexpected error occurred while fetching orders. *** ## Trades ### GET trades **400** `Bad Request` `Invalid trade params payload` — The query parameters are malformed or contain invalid values. **500** `Internal Server Error` `Internal server error` — An unexpected error occurred while fetching trades. ### GET last-trade-price **400** `Bad Request` `Invalid token id` — The `token_id` parameter is missing or is not a valid outcome ID. **500** `Internal Server Error` `Internal server error` — An unexpected error occurred while fetching the last trade price. ### POST last-trades-prices **400** `Bad Request` `Invalid payload` — The request body is malformed or missing required fields. **400** `Bad Request` `Payload exceeds the limit` — Too many outcome IDs in a single request. *** ## Markets ### GET market by condition ID **400** `Bad Request` `Invalid market` — The condition ID is not a valid format. **404** `Not Found` `market not found` — No market exists with this condition ID. ### GET tick-size **400** `Bad Request` `Invalid token id` — The outcome ID is not valid. **404** `Not Found` `market not found` — No market found for this outcome ID. ### GET neg-risk **400** `Bad Request` `Invalid token id` — The outcome ID is not valid. **404** `Not Found` `market not found` — No market found for this outcome ID. *** ## Price History ### GET prices-history **400** `Bad Request` Filter validation errors — One or more query parameters (`market`, `startTs`, `endTs`, `fidelity`) are invalid. ### GET ohlc **400** `Bad Request` `startTs is required` — The `startTs` query parameter is missing. **400** `Bad Request` `asset_id is required` — The `asset_id` query parameter is missing. **400** `Bad Request` `invalid fidelity: {val}` — The `fidelity` parameter must be one of: `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `1d`, `1w`. **400** `Bad Request` `limit cannot exceed 1000` — Reduce the `limit` parameter to 1000 or below. *** ## Authentication and API Keys ### POST auth api-key **401** `Unauthorized` `Invalid L1 Request headers` — L1 authentication headers are missing or invalid. **400** `Bad Request` `Could not create api key` ### GET auth api-keys **500** `Internal Server Error` `Could not retrieve API keys` — An unexpected error occurred while fetching your API keys. ### DELETE auth api-key **500** `Internal Server Error` `Could not delete API key` — An unexpected error occurred while deleting the API key. ### GET auth derive-api-key **401** `Unauthorized` `Invalid L1 Request headers` — L1 authentication headers are missing or invalid. **400** `Bad Request` `Could not derive api key!` *** ## Builder API Keys ### POST auth builder-api-key **500** `Internal Server Error` `could not create builder api key` — Builder API key creation failed. ### GET auth builder-api-key **500** `Internal Server Error` `could not get builder api keys` — An unexpected error occurred while fetching builder API keys. ### DELETE auth builder-api-key **400** `Bad Request` `invalid revoke builder api key body` — The request body is malformed. **400** `Bad Request` `invalid revoke builder api key headers` — Required authentication headers are missing. **500** `Internal Server Error` `could not revoke the builder api key: {key}` — An unexpected error occurred while revoking the key. *** ## Builder Trades ### GET builder trades **400** `Bad Request` `invalid builder trade params` — The query parameters are malformed or contain invalid values. **500** `Internal Server Error` `could not fetch builder trades` — An unexpected error occurred while fetching builder trades. *** ## Balance and Allowance ### GET balance-allowance **400** `Bad Request` `Invalid asset type` — The `asset_type` parameter is not a recognized asset type. **400** `Bad Request` `Invalid signature_type` — The `signature_type` parameter must be `0` (EOA), `1` (POLY_PROXY), `2` (POLY_GNOSIS_SAFE) or `3` (POLY_1271, Deposit Wallet). *** ## Status Code Reference | Status | Meaning | Common Causes | | - | - | - | | `400` | Bad Request | Invalid parameters, malformed payload, business logic violation | | `401` | Unauthorized | Missing or invalid API key, bad HMAC signature, expired timestamp | | `404` | Not Found | Market doesn't exist, order not found, outcome ID not recognized | | `425` | Too Early | Matching engine is restarting — retry with backoff. See [Matching Engine Restarts](/trading/matching-engine) | | `429` | Too Many Requests | Rate limit exceeded — implement exponential backoff | | `500` | Internal Server Error | Unexpected server error — retry with backoff | | `503` | Service Unavailable | Exchange paused, or order placement blocked by cancel-only / post-only mode | > [!NOTE] > > The CLOB API has an internal override: any error message containing `"not > found"` returns `404`, `"unauthorized"` returns `401`, and `"context > canceled"` returns `400`, regardless of the original status code. # Onchain Position Data Source: https://docs.polymarket.com/resources/onchain-position-data Index balances, trades, and resolution across both position systems Polymarket outcome balances live in one of two ERC-1155 contracts. Use the market `version` returned by Gamma to select the correct section below. Field presence is not a reliable discriminator because a CTF market can also appear as a leg in a PositionManager workflow. | Gamma `version` | Position system | Outcome ID | ERC-1155 ledger | Exchange domain version | | - | - | - | - | - | | `"v2"` | Polymarket V2 | Outcome `positionId` | PositionManager | `"3"` | | `"v1"` | CTF | Outcome `tokenId` | Conditional Tokens | `"2"` | See [Discover Markets](/market-data/discover-markets) for the discovery workflow and [Contracts](/resources/contracts) for Polygon addresses. ## CTF ### Derive CTF Identifiers Conditional Tokens derives each identifier from the condition and collateral path. Use the deployed contract helpers when possible. | Identifier | Derivation | | - | - | | Condition ID | `keccak256(abi.encodePacked(oracle, questionId, outcomeSlotCount))` | | Collection ID | `getCollectionId(parentCollectionId, conditionId, indexSet)` | | Position ID | `getPositionId(collateralToken, collectionId)` | A CTF position can contain more than one condition through its parent collection. The `indexSet` selects the represented outcomes. For a binary condition, the two singleton collections use index sets `1` and `2`. Conditional Tokens does not define a platform-wide event identifier. Negative risk grouping is maintained by the Neg Risk Adapter. Gamma provides the event and market identifiers used by application integrations. ### Index CTF Balances and Lifecycle Events Build balances from `TransferSingle` and `TransferBatch` events emitted by Conditional Tokens. Build operator approvals from `ApprovalForAll`. | Event shape | Indexing action | | - | - | | `from` is the zero address | Increase the holder balance and indexed supply | | `to` is the zero address | Decrease the holder balance and indexed supply | | Both addresses are nonzero | Move the balance between holders | | `ApprovalForAll` | Update the owner and operator approval pair | Conditional Tokens does not expose a general total-supply read for every outcome token. Start from the deployment block or another verified checkpoint if your indexer needs complete historical balances or supply. Use these lifecycle events as transaction context around the ERC-1155 balance changes: | Workflow | Events | | - | - | | Prepare | `ConditionPreparation` and `MarketPrepared` | | Split | `PositionSplit` | | Merge | `PositionsMerge` | | Convert | `PositionsConverted` | | Redeem | `PayoutRedemption` | | Resolve | `OutcomeReported` and `ConditionResolution` | ERC-1155 transfer events remain the canonical input for balances, minting, burning, and supply. Do not count a lifecycle event and its underlying transfer as two balance changes. ### Attribute CTF Exchange Fills The CTF exchanges emit `OrderFilled`, `OrdersMatched`, and `FeeCharged`. The signed order field is named `tokenId` and contains the CTF outcome token ID selected during market discovery. `OrderFilled` includes the signed `builder` value and `metadata`. Record the exchange address or EIP-712 domain version `"2"` with each order. This keeps fills attributable to the correct position system when both systems use the same order shape. ### Track CTF Resolution and Redemptions Conditional Tokens stores `payoutNumerators` and `payoutDenominator`. The payout fraction for one outcome is its numerator divided by the condition denominator. AutoRedeemer identifies the source of an automated CTF redemption with one of these events: | Event | Balance source | | - | - | | `BinaryRedemption` | Binary Conditional Tokens position | | `NegRiskRedemption` | Negative risk Conditional Tokens position | The ledger also emits its normal redemption, burn, and transfer events. Use the AutoRedeemer event to attribute the automated action and the ledger events to update balances and supply. ## Polymarket Protocol V2 ### Decode Polymarket Protocol V2 Position IDs A Polymarket Protocol V2 Position ID encodes its module, event, condition, and outcome. The same value can be reduced to a Condition ID or Event ID by clearing its lower fields. ```text theme={null} [moduleId | baseHash | arity | reserved | resolutionChain | conditionIndex | outcomeIndex] 8 bits 128 bits 16 bits 64 bits 16 bits 16 bits 8 bits ``` | Field | Bits | Purpose | | - | - | - | | `moduleId` | 248 to 255 | Routes the position to its module | | `baseHash` | 120 to 247 | Identifies the source event or question data | | `arity` | 104 to 119 | Stores the real condition count for negative risk events | | `reserved` | 40 to 103 | Reserved event identity bits | | `resolutionChain` | 24 to 39 | Identifies the chain allowed to resolve the condition | | `conditionIndex` | 8 to 23 | Selects a condition within an event | | `outcomeIndex` | 0 to 7 | Selects the condition outcome | Current module IDs are: | Module ID | Module | | - | - | | `1` | BinaryModule | | `2` | NegRiskModule | | `3` | CombinatorialModule | The native Polymarket Protocol V2 identifier helpers derive identifiers in this order: | Identifier | Derivation | | - | - | | Base hash | `keccak256(abi.encode(moduleId, data))`, truncated to its low 128 bits in the encoded ID | | Event ID | Encodes the module ID, base hash, arity, and resolution chain with the lower 24 bits clear | | Condition ID | Adds `conditionIndex` to its Event ID and keeps the outcome byte clear | | Position ID | Adds `outcomeIndex` to its Condition ID | Migration uses precomputed legacy identifiers instead of the native base-hash derivation. Binary migration passes the legacy CTF Condition ID directly as the base-hash input. Negative risk migration passes the legacy event ID directly as the Event ID base-hash input, then derives its Condition IDs by index. Do not hash either legacy identifier again. Treat `MigrationConditionRegistered` as the authoritative CTF-to-Polymarket Protocol V2 Condition ID mapping and `EventPrepared` as the authoritative legacy-to-Polymarket Protocol V2 Event ID mapping. Polymarket Protocol V2 represents a Condition ID as `bytes31` and an Event ID as `bytes29`. Compatibility boundaries that accept or return `bytes32` use the same values right-padded with zero bytes. Preserve the native widths when decoding typed ABI values, and pad only when the target ABI requires `bytes32`. Binary conditions have arity `0` and condition index `0`, so their Condition ID is bit-equivalent to their Event ID. Use these masks when decoding a Position ID: ```text theme={null} moduleId = positionId >> 248 outcomeIndex = positionId & 0xff conditionId = positionId with bits 0 to 7 cleared eventId = positionId with bits 0 to 23 cleared conditionIndex = (positionId >> 8) & 0xffff arity = (positionId >> 104) & 0xffff ``` The other binary outcome is derived by replacing `outcomeIndex` with `0` for YES or `1` for NO. A canonical Condition ID has a zero outcome byte. A canonical Event ID has zero condition and outcome fields. ### Index PositionManager Balances and Lifecycle Events Build balances from `TransferSingle` and `TransferBatch` events emitted by PositionManager. Build operator approvals from `ApprovalForAll`. | Event shape | Indexing action | | - | - | | `from` is the zero address | Increase the holder balance and indexed supply | | `to` is the zero address | Decrease the holder balance and indexed supply | | Both addresses are nonzero | Move the balance between holders | | `ApprovalForAll` | Update the owner and operator approval pair | PositionManager does not expose a general total-supply read for every outcome token. Start from the deployment block or another verified checkpoint if your indexer needs complete historical balances or supply. Use these lifecycle events as transaction context around the ERC-1155 balance changes: | Workflow | Module scope | Events | | - | - | - | | Prepare | NegRiskModule migration | `EventPrepared` | | Prepare | CombinatorialModule | `CombinatorialConditionPrepared` | | Split | BinaryModule, NegRiskModule, or Combo | `PositionsSplit`, `HorizontalSplit`, or combinatorial split events | | Merge | BinaryModule, NegRiskModule, or Combo | `PositionsMerged`, `HorizontalMerge`, or combinatorial merge events | | Convert | NegRiskModule | `PositionConverted` | | Redeem | BinaryModule, NegRiskModule, or Combo | `PositionRedeemed` | | Resolve | BinaryModule or NegRiskModule | `ResultReported` and `ConditionResolved` | | Bridge | BinaryModule or NegRiskModule | `BridgePositionMinted` and `BridgePositionsBurned` | Native BinaryModule and NegRiskModule identifiers have no preparation event. CombinatorialModule has its own operation-specific conversion events in addition to those summarized above, and Combo positions are not bridgeable. The Router also emits events for routed splits, merges, conversions, redemptions, and collateral returns. Store these events as call context if needed. Do not apply their amounts as additional ERC-1155 balance updates. CombinatorialModule emits operation-specific events for changes within a Combo, including splits, merges, conversions, extraction, injection, compression, and wrapping. Index the deployed module ABI when those changes must be reconstructed. ERC-1155 transfer events remain the canonical input for balances, minting, burning, and supply. Do not count a lifecycle event and its underlying transfer as two balance changes. ### Attribute Polymarket Protocol V2 Exchange Fills The Polymarket Protocol V2 Exchange emits `OrderFilled`, `OrdersMatched`, and `FeeCharged`. The signed order field is named `tokenId` and contains the Position ID selected during market discovery. `OrderFilled` includes the signed `builder` value and `metadata`. Record the exchange address or EIP-712 domain version `"3"` with each order. This keeps fills attributable to the correct position system when both systems use the same order shape. ### Track Polymarket Protocol V2 Resolution and Redemptions BinaryModule and NegRiskModule store result vectors in parts per million. The result denominator is `1,000,000`. `OracleAggregator` events describe reporter consensus and disputes. A `ConditionResolved` event from BinaryModule or NegRiskModule records the result that controls redemption. CombinatorialModule stores each Combo condition's BinaryModule and NegRiskModule legs, not a separate result vector. Determine a Combo position's payout from the stored legs and their underlying module results. CombinatorialModule does not emit `ConditionResolved`. For native Polymarket Protocol V2 negative risk events, not every result needs a separate stored value: * `RemainingConditionsDerivableAsNo` means the remaining real conditions can be derived as NO after a YES result reaches the full denominator. * `SyntheticConditionDerivableAsYes` means the synthetic Other condition can be derived as YES after every real condition resolves NO. An indexer that displays all outcomes must apply these derivation rules instead of waiting for one `ConditionResolved` event per derived result. Do not derive a sibling-NO result for a registered negative risk migration condition. Even if `RemainingConditionsDerivableAsNo` is emitted for its event, `NegRiskModule.getResult` excludes registered migration conditions from that derivation. Wait for each migrated real condition's stored CTF-backed result, recorded by `ConditionResolved` and `MigrationResolved`. The synthetic Other condition has no CTF mapping and remains derivable after all real conditions resolve NO. AutoRedeemer emits `Redemption` for an automated PositionManager redemption. The ledger also emits its normal redemption, burn, and transfer events. Use the AutoRedeemer event to attribute the automated action and the ledger events to update balances and supply. ### Track Migration from CTF Migration moves a registered CTF balance into the corresponding PositionManager balance. Index these events from BinaryModule and NegRiskModule: | Event | Meaning | | - | - | | `MigrationConditionRegistered` | Links a PositionManager Condition ID to its CTF condition ID | | `EventPrepared` with `legacyEventId` | Links a negative risk Event ID to its CTF event | | `PositionMigrated` | Records the holder, new Condition ID, Position ID, outcome index, and amount | | `MigrationResolved` | Records the CTF payouts and normalized module result | | `LegacyCollateralSettled` | Records collateral released by CTF redemption or complementary YES/NO merges | A migrated condition resolves from the registered CTF payout. A Polymarket Protocol V2 resolver cannot replace that result. A bridge report first derives the result from CTF and must match it. The synthetic Other condition in a negative risk event has no CTF mapping and is derived by NegRiskModule. Migration also emits CTF transfers and PositionManager mint events. Use the ERC-1155 events to update balances, then use `PositionMigrated` to connect the old and new identifiers. # Deposit Source: https://docs.polymarket.com/trading/bridge/deposit Bridge assets from any supported chain to fund your Polymarket account Polymarket uses **pUSD** (Polymarket USD) on Polygon as collateral for all trading. The Bridge API lets you deposit assets from Ethereum, Solana, Bitcoin, and other chains—they're automatically converted to pUSD on Polygon. ## How It Works 1. Request bridge addresses for your Polymarket wallet 2. Send assets to the appropriate address for your source chain 3. Assets are bridged and swapped to pUSD automatically 4. pUSD is credited to your wallet for trading ## Create Bridge Addresses Generate unique bridge addresses linked to your Polymarket wallet. See [Create bridge addresses](/api-reference/bridge/create-bridge-addresses) for the full request and response schemas. > [!TIP] > > **Builders: attach your code.** If you route user funds through this endpoint, > pass your builder code via the optional `X-Builder-Code` header (bytes32 hex; > `0x` + 64 hex chars). It lets our bridge provider attribute traffic to your > app, so stuck or delayed transfers can be traced and prioritized. The header > is optional. Requests without it still succeed but return a > `missing_builder_code` warning, and a malformed code returns `400`. Get your > code at [Settings → Builder](https://polymarket.com/settings?tab=builder). ```bash theme={null} curl -X POST https://bridge.polymarket.com/deposit \ -H "Content-Type: application/json" \ -H "X-Builder-Code: " \ -d '{"address": "0x56687bf447db6ffa42ffe2204a05edaa20f55839"}' ``` The response returns one bridge address per address type (`evm`, `svm`, `btc`, `tron`). Send from the matching source chain to the matching address. ### Address Types | Address | Use For | | - | - | | `evm` | Ethereum, Arbitrum, Base, Optimism, and other EVM chains | | `svm` | Solana | | `btc` | Bitcoin | | `tron` | Tron | > [!WARNING] > > Each address is unique to your wallet. Only send assets from supported chains > to the correct address type. ## Deposit Flow **1. Get Your Bridge Address** Call `POST /deposit` with your Polymarket wallet address to get bridge addresses. **2. Check Supported Assets** Verify your token is supported and meets the minimum deposit amount via `/supported-assets`. **3. Send Assets** Transfer tokens to the appropriate bridge address from your source chain. **4. Track Status** Monitor your deposit progress using `/status/{address}`. ## USDC vs pUSD You can deposit either USDC (native) or USDC.e (bridged) as the source asset to your Polymarket wallet. Either way, the incoming USDC or USDC.e is wrapped into pUSD via the Collateral Onramp, and pUSD is what you hold and trade with on Polymarket. ## Large Deposits For deposits over \$50,000 originating from a chain other than Polygon, we recommend using a third-party bridge to minimize slippage: * [DeBridge](https://app.debridge.finance/) * [Across](https://app.across.to/bridge) * [Portal](https://portalbridge.com/) Bridge directly to your Polymarket USDC (Polygon) bridge address. Polymarket is not affiliated with or responsible for any third-party bridge. ## Minimum Deposits Each asset has a minimum deposit amount. Deposits below the minimum will not be processed. Check `/supported-assets` for current minimums. ## Deposit Recovery If you deposited the wrong token, use this tool to recover your funds: [recovery.polymarket.com](https://recovery.polymarket.com/) > [!WARNING] > > Sending unsupported tokens may cause **irrecoverable loss**. Always verify > your token is listed in [Supported Assets](/trading/bridge/supported-assets) > before depositing. ## Next Steps > [card] [Supported Assets](/trading/bridge/supported-assets) > > See all supported chains and tokens with minimum amounts. > [card] [Check Status](/trading/bridge/status) > > Track your deposit progress through completion. # Quote Source: https://docs.polymarket.com/trading/bridge/quote Preview fees and estimated output for deposits and withdrawals Get an estimated quote before executing a deposit or withdrawal. Quotes include estimated output amounts, checkout time, and a detailed fee breakdown. ## Get a Quote ```bash theme={null} curl -X POST https://bridge.polymarket.com/quote \ -H "Content-Type: application/json" \ -d '{ "fromAmountBaseUnit": "10000000", "fromChainId": "137", "fromTokenAddress": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", "recipientAddress": "0x17eC161f126e82A8ba337f4022d574DBEaFef575", "toChainId": "137", "toTokenAddress": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB" }' ``` ### Request Parameters | Parameter | Type | Description | | - | - | - | | `fromAmountBaseUnit` | string | Amount to send in base units (e.g., `"10000000"` for 10 USDC) | | `fromChainId` | string | Source chain ID (e.g., `"137"` for Polygon) | | `fromTokenAddress` | string | Token contract address on the source chain | | `recipientAddress` | string | Destination wallet address to receive funds | | `toChainId` | string | Destination chain ID | | `toTokenAddress` | string | Token contract address on the destination chain | ### Response The quote response includes an estimated output amount, a fee breakdown, and a `quoteId` you can log for your own records. To track the transfer itself once it's underway, poll [`/status`](/trading/bridge/status) with your bridge address. ```json theme={null} { "estCheckoutTimeMs": 45000, "estInputUsd": 10, "estOutputUsd": 9.94, "estToTokenBaseUnit": "9940000", "quoteId": "0x00c34ba467184b0146406d62b0e60aaa24ed52460bd456222b6155a0d9de0ad5", "estFeeBreakdown": { "gasUsd": 0.02, "appFeeLabel": "Bridge fee", "appFeePercent": 0.3, "appFeeUsd": 0.03, "fillCostPercent": 0.1, "fillCostUsd": 0.01, "maxSlippage": 0.5, "minReceived": 9.89, "swapImpact": 0.05, "swapImpactUsd": 0.005, "totalImpact": 0.6, "totalImpactUsd": 0.06 } } ``` | Field | Type | Description | | - | - | - | | `estCheckoutTimeMs` | number | Estimated checkout time in milliseconds | | `estInputUsd` | number | Estimated input value in USD | | `estOutputUsd` | number | Estimated output value in USD | | `estToTokenBaseUnit` | string | Estimated output amount in base units | | `quoteId` | string | Unique identifier for this quote | | `estFeeBreakdown` | object | Detailed fee breakdown (see below) | ### Fee Breakdown The `estFeeBreakdown` object contains: **gasUsd** `number` Gas fee in USD **appFeeLabel** `string` Label of the app fee **appFeePercent** `number` App fee as a percentage of the total amount **appFeeUsd** `number` App fee in USD **fillCostPercent** `number` Fill cost as a percentage of the total amount **fillCostUsd** `number` Fill cost in USD **maxSlippage** `number` Maximum potential slippage as a percentage **minReceived** `number` Minimum amount received after slippage **swapImpact** `number` Swap impact as a percentage of the total amount **swapImpactUsd** `number` Swap impact in USD **totalImpact** `number` Total impact as a percentage of the total amount **totalImpactUsd** `number` Total impact cost in USD > [!NOTE] > > Quotes are estimates. Actual amounts may vary slightly due to market > conditions. ## Next Steps > [card] [Create Deposit](/trading/bridge/deposit) > > Execute a deposit to Polymarket. > [card] [Withdraw](/trading/bridge/withdraw) > > Withdraw from Polymarket to another chain. # Transaction Status Source: https://docs.polymarket.com/trading/bridge/status Track bridge deposits and withdrawals through completion After sending assets to a bridge address, use the status endpoint to follow the transfer until the funds land. The same request covers deposits and withdrawals: you always query the bridge address that received the funds, not the wallet on either end. ## Check Status Request the transactions for a bridge address. ```bash theme={null} curl --get https://bridge.polymarket.com/status/0x23566f8b2E82aDfCf01846E54899d110e97AC053 \ --data-urlencode 'limit=50' ``` > [!NOTE] > > Use the bridge address from the `/deposit` or `/withdraw` response (EVM, SVM, > Tron, or BTC), not your Polymarket wallet address. ```json theme={null} { "transactions": [ { "fromChainId": "1", "fromTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "fromAmountBaseUnit": "1000000000", "toChainId": "137", "toTokenAddress": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", "status": "COMPLETED", "txHash": "0xabc123…", "createdTimeMs": 1697875200000 } ], "nextCursor": "eyJsYXN0SWQiOiI0MiJ9" } ``` | Field | Description | | - | - | | `transactions` | One page of transactions, newest first | | `nextCursor` | Token for the next page, or `null` when there is nothing older to read | | `fromChainId` | Source chain ID | | `fromTokenAddress` | Token sent | | `fromAmountBaseUnit` | Amount in base units | | `toChainId` | Destination chain ID (137 for Polygon on deposits) | | `toTokenAddress` | Token received | | `status` | Current status (see table below) | | `txHash` | Destination transaction hash (only when `COMPLETED`) | | `createdTimeMs` | Unix timestamp in milliseconds (only present once the transaction has started processing) | If no transfers have been detected at the address yet, `transactions` comes back empty. ## Transaction Statuses Each transfer progresses through these statuses: | Status | Terminal | Description | | - | - | - | | `DEPOSIT_DETECTED` | No | Funds detected on source chain, not yet processing | | `PROCESSING` | No | Transaction is being routed and swapped | | `ORIGIN_TX_CONFIRMED` | No | Source chain transaction confirmed | | `SUBMITTED` | No | Submitted to the destination chain | | `COMPLETED` | Yes | Funds arrived — transaction successful | | `FAILED` | Yes | Transaction encountered an error | > [!NOTE] > > If a bridge transaction fails, remains stuck, or funds are held due to a > compliance check, direct users to [our Bridge API provider's > support](https://intercom.help/funxyz/en/articles/10732578-contact-us) to > resolve the issue. > [!TIP] > > Transfers typically complete within a few minutes, but may take longer > depending on network conditions. Poll every 10-30 seconds until `COMPLETED` or > `FAILED`. ## Read Older Transactions Transactions come back newest first, so a request without a cursor always returns the most recent activity. That first page is all you need to track a transfer you just initiated. ### Query Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | `50` | Transactions per page, from `1` to `100` | | `cursor` | string | None | Continuation token from the previous response's `nextCursor`. Omit it to request the first page. | | `paginate` | string | None | Compatibility parameter for existing integrations. Send `paginate=true` or omit it; pagination applies either way. | To read further back, replay the cursor exactly as you received it and repeat until `nextCursor` is `null`: ```bash theme={null} curl --get https://bridge.polymarket.com/status/0x23566f8b2E82aDfCf01846E54899d110e97AC053 \ --data-urlencode 'limit=100' \ --data-urlencode 'cursor=eyJsYXN0SWQiOiI0MiJ9' ``` Cursors are opaque. Never decode, edit, or build one yourself, never reuse a cursor against a different address, and always URL-encode it — a cursor can contain `+`, `/`, or `=`. A rejected cursor returns `400 {"error": "invalid request"}`; restart the walk without one. > [!WARNING] > > Stop only when `nextCursor` is `null`. A page can be empty, or shorter than > the `limit` you asked for, and still be followed by more pages. ## Next Steps > [card] [Create Deposit](/trading/bridge/deposit) > > Generate bridge addresses for your wallet. > [card] [Supported Assets](/trading/bridge/supported-assets) > > Check supported chains and minimum amounts. # Supported Assets Source: https://docs.polymarket.com/trading/bridge/supported-assets Chains and tokens supported for deposits to Polymarket The Bridge API supports deposits from multiple chains and tokens. All deposits are automatically converted to **pUSD on Polygon**, which is used as collateral for trading on Polymarket. ## Get Supported Assets Retrieve the full list of supported chains and tokens with their minimum deposit amounts. ```bash theme={null} curl https://bridge.polymarket.com/supported-assets ``` ```json theme={null} { "supportedAssets": [ { "chainId": "137", "chainName": "Polygon", "token": { "name": "USD Coin", "symbol": "USDC", "address": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", "decimals": 6 }, "minCheckoutUsd": 2 } ] } ``` ## Supported Chains The bridge supports deposits from these blockchain networks: | Chain | Address Type | Min Deposit | Example Tokens | | - | - | - | - | | Ethereum | EVM | \$7 | ETH, USDC, USDT, WBTC, DAI, LINK, UNI, AAVE | | Polygon | EVM | \$2 | POL, USDC, USDT, DAI, WETH, SAND | | Arbitrum | EVM | \$2 | ETH, ARB, USDC, USDT, DAI, WBTC, USDe | | Base | EVM | \$2 | ETH, USDC, USDT, DAI, cbBTC, AERO, USDS | | Optimism | EVM | \$2 | ETH, OP, USDC, USDT, DAI, USDe | | BNB Smart Chain | EVM | \$2 | BNB, USDC, USDT, DAI, ETH, BTCB, BUSD | | Solana | SVM | \$2 | SOL, USDC, USDT, USDe, TRUMP | | Bitcoin | BTC | \$9 | BTC | | Tron | Tron | \$9 | USDT | | HyperEVM | EVM | \$2 | HYPE, USDC, USDe, stHYPE, UBTC, UETH | | Abstract | EVM | \$2 | ETH, USDC, USDT | | Monad | EVM | \$2 | MON, USDC, USDT | | Ethereal | EVM | \$2 | USDe, WUSDe | | Katana | EVM | \$2 | AUSD | | Lighter | EVM | \$2 | USDC | > [!NOTE] > > Supported assets change over time. Always call `/supported-assets` for the > current list before initiating a deposit. ## Minimum Amounts Each asset has a `minCheckoutUsd` value, the minimum deposit amount in USD equivalent. Deposits below this threshold may fail to process, so check it before you tell a user how much to send. Most L2 chains (Polygon, Arbitrum, Base, Optimism) have low minimums of \$2, while Ethereum deposits require \$7 minimum. Bitcoin and Tron have \$9 minimums due to higher bridging costs. ## Next Steps > [card] [Create Deposit](/trading/bridge/deposit) > > Generate bridge addresses for your wallet. > [card] [Check Status](/trading/bridge/status) > > Track your deposit progress. # Withdraw Source: https://docs.polymarket.com/trading/bridge/withdraw Bridge pUSD from Polymarket to any supported chain Withdraw pUSD from your Polymarket wallet to any supported chain and token. Funds are automatically bridged and swapped to your desired token on the destination chain. ## How It Works 1. Specify your destination chain, token, and recipient address 2. Receive bridge addresses for each destination chain (EVM, Solana, Bitcoin) 3. Send pUSD from your Polymarket wallet to the appropriate bridge address 4. Funds are automatically bridged and swapped to your desired token 5. Funds arrive at your destination wallet > [!WARNING] > > Do not pre-generate withdrawal addresses. Only generate them when you are > ready to execute the withdrawal. Each address is configured for a specific > destination. > [!WARNING] > > When withdrawing, pUSD is unwrapped to USDC via the Collateral Offramp and > swapped through the [Uniswap v3 > pool](https://polygonscan.com/address/0xd36ec33c8bed5a9f7b6630855f1533455b98a418) > for USDC (native). The UI enforces less than 10bp difference in output amount. > At times, this pool may be exhausted. If you are having withdraw issues, try > breaking your withdraw into smaller amounts or waiting for the pool to be > rebalanced. Alternatively, you can withdraw pUSD directly, which does not > require Uniswap liquidity — just be aware that some exchanges no longer accept > pUSD deposits directly. > [!TIP] > > For very large withdrawals (over \$50,000), consider breaking the withdrawal > into smaller amounts or using a third-party bridge to minimize slippage. ## Create Withdrawal Addresses Generate bridge addresses configured for your withdrawal destination. See [Create withdrawal addresses](/api-reference/bridge/create-withdrawal-addresses) for the full request and response schemas. > [!TIP] > > **Builders: attach your code.** If you route user funds through this endpoint, > pass your builder code via the optional `X-Builder-Code` header (bytes32 hex; > `0x` + 64 hex chars). It lets our bridge provider attribute traffic to your > app, so stuck or delayed transfers can be traced and prioritized. The header > is optional. Requests without it still succeed but return a > `missing_builder_code` warning, and a malformed code returns `400`. Get your > code at [Settings → Builder](https://polymarket.com/settings?tab=builder). Tell the bridge where you're sending funds, including the destination chain, the destination token, and the recipient wallet, and it hands back one address per address type. ```bash theme={null} curl -X POST https://bridge.polymarket.com/withdraw \ -H "Content-Type: application/json" \ -H "X-Builder-Code: " \ -d '{ "address": "0x9156dd10bea4c8d7e2d591b633d1694b1d764756", "toChainId": "1", "toTokenAddress": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "recipientAddr": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }' ``` ```json theme={null} { "address": { "evm": "0x23566f8b2E82aDfCf01846E54899d110e97AC053", "svm": "CrvTBvzryYxBHbWu2TiQpcqD5M7Le7iBKzVmEj3f36Jb", "btc": "bc1q8eau83qffxcj8ht4hsjdza3lha9r3egfqysj3g" }, "note": "Send funds to these addresses to bridge to your destination chain and token." } ``` Your Polymarket wallet lives on Polygon, so you always send pUSD to the `evm` address. The response also carries bridge addresses for the other chain families because withdrawals and deposits share the same response format. Ignore those addresses when withdrawing. ### Address Types | Address | Use For | | - | - | | `evm` | Ethereum, Arbitrum, Base, Optimism, and other EVM chains | | `svm` | Solana | | `btc` | Bitcoin | | `tron` | Tron | Withdrawals are **instant** and **free** — Polymarket does not charge withdrawal fees. ## Withdrawal Flow **1. Check Supported Assets** Verify your destination chain and token are supported via `/supported-assets`. **2. Get a Quote** Preview fees and estimated output via `POST /quote`. **3. Create Withdrawal Addresses** Call `POST /withdraw` with your wallet address, destination chain, token, and recipient. **4. Send pUSD** Transfer pUSD from your Polymarket wallet to the appropriate bridge address. **5. Track Status** Monitor progress using `/status/{address}`. ## Next Steps > [card] [Get a Quote](/trading/bridge/quote) > > Preview fees and estimated output before withdrawing. > [card] [Check Status](/trading/bridge/status) > > Track your withdrawal progress. # Combos for Builders Source: https://docs.polymarket.com/trading/combos/builders Request and execute Combo quotes for users through the Builder Gateway Approved builders can request executable Combo quotes and accept them for their users. The Builder Gateway runs a quote competition, returns the best available quote, and tracks the accepted trade through onchain execution. You need the builder credentials provided during onboarding, plus authenticated access to the trading account. If you are not registered, [register as a builder](https://builders.polymarket.com/) before continuing. This guide starts with the custodial model, where the builder controls and signs for one omnibus trading account. If each user signs for their own wallet, follow the [non-custodial guide](#non-custodial-integration) at the end of this page. > [!WARNING] > > Keep the Builder API secret on trusted infrastructure. Never expose it in a > browser or other untrusted client. ## Custodial Integration In the custodial model, the builder holds Combo positions for users in one omnibus Deposit Wallet and controls the account signer. The same account and builder identity must request and accept each quote. ### Request and Execute a Quote Choose 2–50 unique, mutually compatible underlying market position IDs as the legs. These are outcome position IDs from [Combo-enabled markets](/trading/combos/market-makers#get-combo-markets), not CLOB token IDs or the derived Combo position IDs. Contradictory legs cannot form a Combo. A BUY request sets the maximum collateral budget, including fees. A SELL request specifies the number of Combo shares to sell. > [tab] TypeScript > > Use `requestComboQuote()` on a TypeScript `SecureClient` to request, accept, and > track a Combo quote. > > Don't have the TypeScript SDK installed? Start with the > [TypeScript SDK guide's wallet integrations](/getting-started/typescript#wallet-integrations), > then come back. > > **1. Create a Custodial Client** > > Configure a `SecureClient` with the wallet signer, Deposit Wallet address, and > Builder API Key. This server-side example keeps the account key and builder > secret on trusted infrastructure. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY!), > wallet: process.env.POLYMARKET_DEPOSIT_WALLET!, > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > **2. Request a Quote** > > Call `requestComboQuote()` with the leg position IDs and a human-readable > collateral amount. Amounts and sizes must be positive and have at most six > decimal places. Combo quote requests currently target the YES side, which the > SDK supplies by default. The method resolves when the quote competition closes. > > ```ts theme={null} > import { OrderSide } from "@polymarket/client"; > > const result = await client.requestComboQuote({ > legPositionIds: ["", ""], > direction: OrderSide.BUY, > amount: "10", > }); > > // result: RequestComboQuoteResult > ``` > > If no usable quote is available, `result.quote` is `null` and `result.reason` > explains the outcome. A winning quote includes its acceptance deadline in > `result.quote.expiresAt`, as a Unix timestamp in milliseconds. Use that value > rather than assuming a fixed acceptance window. > > For a SELL quote, pass `direction: OrderSide.SELL` with a human-readable `size` > instead of `amount`. The returned `quote.netReceive` is the exact collateral > proceeds after fees. > > **3. Accept and Track the Quote** > > Pass the returned quote to `acceptComboQuote()` immediately. After it enters > execution, call `waitForComboFill()` to wait for a terminal result. > > ```ts theme={null} > import { RfqStatus } from "@polymarket/client"; > > async function acceptAndTrackQuote() { > if (result.quote === null) { > console.log(`No quote available: ${result.reason}`); > return; > } > > const acceptance = await client.acceptComboQuote(result.quote); > > if (acceptance.status === "failed") { > console.log(`Quote not accepted: ${acceptance.reason}`); > return; > } > > const fill = await client.waitForComboFill({ > rfqId: acceptance.rfqId, > timeoutMs: 120_000, > }); > > if (fill.status === RfqStatus.Filled) { > console.log(`Filled: ${fill.txHash}`); > return; > } > > console.log(`Execution ended with ${fill.status}`); > } > > await acceptAndTrackQuote(); > ``` > > An acceptance with `status: "executing"` is not yet a confirmed fill. A maker > decline, expired window, or execution failure is returned as a business outcome. > A local timeout does not mean the trade failed. > [tab] Python > > Use `request_combo_quote()` on `AsyncSecureClient` to request, accept, and track > a Combo quote. The synchronous `SecureClient` exposes the same methods. > > Don't have the Python SDK installed? Start with the > [Python SDK guide](/getting-started/python), then come back. > > **1. Configure Custodial Credentials** > > Load the Builder API Key on trusted infrastructure. The workflow below uses a > server-side account key and Deposit Wallet address. > > ```python theme={null} > import os > > from polymarket import BuilderApiKey > > > builder_api_key = BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ) > ``` > > **2. Request, Accept, and Track the Quote** > > Call `request_combo_quote()` with the leg position IDs and a human-readable > collateral amount. Amounts and sizes must be positive and have at most six > decimal places. Combo quote requests currently target the YES side, which the > SDK supplies by default. The method resolves when the quote competition closes. > > ```python theme={null} > from decimal import Decimal > > from polymarket import AsyncSecureClient, RfqStatus, TimeoutError > > > async with await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_DEPOSIT_WALLET"], > api_key=builder_api_key, > ) as client: > result = await client.request_combo_quote( > leg_position_ids=["", ""], > direction="BUY", > amount=Decimal("10"), > ) > > if result.quote is None: > print(f"No quote available: {result.reason}") > else: > try: > acceptance = await client.accept_combo_quote(result.quote) > > if acceptance.status == "failed": > print(f"Quote not accepted: {acceptance.reason}") > else: > fill = await client.wait_for_combo_fill( > rfq_id=acceptance.rfq_id, > timeout=120.0, > ) > > if fill.status is RfqStatus.FILLED: > print(f"Filled: {fill.tx_hash}") > else: > print(f"Execution ended with {fill.status}") > except TimeoutError: > status = await client.fetch_rfq_status(rfq_id=result.rfq_id) > print(f"Current status: {status.status}") > ``` > > If no usable quote is available, `result.quote` is `None` and `result.reason` > explains the outcome. A winning quote includes its acceptance deadline in > `result.quote.expires_at`, as a Unix timestamp in milliseconds. Use that value > rather than assuming a fixed acceptance window. > > For a SELL quote, pass `direction="SELL"` with a human-readable `size` instead > of `amount`. The returned `quote.net_receive` is the exact collateral proceeds > after fees. > > An acceptance with `status == "executing"` is not yet a confirmed fill. A maker > decline, expired window, or execution failure is returned as a business outcome. > A local timeout does not mean the trade failed. The context manager closes the > client after the workflow, including after an exception. > [tab] API > > The Direct API gives custodial server-side integrations lower-level control over > request signing and order construction. The gateway host is provided during > builder onboarding, and its base path is `/v1/builder/rfq`. > > **1. Sign Request Headers** > > Create and accept requests require both account and builder authentication. > Status requests require account authentication only. > > | Request | Account headers | Builder headers | > | - | - | - | > | `POST /requests` | Required | Required | > | `POST /requests/{rfq_id}/accept` | Required | Required | > | `GET /requests/{rfq_id}` after acceptance | Required | Do not send | > > The account header set is `POLY_ADDRESS`, `POLY_API_KEY`, `POLY_PASSPHRASE`, > `POLY_TIMESTAMP`, and `POLY_SIGNATURE`. The builder header set is > `POLY_BUILDER_API_KEY`, `POLY_BUILDER_PASSPHRASE`, > `POLY_BUILDER_TIMESTAMP`, and `POLY_BUILDER_SIGNATURE`. > > `POLY_ADDRESS` is the EOA that owns the omnibus account credentials. Both > `signer_address` and `maker_address` are the builder-controlled Deposit Wallet > address. > > Compute each signature with HMAC-SHA256, using the base64-decoded secret as the > key. Sign an uppercase method, a Unix timestamp in seconds, the full request path > such as `/v1/builder/rfq/requests` without the host or query string, and the exact > serialized body sent on the wire. Omit the body for `GET` requests. Encode the > digest as base64url with padding preserved. > > ```text theme={null} > HMAC-SHA256( > base64Decode(secret), > timestamp + HTTP_METHOD + FULL_REQUEST_PATH + REQUEST_BODY > ) > ``` > > **2. Create the RFQ** > > Create a BUY RFQ with a collateral budget in 6-decimal base units. The gateway > holds the request until the quote competition finishes. > > ```http theme={null} > POST /v1/builder/rfq/requests > Content-Type: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > POLY_BUILDER_API_KEY: > POLY_BUILDER_PASSPHRASE: > POLY_BUILDER_TIMESTAMP: > POLY_BUILDER_SIGNATURE: > > { > "signer_address": "", > "maker_address": "", > "signature_type": 3, > "leg_position_ids": ["", ""], > "direction": "BUY", > "side": "YES", > "requested_size": { > "unit": "notional", > "value_e6": "1000000" > } > } > ``` > > Use `unit: "notional"` for BUY requests and `unit: "shares"` for SELL > requests. The `value_e6` value is a string in 6-decimal base units. `side` must > currently be `"YES"`. > > An executable response includes the RFQ, the winning quote, and an acceptance > deadline: > > > [accordion] Create RFQ Response > > > > ```json theme={null} > > { > > "rfq_id": "", > > "status": "AWAITING_REQUESTER_ACCEPTANCE", > > "expires_at": 1773890765500, > > "builder_code": "", > > "request": { > > "rfq_id": "", > > "maker_address": "", > > "requestor_public_id": "", > > "leg_position_ids": ["", ""], > > "condition_id": "", > > "yes_position_id": "", > > "no_position_id": "", > > "direction": "BUY", > > "side": "YES", > > "requested_size": { > > "unit": "notional", > > "value_e6": "1000000" > > }, > > "created_at": 1773890758000 > > }, > > "quote": { > > "quote_id": "", > > "blended_price_e6": "500000", > > "maker_amount_e6": "966191", > > "taker_amount_e6": "1932381", > > "total_required_e6": "1000000", > > "net_receive_e6": "1932381" > > } > > } > > ``` > > A terminal result such as no quotes returns HTTP `200` with `status: "FAILED"` > and an `error` object. `expires_at` and `request.created_at` are Unix timestamps > in milliseconds. Construct and submit the signed order before `expires_at`; do > not assume a fixed acceptance window. `total_required_e6` is the exact requester > balance required: collateral including fees for BUY, or Combo shares for SELL. > For BUY quotes, `net_receive_e6` is the number of Combo shares received. For SELL > quotes, it is the exact collateral proceeds after fees; use it instead of > deriving proceeds from the blended price. > > A request whose legs cannot be combined fails with HTTP `400` and code > `CONTRADICTORY_LEGS`. The `conflict` object names the conflicting legs by > decimal position ID, so you can show users which legs to change. > `conflicts_with` is the leg that completes the conflict in request order, and > `legs` are the earlier legs it conflicts with. If a request has several > conflicts, only one is returned. > > ```json theme={null} > { > "error": "invalid rfq: contradictory legs", > "code": "CONTRADICTORY_LEGS", > "conflict": { > "legs": [""], > "conflicts_with": [""] > } > } > ``` > > **3. Accept the Quote** > > Build an Exchange v3 requester order from the returned RFQ and quote, sign it > for the authenticated wallet type, then submit it with both authentication > sets. Use Polygon chain ID `137` and Exchange v3 contract > `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` for the EIP-712 domain. > > Deposit Wallets use `signatureType: 3` and an ERC-7739-wrapped signature. See > [Authorize the Quote](/trading/combos/market-makers#authorize-the-quote) for the > Exchange v3 order types and wallet-specific signing paths. > > ```http theme={null} > POST /v1/builder/rfq/requests//accept > Content-Type: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > POLY_BUILDER_API_KEY: > POLY_BUILDER_PASSPHRASE: > POLY_BUILDER_TIMESTAMP: > POLY_BUILDER_SIGNATURE: > > { > "quote_id": "", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "966191", > "takerAmount": "1932381", > "side": 0, > "signatureType": 3, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "", > "signature": "" > } > } > ``` > > For both directions, copy `maker_amount_e6` to `makerAmount` and > `taker_amount_e6` to `takerAmount`, and use the returned Combo YES position ID > as `tokenId`. Set `side` to `0` for BUY or `1` for SELL. The order's `builder` > must equal the returned `builder_code`. > > The response contains the latest known state. If last look is still pending, > the gateway waits for an update for up to one second before returning. If the > response still has `status: "AWAITING_MAKER_CONFIRMATION"`, fetch status until > the maker responds. > > > [accordion] Accept Quote Response > > > > ```json theme={null} > > { > > "rfq_id": "", > > "status": "EXECUTING", > > "taker_order_hash": "" > > } > > ``` > > The `taker_order_hash` is the EIP-712 hash of the requester order. A maker > decline or execution failure still returns HTTP `200`, with `status: "FAILED"` > and a nested `error` object. Retrying the same authenticated acceptance does not > execute twice; its response may omit `taker_order_hash`. Use `rfq_id` as the > stable recovery identifier. > > **4. Fetch Status** > > After acceptance, fetch durable status with account headers only. > > ```http theme={null} > GET /v1/builder/rfq/requests/ > Accept: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > ``` > > > [accordion] Status Response > > > > ```json theme={null} > > { > > "rfq_id": "", > > "status": "CONFIRMED", > > "tx_hash": "" > > } > > ``` > > Status reads before acceptance return HTTP `409`. The status response contains > one top-level `status` plus an optional `tx_hash` or `error`; it does not repeat > the request or quote. Status can progress through > `AWAITING_MAKER_CONFIRMATION`, `EXECUTING`, `MINED`, and `RETRYING` before > reaching a successful `CONFIRMED` or `FILLED` state. `FAILED`, `EXPIRED`, and > `CANCELED` are terminal states without a fill. ## Non-Custodial Integration In the non-custodial model, each user controls the account signer for their own Deposit Wallet, while the builder provides integration authorization from trusted infrastructure. > [tab] TypeScript > > Use `remoteBuilderSigning()` with a TypeScript `SecureClient` so the connected > wallet authorizes account actions while your server keeps the Builder API secret. > > Start with a connected Viem `WalletClient` and the user's Deposit Wallet > address. See the [TypeScript wallet integrations](/getting-started/typescript#wallet-integrations) > if you have not configured the account signer yet. > > ### Set Up Remote Builder Signing > > Combo quote requests require authenticated account access. Create a > `SecureClient` with `remoteBuilderSigning()` so the user's signer and the > builder's signing service authorize their parts of the request separately. > > ```typescript client.ts theme={null} > import { createSecureClient, remoteBuilderSigning } from "@polymarket/client"; > import { signerFrom } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: signerFrom(walletClient), > wallet: depositWalletAddress, > apiKey: remoteBuilderSigning({ > url: "/api/builder/sign", > }), > }); > ``` > > ```typescript server.ts theme={null} > import { buildHmacSignature } from "@polymarket/client"; > > // Handler for POST /api/builder/sign > export async function handleSignRequest(request: Request): Promise { > const { body, method, path } = await request.json(); > const timestamp = Math.floor(Date.now() / 1000); > const signature = await buildHmacSignature( > process.env.POLYMARKET_BUILDER_SECRET!, > timestamp, > method, > path, > body, > ); > > return Response.json({ > POLY_BUILDER_API_KEY: process.env.POLYMARKET_BUILDER_API_KEY!, > POLY_BUILDER_PASSPHRASE: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > POLY_BUILDER_SIGNATURE: signature, > POLY_BUILDER_TIMESTAMP: `${timestamp}`, > }); > } > ``` > > Here, `walletClient` is the connected Viem `WalletClient` and > `depositWalletAddress` is that user's Deposit Wallet. Authenticate calls to > `/api/builder/sign` with your application session. For cookie authentication, > pass `credentials: "include"` when the signing API is cross-origin. For bearer > authentication, pass the token through the `headers` option on > `remoteBuilderSigning()`. > > Use a Deposit Wallet already associated with the user. To provision a new > account first, follow [Create New Accounts](/trading/wallets-auth#create-new-accounts). > > The signing response gives the browser the Builder key identifier, passphrase, > timestamp, and a signature scoped to that request. The Builder secret never > leaves the signing server. > > > [!WARNING] > > > > Do not sign arbitrary request details from the browser. Bind the application > > session to the expected user and Deposit Wallet, allow only the required > > method and path combinations, and validate account identities in request > > bodies. Protect cookie-backed endpoints from CSRF and rate-limit signing > > requests. Client setup can request signatures for CLOB authentication and > > Deposit Wallet checks before the Combo create and accept requests, so include > > those setup operations in your allowlist. If you parse a body to validate it, > > still sign the original raw `body` string without reserializing it. > > ### Request and Execute a User-Authorized Quote > > Use the same Combo requester methods as the custodial TypeScript flow. The > account identity now comes from the user's signer and Deposit Wallet, while > Builder authentication comes from your signing API. > > ```ts theme={null} > import { OrderSide, RfqStatus } from "@polymarket/client"; > > async function requestAndTrackQuote() { > const result = await client.requestComboQuote({ > legPositionIds: ["", ""], > direction: OrderSide.BUY, > amount: "10", > }); > > if (result.quote === null) { > console.log(`No quote available: ${result.reason}`); > return; > } > > const acceptance = await client.acceptComboQuote(result.quote); > > if (acceptance.status === "failed") { > console.log(`Quote not accepted: ${acceptance.reason}`); > return; > } > > const fill = await client.waitForComboFill({ > rfqId: acceptance.rfqId, > timeoutMs: 120_000, > }); > > if (fill.status === RfqStatus.Filled) { > console.log(`Filled: ${fill.txHash}`); > return; > } > > console.log(`Execution ended with ${fill.status}`); > } > > await requestAndTrackQuote(); > ``` > > The user must approve the requester order before the quote expires. Preserve the > returned quote and retry acceptance before `result.quote.expiresAt` if wallet or > remote signing fails. Keep the RFQ ID to recover status after an interrupted > Gateway response or local timeout. ## Handle Outcomes and Errors Custodial and non-custodial accounts share the same quote and execution outcomes. The account model changes who authorizes the trade, not how the RFQ progresses. Keep the RFQ ID until the request reaches a terminal state. | Case | What happened | What to do | | - | - | - | | No executable quote | The competition ended without a usable quote. | Treat it as a normal market outcome. Retry later or adjust the requested size. | | Acceptance failed | The maker declined, the deadline passed, or execution could not start. | Request a fresh quote. Do not reuse an expired quote. | | Local wait timed out | Your client stopped waiting before a durable outcome was available. | Fetch the RFQ status and continue until it reaches a terminal state. | | Execution ended without a fill | The RFQ failed, expired, or was canceled. | Inspect the returned error before deciding whether to request another quote. | | Filled | The trade was confirmed onchain. | Record the transaction hash and reconcile the trade and resulting positions. | | Request failed | Authentication, validation, rate limiting, transport, or a dependency failed. | Correct the reported cause; retry only when the request is safe to repeat. | No executable quote, failed acceptance, and terminal execution failure are business outcomes. They can be returned successfully by the service and should not be treated as transport failures. ### Check Each Case > [tab] TypeScript > > Use `requestComboQuote()` and its follow-up methods on `SecureClient` to detect > each case. Use the original RFQ ID when a local wait times out. > > | Case | How to detect or recover | > | - | - | > | No executable quote | `result.quote === null`; inspect `result.reason`. | > | Acceptance failed | `acceptance.status === "failed"`; inspect `acceptance.reason`. | > | Local wait timed out | Catch `TimeoutError`, then use the standalone `fetchRfqStatus()` action with `result.rfqId`. | > | Execution ended without a fill | `fill.status` is `RfqStatus.Failed`, `RfqStatus.Expired`, or `RfqStatus.Canceled`. | > | Filled | `fill.status === RfqStatus.Filled`; the transaction hash is `fill.txHash`. | > | Request failed | The SDK throws a typed request, input, authentication, rate-limit, transport, or response error. | > | Remote signing failed | `SigningError` is thrown. This applies only when the non-custodial flow uses `remoteBuilderSigning()`. | > > If remote signing fails while accepting a quote, preserve `result.quote` and > retry acceptance before `result.quote.expiresAt`. The acceptance may not have > reached the Builder Gateway, so do not assume that a status read can recover it. > [tab] Python > > Use `request_combo_quote()` and its follow-up methods on `AsyncSecureClient` or > `SecureClient` to detect each case. Use the original RFQ ID when a local wait > times out. > > | Case | How to detect or recover | > | - | - | > | No executable quote | `result.quote is None`; inspect `result.reason`. | > | Acceptance failed | `acceptance.status == "failed"`; inspect `acceptance.reason`. | > | Local wait timed out | Catch `TimeoutError`, then call `await client.fetch_rfq_status(rfq_id=result.rfq_id)`. | > | Execution ended without a fill | `fill.status` is `RfqStatus.FAILED`, `RfqStatus.EXPIRED`, or `RfqStatus.CANCELED`. | > | Filled | `fill.status is RfqStatus.FILLED`; the transaction hash is `fill.tx_hash`. | > | Request failed | The SDK raises a typed request, input, authentication, rate-limit, transport, or response error. | > [tab] API > > Inspect the response `status` and `error` fields after each Direct API request. > Do not use the HTTP status alone to decide whether the trade filled. > > | Case | How to detect or recover | > | - | - | > | No executable quote | HTTP `200` with `status: "FAILED"` and a nested `error`. | > | Acceptance failed | HTTP `200` with `status: "FAILED"`, or HTTP `409` if the acceptance window expired. Request a fresh quote. | > | Status polling was interrupted | Repeat `GET /v1/builder/rfq/requests/{rfq_id}` with account authentication after acceptance is recorded. | > | Execution ended without a fill | `status` is `FAILED`, `EXPIRED`, or `CANCELED`. | > | Filled | `status` is `CONFIRMED` or `FILLED`; the transaction hash is `tx_hash`. | > | Request failed | A non-2xx response contains a stable `code` and a human-readable top-level `error`; a transport failure has no response. | > > If a create request is interrupted, do not assume that an RFQ was created. If > an acceptance request is interrupted, safely retry the same authenticated > acceptance before the quote expires. Once acceptance is recorded, use the RFQ > ID for status polling. > > For requests rejected before an RFQ outcome, use the HTTP status to identify > the failure category: > > | HTTP status | Meaning | > | - | - | > | `400` | Invalid JSON, RFQ body, acceptance, or signed order | > | `401` | Missing or invalid account or builder authentication | > | `403` | Account authorization failed, or the builder key has no enabled builder code | > | `404` | Unknown RFQ | > | `409` | RFQ state conflict, expired acceptance window, quote mismatch, or status read before acceptance | > | `429` | RFQ request rate limit | > | `503` | A required RFQ dependency is unavailable | ## Next Steps > [card] [Collateral Return](/trading/combos/collateral-return) > > Release pUSD from compatible Combo positions before resolution. > [card] [Discover Combo Markets](/trading/combos/market-makers#get-combo-markets) > > Find eligible markets and their leg position IDs. # Collateral Return Source: https://docs.polymarket.com/trading/combos/collateral-return Release pUSD from compatible Combo positions before resolution Quoting Combos can be capital-intensive because pUSD may remain locked across related positions until every underlying market resolves. Collateral return identifies capital that no longer needs to remain locked and returns it as pUSD, making it available for new quotes while preserving any unmatched exposure. ## How Collateral Return Works Collateral return finds compatible Combo positions that offset one another. It decomposes those positions, merges complementary exposure back into pUSD, and leaves the remaining exposure in residual positions. For example, let `Y(A)` and `N(A)` represent the YES and NO positions for market `A`, and let `A ^ B ^ C` represent a three-leg Combo. Suppose the wallet holds: ```text theme={null} N(A ^ B ^ C) N(N(A) ^ B ^ C) ``` The first leg of each Combo can be decomposed: ```text theme={null} N(A) + Y(A ^ N(B ^ C)) Y(A) + Y(N(A) ^ N(B ^ C)) ``` `Y(A)` and `N(A)` are complementary, so they merge into 1 pUSD per matched share. The two `Y(…)` positions remain in the wallet, preserving its unmatched exposure to the other legs. ## Return Collateral The workflow is plan-based: inspect the proposed position changes, execute that exact plan, wait for confirmation, and request another plan when more work remains. You need a Relayer API key. See [Connect Your Account](/trading/wallets-auth#connect-your-account) to create one before continuing. > [tab] TypeScript > > Given a `SecureClient` configured with a Relayer API key, ensure the wallet has > the required trading approvals: > > ```ts theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.SIGNER_PRIVATE_KEY), > apiKey: relayerApiKey({ > key: process.env.RELAYER_API_KEY!, > address: process.env.RELAYER_API_KEY_ADDRESS!, > }), > }); > > await client.setupTradingApprovals(); > ``` > > > [!NOTE] > > > > Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet > > accounts. EOA accounts are not supported. > > **1. Request a Plan** > > First, request a plan based on the wallet's current Combo positions. > > ```ts theme={null} > import type { CollateralReturnPlanResponse } from "@polymarket/client"; > > const plan: CollateralReturnPlanResponse = await client.planCollateralReturn(); > ``` > > > [accordion] CollateralReturnPlanResponse > > > > ```ts CollateralReturnPlanResponse Type theme={null} > > enum CollateralReturnKnownOperationKind { > > Split = "split", > > Merge = "merge", > > Redeem = "redeem", > > SplitOnCondition = "split_on_condition", > > MergeOnCondition = "merge_on_condition", > > SplitOnEvent = "split_on_event", > > MergeOnEvent = "merge_on_event", > > ConvertOnEvent = "convert_on_event", > > Extract = "extract", > > Inject = "inject", > > ConvertToYesBasket = "convert_to_yes_basket", > > MergeFromYesBasket = "merge_from_yes_basket", > > Compress = "compress", > > } > > > > type CollateralReturnOperationKind = > > | CollateralReturnKnownOperationKind > > | (string & {}); > > > > type CollateralReturnOperation = { > > kind: CollateralReturnOperationKind; > > conditionId?: ComboConditionId; > > eventId?: EventId; > > positionId?: PositionId; > > conditionIndex: number; > > amount: DecimalString; > > }; > > > > type CollateralReturnPositionAmount = { > > positionId: PositionId; > > amount: DecimalString; > > }; > > > > type CollateralReturnPositionSummary = { > > consumed: CollateralReturnPositionAmount[]; > > created: CollateralReturnPositionAmount[]; > > }; > > > > type CollateralReturnRouterCall = { > > to: EvmAddress; > > data: HexString; > > }; > > > > type CollateralReturnPlanResponse = { > > planHash: HexString; > > chainId: number; > > wallet: EvmAddress; > > blockNumber: bigint; > > startingPusd: DecimalString; > > netPusdOut: DecimalString; > > finalPusd: DecimalString; > > operations: CollateralReturnOperation[]; > > operationCount: number; > > truncated: boolean; > > estimatedCost: number; > > requiredPusdInput: DecimalString; > > requiredPositions: CollateralReturnPositionAmount[]; > > positionSummary: CollateralReturnPositionSummary; > > candidatePositionIds: PositionId[]; > > routerCall: CollateralReturnRouterCall; > > }; > > ``` > > > > ```json CollateralReturnPlanResponse Example theme={null} > > { > > "planHash": "", > > "chainId": 137, > > "wallet": "", > > "blockNumber": "74281963", > > "startingPusd": "5.000000", > > "netPusdOut": "1.000000", > > "finalPusd": "6.000000", > > "operations": [ > > { > > "kind": "merge_on_condition", > > "conditionId": "", > > "positionId": "", > > "conditionIndex": 0, > > "amount": "1.000000" > > } > > ], > > "operationCount": 1, > > "truncated": false, > > "estimatedCost": 240000, > > "requiredPusdInput": "0.000000", > > "requiredPositions": [ > > { > > "positionId": "", > > "amount": "1.000000" > > } > > ], > > "positionSummary": { > > "consumed": [ > > { > > "positionId": "", > > "amount": "1.000000" > > } > > ], > > "created": [ > > { > > "positionId": "", > > "amount": "0.500000" > > } > > ] > > }, > > "candidatePositionIds": [ > > "", > > "" > > ], > > "routerCall": { > > "to": "", > > "data": "" > > } > > } > > ``` > > **2. Inspect the Plan** > > Next, inspect the plan before signing. It is an inspectable execution artifact, > not just a transaction payload. Review its expected return and residual-position > impact, and apply any application-specific limits. > > | Field | What to inspect | > | - | - | > | `startingPusd`, `netPusdOut`, `finalPusd` | The expected pUSD return and resulting wallet balance. | > | `requiredPositions` | The Combo positions the plan requires. | > | `operations` | The ordered position changes. | > | `positionSummary` | The positions consumed and the residual positions created. | > | `estimatedCost` | The estimated execution cost against any application-specific limit. | > | `truncated` | Whether more work remains after this plan confirms. | > | `routerCall` | The exact action that will be submitted. | > > **3. Execute the Inspected Plan** > > Finally, execute the inspected plan and wait for the transaction to confirm. > > ```ts theme={null} > const handle = await client.executeCollateralReturnPlan({ plan }); > const outcome = await handle.wait(); > > // outcome.transactionHash: TxHash > ``` > > `await handle.wait()` returns after the submitted plan's transaction confirms. > Request another plan only then, because the next plan is calculated from the > resulting onchain state. > > > [!NOTE] > > > > If execution fails, discard the plan and request a new one before retrying. > [tab] Python > > Given an `AsyncSecureClient` configured with a Relayer API key, ensure the wallet > has the required trading approvals: > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > > await client.setup_trading_approvals() > ``` > > The sync `SecureClient` provides the same methods. > > > [!NOTE] > > > > Collateral return supports Deposit Wallet, Safe Wallet, and Proxy Wallet > > accounts. EOA accounts are not supported. > > **1. Request a Plan** > > First, request a plan based on the wallet's current Combo positions. > > ```python theme={null} > from polymarket import CollateralReturnPlanResponse > > plan: CollateralReturnPlanResponse = await client.plan_collateral_return() > ``` > > > [accordion] CollateralReturnPlanResponse > > > > ```python CollateralReturnPlanResponse Type theme={null} > > class CollateralReturnOperationKind(StrEnum): > > SPLIT = "split" > > MERGE = "merge" > > REDEEM = "redeem" > > SPLIT_ON_CONDITION = "split_on_condition" > > MERGE_ON_CONDITION = "merge_on_condition" > > SPLIT_ON_EVENT = "split_on_event" > > MERGE_ON_EVENT = "merge_on_event" > > CONVERT_ON_EVENT = "convert_on_event" > > EXTRACT = "extract" > > INJECT = "inject" > > CONVERT_TO_YES_BASKET = "convert_to_yes_basket" > > MERGE_FROM_YES_BASKET = "merge_from_yes_basket" > > COMPRESS = "compress" > > > > > > class CollateralReturnOperation: > > kind: CollateralReturnOperationKind | str > > condition_id: ComboConditionId | None > > event_id: EventId | None > > position_id: PositionId | None > > condition_index: int > > amount: Decimal > > > > > > class CollateralReturnPositionAmount: > > position_id: PositionId > > amount: Decimal > > > > > > class CollateralReturnPositionSummary: > > consumed: tuple[CollateralReturnPositionAmount, ...] > > created: tuple[CollateralReturnPositionAmount, ...] > > > > > > class CollateralReturnRouterCall: > > to: EvmAddress > > data: HexString > > > > > > class CollateralReturnPlanResponse: > > plan_hash: HexString > > chain_id: int > > wallet: EvmAddress > > block_number: int > > starting_pusd: Decimal > > net_pusd_out: Decimal > > final_pusd: Decimal > > operations: tuple[CollateralReturnOperation, ...] > > operation_count: int > > truncated: bool > > estimated_cost: float > > required_pusd_input: Decimal > > required_positions: tuple[CollateralReturnPositionAmount, ...] > > position_summary: CollateralReturnPositionSummary > > candidate_position_ids: tuple[PositionId, ...] > > router_call: CollateralReturnRouterCall > > ``` > > > > ```json CollateralReturnPlanResponse Example theme={null} > > { > > "plan_hash": "", > > "chain_id": 137, > > "wallet": "", > > "block_number": 74281963, > > "starting_pusd": "5.000000", > > "net_pusd_out": "1.000000", > > "final_pusd": "6.000000", > > "operations": [ > > { > > "kind": "merge_on_condition", > > "condition_id": "", > > "position_id": "", > > "condition_index": 0, > > "amount": "1.000000" > > } > > ], > > "operation_count": 1, > > "truncated": false, > > "estimated_cost": 240000, > > "required_pusd_input": "0.000000", > > "required_positions": [ > > { > > "position_id": "", > > "amount": "1.000000" > > } > > ], > > "position_summary": { > > "consumed": [ > > { > > "position_id": "", > > "amount": "1.000000" > > } > > ], > > "created": [ > > { > > "position_id": "", > > "amount": "0.500000" > > } > > ] > > }, > > "candidate_position_ids": [ > > "", > > "" > > ], > > "router_call": { > > "to": "", > > "data": "" > > } > > } > > ``` > > **2. Inspect the Plan** > > Next, inspect the plan before signing. Review its expected return and > residual-position impact, and apply any application-specific limits. > > | Field | What to inspect | > | - | - | > | `starting_pusd`, `net_pusd_out`, `final_pusd` | The expected pUSD return and resulting wallet balance. | > | `required_positions` | The Combo positions the plan requires. | > | `operations` | The ordered position changes. | > | `position_summary` | The positions consumed and the residual positions created. | > | `estimated_cost` | The estimated execution cost against any application-specific limit. | > | `truncated` | Whether more work remains after this plan confirms. | > | `router_call` | The exact action that will be submitted. | > > **3. Execute the Inspected Plan** > > Finally, execute the inspected plan and wait for the transaction to confirm. > > ```python theme={null} > handle = await client.execute_collateral_return_plan(plan=plan) > outcome = await handle.wait() > > # outcome.transaction_hash: TransactionHash > ``` > > `await handle.wait()` returns after the submitted plan's transaction confirms. > Request another plan only then, because the next plan is calculated from the > resulting onchain state. > > > [!NOTE] > > > > If execution fails, discard the plan and request a new one before retrying. > [tab] API > > > [!NOTE] > > > > The following steps show the Deposit Wallet path. For Safe or Proxy Wallet > > flows, use an SDK or see the reference examples at the end of this tab. > > Before requesting a plan, ensure the wallet has the approvals below. Follow [Set > Up Trading Approvals](/trading/wallets-auth#set-up-trading-approvals) to check, > encode, and submit the required approval calls. > > | Asset | Contract to approve | Contract call | > | - | - | - | > | pUSD | Collateral Return Router | `approve(CollateralReturnRouter, maxUint256)` | > | Combo positions | Collateral Return Router | `setApprovalForAll(CollateralReturnRouter, true)` | > > Use the following production contract addresses when building the approval > calls. > > | Contract | Address | > | - | - | > | pUSD | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | Position Manager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > | Collateral Return Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > > Follow these steps to request and execute a collateral-return plan. > > **1. Request a Plan** > > First, request a plan for the Deposit Wallet whose Combo positions you want to > process. > > ```bash theme={null} > curl -X POST "https://combos-rfq-collateral-return.polymarket.com/v1/collateral-return/plan" \ > -H "Content-Type: application/json" \ > --data '{ > "wallet": "" > }' > ``` > > The plan is calculated from one pinned block and contains the position changes > and Router call for that state snapshot. > > > [accordion] Collateral Return Plan > > > > ```json theme={null} > > { > > "plan_hash": "", > > "chain_id": 137, > > "wallet": "", > > "block_number": "74281963", > > "starting_pusd": "5.000000", > > "net_pusd_out": "1.000000", > > "final_pusd": "6.000000", > > "operations": [ > > { > > "kind": "merge_on_condition", > > "condition_id": "", > > "position_id": "", > > "condition_index": 0, > > "amount": "1000000" > > } > > ], > > "operation_count": 1, > > "truncated": false, > > "estimated_cost": 240000, > > "required_positions": [ > > { > > "position_id": "", > > "amount": "1000000" > > } > > ], > > "position_summary": { > > "consumed": [ > > { > > "position_id": "", > > "amount": "1000000" > > } > > ], > > "created": [ > > { > > "position_id": "", > > "amount": "1000000" > > } > > ] > > }, > > "candidate_position_ids": [ > > "", > > "" > > ], > > "router_call": { > > "to": "", > > "data": "" > > } > > } > > ``` > > Nested `amount` values use six-decimal base units, so `1000000` represents one > position unit. > > **2. Inspect the Plan** > > Next, inspect the plan before signing. Review its expected return, > residual-position impact, and execution cost against any application-specific > limits. > > | Field | What to inspect | > | - | - | > | `starting_pusd`, `net_pusd_out`, `final_pusd` | The expected pUSD return and resulting wallet balance. | > | `required_positions` | The Combo positions the plan consumes. | > | `position_summary` | The positions consumed and created, including residual positions. | > | `operations` | The ordered position changes. | > | `estimated_cost` | The estimated execution cost against any application-specific limit. | > | `truncated` | Whether more work remains after this plan confirms. | > | `router_call` | The exact Router action that the wallet will authorize. | > | `plan_hash` | The correlation value to send with the signed wallet action. | > > **3. Fetch the Wallet Nonce** > > Then, fetch a fresh Deposit Wallet nonce for the signer from the Relayer. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > ```json Response theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **4. Create the Batch Typed Data** > > Next, create Deposit Wallet EIP-712 `Batch` typed data containing exactly one > call. Copy `router_call.to` and `router_call.data` from the plan without > modification, and use `0` for the call value. Set `deadline` to a future Unix > timestamp; the complete example below uses ten minutes from the current time. > > ```json walletBatchTypedData theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > } > ``` > > **5. Sign the Batch** > > Then, sign the typed data with the signer that controls the Deposit Wallet. The > example below uses Viem. > > ```ts theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount( > process.env.SIGNER_PRIVATE_KEY as `0x${string}`, > ); > const signature = await signer.signTypedData(walletBatchTypedData); > ``` > > **6. Execute the Plan** > > Next, send the plan hash and signed Deposit Wallet envelope to the Collateral > Return API. Use the same nonce, deadline, and Router call that you signed. > > ```bash theme={null} > curl -X POST "https://combos-rfq-collateral-return.polymarket.com/v1/collateral-return/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > --data '{ > "plan_hash": "", > "envelope": { > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Return Combo collateral", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > } > }' > ``` > > The Collateral Return service validates and simulates the signed action against > current state before forwarding it to the Relayer. The response includes the > transaction ID used in the next step. > > ```json Response theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > > [!NOTE] > > > > If submission returns `409 fresh plan required`, discard the plan and request > > a new one before rebuilding and signing the wallet action. > > **7. Confirm the Transaction** > > Finally, poll the Relayer transaction until it reaches `STATE_CONFIRMED`. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " > ``` > > ```json Response theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > | State | Action | > | - | - | > | `STATE_NEW`, `STATE_EXECUTED`, `STATE_MINED` | Continue polling. | > | `STATE_CONFIRMED` | The transaction confirmed successfully. | > | `STATE_FAILED`, `STATE_INVALID` | Discard the plan and request a new one before retrying. | > > The complete examples below use Viem. > > ```javascript Deposit Wallet theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const COLLATERAL_RETURN_API = > "https://combos-rfq-collateral-return.polymarket.com"; > const RELAYER_API = "https://relayer-v2.polymarket.com"; > const DEPOSIT_WALLET_FACTORY = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"; > > const account = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const wallet = process.env.POLYMARKET_WALLET_ADDRESS; > const relayerHeaders = { > RELAYER_API_KEY: process.env.RELAYER_API_KEY, > RELAYER_API_KEY_ADDRESS: account.address, > }; > > // Request a plan. > const planResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/plan`, > { > method: "POST", > headers: { "Content-Type": "application/json" }, > body: JSON.stringify({ wallet }), > }, > ); > if (!planResponse.ok) throw new Error(await planResponse.text()); > const plan = await planResponse.json(); > > // Inspect the plan and apply any application-specific limits before signing. > console.log({ > netPusdOut: plan.net_pusd_out, > positionSummary: plan.position_summary, > estimatedCost: plan.estimated_cost, > truncated: plan.truncated, > }); > > // Fetch a fresh Deposit Wallet nonce. > const executeParamsResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/params?address=${account.address}&type=WALLET`, > { headers: relayerHeaders }, > ); > if (!executeParamsResponse.ok) { > throw new Error(await executeParamsResponse.text()); > } > const executeParams = await executeParamsResponse.json(); > > // Create and sign the Deposit Wallet batch. > const deadline = BigInt(Math.floor(Date.now() / 1_000) + 600); > const calls = [ > { > target: plan.router_call.to, > value: 0n, > data: plan.router_call.data, > }, > ]; > const signature = await account.signTypedData({ > domain: { > name: "DepositWallet", > version: "1", > chainId: 137, > verifyingContract: wallet, > }, > types: { > Call: [ > { name: "target", type: "address" }, > { name: "value", type: "uint256" }, > { name: "data", type: "bytes" }, > ], > Batch: [ > { name: "wallet", type: "address" }, > { name: "nonce", type: "uint256" }, > { name: "deadline", type: "uint256" }, > { name: "calls", type: "Call[]" }, > ], > }, > primaryType: "Batch", > message: { > wallet, > nonce: BigInt(executeParams.nonce), > deadline, > calls, > }, > }); > const envelope = { > type: "WALLET", > from: account.address, > to: DEPOSIT_WALLET_FACTORY, > nonce: executeParams.nonce, > signature, > metadata: "Return Combo collateral", > depositWalletParams: { > depositWallet: wallet, > deadline: deadline.toString(), > calls: calls.map((call) => ({ > ...call, > value: call.value.toString(), > })), > }, > }; > > // Execute the plan. > const submitResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/submit`, > { > method: "POST", > headers: { "Content-Type": "application/json", ...relayerHeaders }, > body: JSON.stringify({ plan_hash: plan.plan_hash, envelope }), > }, > ); > if (!submitResponse.ok) throw new Error(await submitResponse.text()); > const submitted = await submitResponse.json(); > > // Confirm the transaction. > let outcome; > for (;;) { > const transactionResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/${submitted.transactionID}`, > { headers: relayerHeaders }, > ); > if (!transactionResponse.ok) { > throw new Error(await transactionResponse.text()); > } > const transaction = await transactionResponse.json(); > > if (transaction.state === "STATE_CONFIRMED") { > outcome = transaction; > break; > } > if ( > transaction.state === "STATE_FAILED" || > transaction.state === "STATE_INVALID" > ) { > throw new Error(transaction.error_msg ?? transaction.state); > } > > await new Promise((resolve) => setTimeout(resolve, 1_000)); > } > > console.log(outcome); > ``` > > ```javascript Safe Wallet theme={null} > import { hashTypedData, zeroAddress } from "viem"; > import { privateKeyToAccount } from "viem/accounts"; > > const COLLATERAL_RETURN_API = > "https://combos-rfq-collateral-return.polymarket.com"; > const RELAYER_API = "https://relayer-v2.polymarket.com"; > > const account = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const wallet = process.env.POLYMARKET_WALLET_ADDRESS; > const relayerHeaders = { > RELAYER_API_KEY: process.env.RELAYER_API_KEY, > RELAYER_API_KEY_ADDRESS: account.address, > }; > > // Request a plan. > const planResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/plan`, > { > method: "POST", > headers: { "Content-Type": "application/json" }, > body: JSON.stringify({ wallet }), > }, > ); > if (!planResponse.ok) throw new Error(await planResponse.text()); > const plan = await planResponse.json(); > > // Inspect the plan and apply any application-specific limits before signing. > console.log({ > netPusdOut: plan.net_pusd_out, > positionSummary: plan.position_summary, > estimatedCost: plan.estimated_cost, > truncated: plan.truncated, > }); > > // Fetch a fresh Safe nonce. > const executeParamsResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/params?address=${account.address}&type=SAFE`, > { headers: relayerHeaders }, > ); > if (!executeParamsResponse.ok) { > throw new Error(await executeParamsResponse.text()); > } > const executeParams = await executeParamsResponse.json(); > > // Create and sign the Safe transaction. > const message = { > to: plan.router_call.to, > value: 0n, > data: plan.router_call.data, > operation: 0, > safeTxGas: 0n, > baseGas: 0n, > gasPrice: 0n, > gasToken: zeroAddress, > refundReceiver: zeroAddress, > nonce: BigInt(executeParams.nonce), > }; > const digest = hashTypedData({ > domain: { chainId: 137, verifyingContract: wallet }, > types: { > SafeTx: [ > { name: "to", type: "address" }, > { name: "value", type: "uint256" }, > { name: "data", type: "bytes" }, > { name: "operation", type: "uint8" }, > { name: "safeTxGas", type: "uint256" }, > { name: "baseGas", type: "uint256" }, > { name: "gasPrice", type: "uint256" }, > { name: "gasToken", type: "address" }, > { name: "refundReceiver", type: "address" }, > { name: "nonce", type: "uint256" }, > ], > }, > primaryType: "SafeTx", > message, > }); > > const signed = (await account.signMessage({ message: { raw: digest } })).slice( > 2, > ); > const v = Number.parseInt(signed.slice(128, 130), 16); > const packedV = v === 0 || v === 1 ? v + 31 : v === 27 || v === 28 ? v + 4 : v; > const signature = `0x${signed.slice(0, 128)}${packedV.toString(16).padStart(2, "0")}`; > const envelope = { > type: "SAFE", > from: account.address, > to: message.to, > proxyWallet: wallet, > value: "0", > data: message.data, > nonce: executeParams.nonce, > signature, > metadata: "Return Combo collateral", > signatureParams: { > operation: "0", > safeTxnGas: "0", > baseGas: "0", > gasPrice: "0", > gasToken: zeroAddress, > refundReceiver: zeroAddress, > }, > }; > > // Execute the plan. > const submitResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/submit`, > { > method: "POST", > headers: { "Content-Type": "application/json", ...relayerHeaders }, > body: JSON.stringify({ plan_hash: plan.plan_hash, envelope }), > }, > ); > if (!submitResponse.ok) throw new Error(await submitResponse.text()); > const submitted = await submitResponse.json(); > > // Confirm the transaction. > let outcome; > for (;;) { > const transactionResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/${submitted.transactionID}`, > { headers: relayerHeaders }, > ); > if (!transactionResponse.ok) { > throw new Error(await transactionResponse.text()); > } > const transaction = await transactionResponse.json(); > > if (transaction.state === "STATE_CONFIRMED") { > outcome = transaction; > break; > } > if ( > transaction.state === "STATE_FAILED" || > transaction.state === "STATE_INVALID" > ) { > throw new Error(transaction.error_msg ?? transaction.state); > } > > await new Promise((resolve) => setTimeout(resolve, 1_000)); > } > > console.log(outcome); > ``` > > ```javascript Proxy Wallet theme={null} > import { > concat, > createPublicClient, > encodeFunctionData, > http, > keccak256, > toHex, > } from "viem"; > import { privateKeyToAccount } from "viem/accounts"; > import { polygon } from "viem/chains"; > > const COLLATERAL_RETURN_API = > "https://combos-rfq-collateral-return.polymarket.com"; > const RELAYER_API = "https://relayer-v2.polymarket.com"; > const PROXY_WALLET_FACTORY = "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"; > const RELAY_HUB = "0xD216153c06E857cD7f72665E0aF1d7D82172F494"; > > const account = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const wallet = process.env.POLYMARKET_WALLET_ADDRESS; > const publicClient = createPublicClient({ > chain: polygon, > transport: http(process.env.RPC_URL), > }); > const relayerHeaders = { > RELAYER_API_KEY: process.env.RELAYER_API_KEY, > RELAYER_API_KEY_ADDRESS: account.address, > }; > > // Request a plan. > const planResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/plan`, > { > method: "POST", > headers: { "Content-Type": "application/json" }, > body: JSON.stringify({ wallet }), > }, > ); > if (!planResponse.ok) throw new Error(await planResponse.text()); > const plan = await planResponse.json(); > > // Inspect the plan and apply any application-specific limits before signing. > console.log({ > netPusdOut: plan.net_pusd_out, > positionSummary: plan.position_summary, > estimatedCost: plan.estimated_cost, > truncated: plan.truncated, > }); > > // Fetch a fresh Proxy Wallet nonce and relay address. > const executeParamsResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/params?address=${account.address}&type=PROXY`, > { headers: relayerHeaders }, > ); > if (!executeParamsResponse.ok) { > throw new Error(await executeParamsResponse.text()); > } > const executeParams = await executeParamsResponse.json(); > > // Encode and sign the Proxy Wallet relay request. > const data = encodeFunctionData({ > abi: [ > { > type: "function", > name: "proxy", > inputs: [ > { > type: "tuple[]", > components: [ > { name: "typeCode", type: "uint8" }, > { name: "to", type: "address" }, > { name: "value", type: "uint256" }, > { name: "data", type: "bytes" }, > ], > }, > ], > outputs: [{ type: "bytes[]" }], > }, > ], > functionName: "proxy", > args: [ > [ > { > typeCode: 1, > to: plan.router_call.to, > value: 0n, > data: plan.router_call.data, > }, > ], > ], > }); > const relayerFee = 0n; > const gasPrice = 0n; > const gasLimit = await publicClient.estimateGas({ > account: account.address, > to: PROXY_WALLET_FACTORY, > data, > }); > const digest = keccak256( > concat([ > toHex("rlx:"), > account.address, > PROXY_WALLET_FACTORY, > data, > toHex(relayerFee, { size: 32 }), > toHex(gasPrice, { size: 32 }), > toHex(gasLimit, { size: 32 }), > toHex(BigInt(executeParams.nonce), { size: 32 }), > RELAY_HUB, > executeParams.address, > ]), > ); > const signature = await account.signMessage({ message: { raw: digest } }); > const envelope = { > type: "PROXY", > from: account.address, > to: PROXY_WALLET_FACTORY, > proxyWallet: wallet, > value: "0", > data, > nonce: executeParams.nonce, > signature, > metadata: "Return Combo collateral", > signatureParams: { > gasPrice: gasPrice.toString(), > relayerFee: relayerFee.toString(), > gasLimit: gasLimit.toString(), > relayHub: RELAY_HUB, > relay: executeParams.address, > }, > }; > > // Execute the plan. > const submitResponse = await fetch( > `${COLLATERAL_RETURN_API}/v1/collateral-return/submit`, > { > method: "POST", > headers: { "Content-Type": "application/json", ...relayerHeaders }, > body: JSON.stringify({ plan_hash: plan.plan_hash, envelope }), > }, > ); > if (!submitResponse.ok) throw new Error(await submitResponse.text()); > const submitted = await submitResponse.json(); > > // Confirm the transaction. > let outcome; > for (;;) { > const transactionResponse = await fetch( > `${RELAYER_API}/v1/account/transactions/${submitted.transactionID}`, > { headers: relayerHeaders }, > ); > if (!transactionResponse.ok) { > throw new Error(await transactionResponse.text()); > } > const transaction = await transactionResponse.json(); > > if (transaction.state === "STATE_CONFIRMED") { > outcome = transaction; > break; > } > if ( > transaction.state === "STATE_FAILED" || > transaction.state === "STATE_INVALID" > ) { > throw new Error(transaction.error_msg ?? transaction.state); > } > > await new Promise((resolve) => setTimeout(resolve, 1_000)); > } > > console.log(outcome); > ``` ## Handle a Truncated Plan The service limits how much work one transaction can contain. When more work remains, each plan is one complete, executable chunk—not a partial transaction. Execute and confirm each chunk before requesting the next plan because every new plan depends on the resulting onchain state. > [tab] TypeScript > > Use `plan.truncated` to determine whether more work remains after the current > plan. > > ```ts theme={null} > let plan: CollateralReturnPlanResponse; > > do { > plan = await client.planCollateralReturn(); > > // Inspect the return and residual-position impact, and apply any > // application-specific limits before signing. > const handle = await client.executeCollateralReturnPlan({ plan }); > await handle.wait(); > } while (plan.truncated); > ``` > [tab] Python > > Use `plan.truncated` to determine whether more work remains after the current > plan. > > ```python theme={null} > while True: > plan = await client.plan_collateral_return() > > # Inspect the return and residual-position impact before signing. > handle = await client.execute_collateral_return_plan(plan=plan) > await handle.wait() > > if not plan.truncated: > break > ``` > [tab] API > > After the submitted transaction confirms, inspect the `truncated` value from > the plan that produced it. When it is `true`, request a fresh plan, inspect and > sign its wallet action, submit it, and wait for confirmation again. Continue > until the confirmed plan has `truncated: false`. ## Understand Residual Positions Collateral return only removes exposure that can be recombined into collateral. Any unmatched exposure remains in new residual positions. These positions preserve the wallet's remaining economic exposure after the returned pUSD is removed. For example, complementary exposure to one underlying leg may unlock pUSD while the rest of each Combo remains open. Inspect the created positions before execution and include them in your normal [Combo position sync](/trading/combos/market-makers#list-combo-positions) after confirmation. # Market Makers Source: https://docs.polymarket.com/trading/combos/market-makers Build a market maker integration for pricing and executing Combos This guide shows market makers how to handle Combo RFQs. You will open a quoting session, respond to incoming requests, cancel submitted quotes when needed, confirm fills through Last Look, and monitor execution updates. > [!NOTE] > > For development updates on market making for Combos, join the [Combos market > maker Telegram group](https://t.me/+eyMtdtKasWZjYTMx). ## Start Quoting Start by preparing an authenticated quoting session with the RFQ system. You need a Polymarket account; create one at [polymarket.com](https://polymarket.com). > [tab] TypeScript > > **1. Install the Package** > > Install the Unified TypeScript SDK with the package manager of your choice. > > ```bash pnpm theme={null} > pnpm add @polymarket/client@latest viem > ``` > > ```bash npm theme={null} > npm install @polymarket/client@latest viem > ``` > > ```bash yarn theme={null} > yarn add @polymarket/client@latest viem > ``` > > > [!NOTE] > > > > This page uses Viem for wallet signing. See the [TypeScript tooling > > guide](/getting-started/typescript#wallet-integrations) for other wallet > > library integrations. > > **2. Create a Secure Client** > > Create a `SecureClient` with a wallet that has funds for fulfilling > user requests and its signer details. > > ```ts theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS!, > signer: privateKey(process.env.PRIVATE_KEY!), > apiKey: relayerApiKey({ > key: process.env.RELAYER_API_KEY!, > address: process.env.RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > The Relayer API key is necessary for setting up trading approvals in the next > step. Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) > from polymarket.com → Settings → API Keys. > > **3. Set Up Trading Approvals** > > Set up the approvals required to fill user requests. > > ```ts theme={null} > await client.setupTradingApprovals(); > ``` > > **4. Open an RFQ Session** > > Open the RFQ session. > > ```ts theme={null} > const session = await client.openRfqSession(); > > for await (const event of session) { > // event: RfqEvent > } > ``` > > **5. Close the Session** > > You can close the session at any time by calling `session.close()`. > > ```ts theme={null} > for await (const event of session) { > if (shouldCloseSession) { > await session.close(); > break; > } > > // … > } > ``` > [tab] Python > > **1. Install the Package** > > Install the Python SDK with the package manager of your choice. > > ```bash uv theme={null} > uv add polymarket-client > ``` > > ```bash pip theme={null} > pip install polymarket-client > ``` > > ```bash poetry theme={null} > poetry add polymarket-client > ``` > > **2. Create a Secure Client** > > Create an `AsyncSecureClient` with a wallet that has funds for fulfilling user > requests and its signer details. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > > client = await AsyncSecureClient.create( > private_key=os.environ["PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["RELAYER_API_KEY"], > address=os.environ["RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > The Relayer API key is necessary for setting up trading approvals in the next > step. Create a [Relayer API key](https://polymarket.com/settings?tab=api-keys) > from polymarket.com → Settings → API Keys. > > **3. Set Up Trading Approvals** > > Set up the approvals required to fill user requests. > > ```python theme={null} > await client.setup_trading_approvals() > ``` > > **4. Open an RFQ Session** > > Open the RFQ session. > > ```python theme={null} > async with client.open_rfq_session() as session: > async for event in session: > # event: RfqEvent > ... > ``` > > **5. Close the Session** > > You can close the session at any time by calling `await session.close()`. > > ```python theme={null} > async with client.open_rfq_session() as session: > async for event in session: > if should_close_session: > await session.close() > break > > ... > ``` > [tab] API > > > [!NOTE] > > > > Use Polygon mainnet chain ID `137` for CLOB authentication and Exchange v3 > > order signing. > > **1. Open the WebSocket** > > Connect to the RFQ system WebSocket. > > ```text theme={null} > wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq > ``` > > To inspect the stream before integrating: > > ```bash theme={null} > wscat -c "wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq" > ``` > > Some write operations are also available through the REST API. > > ```text theme={null} > https://combos-rfq-api.polymarket.com > ``` > > **2. Acquire CLOB Credentials** > > RFQ WebSocket authentication uses CLOB API credentials: API key, secret, and > passphrase. If you need credentials, start with [Getting API > Credentials](/getting-started/api#authentication). > > **3. Resolve Quoter Identity** > > Resolve the order signer identity before sending `auth`. The RFQ system needs > the address that signs the order, the wallet that funds the order, and the > signature type that connects those two addresses. > > | Wallet Type | `signature_type` | `signer_address` | `maker_address` | > | - | - | - | - | > | Deposit Wallet | `3` POLY_1271 | Deposit wallet address | Deposit wallet | > | Safe Wallet | `2` Safe | Authenticated signing address | Derived Safe wallet | > | Proxy Wallet | `1` Proxy | Authenticated signing address | Derived proxy wallet | > | EOA | `0` EOA | EOA address | Same EOA address | > > For more detail, see [Wallets and Authentication](/trading/wallets-auth#wallet-types). > > **4. Authenticate** > > Send `auth` as the first WebSocket message within 30 seconds. Include the CLOB > credentials and the `signer_address`, `maker_address`, and `signature_type` > values resolved in the previous step. This example uses a Deposit Wallet. > > ```json theme={null} > { > "type": "auth", > "auth": { > "apiKey": "YOUR_API_KEY", > "secret": "YOUR_API_SECRET", > "passphrase": "YOUR_API_PASSPHRASE" > }, > "identity": { > "signer_address": "", > "maker_address": "", > "signature_type": 3 // > } > } > ``` > > Authentication returns a success or failure response. > > ```json Success theme={null} > { > "type": "auth", > "success": true, > "address": "0xAuthenticatedAddress", > "role": "maker" > } > ``` > > ```json Failure theme={null} > { > "type": "auth", > "success": false, > "error": "unauthenticated" > } > ``` > > > [!NOTE] > > > > The RFQ system uses WebSocket protocol heartbeat frames to keep the connection > > alive. It sends a ping frame every 30 seconds with payload `rfq`; your client > > must respond with a pong frame that echoes the same payload. Most WebSocket > > clients handle this automatically. These are protocol frames, not JSON > > messages in the RFQ event stream. The gateway closes stale connections after 2 > > minutes without an inbound message or pong. > > **5. Check Approval Requirements** > > Before posting quotes or managing Combo inventory, `maker_address` must approve > the contracts that may transfer its assets. > > | Approval | Required when | Contract call | > | - | - | - | > | pUSD collateral | The quoted order transfers pUSD | `CollateralToken.approve(ExchangeV3, maxUint256)` | > | Combo positions | The quoted order transfers Combo positions | `PositionManager.setApprovalForAll(ExchangeV3, true)` | > | Router pUSD collateral | You split pUSD into positions through the Router | `CollateralToken.approve(Router, maxUint256)` | > | Router positions | You manage or redeem positions through the Router | `PositionManager.setApprovalForAll(Router, true)` | > | AutoRedeemer Combo operator | You want automatic redemption flows to use it | `PositionManager.setApprovalForAll(AutoRedeemer, true)` | > > Use these contract addresses to build the approval calls. > > | Contract | Address | > | - | - | > | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | Exchange v3 | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | > | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > | AutoRedeemer | `0xa1200000d0002264C9a1698e001292D00E1b00af` | > > > [!NOTE] > > > > The following steps use the Deposit Wallet [gasless transaction > > flow](/trading/wallets-auth#execute-gasless-transactions). If you are trading > > with an EOA, submit the approvals directly from `maker_address`. For Safe or > > Proxy Wallet flows, use an SDK. > > **6. Build the Approval Call List** > > Encode the approval calls that are not already in place. > > ```solidity ERC-20 Approval theme={null} > function approve(address spender, uint256 amount) returns (bool); > ``` > > ```solidity ERC-1155 Approval theme={null} > function setApprovalForAll(address operator, bool approved); > ``` > > Build a relayer call list from the encoded calldata. > > ```json theme={null} > [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > }, > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > }, > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > } > ] > ``` > > **7. Fetch the Nonce** > > Fetch a fresh `WALLET` nonce before signing the batch. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the nonce to sign with the transaction. > > ```json theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **8. Submit the Transaction** > > Build and sign a Deposit Wallet `Batch` with the owner. Use the approval calls > from the call-list step as `calls`. > > ```json EIP-712 Batch theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > } > ] > } > } > ``` > > Submit the signed batch to the relayer. > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Approve Combo RFQ contracts", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > The response includes the relayer transaction ID. > > ```json theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **9. Poll the Transaction** > > Poll the relayer transaction until it reaches `STATE_CONFIRMED` before posting > quotes that rely on those approvals. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" > ``` > > ```json theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. ## Handle Quote Requests Quote requests describe a user's intent to buy or sell shares in a Combo defined by a given set of legs. A quote request can currently only buy or sell the YES side of a Combo. The following cases show how a market maker can satisfy a user's buy or sell request using collateral or inventory. | Quote Request | Using Collateral | From Inventory | | - | - | - | | Buy YES | Buy NO at `1 - price` | Sell YES at `price` | | Sell YES | Buy YES at `price` | Sell NO at `1 - price` | See [Combinatorial Positions](/trading/positions/combinatorial) for more detail on the YES/NO position model. The diagram below shows the maker-side quote lifecycle, from receiving a quote request through its terminal outcome. ```mermaid theme={null} flowchart TD A[Receive request] --> B[Send quote] B --> C[Active quote] C --> D[Canceled] C --> E[Selected] E --> F{Last Look?} F -->|No| G[Execution] subgraph lastLook["Last Look"] F -->|Yes| H[Review fill] H --> I[Confirm] H --> J[Decline] H --> K[Timeout] end I --> G G --> L[Confirmed] G --> M[Failed] style lastLook fill:#165DFC14,stroke:#165DFC66,stroke-width:1px ``` ### Authorize the Quote Authorize each quote by pricing the request and returning a signed order to the RFQ system. Quoters should respond within the **400 ms** submission window. > [tab] TypeScript > > **1. Switch on Event Type** > > First, switch on `event.type` to handle quote requests from the session stream. > > ```ts theme={null} > switch (event.type) { > case "quote_request": > // event: RfqQuoteRequestEvent > void handleQuoteRequest(event); > break; > > // … > } > ``` > > **2. Evaluate Request** > > Then, inspect the `RfqQuoteRequestEvent` before pricing it. > > | Field | Type | Description | > | - | - | - | > | `rfqId` | `RfqId` | RFQ identifier used to correlate responses | > | `requestorPublicId` | `RfqRequestorPublicId` | Public identifier for the user request | > | `conditionId` | `ComboConditionId` | Derived Combo condition ID | > | `direction` | `RfqDirection` | Whether the user wants to buy or sell | > | `side` | `RfqSide.Yes` | Currently always `RfqSide.Yes` | > | `requestedSize` | `RfqRequestedSize` | User-requested notional or share size | > | `yesPositionId` | `PositionId` | Derived YES Combo position ID | > | `noPositionId` | `PositionId` | Derived NO Combo position ID | > | `legPositionIds` | `PositionId[]` | Underlying leg position IDs | > | `submissionDeadline` | `EpochMilliseconds` | Unix-millisecond quote submission deadline | > > `requestedSize` is an `RfqRequestedSize` value that describes how the user sized > the request. > > ```ts theme={null} > type RfqRequestedSize = > | { > unit: RfqRequestedSizeUnit.Notional; > value: DecimalString; > } > | { > unit: RfqRequestedSizeUnit.Shares; > value: DecimalString; > }; > ``` > > Where: > > * `notional`: the target value of the request in collateral currency. For > example, `"3"` means the user wants roughly 3 pUSD worth of the Combo, with the > resulting share size derived from the quote price. `notional` is always and only used by BUY requests. > * `shares`: the target number of Combo outcome tokens. For example, `"10"` means > the user wants 10 shares, or 10,000,000 base units. `shares` is always and only used by SELL requests. > > In both cases, `value` is a normalized decimal string. > > **3. Submission** > > Finally, handle pricing, quote submission, and persistence outside the session > loop before the `event.submissionDeadline` deadline. Price the request as pUSD > per YES Combo share; for example, `0.45` means `0.45` pUSD per share. If you do > not want to quote the request, skip submission. > > ```ts theme={null} > async function handleQuoteRequest(event: RfqQuoteRequestEvent) { > const price = priceComboRequest(event); > > if (price === undefined) return; > > const reference = await event.quote({ price }); > > storeQuoteReference(reference); > } > ``` > [tab] Python > > **1. Check Event Type** > > First, use `isinstance(...)` to handle quote requests from the session stream. > > ```python theme={null} > from polymarket import RfqQuoteRequestEvent > > > async for event in session: > if isinstance(event, RfqQuoteRequestEvent): > await handle_quote_request(event) > ``` > > **2. Evaluate Request** > > Then, inspect the `RfqQuoteRequestEvent` before pricing it. > > | Field | Type | Description | > | - | - | - | > | `rfq_id` | `RfqId` | RFQ identifier used to correlate responses | > | `requestor_public_id` | `RfqRequestorPublicId` | Public identifier for the user request | > | `condition_id` | `ComboConditionId` | Derived Combo condition ID | > | `direction` | `RfqDirection` | Whether the user wants to buy or sell | > | `side` | `RfqSide` | Currently always `RfqSide.YES` | > | `requested_size` | `RfqRequestedSize` | User-requested notional or share size | > | `yes_position_id` | `PositionId` | Derived YES Combo position ID | > | `no_position_id` | `PositionId` | Derived NO Combo position ID | > | `leg_position_ids` | `tuple[PositionId, ...]` | Underlying leg position IDs | > | `submission_deadline` | `int` | Unix-millisecond quote submission deadline | > > `requested_size` is an `RfqRequestedSize` value that describes how the user sized > the request. > > ```python theme={null} > from dataclasses import dataclass > from decimal import Decimal > > from polymarket import RfqRequestedSizeUnit > > > @dataclass(frozen=True, slots=True, kw_only=True) > class RfqRequestedSize: > unit: RfqRequestedSizeUnit > value: Decimal > ``` > > Where: > > * `RfqRequestedSizeUnit.NOTIONAL`: the target value of the request in collateral > currency. For example, `Decimal("3")` means the user wants roughly 3 pUSD worth > of the Combo, with the resulting share size derived from the quote price. > BUY RFQs will always use `NOTIONAL`. > * `RfqRequestedSizeUnit.SHARES`: the target number of Combo outcome tokens. For > example, `Decimal("10")` means the user wants 10 shares, or 10,000,000 base > units. SELL RFQs will always use `SHARES`. > > In both cases, `value` is a `Decimal`. > > **3. Submission** > > Finally, handle pricing, quote submission, and persistence outside the session > loop before the `event.submission_deadline` deadline. Price the request as pUSD > per YES Combo share; for example, `Decimal("0.45")` means `0.45` pUSD per share. > If you do not want to quote the request, skip submission. > > ```python theme={null} > from decimal import Decimal > > from polymarket import RfqQuoteRequestEvent > > > async def handle_quote_request(event: RfqQuoteRequestEvent) -> None: > price = price_combo_request(event) > > if price is None: > return > > reference = await event.quote(price=price) > > store_quote_reference(reference) > ``` > [tab] API > > **1. Receive the Quote Request** > > The RFQ system sends `RFQ_REQUEST` messages over the authenticated WebSocket. > Inspect the request before pricing it. > > ```json Notional Request theme={null} > { > "type": "RFQ_REQUEST", > "rfq_id": "", > "requestor_public_id": "", > "leg_position_ids": ["", ""], > "condition_id": "", > "yes_position_id": "", > "no_position_id": "", > "direction": "BUY", > "side": "YES", > "requested_size": { > "unit": "notional", > "value_e6": "1000000" > }, > "submission_deadline": "" > } > ``` > > ```json Shares Request theme={null} > { > "type": "RFQ_REQUEST", > "rfq_id": "", > "requestor_public_id": "", > "leg_position_ids": ["", ""], > "condition_id": "", > "yes_position_id": "", > "no_position_id": "", > "direction": "SELL", > "side": "YES", > "requested_size": { > "unit": "shares", > "value_e6": "1000000" > }, > "submission_deadline": "" > } > ``` > > A `BUY` request always uses `notional` sizing, which specifies a target pUSD > amount and derives the fillable share size from the quote price. A `SELL` > request always uses `shares` sizing, which specifies the exact number of Combo > outcome tokens requested to sell. > > **2. Build the Order** > > Decide the `price` in base units for a full share. A full share is `1000000` > share base units, and `1` pUSD is `1000000` pUSD base units. For example, a > price of `0.45` pUSD per share means `price = 450000`. > > Determine `size` from the request: > > | `requested_size.unit` | `size` | > | - | - | > | `notional` | `floor(requested_size.value_e6 * 1000000 / price)` | > | `shares` | `requested_size.value_e6` | > > Then determine the order token and amounts: > > | Quote Request | Token | `makerAmount` | `takerAmount` | > | - | - | - | - | > | `SELL` YES | `yes_position_id` | `ceil(price * size / 1000000)` | `size` | > | `BUY` YES | `no_position_id` | `ceil((1000000 - price) * size / 1000000)` | `size` | > > The examples below quote `1` share, so `size = 1000000`. > > ```json SELL Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "450000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > ```json BUY Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "550000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > **3. Build EIP-712 Typed Data** > > Build the EIP-712 typed-data payload for your wallet type: > > * Use `depositWalletTypedData` when `signature_type` is `3`. > * Use `exchangeV3OrderTypedData` when `signature_type` is `0`, `1`, or `2`. > > ```json depositWalletTypedData theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "3", > "chainId": 137, > "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" > }, > "types": { > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ], > "TypedDataSign": [ > { "name": "contents", "type": "Order" }, > { "name": "name", "type": "string" }, > { "name": "version", "type": "string" }, > { "name": "chainId", "type": "uint256" }, > { "name": "verifyingContract", "type": "address" }, > { "name": "salt", "type": "bytes32" } > ] > }, > "primaryType": "TypedDataSign", > "message": { > "contents": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "450000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > }, > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "0xYourDepositWallet", > "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > ```json exchangeV3OrderTypedData theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "3", > "chainId": 137, > "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" > }, > "types": { > "EIP712Domain": [ > { "name": "name", "type": "string" }, > { "name": "version", "type": "string" }, > { "name": "chainId", "type": "uint256" }, > { "name": "verifyingContract", "type": "address" } > ], > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ] > }, > "primaryType": "Order", > "message": { > "salt": "", > "maker": "0xYourEoaAddress", > "signer": "0xYourEoaAddress", > "tokenId": "", > "makerAmount": "450000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 0, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > Both payloads use the Exchange v3 EIP-712 domain. `exchangeV3OrderTypedData` is > the direct Exchange v3 `Order` payload. `depositWalletTypedData` is a > `TypedDataSign` wrapper whose `contents` field is the Exchange v3 order and > whose message includes the Deposit Wallet validation fields. > > **4. Sign the Order** > > Sign the typed-data payload for the wallet type you authenticated with. The > normal Exchange v3 payload and the Deposit Wallet payload are different: > > | Wallet Type | `signatureType` | Payload to sign | `signed_order.signature` | > | - | - | - | - | > | Deposit Wallet | `3` | `depositWalletTypedData` | ERC-7739-wrapped signature | > | Safe Wallet | `2` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | > | Proxy Wallet | `1` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | > | EOA | `0` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | > > The example below shows how to produce `signature` with Viem for both signing > paths. > > ```ts sign.ts theme={null} > import { privateKeyToAccount } from "viem/accounts"; > import { wrapDepositWalletSignature } from "./wrapDepositWalletSignature"; > > const signer = privateKeyToAccount(""); > > const signature = > signatureType === 3 > ? wrapDepositWalletSignature( > await signer.signTypedData(depositWalletTypedData), > depositWalletTypedData, > ) > : await signer.signTypedData(exchangeV3OrderTypedData); > ``` > > ```ts wrapDepositWalletSignature.ts theme={null} > import { > concatHex, > encodeAbiParameters, > keccak256, > toHex, > type Address, > type Hex, > } from "viem"; > import type { DepositWalletTypedData } from "./types"; > > const ORDER_TYPE = > "Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)"; > const EIP712_DOMAIN_TYPE = > "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; > > export function wrapDepositWalletSignature( > innerSignature: Hex, > depositWalletTypedData: DepositWalletTypedData, > ): Hex { > const order = depositWalletTypedData.message.contents; > const exchangeV3Domain = depositWalletTypedData.domain; > > const appDomainSeparator = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "bytes32" }, > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > ], > [ > keccak256(toHex(EIP712_DOMAIN_TYPE)), > keccak256(toHex(exchangeV3Domain.name)), > keccak256(toHex(exchangeV3Domain.version)), > BigInt(exchangeV3Domain.chainId), > exchangeV3Domain.verifyingContract, > ], > ), > ); > const contentsHash = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > { type: "address" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint8" }, > { type: "uint8" }, > { type: "uint256" }, > { type: "bytes32" }, > { type: "bytes32" }, > ], > [ > keccak256(toHex(ORDER_TYPE)), > BigInt(order.salt), > order.maker, > order.signer, > BigInt(order.tokenId), > BigInt(order.makerAmount), > BigInt(order.takerAmount), > order.side, > order.signatureType, > BigInt(order.timestamp), > order.metadata, > order.builder, > ], > ), > ); > > return concatHex([ > innerSignature, > appDomainSeparator, > contentsHash, > toHex(ORDER_TYPE), > toHex(ORDER_TYPE.length, { size: 2 }), > ]); > } > ``` > > ```ts types.ts theme={null} > import type { Address, Hex } from "viem"; > > export type DepositWalletTypedData = { > domain: { > name: string; > version: string; > chainId: number; > verifyingContract: Address; > }; > message: { > contents: { > salt: string; > maker: Address; > signer: Address; > tokenId: string; > makerAmount: string; > takerAmount: string; > side: number; > signatureType: number; > timestamp: string; > metadata: Hex; > builder: Hex; > }; > }; > types: Record; > primaryType: "TypedDataSign"; > }; > ``` > > **5. Submit the Quote** > > Before `submission_deadline`, submit the RFQ ID, quote price, fillable size, and > signed order. Add the signature from the previous step as > `signed_order.signature`. > > ```json WebSocket theme={null} > { > "type": "RFQ_QUOTE", > "rfq_id": "", > "price_e6": "450000", > "size_e6": "1000000", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "450000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "signature": "" > } > } > ``` > > ```bash REST theme={null} > curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/quotes" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -d '{ > "quote_id": "", > "rfq_id": "", > "signer_address": "", > "maker_address": "", > "signature_type": 3, > "price_e6": "450000", > "size_e6": "1000000", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "450000", > "takerAmount": "1000000", > "side": 0, > "signatureType": 3, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "signature": "" > } > }' > ``` > > > [!NOTE] > > > > REST submissions require a client-generated `quote_id`. Use an opaque unique > > value; the RFQ system uses the `quote_` prefix followed by 32 lowercase hex > > characters. > > **6. Store the Quote Reference** > > After submitting a quote, store the RFQ ID and quote ID together. WebSocket > submissions receive both values in the acknowledgement. REST submissions return > the current RFQ snapshot, so use the client-generated `quote_id` from the request. > > ```json WebSocket theme={null} > { > "type": "ACK_RFQ_QUOTE", > "rfq_id": "", > "quote_id": "" > } > ``` > > ```json REST theme={null} > { > "request": { > "rfq_id": "" > // … > }, > "status": "COLLECTING_QUOTES", > "competition_started_at": 1780963200000, > "competition_ends_at": 1780963200400 > } > ``` > > This reference identifies the submitted quote. ### Quote Partial Fills > [tab] TypeScript > > If you only want to fill part of the requested size, pass `size` with the quote. > `size` is a normalized decimal value: `"10"` means 10 shares, or 10,000,000 base > units. When omitted, the SDK quotes the full requested size. > > ```ts theme={null} > await event.quote({ > price: "0.45", > size: "10", > }); > ``` > [tab] Python > > If you only want to fill part of the requested size, pass `size` with the quote. > `size` is a `Decimal`-compatible value: `Decimal("10")` means 10 shares, or > 10,000,000 base units. When omitted, the SDK quotes the full requested size. > > ```python theme={null} > from decimal import Decimal > > > await event.quote( > price=Decimal("0.45"), > size=Decimal("10"), > ) > ``` > [tab] API > > Partial fills use the same signed-order flow as a full quote. > > **1. Determine the Quote Size** > > Start by converting `requested_size` into the full request size in share base > units. > > | `requested_size.unit` | Full request size | > | - | - | > | `notional` | `floor(requested_size.value_e6 * 1000000 / price)` | > | `shares` | `requested_size.value_e6` | > > Choose a partial `size` in share base units that is smaller than the full request > size. > > **2. Build the Partial Order** > > Compute the signed order amounts from the partial `size`. > > | Quote Request | Token | `makerAmount` | `takerAmount` | > | - | - | - | - | > | `SELL` YES | `yes_position_id` | `ceil(price * size / 1000000)` | `size` | > | `BUY` YES | `no_position_id` | `ceil((1000000 - price) * size / 1000000)` | `size` | > > This example quotes half of a `1` share request at `0.45` pUSD per share, so > `size = 500000`: > > ```json SELL Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "225000", > "takerAmount": "500000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > ```json BUY Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "275000", > "takerAmount": "500000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > **3. Sign and Submit the Quote** > > Sign the partial order, then submit the quote. > > ```json theme={null} > { > "type": "RFQ_QUOTE", > "rfq_id": "", > "price_e6": "450000", > "size_e6": "500000", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "225000", > "takerAmount": "500000", > "side": 0, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "signature": "" > } > } > ``` ### Use Inventory > [tab] TypeScript > > By default, quotes use collateral (pUSD) to buy YES or NO tokens as needed to > satisfy the quote request according to the combinatorial position logic. Pass > `source: "inventory"` when you want to quote from existing inventory instead. > > ```ts theme={null} > await event.quote({ > price: "0.45", > source: "inventory", > }); > ``` > [tab] Python > > By default, quotes use collateral (pUSD) to buy YES or NO tokens as needed to > satisfy the quote request according to the combinatorial position logic. Pass > `source=RfqQuoteSource.INVENTORY` when you want to quote from existing inventory > instead. > > ```python theme={null} > from decimal import Decimal > > from polymarket import RfqQuoteSource > > > await event.quote( > price=Decimal("0.45"), > source=RfqQuoteSource.INVENTORY, > ) > ``` > [tab] API > > Inventory quotes sell existing outcome tokens instead of spending collateral. The > RFQ quote price still means pUSD per YES Combo share. > > **1. Choose the Inventory Token** > > Use the token you already hold for the side of the quote request. > > | Quote Request | Inventory Token | Order Side | > | - | - | - | > | `BUY` YES | `yes_position_id` | SELL | > | `SELL` YES | `no_position_id` | SELL | > > **2. Build the Inventory Order** > > Compute the signed order amounts from the inventory `size`. > > | Quote Request | Order Price | `makerAmount` | `takerAmount` | > | - | - | - | - | > | `BUY` YES | `price` | `size` | `floor(price * size / 1000000)` | > | `SELL` YES | `1000000 - price` | `size` | `floor((1000000 - price) * size / 1000000)` | > > This example quotes `1` share at `0.45` pUSD per share, so `price = 450000` and > `size = 1000000`: > > ```json BUY Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "1000000", > "takerAmount": "450000", > "side": 1, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > ```json SELL Request theme={null} > { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "1000000", > "takerAmount": "550000", > "side": 1, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > ``` > > **3. Sign and Submit the Quote** > > Sign the inventory order, then submit the quote. > > ```json theme={null} > { > "type": "RFQ_QUOTE", > "rfq_id": "", > "price_e6": "450000", > "size_e6": "1000000", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "1000000", > "takerAmount": "450000", > "side": 1, > "signatureType": 3, // > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "signature": "" > } > } > ``` ### Cancel Quotes After you submit a quote, keep the returned quote reference. If your price, inventory, or risk changes before the quote is selected, use that reference to request cancellation. > [!NOTE] > > A cancellation acknowledgement means the RFQ system processed the cancellation > request. It does not guarantee the quote was withdrawn from an RFQ that was > already selected. > [tab] TypeScript > > **1. Store the Quote Reference** > > First, keep the quote reference returned by `event.quote(…)`. It contains the > `rfqId` and `quoteId` needed to cancel the quote. > > ```ts theme={null} > const reference = await event.quote({ price: 0.45 }); > > // reference.rfqId: RfqId > // reference.quoteId: RfqQuoteId > ``` > > **2. Cancel the Quote** > > Then, pass that reference to `session.cancelQuote(…)` on the same live RFQ > session. > > ```ts theme={null} > if (shouldCancelQuote) { > const ack = await session.cancelQuote(reference); > > // ack.rfqId: RfqId > // ack.quoteId: RfqQuoteId > } > ``` > [tab] Python > > **1. Store the Quote Reference** > > First, keep the quote reference returned by `event.quote(...)`. It contains the > `rfq_id` and `quote_id` needed to cancel the quote. > > ```python theme={null} > from decimal import Decimal > > > reference = await event.quote(price=Decimal("0.45")) > > # reference.rfq_id: RfqId > # reference.quote_id: RfqQuoteId > ``` > > **2. Cancel the Quote** > > Then, pass that reference to `session.cancel_quote(...)` on the same live RFQ > session. > > ```python theme={null} > if should_cancel_quote: > ack = await session.cancel_quote(reference) > > # ack.rfq_id: RfqId > # ack.quote_id: RfqQuoteId > ``` > [tab] API > > Send a cancellation request with the RFQ ID and quote ID. On the WebSocket, the > RFQ system acknowledges a processed cancellation request with > `ACK_RFQ_QUOTE_CANCEL`. > > ```json Send theme={null} > { > "type": "RFQ_QUOTE_CANCEL", > "rfq_id": "", > "quote_id": "", > "signer_address": "", > "maker_address": "" > } > ``` > > ```json Receive theme={null} > { > "type": "ACK_RFQ_QUOTE_CANCEL", > "rfq_id": "", > "quote_id": "" > } > ``` > > Alternatively, cancel the quote through the REST API. > > ```bash Request theme={null} > curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/quotes/cancel" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -d '{ > "rfq_id": "", > "quote_id": "", > "signer_address": "", > "maker_address": "", > "signature_type": 3 > }' > ``` > > ```json Response theme={null} > { > "request": { > "rfq_id": "" > // … > }, > "status": "COLLECTING_QUOTES", > "competition_started_at": 1780963200000, > "competition_ends_at": 1780963200400 > } > ``` ### Last Look Last Look is a separate final review step for makers that have it enabled. If a selected quote requires Last Look, run a final risk check before the deadline and accept or reject the fill. Last Look is offered to makers with approximately \$2,500 in Combo notional volume and an established line of communication with Polymarket. This keeps the program reliable and helps Polymarket resolve system issues quickly. To request access, complete the [Last Look request form](https://forms.gle/dk5A1DRw8EN5uP9z5). > [!WARNING] > > Makers are expected to accept most selected quotes. We track acceptance rates, > and makers who reject more than 15% of selected quotes over a one-hour > lookback window may be paused from quoting for a few minutes. Once access is enabled, your quoting system will immediately be asked to review selected fills. Make sure it is ready to evaluate and answer them before approval is activated. > [tab] TypeScript > > **1. Switch on the Event Type** > > First, switch on `event.type` to handle confirmation requests from the same > session stream. > > ```ts theme={null} > switch (event.type) { > case "confirmation_request": > // event: RfqConfirmationRequestEvent > void handleConfirmationRequest(event); > break; > > // … > } > ``` > > **2. Inspect the Confirmation Request** > > Then, inspect the confirmation request before running your final risk check. It > includes the selected quote, the final fill size, and the `event.confirmBy` > deadline for your Last Look response. > > ```ts theme={null} > type RfqConfirmationRequestEvent = { > type: "confirmation_request"; > rfqId: RfqId; > quoteId: RfqQuoteId; > conditionId: ComboConditionId; > direction: RfqDirection; > side: RfqSide.Yes; > price: DecimalString; > fillSize: DecimalString; > yesPositionId: PositionId; > noPositionId: PositionId; > legPositionIds: PositionId[]; > confirmBy: EpochMilliseconds; > confirm(): Promise; > decline(): Promise; > }; > ``` > > **3. Confirm or Decline** > > Finally, run your final risk check outside the session loop and respond before > the `event.confirmBy` deadline. > > ```ts theme={null} > async function handleConfirmationRequest(event: RfqConfirmationRequestEvent) { > const canStillFill = runFinalRiskCheck(event); > > if (canStillFill) { > await event.confirm(); > return; > } > > await event.decline(); > } > ``` > [tab] Python > > **1. Check Event Type** > > First, use `isinstance(...)` to handle confirmation requests from the same > session stream. > > ```python theme={null} > from polymarket import RfqConfirmationRequestEvent > > > async for event in session: > if isinstance(event, RfqConfirmationRequestEvent): > await handle_confirmation_request(event) > ``` > > **2. Inspect the Confirmation Request** > > Then, inspect the confirmation request before running your final risk check. It > includes the selected quote, the final fill size, and the `event.confirm_by` > deadline for your Last Look response. > > ```python theme={null} > class RfqConfirmationRequestEvent: > type: "confirmation_request" > rfq_id: RfqId > quote_id: RfqQuoteId > signer_address: EvmAddress > maker_address: EvmAddress > signature_type: int > condition_id: ComboConditionId > direction: RfqDirection > side: RfqSide > price: Decimal > fill_size: Decimal > yes_position_id: PositionId > no_position_id: PositionId > leg_position_ids: tuple[PositionId, ...] > confirm_by: int > > async def confirm(self) -> RfqConfirmationAck: ... > async def decline(self) -> RfqConfirmationAck: ... > ``` > > **3. Confirm or Decline** > > Finally, run your final risk check outside the session loop and respond before > the `event.confirm_by` deadline. > > ```python theme={null} > from polymarket import RfqConfirmationRequestEvent > > > async def handle_confirmation_request( > event: RfqConfirmationRequestEvent, > ) -> None: > can_still_fill = run_final_risk_check(event) > > if can_still_fill: > await event.confirm() > return > > await event.decline() > ``` > [tab] API > > If Last Look is enabled for your maker, the RFQ WebSocket sends > `RFQ_CONFIRMATION_REQUEST` after your quote is selected. > > ```json theme={null} > { > "type": "RFQ_CONFIRMATION_REQUEST", > "rfq_id": "", > "quote_id": "", > "signer_address": "", > "maker_address": "", > "signature_type": 3, // > "leg_position_ids": ["", ""], > "condition_id": "", > "yes_position_id": "", > "no_position_id": "", > "direction": "BUY", > "side": "YES", > "fill_size_e6": "1000000", > "price_e6": "450000", > "confirm_by": 1780963200000 > } > ``` > > Respond before `confirm_by` with `CONFIRM` or `DECLINE`. > > ```json Confirm theme={null} > { > "type": "RFQ_CONFIRMATION_RESPONSE", > "rfq_id": "", > "quote_id": "", > "decision": "CONFIRM" > } > ``` > > ```json Decline theme={null} > { > "type": "RFQ_CONFIRMATION_RESPONSE", > "rfq_id": "", > "quote_id": "", > "decision": "DECLINE" > } > ``` > > The RFQ system acknowledges the response with > `ACK_RFQ_CONFIRMATION_RESPONSE`. > > ```json theme={null} > { > "type": "ACK_RFQ_CONFIRMATION_RESPONSE", > "rfq_id": "", > "quote_id": "", > "decision": "CONFIRM" > } > ``` > > Do not include `signer_address`, `maker_address`, or `signature_type` in > `RFQ_CONFIRMATION_RESPONSE`. The RFQ system applies identity from the > authenticated session. > > Alternatively, send the Last Look decision through the REST API. The response > returns `execution` when your confirmation completes the bundle. If the RFQ is > still waiting on another maker confirmation, or if you decline, it returns > `snapshot`. > > ```bash Request theme={null} > curl -X POST "https://combos-rfq-api.polymarket.com/v1/maker/confirmations" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -d '{ > "rfq_id": "", > "quote_id": "", > "signer_address": "", > "maker_address": "", > "signature_type": 3, > "decision": "CONFIRM" > }' > ``` > > ```json Execution Response theme={null} > { > "execution": { > "execution_id": "", > "quote_id": "", > "request": { > "rfq_id": "" > } > } > } > ``` > > ```json Snapshot Response theme={null} > { > "snapshot": { > "request": { > "rfq_id": "" > }, > "status": "AWAITING_MAKER_CONFIRMATION" > } > } > ``` ## Manage Combo Positions Use Combo position workflows to manage inventory throughout the quote lifecycle. > [!TIP] > > Quoting can leave pUSD locked across related Combo positions. Use [Collateral > Return](/trading/combos/collateral-return) to release available pUSD before > resolution while preserving unmatched exposure. ### List Combo Positions List Combo positions as part of your background inventory sync. Keep this state fresh outside the quote path. > [!NOTE] > > Default listings omit open positions with a share balance below 0.001, such as > dust left after a sell-all cashout. Resolved positions are always returned, > and incremental sync requests return every position regardless of balance. > [tab] TypeScript > > Use `client.listComboPositions(...)` to page through Combo positions for the > authenticated account. > > ```ts theme={null} > import { ComboPositionStatus, type ComboPosition } from "@polymarket/client"; > > const pages = client.listComboPositions({ > status: ComboPositionStatus.Open, > pageSize: 50, > }); > > for await (const page of pages) { > for (const position of page.items) { > // position: ComboPosition > } > } > ``` > > You can filter positions by the following criteria. `conditionId` accepts one > Combo condition ID or an array of Combo condition IDs. > > ```ts Condition ID theme={null} > const pages = client.listComboPositions({ > conditionId: ["", ""], > }); > ``` > > ```ts Status theme={null} > const pages = client.listComboPositions({ > status: ComboPositionStatus.Open, > }); > ``` > > ```ts Incremental Sync theme={null} > import { ComboPositionSortBy, SortDirection } from "@polymarket/client"; > > const pages = client.listComboPositions({ > updatedAfter: lastWatermarkSeconds, > sortBy: ComboPositionSortBy.Updated, > sortDirection: SortDirection.Asc, > pageSize: 1000, > }); > ``` > > Each returned item is a `ComboPosition`. > > > [accordion] Output: ComboPosition > > > > ```ts ComboPosition Type theme={null} > > type ComboPosition = { > > conditionId: ComboConditionId; > > positionId: PositionId; > > outcomeIndex: number; > > outcomeLabel: string; > > wallet: EvmAddress; > > currentSize: DecimalString; > > entryAvgPriceUsdc: DecimalString; > > entryCostUsdc: DecimalString; > > grossEntryCostUsdc: DecimalString; > > entryFeesUsdc: DecimalString; > > realizedPayoutUsdc: DecimalString; > > status: ComboPositionStatus; > > redeemable: boolean; > > firstEntryAt: IsoDateTimeString; > > resolvedAt?: IsoDateTimeString | null; > > updatedAt: IsoDateTimeString; > > legsTotal: number; > > legsResolved: number; > > legsPending: number; > > legs: ComboPositionLeg[]; > > }; > > ``` > > > > ```ts ComboPositionLeg Type theme={null} > > type ComboPositionLeg = { > > legIndex: number; > > legPositionId: PositionId; > > legConditionId: ConditionId; > > legOutcomeIndex: number; > > legOutcomeLabel?: string | null; > > legStatus: ComboPositionStatus; > > legResolvedAt?: IsoDateTimeString | null; > > legCurrentPrice?: DecimalString | null; > > market?: ComboPositionMarket | null; > > }; > > ``` > > > > ```ts ComboPositionMarket Type theme={null} > > type ComboPositionMarket = { > > marketId?: string | null; > > slug?: string | null; > > title?: string | null; > > question?: string | null; > > groupItemTitle?: string | null; > > sportsMarketType?: string | null; > > line?: number | null; > > outcomes?: string[] | null; > > outcome?: string | null; > > imageUrl?: string | null; > > iconUrl?: string | null; > > category?: string | null; > > subcategory?: string | null; > > tags?: string[] | null; > > endDate?: IsoDateTimeString | null; > > event?: ComboPositionMarketEvent | null; > > }; > > ``` > > > > ```ts ComboPositionMarketEvent Type theme={null} > > type ComboPositionMarketEvent = { > > eventId?: string | null; > > eventSlug?: string | null; > > eventTitle?: string | null; > > eventImage?: string | null; > > }; > > ``` > > After redemption, `currentSize` is zero and the entry basis remains. > `grossEntryCostUsdc` is the exact fee-inclusive basis. Net result is > `realizedPayoutUsdc - grossEntryCostUsdc`. The fee-exclusive basis is > `grossEntryCostUsdc - entryFeesUsdc`. `entryCostUsdc` is the rounded > weighted-average display basis. > [tab] Python > > Call `list_combo_positions()` on an existing `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_combo_positions(status="OPEN", page_size=50) > > async for page in pages: > # page.items: tuple[ComboPosition, ...] > pass > ``` > > Filter by Combo condition or update time. > > ```python Condition ID theme={null} > pages = client.list_combo_positions( > condition_id=["", ""], > ) > ``` > > ```python Status theme={null} > pages = client.list_combo_positions( > status=["OPEN", "PARTIAL"], > ) > ``` > > ```python Incremental Sync theme={null} > pages = client.list_combo_positions( > updated_after=last_watermark_seconds, > sort_by="UPDATED", > sort_direction="ASC", > page_size=1000, > ) > ``` > > `condition_id` accepts one Combo condition ID or a sequence. `"REDEEMABLE"` must be the only status when selected. Update bounds accept epoch seconds or timezone-aware `datetime` values. Zero is a valid bound. > > > [accordion] Output: ComboPosition > > > > ```python ComboPositionMarketEvent Type theme={null} > > class ComboPositionMarketEvent: > > event_id: EventId | None > > event_slug: str | None > > event_title: str | None > > event_image: str | None > > ``` > > > > ```python ComboPositionMarket Type theme={null} > > class ComboPositionMarket: > > market_id: MarketId | None > > slug: str | None > > title: str | None > > question: str | None > > group_item_title: str | None > > sports_market_type: str | None > > line: Decimal | None > > outcomes: tuple[str, ...] | None > > outcome: str | None > > image_url: str | None > > icon_url: str | None > > category: str | None > > subcategory: str | None > > tags: tuple[str, ...] | None > > end_date: datetime | None > > event: ComboPositionMarketEvent | None > > ``` > > > > ```python ComboPositionLeg Type theme={null} > > class ComboPositionLeg: > > leg_index: int > > leg_position_id: PositionId > > leg_condition_id: ConditionId > > leg_outcome_index: int > > leg_outcome_label: str | None > > leg_status: ComboPositionStatus > > leg_resolved_at: datetime | None > > leg_current_price: Decimal | None > > market: ComboPositionMarket | None > > ``` > > > > ```python ComboPosition Type theme={null} > > class ComboPosition: > > condition_id: ComboConditionId > > position_id: PositionId > > wallet: EvmAddress > > outcome_index: int > > outcome_label: str > > current_size: Decimal > > entry_avg_price_usdc: Decimal > > entry_cost_usdc: Decimal > > gross_entry_cost_usdc: Decimal > > entry_fees_usdc: Decimal > > realized_payout_usdc: Decimal > > status: ComboPositionStatus > > redeemable: bool > > first_entry_at: datetime > > resolved_at: datetime | None > > updated_at: datetime > > legs_total: int > > legs_resolved: int > > legs_pending: int > > legs: tuple[ComboPositionLeg, ...] > > ``` > > After redemption, `current_size` is zero and the entry basis remains. `gross_entry_cost_usdc` is the fee-inclusive basis. Net result is `realized_payout_usdc - gross_entry_cost_usdc`. The fee-exclusive basis is `gross_entry_cost_usdc - entry_fees_usdc`. `entry_cost_usdc` is the rounded weighted-average basis. > [tab] API > > Use the Data API to list Combo positions for a wallet. > > ```bash theme={null} > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "limit=50" \ > --data-urlencode "status=OPEN" > ``` > > You can filter positions by the following query parameters: > > ```bash Condition ID theme={null} > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "condition=" > ``` > > ```bash Status theme={null} > # One status, or several comma-separated. Valid values: OPEN, REDEEMABLE, > # PARTIAL, RESOLVED_WIN, RESOLVED_LOSS, RESOLVED_PARTIAL. > # REDEEMABLE must be used alone; combining it with another status is a 400. > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "status=OPEN" > > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "status=RESOLVED_WIN,RESOLVED_PARTIAL,RESOLVED_LOSS" > ``` > > The response returns Combo positions in `data` and pagination metadata in > `pagination`. Each leg carries enriched market and event metadata (trimmed > here): > > ```json theme={null} > { > "data": [ > { > "combo_condition_id": "", > "combo_position_id": "", > "outcome_index": 0, > "outcome_label": "Yes", > "proxy_wallet": "", > "current_size": 10, > "entry_avg_price_usdc": 0.45, > "entry_cost_usdc": 4.5, > "gross_entry_cost_usdc": 4.59, > "entry_fees_usdc": 0.09, > "realized_payout_usdc": 0, > "status": "OPEN", > "redeemable": false, > "first_entry_at": "2026-06-08T00:00:00Z", > "resolved_at": null, > "updated_at": "2026-06-08T00:00:00Z", > "legs_total": 2, > "legs_resolved": 0, > "legs_pending": 2, > "legs": [ > { > "leg_index": 0, > "leg_position_id": "", > "leg_condition_id": "", > "leg_outcome_index": 0, > "leg_outcome_label": "Yes", > "leg_status": "OPEN", > "leg_resolved_at": null, > "leg_current_price": 0.52, > "market": { > "market_id": "", > "title": "", > "outcomes": ["Yes", "No"], > "event": { "event_id": "" } > } > } > ] > } > ], > "pagination": { > "limit": 50, > "offset": 0, > "has_more": true, > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJjb21ib19wb3NpdGlvbnMi…" > } > } > ``` > > `gross_entry_cost_usdc` and `entry_fees_usdc` carry the exact entry basis at > six-decimal grain: gross includes attributed BUY fees (SELL fees are > excluded), and the exact fee-exclusive basis is `gross_entry_cost_usdc − > entry_fees_usdc`. `entry_cost_usdc` remains the rounded weighted-average > display basis; do not reconstruct gross as `entry_cost_usdc + > entry_fees_usdc`. > > Use `cursor` from `pagination.next_cursor` to fetch the next page. Keep the > same filters; the cursor binds them, and a follow-up page that contradicts > them returns a `400`. A `null` cursor means there are no more pages. > > ```bash Cursor theme={null} > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "limit=100" \ > --data-urlencode "sort_by=FIRST_ENTRY" \ > --data-urlencode "cursor=" > ``` > > Use `updated_after` with `sort_by=UPDATED` and `sort_direction=ASC` to > incrementally sync changed positions. Store the newest `updated_at` you > process as your next watermark; the bound is inclusive, so boundary rows may > re-deliver — upsert by `(combo_condition_id, combo_position_id)`. > > ```bash Incremental sync theme={null} > curl -G "https://data-api.polymarket.com/v2/positions/combos" \ > --data-urlencode "user=" \ > --data-urlencode "updated_after=" \ > --data-urlencode "sort_by=UPDATED" \ > --data-urlencode "sort_direction=ASC" \ > --data-urlencode "limit=1000" > ``` > > For redeemed positions, `current_size` tracks remaining inventory, so it reads > zero after a winning Combo is redeemed. The entry fields keep the original > basis: gross redemption proceeds accrue to `realized_payout_usdc`, and the net > result is `realized_payout_usdc − gross_entry_cost_usdc`. ### List Combo Activity Use Combo activity when you need an audit trail for inventory-changing events, including splits, merges, conversions, wraps, unwraps, and redeems. Use Combo positions for current inventory state. > [tab] TypeScript > > Use `client.listComboActivity(...)` to page through Combo lifecycle activity for > the authenticated account. > > ```ts theme={null} > import { ComboActivityType, type ComboActivity } from "@polymarket/client"; > > const pages = client.listComboActivity({ pageSize: 50 }); > > for await (const page of pages) { > for (const item of page.items) { > // item: ComboActivity > if (item.type === ComboActivityType.Redeem) { > console.log(item.positionId, item.payout); > } > } > } > ``` > > Filter to one or more Combos with `conditionId`. > > ```ts theme={null} > const pages = client.listComboActivity({ > conditionId: ["", ""], > }); > ``` > > > [accordion] Output: ComboActivity > > > > ```ts ComboActivity Union theme={null} > > type ComboActivity = > > | ComboSplitActivity > > | ComboMergeActivity > > | ComboConvertActivity > > | ComboCompressActivity > > | ComboWrapActivity > > | ComboUnwrapActivity > > | ComboRedeemActivity; > > ``` > > > > ```ts ComboRedeemActivity Type theme={null} > > type ComboRedeemActivity = { > > id: ComboActivityId; > > type: ComboActivityType.Redeem; > > wallet: EvmAddress; > > conditionId: ComboConditionId; > > positionId: PositionId; > > amount: DecimalString | null; > > timestamp: EpochMilliseconds; > > transactionHash: TxHash; > > blockNumber: number; > > legs: ComboPositionLeg[]; > > payout: DecimalString | null; > > }; > > ``` > > Every `ComboActivity` includes `positionId` and a `timestamp` in epoch > milliseconds. Only `type: ComboActivityType.Redeem` carries `payout`. > The other variants have the same common fields. > [tab] Python > > Call `list_combo_activity()` on an existing `AsyncSecureClient`. > > ```python theme={null} > pages = client.list_combo_activity(page_size=50) > > async for page in pages: > for item in page.items: > if item.type == "REDEEM": > position_id = item.position_id > payout = item.payout > ``` > > Filter to one or more Combos with `condition_id`. > > ```python theme={null} > pages = client.list_combo_activity( > condition_id=["", ""], > ) > ``` > > > [accordion] Output: ComboActivity > > > > ```python ComboActivity Union theme={null} > > ComboActivity = ( > > ComboSplitActivity > > | ComboMergeActivity > > | ComboConvertActivity > > | ComboCompressActivity > > | ComboWrapActivity > > | ComboUnwrapActivity > > | ComboRedeemActivity > > ) > > ``` > > > > ```python ComboRedeemActivity Type theme={null} > > class ComboRedeemActivity: > > id: ComboActivityId > > wallet: EvmAddress > > condition_id: ComboConditionId > > position_id: PositionId > > amount: Decimal | None > > timestamp: datetime > > transaction_hash: TransactionHash > > block_number: int > > legs: tuple[ComboPositionLeg, ...] > > type: Literal[ComboActivityType.REDEEM] > > payout: Decimal | None > > ``` > > Every `ComboActivity` includes `position_id` and a timezone-aware `timestamp`. Only the `"REDEEM"` variant carries `payout`. The other variants share the common fields. > [tab] API > > Use the Data API to list Combo lifecycle activity for a wallet. > > ```bash theme={null} > curl -G "https://data-api.polymarket.com/v2/activity/combos" \ > --data-urlencode "user=" \ > --data-urlencode "limit=50" > ``` > > Filter to specific Combos with `condition`, which accepts comma-separated > `combo_condition_id` values (at most 20 distinct). > > ```bash Filter by Combo theme={null} > curl -G "https://data-api.polymarket.com/v2/activity/combos" \ > --data-urlencode "user=" \ > --data-urlencode "condition=," > ``` > > The response returns lifecycle events in `data` and pagination metadata in > `pagination`. Each leg carries enriched market and event metadata (trimmed > here): > > ```json theme={null} > { > "data": [ > { > "id": "-", > "type": "SPLIT", > "proxy_wallet": "", > "combo_condition_id": "", > "combo_position_id": "", > "amount_usdc": 10.0, > "payout_usdc": null, > "timestamp": 1783379945, > "block_number": 89783300, > "transaction_hash": "", > "legs": [ > { > "leg_index": 0, > "leg_position_id": "", > "leg_condition_id": "", > "leg_outcome_index": 0, > "leg_outcome_label": "Yes", > "leg_status": "OPEN", > "leg_resolved_at": null, > "leg_current_price": 0.52, > "market": { > "market_id": "", > "title": "", > "outcomes": ["Yes", "No"], > "event": { "event_id": "" } > } > } > ] > } > ], > "pagination": { > "limit": 50, > "offset": 0, > "has_more": true, > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJjb21ib19hY3Rpdml0eSI…" > } > } > ``` > > Use `cursor` from `pagination.next_cursor` to fetch the next page, re-sending > the same filters on every page. A `null` cursor means there are no more pages. > > ```bash Cursor theme={null} > curl -G "https://data-api.polymarket.com/v2/activity/combos" \ > --data-urlencode "user=" \ > --data-urlencode "limit=50" \ > --data-urlencode "cursor=" > ``` ### Inventory Management If you want to quote from inventory, build the inventory before quote requests arrive. Splitting converts collateral into complementary Combo positions for a set of legs. Merging converts matching complementary Combo positions back into collateral. > [!NOTE] > > Splitting and merging manage complementary inventory directly. When capital is > locked across related positions that cannot be merged as-is, use [Collateral > Return](/trading/combos/collateral-return). > [tab] TypeScript > > Use `client.splitPosition(...)` with `legs` to create Combo inventory from > collateral. `amount` is in pUSD base units. > > ```ts theme={null} > const split = await client.splitPosition({ > amount: 10_000_000n, > legs: ["", ""], > }); > > const splitOutcome = await split.wait(); > > // splitOutcome.transactionHash identifies the confirmed split transaction. > ``` > > Use `client.mergePositions(...)` with the same `legs` to merge complementary > Combo positions back into collateral. Pass `amount: "max"` to merge the largest > matching amount available. > > ```ts theme={null} > const merge = await client.mergePositions({ > amount: "max", > legs: ["", ""], > }); > > const mergeOutcome = await merge.wait(); > > // mergeOutcome.transactionHash identifies the confirmed merge transaction. > ``` > [tab] Python > > Use `client.split_position(...)` with `legs` to create Combo inventory from > collateral. `amount` is in pUSD base units. > > ```python theme={null} > split = await client.split_position( > amount=10_000_000, > legs=["", ""], > ) > > split_outcome = await split.wait() > > # split_outcome.transaction_hash identifies the confirmed split transaction. > ``` > > Use `client.merge_positions(...)` with the same `legs` to merge complementary > Combo positions back into collateral. Pass `amount="max"` to merge the largest > matching amount available. > > ```python theme={null} > merge = await client.merge_positions( > amount="max", > legs=["", ""], > ) > > merge_outcome = await merge.wait() > > # merge_outcome.transaction_hash identifies the confirmed merge transaction. > ``` > [tab] API > > Use the Relayer API to split or merge Combo inventory by sending an ordered list > of encoded contract calls in one batch. The following steps assume you are using > a Deposit Wallet. > > > [!NOTE] > > > > If you use a Safe or Proxy Wallet, use one of the SDKs instead because those > > wallet integrations require wallet-specific signing and encoding. > > Use these contract addresses when building the call list. > > | Contract | Address | > | - | - | > | CombinatorialModule | `0x30000034706c7d8e12009dab006be20000c031a8` | > | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > | pUSD collateral token | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > > **1. Check Approvals** > > First, determine whether the inventory action needs an approval. If approval is > already in place, skip this step. > > For a split, `` must approve pUSD spending by the Router. For a > merge, `` must approve the Router as a PositionManager ERC-1155 > operator. > > ```solidity ERC-20 Approval theme={null} > function approve(address spender, uint256 amount) returns (bool); > ``` > > ```solidity ERC-1155 Approval theme={null} > function setApprovalForAll(address operator, bool approved); > ``` > > Encode one of these approval calls when needed. Keep the resulting call object; > it will be added before the Combo calls in the next step. > > ```json Split Approval Call theme={null} > [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > } > ] > ``` > > ```json Merge Approval Call theme={null} > [ > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > } > ] > ``` > > **2. Build the Call List** > > Then, add the Combo call objects to the ordered list. > > For a split, include `prepareCondition` before `split`. `prepareCondition` is > idempotent, so it is safe to include even when the Combo condition was already > prepared. For a merge, call `merge` directly with the Combo condition ID for the > positions being merged. > > ```solidity theme={null} > function prepareCondition(uint256[] legs) returns (bytes31); > function split(bytes31 conditionId, uint256 amount); > function merge(bytes31 conditionId, uint256 amount); > ``` > > Append these encoded calls after the approval call from the previous step, if one > was needed. > > ```json Split Combo Calls theme={null} > [ > // Include the approval call first when needed. > // … > { > "target": "0x30000034706c7d8e12009dab006be20000c031a8", > "value": "0", > "data": "" > }, > { > "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", > "value": "0", > "data": "" > } > ] > ``` > > ```json Merge Combo Calls theme={null} > [ > // Include the approval call first when needed. > // … > { > "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", > "value": "0", > "data": "" > } > ] > ``` > > **3. Fetch the Nonce** > > Fetch a fresh `WALLET` nonce before each submission. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the nonce to sign with the transaction. > > ```json theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **4. Build the EIP-712 Batch** > > Build the Deposit Wallet EIP-712 `Batch` typed data. > > ```json theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > // Use the final calls array from the previous steps. > // … > ] > } > } > ``` > > Sign the EIP-712 batch with your signer. Use the resulting signature as > `signature` in the relayer submission. > > **5. Submit the Transaction** > > Submit the signed transaction to the Relayer API. > > ```bash Split theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Split Combo position", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > // Use the final calls array from the previous steps. > // … > ] > } > }' > ``` > > ```bash Merge theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Merge Combo positions", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > // Use the final calls array from the previous steps. > // … > ] > } > }' > ``` > > The response includes the relayer transaction ID. > > ```json theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **6. Poll the Transaction** > > Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying on > the updated inventory. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" > ``` > > ```json theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. ### Redeem Resolved Positions When a Combo position resolves, redeem the winning position to settle it back to collateral. > [tab] TypeScript > > Use `client.redeemPositions(...)` with a Combo `positionId`. The SDK redeems the > available balance for that resolved position. > > ```ts theme={null} > const redeem = await client.redeemPositions({ > positionId: "", > }); > > const redeemOutcome = await redeem.wait(); > > // redeemOutcome.transactionHash identifies the confirmed redemption transaction. > ``` > > You can list resolved winning positions first, then redeem each one. > > ```ts theme={null} > import { ComboPositionStatus } from "@polymarket/client"; > > const pages = client.listComboPositions({ > status: ComboPositionStatus.ResolvedWin, > }); > > for await (const page of pages) { > for (const position of page.items) { > const redeem = await client.redeemPositions({ > positionId: position.positionId, > }); > > await redeem.wait(); > } > } > ``` > [tab] Python > > Use `client.redeem_positions(...)` with a Combo `position_id`. The SDK redeems > the available balance for that resolved position. > > ```python theme={null} > redeem = await client.redeem_positions( > position_id="", > ) > > redeem_outcome = await redeem.wait() > > # redeem_outcome.transaction_hash identifies the confirmed redemption transaction. > ``` > > You can list resolved winning positions first, then redeem each one. > > ```python theme={null} > pages = client.list_combo_positions(status="RESOLVED_WIN") > > async for position in pages.iter_items(): > redeem = await client.redeem_positions( > position_id=position.position_id, > ) > > await redeem.wait() > ``` > [tab] API > > Use the Relayer API to redeem resolved Combo positions by sending an ordered list > of encoded contract calls in one batch. The following steps assume you are using > a Deposit Wallet. > > > [!NOTE] > > > > If you use a Safe or Proxy Wallet, use one of the SDKs instead because those > > wallet integrations require wallet-specific signing and encoding. > > | Contract | Address | > | - | - | > | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > > **1. Check Approval** > > First, determine whether `` has approved the Router as a > PositionManager ERC-1155 operator. If approval is already in place, skip this > step. > > ```solidity theme={null} > function setApprovalForAll(address operator, bool approved); > ``` > > Encode the approval call when needed. The approval call becomes the first object > in the final `calls` array. > > ```json theme={null} > [ > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > } > ] > ``` > > **2. Determine Redeem Inputs** > > Set the Router inputs for the redemption. > > | Value | Source | > | - | - | > | `conditionId` | `` | > | `outcomeIndex` | `0` for YES, `1` for NO | > | `amount` | Shares to redeem, in share base units | > > The Router accepts `conditionId`, `outcomeIndex`, and `amount`, not `positionId`. > > **3. Build the Call List** > > The Router redeem function is: > > ```solidity theme={null} > function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount); > ``` > > Append the redeem call after the approval call from the previous step, if one was > needed. > > ```json Redeem Calls theme={null} > [ > // Include the approval call first when needed. > // … > { > "target": "0x12121212006e4CD160D18e3f00711DA5c3372600", > "value": "0", > "data": "" > } > ] > ``` > > **4. Fetch the Nonce** > > Fetch a fresh `WALLET` nonce before each submission. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "address=$RELAYER_API_KEY_ADDRESS" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the nonce to sign with the transaction. > > ```json theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **5. Build the EIP-712 Batch** > > Build the Deposit Wallet EIP-712 `Batch` typed data. > > ```json theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > // Use the final calls array from the previous steps. > // … > ] > } > } > ``` > > Sign the EIP-712 batch with your signer. Use the resulting signature as > `signature` in the relayer submission. > > **6. Submit the Transaction** > > Submit the signed transaction to the Relayer API. > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Redeem Combo position", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > // Use the final calls array from the previous steps. > // … > ] > } > }' > ``` > > The response includes the relayer transaction ID. > > ```json theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **7. Poll the Transaction** > > Poll the relayer transaction until it reaches `STATE_CONFIRMED` before relying on > the redeemed balance. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" > ``` > > ```json theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. ## Get Combo Markets Use the Combo markets catalog to retrieve active markets that can be used as Combo legs. Markets are ordered by volume descending. > [tab] TypeScript > > Use `client.listComboMarkets(...)` to page through markets that can be used as > Combo legs. > > ```ts theme={null} > const pages = client.listComboMarkets({ pageSize: 50 }); > > for await (const page of pages) { > // page.items: ComboMarket[] > } > ``` > > Use `exclude` to omit markets you have already shown or selected. > > ```ts theme={null} > const pages = client.listComboMarkets({ > exclude: selectedConditionIds, > pageSize: 50, > }); > ``` > > The SDK returns structured YES and NO outcomes. > > ```ts theme={null} > type ComboMarket = { > id: MarketId; > conditionId: CtfConditionId; > slug: string; > title: string; > outcomes: { > yes: { > label: string; > positionId: PositionId; > price: DecimalString; > }; > no: { > label: string; > positionId: PositionId; > price: DecimalString; > }; > }; > image: string; > volume: number; > tags: string[]; > }; > ``` > [tab] Python > > Use `client.list_combo_markets(...)` to page through markets that can be used as > Combo legs. > > ```python theme={null} > pages = client.list_combo_markets(page_size=50) > > async for market in pages.iter_items(): > print(market.title, market.outcomes.yes.position_id) > ``` > > Use `exclude` to omit markets you have already shown or selected. > > ```python theme={null} > pages = client.list_combo_markets( > exclude=selected_condition_ids, > page_size=50, > ) > ``` > > The SDK returns structured YES and NO outcomes with snake_case fields. > > ```python theme={null} > yes_position_id = market.outcomes.yes.position_id > yes_price = market.outcomes.yes.price > no_position_id = market.outcomes.no.position_id > no_price = market.outcomes.no.price > ``` > [tab] API > > Fetch the first page of Combo-enabled markets. > > ```bash theme={null} > curl -G "https://combos-rfq-api.polymarket.com/v1/rfq/combo-markets" \ > --data-urlencode "limit=50" > ``` > > Use `cursor` to fetch the next page, and use `exclude` to omit markets you have > already shown or selected. > > ```bash theme={null} > curl -G "https://combos-rfq-api.polymarket.com/v1/rfq/combo-markets" \ > --data-urlencode "limit=50" \ > --data-urlencode "cursor=" \ > --data-urlencode "exclude=," > ``` > > The response includes markets and an opaque `next_cursor`. A `null` cursor means > there are no more pages. > > ```json theme={null} > { > "markets": [ > { > "id": "1897034", > "condition_id": "0x4cd7...110ff", > "position_ids": ["1012585...362880", "1012585...362881"], > "slug": "fifwc-mex-rsa-2026-06-11-mex", > "title": "Will Mexico win on 2026-06-11?", > "outcomes": ["Yes", "No"], > "outcome_prices": ["0.685", "0.315"], > "image": "https://...", > "volume": 330327.7128580074, > "tags": ["sports", "soccer", "games", "world-cup"] > } > ], > "next_cursor": "Mg" > } > ``` > > For each market, `position_ids`, `outcomes`, and `outcome_prices` are aligned by > array index. Index `0` is the YES outcome, and index `1` is the NO outcome. ## Map Legs to Markets Before quote requests arrive, index Combo-enabled markets by their outcomes' position IDs so your pricing system can map each leg back to market data. > [tab] TypeScript > > Fetch non-closed markets and index Combo-enabled markets by position ID in your > own market data store. > > ```ts theme={null} > import { ComboKnownStatus } from "@polymarket/client"; > > const pages = client.listMarkets({ closed: false }); > > for await (const page of pages) { > for (const market of page.items) { > if (market.state.comboStatus !== ComboKnownStatus.Enabled) continue; > > for (const outcome of [market.outcomes.yes, market.outcomes.no]) { > if (outcome.positionId != null) { > marketByPositionId.set(outcome.positionId, market); > } > } > } > } > ``` > > | Enum member | Meaning | > | - | - | > | `ComboKnownStatus.Pending` | Polymarket plans to enable the market for Combos. Prepare your quoting system for the market. It may appear in an RFQ before it is enabled. | > | `ComboKnownStatus.Enabled` | The market is enabled for Combos and may be quoted. | > | `ComboKnownStatus.Disabled` | The market is not enabled for Combos. Exclude it from quoting. | > > You can also fetch markets by leg position ID on demand, but most market makers > will want this context ready before the **400 ms** quote window starts. > > ```ts theme={null} > const pages = client.listMarkets({ > positionIds: event.legPositionIds, > }); > ``` > [tab] Python > > Fetch non-closed markets and index Combo-enabled markets by position ID in your > own market data store. > > ```python theme={null} > pages = client.list_markets(closed=False) > > async for market in pages.iter_items(): > if market.state.combo_status != "enabled": > continue > > for outcome in (market.outcomes.yes, market.outcomes.no): > if outcome.position_id is not None: > market_by_position_id[outcome.position_id] = market > ``` > > Read Combo status from `market.state.combo_status`. The `ComboStatus` type > includes these known string values: > > | Value | Meaning | > | - | - | > | `"pending"` | Polymarket plans to enable the market for Combos. Prepare your quoting system for the market. It may appear in an RFQ before it is enabled. | > | `"enabled"` | The market is enabled for Combos and may be quoted. | > | `"disabled"` | The market is not enabled for Combos. Exclude it from quoting. | > > You can also fetch markets by leg position ID on demand, but most market makers > will want this context ready before the **400 ms** quote window starts. > > ```python theme={null} > pages = client.list_markets( > position_ids=event.leg_position_ids, > ) > ``` > [tab] API > > Use Gamma `GET /markets/keyset` to resolve Combo leg position IDs into market > metadata. Build this mapping outside the quote path. > > ```bash theme={null} > curl -G "https://gamma-api.polymarket.com/markets/keyset" \ > --data-urlencode "closed=false" \ > --data-urlencode "combo_status=enabled" \ > --data-urlencode "limit=100" > ``` > > Index every returned market by `positionIds`. > > ```json theme={null} > { > "id": "", > "conditionId": "", > "question": "Will example happen?", > "positionIds": ["", ""], > "comboStatus": "enabled" > } > ``` > > Use `comboStatus` to decide whether to prepare the market for quoting. The field > has these known string values: > > | Value | Meaning | > | - | - | > | `"pending"` | Polymarket plans to enable the market for Combos. Prepare your quoting system for the market. It may appear in an `RFQ_REQUEST` before it is enabled. | > | `"enabled"` | The market is enabled for Combos and may be quoted. | > | `"disabled"` | The market is not enabled for Combos. Exclude it from quoting. | > > You can also resolve markets by leg position ID on demand, but avoid doing this > inside the **400 ms** quote window. > > ```bash theme={null} > curl -G "https://gamma-api.polymarket.com/markets/keyset" \ > --data-urlencode "position_ids=" \ > --data-urlencode "position_ids=" > ``` ## Listen to Execution Updates Execution updates tell you what happened after one of your quotes was selected. Use them to reconcile RFQ state, transaction hashes, and terminal execution outcomes in your own systems. > [tab] TypeScript > > **1. Switch on the Event Type** > > First, switch on `event.type` to handle execution updates from the same session > stream. > > ```ts theme={null} > switch (event.type) { > case "execution_update": > // event: RfqExecutionUpdateEvent > handleExecutionUpdate(event); > break; > > // … > } > ``` > > **2. Inspect the Execution Update** > > Then, inspect the execution update before reconciling the selected RFQ. Execution > updates are correlated by `rfqId`. > > ```ts theme={null} > type RfqExecutionUpdateEvent = { > type: "execution_update"; > rfqId: RfqId; > status: RfqExecutionStatus; > txHash?: TxHash; > }; > ``` > > where `RfqExecutionStatus` could be: > > | Status | Meaning | > | - | - | > | `RfqExecutionStatus.Matched` | The quote was selected and handed off to execute. | > | `RfqExecutionStatus.Mined` | The execution transaction was mined. | > | `RfqExecutionStatus.Retrying` | Execution is being retried. | > | `RfqExecutionStatus.Confirmed` | Execution completed successfully. | > | `RfqExecutionStatus.Failed` | Execution failed. | > > **3. Reconcile Execution State** > > Finally, persist the update and treat `RfqExecutionStatus.Confirmed` and > `RfqExecutionStatus.Failed` as terminal states. > > ```ts theme={null} > function handleExecutionUpdate(event: RfqExecutionUpdateEvent) { > storeExecutionUpdate(event); > > if (event.status === RfqExecutionStatus.Confirmed) { > markQuoteConfirmed(event.rfqId); > return; > } > > if (event.status === RfqExecutionStatus.Failed) { > markQuoteFailed(event.rfqId); > } > } > ``` > [tab] Python > > **1. Check Event Type** > > First, use `isinstance(...)` to handle execution updates from the same session > stream. > > ```python theme={null} > from polymarket import RfqExecutionUpdateEvent > > > async for event in session: > if isinstance(event, RfqExecutionUpdateEvent): > handle_execution_update(event) > ``` > > **2. Inspect the Execution Update** > > Then, inspect the execution update before reconciling the selected RFQ. Execution > updates are correlated by `rfq_id`. > > ```python theme={null} > class RfqExecutionUpdateEvent: > type: "execution_update" > rfq_id: RfqId > status: RfqExecutionStatus > tx_hash: TransactionHash | None > ``` > > where `RfqExecutionStatus` could be: > > | Status | Meaning | > | - | - | > | `RfqExecutionStatus.MATCHED` | The quote was selected and handed off to execute. | > | `RfqExecutionStatus.MINED` | The execution transaction was mined. | > | `RfqExecutionStatus.RETRYING` | Execution is being retried. | > | `RfqExecutionStatus.CONFIRMED` | Execution completed successfully. | > | `RfqExecutionStatus.FAILED` | Execution failed. | > > **3. Reconcile Execution State** > > Finally, persist the update and treat `RfqExecutionStatus.CONFIRMED` and > `RfqExecutionStatus.FAILED` as terminal states. > > ```python theme={null} > from polymarket import RfqExecutionStatus, RfqExecutionUpdateEvent > > > def handle_execution_update(event: RfqExecutionUpdateEvent) -> None: > store_execution_update(event) > > if event.status is RfqExecutionStatus.CONFIRMED: > mark_quote_confirmed(event.rfq_id) > return > > if event.status is RfqExecutionStatus.FAILED: > mark_quote_failed(event.rfq_id) > ``` > [tab] API > > Listen for `RFQ_EXECUTION_UPDATE` messages on the RFQ WebSocket after one of your > quotes is selected. > > ```json theme={null} > { > "type": "RFQ_EXECUTION_UPDATE", > "rfq_id": "", > "status": "MINED", > "tx_hash": "" > } > ``` > > Execution updates are correlated by `rfq_id`. > > | Status | Meaning | > | - | - | > | `MATCHED` | The quote was selected and handed off to execute. | > | `MINED` | The execution transaction was mined. | > | `RETRYING` | Execution is being retried. | > | `CONFIRMED` | Execution completed successfully. | > | `FAILED` | Execution failed. | > > Treat `CONFIRMED` and `FAILED` as terminal states. ## Listen to Trade Broadcasts Confirmed trade broadcasts tell connected market makers when any Combo RFQ trade has completed successfully. Use them to build a public trade tape, update risk, or reconcile market activity that was filled by another maker. Trade broadcasts are best-effort and may be replayed after reconnects. Deduplicate them by RFQ ID: `rfqId` in TypeScript or `rfq_id` in Python and raw WebSocket messages. > [tab] TypeScript > > **1. Switch on the Event Type** > > First, switch on `event.type` to handle trade broadcasts from the same session > stream. > > ```ts theme={null} > switch (event.type) { > case "trade": > // event: RfqTradeEvent > handleTrade(event); > break; > > // … > } > ``` > > **2. Inspect the Trade** > > Then, inspect the confirmed trade before storing or applying it. Trade broadcasts > exclude maker identity and per-maker fill allocations. > > ```ts theme={null} > type RfqTradeEvent = { > type: "trade"; > rfqId: RfqId; > requesterId: RfqRequestorPublicId; > conditionId: ComboConditionId; > legPositionIds: PositionId[]; > direction: RfqDirection; > side: RfqSide.Yes; > price: DecimalString; > size: DecimalString; > executedAt: EpochMilliseconds; > }; > ``` > > `price` is the accepted blended price in pUSD per YES Combo share. `size` is the > matched Combo share size. Both values are normalized decimal strings. > > **3. Store the Trade** > > Finally, persist the trade by RFQ ID and execution timestamp for downstream > reconciliation. > > ```ts theme={null} > function handleTrade(event: RfqTradeEvent) { > storeComboTrade({ > rfqId: event.rfqId, > conditionId: event.conditionId, > legPositionIds: event.legPositionIds, > requesterId: event.requesterId, > price: event.price, > size: event.size, > executedAt: event.executedAt, > }); > } > ``` > [tab] Python > > **1. Check Event Type** > > First, use `isinstance(...)` to handle trade broadcasts from the same session > stream. > > ```python theme={null} > from polymarket import RfqTradeEvent > > > async for event in session: > if isinstance(event, RfqTradeEvent): > handle_trade(event) > ``` > > **2. Inspect the Trade** > > Then, inspect the confirmed trade before storing or applying it. Trade broadcasts > exclude maker identity and per-maker fill allocations. > > ```python theme={null} > from decimal import Decimal > > > class RfqTradeEvent: > type: "trade" > rfq_id: RfqId > requester_id: RfqRequestorPublicId > condition_id: ComboConditionId > leg_position_ids: tuple[PositionId, ...] > direction: RfqDirection > side: RfqSide > price: Decimal > size: Decimal > executed_at: int > ``` > > `price` is the accepted blended price in pUSD per YES Combo share. `size` is the > matched Combo share size. Both values are `Decimal` instances. > > **3. Store the Trade** > > Finally, persist the trade by RFQ ID and execution timestamp for downstream > reconciliation. > > ```python theme={null} > from polymarket import RfqTradeEvent > > > def handle_trade(event: RfqTradeEvent) -> None: > store_combo_trade( > rfq_id=event.rfq_id, > condition_id=event.condition_id, > leg_position_ids=event.leg_position_ids, > requester_id=event.requester_id, > price=event.price, > size=event.size, > executed_at=event.executed_at, > ) > ``` > [tab] API > > Listen for `RFQ_TRADE` messages on the RFQ WebSocket after Combo executions are > confirmed. These messages are sent to authenticated quoter sessions and exclude > maker identity and per-maker fill allocations. > > ```json theme={null} > { > "type": "RFQ_TRADE", > "rfq_id": "", > "requester_id": "", > "condition_id": "", > "leg_position_ids": ["", ""], > "direction": "BUY", > "side": "YES", > "price_e6": "125000", > "size_e6": "800000", > "executed_at": 1780854786039 > } > ``` > > `price_e6` is the accepted blended price in 6-decimal base units, and `size_e6` > is the matched Combo share size in 6-decimal base units. ## Handle Errors In this section, we will talk you through how to handle errors with the RFQ system. > [tab] TypeScript > > ### Open the RFQ Session > > Wrap `client.openRfqSession()` in `try`/`catch` and use > `OpenRfqSessionError.isError(…)` to narrow the error type. > > ```ts theme={null} > try { > const session = await client.openRfqSession(); > } catch (error) { > if (!OpenRfqSessionError.isError(error)) throw error; > > switch (error.name) { > case "ConnectionLostError": > // error: ConnectionLostError > // error.code: WebSocketCloseCode > // error.reason: string > break; > case "TransportError": > // error: TransportError > break; > } > } > ``` > > ### Submit a Quote > > Wrap `event.quote(…)` in `try`/`catch` and use `RfqQuoteError.isError(…)` to > narrow the error type. > > ```ts theme={null} > import { RfqKnownErrorCode } from "@polymarket/client"; > > try { > const reference = await event.quote({ price }); > // … > } catch (error) { > if (!RfqQuoteError.isError(error)) throw error; > > switch (error.name) { > case "RfqQuoteRejectedError": > // error: RfqQuoteRejectedError > // error.rfqId: RfqId > // error.code: RfqErrorCode | undefined > switch (error.code) { > case RfqKnownErrorCode.QuotedPriceAboveSafetyThreshold: > // Lower the price passed to event.quote(…). > break; > default: > // Handle every other known or unknown code as a quote rejection. > break; > } > break; > case "ConnectionLostError": > // error: ConnectionLostError > // error.code: WebSocketCloseCode > // error.reason: string > break; > case "SigningError": > // error: SigningError > break; > case "TimeoutError": > // error: TimeoutError > break; > case "TransportError": > // error: TransportError > break; > case "UserInputError": > // error: UserInputError > break; > } > } > ``` > > Invalid price and size values throw `UserInputError` before the SDK sends the > quote. `QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD` is the RFQ rejection tied directly > to `price`. Codes about quote contents or the signed order usually indicate a > client configuration problem or SDK issue. Codes for missing server-assigned > quote or identity values indicate an RFQ system failure. > > ### Cancel a Quote > > Wrap `session.cancelQuote(…)` in `try`/`catch` and use > `RfqCancelQuoteError.isError(…)` to narrow the error type. > > ```ts theme={null} > try { > const ack = await session.cancelQuote(reference); > // … > } catch (error) { > if (!RfqCancelQuoteError.isError(error)) throw error; > > switch (error.name) { > case "RfqCancelQuoteRejectedError": > // error: RfqCancelQuoteRejectedError > // error.rfqId: RfqId > // error.quoteId: RfqQuoteId > // error.code: RfqErrorCode | undefined > break; > case "ConnectionLostError": > // error: ConnectionLostError > // error.code: WebSocketCloseCode > // error.reason: string > break; > case "TimeoutError": > // error: TimeoutError > break; > case "TransportError": > // error: TransportError > break; > } > } > ``` > > ### Confirm or Decline > > Wrap `event.confirm()` or `event.decline()` in `try`/`catch` and use > `RfqConfirmationError.isError(…)` to narrow the error type. > > ```ts theme={null} > try { > if (canStillFill) { > await event.confirm(); > } else { > await event.decline(); > } > } catch (error) { > if (!RfqConfirmationError.isError(error)) throw error; > > switch (error.name) { > case "RfqConfirmationRejectedError": > // error: RfqConfirmationRejectedError > // error.rfqId: RfqId > // error.quoteId: RfqQuoteId > // error.code: RfqErrorCode | undefined > break; > case "ConnectionLostError": > // error: ConnectionLostError > // error.code: WebSocketCloseCode > // error.reason: string > break; > case "TimeoutError": > // error: TimeoutError > break; > case "TransportError": > // error: TransportError > break; > } > } > ``` > [tab] Python > > ### Open the RFQ Session > > Wrap `client.open_rfq_session()` in `try`/`except` and catch SDK exception types. > > ```python theme={null} > from polymarket import ConnectionLostError, TimeoutError, TransportError > > > try: > async with client.open_rfq_session() as session: > async for event in session: > ... > except ConnectionLostError as error: > # error.code: int > # error.reason: str > ... > except TimeoutError as error: > # error: TimeoutError > ... > except TransportError as error: > # error: TransportError > ... > ``` > > ### Submit a Quote > > Wrap `event.quote(...)` in `try`/`except` and catch the typed RFQ rejection, > timeout, and transport errors. > > ```python theme={null} > from decimal import Decimal > > from polymarket import ( > ConnectionLostError, > RfqErrorCode, > RfqQuoteRejectedError, > TimeoutError, > TransportError, > UserInputError, > ) > > > try: > reference = await event.quote(price=Decimal("0.45")) > except RfqQuoteRejectedError as error: > # error.rfq_id: RfqId > # error.code: RfqErrorCode | str | None > if error.code == RfqErrorCode.QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD: > # Lower the price passed to event.quote(...). > ... > else: > # Handle every other known or unknown code as a quote rejection. > ... > except UserInputError: > # Invalid price or size is rejected before the quote is sent. > ... > except ConnectionLostError as error: > # error.code: int > # error.reason: str > ... > except TimeoutError as error: > # error: TimeoutError > ... > except TransportError as error: > # error: TransportError > ... > ``` > > Invalid price and size values raise `UserInputError` before the SDK sends the > quote. `QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD` is the RFQ rejection tied directly > to `price`. Codes about quote contents or the signed order usually indicate a > client configuration problem or SDK issue. Codes for missing server-assigned > quote or identity values indicate an RFQ system failure. > > ### Cancel a Quote > > Wrap `session.cancel_quote(...)` in `try`/`except` and catch the typed RFQ > cancellation rejection, timeout, and transport errors. > > ```python theme={null} > from polymarket import ( > ConnectionLostError, > RfqCancelQuoteRejectedError, > TimeoutError, > TransportError, > ) > > > try: > ack = await session.cancel_quote(reference) > except RfqCancelQuoteRejectedError as error: > # error.rfq_id: RfqId > # error.quote_id: RfqQuoteId > # error.code: RfqErrorCode | str | None > ... > except ConnectionLostError as error: > # error.code: int > # error.reason: str > ... > except TimeoutError as error: > # error: TimeoutError > ... > except TransportError as error: > # error: TransportError > ... > ``` > > ### Confirm or Decline > > Wrap `event.confirm()` or `event.decline()` in `try`/`except` and catch the typed > RFQ confirmation rejection, timeout, and transport errors. > > ```python theme={null} > from polymarket import ( > ConnectionLostError, > RfqConfirmationRejectedError, > TimeoutError, > TransportError, > ) > > > try: > if can_still_fill: > await event.confirm() > else: > await event.decline() > except RfqConfirmationRejectedError as error: > # error.rfq_id: RfqId > # error.quote_id: RfqQuoteId > # error.code: RfqErrorCode | str | None > ... > except ConnectionLostError as error: > # error.code: int > # error.reason: str > ... > except TimeoutError as error: > # error: TimeoutError > ... > except TransportError as error: > # error: TransportError > ... > ``` > [tab] API > > When a WebSocket command fails validation or cannot be applied, the RFQ system > sends `RFQ_ERROR`. > > ```json theme={null} > { > "type": "RFQ_ERROR", > "request_type": "RFQ_QUOTE", > "rfq_id": "", > "quote_id": "", > "code": "SUBMISSION_WINDOW_CLOSED", > "error": "submission window closed" > } > ``` > > Use `request_type`, `rfq_id`, and `quote_id` to correlate the error with the > command you sent. > > | Field | Description | > | - | - | > | `type` | Always `RFQ_ERROR` | > | `request_type` | Inbound command that failed, when parsed | > | `rfq_id` | RFQ ID, when present on the failed command | > | `quote_id` | Quote ID, when present on the failed command | > | `code` | Stable machine-readable error code | > | `error` | Human-readable detail for logging and debugging | > > The `request_type` value identifies the command that failed. > > | `request_type` | Failed command | > | - | - | > | `RFQ_QUOTE` | Quote submission | > | `RFQ_QUOTE_CANCEL` | Quote cancellation | > | `RFQ_CONFIRMATION_RESPONSE` | Last Look confirmation or decline | > > `code` is stable, so branch on it rather than parsing the `error` text. Quote > submissions return the shared command errors plus their own validation codes. > For quote-validation failures, check `price_e6` and `size_e6` first, then inspect > the matching field in `signed_order`. > > For WebSocket quote submissions, the RFQ system assigns `quote_id` and applies > signer and maker identity from the authenticated session. Do not add those > fields to `RFQ_QUOTE` requests. Codes indicating that one is missing represent > an RFQ system failure rather than invalid caller input. > > Most `RFQ_ERROR` messages reject only the referenced command. > `UNAUTHORIZED_ROLE` and `ADDRESS_MISMATCH` are terminal and close the WebSocket. ### Error Code Reference When an RFQ rejection includes a code, its value is stable across integrations. New codes may be introduced over time, so handle unrecognized values as rejections rather than assuming this list is exhaustive. > [accordion] Common RFQ Error Codes > > | Code | Meaning | > | - | - | > | `INVALID_MESSAGE` | Request or action type is invalid | > | `UNAUTHORIZED_ROLE` | Action is not allowed for the authenticated role | > | `ADDRESS_MISMATCH` | Request identity does not match the authenticated session | > | `UNKNOWN_RFQ` | RFQ ID is not active or no longer exists | > | `EXPIRED_RFQ` | RFQ has expired | > | `SUBMISSION_WINDOW_CLOSED` | Quote arrived after the submission window closed | > | `ALLOWANCE_VALIDATION_FAILED` | Maker allowance is insufficient for the quoted order | > | `BALANCE_VALIDATION_FAILED` | Maker balance is insufficient for the quoted order | > | `PRE_EXECUTION_BALANCE_RESERVATION_FAILED` | Balance reservation failed before execution | > | `INVALID_QUOTE` | Quote is invalid and no more specific code applies | > | `INVALID_SIGNATURE` | Signed order signature could not be verified | > | `INVALID_RFQ_STATE` | RFQ is not in a state that accepts the requested command | > | `INVALID_CONFIRMATION` | Last Look response is invalid | > | `MAKER_NOT_REQUIRED` | This quote maker is not required for last-look confirmation | > | `MAKER_ALREADY_RESPONDED` | This quote maker already responded to the confirmation request | > | `MAKER_QUOTE_LIMITED` | Quote submissions from this maker are temporarily limited | > | `SERVICE_UNAVAILABLE` | RFQ system is temporarily unavailable | > [accordion] Quote Validation Codes > > | Code | Meaning | > | - | - | > | `MISSING_QUOTE_ID` | Server-generated quote identifier was not assigned | > | `MISSING_RFQ_ID` | RFQ identifier is missing from the quote | > | `MISSING_SIGNER_ADDRESS_IN_QUOTE` | Authenticated signer identity was not applied | > | `MISSING_MAKER_ADDRESS_IN_QUOTE` | Authenticated maker identity was not applied | > | `PRICE_E6_NOT_POSITIVE` | Quote price is not positive | > | `SIZE_E6_NOT_POSITIVE` | Quote size is not positive | > | `MISSING_SALT_IN_SIGNED_ORDER` | Signed order is missing its salt | > | `MISSING_MAKER_IN_SIGNED_ORDER` | Signed order is missing its maker | > | `MISSING_SIGNER_IN_SIGNED_ORDER` | Signed order is missing its signer | > | `MISSING_TOKEN_ID_IN_SIGNED_ORDER` | Signed order is missing its token identifier | > | `MISSING_MAKER_AMOUNT_IN_SIGNED_ORDER` | Signed order is missing its maker amount | > | `MISSING_TAKER_AMOUNT_IN_SIGNED_ORDER` | Signed order is missing its taker amount | > | `MISSING_TIMESTAMP_IN_SIGNED_ORDER` | Signed order is missing its timestamp | > | `MISSING_SIGNATURE_IN_SIGNED_ORDER` | Signed order is missing its signature | > | `INVALID_ORDER_SIDE` | Signed order uses an invalid side | > | `INVALID_SIGNATURE_TYPE` | Signed order uses an unsupported signature type | > | `SIGNED_ORDER_SIGNER_DOES_NOT_MATCH_AUTH` | Signed-order signer differs from the authenticated signer | > | `SIGNED_ORDER_MAKER_DOES_NOT_MATCH_AUTH` | Signed-order maker differs from the authenticated maker | > | `SIGNED_ORDER_SIGNATURE_TYPE_DOES_NOT_MATCH_AUTH` | Signed-order signature type differs from the authenticated type | > | `QUOTED_PRICE_ABOVE_SAFETY_THRESHOLD` | BUY quote exceeds the `0.90909` safety maximum | > | `QUOTED_PRICE_OUT_OF_RANGE` | Quote price exceeds `1` | > | `ORDER_SIDE_OR_TOKEN_DOES_NOT_MATCH_REQUEST` | Signed-order side or token does not match the RFQ direction | > | `SIGNED_ORDER_MAKER_AMOUNT_NOT_POSITIVE` | Signed-order maker amount is not a positive integer | > | `SIGNED_ORDER_TAKER_AMOUNT_NOT_POSITIVE` | Signed-order taker amount is not a positive integer | > | `SIGNED_ORDER_SIZE_DOES_NOT_COVER_QUOTE` | Signed order cannot cover the quoted size | > | `SIGNED_ORDER_PRICE_WORSE_THAN_QUOTE` | Signed-order limit price is worse than the quoted price | ### Common Footguns When quoting Combos, account for these pricing and data risks: 1. It is of course possible to receive requests where legs are correlated, and an extremely common case of this is same-game combos: for example, if a user requests a combo of the moneyline (certain team to win) and the total number of points scored in the game. Another case that may happen is duplicated events stemming from upstream provider issues -- these events may have 100% correlation and must be accounted for in pricing. 2. Oftentimes, it is not sufficient to use the midpoint of the CLOB orderbook as a "true indicator" of probability of an outcome. Since placing liquidity on orderbooks is open to anyone, this can be problematic to use as a reference price. Be vigilant on quoting illiquid markets. 3. Markets may resolve 50-50 as outlined in the rules of each market, or by clarification. The payout for a YES combo position is the product of the outcome of each individual leg -- if each individual leg resolves 1, then the combo resolves to 1, and can be redeemed for 1 pUSD. If one leg resolves to 0.5, and all others resolve to 1, then that YES combo can be redeemed for `(1 * 1 * 1...) * 0.5 = 0.5`. A NO combo can be redeemed for the complement to the redeemable value of a YES combo. For example, if a YES combo share can be redeemed for 0.25 (perhaps it's two legs resolved to 0.5 each), then the corresponding NO combo share would be redeemable for `1 - 0.25 = 0.75`. Price the likelihood of a leg resolving to 50-50 accordingly. 4. Consider implementing risk thresholds on maximum exposure to a particular outcome. 5. Pending Combo legs may still reach your quoting session. Decide whether they meet your quoting criteria before responding; see [Map Legs to Markets](#map-legs-to-markets) for surface-specific detection guidance. 6. Sports events' home and away assignments can change after markets are created, especially when games are rescheduled or moved. Before quoting, verify Polymarket's assignments and live scores against the external sports data used by your pricing system. Remember that as with all trading, RFQs you choose to quote and fill are your responsibility to vet. # How Combos Work Source: https://docs.polymarket.com/trading/combos/overview Understand Combo positions and the RFQ flow for multi-leg markets Combos combine two or more market outcomes into one YES and NO position pair. Each leg selects an outcome from a Combo-enabled market. The request for quote (RFQ) system enables quote-based Combo execution between two participants: Polymarket users (requesters) and market makers (quoters). A user creates a Request, which starts an auction among connected market makers. Market makers compete by submitting Quotes: executable prices they are willing to fill. ```mermaid theme={null} sequenceDiagram autonumber participant Requester as Polymarket User participant RFQ as RFQ System participant Quoter as Market Maker participant Execution as Execution Requester->>RFQ: Request a Combo price RFQ->>Quoter: Send quote request activate Quoter Note right of Quoter: 400 ms max Quoter->>RFQ: Submit executable price deactivate Quoter RFQ->>Requester: Return best quote activate Requester Note left of Requester: 10 seconds max Requester->>RFQ: Accept quote deactivate Requester opt Last Look enabled RFQ->>Quoter: Request Last Look confirmation activate Quoter Note right of Quoter: 1 second max Quoter->>RFQ: Confirm fill deactivate Quoter end RFQ->>Execution: Execute accepted Combo Execution-->>Requester: Send execution update Execution-->>Quoter: Send execution update RFQ-->>Quoter: Broadcast confirmed trade ``` 1. **User creates an unsigned Request** for a Combo price. 2. **RFQ system sends the Request** to connected market makers. 3. **Market makers submit signed Quotes** within the 400 ms submission window. 4. **RFQ system returns the best Quote** to the user. 5. **User accepts the Quote** by signing the trade within the 10-second acceptance window. 6. **RFQ system requests Last Look confirmation** when Last Look is enabled. 7. **Market maker confirms or declines** within the 1-second confirmation window. 8. **RFQ system executes the accepted Combo**. 9. **User receives execution updates**. 10. **Market maker receives execution updates**. 11. **Connected market makers receive confirmed trade broadcasts**. > [!NOTE] > > Combo position IDs are complementary to CLOB token IDs. A user can trade the > market on the CLOB or can include the market as a leg of a Combo. ## Build With Combos Integrate Combos into market maker systems or builder apps that request executable prices for users. > [card] [Market Makers](/trading/combos/market-makers) > > Build a market maker integration for pricing and executing Combos. > [card] [Builders](/trading/combos/builders) > > Request Combo quotes and execute accepted trades for users. # Requesters Source: https://docs.polymarket.com/trading/combos/requesters Request Combo quotes and execute accepted trades Use the Requester API to request executable Combo quotes, accept a winning quote, and track the trade through onchain execution. This guide walks through the complete workflow. > [!WARNING] > > Keep the CLOB API secret and passphrase on trusted infrastructure. Never > expose them in a browser or other untrusted client. ## Request and Execute a Quote > [tab] API > > The production gateway is > `https://combos-rfq-gateway-requester-api.polymarket.com`, with base path > `/v1/requester/rfq`. > > **1. Prepare the Trading Account** > > Create a Polymarket account, obtain its [CLOB API > credentials](/getting-started/api#authentication), and fund the account wallet. > Set up the wallet and trading approvals by following [Wallets and > Authentication](/trading/wallets-auth). > > Resolve the CLOB credential address, order signer, order maker, and signature > type for the account's wallet: > > | Wallet type | `signature_type` | `POLY_ADDRESS` | `signer_address` | `maker_address` | > | - | - | - | - | - | > | Deposit Wallet | `3` POLY_1271 | Account or session signer with CLOB credentials | Deposit Wallet address | Deposit Wallet address | > | Proxy Wallet | `1` Proxy | Account signer with CLOB credentials | Account signer | Proxy Wallet address | > | Safe Wallet | `2` Safe | Account signer with CLOB credentials | Account signer | Safe Wallet address | > | EOA | `0` EOA | Not supported | Not supported | Not supported | > > Both requester gateways reject EOA accounts. The Requester API returns > `UNSUPPORTED_REQUESTER_SIGNATURE_TYPE`; use a Deposit, Proxy, or Safe Wallet. > > **2. Sign Request Headers** > > Every request requires these CLOB L2 headers: > > * `POLY_ADDRESS` > * `POLY_API_KEY` > * `POLY_PASSPHRASE` > * `POLY_TIMESTAMP` > * `POLY_SIGNATURE` > > `POLY_ADDRESS` is the address associated with the CLOB API credentials. Use the > wallet identity values resolved in the previous step for the request body and > signed order. > > Compute `POLY_SIGNATURE` with HMAC-SHA256, using the base64-decoded CLOB secret > as the key. Sign an uppercase method, a Unix timestamp in seconds, the full > request path without the host or query string, and the exact serialized body > sent on the wire. Omit the body for `GET` requests. Encode the digest as > base64url with padding preserved. > > ```text theme={null} > HMAC-SHA256( > base64Decode(secret), > timestamp + HTTP_METHOD + FULL_REQUEST_PATH + REQUEST_BODY > ) > ``` > > Generate a fresh timestamp and signature for every request, including each > status poll. > > **3. Choose the Combo Legs** > > Fetch active Combo-enabled markets from the public catalog: > > ```bash theme={null} > curl -G "https://combos-rfq-api.polymarket.com/v1/rfq/combo-markets" \ > --data-urlencode "limit=50" > ``` > > The response contains a `markets` array and an opaque `next_cursor`. Pass the > cursor back as `cursor` to fetch the next page. For each market, > `position_ids`, `outcomes`, and `outcome_prices` are aligned by array index: > index `0` is YES and index `1` is NO. > > Choose 2–50 unique, mutually compatible outcome position IDs and pass them in > `leg_position_ids`. > > **4. Create the RFQ** > > Choose the request direction and size: > > * A BUY sets the maximum collateral budget, including fees. Use > `unit: "notional"`. > * A SELL specifies the number of Combo shares to sell. Use `unit: "shares"`. > > `value_e6` is a string in 6-decimal base units, and `side` must currently be > `"YES"`. The gateway holds the request until the quote competition finishes. > The examples below use a Deposit Wallet. The API accepts at most 15 create > requests per rolling minute for each `maker_address`; requests above that limit > return HTTP `429` with `RATE_LIMITED`. > > ```http BUY theme={null} > POST /v1/requester/rfq/requests > Content-Type: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > > { > "signer_address": "", > "maker_address": "", > "signature_type": 3, > "leg_position_ids": ["", ""], > "direction": "BUY", > "side": "YES", > "requested_size": { > "unit": "notional", > "value_e6": "1000000" > } > } > ``` > > ```http SELL theme={null} > POST /v1/requester/rfq/requests > Content-Type: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > > { > "signer_address": "", > "maker_address": "", > "signature_type": 3, > "leg_position_ids": ["", ""], > "direction": "SELL", > "side": "YES", > "requested_size": { > "unit": "shares", > "value_e6": "1000000" > } > } > ``` > > An executable response includes the server-owned RFQ ID, winning quote, and > acceptance deadline: > > > [accordion] Create RFQ Response > > > > ```json theme={null} > > { > > "rfq_id": "", > > "status": "AWAITING_REQUESTER_ACCEPTANCE", > > "expires_at": 1773890763000, > > "request": { > > "rfq_id": "", > > "maker_address": "", > > "requestor_public_id": "", > > "leg_position_ids": ["", ""], > > "condition_id": "", > > "yes_position_id": "", > > "no_position_id": "", > > "direction": "BUY", > > "side": "YES", > > "requested_size": { > > "unit": "notional", > > "value_e6": "1000000" > > }, > > "created_at": 1773890758000 > > }, > > "quote": { > > "quote_id": "", > > "blended_price_e6": "500000", > > "maker_amount_e6": "966191", > > "taker_amount_e6": "1932381", > > "total_required_e6": "1000000", > > "net_receive_e6": "1932381" > > } > > } > > ``` > > `expires_at` and `request.created_at` are Unix timestamps in milliseconds. The > acceptance window is five seconds from quote readiness. Sign and accept the > order before `expires_at`. `total_required_e6` is the exact balance required: > collateral including fees for BUY, or Combo shares for SELL. For BUY, > `net_receive_e6` is the Combo shares received. For SELL, it is the exact > collateral proceeds after fees. > > If no usable quote is available, the gateway returns HTTP `200` with a terminal > business outcome: > > ```json theme={null} > { > "rfq_id": "", > "status": "FAILED", > "error": { > "code": "NO_QUOTES", > "message": "no quotes" > } > } > ``` > > > [!WARNING] > > > > A local create timeout or lost connection has an unknown outcome. The RFQ may > > have been created even if you never received its server-owned ID. This API has > > no idempotency key or lookup for that case, and retrying may create another > > RFQ. > > **5. Build and Sign the Requester Order** > > Build an Exchange v3 order from the returned request and quote. Use Polygon > chain ID `137` and Exchange v3 contract > `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` for the EIP-712 domain. > > For both directions, copy `maker_amount_e6` to `makerAmount` and > `taker_amount_e6` to `takerAmount`, and use the returned Combo YES position ID > as `tokenId`. Set `side` to `0` for BUY or `1` for SELL. > > The `builder` field must be the zero bytes32 value. A non-zero value is rejected > with `BUILDER_ATTRIBUTION_NOT_ALLOWED`. This gateway does not support Builder > attribution. Approved builders that need orders attributed to their Builder > code must authenticate and submit them through the [Builder Gateway > workflow](/trading/combos/builders#request-and-execute-a-quote) instead. > > Use the same wallet identity selected when creating the RFQ. The wallet type > determines which payload to sign and how to encode `signed_order.signature`: > > | Wallet type | `signatureType` | Payload to sign | Submitted signature | > | - | - | - | - | > | Deposit Wallet | `3` | `depositWalletTypedData` | ERC-7739-wrapped signature | > | Proxy Wallet | `1` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | > | Safe Wallet | `2` | `exchangeV3OrderTypedData` | Standard 65-byte EVM signature | > > For a Deposit Wallet, wrap the Exchange v3 order in the Deposit Wallet's > `TypedDataSign` structure. Both `maker` and `signer` in `contents` are the > Deposit Wallet address. The account or session signer signs this outer payload. > > ```json Deposit Wallet Typed Data theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "3", > "chainId": 137, > "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" > }, > "types": { > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ], > "TypedDataSign": [ > { "name": "contents", "type": "Order" }, > { "name": "name", "type": "string" }, > { "name": "version", "type": "string" }, > { "name": "chainId", "type": "uint256" }, > { "name": "verifyingContract", "type": "address" }, > { "name": "salt", "type": "bytes32" } > ] > }, > "primaryType": "TypedDataSign", > "message": { > "contents": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "966191", > "takerAmount": "1932381", > "side": 0, > "signatureType": 3, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > }, > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "", > "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > For a Proxy or Safe Wallet, sign the Exchange v3 `Order` directly. Set `maker` > to the Proxy or Safe Wallet address, `signer` to the account signer, and > `signatureType` to `1` or `2`, respectively. > > ```json Proxy or Safe Wallet Typed Data theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "3", > "chainId": 137, > "verifyingContract": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" > }, > "types": { > "EIP712Domain": [ > { "name": "name", "type": "string" }, > { "name": "version", "type": "string" }, > { "name": "chainId", "type": "uint256" }, > { "name": "verifyingContract", "type": "address" } > ], > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ] > }, > "primaryType": "Order", > "message": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "966191", > "takerAmount": "1932381", > "side": 0, > "signatureType": 1, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > Sign the selected payload with the account or session signer. Deposit Wallets > must wrap the raw signature for ERC-7739 validation; Proxy and Safe Wallets > submit the signature returned by signing the Exchange `Order` directly. > > ```js Deposit Wallet theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const innerSignature = await signer.signTypedData(depositWalletTypedData); > const signature = wrapDepositWalletSignature( > depositWalletTypedData, > innerSignature, > ); > ``` > > ```js Proxy or Safe Wallet theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const signature = await signer.signTypedData(exchangeV3OrderTypedData); > ``` > > ```js wrapDepositWalletSignature() theme={null} > import { concatHex, encodeAbiParameters, keccak256, toHex } from "viem"; > > const ORDER_TYPE = > "Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)"; > const EIP712_DOMAIN_TYPE = > "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; > > function wrapDepositWalletSignature(typedData, innerSignature) { > const order = typedData.message.contents; > const exchangeDomain = typedData.domain; > > const appDomainSeparator = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "bytes32" }, > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > ], > [ > keccak256(toHex(EIP712_DOMAIN_TYPE)), > keccak256(toHex(exchangeDomain.name)), > keccak256(toHex(exchangeDomain.version)), > BigInt(exchangeDomain.chainId), > exchangeDomain.verifyingContract, > ], > ), > ); > const contentsHash = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > { type: "address" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint8" }, > { type: "uint8" }, > { type: "uint256" }, > { type: "bytes32" }, > { type: "bytes32" }, > ], > [ > keccak256(toHex(ORDER_TYPE)), > BigInt(order.salt), > order.maker, > order.signer, > BigInt(order.tokenId), > BigInt(order.makerAmount), > BigInt(order.takerAmount), > order.side, > order.signatureType, > BigInt(order.timestamp), > order.metadata, > order.builder, > ], > ), > ); > > return concatHex([ > innerSignature, > appDomainSeparator, > contentsHash, > toHex(ORDER_TYPE), > toHex(ORDER_TYPE.length, { size: 2 }), > ]); > } > ``` > > **6. Accept the Quote** > > Submit the signed order with the winning `quote_id` before the returned > `expires_at` deadline. > > ```http theme={null} > POST /v1/requester/rfq/requests//accept > Content-Type: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > > { > "quote_id": "", > "signed_order": { > "salt": "", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "966191", > "takerAmount": "1932381", > "side": 0, > "signatureType": 3, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "signature": "" > } > } > ``` > > The response contains the latest known state. If Last Look is pending, the > gateway waits up to one second for an execution or terminal update before > returning. > > ```json theme={null} > { > "rfq_id": "", > "status": "EXECUTING", > "taker_order_hash": "" > } > ``` > > `EXECUTING` is not a confirmed fill. A response may instead remain > `AWAITING_MAKER_CONFIRMATION`, or return HTTP `200` with `status: "FAILED"` and > an `error` object if the maker declines or execution fails. Retrying the same > authenticated acceptance does not execute the order twice; use `rfq_id` as the > stable recovery identifier. > > **7. Poll Status** > > After acceptance, fetch durable status with a newly signed L2 request. > > ```http theme={null} > GET /v1/requester/rfq/requests/ > Accept: application/json > POLY_ADDRESS: > POLY_API_KEY: > POLY_PASSPHRASE: > POLY_TIMESTAMP: > POLY_SIGNATURE: > ``` > > ```json theme={null} > { > "rfq_id": "", > "status": "FILLED", > "tx_hash": "" > } > ``` > > Status reads before acceptance return HTTP `409`. Poll while the state is > `AWAITING_MAKER_CONFIRMATION`, `EXECUTING`, `MINED`, or `RETRYING`. Stop on a > successful `CONFIRMED` or `FILLED` state, or a terminal `FAILED`, `EXPIRED`, or > `CANCELED` state. A local polling timeout does not mean the trade failed; resume > polling the same `rfq_id`. > [tab] TypeScript > > > [!NOTE] > > > > TypeScript SDK support is coming soon. Use the API workflow in the API tab for > > now. > [tab] Python > > > [!NOTE] > > > > Python SDK support is coming soon. Use the API workflow in the API tab for > > now. ## Handle Errors Validation and dependency failures use non-`200` HTTP statuses with stable string codes: ```json theme={null} { "error": "invalid acceptance", "code": "INVALID_ACCEPTANCE" } ``` | HTTP status | Common codes | | - | - | | `400` | `INVALID_JSON`, `INVALID_RFQ`, `CONTRADICTORY_LEGS`, `INVALID_IDENTITY`, `INVALID_ACCEPTANCE`, `INVALID_SIGNATURE`, `UNSUPPORTED_REQUESTER_SIGNATURE_TYPE`, `BUILDER_ATTRIBUTION_NOT_ALLOWED` | | `401` | `UNAUTHENTICATED` | | `403` | `ADDRESS_MISMATCH`, `REQUEST_FAILED` | | `404` | `UNKNOWN_RFQ` | | `409` | `REQUEST_FAILED`, `QUOTE_MISMATCH`, `EXPIRED_RFQ`, `INVALID_RFQ_STATE` | | `429` | `RATE_LIMITED` | | `503` | `SERVICE_UNAVAILABLE`, `PRE_EXECUTION_BALANCE_RESERVATION_FAILED`, `TRADE_SUBMISSION_FAILED` | `CONTRADICTORY_LEGS` errors also include a `conflict` object naming the legs that cannot be combined, by decimal position ID. `conflicts_with` is the leg that completes the conflict in request order, and `legs` are the earlier legs it conflicts with. If a request has several conflicts, only one is returned. ```json theme={null} { "error": "invalid rfq: contradictory legs", "code": "CONTRADICTORY_LEGS", "conflict": { "legs": [""], "conflicts_with": [""] } } ``` Treat codes as strings so integrations remain compatible with new codes. HTTP `200` can still contain a failed business outcome; always inspect both `status` and the nested `error` object. # Fees Source: https://docs.polymarket.com/trading/fees Understanding trading fees on Polymarket > [!NOTE] > > **Upcoming changes — November 20, 2026 at 23:59 UTC.** Polymarket DeFi taker > fees and rebates will change. Maker rebates will move from daily pools to > volume tiers. The current rules below apply until then. [See all fee and > rebate changes](/programs/fee-and-rebate-changes-november-2026). Polymarket charges a small taker fee on certain markets. Fees are set by the protocol and applied at match time — you don't include fee information in your orders. These fees fund the [Maker Rebates Program](/programs/maker-rebates), which redistributes fees daily to market makers to incentivize deeper liquidity and tighter spreads. Takers can also earn a portion of fees back through the tiered [Taker Rebate Program](/programs/taker-rebates). **Geopolitical and world events markets are fee-free.** Polymarket does not charge fees or profit from trading activity on these markets. There are also no Polymarket fees to deposit or withdraw USDC (though intermediaries like Coinbase or MoonPay may charge their own fees). **Combos have their own fee rate.** Every combo is charged the Combos taker fee rate in the table below, whatever categories its legs come from. The fee rates of the underlying markets don't apply. *** ## Fee Structure Fees are calculated using the following formula: ```text theme={null} theme={null} fee = C × feeRate × p × (1 - p) ``` Where **C** = number of shares traded and **p** = price of the shares. See [Market Details](/market-data/market-details#trading-fees) to read the fee parameters for a market. > [!NOTE] > > **Makers are never charged fees.** Only takers pay fees. The fee parameters differ by market category: | Category | Taker Fee Rate | Maker Fee Rate | Maker Rebate | | - | - | - | - | | Crypto | 0.07 | 0 | 20% | | Sports | 0.05 | 0 | 15% | | Finance | 0.04 | 0 | 25% | | Politics | 0.04 | 0 | 25% | | Economics | 0.05 | 0 | 25% | | Culture | 0.05 | 0 | 25% | | Weather | 0.05 | 0 | 25% | | Other / General | 0.05 | 0 | 25% | | Mentions | 0.04 | 0 | 25% | | Tech | 0.04 | 0 | 25% | | Geopolitics | 0 | 0 | — | | Combos | 0.05 | 0 | 0% | Taker fees are calculated in USDC and vary based on the share price. The fee amount in USDC is symmetric around 50% probability — a trade at 30¢ incurs the same dollar fee as a trade at 70¢. [Fee Curves](https://datawrapper.dwcdn.net/dJ74e/) ## Fee Tables (100 Shares) > [tab] Crypto > > | Price | Trade Value | Taker Fee (USDC) | > | - | - | - | > | \$0.01 | \$1 | \$0.07 | > | \$0.05 | \$5 | \$0.33 | > | \$0.10 | \$10 | \$0.63 | > | \$0.15 | \$15 | \$0.89 | > | \$0.20 | \$20 | \$1.12 | > | \$0.25 | \$25 | \$1.31 | > | \$0.30 | \$30 | \$1.47 | > | \$0.35 | \$35 | \$1.59 | > | \$0.40 | \$40 | \$1.68 | > | \$0.45 | \$45 | \$1.73 | > | \$0.50 | \$50 | \$1.75 | > | \$0.55 | \$55 | \$1.73 | > | \$0.60 | \$60 | \$1.68 | > | \$0.65 | \$65 | \$1.59 | > | \$0.70 | \$70 | \$1.47 | > | \$0.75 | \$75 | \$1.31 | > | \$0.80 | \$80 | \$1.12 | > | \$0.85 | \$85 | \$0.89 | > | \$0.90 | \$90 | \$0.63 | > | \$0.95 | \$95 | \$0.33 | > | \$0.99 | \$99 | \$0.07 | > > The fee in USDC **peaks at 50%** probability (\$1.75) and decreases symmetrically toward both extremes. > [tab] Sports > > | Price | Trade Value | Taker Fee (USDC) | > | - | - | - | > | \$0.01 | \$1 | \$0.05 | > | \$0.05 | \$5 | \$0.24 | > | \$0.10 | \$10 | \$0.45 | > | \$0.15 | \$15 | \$0.64 | > | \$0.20 | \$20 | \$0.80 | > | \$0.25 | \$25 | \$0.94 | > | \$0.30 | \$30 | \$1.05 | > | \$0.35 | \$35 | \$1.14 | > | \$0.40 | \$40 | \$1.20 | > | \$0.45 | \$45 | \$1.24 | > | \$0.50 | \$50 | \$1.25 | > | \$0.55 | \$55 | \$1.24 | > | \$0.60 | \$60 | \$1.20 | > | \$0.65 | \$65 | \$1.14 | > | \$0.70 | \$70 | \$1.05 | > | \$0.75 | \$75 | \$0.94 | > | \$0.80 | \$80 | \$0.80 | > | \$0.85 | \$85 | \$0.64 | > | \$0.90 | \$90 | \$0.45 | > | \$0.95 | \$95 | \$0.24 | > | \$0.99 | \$99 | \$0.05 | > > The fee in USDC **peaks at 50%** probability (\$1.25) and decreases symmetrically toward both extremes. > [tab] Finance / Politics / Mentions / Tech > > | Price | Trade Value | Taker Fee (USDC) | > | - | - | - | > | \$0.01 | \$1 | \$0.04 | > | \$0.05 | \$5 | \$0.19 | > | \$0.10 | \$10 | \$0.36 | > | \$0.15 | \$15 | \$0.51 | > | \$0.20 | \$20 | \$0.64 | > | \$0.25 | \$25 | \$0.75 | > | \$0.30 | \$30 | \$0.84 | > | \$0.35 | \$35 | \$0.91 | > | \$0.40 | \$40 | \$0.96 | > | \$0.45 | \$45 | \$0.99 | > | \$0.50 | \$50 | \$1.00 | > | \$0.55 | \$55 | \$0.99 | > | \$0.60 | \$60 | \$0.96 | > | \$0.65 | \$65 | \$0.91 | > | \$0.70 | \$70 | \$0.84 | > | \$0.75 | \$75 | \$0.75 | > | \$0.80 | \$80 | \$0.64 | > | \$0.85 | \$85 | \$0.51 | > | \$0.90 | \$90 | \$0.36 | > | \$0.95 | \$95 | \$0.19 | > | \$0.99 | \$99 | \$0.04 | > > The fee in USDC **peaks at 50%** probability (\$1.00) and decreases symmetrically toward both extremes. > [tab] Economics / Culture / Weather / Other > > | Price | Trade Value | Taker Fee (USDC) | > | - | - | - | > | \$0.01 | \$1 | \$0.05 | > | \$0.05 | \$5 | \$0.24 | > | \$0.10 | \$10 | \$0.45 | > | \$0.15 | \$15 | \$0.64 | > | \$0.20 | \$20 | \$0.80 | > | \$0.25 | \$25 | \$0.94 | > | \$0.30 | \$30 | \$1.05 | > | \$0.35 | \$35 | \$1.14 | > | \$0.40 | \$40 | \$1.20 | > | \$0.45 | \$45 | \$1.24 | > | \$0.50 | \$50 | \$1.25 | > | \$0.55 | \$55 | \$1.24 | > | \$0.60 | \$60 | \$1.20 | > | \$0.65 | \$65 | \$1.14 | > | \$0.70 | \$70 | \$1.05 | > | \$0.75 | \$75 | \$0.94 | > | \$0.80 | \$80 | \$0.80 | > | \$0.85 | \$85 | \$0.64 | > | \$0.90 | \$90 | \$0.45 | > | \$0.95 | \$95 | \$0.24 | > | \$0.99 | \$99 | \$0.05 | > > The fee in USDC **peaks at 50%** probability (\$1.25) and decreases symmetrically toward both extremes. ## Fee Precision Fees are rounded to 5 decimal places. The smallest fee charged is **0.00001 USDC**. Anything smaller rounds to zero, so very small trades near the extremes may incur no fee at all. # Manage Orders Source: https://docs.polymarket.com/trading/manage-orders Learn how to track and manage orders after submitting them. After submitting an order, use authenticated account reads to check its current state, reconcile open orders and resulting trades, and cancel liquidity you no longer want resting on the book. > [!NOTE] > > Clients authenticated with [Session > Keys](/trading/session-keys#session-key-considerations) can only fetch orders > and trades associated with those Session Keys. **Deposit Wallet Owners** > cannot fetch orders from authorized Session Keys. ## Fetch an Order Look up a single order by its ID. Use this to check the current status of an order you already know about, rather than scanning the full list of open orders. > [tab] TypeScript > > Call `fetchOrder()` on a `SecureClient` to fetch an order by ID: > > ```ts theme={null} > const order = await client.fetchOrder({ orderId: "ORDER_ID" }); > > // order: OpenOrder > ``` > > The method returns an `OpenOrder` with normalized asset, decimal, and date > values: > > ```ts OpenOrder Type theme={null} > type OpenOrder = { > id: string; > conditionId: ConditionId; > assetId: ClobAssetId; > owner: string; > makerAddress: string; > side: string; > price: DecimalString; > originalSize: DecimalString; > sizeMatched: DecimalString; > outcome: string; > orderType: string; > status: string; > /** @deprecated Use sizeMatched or account trade records to track fills. */ > associateTrades: string[]; > createdAt: IsoDateTimeString; > expiresAt?: IsoDateTimeString; > }; > ``` > > ```json OpenOrder Example theme={null} > { > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "makerAddress": "0x1234567890123456789012345678901234567890", > "side": "BUY", > "price": "0.52", > "originalSize": "10", > "sizeMatched": "0", > "outcome": "Yes", > "orderType": "GTD", > "status": "LIVE", > "associateTrades": [], > "createdAt": "2026-06-01T12:00:00.000Z", > "expiresAt": "2026-06-01T13:00:00.000Z" > } > ``` > > The unified SDK uses `assetId` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > `associateTrades` is deprecated and defaults to an empty array when omitted > from the response. Use `sizeMatched` for cumulative filled quantity, or > `listAccountTrades()` for individual fills matched by `takerOrderId` or > `makerOrders[].orderId`. An empty array does not mean the order has no fills. > > `expiresAt` is present when the response includes an expiration. Otherwise, > the field is omitted. > [tab] Python > > Call `get_order()` on an `AsyncSecureClient` to fetch an order by ID. The > synchronous `SecureClient` provides the same method. > > ```python theme={null} > order = await client.get_order(order_id="ORDER_ID") > > # order: OpenOrder > ``` > > The method returns an `OpenOrder` with normalized asset, decimal, and date > values: > > ```python OpenOrder Type theme={null} > class OpenOrder: > id: str > condition_id: ConditionId > asset_id: ClobAssetId > owner: str > maker_address: str > side: Literal["BUY", "SELL"] > price: Decimal > original_size: Decimal > size_matched: Decimal > outcome: str > order_type: str > status: str > associate_trades: tuple[str, ...] # Deprecated; use size_matched or account trades. > created_at: datetime > expires_at: datetime | None > ``` > > ```json OpenOrder Example theme={null} > { > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker_address": "0x1234567890123456789012345678901234567890", > "side": "BUY", > "price": "0.52", > "original_size": "10", > "size_matched": "0", > "outcome": "Yes", > "order_type": "GTD", > "status": "LIVE", > "associate_trades": [], > "created_at": "2026-06-01T12:00:00Z", > "expires_at": "2026-06-01T13:00:00Z" > } > ``` > > The unified SDK uses `asset_id` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > `associate_trades` is deprecated and defaults to an empty tuple when omitted > from the response. Use `size_matched` for cumulative filled quantity, or > `list_account_trades()` for individual fills matched by `taker_order_id` or > `maker_orders[].order_id`. An empty tuple does not mean the order has no fills. > > `expires_at` contains the normalized expiration when one is returned and > can otherwise be `None`. > [tab] API > > Fetch the order with an authenticated CLOB request. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > ```bash theme={null} > curl "https://clob.polymarket.com/data/order/$ORDER_ID" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > where `` is a Unix timestamp and > `` is generated as follows: > > ```text theme={null} > message = + "GET" + "/data/order/$ORDER_ID" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The CLOB returns the order in its wire response shape: > > ```ts Order Type theme={null} > type Order = { > id: string; > market: string; > asset_id: string; > owner: string; > maker_address: string; > side: string; > price: string; > original_size: string; > size_matched: string; > outcome: string; > order_type: string; > status: string; > /** @deprecated May be omitted. Use size_matched or trade records. */ > associate_trades?: string[]; > created_at: number; > expiration: string; > }; > ``` > > ```json Order Example theme={null} > { > "id": "ORDER_ID", > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "0x1234...", > "maker_address": "0x1234...", > "side": "BUY", > "price": "0.52", > "original_size": "10", > "size_matched": "0", > "outcome": "Yes", > "order_type": "GTC", > "status": "LIVE", > "created_at": 1748779200, > "expiration": "0" > } > ``` > > `associate_trades` is deprecated and may be omitted. Use `size_matched` for > cumulative filled quantity, or `GET /data/trades` for individual fills matched > by `taker_order_id` or `maker_orders[].order_id`. An absent or empty field does > not mean the order has no fills. > > An `expiration` of `"0"` means the order is GTC and never expires on a > timer. See the [order response reference](/api-reference/trade/get-single-order-by-id) for quantity units and statuses. ## List Open Orders Retrieve every resting order on the account, optionally narrowed to one outcome or market. Filtering by a specific order ID can also return a canceled or fully matched order. > [tab] TypeScript > > Call `listOpenOrders()` on a `SecureClient` to iterate over the account's > open orders: > > ```ts theme={null} > const pages = client.listOpenOrders(); > > for await (const page of pages) { > // page.items: OpenOrder[] > } > ``` > > Pass a filter to narrow the results. Despite its name, `market` takes the > market's condition ID: > > ```ts theme={null} > const yesAssetId = > market.version === "v2" > ? market.outcomes.yes.positionId > : market.outcomes.yes.tokenId; > if (yesAssetId === null) { > throw new Error("Market outcome ID not found."); > } > ``` > > When filtering by `assetId` or the deprecated `tokenId` alias, also supply > a nonblank `market`. Asset-only queries throw `UserInputError` before sending > a request. Unfiltered and market-only queries remain supported. > > ```ts Asset theme={null} > const pages = client.listOpenOrders({ > assetId: yesAssetId, > market: market.conditionId!, > }); > ``` > > ```ts Condition theme={null} > const pages = client.listOpenOrders({ > market: market.conditionId!, > }); > ``` > > ```ts Order ID theme={null} > const pages = client.listOpenOrders({ > id: order.id, > }); > ``` > > Each page contains `OpenOrder` items: > > ```ts OpenOrder Type theme={null} > type OpenOrder = { > id: string; > conditionId: ConditionId; > assetId: ClobAssetId; > owner: string; > makerAddress: string; > side: string; > price: DecimalString; > originalSize: DecimalString; > sizeMatched: DecimalString; > outcome: string; > orderType: string; > status: string; > /** @deprecated Use sizeMatched or account trade records to track fills. */ > associateTrades: string[]; > createdAt: IsoDateTimeString; > expiresAt?: IsoDateTimeString; > }; > ``` > > ```json OpenOrder Example theme={null} > { > "items": [ > { > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "makerAddress": "0x1234567890123456789012345678901234567890", > "side": "BUY", > "price": "0.52", > "originalSize": "10", > "sizeMatched": "0", > "outcome": "Yes", > "orderType": "GTD", > "status": "LIVE", > "associateTrades": [], > "createdAt": "2026-06-01T12:00:00.000Z", > "expiresAt": "2026-06-01T13:00:00.000Z" > } > ], > "hasMore": false, > "totalCount": 1 > } > ``` > [tab] Python > > Call `list_open_orders()` on an `AsyncSecureClient` to iterate over the > account's open orders. The synchronous `SecureClient` provides the same method. > > ```python theme={null} > pages = client.list_open_orders() > > async for page in pages: > # page.items: tuple[OpenOrder, ...] > ``` > > Pass a filter to narrow the results. Despite its name, `market` takes the > market's condition ID: > > ```python theme={null} > yes_asset_id = ( > market.outcomes.yes.position_id > if market.version == "v2" > else market.outcomes.yes.token_id > ) > if yes_asset_id is None: > raise ValueError("Market outcome ID not found.") > ``` > > When filtering by `asset_id` or the deprecated `token_id` alias, also supply > a nonblank `market`. Asset-only queries raise `UserInputError` when the > paginator fetches a page. Unfiltered and market-only queries remain supported. > > ```python Asset theme={null} > pages = client.list_open_orders( > asset_id=yes_asset_id, > market=market.condition_id, > ) > ``` > > ```python Condition theme={null} > pages = client.list_open_orders( > market=market.condition_id, > ) > ``` > > ```python Order ID theme={null} > pages = client.list_open_orders( > id=order.id, > ) > ``` > > Each page contains `OpenOrder` items: > > ```python OpenOrder Type theme={null} > class OpenOrder: > id: str > condition_id: ConditionId > asset_id: ClobAssetId > owner: str > maker_address: str > side: Literal["BUY", "SELL"] > price: Decimal > original_size: Decimal > size_matched: Decimal > outcome: str > order_type: str > status: str > associate_trades: tuple[str, ...] # Deprecated; use size_matched or account trades. > created_at: datetime > expires_at: datetime | None > ``` > > ```json OpenOrder Example theme={null} > { > "items": [ > { > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker_address": "0x1234567890123456789012345678901234567890", > "side": "BUY", > "price": "0.52", > "original_size": "10", > "size_matched": "0", > "outcome": "Yes", > "order_type": "GTD", > "status": "LIVE", > "associate_trades": [], > "created_at": "2026-06-01T12:00:00Z", > "expires_at": "2026-06-01T13:00:00Z" > } > ], > "has_more": false, > "next_cursor": null, > "total_count": 1 > } > ``` > [tab] API > > List open orders with an authenticated CLOB request, optionally filtering > by `id`, `market`, or `asset_id`. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > When filtering by `asset_id`, include the market's condition ID in `market`. > From December 14, 2026, asset-only requests return HTTP `400` > (`asset_id requires market`). Unfiltered and market-only queries remain supported. > > ```bash theme={null} > curl "https://clob.polymarket.com/data/orders?asset_id=$ASSET_ID&market=$CONDITION_ID" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > where `` is a Unix timestamp and > `` is generated as follows: > > ```text theme={null} > message = + "GET" + "/data/orders" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The CLOB returns the matching orders in its wire response shape: > > ```ts Order Type theme={null} > type Order = { > id: string; > market: string; > asset_id: string; > owner: string; > maker_address: string; > side: string; > price: string; > original_size: string; > size_matched: string; > outcome: string; > order_type: string; > status: string; > /** @deprecated May be omitted. Use size_matched or trade records. */ > associate_trades?: string[]; > created_at: number; > expiration: string; > }; > ``` > > ```json Order Example theme={null} > [ > { > "id": "ORDER_ID", > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "0x1234...", > "maker_address": "0x1234...", > "side": "BUY", > "price": "0.52", > "original_size": "10", > "size_matched": "0", > "outcome": "Yes", > "order_type": "GTC", > "status": "LIVE", > "created_at": 1748779200, > "expiration": "0" > } > ] > ``` See the [order response reference](/api-reference/trade/get-single-order-by-id) for quantity units and statuses. ## List Account Trades Retrieve executed fills for the account, as opposed to orders that are still resting on the book. Use this to reconstruct fill history, compute realized position size, or audit what actually matched. > [tab] TypeScript > > Call `listAccountTrades()` on a `SecureClient` to iterate over the > account's trades: > > ```ts theme={null} > const pages = client.listAccountTrades(); > > for await (const page of pages) { > // page.items: ClobTrade[] > } > ``` > > Pass a filter to narrow the results. Despite its name, `market` takes the > market's condition ID: > > ```ts Asset theme={null} > const pages = client.listAccountTrades({ > assetId: yesAssetId, > }); > ``` > > ```ts Condition theme={null} > const pages = client.listAccountTrades({ > market: market.conditionId!, > }); > ``` > > ```ts Maker theme={null} > const pages = client.listAccountTrades({ > makerAddress: process.env.POLYMARKET_MAKER_ADDRESS!, > }); > ``` > > ```ts Time Range theme={null} > const now = Math.floor(Date.now() / 1000); > > const pages = client.listAccountTrades({ > after: String(now - 24 * 60 * 60), > before: String(now), > }); > ``` > > Each page contains `ClobTrade` items: > > ```ts ClobTrade Type theme={null} > type MakerOrder = { > orderId: string; > assetId: ClobAssetId; > makerAddress: string; > owner: string; > side: string; > price: DecimalString; > matchedAmount: DecimalString; > outcome: string; > feeRateBps: DecimalString | null; > }; > > type ClobTrade = { > id: string; > conditionId: ConditionId; > assetId: ClobAssetId; > owner: string; > makerAddress: string; > takerOrderId: string; > side: string; > traderSide: "TAKER" | "MAKER"; > price: DecimalString; > size: DecimalString; > outcome: string; > status: string; > feeRateBps: DecimalString; > bucketIndex: number; > transactionHash: string; > makerOrders: MakerOrder[]; > matchedAt: IsoDateTimeString; > updatedAt: IsoDateTimeString; > }; > ``` > > ```json ClobTrade Example theme={null} > { > "items": [ > { > "id": "TRADE_ID", > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "makerAddress": "0x1234567890123456789012345678901234567890", > "takerOrderId": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "side": "BUY", > "traderSide": "TAKER", > "price": "0.52", > "size": "10", > "outcome": "Yes", > "status": "TRADE_STATUS_MATCHED", > "feeRateBps": "0", > "bucketIndex": 0, > "transactionHash": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd", > "makerOrders": [], > "matchedAt": "2026-06-01T12:00:05.000Z", > "updatedAt": "2026-06-01T12:00:05.000Z" > } > ], > "hasMore": false, > "totalCount": 1 > } > ``` > [tab] Python > > Call `list_account_trades()` on an `AsyncSecureClient` to iterate over the > account's trades. The synchronous `SecureClient` provides the same method. > > ```python theme={null} > pages = client.list_account_trades() > > async for page in pages: > # page.items: tuple[ClobTrade, ...] > ``` > > Pass a filter to narrow the results. Despite its name, `market` takes the > market's condition ID: > > ```python Asset theme={null} > pages = client.list_account_trades( > asset_id=yes_asset_id, > ) > ``` > > ```python Condition theme={null} > pages = client.list_account_trades( > market=market.condition_id, > ) > ``` > > ```python Maker theme={null} > pages = client.list_account_trades( > maker_address=os.environ["POLYMARKET_MAKER_ADDRESS"], > ) > ``` > > ```python Time Range theme={null} > import time > > now = int(time.time()) > > pages = client.list_account_trades( > after=str(now - 24 * 60 * 60), > before=str(now), > ) > ``` > > Each page contains `ClobTrade` items: > > ```python ClobTrade Type theme={null} > class MakerOrder: > order_id: str > asset_id: ClobAssetId > maker_address: str > owner: str > side: Literal["BUY", "SELL"] > price: Decimal > matched_amount: Decimal > outcome: str > fee_rate_bps: Decimal | None > > class ClobTrade: > id: str > condition_id: ConditionId > asset_id: ClobAssetId > owner: str > maker_address: str > taker_order_id: str > side: Literal["BUY", "SELL"] > trader_side: Literal["TAKER", "MAKER"] > price: Decimal > size: Decimal > outcome: str > status: str > fee_rate_bps: Decimal > bucket_index: int > transaction_hash: str > maker_orders: tuple[MakerOrder, ...] > matched_at: datetime > updated_at: datetime > ``` > > ```json ClobTrade Example theme={null} > { > "items": [ > { > "id": "TRADE_ID", > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker_address": "0x1234567890123456789012345678901234567890", > "taker_order_id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "side": "BUY", > "trader_side": "TAKER", > "price": "0.52", > "size": "10", > "outcome": "Yes", > "status": "TRADE_STATUS_MATCHED", > "fee_rate_bps": "0", > "bucket_index": 0, > "transaction_hash": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd", > "maker_orders": [], > "matched_at": "2026-06-01T12:00:05Z", > "updated_at": "2026-06-01T12:00:05Z" > } > ], > "has_more": false, > "next_cursor": null, > "total_count": 1 > } > ``` > [tab] API > > List account trades with an authenticated CLOB request, optionally > filtering by `id`, `market`, `asset_id`, `maker_address`, `after`, or > `before`. See [API Authentication](/getting-started/api#authentication) for > the complete signing flow. > > ```bash theme={null} > curl "https://clob.polymarket.com/data/trades?market=$CONDITION_ID" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > where `` is a Unix timestamp and > `` is generated as follows: > > ```text theme={null} > message = + "GET" + "/data/trades" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The CLOB returns the matching trades in its wire response shape: > > ```ts Trade Type theme={null} > type MakerOrder = { > order_id: string; > asset_id: string; > maker_address: string; > owner: string; > side: string; > price: string; > matched_amount: string; > outcome: string; > fee_rate_bps: string; > }; > > type Trade = { > id: string; > market: string; > asset_id: string; > owner: string; > maker_address: string; > taker_order_id: string; > side: string; > trader_side: string; > price: string; > size: string; > outcome: string; > status: string; > fee_rate_bps?: string; > bucket_index: number; > transaction_hash?: string; > maker_orders?: MakerOrder[]; > match_time: string; > last_update: string; > }; > ``` > > ```json Trade Example theme={null} > [ > { > "id": "TRADE_ID", > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": "0x1234...", > "maker_address": "0x1234...", > "taker_order_id": "ORDER_ID", > "side": "BUY", > "trader_side": "TAKER", > "price": "0.52", > "size": "10", > "outcome": "Yes", > "status": "MATCHED", > "fee_rate_bps": "0", > "bucket_index": 0, > "transaction_hash": "0xabc...", > "maker_orders": [], > "match_time": "1748779205", > "last_update": "1748779205" > } > ] > ``` See [Trade Statuses](/concepts/order-lifecycle#trade-statuses) to follow each trade's `status` through settlement. ## List Builder Trades Retrieve matched trades attributed to a builder code across the accounts your application serves. Use this instead of an account trade read when you need to reconcile fills or measure activity for the builder integration as a whole. Orders do not appear here until they match. > [tab] TypeScript > > Call `listBuilderTrades()` on a `PublicClient` or `SecureClient` to iterate over > trades attributed to your builder code: > > ```ts theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE!, > }); > > for await (const page of pages) { > // page.items: BuilderTrade[] > } > ``` > > Pass a filter to narrow the results: > > ```ts Asset theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE!, > assetId: yesAssetId, > }); > ``` > > ```ts Condition theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE!, > market: market.conditionId!, > }); > ``` > > ```ts Trade ID theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE!, > id: trade.id, > }); > ``` > > ```ts Time Range theme={null} > const now = Math.floor(Date.now() / 1000); > > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE!, > after: String(now - 24 * 60 * 60), > before: String(now), > }); > ``` > > Each page contains `BuilderTrade` items: > > ```ts BuilderTrade Type theme={null} > type BuilderTrade = { > id: string; > tradeType: string; > takerOrderHash: string; > builder: string; > conditionId: ConditionId; > assetId: ClobAssetId; > side: "BUY" | "SELL"; > size: DecimalString; > sizeUsdc: DecimalString; > price: DecimalString; > status: string; > outcome: string; > outcomeIndex: number; > owner: string; > maker: string; > transactionHash: string; > matchedAt: IsoDateTimeString; > bucketIndex: number; > fee: DecimalString; > feeUsdc: DecimalString; > errMsg?: string | null; > createdAt?: IsoDateTimeString; > updatedAt?: IsoDateTimeString; > }; > ``` > > ```json BuilderTrade Example theme={null} > { > "items": [ > { > "id": "TRADE_ID", > "tradeType": "TAKER", > "takerOrderHash": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "builder": "0x1111111111111111111111111111111111111111111111111111111111111111", > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "side": "BUY", > "size": "10", > "sizeUsdc": "5.2", > "price": "0.52", > "status": "TRADE_STATUS_MATCHED", > "outcome": "Yes", > "outcomeIndex": 0, > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker": "0x1234567890123456789012345678901234567890", > "transactionHash": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd", > "matchedAt": "2026-06-01T12:00:05.000Z", > "bucketIndex": 0, > "fee": "0", > "feeUsdc": "0", > "errMsg": null, > "createdAt": "2026-06-01T12:00:05.000Z", > "updatedAt": "2026-06-01T12:00:05.000Z" > } > ], > "hasMore": false, > "totalCount": 1 > } > ``` > [tab] Python > > Call `list_builder_trades()` on an `AsyncPublicClient` or > `AsyncSecureClient` to iterate over trades attributed to your builder code. > The synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > ) > > async for page in pages: > # page.items: tuple[BuilderTrade, ...] > ``` > > Pass a filter to narrow the results: > > ```python Asset theme={null} > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > asset_id=yes_asset_id, > ) > ``` > > ```python Condition theme={null} > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > market=market.condition_id, > ) > ``` > > ```python Trade ID theme={null} > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > id=trade.id, > ) > ``` > > ```python Time Range theme={null} > import time > > now = int(time.time()) > > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > after=str(now - 24 * 60 * 60), > before=str(now), > ) > ``` > > Each page contains `BuilderTrade` items: > > ```python BuilderTrade Type theme={null} > class BuilderTrade: > id: str > trade_type: str > taker_order_hash: str > builder: str > condition_id: ConditionId > asset_id: ClobAssetId > side: Literal["BUY", "SELL"] > size: Decimal > size_usdc: Decimal > price: Decimal > status: str > outcome: str > outcome_index: int > owner: str > maker: str > transaction_hash: str > matched_at: datetime > bucket_index: int > fee: Decimal > fee_usdc: Decimal > error_msg: str | None > created_at: datetime | None > updated_at: datetime | None > ``` > > ```json BuilderTrade Example theme={null} > { > "items": [ > { > "id": "TRADE_ID", > "trade_type": "TAKER", > "taker_order_hash": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "builder": "0x1111111111111111111111111111111111111111111111111111111111111111", > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "side": "BUY", > "size": "10", > "size_usdc": "5.2", > "price": "0.52", > "status": "TRADE_STATUS_MATCHED", > "outcome": "Yes", > "outcome_index": 0, > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker": "0x1234567890123456789012345678901234567890", > "transaction_hash": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd", > "matched_at": "2026-06-01T12:00:05Z", > "bucket_index": 0, > "fee": "0", > "fee_usdc": "0", > "error_msg": null, > "created_at": "2026-06-01T12:00:05Z", > "updated_at": "2026-06-01T12:00:05Z" > } > ], > "has_more": false, > "next_cursor": null, > "total_count": 1 > } > ``` > [tab] API > > List trades attributed to a builder code with a public CLOB request. Filter > the results with `id`, `market`, `asset_id`, `after`, or `before` when > needed: > > ```bash theme={null} > curl "https://clob.polymarket.com/builder/trades?builder_code=$POLYMARKET_BUILDER_CODE" > ``` > > The response contains the matching trades and a cursor for the next page: > > ```json theme={null} > { > "limit": 300, > "next_cursor": "LTE=", > "count": 1, > "data": [ > { > "id": "TRADE_ID", > "tradeType": "TAKER", > "takerOrderHash": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "builder": "0x1111111111111111111111111111111111111111111111111111111111111111", > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "side": "BUY", > "size": "10", > "sizeUsdc": "5.2", > "price": "0.52", > "status": "TRADE_STATUS_MATCHED", > "outcome": "Yes", > "outcomeIndex": 0, > "owner": "9180014b-33c8-9240-a14b-bdca11c0a465", > "maker": "0x1234567890123456789012345678901234567890", > "transactionHash": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd", > "matchTime": "1748779205", > "bucketIndex": 0, > "fee": "0", > "feeUsdc": "0", > "err_msg": null, > "createdAt": "2026-06-01T12:00:05Z", > "updatedAt": "2026-06-01T12:00:05Z" > } > ] > } > ``` > > Pass `next_cursor` back as the `next_cursor` query parameter to request the > next page. The terminal cursor is `LTE=`. See [Builder Programs](/programs/builders/overview) to learn how attribution works. ## Cancel Orders Cancel only as broadly as needed. Start with known order IDs, use a market or asset filter when withdrawing a set of quotes, and reserve account-wide cancellation for exceptional situations. Cancellation remains available while the exchange is in cancel-only mode, when new orders are rejected. For a partially filled order, cancellation removes only its unfilled remainder, including when the market resolves. It preserves the original and matched sizes and does not undo settled fills. ### Cancel Orders by ID Cancel one order when you know its ID. To cancel a known set of orders in one request, submit a batch of up to 3,000 IDs. Duplicate IDs in the batch are ignored. > [tab] TypeScript > > Call `cancelOrder()` on a `SecureClient` to cancel one order: > > ```ts theme={null} > const result = await client.cancelOrder({ orderId: order.id }); > > // result: CancelOrdersResponse > ``` > > Call `cancelOrders()` to cancel several known orders in one request: > > ```ts theme={null} > const result = await client.cancelOrders({ > orderIds: orders.map((order) => order.id), > }); > > // result: CancelOrdersResponse > ``` > [tab] Python > > Call `cancel_order()` on an `AsyncSecureClient` to cancel one order. The > synchronous `SecureClient` provides the same method without `await`. > > ```python theme={null} > result = await client.cancel_order(order_id=order.id) > > # result: CancelOrdersResponse > ``` > > Call `cancel_orders()` to cancel several known orders in one request: > > ```python theme={null} > result = await client.cancel_orders( > order_ids=[order.id for order in orders], > ) > > # result: CancelOrdersResponse > ``` > [tab] API > > Cancel one order with an authenticated CLOB request. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"orderID":"'"$ORDER_ID"'"}' > ``` > > where `` is a Unix timestamp and > `` is generated from the exact serialized body: > > ```text theme={null} > body = '{"orderID":"' + order_id + '"}' > message = + "DELETE" + "/order" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > To cancel multiple orders, send an array containing 1 to 3,000 order IDs: > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '["'"$ORDER_ID_1"'","'"$ORDER_ID_2"'"]' > ``` > > Sign the batch request using its path and exact serialized array: > > ```text theme={null} > body = '["' + order_id_1 + '","' + order_id_2 + '"]' > message = + "DELETE" + "/orders" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Both requests return `200 OK` with a [cancellation > result](#cancellation-results) containing `canceled` and > `not_canceled`. ### Cancel Market Orders Cancel by outcome to withdraw orders for one outcome, or by market to withdraw orders for every outcome in the condition. At least one filter is required. > [tab] TypeScript > > Call `cancelMarketOrders()` on a `SecureClient` with an asset ID or condition > ID: > > ```ts Asset theme={null} > const result = await client.cancelMarketOrders({ > assetId: yesAssetId, > }); > ``` > > ```ts Condition theme={null} > const result = await client.cancelMarketOrders({ > market: market.conditionId!, > }); > ``` > > The `market` field takes the market's condition ID. > [tab] Python > > Call `cancel_market_orders()` on an `AsyncSecureClient` with an asset ID or > condition ID. The synchronous `SecureClient` provides the same method without > `await`. > > ```python Asset theme={null} > result = await client.cancel_market_orders( > asset_id=yes_asset_id, > ) > ``` > > ```python Condition theme={null} > result = await client.cancel_market_orders( > market=market.condition_id, > ) > ``` > > The `market` argument takes the market's condition ID. > [tab] API > > Cancel every open order for one outcome with an authenticated CLOB request. > See [API Authentication](/getting-started/api#authentication) for the > complete signing flow. > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/cancel-market-orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"asset_id":"'"$ASSET_ID"'"}' > ``` > > where `` is a Unix timestamp and > `` is generated from the exact serialized body: > > ```text theme={null} > body = '{"asset_id":"' + asset_id + '"}' > message = + "DELETE" + "/cancel-market-orders" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > To cancel every open order for a condition, send its condition ID as > `market` and sign that exact body instead: > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/cancel-market-orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"market":"'"$CONDITION_ID"'"}' > ``` > > Sign the condition-scoped request using the same path and its exact > serialized body: > > ```text theme={null} > body = '{"market":"' + condition_id + '"}' > message = + "DELETE" + "/cancel-market-orders" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Both requests return `200 OK` with a [cancellation > result](#cancellation-results) containing `canceled` and > `not_canceled`. ### Cancel All Orders Use account-wide cancellation when you need to remove every resting order, such as during an emergency shutdown. > [!WARNING] > > This action cancels every open order associated with the authenticated CLOB > API credentials. > [tab] TypeScript > > Call `cancelAll()` on a `SecureClient`: > > ```ts theme={null} > const result = await client.cancelAll(); > > // result: CancelOrdersResponse > ``` > [tab] Python > > Call `cancel_all()` on an `AsyncSecureClient`. The synchronous `SecureClient` > provides the same method without `await`. > > ```python theme={null} > result = await client.cancel_all() > > # result: CancelOrdersResponse > ``` > [tab] API > > Cancel every open order with an authenticated CLOB request. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/cancel-all" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > where `` is a Unix timestamp and > `` is generated without a request body: > > ```text theme={null} > message = + "DELETE" + "/cancel-all" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The request returns `200 OK` with a [cancellation > result](#cancellation-results) containing `canceled` and > `not_canceled`. ### Cancellation Results A cancellation can succeed for only some of the requested orders. Reconcile the result before retrying: it identifies the orders that were canceled and gives a reason for each order that could not be canceled. > [tab] TypeScript > > The TypeScript SDK returns a `CancelOrdersResponse`: > > ```ts Type theme={null} > type CancelOrdersResponse = { > canceled: OrderId[]; > notCanceled: Record; > }; > ``` > > In this example, one order was canceled and another could not be canceled > because it had already matched: > > ```json Example theme={null} > { > "canceled": ["ORDER_ID_1"], > "notCanceled": { > "ORDER_ID_2": "order already matched" > } > } > ``` > [tab] Python > > The Python SDK returns a `CancelOrdersResponse`: > > ```python Type theme={null} > class CancelOrdersResponse: > canceled: tuple[OrderId, ...] > not_canceled: dict[OrderId, str] > ``` > > In this example, one order was canceled and another could not be canceled > because it had already matched: > > ```json Example theme={null} > { > "canceled": ["ORDER_ID_1"], > "not_canceled": { > "ORDER_ID_2": "order already matched" > } > } > ``` > [tab] API > > The API returns the cancellation result as JSON. This response shows one > canceled order and one order that had already matched: > > ```json Response theme={null} > { > "canceled": ["ORDER_ID_1"], > "not_canceled": { > "ORDER_ID_2": "order already matched" > } > } > ``` ## Order Heartbeats Use order heartbeats to request cancellation of your API key's open orders if its trading process stops responding. Each SDK call sends one request. Your application owns the ongoing heartbeat loop and failure handling. > [!WARNING] > > The **first accepted heartbeat enables timeout cancellation for all open > orders owned by the same API key**, across markets and processes. Start only > when you can keep sending accepted heartbeats every **5 seconds**. There is > **no disarm endpoint**: stopping the loop or closing the SDK client leaves the > deadline active. A single test call with production credentials can put > existing orders at risk of cancellation. After **10 seconds** without an accepted heartbeat, the server detects expiry on its five-second scan and queues a cancel-all attempt. Cancellation is best effort: queue delays, service failures, or orders that cannot be canceled can prevent or delay completion. Ten seconds is the expiry threshold, not a guaranteed cancellation time. WebSocket keepalive does not refresh this deadline. > [tab] TypeScript > > Call `sendOrderHeartbeat()` on a `SecureClient` with the same API key that owns > your orders. The first call uses an empty ID by default. > > ```ts theme={null} > import { OrderHeartbeatMismatchError } from "@polymarket/client"; > > let heartbeatId = ""; > let keepQuoting = true; // Your quoting process sets this to false when stopping. > > while (keepQuoting) { > try { > const heartbeat = await client.sendOrderHeartbeat({ heartbeatId }); > heartbeatId = heartbeat.heartbeatId; > } catch (error) { > if (!(error instanceof OrderHeartbeatMismatchError)) throw error; > const heartbeat = await client.sendOrderHeartbeat({ > heartbeatId: error.heartbeatId, > }); > heartbeatId = heartbeat.heartbeatId; > } > await new Promise((resolve) => setTimeout(resolve, 5000)); > } > ``` > > Await every send before the next one and retain the latest returned > `heartbeatId`. A mismatch error contains the expected ID. The explicit retry > above uses it to recover. A rejected send does not refresh the deadline. The > SDK provides a single request per call. The loop owns scheduling and recovery. > [tab] Python > > Call `send_order_heartbeat()` on an `AsyncSecureClient` with the same API key > that owns your orders. The synchronous `SecureClient` provides the same method. > The first call uses an empty ID by default. > > ```python theme={null} > import asyncio > from polymarket import OrderHeartbeatMismatchError > > heartbeat_id = "" > keep_quoting = True # Your quoting process sets this to False when stopping. > > while keep_quoting: > try: > heartbeat = await client.send_order_heartbeat(heartbeat_id=heartbeat_id) > except OrderHeartbeatMismatchError as error: > heartbeat = await client.send_order_heartbeat( > heartbeat_id=error.heartbeat_id, > ) > heartbeat_id = heartbeat.heartbeat_id > await asyncio.sleep(5) > ``` > > Await every send before the next one and retain the latest returned > `heartbeat_id`. A mismatch error contains the expected ID. The explicit retry > above uses it to recover. A rejected send does not refresh the deadline. The > SDK provides a single request per call. The loop owns scheduling and recovery. > [tab] API > > Send a heartbeat every **5 seconds**. > > **1. Start the Heartbeat** > > Send an empty `heartbeat_id` to `POST /v1/heartbeats`. Authenticate the > request with the same CLOB API credentials that own the orders you want to > protect: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/v1/heartbeats" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"heartbeat_id":""}' > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` from the exact > serialized body sent over the wire: > > ```text theme={null} > body = '{"heartbeat_id":""}' > message = + "POST" + "/v1/heartbeats" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Save the ID returned in the response: > > ```json theme={null} > { > "heartbeat_id": "" > } > ``` > > **2. Continue the Heartbeat** > > After five seconds, send the latest `heartbeat_id` back to the same route. > Each successful response returns a new ID to use for the following > heartbeat: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/v1/heartbeats" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"heartbeat_id":""}' > ``` > > Create a fresh `` and `` for this > request, replacing `body` in the signing calculation above with the exact > serialized body containing the latest ID. > > If the ID differs from the currently registered ID, the CLOB responds with `400 Bad Request` > and supplies the expected ID. Sign a new request with that ID and retry: > > ```json theme={null} > { > "error_msg": "Invalid Heartbeat ID", > "heartbeat_id": "" > } > ``` ### Heartbeat FAQ > [accordion] Can multiple processes send heartbeats with the same API key? > > Use one coordinated sender per API key and wait for each send to finish > before sending the next. Concurrent sends can race over the rotating > heartbeat ID. Every accepted heartbeat covers all open orders owned by that > key, across markets and processes. > [accordion] How do I recover from a heartbeat ID mismatch? > > A rejected request does not refresh the deadline. Retry with the expected > ID from the mismatch response, then save the ID returned by the successful > retry. The expected ID can be empty if another integration sent a legacy > heartbeat request. > > The SDK examples above retry the first mismatch once. A second mismatch > raises an error for your application to handle. > [accordion] What should I do if a heartbeat request fails? > > Stop placing new orders and check your outstanding orders. The examples > above propagate authentication, payload, rate-limit, transport, and response > errors to your application. > > A request can succeed even if its response is lost. An SDK exception does > not tell you whether the heartbeat registration is active or whether the > server has rotated the ID. > [accordion] How do I stop sending heartbeats? > > Stop placing orders, cancel the orders you want to remove, and verify the > cancellations before stopping the heartbeat loop. > > Stopping the loop or closing the client leaves the server's deadline > active. There is no disarm operation that lets you immediately disable the > timeout while keeping existing orders live. > [accordion] What happens after the heartbeat times out? > > The server removes the heartbeat registration, then attempts to cancel the > orders. Cancellation is best effort. Check the cancellation results and > outstanding orders rather than assuming every order is gone. The server > does not keep canceling later orders indefinitely. > > A later accepted heartbeat registers the API key again. Before resuming > quoting, reconcile open orders. A successful heartbeat does not tell you > whether orders placed before the outage survived or were canceled. ## Check Closed-Only Mode Closed-only mode is an account-level circuit breaker for a market. When it's on, the account can only place orders that reduce an existing position, not new opening orders. Check this before placing an order if you want to fail fast instead of waiting for a rejection. > [tab] TypeScript > > Call `fetchClosedOnlyMode()` on a `SecureClient`: > > ```ts theme={null} > const closedOnly = await client.fetchClosedOnlyMode(); > > // closedOnly: boolean > ``` > > The method returns the account's closed-only state as a boolean: > > ```json ClosedOnlyMode Example theme={null} > false > ``` > [tab] Python > > Call `get_closed_only_mode()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method. > > ```python theme={null} > closed_only = await client.get_closed_only_mode() > > # closed_only: bool > ``` > > The method returns the account's closed-only state as a `bool`: > > ```json ClosedOnlyMode Example theme={null} > false > ``` > [tab] API > > Read the account's closed-only state: > > ```bash theme={null} > curl "https://clob.polymarket.com/auth/ban-status/closed-only" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` without a > request body: > > ```text theme={null} > message = + "GET" + "/auth/ban-status/closed-only" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > ```ts ClosedOnlyMode Type theme={null} > type ClosedOnlyMode = { > closed_only: boolean; > }; > ``` > > ```json ClosedOnlyMode Example theme={null} > { > "closed_only": false > } > ``` > > `closed_only: true` means the account can only reduce or close existing > positions. New position-opening orders are rejected. ## Check Order Scoring An order scores when it is live on a market with [liquidity rewards](/programs/liquidity-rewards) and meets the market's minimum qualifying size, maximum qualifying spread, and required live duration. Because eligibility changes as the order book moves, treat the result as a point-in-time check. > [tab] TypeScript > > Call `fetchOrderScoring()` on a `SecureClient` with the order ID: > > ```ts theme={null} > const scoring = await client.fetchOrderScoring({ orderId: order.id }); > > // scoring: boolean > ``` > > To check the scoring status of several orders in one request, call > `fetchOrdersScoring()` with their IDs: > > ```ts theme={null} > const scoringByOrder = await client.fetchOrdersScoring({ > orderIds: ["ORDER_ID_1", "ORDER_ID_2"], > }); > > // scoringByOrder: OrdersScoringResponse > ``` > > The response maps each order ID to its scoring status: > > ```ts OrdersScoringResponse Type theme={null} > type OrdersScoringResponse = Record; > ``` > > ```json OrdersScoringResponse Example theme={null} > { > "ORDER_ID_1": true, > "ORDER_ID_2": false > } > ``` > [tab] Python > > Call `get_order_scoring()` on an `AsyncSecureClient` with the order ID. The > synchronous `SecureClient` provides the same method. > > ```python theme={null} > scoring = await client.get_order_scoring(order_id=order.id) > > # scoring: bool > ``` > > To check the scoring status of several orders in one request, call > `get_orders_scoring()` with their IDs: > > ```python theme={null} > scoring_by_order = await client.get_orders_scoring( > order_ids=["ORDER_ID_1", "ORDER_ID_2"], > ) > > # scoring_by_order: dict[str, bool] > ``` > > The response maps each order ID to its scoring status: > > ```python OrdersScoringResponse Type theme={null} > dict[str, bool] > ``` > > ```json OrdersScoringResponse Example theme={null} > { > "ORDER_ID_1": true, > "ORDER_ID_2": false > } > ``` > [tab] API > > Check whether an order currently qualifies for rewards: > > ```bash theme={null} > curl "https://clob.polymarket.com/order-scoring?order_id=" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` without a > request body. The `order_id` query parameter is not part of the signed path: > > ```text theme={null} > message = + "GET" + "/order-scoring" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The response contains the order's current scoring status: > > ```json Example theme={null} > { > "scoring": true > } > ``` > > See [Get Order Scoring > Status](/api-reference/trade/get-order-scoring-status) for the complete > request and response schema. # Market Making Source: https://docs.polymarket.com/trading/market-making Guidance for operating a market-making system on Polymarket. A market maker (MM) provides liquidity by continuously posting bids and asks. By quoting both sides of a market, market makers make it easier for other traders to execute while seeking to earn the spread in exchange for the risks they take. On Polymarket, market makers deepen order books, tighten spreads, support price discovery, and absorb trading flow as market conditions change. > [!NOTE] > > Building a product that routes orders for its users? See the [Builder > Program](/programs/builders/overview). This page is for traders providing > liquidity from their own account. ## Set Up for Market Making Complete these account-level requirements before quoting a market. **1. Connect Your Account** Create or connect the wallet that will hold funds, positions, and orders, then authenticate the integration. See [Wallets and Authentication](/trading/wallets-auth) for the supported workflows. **2. Fund the Wallet** The wallet needs pUSD on Polygon before it can trade. To deposit another supported asset or transfer funds from another network, use the [Bridge](/trading/bridge/deposit). **3. Set Up Trading Approvals** Authorize the contracts required to trade outcomes and manage positions. See [Set Up Trading Approvals](/trading/wallets-auth#set-up-trading-approvals). ## Quote and Manage Orders ### Build Two-Sided Quotes Market makers maintain bids and asks around their fair value so other traders can execute in either direction. The midpoint describes the current book, but the quoting strategy must determine whether it represents fair value and how much risk to take around it. In a binary market, complementary outcomes provide another way to express the two sides. Buying NO at `0.48`, for example, is economically equivalent to selling YES at `0.52`. Before submitting a quote, confirm that the market is accepting orders and validate its current minimum price increment and minimum order size. See [Market Details](/market-data/market-details) for these constraints. ### Choose Order Types Choose the order type according to what the strategy needs to accomplish: | Type | Behavior | When to use | | - | - | - | | Good-Til-Cancelled (GTC) | Rests on the book until filled or canceled | Default for passive quotes | | Good-Til-Date (GTD) | Rests on the book until filled, canceled, or expired | Expire a passive quote at a known time | | Fill-or-Kill (FOK) | Fills the entire amount immediately or cancels | Rebalance immediately when a partial fill is not useful | | Fill-and-Kill (FAK) | Fills the available amount immediately and cancels the remainder | Rebalance immediately while allowing a partial fill | GTC and GTD are the primary order types for passive market making. Add the [post-only option](/trading/place-orders#post-only-orders) when an order must add liquidity rather than execute immediately. FAK and FOK are the execution types used by market orders for immediate rebalancing. ### Submit and Maintain Orders Submit related price levels as a [batch](/trading/place-orders#post-a-batch-of-orders) to reduce submission latency. Each order is evaluated independently, so check every result rather than treating the batch as a single success or failure. See [Place Orders](/trading/place-orders) for the complete order workflows. Once submitted, the quotes become orders resting on the book. Orders cannot be edited in place, so changing a quote means canceling the existing order and submitting a replacement: * Cancel and replace open orders when fair value, inventory, or market constraints change. * Keep the local book current with [real-time market data](/market-data/realtime-data#market-stream). * Monitor fills and order changes through [Real-Time Order Updates](/trading/realtime-order-updates). * After reconnecting, [fetch open orders and recent trades](/trading/manage-orders) before resuming the strategy. ## Manage Inventory Inventory is the outcome-token exposure accumulated through trading. Every fill changes that exposure and the pUSD or tokens available for new orders, so inventory must be part of every pricing and sizing decision. Buy orders use available pUSD, while sell orders require the corresponding outcome tokens. Splitting pUSD creates a complete set of outcome tokens. Merging a complete set returns pUSD, and redeeming a winning position releases its value after resolution. See [Manage Positions](/trading/positions/manage) for these workflows. ### Inventory Strategies | Phase | Guidance | | - | - | | Before quoting | Estimate the intended order sizes and prepare enough pUSD and outcome positions to support them. Confirm that the required trading approvals are in place. | | During trading | Track exposure by market and outcome. Skew quote prices or sizes to reduce an imbalance, split additional pUSD when tokens run low, and merge complete sets to release capital. | | When exiting | Cancel the market's remaining orders, merge any complete sets that are no longer needed, and retain or reduce the remaining directional exposure deliberately. | | After resolution | Confirm that the market has resolved, redeem winning positions, and return the released capital to the strategy. | Multi-outcome events use [negative-risk markets](/concepts/negative-risk), which change how complete sets are created and merged. Account for the market type when planning inventory operations. ## Best Practices Use these practices to keep quotes current and limit avoidable execution risk. ### Quote Management * **Quote both sides**: Post bids and asks to provide liquidity in both directions. * **Skew on inventory**: Adjust quote prices based on the current position to manage exposure. * **Cancel stale quotes**: Pull orders immediately when market conditions change. * **Use GTD for events**: Expire quotes before known catalysts to avoid stale exposure. ### Latency * **Batch orders**: Submit related quotes in a [single request](/trading/place-orders#post-a-batch-of-orders). * **Use real-time data**: Subscribe to [market updates](/market-data/realtime-data#market-stream) instead of polling. ### Risk Controls * **Set size limits**: Check outcome token balances before quoting and do not exceed the available inventory. * **Use price guards**: Validate prices against the book midpoint and reject outliers. * **Add a kill switch**: [Cancel all open orders](/trading/manage-orders#cancel-all-orders) when errors or position limits require the strategy to stop. * **Monitor fills**: Subscribe to [real-time order updates](/trading/realtime-order-updates) to track executions. ## Programs and Incentives In addition to the spread captured through executions, qualifying market-making activity may earn incentives through two separate programs. > [card] [Liquidity Rewards](/programs/liquidity-rewards) > > Earn rewards by maintaining qualifying resting liquidity in incentivized > markets. > [card] [Maker Rebates](/programs/maker-rebates) > > Earn rebates when maker liquidity executes in eligible fee-enabled markets. Eligibility, calculations, and payouts differ between the programs. See each program page for its current terms. ## Support For market maker onboarding and support, contact [support@polymarket.com](mailto:support@polymarket.com). # Matching Engine Restarts Source: https://docs.polymarket.com/trading/matching-engine Maintenance windows, restart handling, and post-restart post-only mode The Polymarket matching engine periodically restarts for maintenance and upgrades. Prepare your order workflow to pause safely, honor server-provided delays, and resume under the temporary post-only rules that follow a restart. *** ## Announcements Matching engine changes, including planned restarts, updates, and maintenance windows, are announced **before they happen** in these channels: > [card] [Telegram](https://t.me/polytradingapis) > > Join the Polymarket Trading APIs channel for real-time announcements. > [card] [Discord](https://discord.com/channels/710897173927297116/1473553279421255803) > > Join the #trading-api-announcements channel in the Polymarket Discord. Announcements typically include **what's changing**, the **scheduled time**, and the **expected downtime window**. The goal is about two days' notice when possible. *** ## Handle Matching Engine Restarts During a restart, order-related actions reject new work temporarily. After the engine returns, it enters post-only mode for two minutes: cancels remain available, but new orders must be eligible maker orders submitted as post-only. Your integration controls whether and when to retry. Use a delay supplied by the service when one is available; otherwise, fall back to exponential backoff. ### Recommended Retry Strategy **1. Detect the Restart** Treat the restart signal as a temporary condition. Do not retry unrelated request failures under the same policy. **2. Wait Before Retrying** Honor the server-provided delay when present. Otherwise, start with a one-to-two-second delay and increase it after each failed attempt. **3. Resume in Post-Only Mode** Once restart rejections stop, continue canceling as needed and submit only eligible maker orders as post-only for the next two minutes. ### Retry Order Placement Retry an eligible post-only limit order only when the rejection identifies a matching engine restart: > [tab] TypeScript > > Given a `SecureClient` and a selected `assetId`, catch `RequestRejectedError` and check its > `restriction` field. The SDK does not retry automatically. > > Don't have the TypeScript SDK installed? Start with the [TypeScript SDK > guide](/getting-started/typescript), then come back. > > ```typescript TypeScript theme={null} theme={null} > import { > OrderSide, > RequestRejectedError, > TradingRestriction, > } from "@polymarket/client"; > > async function placeWithRestartRetry(assetId: string) { > const MAX_RETRIES = 10; > let fallbackDelayMs = 1000; > > for (let attempt = 0; attempt < MAX_RETRIES; attempt++) { > try { > return await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > postOnly: true, > }); > } catch (error) { > if ( > !(error instanceof RequestRejectedError) || > error.restriction !== TradingRestriction.RESTARTING > ) { > throw error; > } > > const delayMs = > error.retryAfter === undefined > ? fallbackDelayMs > : error.retryAfter * 1000; > > await new Promise((resolve) => setTimeout(resolve, delayMs)); > > if (error.retryAfter === undefined) { > fallbackDelayMs = Math.min(fallbackDelayMs * 2, 30000); > } > } > } > > throw new Error("Engine restart exceeded maximum retry attempts"); > } > > const response = await placeWithRestartRetry(assetId); > // response: OrderResponse > ``` > [tab] Python > > Given an `AsyncSecureClient` and a selected `asset_id`, catch `RequestRejectedError` and check its > `restriction` field. The synchronous `SecureClient` raises the same error, > and neither client retries automatically. > > Don't have the Python SDK installed? Start with the [Python SDK > guide](/getting-started/python), then come back. > > ```python Python theme={null} theme={null} > import asyncio > > from polymarket import RequestRejectedError > > > async def place_with_restart_retry(asset_id: str): > max_retries = 10 > fallback_delay = 1 > > for _ in range(max_retries): > try: > return await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > post_only=True, > ) > except RequestRejectedError as error: > if error.restriction != "restarting": > raise > > delay = ( > fallback_delay > if error.retry_after is None > else error.retry_after > ) > await asyncio.sleep(delay) > > if error.retry_after is None: > fallback_delay = min(fallback_delay * 2, 30) > > raise RuntimeError("Engine restart exceeded maximum retry attempts") > > > response = await place_with_restart_retry(asset_id) > # response: OrderResponse > ``` > [tab] API > > An order-related request returns HTTP `425` while the matching engine is > restarting. Honor `Retry-After` when the response includes it; otherwise, > apply bounded exponential backoff before resubmitting the signed request. > > ```http Response theme={null} theme={null} > HTTP/1.1 425 Too Early > Retry-After: 1 > ``` *** ## Handle Restricted Trading Modes Restricted modes change which new orders are accepted. Cancels remain available unless trading is fully disabled. A cancel-only restriction blocks all new orders; a post-only restriction allows eligible maker orders submitted as post-only. ### Handle Request-Level Restrictions Pause new submissions when trading is unavailable. Switch to eligible post-only orders only when the rejection identifies post-only mode: > [tab] TypeScript > > Given a `SecureClient` and a selected `assetId`, handle rejections from `placeLimitOrder()`: > > ```typescript TypeScript theme={null} theme={null} > import { > OrderSide, > RequestRejectedError, > TradingRestriction, > } from "@polymarket/client"; > > try { > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > }); > // response: OrderResponse > } catch (error) { > if (!(error instanceof RequestRejectedError)) { > throw error; > } > > if (error.restriction === TradingRestriction.POST_ONLY) { > if (error.retryAfter !== undefined) { > const delayMs = error.retryAfter * 1000; > await new Promise((resolve) => setTimeout(resolve, delayMs)); > } > // Submit only eligible maker orders with postOnly: true. > } else { > throw error; > } > } > ``` > > `restriction` identifies post-only rejections, and `retryAfter` contains > the server-provided delay in seconds when supplied. An unclassified HTTP > `503` does not distinguish cancel-only mode from fully disabled trading. > Pause new submissions and propagate the error; do not infer that cancels > are available from this response alone. > [tab] Python > > Given an `AsyncSecureClient` and a selected `asset_id`, handle rejections from > `place_limit_order()`. The synchronous `SecureClient` raises the same error. > > ```python Python theme={null} theme={null} > import asyncio > > from polymarket import RequestRejectedError > > try: > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > ) > # response: OrderResponse > except RequestRejectedError as error: > if error.restriction == "post_only": > if error.retry_after is not None: > await asyncio.sleep(error.retry_after) > # Submit only eligible maker orders with post_only=True. > else: > raise > ``` > > `restriction` identifies post-only rejections, and `retry_after` contains > the server-provided delay in seconds when supplied. An unclassified HTTP > `503` does not distinguish cancel-only mode from fully disabled trading. > Pause new submissions and propagate the error; do not infer that cancels > are available from this response alone. > [tab] API > > Inspect the response when an order submission is rejected: > > ```http Trading Unavailable Response theme={null} > HTTP/1.1 503 Service Unavailable > Content-Type: application/json > > { > "error": "trading is disabled" > } > ``` > > ```http Post-Only Response theme={null} > HTTP/1.1 503 Service Unavailable > Content-Type: application/json > Retry-After: 79 > > { > "error": "post-only mode: only post-only orders and cancels are allowed", > "code": "post_only_mode", > "retry_after_seconds": 79 > } > ``` > > `POST /order` and `POST /orders` return the same trading-disabled response > in cancel-only and fully disabled modes. Pause new submissions; this > response does not establish whether cancels are available. > > A non-post-only order submitted to `POST /order` during post-only mode > returns `code: "post_only_mode"`. Honor the delay in `Retry-After` or > `retry_after_seconds` before retrying. Batch behavior appears below. ### Handle Batch Post-Only Rejections A batch can be accepted at the request level while individual non-post-only orders are rejected. Check every result before treating the batch as successful: > [tab] TypeScript > > `postOrders()` returns an `OrderResponse` for each submitted order. Compare > rejected results with `OrderResponseErrorCode.POST_ONLY_MODE`. > > ```typescript TypeScript theme={null} theme={null} > import { OrderResponseErrorCode } from "@polymarket/client"; > > const responses = await client.postOrders(signedOrders); > const postOnlyRejections = responses.filter( > (response) => > !response.ok && response.code === OrderResponseErrorCode.POST_ONLY_MODE, > ); > ``` > [tab] Python > > `post_orders()` returns an `OrderResponse` for each submitted order. The > `code` on a post-only rejection is `"post_only_mode"`. > > ```python Python theme={null} theme={null} > responses = await client.post_orders(signed_orders) > post_only_rejections = [ > response > for response in responses > if not response.ok and response.code == "post_only_mode" > ] > ``` > [tab] API > > `POST /orders` returns per-order errors in its successful response array: > > ```json Response theme={null} theme={null} > [ > { > "errorMsg": "post-only mode: only post-only orders and cancels are allowed", > "orderID": "", > "takingAmount": "", > "makingAmount": "", > "status": "", > "success": true > }, > { > "errorMsg": "post-only mode: only post-only orders and cancels are allowed", > "orderID": "", > "takingAmount": "", > "makingAmount": "", > "status": "", > "success": true > } > ] > ``` Do not retry the same non-post-only order unchanged. Pause new submissions in cancel-only mode, wait for an indicated delay when appropriate, or submit an eligible maker order as post-only. *** ## Best Practices * **Subscribe to announcement channels** — prepare your order workflow before a planned restart. * **Retry only restart rejections** — do not apply restart retry logic to unrelated failures. * **Honor server delays** — use the supplied delay when present and bounded exponential backoff otherwise. * **Adapt to restricted modes** — pause new orders in cancel-only mode and submit only eligible maker orders in post-only mode. * **Log restriction changes** — correlate observed transitions with announced maintenance windows. # Overview Source: https://docs.polymarket.com/trading/overview Understand how orders, settlement, and positions fit together on Polymarket. Trading connects signed orders on the CLOB with settlement on Polygon. You choose an outcome, authorize an order with your signer, and submit it to the order book. When the order matches, settlement transfers pUSD and outcome tokens between trading accounts. ## Trading Workflow Set up your account once, then repeat the remaining steps for each order. **1. Set Up Your Account** Connect a signer to your account wallet, fund it, and grant the required trading approvals. **2. Choose an Outcome** Select the outcome you want to buy or sell and check its current market constraints. **3. Place an Order** Choose a price and size, sign the order, and submit it to the CLOB. **4. Manage the Order** Monitor fills and cancel any remaining open amount. Matched trades settle on Polygon and update your balances and positions. > [!NOTE] > > The Exchange operator can match orders and enforce their ordering, but cannot > set prices or execute trades that users did not authorize. ## Start Trading > [card] [Place Your First Order](/trading/quickstart) > > Complete the first authenticated trading workflow. > [card] [Wallets and Authentication](/trading/wallets-auth) > > Connect a signer to the account wallet that holds funds and positions. > [card] [Order Lifecycle](/concepts/order-lifecycle) > > Understand how orders move from submission through fills, cancellation, or > expiration. > [card] [Session Keys](/trading/session-keys) > > Give a separate signer scoped, time-limited Deposit Wallet access. # Place Orders Source: https://docs.polymarket.com/trading/place-orders Learn how to place orders and control how they execute Place a market order to trade against available liquidity immediately, or use a limit order to specify a price and wait for a match. Before placing an order, choose an outcome and confirm that the market is [accepting orders](/market-data/market-details#market-status). The examples below assume you already have a market object. To find or fetch one, see [Discover Markets](/market-data/discover-markets). > [tab] TypeScript > > Choose an outcome (YES in this example) and select its trading identifier based on the market version. > > ```ts theme={null} > const { yes, no } = market.outcomes; > const assetId = market.version === "v2" ? yes.positionId : yes.tokenId; > ``` > > The unified SDK uses `assetId` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Pass an `assetId` to the order methods. The client selects the matching > exchange, signing domain, and approval route. > [tab] Python > > Choose an outcome (YES in this example) and select its trading identifier based on the market version. > > ```python theme={null} > yes = market.outcomes.yes > asset_id = yes.position_id if market.version == "v2" else yes.token_id > ``` > > The unified SDK uses `asset_id` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > > Pass an `asset_id` to the order methods. The client selects the matching > exchange, signing domain, and approval route. > [tab] API > > Select the identifier at the chosen outcome's index: > > ```text theme={null} > outcome_asset_id = > selected outcome's positionIds entry for a V2 market > selected outcome's parsed clobTokenIds entry for a CTF market > ``` ## Limit Orders A limit order specifies the price at which you are willing to trade and can rest on the book until it fills, expires, or you cancel it. Use one when price control matters more than immediate execution. A limit order also defines how long any unfilled amount remains active: | Lifetime | Behavior | Use when | | - | - | - | | Good Till Cancelled (GTC) | Remains active until it fills or you cancel it. | The order has no deadline. | | Good Till Date (GTD) | Remains active until the expiration time you specify. | The order should expire before a known event. | > [!NOTE] > > GTD orders expire one minute before their stated expiration as a security > threshold. To set an effective lifetime of N seconds, use `now + 60 + N`. In > addition, the expiration must be at least **3 minutes** in the future. Orders > expiring sooner are rejected, so the minimum effective lifetime is about two > minutes. ### Place a Limit Order > [tab] TypeScript > > Given a `SecureClient`, place the limit order and check its > response: > > **1. Place the Order** > > First, call `placeLimitOrder()` with the price and number of shares. The > price must follow the market's minimum price increment, and the size must > meet its minimum order size. Omit `expiration` for a GTC order or provide a > Unix timestamp in seconds for a GTD order. > > ```ts GTC theme={null} > import { OrderSide } from "@polymarket/client"; > > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > }); > > // response: OrderResponse > ``` > > ```ts GTD theme={null} > import { OrderSide } from "@polymarket/client"; > > const expiration = Math.floor(Date.now() / 1000) + 60 + 60 * 60; > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > expiration, > }); > > // response: OrderResponse > ``` > > Both examples buy `10` shares at a price of `0.52` USD per share. The GTD > order has an effective lifetime of one hour. > > **2. Check the Response** > > Then, check `response.ok` to determine whether the CLOB accepted the order: > > ```ts theme={null} > if (response.ok) { > console.log(response.orderId, response.status); > console.log(response.tradeIds, response.transactionsHashes); > } else { > console.error(response.code, response.message); > } > ``` > > An accepted response includes the order ID and one of these statuses. If > the order fills fully or partially, the `tradeIds` collection identifies > the resulting trades. When available, `transactionsHashes` contains their > transaction hashes: > > | Status | Description | > | - | - | > | `live` | The order is resting on the book. | > | `matched` | The order matched immediately with resting liquidity. | > | `delayed` | The order is marketable but subject to a matching delay. | > > A rejected order returns `ok: false` with a code and message. > [tab] Python > > Given an `AsyncSecureClient`, place the limit order and check > its response. The synchronous `SecureClient` provides the same method. > > **1. Place the Order** > > First, call `place_limit_order()` with the price and number of shares. The > price must follow the market's minimum price increment, and the size must > meet its minimum order size. Omit `expiration` for a GTC order or provide a > Unix timestamp in seconds for a GTD order. > > ```python GTC theme={null} > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > ) > > # response: OrderResponse > ``` > > ```python GTD theme={null} > import time > > expiration = int(time.time()) + 60 + 60 * 60 > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > expiration=expiration, > ) > > # response: OrderResponse > ``` > > Both examples buy `10` shares at a price of `0.52` USD per share. The GTD > order has an effective lifetime of one hour. > > **2. Check the Response** > > Then, check `response.ok` to determine whether the CLOB accepted the order: > > ```python theme={null} > if response.ok: > print(response.order_id, response.status) > print(response.trade_ids, response.transactions_hashes) > else: > print(response.code, response.message) > ``` > > An accepted response includes the order ID and one of these statuses. If > the order fills fully or partially, the `trade_ids` collection identifies > the resulting trades. When available, `transactions_hashes` contains their > transaction hashes: > > | Status | Description | > | - | - | > | `live` | The order is resting on the book. | > | `matched` | The order matched immediately with resting liquidity. | > | `delayed` | The order is marketable but subject to a matching delay. | > > A rejected order returns `ok=False` with a code and message. > [tab] API > > Build the limit order from its price and size, then sign and submit it: > > **1. Read the Market Context** > > First, fetch the current order book to read the market's trading > constraints and exchange type: > > ```bash theme={null} > curl "https://clob.polymarket.com/book?token_id=" > ``` > > ```json theme={null} > { > "asset_id": "", > "version": "v2", > "bids": [{ "price": "0.50", "size": "40" }], > "asks": [{ "price": "0.54", "size": "30" }], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": false > } > ``` > > Where: > > * `min_order_size` is the minimum number of shares the CLOB accepts for an > order. > > **2. Calculate the Order Amounts** > > Then, choose a price that conforms to `tick_size` and a share quantity that > meets `min_order_size`. Use the tick size to select the required precision: > > | Tick size | Price decimals | Size decimals | Amount decimals | > | - | -: | -: | -: | > | `0.1` | 1 | 2 | 3 | > | `0.01` | 2 | 2 | 4 | > | `0.005` | 3 | 2 | 5 | > | `0.0025` | 4 | 2 | 6 | > | `0.001` | 3 | 2 | 5 | > | `0.0001` | 4 | 2 | 6 | > > > [!NOTE] > > > > If your integration stores `tick_size` for later orders, listen for the > > `tick_size_change` event on the [market > > stream](/market-data/realtime-data#market-stream) and replace the stored value > > when it changes. The CLOB rejects an order whose price does not conform to the > > market's current tick size. > > The two sides map the price and size differently: > > * For a BUY, `makerAmount` is `price × size` USD and `takerAmount` is the > number of shares. > * For a SELL, `makerAmount` is the number of shares and `takerAmount` is > `price × size` USD. > > Apply the table's precision in this order: > > 1. Express the price using no more than **Price decimals**. > 2. Round the share quantity down to **Size decimals**. > 3. Calculate the USD amount. If it exceeds **Amount decimals**, round it up > first to **Amount decimals + 4**, then down to **Amount decimals**. > > **3. Validate and Encode the Amounts** > > Next, verify that the rounded share quantity still meets `min_order_size`, > then convert both amounts to six-decimal integers. > > For a BUY of `10` shares at `0.52`, the USD amount is `5.20` and the share > quantity is above the minimum of `5`. The encoded values are: > > ```json theme={null} > { > "makerAmount": "5200000", > "takerAmount": "10000000" > } > ``` > > **4. Create the Order Typed Data** > > Choose the signing domain using the order book retrieved above. Polymarket > Protocol V2 books return `version: "v2"`. CTF books omit `version`. For CTF, > `neg_risk` selects the exchange. > > | Order book | Domain `version` | Domain `verifyingContract` | > | - | - | - | > | `version: "v2"` | `"3"` | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | > | CTF, `neg_risk: false` | `"2"` | `0xE111180000d2663C0091e4f400237545B87B996B` | > | CTF, `neg_risk: true` | `"2"` | `0xe2222d279d744050d28e00520010520000310F59` | > > The domain name is `Polymarket CTF Exchange` and the chain ID is `137`. > Market protocol versions and signing-domain versions are different values. > > Create the typed data for your wallet using the selected domain values: > > | Wallet | `signature_type` | `maker_address` | `order_signer_address` | > | - | -: | - | - | > | Deposit Wallet | `3` | Deposit Wallet address | Deposit Wallet address | > | Proxy Wallet | `1` | Proxy Wallet address | Account signer address | > | Safe Wallet | `2` | Safe Wallet address | Account signer address | > | EOA | `0` | EOA address | EOA address | > > ```json Deposit Wallet Typed Data theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ], > "TypedDataSign": [ > { "name": "contents", "type": "Order" }, > { "name": "name", "type": "string" }, > { "name": "version", "type": "string" }, > { "name": "chainId", "type": "uint256" }, > { "name": "verifyingContract", "type": "address" }, > { "name": "salt", "type": "bytes32" } > ] > }, > "primaryType": "TypedDataSign", > "message": { > "contents": { > "salt": "479249096354", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "5200000", > "takerAmount": "10000000", > "side": 0, > "signatureType": 3, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > }, > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "", > "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > ```json Proxy, Safe, or EOA Typed Data theme={null} > { > "domain": { > "name": "Polymarket CTF Exchange", > "version": "", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Order": [ > { "name": "salt", "type": "uint256" }, > { "name": "maker", "type": "address" }, > { "name": "signer", "type": "address" }, > { "name": "tokenId", "type": "uint256" }, > { "name": "makerAmount", "type": "uint256" }, > { "name": "takerAmount", "type": "uint256" }, > { "name": "side", "type": "uint8" }, > { "name": "signatureType", "type": "uint8" }, > { "name": "timestamp", "type": "uint256" }, > { "name": "metadata", "type": "bytes32" }, > { "name": "builder", "type": "bytes32" } > ] > }, > "primaryType": "Order", > "message": { > "salt": "479249096354", > "maker": "", > "signer": "", > "tokenId": "", > "makerAmount": "5200000", > "takerAmount": "10000000", > "side": 0, > "signatureType": 1, > "timestamp": "", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > } > } > ``` > > Where: > > * The signed `tokenId` field carries the selected asset ID. For a > `"v2"` market, its value is a Position ID. > * `side` is `0` for a BUY and `1` for a SELL. > * `salt` is a fresh random value for each order. Because the request body > serializes it as a JSON number, JavaScript integrations should keep it > within `Number.MAX_SAFE_INTEGER`. > > **5. Sign the Order** > > Then, sign the typed data with the account signer. Deposit Wallets require > the raw signature to be wrapped for ERC-7739 validation. Proxy Wallets, > Safe Wallets, and EOAs submit the standard signature returned by signing > the Exchange `Order` typed data directly. > > See the example below using Viem: > > ```js Deposit Wallet theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const innerSignature = await signer.signTypedData(typedData); > const signature = wrapDepositWalletSignature(typedData, innerSignature); > ``` > > ```js Proxy, Safe, or EOA theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY); > const signature = await signer.signTypedData(typedData); > ``` > > ```js wrapDepositWalletSignature() theme={null} > import { concatHex, encodeAbiParameters, keccak256, toHex } from "viem"; > > const ORDER_TYPE = > "Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)"; > const EIP712_DOMAIN_TYPE = > "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; > > function wrapDepositWalletSignature(typedData, innerSignature) { > const order = typedData.message.contents; > const exchangeDomain = typedData.domain; > > const appDomainSeparator = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "bytes32" }, > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > ], > [ > keccak256(toHex(EIP712_DOMAIN_TYPE)), > keccak256(toHex(exchangeDomain.name)), > keccak256(toHex(exchangeDomain.version)), > BigInt(exchangeDomain.chainId), > exchangeDomain.verifyingContract, > ], > ), > ); > const contentsHash = keccak256( > encodeAbiParameters( > [ > { type: "bytes32" }, > { type: "uint256" }, > { type: "address" }, > { type: "address" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint256" }, > { type: "uint8" }, > { type: "uint8" }, > { type: "uint256" }, > { type: "bytes32" }, > { type: "bytes32" }, > ], > [ > keccak256(toHex(ORDER_TYPE)), > BigInt(order.salt), > order.maker, > order.signer, > BigInt(order.tokenId), > BigInt(order.makerAmount), > BigInt(order.takerAmount), > order.side, > order.signatureType, > BigInt(order.timestamp), > order.metadata, > order.builder, > ], > ), > ); > > return concatHex([ > innerSignature, > appDomainSeparator, > contentsHash, > toHex(ORDER_TYPE), > toHex(ORDER_TYPE.length, { size: 2 }), > ]); > } > ``` > > **6. Submit the Order** > > Submit the signed order using the selected outcome identifier: > > ```bash GTC theme={null} > curl -X POST "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{ > "deferExec": false, > "order": { > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "expiration": "0", > "maker": "", > "makerAmount": "5200000", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "salt": 479249096354, > "side": "BUY", > "signature": "", > "signatureType": 3, > "signer": "", > "takerAmount": "10000000", > "timestamp": "", > "tokenId": "" > }, > "orderType": "GTC", > "owner": "" > }' > ``` > > ```bash GTD theme={null} > curl -X POST "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{ > "deferExec": false, > "order": { > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "expiration": "", > "maker": "", > "makerAmount": "5200000", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "salt": 479249096354, > "side": "BUY", > "signature": "", > "signatureType": 3, > "signer": "", > "takerAmount": "10000000", > "timestamp": "", > "tokenId": "" > }, > "orderType": "GTD", > "owner": "" > }' > ``` > > For GTD, set `expiration` to a Unix timestamp in seconds before signing and > submitting the request. > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` from the exact > serialized body sent over the wire: > > ```text theme={null} > body = > message = + "POST" + "/order" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > **7. Check the Response** > > Finally, check `success` to determine whether the CLOB accepted the order. > A successful response includes the order ID and its insertion status. A > failed response includes the reason in `errorMsg`: > > ```json Success theme={null} > { > "success": true, > "errorMsg": "", > "orderID": "", > "status": "live", > "makingAmount": "", > "takingAmount": "", > "transactionsHashes": [""], > "tradeIDs": [""] > } > ``` > > ```json Failure theme={null} > { > "success": false, > "errorMsg": "not enough balance / allowance", > "orderID": "", > "status": "", > "makingAmount": "", > "takingAmount": "" > } > ``` > > A successful response has one of the following statuses. When the order > fills fully or partially, the `tradeIDs` collection identifies the > resulting trades. When available, `transactionsHashes` contains their > transaction hashes: > > | Status | Description | > | - | - | > | `live` | The order is resting on the book. | > | `matched` | The order matched immediately with resting liquidity. | > | `delayed` | The order is marketable but subject to a matching delay. | > | `unmatched` | The order is marketable but failed to delay. Placement still succeeded. | ### Post-Only Orders A post-only order adds liquidity only: if it would match immediately against the book, it is rejected instead of taking. Use it to guarantee you quote as a maker. > [!TIP] > > Market makers use post-only orders to add liquidity with resting orders. > [tab] TypeScript > > Given a `SecureClient`, set `postOnly` when placing the > limit order: > > ```ts theme={null} > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > postOnly: true, > }); > > // response: OrderResponse > ``` > [tab] Python > > Given an `AsyncSecureClient`, set `post_only` when placing > the limit order. The synchronous `SecureClient` provides the same method. > > ```python theme={null} > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > post_only=True, > ) > > # response: OrderResponse > ``` > [tab] API > > Follow the API workflow in [Place a Limit Order](#place-a-limit-order), then > add `postOnly: true` to the final request alongside a GTC or GTD > `orderType`. For example, submit a GTC post-only order: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{ > "deferExec": false, > "order": { > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "expiration": "0", > "maker": "", > "makerAmount": "5200000", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "salt": 479249096354, > "side": "BUY", > "signature": "", > "signatureType": 3, > "signer": "", > "takerAmount": "10000000", > "timestamp": "", > "tokenId": "" > }, > "orderType": "GTC", > "owner": "", > "postOnly": true > }' > ``` ## Market Orders A market order uses the same underlying order as a limit order but derives a marketable price from current order-book liquidity. This allows it to execute immediately instead of resting on the book. Use a market order when execution matters more than setting an exact price. Read the market's [trading constraints](/market-data/market-details#trading-constraints) before deciding how much to buy or sell. ### Place a Market Order The examples below use Fill and Kill (FAK), which fills available liquidity immediately and cancels any remainder. See [Market Order Types](#market-order-types) for Fill or Kill (FOK). > [tab] TypeScript > > Given a `SecureClient`, estimate the price and place the > market order: > > **1. Estimate the Price** > > First, call `estimateMarketPrice()` to discover the price level the order > would reach at the current order-book depth. For a BUY, `amount` is the USD > notional to spend. For a SELL, `shares` is the number of shares to sell, > rather than their USD value. > > ```ts Buy theme={null} > import { OrderSide, OrderType } from "@polymarket/client"; > > const estimatedBuyPrice = await client.estimateMarketPrice({ > assetId, > side: OrderSide.BUY, > amount: "10", > orderType: OrderType.FAK, > }); > > // estimatedBuyPrice: number > ``` > > ```ts Sell theme={null} > import { OrderSide, OrderType } from "@polymarket/client"; > > const estimatedSellPrice = await client.estimateMarketPrice({ > assetId, > side: OrderSide.SELL, > shares: "10", > orderType: OrderType.FAK, > }); > > // estimatedSellPrice: number > ``` > > In these examples, `amount: "10"` means spending \$10, while `shares: "10"` > means selling 10 shares. > > The estimate is a snapshot of the current order book. The available price > can change before you submit the order. > > **2. Place the Order** > > Then, if the estimated price is acceptable, pass it as the maximum price > for a BUY or the minimum price for a SELL, and place the market order: > > ```ts Buy theme={null} > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.BUY, > amount: "10", > maxPrice: estimatedBuyPrice, > orderType: OrderType.FAK, > }); > > // response: OrderResponse > ``` > > ```ts Sell theme={null} > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.SELL, > shares: "10", > minPrice: estimatedSellPrice, > orderType: OrderType.FAK, > }); > > // response: OrderResponse > ``` > > `maxPrice` prevents a BUY from crossing a higher price, while `minPrice` > prevents a SELL from crossing a lower one. If the book moves before > submission, the order may fill only partially or not at all. > > With `maxPrice`, the SDK rounds BUY shares down to supported precision > without increasing the signed spend, so the order can match an ask at that > price. If the final fee-adjusted amounts cannot preserve the price bound, > it refreshes market metadata at most once and throws `UserInputError` > before signing if the amounts are still invalid. Increase `amount` and, > if set, `maxSpend`, or choose a different `maxPrice`. > > **3. Check the Response** > > Then, check `response.ok` to determine whether the CLOB accepted the > order: > > ```ts theme={null} > if (response.ok) { > console.log(response.orderId, response.status); > console.log(response.tradeIds, response.transactionsHashes); > } else { > console.error(response.code, response.message); > } > ``` > > An accepted response includes the order ID and one of these statuses. If > the order fills fully or partially, `tradeIds` identifies the resulting > trades. When available, `transactionsHashes` contains their transaction > hashes: > > | Status | Description | > | - | - | > | `matched` | The order matched immediately with resting liquidity. | > | `delayed` | The market imposes a matching delay. Matching begins after the delay elapses. | > > A `delayed` response is accepted but has not matched yet. Its > `makingAmount` and `takingAmount` are `"0"`, and its `tradeIds` and > `transactionsHashes` are empty because no fills exist yet. Treat it as a > pending order rather than a fill, and use [real-time order > updates](/trading/realtime-order-updates) to follow its outcome. To identify > markets with this behavior before placing an order, read > [`market.trading.secondsDelay`](/market-data/market-details#market-timing). > > A market order never rests on the book: any amount that cannot fill is > canceled. A rejected order returns `ok: false` with a code and message. > > **4. Wait for Fill Settlement (Optional)** > > Settlement happens asynchronously after an order matches, so an accepted > response may not carry transaction hashes yet. If you need them, call > `waitForOrderFillSettlement()` with the accepted response: > > ```ts theme={null} > if (response.ok) { > const hashes = await client.waitForOrderFillSettlement(response); > // hashes: TxHash[] > } > ``` > > The call waits until every fill identified by `tradeIds` settles on-chain > and returns the settlement transaction hashes. When `tradeIds` is empty, it > returns `transactionsHashes` immediately. It does not wait for a `delayed` > order to match. By default it waits up to 30 seconds (configurable with > `timeoutMs`) and throws a `TimeoutError` if fills are still settling at the > deadline. The executed trades are unaffected. > [tab] Python > > Given an `AsyncSecureClient`, estimate the price and place > the market order. The synchronous `SecureClient` provides the same methods. > > **1. Estimate the Price** > > First, call `estimate_market_price()` to discover the price level the order > would reach at the current order-book depth. For a BUY, `amount` is the USD > notional to spend. For a SELL, `shares` is the number of shares to sell, > rather than their USD value. > > ```python Buy theme={null} > estimated_buy_price = await client.estimate_market_price( > asset_id=asset_id, > side="BUY", > amount="10", > order_type="FAK", > ) > > # estimated_buy_price: Decimal > ``` > > ```python Sell theme={null} > estimated_sell_price = await client.estimate_market_price( > asset_id=asset_id, > side="SELL", > shares="10", > order_type="FAK", > ) > > # estimated_sell_price: Decimal > ``` > > In these examples, `amount="10"` means spending \$10, while `shares="10"` > means selling 10 shares. > > The estimate is a snapshot of the current order book. The available price > can change before you submit the order. > > **2. Place the Order** > > Then, if the estimated price is acceptable, pass it as the maximum price > for a BUY or the minimum price for a SELL, and place the market order: > > ```python Buy theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="BUY", > amount="10", > max_price=estimated_buy_price, > order_type="FAK", > ) > > # response: OrderResponse > ``` > > ```python Sell theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="SELL", > shares="10", > min_price=estimated_sell_price, > order_type="FAK", > ) > > # response: OrderResponse > ``` > > `max_price` prevents a BUY from crossing a higher price, while `min_price` > prevents a SELL from crossing a lower one. If the amount's precision cannot > keep a BUY below the next possible price, the SDK refreshes market metadata > once and then raises `UserInputError` before signing. If the book moves > before submission, the order may fill only partially or not at all. > > **3. Check the Response** > > Then, check `response.ok` to determine whether the CLOB accepted the > order: > > ```python theme={null} > if response.ok: > print(response.order_id, response.status) > print(response.trade_ids, response.transactions_hashes) > else: > print(response.code, response.message) > ``` > > An accepted response includes the order ID and one of these statuses. If > the order fills fully or partially, `trade_ids` identifies the resulting > trades. When available, `transactions_hashes` contains their transaction > hashes: > > | Status | Description | > | - | - | > | `matched` | The order matched immediately with resting liquidity. | > | `delayed` | The market imposes a matching delay. Matching begins after the delay elapses. | > > A `delayed` response is accepted but has not matched yet. Its > `making_amount` and `taking_amount` are `0`, and its `trade_ids` and > `transactions_hashes` are empty because no fills exist yet. Treat it as a > pending order rather than a fill, and use [real-time order > updates](/trading/realtime-order-updates) to follow its outcome. To identify > markets with this behavior before placing an order, read > [`market.trading.seconds_delay`](/market-data/market-details#market-timing). > > A market order never rests on the book: any amount that cannot fill is > canceled. A rejected order returns `ok=False` with a code and message. > > **4. Wait for Fill Settlement (Optional)** > > Settlement happens asynchronously after an order matches, so an accepted > response may not carry transaction hashes yet. If you need them, call > `wait_for_order_fill_settlement()` with the accepted response: > > ```python theme={null} > if response.ok: > hashes = await client.wait_for_order_fill_settlement(response) > # hashes: tuple[TransactionHash, ...] > ``` > > The call waits until every fill identified by `trade_ids` settles on-chain > and returns the settlement transaction hashes. When `trade_ids` is empty, > it returns `transactions_hashes` immediately. It does not wait for a > `delayed` order to match. By default it waits up to 30 seconds (configurable > with `timeout_s`) and raises a `TimeoutError` if fills are still settling at > the deadline. The executed trades are unaffected. > [tab] API > > Market orders reuse the construction and signing flow from [Place a Limit > Order](#place-a-limit-order). Start from the current order book, calculate > market-order amounts, then build and sign the same Exchange order with > those values. The steps below call out what changes when the order should > execute against current liquidity: > > **1. Estimate the Price** > > First, fetch the current order book: > > ```bash theme={null} > curl "https://clob.polymarket.com/book?token_id=" > ``` > > ```json theme={null} > { > "asset_id": "", > "version": "v2", > "bids": [{ "price": "0.50", "size": "40" }], > "asks": [ > { "price": "0.54", "size": "30" }, > { "price": "0.52", "size": "25" } > ], > "min_order_size": "5", > "tick_size": "0.01", > "neg_risk": false > } > ``` > > Estimate the price according to the order side: > > * For a BUY, walk the asks from the best price upward and accumulate > `price × size` until the total reaches the USD amount you want to spend. > Use the final price as the maximum price. > * For a SELL, walk the bids from the best price downward until their > cumulative size reaches the number of shares you want to sell. Use the > final price as the minimum price. > > In this example, a 10 USD BUY can fill entirely at `0.52`, so its maximum > price is `0.52`. Recalculate the estimate if the order book changes before > submission. > > **2. Calculate the Order Amounts** > > Use the precision table in the limit-order workflow above, but map the > amounts according to the side: > > * For a BUY, `makerAmount` is the USD amount to spend and `takerAmount` > is `makerAmount ÷ maximum price` shares. > * For a SELL, `makerAmount` is the number of shares and `takerAmount` is > `makerAmount × minimum price` USD. > > Round the price and input amount down to the table's **Price decimals** and > **Size decimals**. Then round `takerAmount` down to **Amount decimals**. For > a BUY, rounding the share amount down keeps the order's price, > `makerAmount ÷ takerAmount`, at or slightly above the maximum price, so the > order can match an ask resting at that price. For a SELL, > `makerAmount × minimum price` is already exact at **Amount decimals**, so no > rounding applies. > > A 10 USD BUY with a maximum price of `0.52` produces `19.2307` shares at a > tick size of `0.01`. This exceeds the five-share minimum in the order book. > Converted to six-decimal integers, the amounts are: > > ```json theme={null} > { > "makerAmount": "10000000", > "takerAmount": "19230700" > } > ``` > > The order's price is `10 ÷ 19.2307 ≈ 0.5200019`. It sits above the maximum > price by less than the finest tick size, `0.0001`, so the order cannot cross > a higher ask, and a fill executes at the resting ask's price. If > `makerAmount ÷ takerAmount` reaches the maximum price plus `0.0001`, increase > the amount or choose a different maximum price. This can happen with small > amounts on markets with a tick size of `0.1`. > > **3. Build and Sign the Order** > > Select the signing domain from the order book as shown in > [Create the Order Typed Data](#create-the-order-typed-data). Then resolve the > maker, signer, and signature type for the wallet. Build the same EIP-712 > order typed data, replacing `makerAmount` and `takerAmount` with the > market-order amounts calculated above. > > Sign with the account signer. Deposit Wallets use the `TypedDataSign` > payload and wrap the resulting signature for ERC-7739 validation. Proxy > Wallets, Safe Wallets, and EOAs sign the Exchange `Order` directly. > > **4. Submit the Market Order** > > Set `orderType` to `"FAK"` and submit the order: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{ > "deferExec": false, > "order": { > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "expiration": "0", > "maker": "", > "makerAmount": "10000000", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "salt": 479249096354, > "side": "BUY", > "signature": "", > "signatureType": 3, > "signer": "", > "takerAmount": "19230700", > "timestamp": "", > "tokenId": "" > }, > "orderType": "FAK", > "owner": "" > }' > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` from the exact > serialized body sent over the wire: > > ```text theme={null} > body = > message = + "POST" + "/order" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Market orders must use an `expiration` of `"0"`. > > **5. Check the Response** > > Finally, check `success`. A FAK order may fill fully or partially. Any > unfilled remainder is canceled. Successful fills are identified by > `tradeIDs`. `transactionsHashes` contains any transaction hashes available > when the response is returned. A rejected order explains the failure in > `errorMsg`: > > ```json Success theme={null} > { > "success": true, > "errorMsg": "", > "orderID": "", > "status": "matched", > "makingAmount": "", > "takingAmount": "", > "transactionsHashes": [""], > "tradeIDs": [""] > } > ``` > > ```json Failure theme={null} > { > "success": false, > "errorMsg": "not enough balance / allowance", > "orderID": "", > "status": "", > "makingAmount": "", > "takingAmount": "" > } > ``` > > When `status` is `"delayed"`, the order is accepted but matching has not > happened yet. `makingAmount` and `takingAmount` may be empty, and > `tradeIDs` and `transactionsHashes` are empty because no fills exist yet. > Treat the order as pending and use [real-time order > updates](/trading/realtime-order-updates) to follow its outcome. To identify > markets with this behavior before submitting, read > [`secondsDelay`](/market-data/market-details#market-timing). ### Cap Market Buy Spending A market BUY's amount is the pre-fee USD notional. Applicable [platform fees](/market-data/market-details#trading-fees) and [builder taker fees](/programs/builders/fees) are charged on top. Set an all-in spending limit when the complete cost must remain within a fixed budget. > [tab] TypeScript > > Set `maxSpend` to the most you want to spend, including fees: > > ```ts theme={null} > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.BUY, > amount: "10", > maxSpend: "10", > maxPrice: estimatedBuyPrice, > orderType: OrderType.FAK, > }); > ``` > > Here, `amount: "10"` requests a 10 USD pre-fee buy, while `maxSpend: "10"` > caps the total spend at 10 USD. The SDK reduces the signed buy amount so > the order and its fees fit within the cap. Omit `maxSpend` to pay fees on > top of `amount`. > [tab] Python > > Set `max_spend` to the most you want to spend, including fees: > > ```python theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="BUY", > amount="10", > max_spend="10", > max_price=estimated_buy_price, > order_type="FAK", > ) > ``` > > Here, `amount="10"` requests a 10 USD pre-fee buy, while `max_spend="10"` > caps the total spend at 10 USD. The SDK reduces the signed buy amount so > the order and its fees fit within the cap. Omit `max_spend` to pay fees on > top of `amount`. > [tab] API > > Before signing, reduce `makerAmount` so the order notional plus applicable > platform and builder taker fees does not exceed the intended limit. Then > use the fee-adjusted value when calculating the market-order amounts above. ### Market Order Types A market order uses one of two execution types, depending on whether a partial fill is acceptable: | Type | Behavior | | - | - | | Fill and Kill (FAK) | Fills against the available liquidity immediately and cancels any unfilled remainder. | | Fill or Kill (FOK) | Fills the entire order immediately or does not fill any of it. | > [tab] TypeScript > > Set `orderType` when calling `placeMarketOrder()` on a `SecureClient`. > Fill and Kill is the default. > > ```ts FAK theme={null} > import { OrderSide, OrderType } from "@polymarket/client"; > > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.BUY, > amount: "10", > orderType: OrderType.FAK, > }); > > // response: OrderResponse > ``` > > ```ts FOK theme={null} > import { OrderSide, OrderType } from "@polymarket/client"; > > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.BUY, > amount: "10", > orderType: OrderType.FOK, > }); > > // response: OrderResponse > ``` > [tab] Python > > Set `order_type` when calling `place_market_order()` on an > `AsyncSecureClient`. Fill and Kill is the default, and the synchronous > `SecureClient` provides the same method. > > ```python FAK theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="BUY", > amount="10", > order_type="FAK", > ) > > # response: OrderResponse > ``` > > ```python FOK theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="BUY", > amount="10", > order_type="FOK", > ) > > # response: OrderResponse > ``` > [tab] API > > `orderType` is not part of the signed EIP-712 order typed data. Set it to > `FAK` or `FOK` alongside the signed order in the top-level `/order` body: > > ```json theme={null} > { > "deferExec": false, > "order": { "…": "…" }, > "orderType": "FOK", > "owner": "" > } > ``` ## Create and Post Separately Create and sign an order without submitting it when you need to inspect it, store it temporarily, or include it in a later batch. > [tab] TypeScript > > Given a `SecureClient`, create the signed order locally, > then post it when ready: > > ```ts theme={null} > const signedOrder = await client.createLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > }); > > // signedOrder: SignedOrder > > const response = await client.postOrder(signedOrder); > > // response: OrderResponse > ``` > [tab] Python > > Given an `AsyncSecureClient`, create the signed order > locally, then post it when ready. The synchronous `SecureClient` provides > the same methods. > > ```python theme={null} > signed_order = await client.create_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > ) > > # signed_order: SignedOrder > > response = await client.post_order(signed_order) > > # response: OrderResponse > ``` > [tab] API > > The API is inherently two-step: signing happens locally and submission is > a separate HTTP request. Build and sign the order as described in [Place a > Limit Order](#place-a-limit-order), then keep the signed order until you are > ready to submit it. ## Post a Batch of Orders Submit several signed orders in one request. This is useful for placing a ladder of quotes across multiple price levels when market making. > [tab] TypeScript > > Given a `SecureClient`, create each signed order, then pass > them together to `postOrders()`: > > ```ts theme={null} > const firstOrder = await client.createLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.51", > size: "10", > }); > > const secondOrder = await client.createLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > }); > > const responses = await client.postOrders([firstOrder, secondOrder]); > > // responses: OrderResponse[] > ``` > > ```json Example theme={null} > [ > { > "ok": true, > "orderId": "0x0827…", > "status": "live", > "makingAmount": "0", > "takingAmount": "0", > "transactionsHashes": [], > "tradeIds": [] > }, > { > "ok": true, > "orderId": "0x09f3…", > "status": "live", > "makingAmount": "0", > "takingAmount": "0", > "transactionsHashes": [], > "tradeIds": [] > } > ] > ``` > > `postOrders` accepts between 1 and 15 signed orders per call. Each > entry in `responses` can independently be accepted or rejected, so check > `ok` on every entry rather than assuming the whole batch succeeded or > failed together. > [tab] Python > > Given an `AsyncSecureClient`, create each signed order, then > pass them together to `post_orders()`. The synchronous `SecureClient` > provides the same methods. > > ```python theme={null} > first_order = await client.create_limit_order( > asset_id=asset_id, > side="BUY", > price="0.51", > size="10", > ) > > second_order = await client.create_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > ) > > responses = await client.post_orders([first_order, second_order]) > > # responses: tuple[OrderResponse, ...] > ``` > > ```python OrderResponse Type theme={null} > tuple[OrderResponse, ...] > ``` > > ```json OrderResponse Example theme={null} > [ > { > "ok": true, > "order_id": "0x0827…", > "status": "live", > "making_amount": "0", > "taking_amount": "0", > "trade_ids": [], > "transactions_hashes": [] > }, > { > "ok": true, > "order_id": "0x09f3…", > "status": "live", > "making_amount": "0", > "taking_amount": "0", > "trade_ids": [], > "transactions_hashes": [] > } > ] > ``` > > `post_orders` accepts between 1 and 15 signed orders per call. Each > entry in `responses` can independently be accepted or rejected, so check > `ok` on every entry rather than assuming the whole batch succeeded or > failed together. > [tab] API > > Send an array of 1 to 15 signed-order entries to `/orders`: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '[ > { > "deferExec": false, > "order": { "…": "…" }, > "orderType": "GTC", > "owner": "" > }, > { > "deferExec": false, > "order": { "…": "…" }, > "orderType": "GTC", > "owner": "" > } > ]' > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` from the exact > serialized array sent over the wire: > > ```text theme={null} > body = > message = + "POST" + "/orders" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Each entry uses the same shape as a single `/order` request. The response > contains one result for each submitted order. For example, one order can > be accepted while another is rejected: > > ```json theme={null} > [ > { > "success": true, > "errorMsg": "", > "orderID": "", > "status": "live", > "makingAmount": "", > "takingAmount": "", > "transactionsHashes": [], > "tradeIDs": [] > }, > { > "success": false, > "errorMsg": "not enough balance / allowance", > "orderID": "", > "status": "", > "makingAmount": "", > "takingAmount": "" > } > ] > ``` > > Check every result rather than treating the batch as a single success or > failure. ## Builder Attribution As part of the [Builder Program](/programs/builders/overview), attach your builder code to orders so matched trades are credited to your builder profile. The code is a 32-byte hex string that identifies your profile. ### Attach Your Builder Code In the builder account, open polymarket.com → Settings → Builders and copy the **Builder Code** from your profile: ![Open Settings, select Builders, and copy the Builder Code](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/builder-code-tutorial.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=6648f4bfed0dd365fc1ad40664371032) Include the builder code in every order you want attributed to your integration. Because it is part of the signed order, add it before signing. > [tab] TypeScript > > Given a `SecureClient`, pass the code as `builderCode` when > placing the order: > > ```ts theme={null} > const response = await client.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > builderCode: process.env.POLYMARKET_BUILDER_CODE, > }); > > // response: OrderResponse > ``` > [tab] Python > > Given an `AsyncSecureClient` (or `SecureClient` for synchronous code), pass > the code as `builder_code` when > placing the order: > > ```python theme={null} > response = await client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > ) > > # response: OrderResponse > ``` > [tab] API > > Set the `builder` field of the order struct to your builder code before > signing, in place of its 32-byte zero default. The code becomes part of the > signed order and attributes any resulting trades to your builder profile. > > ```json theme={null} > { > "deferExec": false, > "order": { > "builder": "", > "…": "…" > }, > "orderType": "GTC", > "owner": "" > } > ``` ### Verify Attribution After an attributed order matches, query builder trades using your builder code to confirm that the trade was credited to your profile. Orders that have not matched do not appear in builder trade results. > [tab] TypeScript > > Use `listBuilderTrades` with a `PublicClient` or `SecureClient`, then fetch > the first page of matching trades: > > ```ts theme={null} > const pages = client.listBuilderTrades({ > builderCode: process.env.POLYMARKET_BUILDER_CODE, > }); > > const page = await pages.firstPage(); > > // page.items: BuilderTrade[] > ``` > [tab] Python > > Use `list_builder_trades` with an `AsyncPublicClient` or > `AsyncSecureClient`, then fetch the first page of matching trades. The > synchronous `PublicClient` and `SecureClient` provide the same method. > > ```python theme={null} > pages = client.list_builder_trades( > builder_code=os.environ["POLYMARKET_BUILDER_CODE"], > ) > > page = await pages.first_page() > > # page.items: tuple[BuilderTrade, ...] > ``` > [tab] API > > Builder trades are a public read and do not require authentication headers: > > ```bash theme={null} > curl "https://clob.polymarket.com/builder/trades?builder_code=$POLYMARKET_BUILDER_CODE" > ``` > > Use the response's `next_cursor` value to request additional pages. You can also monitor credited volume on the [Builder Leaderboard](https://builders.polymarket.com). Allow up to 24 hours for matched volume to appear there. # Combinatorial Positions Source: https://docs.polymarket.com/trading/positions/combinatorial Multi-leg positions built from existing Polymarket outcomes Combinatorial positions let traders express a single view across multiple Polymarket outcomes. Instead of trading one market at a time, a combinatorial position combines existing outcome tokens into one new YES/NO pair. ## What They Represent A combinatorial **YES** position represents a conjunction of legs: ```text theme={null} YES( YES(Market A) and YES(Market B) and NO(Market C) ) ``` It pays out when every leg in the combination pays out -- in above example, if Market A resolves YES AND Market B resolves YES AND Market C resolves NO. The matching combinatorial **NO** position is the complement: ```text theme={null} NO( YES(Market A) and YES(Market B) and NO(Market C) ) ``` It pays out when the full conjunction does not pay out. In this example, it will pay out if Market A resolves NO OR Market B resolves NO OR Market C resolves YES. ## How Tokens Work A combinatorial condition represents a conjuction of legs, but not a side. The combinatorial condition from above would be: ```text theme={null} YES(Market A) and YES(Market B) and NO(Market C) ``` Each combinatorial condition has two **combinatorial positions**, the YES and the NO, which each have their own ERC 1155 token ID: | Position | Meaning | | - | - | | YES | The full combination pays out | | NO | The full combination does not pay out | Like standard CTF positions, the YES and NO pair is fully collateralized. Splitting collateral creates matching YES and NO combinatorial tokens, and merging a matching pair returns collateral. These positions use Polymarket Protocol V2 rather than the Conditional Tokens Framework. ## Resolution A combinatorial YES position pays the product of its legs' payouts. A leg that wins pays `1`, a leg that loses pays `0`, and a leg whose market [resolves 50/50](/concepts/resolution) pays `0.5`. The matching NO position pays `1` minus the YES payout. | Leg Results | YES Payout per Token | NO Payout per Token | | - | - | - | | Every leg wins | \$1.00 | \$0.00 | | Any leg loses | \$0.00 | \$1.00 | | One leg resolves 50/50, others win | \$0.50 | \$0.50 | | Two legs resolve 50/50, others win | \$0.25 | \$0.75 | A leg that resolves 50/50 stays in the combination. It is not dropped, so a YES position bought above its final payout returns less than it cost. Whether a canceled or postponed event resolves 50/50 depends on the rules of that leg's market. If some legs are already resolved and others remain open, the position can be compressed into a simpler position that keeps only the unresolved legs and realizes any resolved collateral value. ## Related Pages > [card] [CTF Overview](/trading/positions/how-positions-work) > > Minimal overview of Conditional Tokens > [card] [Split Tokens](/trading/positions/manage#split-a-position) > > Create YES and NO token pairs > [card] [Combos](/trading/combos/overview) > > Quote combinatorial positions through RFQ # How Positions Work Source: https://docs.polymarket.com/trading/positions/how-positions-work Understand Polymarket outcome positions, ledgers, and identifiers. Polymarket represents tradeable outcomes as ERC-1155 balances. Every binary market has a YES position and a NO position, but the contract that owns those balances depends on the market's position system. ## Positions Ledgers | Position system | ERC-1155 ledger | Market logic | Outcome identifier | | - | - | - | - | | Polymarket V2 | PositionManager | BinaryModule, NegRiskModule, or CombinatorialModule | Position ID | | CTF | Conditional Tokens | Standard CTF or Neg Risk Adapter | CTF token ID | Do not send a CTF token ID to PositionManager or a Position ID to Conditional Tokens. Market discovery provides the identifiers required by each workflow. ## Position Lifecycle Both systems expose the same basic position lifecycle. > [card] [Split](/trading/positions/manage#split-a-position) > > Convert pUSD into a YES and NO token pair. > [card] [Merge](/trading/positions/manage#merge-positions) > > Convert a YES and NO token pair back into pUSD. > [card] [Redeem](/trading/positions/manage#redeem-resolved-positions) > > Exchange resolved outcome tokens for their payout. ## Token Flow ![pUSD can be split into YES and NO outcome tokens, which can be traded, merged, or redeemed after resolution.](https://mintcdn.com/polymarket-292d1b1b/FOMte3ewbG-LVy3k/images/core-concepts/token-flow.png?fit=max\&auto=format\&n=FOMte3ewbG-LVy3k\&q=85\&s=36f5a57946ac2b83136e17b6c06b358c) ## CTF Conditional Tokens owns the outcome balances. Each outcome token has a unique CTF position ID, used as its ERC-1155 token ID. CTF computes it onchain in three steps. **1. Compute the Condition ID** ```solidity theme={null} getConditionId(oracle, questionId, outcomeSlotCount) ``` | Parameter | Type | Value | | - | - | - | | `oracle` | `address` | [UMA CTF Adapter](https://github.com/Polymarket/uma-ctf-adapter) | | `questionId` | `bytes32` | Hash of the UMA ancillary data | | `outcomeSlotCount` | `uint` | `2` for binary markets | **2. Compute the Collection IDs** ```solidity theme={null} getCollectionId(parentCollectionId, conditionId, indexSet) ``` | Parameter | Type | Value | | - | - | - | | `parentCollectionId` | `bytes32` | `bytes32(0)` for top-level positions | | `conditionId` | `bytes32` | Condition ID from the previous step | | `indexSet` | `uint` | `1` (`0b01`) for the first outcome or `2` (`0b10`) for the second | The `indexSet` is a bitmask identifying which outcome slots belong to a collection. It must be a nonempty proper subset of the condition's outcome slots. A binary market has one collection for each outcome. **3. Compute the Position IDs** ```solidity theme={null} getPositionId(collateralToken, collectionId) ``` | Parameter | Type | Value | | - | - | - | | `collateralToken` | `IERC20` | pUSD contract address on Polygon | | `collectionId` | `bytes32` | Collection ID for one market outcome | The resulting position IDs are the ERC-1155 token IDs for the market's YES and NO outcomes. Most integrations should read these token IDs from market data. Computing them manually is only necessary for direct contract integrations. | Market type | Position operations | Trading contract | | - | - | - | | Standard binary | `CtfCollateralAdapter` | CTF Exchange | | Negative risk | `NegRiskCtfCollateralAdapter` | Negative Risk CTF Exchange | For a binary condition, index set `1` identifies YES and index set `2` identifies NO. Market data returns the resulting token IDs, so most integrations do not need to derive them. ## Polymarket Protocol V2 PositionManager owns every outcome balance and routes each Position ID to its registered module. The module ID is encoded in the Position ID. | Module ID | Module | Position shape | | - | - | - | | `1` | BinaryModule | One YES and one NO position | | `2` | NegRiskModule | One YES and one NO position for each event outcome | | `3` | CombinatorialModule | One YES and one NO position for a set of legs | ### Position ID A Position ID is the ERC-1155 token ID for a Polymarket Protocol V2 outcome. Its 256 bits encode the module, condition, and outcome that define the position. The first byte identifies the owning module, and the last byte identifies the outcome, with `0` for YES and `1` for NO. Treat the complete Position ID as an opaque decimal string in application code. ![The 256-bit position ID, split into moduleId, baseHash, arity, reserved, resolutionChain, conditionIndex, and outcomeIndex fields](https://mintcdn.com/polymarket-292d1b1b/_aswwXEhQSghbFEe/images/position-id-bit-layout.svg?fit=max\&auto=format\&n=_aswwXEhQSghbFEe\&q=85\&s=3f9b1b17df0c6e7de8157763a57886f4) The Router is the public entry point for splits, merges, redemptions, and module-specific position operations. A split requires pUSD approval for the Router. A merge or redemption requires PositionManager approval for the Router. ## Negative Risk and Combos Negative-risk events link several outcomes so a NO position can be converted into the complementary YES positions. The two systems implement that behavior through different contracts. See [Negative Risk Markets](/concepts/negative-risk) for the event model. Combos use PositionManager and the CombinatorialModule. Each leg is a Polymarket Protocol V2 Position ID from the BinaryModule or NegRiskModule. The resulting Combo is still a binary-shaped YES and NO pair, which allows it to use Exchange v3. See [Combinatorial Positions](/trading/positions/combinatorial) for the Combo position model. ## Contract Addresses See [Contracts](/resources/contracts) for Polymarket's current smart contract addresses on Polygon. # Manage Positions Source: https://docs.polymarket.com/trading/positions/manage Learn how to manage outcome-token inventory from creation through redemption. Manage positions outside the order book by splitting collateral into complete sets of outcome tokens, merging balanced tokens back into collateral, or redeeming winning tokens after resolution. Choose an operation based on how you want to change your position: | Operation | Use it when | | - | - | | Split | You need to convert collateral into a complete set of outcome tokens. | | Merge | You hold balanced outcome tokens and want to convert them back to collateral. | | Redeem | A market has resolved and you want to claim collateral for winning positions. | Choose the integration surface you will use to submit position operations. > [tab] TypeScript > > The examples on this page assume you have a `SecureClient` configured with > either a Relayer API key or a Builder API key. > > ```ts Relayer API Key theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.SIGNER_PRIVATE_KEY), > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: relayerApiKey({ > key: process.env.POLYMARKET_RELAYER_API_KEY!, > address: process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ```ts Builder API Key theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.SIGNER_PRIVATE_KEY), > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > See [Wallets and > Authentication](/trading/wallets-auth#execute-gasless-transactions) for the > complete wallet setup and Relayer authorization flow. > [tab] Python > > The examples on this page assume you have an `AsyncSecureClient` configured > with either a Relayer API key or a Builder API key. > > ```python Relayer API Key theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python Builder API Key theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > The synchronous `SecureClient` provides the same methods and supports both > API key types. > > See [Wallets and > Authentication](/trading/wallets-auth#execute-gasless-transactions) for the > complete wallet setup and Relayer authorization flow. > [tab] API > > Use a deployed Deposit Wallet and its owner signer to submit position calls through the Relayer. Complete [wallet setup and Relayer authorization](/trading/wallets-auth#execute-gasless-transactions), then set the request credentials: > > ```bash theme={null} > RELAYER_API_KEY="" > RELAYER_API_KEY_ADDRESS="" > ``` > > Use the target for the market's position system: > > | Position system | Market type | Target contract | Address | > | - | - | - | - | > | Polymarket V2 | Standard or negative risk | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > | CTF | Standard | CtfCollateralAdapter | `0xAdA100Db00Ca00073811820692005400218FcE1f` | > | CTF | Negative risk | NegRiskCtfCollateralAdapter | `0xadA2005600Dec949baf300f4C6120000bDB6eAab` | > > Replace `` with the selected address in both the signed call list and submission. For CTF, choose the adapter using the market's `negRisk` value. A market whose `version` is `"v2"` uses the Router. > [tab] Solidity > > Call the position contract directly from the address holding the collateral or outcome tokens. Select the target for the market's position system: > > | Position system | Market type | Target contract | Address | > | - | - | - | - | > | Polymarket V2 | Standard or negative risk | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | > | CTF | Standard | CtfCollateralAdapter | `0xAdA100Db00Ca00073811820692005400218FcE1f` | > | CTF | Negative risk | NegRiskCtfCollateralAdapter | `0xadA2005600Dec949baf300f4C6120000bDB6eAab` | > > Use these token contracts when granting approvals: > > | Asset | Contract | Address | > | - | - | - | > | Collateral | pUSD | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | Polymarket V2 outcome tokens | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > | CTF outcome tokens | Conditional Tokens | `0x4D97DCd97eC945f40cF65F87097ACe5EA0476045` | ## Split a Position Splitting converts pUSD into a complete set of outcome tokens. Every 1 pUSD produces 1 YES token and 1 NO token. ```text theme={null} 100 pUSD → 100 YES tokens + 100 NO tokens ``` Before splitting, ensure you have: 1. Enough pUSD in the wallet for the amount you want to split. 2. Approved the position call target for the market's position system to spend the wallet's pUSD. > [tab] TypeScript > > Call `splitPosition()` on a `SecureClient`. The client identifies the > position system from the condition ID and selects the correct route. > > ```ts theme={null} > const transaction = await client.splitPosition({ > conditionId: market.conditionId, > amount: 1_000_000n, > }); > > const outcome = await transaction.wait(); > > // outcome.transactionHash: TxHash > // outcome.transactionId: TransactionId | null > ``` > > `amount` is denominated in pUSD base units, so `1_000_000n` splits 1 pUSD > into 1 YES token and 1 NO token. `wait()` returns a `TransactionOutcome` > after the transaction settles. > [tab] Python > > Call `split_position()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method. Both clients identify the position > system from the condition ID and select the correct route. > > ```python theme={null} > transaction = await client.split_position( > condition_id=market.condition_id, > amount=1_000_000, > ) > > outcome = await transaction.wait() > > # outcome.transaction_hash: TransactionHash > # outcome.transaction_id: str | None > ``` > > `amount` is denominated in pUSD base units, so `1_000_000` splits 1 pUSD > into 1 YES token and 1 NO token. `wait()` returns a `TransactionOutcome` > after the transaction settles. > [tab] API > > Encode the split call, then sign and submit it as a Deposit Wallet batch. > > **1. Build the Position Call** > > Use the target from the API table in the setup above and the arguments for your position system: > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `partition` | — | `[1, 2]` | > | `amount` | Amount in six-decimal base units | Amount in six-decimal base units | > > ABI-encode the function for your market's protocol using the arguments above: > > ```solidity Polymarket V2 theme={null} > function split(bytes31 conditionId, uint256 amount); > ``` > > ```solidity CTF theme={null} > function splitPosition( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] partition, > uint256 amount > ); > ``` > > Place the resulting calldata in the wallet call list: > > ```json theme={null} > [ > { > "target": "", > "value": "0", > "data": "" > } > ] > ``` > > Use this list as `calls` in the wallet batch. > > **2. Submit the Batch** > > Include the encoded call in a signed Deposit Wallet batch and submit it with the Relayer API key: > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Split position", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > See [Execute Gasless Transactions](/trading/wallets-auth#execute-gasless-transactions) for nonce creation, wallet-batch signing, and confirmation. Wait for `STATE_CONFIRMED` before using the new balances. > [tab] Solidity > > Approve the selected position contract, then execute the split from the same address. > > **1. Approve pUSD** > > Call `approve` on pUSD from the address holding the collateral. Use the selected adapter or Router as `spender` and the split amount as `amount`: > > ```solidity theme={null} > function approve(address spender, uint256 amount) external returns (bool); > ``` > > An existing allowance covering the amount is sufficient. > > **2. Split the Position** > > Use the approved target from the Solidity table in the setup above. Call the function for your position system: > > ```solidity Polymarket V2 theme={null} > function split(bytes31 conditionId, uint256 amount); > ``` > > ```solidity CTF theme={null} > function splitPosition( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] partition, > uint256 amount > ); > ``` > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `partition` | — | `[1, 2]` | > | `amount` | Amount in six-decimal base units | Amount in six-decimal base units | ## Merge Positions Merging converts a complete set of outcome tokens back into pUSD. Every 1 YES token and 1 NO token returns 1 pUSD. ```text theme={null} 100 YES tokens + 100 NO tokens → 100 pUSD ``` Before merging, ensure you have: 1. Equal amounts of YES and NO tokens. 2. Approved the position call target for the market's position system to transfer the wallet's outcome tokens. > [tab] TypeScript > > Call `mergePositions()` on a `SecureClient`. The client identifies the > position system, selects the correct route, and checks the > wallet's mergeable balance. > > ```ts theme={null} > const transaction = await client.mergePositions({ > conditionId: market.conditionId, > amount: "max", > }); > > const outcome = await transaction.wait(); > > // outcome.transactionHash: TxHash > // outcome.transactionId: TransactionId | null > ``` > > Pass a base-unit `bigint` to merge a specific amount. `"max"` merges the > smaller of the wallet's YES and NO balances. `wait()` returns a > `TransactionOutcome` after the transaction settles. > [tab] Python > > Call `merge_positions()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method. Both clients identify the > position system, select the correct route, and check the wallet's > mergeable balance. > > ```python theme={null} > transaction = await client.merge_positions( > condition_id=market.condition_id, > amount="max", > ) > > outcome = await transaction.wait() > > # outcome.transaction_hash: TransactionHash > # outcome.transaction_id: str | None > ``` > > Pass a base-unit `int` to merge a specific amount. `"max"` merges the > smaller of the wallet's YES and NO balances. `wait()` returns a > `TransactionOutcome` after the transaction settles. > [tab] API > > Encode the merge call, then sign and submit it as a Deposit Wallet batch. > > **1. Build the Position Call** > > Use the target from the API table in the setup above and the arguments for your position system: > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `partition` | — | `[1, 2]` | > | `amount` | Amount in six-decimal base units | Amount in six-decimal base units | > > ABI-encode the function for your market's protocol using the arguments above: > > ```solidity Polymarket V2 theme={null} > function merge(bytes31 conditionId, uint256 amount); > ``` > > ```solidity CTF theme={null} > function mergePositions( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] partition, > uint256 amount > ); > ``` > > Place the resulting calldata in the wallet call list: > > ```json theme={null} > [ > { > "target": "", > "value": "0", > "data": "" > } > ] > ``` > > Use this list as `calls` in the wallet batch. > > **2. Submit the Batch** > > Include the encoded call in a signed Deposit Wallet batch and submit it with the Relayer API key: > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Merge position", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > See [Execute Gasless Transactions](/trading/wallets-auth#execute-gasless-transactions) for nonce creation, wallet-batch signing, and confirmation. Wait for `STATE_CONFIRMED` before using the new balances. > [tab] Solidity > > Approve the selected position contract, then execute the merge from the same address. > > **1. Approve Outcome Transfers** > > Call `setApprovalForAll` on the outcome-token ledger from the address holding the positions: > > ```solidity theme={null} > function setApprovalForAll(address operator, bool approved) external; > ``` > > | Position system | Token ledger | Operator | Approved | > | - | - | - | - | > | Polymarket V2 | PositionManager | Router | `true` | > | CTF | Conditional Tokens | Selected collateral adapter | `true` | > > Use the addresses in the Solidity setup above. An existing operator approval is sufficient. > > **2. Merge the Positions** > > Use the approved target from the Solidity table in the setup above. Call the function for your position system: > > ```solidity Polymarket V2 theme={null} > function merge(bytes31 conditionId, uint256 amount); > ``` > > ```solidity CTF theme={null} > function mergePositions( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] partition, > uint256 amount > ); > ``` > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `partition` | — | `[1, 2]` | > | `amount` | Amount in six-decimal base units | Amount in six-decimal base units | ## Redeem Resolved Positions Redeeming converts outcome tokens into pUSD after a market resolves. Each winning token returns 1 pUSD, while losing tokens return 0. ```text theme={null} Market resolves YES: 100 YES tokens → 100 pUSD 100 NO tokens → 0 pUSD ``` > [!NOTE] > > There is no redemption deadline. Winning tokens remain redeemable at any time > after resolution. Before redeeming, ensure you have: 1. A resolved market. 2. Outcome tokens for the market. 3. Approved the position call target for the market's position system to transfer the wallet's outcome tokens. > [tab] TypeScript > > Call `redeemPositions()` on a `SecureClient`. The client uses the condition > ID to select the correct route for the market's position system. > > ```ts theme={null} > const transaction = await client.redeemPositions({ > conditionId: market.conditionId, > }); > > const outcome = await transaction.wait(); > > // outcome.transactionHash: TxHash > // outcome.transactionId: TransactionId | null > ``` > > Redemption has no amount parameter: it redeems the wallet's balances for > both outcomes. `wait()` returns a `TransactionOutcome` after the transaction > settles. > [tab] Python > > Call `redeem_positions()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method. Both clients use the condition ID > to select the correct route for the market's position system. > > ```python theme={null} > transaction = await client.redeem_positions( > condition_id=market.condition_id, > ) > > outcome = await transaction.wait() > > # outcome.transaction_hash: TransactionHash > # outcome.transaction_id: str | None > ``` > > Redemption has no amount parameter: it redeems the wallet's balances for > both outcomes. `wait()` returns a `TransactionOutcome` after the transaction > settles. > [tab] API > > Encode the redeem call, then sign and submit it as a Deposit Wallet batch. > > **1. Build the Position Call** > > Use the target from the API table in the setup above and the arguments for your position system: > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `indexSets` | — | `[1, 2]` to redeem both outcomes | > | `outcomeIndex` | `0` for YES or `1` for NO | — | > | `amount` | Amount to redeem for the selected outcome, in base units | Redeems the selected outcome balances in full | > > ABI-encode the function for your market's protocol using the arguments above: > > ```solidity Polymarket V2 theme={null} > function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount); > ``` > > ```solidity CTF theme={null} > function redeemPositions( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] indexSets > ); > ``` > > Build the call list for the outcomes you want to redeem. Polymarket Protocol V2 uses one call per outcome. CTF can redeem both in one call. Include the calls in the same wallet batch. > > ```json Polymarket V2 theme={null} > [ > { > "target": "", > "value": "0", > "data": "" > }, > { > "target": "", > "value": "0", > "data": "" > } > ] > ``` > > ```json CTF theme={null} > [ > { > "target": "", > "value": "0", > "data": "" > } > ] > ``` > > Use this list as `calls` in the wallet batch. > > > [accordion] Derive V2 Inputs From a Position ID > > > > If you start with a Polymarket Protocol V2 Position ID, derive the condition and outcome locally, retaining all 256 bits: > > > > ```text Pseudocode theme={null} > > positionId = parseUnsigned256("") > > conditionId = encodeBytes31(positionId >> 8) > > outcomeIndex = positionId & 255 > > ``` > > > > `encodeBytes31` writes exactly 31 big-endian bytes, preserving leading zeros. For a YES/NO position, the outcome index is `0` or `1`. > > **2. Submit the Batch** > > Include the selected call list in the signed Deposit Wallet batch and submit it with the Relayer API key. This example redeems both Polymarket Protocol V2 outcomes: > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: $RELAYER_API_KEY" \ > -H "RELAYER_API_KEY_ADDRESS: $RELAYER_API_KEY_ADDRESS" \ > --data '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "Redeem position", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > }, > { > "target": "", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > See [Execute Gasless Transactions](/trading/wallets-auth#execute-gasless-transactions) for nonce creation, wallet-batch signing, and confirmation. Wait for `STATE_CONFIRMED` before using the new balances. > [tab] Solidity > > Approve the selected position contract, then execute the redeem from the same address. > > **1. Approve Outcome Transfers** > > Call `setApprovalForAll` on the outcome-token ledger from the address holding the positions: > > ```solidity theme={null} > function setApprovalForAll(address operator, bool approved) external; > ``` > > | Position system | Token ledger | Operator | Approved | > | - | - | - | - | > | Polymarket V2 | PositionManager | Router | `true` | > | CTF | Conditional Tokens | Selected collateral adapter | `true` | > > Use the addresses in the Solidity setup above. An existing operator approval is sufficient. > > **2. Redeem the Positions** > > Use the approved target from the Solidity table in the setup above. Call the function for your position system: > > ```solidity Polymarket V2 theme={null} > function redeem(bytes31 conditionId, uint256 outcomeIndex, uint256 amount); > ``` > > ```solidity CTF theme={null} > function redeemPositions( > address collateralToken, > bytes32 parentCollectionId, > bytes32 conditionId, > uint256[] indexSets > ); > ``` > > | Argument | Polymarket V2 | CTF | > | - | - | - | > | `conditionId` | 31-byte Polymarket V2 condition ID | Original 32-byte CTF condition ID | > | `collateralToken` | — | pUSD: `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | `parentCollectionId` | — | 32 zero bytes | > | `indexSets` | — | `[1, 2]` to redeem both outcomes | > | `outcomeIndex` | `0` for YES or `1` for NO | — | > | `amount` | Amount to redeem for the selected outcome, in base units | Redeems the selected outcome balances in full | > > Polymarket Protocol V2 redeems one outcome and an explicit amount per call. Both calls can execute in one transaction. CTF redeems both selected outcome balances in one call. > > > [accordion] Derive V2 Inputs From a Position ID > > > > If you start with a Polymarket Protocol V2 Position ID, derive the condition and outcome locally, retaining all 256 bits: > > > > ```text Pseudocode theme={null} > > positionId = parseUnsigned256("") > > conditionId = encodeBytes31(positionId >> 8) > > outcomeIndex = positionId & 255 > > ``` > > > > `encodeBytes31` writes exactly 31 big-endian bytes, preserving leading zeros. For a YES/NO position, the outcome index is `0` or `1`. # Place Your First Order Source: https://docs.polymarket.com/trading/quickstart Learn how to authenticate with the CLOB and submit your first market order. This guide shows you how to place your first order using an existing Polymarket account. For this guide, we recommend having at least 10 pUSD available. Create or fund an account at [polymarket.com](https://polymarket.com/) before you start. Find your Polymarket wallet address in your profile menu: ![Polymarket profile menu showing the account wallet address on desktop](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/deposit-wallet-desktop.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=6be3b87c53d6718f973db37e134ee944) ![Polymarket profile menu showing the account wallet address on mobile](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/deposit-wallet-mobile.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=4d6f87ed5440c5297e60d6331c47dc73) **1. Authenticate** First, authenticate with the CLOB. > [tab] TypeScript > > Pass the signer and wallet address to `createSecureClient`. > > ```ts theme={null} > import { createSecureClient, OrderSide } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > }); > ``` > > > [!NOTE] > > > > This example uses Viem. See [Wallet > > Integrations](/getting-started/typescript#wallet-integrations) to connect a > > signer from another supported wallet library. > [tab] Python > > Pass the private key and wallet address to `AsyncSecureClient.create`. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` **2. Choose an Outcome** Then, fetch the market and select the outcome you want to buy. See [Market Data](/market-data/overview) to find a different market. > [tab] TypeScript > > ```ts theme={null} > const market = await client.fetchMarket({ > slug: "will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > }); > ``` > > Choose an outcome (YES in this example) and select its trading identifier based on the market version. > > ```ts theme={null} > const { yes, no } = market.outcomes; > const assetId = market.version === "v2" ? yes.positionId : yes.tokenId; > ``` > > The unified SDK uses `assetId` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. > [tab] Python > > ```python theme={null} > market = await client.get_market( > slug="will-the-us-confirm-that-aliens-exist-before-2027-789-924-249", > ) > ``` > > Choose an outcome (YES in this example) and select its trading identifier based on the market version. > > ```python theme={null} > yes = market.outcomes.yes > asset_id = yes.position_id if market.version == "v2" else yes.token_id > ``` > > The unified SDK uses `asset_id` for an outcome's trading identifier: a token > ID for a CTF market or a position ID for a Polymarket Protocol V2 market. > Use the identifier exposed for that outcome. **3. Place a Market Order** Then, submit a small market buy. The order fills against available liquidity, and any unfilled amount is canceled instead of remaining open. > [tab] TypeScript > > Use `placeMarketOrder` to place the market order. > > ```ts theme={null} > const response = await client.placeMarketOrder({ > assetId, > side: OrderSide.BUY, > amount: "10", // Spend up to 10 pUSD > }); > > if (!response.ok) { > throw new Error(response.message); > } > > // response.orderId: string > ``` > [tab] Python > > Use `place_market_order` to place the market order. > > ```python theme={null} > response = await client.place_market_order( > asset_id=asset_id, > side="BUY", > amount="10", # Spend up to 10 pUSD > ) > > if not response.ok: > raise RuntimeError(response.message) > > # response.order_id: str > ``` **4. Wait for Settlement** Your order matched, but its trade settles on-chain asynchronously. Wait for settlement before checking your position. > [tab] TypeScript > > Use `waitForOrderFillSettlement` to wait for the trade to settle. > > ```ts theme={null} > const hashes = await client.waitForOrderFillSettlement(response); > > // hashes: TxHash[] > ``` > [tab] Python > > Use `wait_for_order_fill_settlement` to wait for the trade to settle. > > ```python theme={null} > hashes = await client.wait_for_order_fill_settlement(response) > > # hashes: tuple[TransactionHash, ...] > ``` **5. Check Your Position** Finally, list your positions for the selected market and find the outcome you bought. > [tab] TypeScript > > ```ts theme={null} > const page = await client > .listPositions({ > market: [market.conditionId!], > }) > .firstPage(); > > const position = page.items.find((item) => item.assetId === assetId); > if (!position) { > throw new Error("Position not found."); > } > > const positionSize = position.size; // Outcome shares held > ``` > [tab] Python > > ```python theme={null} > condition_id = market.condition_id > assert condition_id is not None > > page = await client.list_positions(market=[condition_id]).first_page() > > position = next( > (item for item in page.items if item.asset_id == asset_id), > None, > ) > if position is None: > raise RuntimeError("Position not found.") > > position_size = position.size # Outcome shares held > ``` You placed your first market order on Polymarket. To let a separate signer place and cancel orders without using the owner key, continue to [Session Keys](/trading/session-keys). # Real-Time Order Updates Source: https://docs.polymarket.com/trading/realtime-order-updates React to authenticated order and trade activity as it happens. Use real-time order updates to keep your view of a trading account current without polling. The user stream reports changes to the account's orders and the trades created when those orders match. For public order-book and market updates, see [Real-Time Data](/market-data/realtime-data). > [!NOTE] > > Before subscribing, authenticate the account whose activity you want to > monitor. See [Wallets and Authentication](/trading/wallets-auth). ## User Stream The user stream delivers order changes and trade updates for the authenticated account. Subscribe without a market filter to follow the entire account, or provide condition IDs to follow selected markets. > [tab] TypeScript > > Given a `SecureClient`, subscribe to the `user` topic: > > ```ts theme={null} > const stream = await client.subscribe([{ topic: "user" }]); > > for await (const event of stream) { > switch (event.type) { > case "order": > // event: UserOrderEvent > break; > case "trade": > // event: UserTradeEvent > break; > } > } > ``` > > > [accordion] User Events > > > > #### Order Update > > > > ```ts UserOrderEvent Type theme={null} > > type UserOrderEvent = { > > topic: "user"; > > type: "order"; > > payload: { > > id: string; > > owner: string; > > conditionId: ConditionId; > > assetId: ClobAssetId; > > side: OrderSide; > > orderOwner?: string | null; > > originalSize: DecimalString; > > sizeMatched: DecimalString; > > price: DecimalString; > > associateTrades?: string[] | null; > > outcome?: string | null; > > orderEventType: "PLACEMENT" | "UPDATE" | "CANCELLATION"; > > createdAt?: IsoDateTimeString | null; > > expiresAt?: IsoDateTimeString | null; > > orderType?: "GTC" | "FOK" | "GTD" | "FAK" | null; > > status?: "LIVE" | "MATCHED" | "DELAYED" | "UNMATCHED" | "CANCELED" | null; > > makerAddress?: string | null; > > timestamp: EpochMilliseconds; > > }; > > }; > > ``` > > > > ```json UserOrderEvent Example theme={null} > > { > > "topic": "user", > > "type": "order", > > "payload": { > > "id": "", > > "owner": "", > > "conditionId": "", > > "assetId": "", > > "side": "BUY", > > "originalSize": "10", > > "sizeMatched": "0", > > "price": "0.52", > > "outcome": "Yes", > > "orderEventType": "PLACEMENT", > > "status": "LIVE", > > "timestamp": 1782753357257 > > } > > } > > ``` > > > > #### Trade Update > > > > ```ts UserTradeEvent Type theme={null} > > type TradeMakerOrder = { > > orderId: string; > > owner: string; > > makerAddress?: string | null; > > matchedAmount: DecimalString; > > price: DecimalString; > > feeRateBps?: DecimalString | null; > > assetId: ClobAssetId; > > outcome?: string | null; > > outcomeIndex?: number | null; > > side: OrderSide; > > }; > > > > type UserTradeEvent = { > > topic: "user"; > > type: "trade"; > > payload: { > > id: string; > > takerOrderId: string; > > conditionId: ConditionId; > > assetId: ClobAssetId; > > side: OrderSide; > > size: DecimalString; > > feeRateBps?: DecimalString | null; > > price: DecimalString; > > status: > > | "TRADE_STATUS_MATCHED" > > | "TRADE_STATUS_MATCHED_NOT_BROADCASTED" > > | "TRADE_STATUS_MINED" > > | "TRADE_STATUS_CONFIRMED" > > | "TRADE_STATUS_RETRYING" > > | "TRADE_STATUS_FAILED"; > > matchedAt?: IsoDateTimeString | null; > > updatedAt?: IsoDateTimeString | null; > > outcome?: string | null; > > owner: string; > > tradeOwner?: string | null; > > makerAddress?: string | null; > > transactionHash?: string | null; > > bucketIndex?: number | null; > > makerOrders?: TradeMakerOrder[] | null; > > traderSide?: "TAKER" | "MAKER" | null; > > timestamp: EpochMilliseconds; > > }; > > }; > > ``` > > > > ```json UserTradeEvent Example theme={null} > > { > > "topic": "user", > > "type": "trade", > > "payload": { > > "id": "", > > "takerOrderId": "", > > "conditionId": "", > > "assetId": "", > > "side": "BUY", > > "size": "10", > > "price": "0.52", > > "status": "TRADE_STATUS_MATCHED", > > "owner": "", > > "traderSide": "TAKER", > > "timestamp": 1782753357257 > > } > > } > > ``` > > Use `sizeMatched` on order updates for cumulative filled quantity. For > individual fills, match trade updates by `takerOrderId` or > `makerOrders[].orderId`. `associateTrades` may be absent or empty; neither > means the order has no fills. > > To receive updates only for selected markets, pass their condition IDs in > `markets`: > > ```ts theme={null} > const stream = await client.subscribe([ > { > topic: "user", > markets: [""], > }, > ]); > ``` > [tab] Python > > Given an `AsyncSecureClient`, subscribe with `UserSpec`. > Real-time subscriptions are not available from the synchronous > `SecureClient`. > > ```python theme={null} > from polymarket.streams import UserSpec > > > async with await client.subscribe(UserSpec()) as stream: > async for event in stream: > if event.type == "order": > ... # event: UserOrderEvent > elif event.type == "trade": > ... # event: UserTradeEvent > ``` > > > [accordion] User Events > > > > #### Order Update > > > > ```python UserOrderEvent Type theme={null} > > class UserOrderPayload: > > id: str > > owner: str > > condition_id: ConditionId > > asset_id: ClobAssetId > > side: Literal["BUY", "SELL"] > > order_owner: str | None > > original_size: Decimal > > size_matched: Decimal > > price: Decimal > > associate_trades: tuple[str, ...] | None > > outcome: str | None > > order_event_type: Literal["PLACEMENT", "UPDATE", "CANCELLATION"] > > created_at: datetime | None > > expires_at: datetime | None > > order_type: Literal["GTC", "FOK", "IOC", "GTD", "FAK"] | None > > status: Literal["LIVE", "MATCHED", "DELAYED", "UNMATCHED", "CANCELED"] | None > > maker_address: str | None > > timestamp: datetime | None > > > > class UserOrderEvent: > > topic: Literal["user"] > > type: Literal["order"] > > payload: UserOrderPayload > > ``` > > > > ```json UserOrderEvent Example theme={null} > > { > > "topic": "user", > > "type": "order", > > "payload": { > > "id": "", > > "owner": "", > > "condition_id": "", > > "asset_id": "", > > "side": "BUY", > > "original_size": "10", > > "size_matched": "0", > > "price": "0.52", > > "outcome": "Yes", > > "order_event_type": "PLACEMENT", > > "status": "LIVE", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > > > #### Trade Update > > > > ```python UserTradeEvent Type theme={null} > > class UserTradeMakerOrder: > > order_id: str > > owner: str > > maker_address: str | None > > matched_amount: Decimal > > price: Decimal > > fee_rate_bps: Decimal | None > > asset_id: ClobAssetId > > outcome: str | None > > outcome_index: int | None > > side: Literal["BUY", "SELL"] > > > > class UserTradePayload: > > id: str > > taker_order_id: str > > condition_id: ConditionId > > asset_id: ClobAssetId > > side: Literal["BUY", "SELL"] > > size: Decimal > > fee_rate_bps: Decimal | None > > price: Decimal > > status: Literal[ > > "MATCHED", > > "MATCHED_NOT_BROADCASTED", > > "MINED", > > "CONFIRMED", > > "RETRYING", > > "FAILED", > > ] > > matched_at: datetime | None > > updated_at: datetime | None > > outcome: str | None > > owner: str > > trade_owner: str | None > > maker_address: str | None > > transaction_hash: str | None > > bucket_index: int | None > > maker_orders: tuple[UserTradeMakerOrder, ...] | None > > trader_side: Literal["TAKER", "MAKER"] | None > > timestamp: datetime | None > > > > class UserTradeEvent: > > topic: Literal["user"] > > type: Literal["trade"] > > payload: UserTradePayload > > ``` > > > > ```json UserTradeEvent Example theme={null} > > { > > "topic": "user", > > "type": "trade", > > "payload": { > > "id": "", > > "taker_order_id": "", > > "condition_id": "", > > "asset_id": "", > > "side": "BUY", > > "size": "10", > > "price": "0.52", > > "status": "MATCHED", > > "owner": "", > > "trader_side": "TAKER", > > "timestamp": "2026-06-29T17:15:57.257000Z" > > } > > } > > ``` > > Use `size_matched` on order updates for cumulative filled quantity. For > individual fills, match trade updates by `taker_order_id` or > `maker_orders[].order_id`. `associate_trades` may be absent or empty; neither > means the order has no fills. > > To receive updates only for selected markets, pass their condition IDs to > `UserSpec`: > > ```python theme={null} > async with await client.subscribe( > UserSpec(markets=[""]), > ) as stream: > async for event in stream: > ... > ``` > [tab] API > > Connect to the authenticated user WebSocket: > > ```text theme={null} > wss://ws-subscriptions-clob.polymarket.com/ws/user > ``` > > > [!NOTE] > > > > The user WebSocket uses an application-level heartbeat. Send the text frame > > `PING` every 10 seconds. The server replies with `PONG`. > > Once connected, send a `user` subscription frame with the CLOB API > credentials created through [API > Authentication](/getting-started/api#authentication): > > ```json theme={null} > { > "auth": { > "apiKey": "", > "secret": "", > "passphrase": "" > }, > "type": "user" > } > ``` > > > [!WARNING] > > > > Send the subscription frame immediately after connecting. The server may close > > a connection that remains unsubscribed. > > > [!WARNING] > > > > Keep CLOB API credentials in a server environment. Never expose them in > > client-side code. > > On the wire, `event_type` distinguishes order and trade events. For an > order event, `type` identifies whether the order was placed, updated, or > canceled. > > > [accordion] User Events > > > > #### Order Update > > > > ```json theme={null} > > { > > "event_type": "order", > > "id": "", > > "owner": "", > > "market": "", > > "asset_id": "", > > "side": "BUY", > > "order_owner": "", > > "original_size": "10", > > "size_matched": "0", > > "price": "0.52", > > "associate_trades": null, > > "outcome": "Yes", > > "type": "PLACEMENT", > > "created_at": "1782753357", > > "expiration": "0", > > "order_type": "GTC", > > "status": "LIVE", > > "maker_address": "", > > "timestamp": "1782753357257" > > } > > ``` > > > > #### Trade Update > > > > ```json theme={null} > > { > > "event_type": "trade", > > "type": "TRADE", > > "id": "", > > "taker_order_id": "", > > "market": "", > > "asset_id": "", > > "side": "BUY", > > "size": "10", > > "fee_rate_bps": "0", > > "price": "0.52", > > "status": "MATCHED", > > "match_time": "1782753357", > > "last_update": "1782753357", > > "outcome": "Yes", > > "owner": "", > > "trade_owner": "", > > "maker_address": "", > > "transaction_hash": null, > > "bucket_index": 0, > > "maker_orders": [ > > { > > "order_id": "", > > "owner": "", > > "maker_address": "", > > "matched_amount": "10", > > "price": "0.52", > > "fee_rate_bps": "0", > > "asset_id": "", > > "outcome": "Yes", > > "outcome_index": 0, > > "side": "SELL" > > } > > ], > > "trader_side": "TAKER", > > "timestamp": "1782753357257" > > } > > ``` > > Use `size_matched` on order events for cumulative filled quantity. For > individual fills, match trade events by `taker_order_id` or > `maker_orders[].order_id`. `associate_trades` may be absent, `null`, or empty; > none of these means the order has no fills. > > To receive updates only for selected markets, include their condition IDs > in the initial subscription frame: > > ```json theme={null} > { > "auth": { > "apiKey": "", > "secret": "", > "passphrase": "" > }, > "markets": [""], > "type": "user" > } > ``` > > You can add or remove market filters without reconnecting: > > ```json Subscribe theme={null} > { > "operation": "subscribe", > "markets": [""] > } > ``` > > ```json Unsubscribe theme={null} > { > "operation": "unsubscribe", > "markets": [""] > } > ``` ## Understand Order Updates Order updates tell you why the account's open-order state changed: | Update | Meaning | | - | - | | Placement | A new order was accepted. | | Update | Some or all of the order matched. | | Cancellation | The remaining open amount was canceled. | ## Understand Trade Updates Trade updates follow a match through onchain settlement. Confirmation and permanent failure are terminal. A trade being retried may later be mined and confirmed. | State | Terminal | Meaning | | - | - | - | | Matched, not broadcast | No | The orders matched before an onchain transaction was broadcast. | | Matched | No | The orders matched and the transaction was submitted for execution. | | Mined | No | The transaction was observed onchain but has not reached finality. | | Confirmed | Yes | The trade reached finality successfully. | | Retrying | No | Settlement failed temporarily and is being retried. | | Failed | Yes | Settlement failed permanently. | ## Recover After Reconnecting Real-time updates do not replace authoritative account reads or replay every change missed during a disconnection. After reconnecting, fetch the account's open orders and recent trades from [Manage Orders](/trading/manage-orders), then resume applying new stream events from that refreshed state. # Session Keys Source: https://docs.polymarket.com/trading/session-keys Authorize a separate signer for scoped, time-limited Deposit Wallet trading. A Session Key is a separate signer that a Deposit Wallet Owner authorizes to trade for a Deposit Wallet. It lets an integration perform routine trading without using the owner's key. A Session Key cannot withdraw funds from the Deposit Wallet. > [!NOTE] > > Session Keys work only with Deposit Wallets. A dedicated migration flow from > Safe Wallets and Proxy Wallets is planned. A Session Key can be scoped to trade on specific supported venues or all venues: * **CLOB:** [Place prediction market orders](/trading/place-orders) on the central limit order book. * **Combos:** [Trade Combos through RFQs](/trading/combos/overview). * **All:** A shortcut that grants access to CLOB, Combos, and any future supported venues. ## Authorize a Session Key The Deposit Wallet Owner authorizes a session signer address with an expiration of 180 days and scoped permissions. > [!WARNING] > > Session Keys are Externally Owned Accounts (EOAs). Keep their private keys > secret to prevent unauthorized trading on behalf of your Deposit Wallet. Authorizing or revoking a Session Key requires a [Relayer API key](https://polymarket.com/settings?tab=api-keys) for the Deposit Wallet Owner's address or a [Builder API key](/trading/wallets-auth#create-new-accounts). > [tab] TypeScript > > **1. Generate a Session Key** > > First, generate a fresh EVM keypair for the Session Key. > > ```ts theme={null} > import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; > > const sessionKeyPrivateKey = generatePrivateKey(); > const { address: sessionKeyAddress } = > privateKeyToAccount(sessionKeyPrivateKey); > ``` > > Store **your private key** in a secrets manager or another secure key > store. > > **2. Create the Deposit Wallet Owner Client** > > Then, create a `SecureClient` with the Deposit Wallet Owner's private key > and either a Relayer API key or Builder API credentials. > > ```ts Relayer API Key theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const secureClient = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > wallet: process.env.POLYMARKET_DEPOSIT_WALLET!, > apiKey: relayerApiKey({ > key: process.env.POLYMARKET_RELAYER_API_KEY!, > address: process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ```ts Builder API Key theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const secureClient = await createSecureClient({ > signer: privateKey(process.env.POLYMARKET_PRIVATE_KEY), > wallet: process.env.POLYMARKET_DEPOSIT_WALLET!, > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > In `relayerApiKey()`, `address` is the Deposit Wallet Owner's address. > > **3. Authorize the Session Key** > > Finally, call `authorizeSessionKey()` to authorize your Session Key. > > ```ts theme={null} > const authorization = await secureClient.authorizeSessionKey({ > address: sessionKeyAddress, > }); > > // authorization: AuthorizeSessionKeyResult > ``` > > You can also authorize only the desired trading venues with the `scopes` > parameter: > > ```ts theme={null} > import { SessionKeyKnownScope } from "@polymarket/client"; > > const scopedAuthorization = await secureClient.authorizeSessionKey({ > address: sessionKeyAddress, > scopes: [SessionKeyKnownScope.CLOB, SessionKeyKnownScope.COMBOSRFQ], > }); > > // scopedAuthorization: AuthorizeSessionKeyResult > ``` > [tab] Python > > **1. Generate a Session Key** > > First, generate a fresh EVM keypair for the Session Key. > > ```python theme={null} > from eth_account import Account > > session_key = Account.create() > session_key_private_key = "0x" + session_key.key.hex().removeprefix("0x") > session_key_address = session_key.address > ``` > > Store **your private key** in a secrets manager or another secure key > store. > > **2. Create the Deposit Wallet Owner Client** > > Then, create an `AsyncSecureClient` with the Deposit Wallet Owner's > private key and either a Relayer API key or Builder API credentials. > > ```python Relayer API Key theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > secure_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_DEPOSIT_WALLET"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python Builder API Key theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > secure_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_DEPOSIT_WALLET"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > In `RelayerApiKey`, `address` is the Deposit Wallet Owner's address. > > **3. Authorize the Session Key** > > Finally, call `authorize_session_key()` to authorize your Session Key. > > ```python theme={null} > authorization = await secure_client.authorize_session_key( > address=session_key_address, > ) > > # authorization: AuthorizeSessionKeyResult > ``` > > You can also authorize only the desired trading venues with the `scopes` > parameter: > > ```python theme={null} > from polymarket import SessionKeyKnownScope > > scoped_authorization = await secure_client.authorize_session_key( > address=session_key_address, > scopes=( > SessionKeyKnownScope.CLOB, > SessionKeyKnownScope.COMBOSRFQ, > ), > ) > > # scoped_authorization: AuthorizeSessionKeyResult > ``` > [tab] API > > Authorize the session signer through the Relayer, then confirm that it is > available for trading. > > **1. Generate a Session Key** > > First, generate a fresh EVM keypair for the Session Key: > > ```bash Foundry theme={null} > $ cast wallet new > Successfully created new keypair. > Address: > Private key: > ``` > > ```ts Viem theme={null} > import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"; > > const sessionSignerPrivateKey = generatePrivateKey(); > const { address: sessionSignerAddress } = privateKeyToAccount( > sessionSignerPrivateKey, > ); > ``` > > Store the `` in a secrets manager or another > secure key store. > > **2. Fetch the Wallet Nonce** > > Then, fetch the Deposit Wallet's `WALLET` nonce by passing the Deposit > Wallet Owner address. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the Deposit Wallet nonce: > > ```json Response theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **3. Define the Session Key Authorization** > > Then, encode the `authorizeSessionSigner` call that the Deposit Wallet > will execute: > > ```solidity theme={null} > function authorizeSessionSigner(address sessionSigner, uint256 validUntil) > ``` > > `validUntil` is required. Always set it to the current whole Unix > timestamp in seconds plus 180 days. Other values are rejected. The > following Viem example computes this value: > > ```ts Example theme={null} > import { encodeFunctionData, parseAbi } from "viem" > > const sessionSignerAddress = "" as `0x${string}` > const sessionExpiryUnixSeconds = BigInt( > Math.floor(Date.now() / 1_000) + 4_315 * 60 * 60, > ) > > const calldata = encodeFunctionData({ > abi: parseAbi([ > "function authorizeSessionSigner(address sessionSigner, uint256 validUntil)", > ]), > functionName: "authorizeSessionSigner", > args: [sessionSignerAddress, sessionExpiryUnixSeconds], > }) > ``` > > **4. Prepare the Owner Authorization** > > Then, prepare the EIP-712 typed data for the Deposit Wallet Owner to > approve: > > ```json walletBatchTypedData theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > } > ``` > > Where: > > * `` is the Deposit Wallet address. > * `` is the nonce returned when fetching the Deposit > Wallet nonce. > * `` is a future whole Unix timestamp in > seconds after which the signed authorization request can no longer be > executed. The Relayer requires at least 10 seconds of remaining > validity. > * `` is the encoded authorization call from the previous step. > > **5. Sign as the Deposit Wallet Owner** > > Then, prove that the Deposit Wallet Owner approves the authorization by > signing the typed data. The following example uses Viem: > > ```ts TypeScript with Viem theme={null} > import { privateKeyToAccount } from "viem/accounts" > > const depositWalletOwner = privateKeyToAccount( > process.env.DEPOSIT_WALLET_OWNER_PRIVATE_KEY as `0x${string}`, > ) > > const signature = await depositWalletOwner.signTypedData(walletBatchTypedData) > ``` > > **6. Build the Authorization Body** > > Then, build the request body that authorizes the session signer: > > ```json theme={null} > { > "walletAddress": "", > "sessionSignerAddress": "", > "scopes": ["CLOB", "COMBOSRFQ"], > "validUntil": "", > "nonce": "", > "deadline": "", > "signature": "" > } > ``` > > Where: > > * `` is the Deposit Wallet address. > * `` and `` are the > signer and expiration encoded in ``. > * `scopes` contains one or more venue literals (`"CLOB"` or > `"COMBOSRFQ"`), or `["ALL"]` by itself. > * `` and `` match the values > in the signed typed data. > * `` is the value returned in the previous step. > > **7. Submit the Authorization** > > Then, submit the authorization request to the Relayer with your Relayer > API key or Builder API key: > > ```bash Relayer API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/v1/session-signers/authorizations" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > -H "Idempotency-Key: " \ > -d '{ > "walletAddress": "", > "sessionSignerAddress": "", > "scopes": ["CLOB", "COMBOSRFQ"], > "validUntil": "", > "nonce": "", > "deadline": "", > "signature": "" > }' > ``` > > ```bash Builder API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/v1/session-signers/authorizations" \ > -H "Content-Type: application/json" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " \ > -H "Idempotency-Key: " \ > -d '{ > "walletAddress": "", > "sessionSignerAddress": "", > "scopes": ["CLOB", "COMBOSRFQ"], > "validUntil": "", > "nonce": "", > "deadline": "", > "signature": "" > }' > ``` > > Where: > > * `` uniquely identifies this authorization request. > Reuse it when retrying the same request. > * `` is your Relayer API key, and > `` is the Deposit Wallet Owner address > the key belongs to. > * `` and `` are your Builder API > credentials. > * `` and `` authenticate a Builder > API key request. Create the signature from the exact serialized > request body: > > ```text theme={null} > authorization_body = > request_timestamp = > method = "POST" > request_path = "/v1/session-signers/authorizations" > > message = request_timestamp + method + request_path + authorization_body > builder_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The response includes the Relayer transaction ID used to confirm the > authorization: > > ```json Response theme={null} > { > "operationId": "", > "status": "SUBMITTED", > "transactionHash": "", > "transactionId": "" > } > ``` > > **8. Confirm the Relayer Transaction** > > Then, poll the transaction endpoint using the returned > ``: > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" > ``` > > Continue until `state` is `STATE_CONFIRMED`. Treat `STATE_FAILED` and > `STATE_INVALID` as terminal failures. > > ```json Response theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > **9. Poll for the Session Key** > > Finally, poll the Session Keys endpoint until it returns the Session > Key with the expected scopes and expiration: > > ```bash theme={null} > curl "https://clob.polymarket.com/v1/user/session-signers" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > Using the Deposit Wallet Owner's CLOB credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > timestamp for each request and calculate `` from the > exact request path: > > ```text theme={null} > clob_request_timestamp = > method = "GET" > request_path = "/v1/user/session-signers" > > message = clob_request_timestamp + method + request_path > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Continue until `signers` contains the requested session signer with the > expected scopes and expiration. The authorization is ready for use > only after the session signer appears in the response. > > ```json Response theme={null} > { > "wallet": "", > "signers": [ > { > "address": "", > "scopes": ["CLOB", "COMBOSRFQ"], > "valid_until": 1800000000 // > } > ] > } > ``` ## Place an Order This section shows how to place an order using a Session Key. See [Place Orders](/trading/place-orders) for the complete order workflow. > [tab] TypeScript > > **1. Create the Session Client** > > First, create a `SecureClient` for the Deposit Wallet with the session > signer. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const sessionPrivateKey = process.env.POLYMARKET_SESSION_PRIVATE_KEY!; > const depositWallet = process.env.POLYMARKET_DEPOSIT_WALLET!; > > const sessionClient = await createSecureClient({ > signer: privateKey(sessionPrivateKey), > wallet: depositWallet, > }); > ``` > > **2. Place an Order** > > Then, submit a limit order with the already-selected `assetId`. > > ```ts theme={null} > import { OrderSide } from "@polymarket/client"; > > const response = await sessionClient.placeLimitOrder({ > assetId, > side: OrderSide.BUY, > price: "0.52", > size: "10", > }); > > // response: OrderResponse > ``` > > The order buys `10` shares at a price of `0.52` USD per share. See > [Place Orders](/trading/place-orders#place-a-limit-order) for market > constraints, order types, and response handling. > [tab] Python > > **1. Create the Session Client** > > First, create an `AsyncSecureClient` for the Deposit Wallet with the > Session Key. > > ```python theme={null} > from polymarket import AsyncSecureClient > > session_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_SESSION_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_DEPOSIT_WALLET"], > ) > ``` > > **2. Place an Order** > > Then, submit a limit order with the already-selected `asset_id`. > > ```python theme={null} > response = await session_client.place_limit_order( > asset_id=asset_id, > side="BUY", > price="0.52", > size="10", > ) > > # response: OrderResponse > ``` > > The order buys `10` shares at a price of `0.52` USD per share. See > [Place Orders](/trading/place-orders#place-a-limit-order) for market > constraints, order types, and response handling. > [tab] API > > Authenticate with the CLOB using the Session Key, then place an order. See > [API Authentication](/getting-started/api#authentication) for the complete > signing flow. > > **1. Create a CLOB L1 Signature** > > First, create a `` with the Session Key to prove > control of the session signer. > > ```json ClobAuth theme={null} > { > "domain": { > "name": "ClobAuthDomain", > "version": "1", > "chainId": 137 > }, > "types": { > "ClobAuth": [ > { "name": "address", "type": "address" }, > { "name": "timestamp", "type": "string" }, > { "name": "nonce", "type": "uint256" }, > { "name": "message", "type": "string" } > ] > }, > "primaryType": "ClobAuth", > "message": { > "address": "", > "timestamp": "", > "nonce": "", > "message": "This message attests that I control the given wallet" > } > } > ``` > > **2. Create or Derive CLOB Credentials** > > Then, create CLOB credentials for the session signer. If credentials > already exist, derive them instead. > > ```bash Create theme={null} > curl -X POST "https://clob.polymarket.com/auth/api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > ```bash Derive theme={null} > curl "https://clob.polymarket.com/auth/derive-api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > `` identifies the credential set. Use `0` unless you manage > multiple credential sets. > > The response contains the credentials used to authenticate the order > request: > > ```json theme={null} > { > "apiKey": "", > "secret": "", > "passphrase": "" > } > ``` > > **3. Create the Order Typed Data** > > Select the outcome identifier and signing domain as shown in > [Place Orders](/trading/place-orders#create-the-order-typed-data), > then create the Deposit Wallet typed data using these values: > > | Field | Value | > | - | - | > | `maker` | `` | > | `signer` | `` | > | `signatureType` | `3` | > > > [accordion] TypedDataSign Example > > > > ```json TypedDataSign theme={null} > > { > > "domain": { > > "name": "Polymarket CTF Exchange", > > "version": "", > > "chainId": 137, > > "verifyingContract": "" > > }, > > "types": { > > "Order": [ > > { "name": "salt", "type": "uint256" }, > > { "name": "maker", "type": "address" }, > > { "name": "signer", "type": "address" }, > > { "name": "tokenId", "type": "uint256" }, > > { "name": "makerAmount", "type": "uint256" }, > > { "name": "takerAmount", "type": "uint256" }, > > { "name": "side", "type": "uint8" }, > > { "name": "signatureType", "type": "uint8" }, > > { "name": "timestamp", "type": "uint256" }, > > { "name": "metadata", "type": "bytes32" }, > > { "name": "builder", "type": "bytes32" } > > ], > > "TypedDataSign": [ > > { "name": "contents", "type": "Order" }, > > { "name": "name", "type": "string" }, > > { "name": "version", "type": "string" }, > > { "name": "chainId", "type": "uint256" }, > > { "name": "verifyingContract", "type": "address" }, > > { "name": "salt", "type": "bytes32" } > > ] > > }, > > "primaryType": "TypedDataSign", > > "message": { > > "contents": { > > "salt": "479249096354", > > "maker": "", > > "signer": "", > > "tokenId": "", > > "makerAmount": "5200000", > > "takerAmount": "10000000", > > "side": 0, > > "signatureType": 3, > > "timestamp": "", > > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000" > > }, > > "name": "DepositWallet", > > "version": "1", > > "chainId": 137, > > "verifyingContract": "", > > "salt": "0x0000000000000000000000000000000000000000000000000000000000000000" > > } > > } > > ``` > > **4. Sign the Order** > > Then, sign the order with the Session Key as shown in [Sign the > Order](/trading/place-orders#sign-the-order): > > ```text theme={null} > inner_signature = signTypedData(typedData) > deposit_wallet_order_signature = wrapDepositWalletSignature( > typedData, > inner_signature > ) > ``` > > Use the `wrapDepositWalletSignature()` helper from the linked example. > > **5. Add the Session Signer Envelope** > > Then, wrap `` with the session signer > address: > > ```text theme={null} > signer_id = leftPadToBytes32() > session_payload = abiEncode( > ["bytes32", "bytes32", "bytes"], > [signer_id, bytes32(0), ] > ) > > session_wrapped_order_signature = > session_payload + > 0x6492649264926492649264926492649264926492649264926492649264926492 > ``` > > **6. Create the Order Request** > > Then, create the order request using > ``: > > ```json requestBody theme={null} > { > "deferExec": false, > "order": { > "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", > "expiration": "0", > "maker": "", > "makerAmount": "5200000", > "metadata": "0x0000000000000000000000000000000000000000000000000000000000000000", > "salt": 479249096354, > "side": "BUY", > "signature": "", > "signatureType": 3, > "signer": "", > "takerAmount": "10000000", > "timestamp": "", > "tokenId": "" > }, > "orderType": "GTC", > "owner": "" > } > ``` > > **7. Submit the Order** > > Finally, submit the order request: > > ```bash theme={null} > curl -X POST "https://clob.polymarket.com/order" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '' > ``` > > `` authenticates the request. Generate it from the > exact serialized request body and a fresh ``: > > ```text theme={null} > message = + "POST" + "/order" + > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` ## Manage Wallet Orders List and cancel open orders across the Deposit Wallet, whichever signer placed them. The Deposit Wallet Owner and any active Session Key can list them. Only the Deposit Wallet Owner can cancel them. ### List Wallet Orders List all open orders on the Deposit Wallet, or filter by market, outcome, or the signers that placed them. > [tab] TypeScript > > Call `listWalletOpenOrders()` on a `SecureClient` for the Deposit Wallet > Owner or a Session Key. Omit filters to list all open orders: > > ```ts theme={null} > const pages = secureClient.listWalletOpenOrders(); > > for await (const page of pages) { > // page.items: WalletOpenOrder[] > } > ``` > > To filter the list, create `pages` with one of these calls, then iterate as > above: > > ```ts Deposit Wallet Owner theme={null} > const pages = secureClient.listWalletOpenOrders({ > signerAddresses: [depositWalletOwnerAddress], > }); > ``` > > ```ts Session Key theme={null} > const pages = secureClient.listWalletOpenOrders({ > signerAddresses: [sessionKeyAddress], > }); > ``` > > ```ts Market theme={null} > const pages = secureClient.listWalletOpenOrders({ > market: "", > }); > ``` > > ```ts Outcome theme={null} > const pages = secureClient.listWalletOpenOrders({ > assetId: "", > }); > ``` > > `signerAddresses` accepts up to 50 signer addresses. For owner orders, use > the Deposit Wallet Owner's signer address, not the Deposit Wallet address. > `market` takes the market's condition ID. Use `assetId` to filter by outcome. > Filters can be combined. > > > [accordion] Output: WalletOpenOrder > > > > ```ts WalletOpenOrder Type theme={null} > > type WalletOpenOrder = { > > id: string; > > conditionId: ConditionId; > > assetId: ClobAssetId; > > owner: string | null; > > makerAddress: EvmAddress; > > signerAddress: EvmAddress; > > side: string; > > price: DecimalString; > > originalSize: DecimalString; > > sizeMatched: DecimalString; > > outcome: string; > > orderType: string; > > status: string; > > createdAt: IsoDateTimeString; > > expiresAt?: IsoDateTimeString; > > }; > > ``` > > > > ```json WalletOpenOrder Example theme={null} > > { > > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "owner": null, > > "makerAddress": "", > > "signerAddress": "", > > "side": "BUY", > > "price": "0.52", > > "originalSize": "10", > > "sizeMatched": "0", > > "outcome": "Yes", > > "orderType": "GTC", > > "status": "LIVE", > > "createdAt": "2026-06-01T12:00:00.000Z" > > } > > ``` > > `signerAddress` is the signer that placed the order. `owner` is `null` when > the order's API key identifier is withheld. > [tab] Python > > Call `list_wallet_open_orders()` on an `AsyncSecureClient` for the Deposit > Wallet Owner or a Session Key. The synchronous `SecureClient` provides the > same method. Omit filters to list all open orders: > > ```python theme={null} > pages = secure_client.list_wallet_open_orders() > > async for page in pages: > # page.items: tuple[WalletOpenOrder, ...] > ``` > > To filter the list, create `pages` with one of these calls, then iterate as > above: > > ```python Deposit Wallet Owner theme={null} > pages = secure_client.list_wallet_open_orders( > signer_addresses=[deposit_wallet_owner_address], > ) > ``` > > ```python Session Key theme={null} > pages = secure_client.list_wallet_open_orders( > signer_addresses=[session_key_address], > ) > ``` > > ```python Market theme={null} > pages = secure_client.list_wallet_open_orders(market="") > ``` > > ```python Outcome theme={null} > pages = secure_client.list_wallet_open_orders(asset_id="") > ``` > > `signer_addresses` accepts up to 50 signer addresses. For owner orders, use > the Deposit Wallet Owner's signer address, not the Deposit Wallet address. > `market` takes the market's condition ID. Use `asset_id` to filter by outcome. > Filters can be combined. > > > [accordion] Output: WalletOpenOrder > > > > ```python WalletOpenOrder Type theme={null} > > class WalletOpenOrder: > > id: str > > condition_id: ConditionId > > asset_id: ClobAssetId > > maker_address: EvmAddress > > signer_address: EvmAddress > > owner: str | None > > side: Literal["BUY", "SELL"] > > price: Decimal > > original_size: Decimal > > size_matched: Decimal > > outcome: str > > order_type: str > > status: str > > created_at: datetime > > expires_at: datetime | None > > ``` > > > > ```json WalletOpenOrder Example theme={null} > > { > > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "maker_address": "", > > "signer_address": "", > > "owner": null, > > "side": "BUY", > > "price": "0.52", > > "original_size": "10", > > "size_matched": "0", > > "outcome": "Yes", > > "order_type": "GTC", > > "status": "LIVE", > > "created_at": "2026-06-01T12:00:00Z", > > "expires_at": null > > } > > ``` > > `signer_address` is the signer that placed the order. `owner` is `None` when > the order's API key identifier is withheld. > [tab] API > > List open orders with an authenticated CLOB request signed by the Deposit > Wallet Owner or a Session Key. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. Omit filters to list all open orders: > > ```bash theme={null} > curl "https://clob.polymarket.com/data/wallet-open-orders" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > To filter the list, use one of these URLs with the same headers: > > ```text Deposit Wallet Owner theme={null} > https://clob.polymarket.com/data/wallet-open-orders?session_keys= > ``` > > ```text Session Key theme={null} > https://clob.polymarket.com/data/wallet-open-orders?session_keys= > ``` > > ```text Market theme={null} > https://clob.polymarket.com/data/wallet-open-orders?market= > ``` > > ```text Outcome theme={null} > https://clob.polymarket.com/data/wallet-open-orders?asset_id= > ``` > > `session_keys` accepts up to 50 comma-separated signer addresses. For owner > orders, use the Deposit Wallet Owner's signer address, not the Deposit > Wallet address. `market` takes the market's condition ID. Use `asset_id` to > filter by outcome. Filters can be combined. > Generate `` from the request path: > > ```text theme={null} > message = + "GET" + "/data/wallet-open-orders" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The response contains a page of orders and a continuation cursor: > > ```json Response theme={null} > { > "data": [ > { > "id": "0xff354cd7ca7539dfa9c28d90943ab5779a4eac34b9b37a757d7b32bdfb11790b", > "market": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > "asset_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > "owner": null, > "maker_address": "", > "signer_address": "", > "side": "BUY", > "price": "0.52", > "original_size": "10", > "size_matched": "0", > "outcome": "Yes", > "order_type": "GTC", > "status": "LIVE", > "created_at": 1780315200, > "expiration": "0" > } > ], > "next_cursor": "" > } > ``` > > `signer_address` is the signer that placed the order. `owner` is empty or > `null` when the order's API key identifier is withheld. Repeat the request > with `cursor=` until `next_cursor` is an empty string. A page > can be empty before the last page. ### Cancel Wallet Orders The Deposit Wallet Owner can cancel up to 1,000 orders by ID or every open order on the Deposit Wallet. If a cancellation's outcome is uncertain, such as after a network error, list the wallet orders before retrying. > [tab] TypeScript > > Call `cancelWalletOrders()` on the Deposit Wallet Owner's `SecureClient`: > > ```ts theme={null} > const result = await secureClient.cancelWalletOrders({ > orderIds: [order.id], > }); > > // result: CancelOrdersResponse > ``` > > Call `cancelAllWalletOrders()` to cancel every open order: > > ```ts theme={null} > const result = await secureClient.cancelAllWalletOrders(); > > // result: CancelOrdersResponse > ``` > [tab] Python > > Call `cancel_wallet_orders()` on the Deposit Wallet Owner's > `AsyncSecureClient`. The synchronous `SecureClient` provides the same method > without `await`. > > ```python theme={null} > result = await secure_client.cancel_wallet_orders( > order_ids=[order.id], > ) > > # result: CancelOrdersResponse > ``` > > Call `cancel_all_wallet_orders()` to cancel every open order: > > ```python theme={null} > result = await secure_client.cancel_all_wallet_orders() > > # result: CancelOrdersResponse > ``` > [tab] API > > Cancel orders with the Deposit Wallet Owner's CLOB credentials. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/cancel-wallet-orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"order_ids":["'"$ORDER_ID"'"]}' > ``` > > Generate `` from the exact serialized body: > > ```text theme={null} > body = '{"order_ids":["' + order_id + '"]}' > message = + "DELETE" + "/cancel-wallet-orders" + body > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > To cancel every open order, send and sign `{"all":true}` instead: > > ```bash theme={null} > curl -X DELETE "https://clob.polymarket.com/cancel-wallet-orders" \ > -H "Content-Type: application/json" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > --data '{"all":true}' > ``` Each request returns a [cancellation result](/trading/manage-orders#cancellation-results). ## Fetch Session Keys List the active Session Keys for a Deposit Wallet to see which signers can currently act on its behalf. > [tab] TypeScript > > Call `fetchSessionKeys()` on the Deposit Wallet Owner's `SecureClient`: > > ```ts theme={null} > const sessionKeys = await secureClient.fetchSessionKeys(); > > // sessionKeys: SessionKey[] > ``` > > > [accordion] Output: SessionKey\[] > > > > ```ts SessionKey Type theme={null} > > type SessionKey = { > > address: EvmAddress; > > scopes: SessionKeyScope[]; > > validUntil: number; > > }; > > ``` > > > > ```json SessionKey Example theme={null} > > [ > > { > > "address": "", > > "scopes": ["CLOB", "COMBOSRFQ"], > > "validUntil": 1800000000 > > } > > ] > > ``` > [tab] Python > > Call `fetch_session_keys()` on the Deposit Wallet Owner's > `AsyncSecureClient`. The synchronous `SecureClient` provides the same > method without `await`. > > ```python theme={null} > session_keys = await secure_client.fetch_session_keys() > > # session_keys: tuple[AuthorizedSessionKey, ...] > ``` > > > [accordion] Output: tuple\[AuthorizedSessionKey, ...] > > > > ```python AuthorizedSessionKey Type theme={null} > > class AuthorizedSessionKey: > > address: EvmAddress > > scopes: tuple[SessionKeyScope, ...] > > valid_until: datetime > > ``` > > > > ```json AuthorizedSessionKey Example theme={null} > > [ > > { > > "address": "", > > "scopes": ["CLOB", "COMBOSRFQ"], > > "valid_until": "2027-01-15T08:00:00Z" > > } > > ] > > ``` > [tab] API > > Authenticate the Deposit Wallet Owner with the CLOB, then fetch the Deposit > Wallet's active Session Keys. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > **1. Create a CLOB L1 Signature** > > First, create a `` with the Deposit Wallet Owner to > prove control of ``. > > ```json ClobAuth theme={null} > { > "domain": { > "name": "ClobAuthDomain", > "version": "1", > "chainId": 137 > }, > "types": { > "ClobAuth": [ > { "name": "address", "type": "address" }, > { "name": "timestamp", "type": "string" }, > { "name": "nonce", "type": "uint256" }, > { "name": "message", "type": "string" } > ] > }, > "primaryType": "ClobAuth", > "message": { > "address": "", > "timestamp": "", > "nonce": 0, > "message": "This message attests that I control the given wallet" > } > } > ``` > > **2. Create or Derive CLOB Credentials** > > Then, create CLOB credentials for the Deposit Wallet Owner. If > credentials already exist, derive them instead. > > ```bash Create theme={null} > curl -X POST "https://clob.polymarket.com/auth/api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: 0" > ``` > > ```bash Derive theme={null} > curl "https://clob.polymarket.com/auth/derive-api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: 0" > ``` > > The response contains the credentials used to authenticate the session > keys request: > > ```json Response theme={null} > { > "apiKey": "", > "secret": "", > "passphrase": "" > } > ``` > > **3. Fetch the Session Keys** > > Finally, fetch the active Session Keys: > > ```bash theme={null} > curl "https://clob.polymarket.com/v1/user/session-signers" \ > -H "POLY_ADDRESS: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " > ``` > > `` authenticates the request. Generate it from the > request path and a fresh ``: > > ```text theme={null} > message = + "GET" + "/v1/user/session-signers" > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The response identifies the Deposit Wallet and lists its active session > keys: > > ```json Response theme={null} > { > "wallet": "", > "signers": [ > { > "address": "", > "scopes": ["CLOB", "COMBOSRFQ"], > "valid_until": 1800000000 // > } > ] > } > ``` > > `signers` contains only usable, unexpired, non-revoked authorizations. > An empty array means the request succeeded but there are no active > Session Keys. ## Revoke a Session Key Revoke a Session Key when an integration no longer needs access or its private key may have been exposed. Revocation prevents further trading by that key and cancels its open orders without affecting orders placed by other Session Keys. > [tab] TypeScript > > Call `revokeSessionKey()` on the Deposit Wallet Owner's `SecureClient` with > the Session Key's public address: > > ```ts theme={null} > await secureClient.revokeSessionKey({ > address: sessionKeyAddress, > }); > ``` > > `revokeSessionKey()` resolves to `void` once the Session Key is no longer active in the Wallet Registry. > The backend continues the remaining revocation work asynchronously, canceling open orders and finalizing the on-chain transaction. > [tab] Python > > Call `revoke_session_key()` on the Deposit Wallet Owner's > `AsyncSecureClient` with the Session Key's public address. The synchronous > `SecureClient` provides the same method without `await`. > > ```python theme={null} > await secure_client.revoke_session_key( > address=session_key_address, > ) > ``` > > `revoke_session_key()` returns `None` once the Session Key is no longer active in the Wallet Registry. > The backend continues the remaining revocation work asynchronously, canceling open orders and finalizing the on-chain transaction. > [tab] API > > Authorize the revocation as the Deposit Wallet Owner, then submit it with a > Relayer API key or Builder API key. > > **1. Fetch the Wallet Nonce** > > First, fetch the Deposit Wallet's `WALLET` nonce by passing the Deposit > Wallet Owner address. > > ```bash theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > The response includes the Deposit Wallet nonce: > > ```json Response theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **2. Define the Session Key Revocation** > > Then, encode the `revokeSessionSigner` call that the Deposit Wallet will > execute: > > ```solidity theme={null} > function revokeSessionSigner(address sessionSigner) > ``` > > The following example uses Viem: > > ```ts Example theme={null} > import { encodeFunctionData, parseAbi } from "viem" > > const sessionSignerAddress = "" as `0x${string}` > > const calldata = encodeFunctionData({ > abi: parseAbi([ > "function revokeSessionSigner(address sessionSigner)", > ]), > functionName: "revokeSessionSigner", > args: [sessionSignerAddress], > }) > ``` > > **3. Prepare the Owner Authorization** > > Then, prepare the EIP-712 typed data for the Deposit Wallet Owner to > approve: > > ```json Batch theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > } > ``` > > Where: > > * `` is the Deposit Wallet address. > * `` is the nonce returned when fetching the Deposit > Wallet nonce. > * `` is a future whole Unix timestamp in > seconds after which the signed revocation request can no longer be > executed. The Relayer requires at least 10 seconds of remaining > validity. > * `` is the encoded revocation call from the previous step. > > **4. Sign as the Deposit Wallet Owner** > > Then, prove that the Deposit Wallet Owner approves the revocation by > signing the typed data. The following example uses Viem: > > ```ts TypeScript with Viem theme={null} > import { privateKeyToAccount } from "viem/accounts" > > const depositWalletOwner = privateKeyToAccount( > process.env.DEPOSIT_WALLET_OWNER_PRIVATE_KEY as `0x${string}`, > ) > > const signature = > await depositWalletOwner.signTypedData(walletBatchTypedData) > ``` > > **5. Build the Revocation Body** > > Then, build the request body that revokes the session signer: > > ```json theme={null} > { > "walletAddress": "", > "sessionSignerAddress": "", > "nonce": "", > "deadline": "", > "signature": "" > } > ``` > > Where: > > * `` is the Session Key to revoke. > * `` and `` match the values > in the signed typed data. > * `` is the value returned in the previous step. > > **6. Submit the Revocation** > > Then, submit the revocation request to the Relayer with your Relayer > API key or Builder API key: > > ```bash Relayer API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/v1/session-signers/revocations" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > -H "Idempotency-Key: " \ > -d '{ > "walletAddress": "", > "sessionSignerAddress": "", > "nonce": "", > "deadline": "", > "signature": "" > }' > ``` > > ```bash Builder API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/v1/session-signers/revocations" \ > -H "Content-Type: application/json" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " \ > -H "Idempotency-Key: " \ > -d '{ > "walletAddress": "", > "sessionSignerAddress": "", > "nonce": "", > "deadline": "", > "signature": "" > }' > ``` > > Where: > > * `` uniquely identifies this revocation request. > Reuse it when retrying the same request. > * `` is your Relayer API key, and > `` is the Deposit Wallet Owner address > the key belongs to. > * `` and `` are your Builder API > credentials. > * `` and `` authenticate a Builder > API key request. Create the signature from the exact serialized > request body: > > ```text theme={null} > revocation_body = > request_timestamp = > method = "POST" > request_path = "/v1/session-signers/revocations" > > message = request_timestamp + method + request_path + revocation_body > builder_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > The accepted response contains the identifiers used to track the > revocation: > > ```json Response theme={null} > { > "fenced": true, > "operationId": "", > "status": "", > "transactionId": "" > } > ``` > > **7. Confirm the Relayer Transaction** > > Finally, poll the transaction endpoint using the returned > ``: > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" > ``` > > Continue until `state` is `STATE_CONFIRMED`. Treat `STATE_FAILED` and > `STATE_INVALID` as terminal failures. > > ```json Response theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Revocation completes after the Session Key's open orders are canceled and > the on-chain transaction is confirmed, which may take several minutes. ## Session Key Considerations Configurable shorter Session Key expirations are not currently supported. To end access before 180 days, [revoke the Session Key](#revoke-a-session-key). If you are adding Session Key support to an existing integration, keep these access boundaries in mind: * **Notifications:** A Session Key receives only [notifications](/trading/wallet-activity#notifications) and [real-time order and trade updates](/trading/realtime-order-updates#user-stream) generated by its own activity. * **Orders:** A Session Key can [fetch an order](/trading/manage-orders#fetch-an-order) or [list open orders](/trading/manage-orders#list-open-orders) only for orders it submitted. The same applies to the Deposit Wallet Owner. To list or cancel every signer's orders, see [Manage Wallet Orders](#manage-wallet-orders). * **Trades:** A Session Key can [list account trades](/trading/manage-orders#list-account-trades) only for trades associated with its own orders. # Wallet Activity Source: https://docs.polymarket.com/trading/wallet-activity Track the positions and activity associated with a Polymarket wallet. Use a wallet address to understand an account's current exposure and trace how its activity has changed over time. ## Open Positions Inspect a wallet's current outcome exposure and unrealized performance. > [tab] TypeScript > > Call `listPositions()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > const address = "0x8ba1f109551bD432803012645Ac136ddd64DBA72"; > > const pages = client.listPositions({ user: address, pageSize: 1 }); > > for await (const page of pages) { > // page.items: Position[] > } > ``` > > > [accordion] Output: Position\[] > > > > ```ts Position Type theme={null} > > // Trimmed for brevity. > > type Position = { > > wallet: EvmAddress; > > assetId: TokenId | PositionId; > > conditionId: ConditionId; > > /** The current holding, in shares. */ > > currentSize: DecimalString; > > avgPrice: DecimalString; > > /** Fee-exclusive entry basis in USD. */ > > entryCostUsdc: DecimalString; > > /** Attributed BUY fees in USD (disclosure; already excluded from entryCostUsdc). */ > > entryFeesUsdc: DecimalString; > > /** Always entryCostUsdc + entryFeesUsdc. */ > > totalCostUsdc: DecimalString; > > currentPrice: DecimalString; > > currentValue: DecimalString; > > realizedPnl: DecimalString; > > /** currentValue - entryCostUsdc. */ > > unrealizedPnl: DecimalString; > > /** Always realizedPnl + unrealizedPnl. */ > > totalPnl: DecimalString; > > percentPnl: DecimalString; > > status: PositionStatus; > > redeemable: boolean; > > mergeable: boolean; > > negativeRisk: boolean; > > title?: string; > > slug?: string; > > eventSlug?: string; > > outcome?: string; > > outcomeIndex?: number; > > endDate?: IsoCalendarDateString; > > lastEventAt?: EpochMilliseconds; > > firstEntryAt?: EpochMilliseconds; > > }; > > ``` > > > > ```json Position Example theme={null} > > [ > > { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "wallet": "0x8ba1f109551bd432803012645ac136ddd64dba72", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "currentSize": "125.5", > > "avgPrice": "0.42", > > "entryCostUsdc": "52.71", > > "entryFeesUsdc": "0", > > "totalCostUsdc": "52.71", > > "currentPrice": "0.49", > > "currentValue": "61.495", > > "realizedPnl": "0", > > "unrealizedPnl": "8.785", > > "totalPnl": "8.785", > > "percentPnl": "16.66", > > "status": "OPEN", > > "redeemable": false, > > "mergeable": false, > > "negativeRisk": false, > > "title": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "eventSlug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "outcome": "Yes", > > "outcomeIndex": 0 > > } > > ] > > ``` > > `firstEntryAt` is the first acquisition time in Unix epoch milliseconds, or `undefined` when unrecorded. Acquisitions include buys, splits, mints, migrations, and incoming transfers. > [tab] Python > > Call `list_positions()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > address = "0x8ba1f109551bD432803012645Ac136ddd64DBA72" > > pages = client.list_positions( > user=address, > page_size=1, > ) > > async for page in pages: > # page.items: tuple[Position, ...] > pass > ``` > > > [accordion] Output: Position > > > > ```python Position Type theme={null} > > class Position: > > wallet: EvmAddress > > asset_id: ClobAssetId > > condition_id: ConditionId > > current_size: Decimal > > avg_price: Decimal > > entry_cost_usdc: Decimal > > entry_fees_usdc: Decimal > > total_cost_usdc: Decimal > > current_price: Decimal > > current_value: Decimal > > total_size: Decimal > > realized_pnl: Decimal > > unrealized_pnl: Decimal > > total_pnl: Decimal > > percent_pnl: Decimal > > percent_realized_pnl: Decimal > > status: PositionStatus > > redeemable: bool > > mergeable: bool > > negative_risk: bool > > archived: bool > > verified: bool > > title: str | None > > slug: str | None > > icon: str | None > > event_slug: str | None > > outcome: str | None > > opposite_outcome: str | None > > name: str | None > > profile_image: str | None > > event_id: EventId | None > > outcome_index: int | None > > opposite_asset_id: ClobAssetId | None > > end_date: date | None > > last_event_at: datetime | None > > first_entry_at: datetime | None > > ``` > > > > ```json Position Example theme={null} > > { > > "wallet": "0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b", > > "asset_id": "94476829201604408463453426454480212459887267917122244941405244686637914508323", > > "condition_id": "0x7ad403c3508f8e3912940fd1a913f227591145ca0614074208e0b962d5fcc422", > > "current_size": "400000.0", > > "avg_price": "0.5", > > "entry_cost_usdc": "200000.0", > > "entry_fees_usdc": "0.0", > > "total_cost_usdc": "200000.0", > > "current_price": "0.7545", > > "current_value": "301800.0", > > "total_size": "10386654.0", > > "realized_pnl": "0.0", > > "unrealized_pnl": "101800.0", > > "total_pnl": "101800.0", > > "percent_pnl": "50.9", > > "percent_realized_pnl": "-94.1886", > > "status": "OPEN", > > "redeemable": false, > > "mergeable": true, > > "negative_risk": true, > > "archived": false, > > "verified": true, > > "title": "Will JD Vance win the 2028 US Presidential Election?", > > "slug": "will-jd-vance-win-the-2028-us-presidential-election", > > "icon": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-jd-vance-win-the-2028-us-presidential-election-P-zEgXjCWbdY.png", > > "event_slug": "presidential-election-winner-2028", > > "outcome": "No", > > "opposite_outcome": "Yes", > > "name": "Car", > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-501613-aa434e55-7732-41b1-9650-83a9d1d716ef.png", > > "event_id": "31552", > > "outcome_index": 1, > > "opposite_asset_id": "16040015440196279900485035793550429453516625694844857319147506590755961451627", > > "end_date": "2028-11-07", > > "last_event_at": "2026-08-23T15:46:10Z", > > "first_entry_at": "2025-08-13T21:51:32Z" > > } > > ``` > > `current_size` is in shares. Costs, values, and PnL use `Decimal` values in USDC. `entry_cost_usdc` excludes fees. Do not subtract `entry_fees_usdc` from it again. `first_entry_at` is the first acquisition time as a UTC `datetime`, or `None` when unrecorded. Acquisitions include buys, splits, mints, migrations, and incoming transfers. > > Position reads have no time bounds by default. `full_history=True` preserves that behavior, including holdings without activity timestamps. Use `start` and `end` to filter by last activity instead. > [tab] API > > List the open positions for a wallet: > > ```bash theme={null} > ADDRESS="0x8ba1f109551bD432803012645Ac136ddd64DBA72" > > curl "https://data-api.polymarket.com/v2/positions?user=$ADDRESS&limit=1" > ``` > > The response contains the wallet's open positions (row fields trimmed for > brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "proxy_wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "status": "OPEN", > > "current_size": 125.5, > > "avg_price": 0.42, > > "entry_cost_usdc": 52.71, > > "current_price": 0.49, > > "current_value": 61.5, > > "unrealized_pnl": 8.79, > > "total_pnl": 8.79, > > "percent_pnl": 16.68, > > "redeemable": false, > > "mergeable": false, > > "title": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "event_slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "outcome": "Yes", > > "outcome_index": 0 > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJwb3NpdGlvbnMi…" > > } > > } > > ``` > > The position's acquisition timestamp has this shape: > > | Field | Type | > | - | - | > | `first_entry_at` | integer | > > `first_entry_at` is the first acquisition time in Unix epoch seconds, or `0` when unrecorded. Acquisitions include buys, splits, mints, migrations, and incoming transfers. > > Follow `pagination.next_cursor` with the `cursor` parameter for the next > page. ### Filter Positions by Title Narrow positions to markets whose titles contain a search term, ignoring case. This works across position statuses and when listing a market's holders. > [tab] TypeScript > > Pass `title` to `listPositions()` on the existing `PublicClient` or `SecureClient`: > > ```ts theme={null} > const pages = client.listPositions({ user: address, title: "election" }); > > for await (const page of pages) { > // page.items: Position[] > } > ``` > > `title` accepts at most 200 Unicode characters. Empty or whitespace-only > input disables the filter. Other patterns are preserved unchanged; `%` > matches any sequence of characters and `_` matches one character. > The paginator retains `title` on every page, including when resumed with > `pages.from(nextCursor)`. > [tab] Python > > Pass `title` to `list_positions()` on the existing `AsyncPublicClient` or > `AsyncSecureClient`. The synchronous clients accept the same argument: > > ```python theme={null} > pages = client.list_positions(user=address, title="election") > > async for page in pages: > # page.items: tuple[Position, ...] > pass > ``` > > `title` accepts at most 200 Unicode characters. Empty or whitespace-only > input disables the filter. Other patterns are preserved unchanged; `%` > matches any sequence of characters and `_` matches one character. > The paginator retains `title` on every page, including when resumed with > `pages.from_cursor(next_cursor)`. > [tab] API > > Send `title` with the position request: > > ```bash theme={null} > curl --get "https://data-api.polymarket.com/v2/positions" \ > --data-urlencode "user=$ADDRESS" \ > --data-urlencode "title=election" > ``` > > `title` accepts at most 200 Unicode characters. Empty or whitespace-only > input disables the filter. Other patterns are preserved unchanged; SQL > `LIKE` wildcards keep their meaning: `%` matches any sequence of characters > and `_` matches one character. > Re-send the same `title` and anchor with every `cursor` request. The cursor > does not carry the title filter, so omitting it broadens subsequent pages. ## Closed Positions Review the positions a wallet has exited or that have resolved, including their realized performance. > [tab] TypeScript > > One method serves the whole position lifecycle: call `listPositions()` > with `status: PositionStatus.Closed`. Closed rows keep the same `Position` > shape with realized economics (`currentSize` is a \~0 residual and > `realizedPnl` carries the outcome); they default to sorting by realized > PnL. > > This example uses an existing `PublicClient` or `SecureClient`. If needed, > [create a Public Client](/getting-started/typescript#create-a-public-client) first. > > ```ts theme={null} > import { > PositionSortBy, > PositionStatus, > SortDirection, > } from "@polymarket/client"; > > const pages = client.listPositions({ > user: address, > status: PositionStatus.Closed, > sortBy: PositionSortBy.Price, > sortDirection: SortDirection.Desc, > pageSize: 1, > }); > > for await (const page of pages) { > // page.items: Position[] > } > ``` > > > [accordion] Output: Position\[] > > > > ```json Position Example theme={null} > > [ > > { > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "wallet": "0x8ba1f109551bd432803012645ac136ddd64dba72", > > "assetId": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "currentSize": "0", > > "avgPrice": "0.58", > > "entryCostUsdc": "145", > > "totalCostUsdc": "145", > > "realizedPnl": "34.25", > > "unrealizedPnl": "0", > > "totalPnl": "34.25", > > "status": "CLOSED", > > "redeemable": false, > > "title": "Will the US confirm that aliens exist before 2027?", > > "outcome": "No", > > "outcomeIndex": 1 > > } > > ] > > ``` > > For a `user`-anchored listing with `status: PositionStatus.Closed`, > `PositionSortBy.Tokens`, `CurrentValue`, `Price`, and `UnrealizedPnl` > rank by realized PnL, preserving the requested `sortDirection`. This > example therefore orders realized PnL descending. `RealizedPnl`, > `TotalPnl`, and `Timestamp` retain their semantics. Market-only CLOSED > listings do not use this fallback. > > Keep the original filters and `sortBy` when continuing with a cursor. > Do not rewrite it to `RealizedPnl`. An old residual-sort cursor can raise > `RequestRejectedError` with a message containing > `positions order changed; restart pagination without cursor`. The SDK > passes the rejection to the caller without restarting. Explicitly discard > that cursor and start again with the original request and no `cursor`. > Restarting can return rows you have already consumed. > [tab] Python > > Call `list_positions()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > If needed, [create a Public Client](/getting-started/python#create-a-public-client) first. > > ```python theme={null} > pages = client.list_positions( > user=address, > status="CLOSED", > sort_by="PRICE", > sort_direction="DESC", > page_size=1, > ) > > async for page in pages: > # page.items: tuple[Position, ...] > pass > ``` > > Closed positions use the same `Position` model as open positions. Read `realized_pnl` for realized performance. Secure clients can omit `user` to read the authenticated wallet. > > For a `user`-anchored listing with `status="CLOSED"`, `sort_by` values > `TOKENS`, `CURRENT_VALUE`, `PRICE`, and `UNREALIZED_PNL` rank by realized PnL, > preserving `sort_direction`. This example therefore orders realized PnL > descending. `REALIZED_PNL`, `TOTAL_PNL`, and `TIMESTAMP` retain their semantics. > Market-only CLOSED listings do not use this fallback. > > Keep the original filters and `sort_by` when continuing with a cursor. > Do not rewrite it to `REALIZED_PNL`. An old residual-sort cursor can raise > `RequestRejectedError` with a message containing > `positions order changed; restart pagination without cursor`. The SDK passes > the rejection to the caller without restarting. Explicitly discard that cursor > and start again with the original request and no `cursor`. Restarting can > return rows you have already consumed. > [tab] API > > Closed positions are served by the same route behind the `status` filter: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/positions?user=$ADDRESS&status=CLOSED&sort_by=PRICE&sort_direction=DESC&limit=1" > ``` > > The response contains the wallet's closed positions (row fields trimmed > for brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "proxy_wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "token_id": "7305630249804085635496399869905769372294302716159034447326228509068694952392", > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "status": "CLOSED", > > "current_size": 0, > > "total_size": 250, > > "avg_price": 0.58, > > "current_price": 0, > > "realized_pnl": 34.25, > > "total_pnl": 34.25, > > "last_event_at": 1782752879, > > "title": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "event_slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "outcome": "No", > > "outcome_index": 1 > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJwb3NpdGlvbnMi…" > > } > > } > > ``` > > For a `user`-anchored listing with `status=CLOSED`, `sort_by` values > `TOKENS`, `CURRENT_VALUE`, `PRICE`, and `UNREALIZED_PNL` rank by realized > PnL, preserving `sort_direction`. `REALIZED_PNL`, `TOTAL_PNL`, and > `TIMESTAMP` retain their semantics. Market-only CLOSED listings do not > use this fallback. > > Continue with the returned `pagination.next_cursor`, retaining the original > filters and requested `sort_by`. Old residual-sort cursors return HTTP > `400` with `invalid cursor: positions order changed; restart pagination without cursor`. > Explicitly discard that cursor and start again with the original request > and no `cursor`. Changing the sort or repeatedly retrying the same cursor > does not recover it. Restarting can return rows you have already consumed. ## Sort Positions by Price Rank a wallet's holdings by current effective price to find its lowest- or highest-priced outcomes. > [tab] TypeScript > > Call `listPositions()` on an existing `PublicClient` or `SecureClient`, using > the `address` from the open positions example. > > ```ts theme={null} > import { PositionSortBy, SortDirection } from "@polymarket/client"; > > const pages = client.listPositions({ > user: address, > sortBy: PositionSortBy.Price, > sortDirection: SortDirection.Asc, > }); > > for await (const page of pages) { > // page.items: Position[] > } > ``` > > `PositionSortBy.Price` orders by `currentPrice`. Use `SortDirection.Desc` for > highest prices first. The paginator retains the selected sort on later pages. > [tab] Python > > Call `list_positions()` on an existing `AsyncPublicClient` or `AsyncSecureClient`, > using the `address` from the open positions example. The sync clients accept the > same sort options. > > ```python theme={null} > pages = client.list_positions( > user=address, > sort_by="PRICE", > sort_direction="ASC", > ) > > async for page in pages: > # page.items: tuple[Position, ...] > pass > ``` > > `sort_by="PRICE"` orders by `current_price`. Use `sort_direction="DESC"` for > highest prices first. The paginator retains the selected sort on later pages. > [tab] API > > Request the wallet's positions using the `ADDRESS` from the open positions example: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/positions?user=$ADDRESS&sort_by=PRICE&sort_direction=ASC&limit=100" > ``` > > `sort_by=PRICE` orders by `current_price`. Use `sort_direction=DESC` for highest > prices first. For later pages, pass `pagination.next_cursor` as `cursor` and keep > the same sort parameters. Redeemable holdings keep winners ahead of losing holdings, then apply the selected price order within each group. A wallet's closed positions use realized profit and loss ordering when price ordering is requested. Without an explicit sort, mergeable holdings use token quantity, closed positions use realized profit and loss, and other holdings use current value. The default direction is descending. ## Activity History Follow the timeline for a wallet across trades and other activity. > [tab] TypeScript > > Call `listActivity()` on an existing `PublicClient` or `SecureClient`. > If needed, [create a Public Client](/getting-started/typescript#create-a-public-client) first. > > ```ts theme={null} > import { ActivityType } from "@polymarket/client"; > > const pages = client.listActivity({ user: address, pageSize: 1 }); > > for await (const page of pages) { > for (const activity of page.items) { > if ( > (activity.type === ActivityType.TRADE || > activity.type === ActivityType.REDEEM) && > activity.isCombo > ) { > console.log( > activity.conditionId, > activity.outcome, > activity.outcomeIndex, > ); > } > } > } > ``` > > You can narrow down the activity types using the `type` field: > > ```ts theme={null} > import { ActivityType } from "@polymarket/client"; > > const pages = client.listActivity({ > user: address, > type: [ActivityType.DEPOSIT, ActivityType.WITHDRAWAL], > }); > ``` > > For `TRADE`, `SPLIT`, `MERGE` and `REDEEM`, check `type` first, then `isCombo`. A value of > `true` identifies Combo activity. `false` identifies ordinary market > activity. `RedeemActivity` is `ClobRedeemActivity | ComboRedemptionActivity`. > Combo rows carry a `ComboConditionId` in `conditionId`. > Combo splits, merges and redemptions have optional titles and no single > market or event URL slug. > > Combo `outcome` and `outcomeIndex` describe the Yes/No side of the aggregate > basket token, rather than a selected leg's label. Unavailable labels or > indexes stay `undefined`. A known index of `0` is preserved. Automatic > redemption is also represented by `ActivityType.REDEEM`. > > This source-breaking 0.x API update adds Combo variants to > `SplitActivity`, `MergeActivity` and `RedeemActivity`. Code that previously accessed market URLs after > checking only `type` must also check `!isCombo`. For example, read ordinary > market URLs within the same activity iterator: > > ```ts theme={null} > const pages = client.listActivity({ user: address }); > for await (const page of pages) { > for (const activity of page.items) { > if ( > (activity.type === ActivityType.SPLIT || > activity.type === ActivityType.MERGE || > activity.type === ActivityType.REDEEM) && > !activity.isCombo > ) { > console.log(activity.slug, activity.eventSlug); > } > } > } > ``` > > Parsed ordinary rows return `isCombo: false`. Manually constructed ordinary > split, merge and redemption values may omit it. > > `Activity` is a discriminated union. The `type` field identifies each > variant: > > > [accordion] Output: Activity\[] > > > > ```ts Activity Union theme={null} > > type Activity = > > | TradeActivity > > | SplitActivity > > | MergeActivity > > | RedeemActivity > > | ConversionActivity > > | MigrationActivity > > | RewardActivity > > | MakerRebateActivity > > | ReferralRewardActivity > > | YieldActivity > > | DepositActivity > > | WithdrawalActivity > > | TakerRebateActivity > > | TipActivity > > | DirectionalSplitActivity > > | DirectionalMergeActivity > > | ThresholdComposeActivity > > | ThresholdDecomposeActivity; > > ``` > > > > ```json Activity Example theme={null} > > [ > > { > > "type": "TRADE", > > "isCombo": false, > > "wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "timestamp": 1782752879000, > > "transactionHash": "0x4f3d2c1b0a9876543210fedcba9876543210fedcba9876543210fedcba987654", > > "conditionId": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "assetId": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "side": "BUY", > > "shares": "25", > > "amount": "12.25", > > "price": "0.49", > > "title": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "eventSlug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "outcome": "Yes", > > "outcomeIndex": 0 > > }, > > { > > "type": "REWARD", > > "wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "timestamp": 1782752979000, > > "transactionHash": "0x7a6b5c4d3e2f109876543210fedcba9876543210fedcba9876543210fedcba98", > > "amount": "5" > > } > > ] > > ``` > [tab] Python > > Call `list_activity()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > If needed, [create a Public Client](/getting-started/python#create-a-public-client) first. > > ```python theme={null} > from polymarket import ComboTradeActivity, RedeemActivity > > pages = client.list_activity(user=address, page_size=1) > > async for page in pages: > for activity in page.items: > if isinstance(activity, (ComboTradeActivity, RedeemActivity)) and activity.is_combo: > print(activity.condition_id, activity.outcome, activity.outcome_index) > ``` > > Check `is_combo` on trades and redemptions to identify Combo activity. > `ComboTradeActivity` has `is_combo=True` and a `ComboConditionId`. > All redemptions remain `RedeemActivity`, with a `ConditionId`. Check > `is_combo` to distinguish a basket from an ordinary market. Existing > `isinstance(activity, RedeemActivity)` checks include Combo redemptions. > > Combo `outcome` and `outcome_index` describe the Yes/No side of the aggregate > basket token, rather than a selected leg's label. Unavailable labels or indexes > stay `None`. A known index of `0` is preserved. Automatic redemption is also > represented by `REDEEM`. > > Filter activity kinds with `activity_types`. Use `full_history=True` for complete history without explicit `start` or `end` bounds. > > ```python theme={null} > pages = client.list_activity( > user=address, > activity_types=["DEPOSIT", "WITHDRAWAL"], > full_history=True, > ) > ``` > > > [accordion] Output: Activity > > > > ```python Activity Union theme={null} > > Activity = ( > > TradeActivity > > | ComboTradeActivity > > | SplitActivity > > | MergeActivity > > | RedeemActivity > > | ConversionActivity > > | RewardActivity > > | DepositActivity > > | WithdrawalActivity > > | MakerRebateActivity > > | TakerRebateActivity > > | ReferralRewardActivity > > | YieldActivity > > | MigrationActivity > > | TipActivity > > | DirectionalSplitActivity > > | DirectionalMergeActivity > > | ThresholdComposeActivity > > | ThresholdDecomposeActivity > > | UnknownActivity > > ) > > ``` > > > > ```json Activity Example theme={null} > > [ > > { > > "wallet": "0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b", > > "timestamp": "2026-09-08T16:56:49Z", > > "transaction_hash": "0xa661459fc2483ddb4e5c7d13c76347fa2b1fb2faae10eed484c810ae46c471dd", > > "name": "Car", > > "pseudonym": "Peppery-Capital", > > "bio": "what is your plan", > > "profile_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-501613-aa434e55-7732-41b1-9650-83a9d1d716ef.png", > > "profile_image_optimized": null, > > "type": "TRADE", > > "is_combo": false, > > "condition_id": "0x0a91645ed98ad09817e051a17466cff087b920393aefba0fe74e8735fc192f15", > > "asset_id": "98255364887669934733864645030488537034263699416357729920734267612805930214172", > > "side": "BUY", > > "shares": "14.285715", > > "amount": "13.285715", > > "price": "0.9300000035", > > "outcome": "Yes", > > "outcome_index": 0, > > "title": "LAPTOP FDV above $25M one day after launch?", > > "slug": "laptop-fdv-above-25m-one-day-after-launch", > > "icon": "https://polymarket-upload.s3.us-east-2.amazonaws.com/laptop-fdv-above-25m-one-day-after-launch-UQwx2GeHcu_f.jpg", > > "event_slug": "laptop-fdv-above-one-day-after-launch" > > } > > ] > > ``` > [tab] API > > List the activity for a wallet: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/activity?user=$ADDRESS&limit=1" > ``` > > The endpoint excludes deposit and withdrawal records by default, even when > `type` requests them. To get them, pass > `exclude_deposits_withdrawals=false`. > > The response contains the wallet's activity (row fields trimmed for > brevity): > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": [ > > { > > "proxy_wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "timestamp": 1782752879, > > "condition_id": "0x747dc809fb79e1b05be09c42d6179459a58de2ef3e40f02484a4e1260f741f75", > > "type": "TRADE", > > "size": 25, > > "usdc_size": 12.25, > > "transaction_hash": "0x4f3d2c1b0a9876543210fedcba9876543210fedcba9876543210fedcba987654", > > "price": 0.49, > > "token_id": "107505882767731489358349912513945399560393482969656700824895970500493757150417", > > "side": "BUY", > > "title": "Will the US confirm that aliens exist before 2027?", > > "slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "event_slug": "will-the-us-confirm-that-aliens-exist-before-2027", > > "outcome": "Yes", > > "outcome_index": 0 > > } > > ], > > "pagination": { > > "limit": 1, > > "offset": 0, > > "has_more": true, > > "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJhY3Rpdml0eSI…" > > } > > } > > ``` > > For `TRADE`, `SPLIT`, `MERGE` and `REDEEM` rows, `is_combo=true` identifies > Combo activity. Ordinary activity omits this field. On Combo trades and > redemptions, `outcome` and `outcome_index` are the aggregate basket > token's Yes/No label and slot, rather than a selected leg's outcome. > Automatic redemption also returns `type=REDEEM`. A blank label or index > `999` means unavailable. Index `0` is known. Preserve the returned > `condition_id` width and use the discriminator rather than its prefix to > classify the activity. ## Notifications Notifications provide a short-lived record of unread events for the connected account. The CLOB retains them for 48 hours. > [!NOTE] > > Clients authenticated with [Session > Keys](/trading/session-keys#session-key-considerations) receive only > notifications generated by those Session Keys. ### List Notifications > [tab] TypeScript > > Call `fetchNotifications()` on a `SecureClient`: > > ```ts theme={null} > const notifications = await client.fetchNotifications(); > > // notifications: Notification[] > ``` > > > [accordion] Output: Notification\[] > > > > ```ts Notification Type theme={null} > > type Notification = { > > id: NotificationId; > > owner: string; > > payload: unknown; > > timestamp: EpochMilliseconds; > > type: number; > > }; > > ``` > > > > ```json Notification Example theme={null} > > [ > > { > > "id": 1, > > "owner": "f4f247b7-4ac7-ff29-a152-04fda0a8755a", > > "type": 2, > > "payload": { > > "order_id": "0x72c66a1f70c00ac5e5eb9ce0452b7d118bc4869f8b822a1a8d8580c16e3ca83e" > > }, > > "timestamp": 1675277676000 > > } > > ] > > ``` > [tab] Python > > Call `get_notifications()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method: > > ```python theme={null} > notifications = await client.get_notifications() > > # notifications: tuple[Notification, ...] > ``` > > > [accordion] Output: tuple\[Notification, ...] > > > > ```python Notification Type theme={null} > > class Notification: > > id: int > > owner: str > > type: int > > payload: Any > > timestamp: datetime > > ``` > > > > ```json Notification Example theme={null} > > [ > > { > > "id": 1, > > "owner": "f4f247b7-4ac7-ff29-a152-04fda0a8755a", > > "type": 2, > > "payload": { > > "order_id": "0x72c66a1f70c00ac5e5eb9ce0452b7d118bc4869f8b822a1a8d8580c16e3ca83e" > > }, > > "timestamp": "2023-02-01T18:54:36Z" > > } > > ] > > ``` > [tab] API > > List unread notifications for the account: > > ```bash theme={null} > curl -G "https://clob.polymarket.com/notifications" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > --data-urlencode "signature_type=" > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` for > `GET /notifications`. The `signature_type` query parameter is not part of > the signed path: > > ```text theme={null} > message = + "GET" + "/notifications" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Select `signature_type` from the connected account's [wallet > type](/trading/wallets-auth#wallet-types): > > | Wallet | `signature_type` | > | - | -: | > | Deposit Wallet | `3` | > | Proxy Wallet | `1` | > | Safe Wallet | `2` | > | EOA | `0` | > > The response contains the unread notifications: > > ```json theme={null} > [ > { > "id": 1, > "owner": "f4f247b7-4ac7-ff29-a152-04fda0a8755a", > "type": 2, > "payload": { > "order_id": "0x72c66a1f70c00ac5e5eb9ce0452b7d118bc4869f8b822a1a8d8580c16e3ca83e" > }, > "timestamp": 1675277676 > } > ] > ``` ### Drop Notifications Mark notifications as read after processing them. Dropped notifications no longer appear when you list unread notifications. > [tab] TypeScript > > Call `dropNotifications()` on a `SecureClient` with the notification IDs: > > ```ts theme={null} > await client.dropNotifications({ > ids: notifications.map(({ id }) => String(id)), > }); > ``` > [tab] Python > > Call `drop_notifications()` on an `AsyncSecureClient`. The synchronous > `SecureClient` provides the same method: > > ```python theme={null} > await client.drop_notifications( > ids=[notification.id for notification in notifications], > ) > ``` > [tab] API > > Send the notification IDs as a comma-separated list: > > ```bash theme={null} > curl -X DELETE -G "https://clob.polymarket.com/notifications" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > --data-urlencode "ids=1,2" > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` for > `DELETE /notifications`. The `ids` query parameter is not part of the signed > path: > > ```text theme={null} > message = + "DELETE" + "/notifications" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > A successful request returns `OK`. ## Portfolio Value Read the current portfolio value for a wallet. > [tab] TypeScript > > Call `fetchPortfolioValue()` on a `PublicClient` or `SecureClient`. It > returns a single object: the wallet's marked portfolio value in USDC, > rounded to four decimals. > > ```ts theme={null} > const portfolioValue = await client.fetchPortfolioValue({ user: address }); > > // portfolioValue: PortfolioValue > ``` > > > [accordion] Output: PortfolioValue > > > > ```ts PortfolioValue Type theme={null} > > type PortfolioValue = { > > wallet: EvmAddress; > > /** Total marked portfolio value, in USDC, rounded to four decimals. */ > > value: DecimalString; > > }; > > ``` > > > > ```json PortfolioValue Example theme={null} > > { > > "wallet": "0x8ba1f109551bd432803012645ac136ddd64dba72", > > "value": "1842.37" > > } > > ``` > [tab] Python > > Call `get_portfolio_value()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > portfolio_value = await client.get_portfolio_value(user=address) > > # portfolio_value: PortfolioValue > ``` > > > [accordion] Output: PortfolioValue > > > > ```python PortfolioValue Type theme={null} > > class PortfolioValue: > > wallet: EvmAddress > > value: Decimal > > ``` > > > > ```json PortfolioValue Example theme={null} > > { > > "wallet": "0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b", > > "value": "684953.8942" > > } > > ``` > > The result is one `PortfolioValue` object. `value` is the wallet's marked portfolio value in USDC. > [tab] API > > Fetch the portfolio value for a wallet: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/value?user=$ADDRESS" > ``` > > The response contains the wallet's current portfolio value: > > > [accordion] Response > > > > ```json theme={null} > > { > > "data": { > > "proxy_wallet": "0x8ba1f109551bD432803012645Ac136ddd64DBA72", > > "value": 1842.37 > > } > > } > > ``` ## Wallet Stats Read a wallet's lifetime trading statistics. > [tab] TypeScript > > Call `fetchUserStats()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > const stats = await client.fetchUserStats({ user: address }); > > // stats: UserStats | null > const tradedMarketCount = stats?.tradedMarketCount; > ``` > > `tradedMarketCount` counts distinct markets, not fills. `stats` is `null` > for an unknown user. > [tab] Python > > Call `get_user_stats()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > stats = await client.get_user_stats(user=address) > > # stats: UserStats | None > traded_market_count = stats.traded_market_count if stats is not None else None > ``` > > `traded_market_count` counts distinct markets, not fills. `stats` is `None` when no statistics are available. Secure clients default `user` to the authenticated wallet. > [tab] API > > Fetch the wallet's profile statistics: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/user-stats?user=$ADDRESS" > ``` > > `data.trades` counts distinct markets and replaces the count from `/traded`. > Unknown users return `data: null`. ## Wallet PnL History Track a wallet's cumulative profit and loss over time. > [tab] TypeScript > > Call `fetchUserPnl()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > const pnl = await client.fetchUserPnl({ user: address }); > > // pnl: UserPnlSeries > const points = pnl.points; > // points: UserPnlPoint[] > ``` > > The default is one day sampled hourly. `points` are cumulative and ordered > oldest first. Nullable amounts mean unavailable, not zero. > [tab] Python > > Call `get_user_pnl()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > pnl = await client.get_user_pnl(user=address, interval="1d", fidelity="1h") > > # pnl: UserPnlSeries > points = pnl.points > # points: tuple[UserPnlPoint, ...] > ``` > > `points` are cumulative and ordered oldest first. Do not sum them as period returns. Optional amounts remain `None` when unavailable. PnL is in USDC and volume is in shares. > [tab] API > > Fetch the last day's cumulative PnL observations: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/user-pnl?user=$ADDRESS&interval=1d&fidelity=1h" > ``` > > `data.points` contains cumulative observations, oldest first. Do not sum > them as period returns or replace unavailable amounts with zero. ## Wallet Trading Volume Measure a wallet's trading volume over a selected period. > [tab] TypeScript > > Call `fetchUserVolume()` on a `PublicClient` or `SecureClient`. > > ```ts theme={null} > const volume = await client.fetchUserVolume({ > user: address, > window: { start: new Date("2026-09-01T00:00:00Z") }, > }); > > // volume: UserVolume > ``` > > `volume.volume` is in shares, `volume.volumeUsdc` is in USD, and > `volume.tradeCount` counts fills. Window bounds expand to whole UTC days. > [tab] Python > > Call `get_user_volume()` on an existing `AsyncPublicClient` or `AsyncSecureClient`. > > ```python theme={null} > from datetime import UTC, datetime > > volume = await client.get_user_volume( > user=address, > start=datetime(2026, 9, 1, tzinfo=UTC), > ) > > # volume: UserVolume > ``` > > `volume.volume` is in shares, `volume.volume_usdc` is in USDC, and `volume.trade_count` counts fills. Time bounds are floored to UTC days. Use `full_history=True` without `start` or `end` for full history. > [tab] API > > Fetch trading volume from the start of September: > > ```bash theme={null} > curl "https://data-api.polymarket.com/v2/user-volume?user=$ADDRESS&start=1788220800" > ``` > > `data.volume` is in shares, `data.volume_usdc` is in USD, and > `data.trade_count` counts fills. `start`/`end` use epoch seconds and expand > to whole UTC days. # Wallets and Authentication Source: https://docs.polymarket.com/trading/wallets-auth Connect or create a Polymarket account for trading. Start by identifying the account's wallet type. You can then connect an existing Polymarket account or create new accounts for your users. ## Wallet Types A Deposit Wallet is the default smart wallet for trading on Polymarket. Your wallet type depends on how and when the account wallet was created. | Wallet type | When it applies | | - | - | | **Deposit Wallet** | All Polymarket account wallets deployed on or after May 4, 2026 use it. | | **Proxy Wallet** | A legacy smart wallet created through Magic Link or Google authentication on polymarket.com. | | **Safe Wallet** | A legacy smart wallet created with an external signer such as MetaMask or Rabby Wallet. | A Deposit Wallet owner can give a separate signer scoped, time-limited trading access. See [Session Keys](/trading/session-keys) to authorize the signer and use its credentials. ## Connect Your Account Connect an existing polymarket.com account to trade with its funds and positions. Copy the account wallet address from the profile menu: ![Polymarket profile menu showing the account wallet address on desktop](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/deposit-wallet-desktop.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=6be3b87c53d6718f973db37e134ee944) ![Polymarket profile menu showing the account wallet address on mobile](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/deposit-wallet-mobile.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=4d6f87ed5440c5297e60d6331c47dc73) Create a Relayer API key under polymarket.com → Settings → API Keys → Relayer API Keys: ![Creating a Relayer API key from Polymarket settings](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/relay-api-key-tutorial.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=674de7b1f46982a57fbe2bf57b905963) This key authorizes gasless wallet operations for the account. Copy the **Signer Address** and **API Key** shown after creation. > [tab] TypeScript > > With the wallet address and Relayer API key ready, connect the account with > `createSecureClient`. > > **1. Create a Secure Client** > > First, provide the signer and account wallet. Include the Relayer API > key to authorize gasless wallet operations. > > ```ts theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > signer: privateKey(process.env.SIGNER_PRIVATE_KEY), > apiKey: relayerApiKey({ > key: process.env.RELAYER_API_KEY!, > address: process.env.RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > > [!NOTE] > > > > This example uses Viem with a private key. See [Wallet > > Integrations](/getting-started/typescript#wallet-integrations) to connect a > > signer from another supported wallet library. > > **2. Inspect the Account** > > Then, inspect the resolved account identity and wallet type. > > `client.account` contains the signer, account wallet, and wallet type for the session. > > ```ts AccountIdentity Type theme={null} > type AccountIdentity = { > signer: EvmAddress; > wallet: EvmAddress; > walletType: WalletType; > }; > > enum WalletType { > EOA = 0, > POLY_PROXY = 1, > GNOSIS_SAFE = 2, > DEPOSIT_WALLET = 3, > } > ``` > > ```json AccountIdentity Example theme={null} > { > "signer": "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063", > "wallet": "0x2e234dae75c793f67a35089c9d99245e1c58470b", > "walletType": 3 > } > ``` > > You have connected your account. > [tab] Python > > With the wallet address and Relayer API key ready, connect the account with > `AsyncSecureClient.create` (`SecureClient.create` is available for > synchronous workflows). > > **1. Create a Secure Client** > > First, create an `AsyncSecureClient` or `SecureClient` with the private > key and account wallet. > Include the Relayer API key to authorize gasless wallet operations. > > ```python Async theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python Sync theme={null} > import os > > from polymarket import RelayerApiKey, SecureClient > > client = SecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > **2. Inspect the Account** > > Then, inspect the resolved account wallet and wallet type. > > `client.wallet` and `client.wallet_type` contain the resolved account wallet and wallet type for the session. > > ```python Async theme={null} > EvmAddress = NewType("EvmAddress", str) > > WalletType: TypeAlias = Literal["EOA", "POLY_PROXY", "GNOSIS_SAFE", "DEPOSIT_WALLET"] > > class AsyncSecureClient: > wallet: EvmAddress > wallet_type: WalletType > ``` > > ```python Sync theme={null} > EvmAddress = NewType("EvmAddress", str) > > WalletType: TypeAlias = Literal["EOA", "POLY_PROXY", "GNOSIS_SAFE", "DEPOSIT_WALLET"] > > class SecureClient: > wallet: EvmAddress > wallet_type: WalletType > ``` > > You have connected your account. > [tab] API > > Authenticate with the CLOB and create L2 credentials. > > **1. Create an L1 Signature** > > First, create an L1 signature to attest to ownership of the signer > address. See [API Authentication](/getting-started/api#authentication) > for the complete signing flow. > > ```json clobAuthTypedData theme={null} > { > "domain": { > "name": "ClobAuthDomain", > "version": "1", > "chainId": 137 > }, > "types": { > "ClobAuth": [ > { "name": "address", "type": "address" }, > { "name": "timestamp", "type": "string" }, > { "name": "nonce", "type": "uint256" }, > { "name": "message", "type": "string" } > ] > }, > "primaryType": "ClobAuth", > "message": { > "address": "", > "timestamp": "", > "nonce": "", > "message": "This message attests that I control the given wallet" > } > } > ``` > > Sign `clobAuthTypedData` with the signer that controls > ``. The returned signature is ``. > > **2. Create L2 Credentials** > > Then, create L2 credentials by sending the signer address, timestamp, > nonce, and L1 signature to the CLOB. > > ```bash Create theme={null} > curl -X POST "https://clob.polymarket.com/auth/api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > ```bash Derive theme={null} > curl "https://clob.polymarket.com/auth/derive-api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > Store the returned L2 credentials for authenticating private requests, > including requests that place orders: > > ```json Response theme={null} > { > "apiKey": "", > "secret": "", > "passphrase": "" > } > ``` > > You have connected your account. ## Create New Accounts Create a polymarket.com account to serve as your builder account. It represents your integration and owns the builder profile and API credentials used to create Deposit Wallets for your users. Each wallet remains controlled by its signer. In the builder account, open polymarket.com → Settings → Builders and create an API key: ![Open Settings, select Builders, and create a Builder API key](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/builder-key-1.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=70d5709ef4dbf6bc276ef7caa41cdb23) ![Copy the generated Builder API key, secret, and passphrase](https://mintcdn.com/polymarket-292d1b1b/1lJ_npwaE_MShiVL/images/builder-key-2.png?fit=max\&auto=format\&n=1lJ_npwaE_MShiVL\&q=85\&s=509d270f5f5ff4dc882d7d8b7db17679) Copy the **API Key**, **Secret**, and **Passphrase** shown after creation. > [!WARNING] > > Builder API credentials are secrets. Keep them on your server, and never > expose or share them. > [tab] TypeScript > > With the Builder API key ready, create the new account with > `createSecureClient`. > > **1. Create a Deposit Wallet** > > First, create a `SecureClient` with the signer and Builder API key. The SDK > derives the signer's Deposit Wallet address and deploys the wallet > automatically. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > import { privateKey } from "@polymarket/client/viem"; > > const client = await createSecureClient({ > signer: privateKey(process.env.SIGNER_PRIVATE_KEY), > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > > [!NOTE] > > > > This example uses Viem with a private key. See [Wallet > > Integrations](/getting-started/typescript#wallet-integrations) to connect a > > signer from another supported wallet library. > > **2. Inspect the Account** > > Then, inspect the resolved account identity and wallet type. > > `client.account` contains the signer, account wallet, and wallet type for the session. > > ```ts AccountIdentity Type theme={null} > type AccountIdentity = { > signer: EvmAddress; > wallet: EvmAddress; > walletType: WalletType; > }; > > enum WalletType { > EOA = 0, > POLY_PROXY = 1, > GNOSIS_SAFE = 2, > DEPOSIT_WALLET = 3, > } > ``` > > ```json AccountIdentity Example theme={null} > { > "signer": "0x8f3cf7ad23cd3cadbd9735aff958023239c6a063", > "wallet": "0x2e234dae75c793f67a35089c9d99245e1c58470b", > "walletType": 3 > } > ``` > > You have created the new account. > [tab] Python > > With the Builder API key ready, create the new account with > `AsyncSecureClient.create` (`SecureClient.create` is available for > synchronous workflows). > > **1. Create a Deposit Wallet** > > First, create an `AsyncSecureClient` or `SecureClient` with the private > key and Builder API key. > The SDK derives the signer's Deposit Wallet address and deploys the > wallet automatically. > > ```python Async theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > ```python Sync theme={null} > import os > > from polymarket import BuilderApiKey, SecureClient > > client = SecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > **2. Inspect the Account** > > Then, inspect the resolved account wallet and wallet type. > > `client.wallet` and `client.wallet_type` contain the resolved account wallet and wallet type for the session. > > ```python Async theme={null} > EvmAddress = NewType("EvmAddress", str) > > WalletType: TypeAlias = Literal["EOA", "POLY_PROXY", "GNOSIS_SAFE", "DEPOSIT_WALLET"] > > class AsyncSecureClient: > wallet: EvmAddress > wallet_type: WalletType > ``` > > ```python Sync theme={null} > EvmAddress = NewType("EvmAddress", str) > > WalletType: TypeAlias = Literal["EOA", "POLY_PROXY", "GNOSIS_SAFE", "DEPOSIT_WALLET"] > > class SecureClient: > wallet: EvmAddress > wallet_type: WalletType > ``` > > You have created the new account. > [tab] API > > With the Builder API key ready, deploy a Deposit Wallet for each new signer > through the Relayer. > > **1. Prepare the Deployment Request** > > First, prepare a `WALLET-CREATE` request for each new signer. > > ```json wallet_create_body theme={null} > { > "type": "WALLET-CREATE", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "metadata": "Deploy Deposit Wallet" > } > ``` > > Create a Unix timestamp in seconds, then sign the exact serialized request body with the Builder API key `secret`. > > ```text theme={null} > request_timestamp = > method = "POST" > request_path = "/submit" > > message = request_timestamp + method + request_path + wallet_create_body > builder_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > **2. Deploy the Deposit Wallet** > > Then, submit the signed request to the Relayer. > > ```bash theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " \ > -d '{ > "type": "WALLET-CREATE", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "metadata": "Deploy Deposit Wallet" > }' > ``` > > The response includes the Relayer transaction ID. > > ```json Response theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **3. Confirm the Deployment** > > Then, poll the Relayer transaction until it reaches `STATE_CONFIRMED`. > > ```bash theme={null} > curl "https://relayer-v2.polymarket.com/transaction?id=" > ``` > > The confirmed transaction includes the new Deposit Wallet address as `proxyAddress`. > > ```json Response theme={null} > [ > { > "transactionID": "", > "transactionHash": "", > "proxyAddress": "", > "state": "STATE_CONFIRMED" > } > ] > ``` > > Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. > > **4. Create an L1 Signature** > > Then, create an L1 signature to attest to ownership of the signer > address. See [API Authentication](/getting-started/api#authentication) > for the complete signing flow. > > ```json clobAuthTypedData theme={null} > { > "domain": { > "name": "ClobAuthDomain", > "version": "1", > "chainId": 137 > }, > "types": { > "ClobAuth": [ > { "name": "address", "type": "address" }, > { "name": "timestamp", "type": "string" }, > { "name": "nonce", "type": "uint256" }, > { "name": "message", "type": "string" } > ] > }, > "primaryType": "ClobAuth", > "message": { > "address": "", > "timestamp": "", > "nonce": "", > "message": "This message attests that I control the given wallet" > } > } > ``` > > Sign `clobAuthTypedData` with the signer that controls ``. The returned signature is ``. > > **5. Create L2 Credentials** > > Finally, create L2 credentials by sending the signer address, > timestamp, nonce, and L1 signature to the CLOB. > > ```bash Create theme={null} > curl -X POST "https://clob.polymarket.com/auth/api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > ```bash Derive theme={null} > curl "https://clob.polymarket.com/auth/derive-api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > Store the returned L2 credentials for authenticated requests and order placement. > > ```json Response theme={null} > { > "apiKey": "", > "secret": "", > "passphrase": "" > } > ``` > > You have created the new account. ## Execute Gasless Transactions Approve token spending, transfer funds, and manage positions from the account wallet without paying gas. > [!NOTE] > > Polymarket Relayer only allows gasless transactions that interact with the > Polymarket Protocol and supported third-party contracts. > [tab] TypeScript > > `SecureClient` provides named methods for supported wallet actions. Most > return a `TransactionHandle` when awaited. Call `.wait()` on the handle to > wait for the action to settle. `setupTradingApprovals()` returns a > `Promise` and waits for completion internally, so await it directly. > > Create a `SecureClient` with either a Relayer or Builder API key: > > ```ts Relayer API Key theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > > const client = await createSecureClient({ > signer, > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: relayerApiKey({ > key: process.env.POLYMARKET_RELAYER_API_KEY!, > address: process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ```ts Builder API Key theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > > const client = await createSecureClient({ > signer, > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > Use the method that matches the wallet action you want to perform: > > | Action | Method | Documentation | > | - | - | - | > | Approve ERC-20 spending | `approveErc20()` | Below | > | Approve an ERC-1155 operator | `approveErc1155ForAll()` | Below | > | Transfer ERC-20 tokens | `transferErc20()` | Below | > | Set up trading approvals | `setupTradingApprovals()` | [Set Up Trading Approvals](#set-up-trading-approvals) | > | Split, merge, or redeem tokens | Position lifecycle methods | [Manage Positions](/trading/positions/manage) | > | Fund a Perps account | `depositToPerps()` | [Fund Your Account](/perps/fund-your-account) | > > **Approve ERC-20 spending** > > Set an allowance for a contract to spend an ERC-20 token from the account > wallet. Pass `"max"` to approve the maximum amount. > > ```ts theme={null} > const approval = await client.approveErc20({ > tokenAddress: "", > spenderAddress: "", > amount: "max", > }); > > await approval.wait(); > ``` > > **Approve an ERC-1155 operator** > > Allow an operator to manage every ERC-1155 token held by the account wallet. > Set `approved` to `false` to revoke access. > > ```ts theme={null} > const approval = await client.approveErc1155ForAll({ > tokenAddress: "", > operatorAddress: "", > approved: true, > }); > > await approval.wait(); > ``` > > **Transfer ERC-20 tokens** > > Transfer an ERC-20 token from the account wallet. `amount` is expressed in the > token's base units. > > ```ts theme={null} > const transfer = await client.transferErc20({ > tokenAddress: "", > recipientAddress: "", > amount: 1_000_000n, > }); > > await transfer.wait(); > ``` > [tab] Python > > `AsyncSecureClient` provides named methods for supported wallet actions. > Each method returns a transaction handle. Call `await handle.wait()` to > wait for the action to settle. The same methods are available on the > synchronous `SecureClient`. > > Create an `AsyncSecureClient` with either a Relayer or Builder API key: > > ```python Relayer API Key theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python Builder API Key theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > Use the method that matches the wallet action you want to perform: > > | Action | Method | Documentation | > | - | - | - | > | Approve ERC-20 spending | `approve_erc20()` | Below | > | Approve an ERC-1155 operator | `approve_erc1155_for_all()` | Below | > | Transfer ERC-20 tokens | `transfer_erc20()` | Below | > | Set up trading approvals | `setup_trading_approvals()` | [Set Up Trading Approvals](#set-up-trading-approvals) | > | Split, merge, or redeem tokens | Position lifecycle methods | [Manage Positions](/trading/positions/manage) | > | Fund a Perps account | `deposit_to_perps()` | [Fund Your Account](/perps/fund-your-account) | > > **Approve ERC-20 spending** > > Set an allowance for a contract to spend an ERC-20 token from the account > wallet. Pass `"max"` to approve the maximum amount. > > ```python theme={null} > approval = await client.approve_erc20( > token_address="", > spender_address="", > amount="max", > ) > > await approval.wait() > ``` > > **Approve an ERC-1155 operator** > > Allow an operator to manage every ERC-1155 token held by the account wallet. > Set `approved` to `False` to revoke access. > > ```python theme={null} > approval = await client.approve_erc1155_for_all( > token_address="", > operator_address="", > approved=True, > ) > > await approval.wait() > ``` > > **Transfer ERC-20 tokens** > > Transfer an ERC-20 token from the account wallet. `amount` is expressed in the > token's base units. > > ```python theme={null} > transfer = await client.transfer_erc20( > token_address="", > recipient_address="", > amount=1_000_000, > ) > > await transfer.wait() > ``` > [tab] API > > A Deposit Wallet executes one or more contract calls as an ordered batch. > The signer authorizes the complete batch, and the Relayer submits it > gaslessly. > > > [!NOTE] > > > > The following steps show the Deposit Wallet path. For Safe or Proxy Wallet > > flows, use an SDK that handles the wallet-specific payloads. > > **1. Build the Call List** > > First, encode each contract call and add it to the batch in execution order. > > ```json theme={null} > [ > { > "target": "", > "value": "0", > "data": "" > } > ] > ``` > > `target` is the contract to call, `value` is the amount of native POL to send in > wei, and `data` is the ABI-encoded function call. Use `"0"` for `value` when the > call does not transfer POL. > > **2. Fetch the Wallet Nonce** > > Then, fetch a fresh `WALLET` nonce for the signer using the API key for your > integration. > > ```bash Relayer API Key theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > ```bash Builder API Key theme={null} > curl -G "https://relayer-v2.polymarket.com/v1/account/transactions/params" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " \ > --data-urlencode "address=" \ > --data-urlencode "type=WALLET" > ``` > > For Builder API keys, create `builder_signature` from the request timestamp, > method, and path. See [Create New Accounts](#create-new-accounts) for the > complete signing flow. > > ```json Response theme={null} > { > "address": "", > "nonce": "" > } > ``` > > **3. Create the Batch Typed Data** > > Build a Deposit Wallet `Batch` containing the wallet address, fresh nonce, > future deadline, and call list. > > ```json walletBatchTypedData theme={null} > { > "domain": { > "name": "DepositWallet", > "version": "1", > "chainId": 137, > "verifyingContract": "" > }, > "types": { > "Call": [ > { "name": "target", "type": "address" }, > { "name": "value", "type": "uint256" }, > { "name": "data", "type": "bytes" } > ], > "Batch": [ > { "name": "wallet", "type": "address" }, > { "name": "nonce", "type": "uint256" }, > { "name": "deadline", "type": "uint256" }, > { "name": "calls", "type": "Call[]" } > ] > }, > "primaryType": "Batch", > "message": { > "wallet": "", > "nonce": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > } > ``` > > **4. Sign the Batch** > > Sign the typed data with the signer that controls the Deposit Wallet. The > example below uses Viem. > > ```ts theme={null} > import { privateKeyToAccount } from "viem/accounts"; > > const signer = privateKeyToAccount( > process.env.SIGNER_PRIVATE_KEY as `0x${string}`, > ); > const walletBatchSignature = await signer.signTypedData(walletBatchTypedData); > ``` > > **5. Submit the Batch** > > Submit the signed batch using the same call list and API key for your > integration. > > ```bash Relayer API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > ```bash Builder API Key theme={null} > curl -X POST "https://relayer-v2.polymarket.com/submit" \ > -H "Content-Type: application/json" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " \ > -d '{ > "type": "WALLET", > "from": "", > "to": "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", > "nonce": "", > "signature": "", > "metadata": "", > "depositWalletParams": { > "depositWallet": "", > "deadline": "", > "calls": [ > { > "target": "", > "value": "0", > "data": "" > } > ] > } > }' > ``` > > For Builder API keys, sign the request timestamp, method, path, and exact > serialized body as described in [Create New Accounts](#create-new-accounts). > > The response includes the transaction ID used in the next step. > > ```json Response theme={null} > { > "transactionID": "", > "state": "STATE_NEW" > } > ``` > > **6. Confirm the Transaction** > > Poll the transaction until it reaches `STATE_CONFIRMED`. > > ```bash Relayer API Key theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "RELAYER_API_KEY: " \ > -H "RELAYER_API_KEY_ADDRESS: " > ``` > > ```bash Builder API Key theme={null} > curl "https://relayer-v2.polymarket.com/v1/account/transactions/" \ > -H "POLY_BUILDER_API_KEY: " \ > -H "POLY_BUILDER_TIMESTAMP: " \ > -H "POLY_BUILDER_PASSPHRASE: " \ > -H "POLY_BUILDER_SIGNATURE: " > ``` > > ```json Response theme={null} > { > "transaction_id": "", > "transaction_hash": "", > "state": "STATE_CONFIRMED", > "error_msg": null > } > ``` > > Treat `STATE_FAILED` and `STATE_INVALID` as terminal failures. ## Set Up Trading Approvals Set up the ERC-20 and ERC-1155 approvals that allow Polymarket's exchange contracts to spend the account wallet's pUSD and outcome tokens when placing orders. For Deposit Wallets, Safe Wallets, and Proxy Wallets, these approvals are submitted as a gasless transaction. Orders on CTF negative-risk markets also require pUSD and outcome token approvals for the Neg Risk Adapter. The CLOB rejects buy orders without the pUSD approval and sell orders without the outcome token approval. > [tab] TypeScript > > Create a `SecureClient` with either a Relayer or Builder API key: > > ```ts Relayer API Key theme={null} > import { createSecureClient, relayerApiKey } from "@polymarket/client"; > > const client = await createSecureClient({ > signer, > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: relayerApiKey({ > key: process.env.POLYMARKET_RELAYER_API_KEY!, > address: process.env.POLYMARKET_RELAYER_API_KEY_ADDRESS!, > }), > }); > ``` > > ```ts Builder API Key theme={null} > import { createSecureClient } from "@polymarket/client"; > import { builderApiKey } from "@polymarket/client/node"; > > const client = await createSecureClient({ > signer, > wallet: process.env.POLYMARKET_WALLET_ADDRESS, > apiKey: builderApiKey({ > key: process.env.POLYMARKET_BUILDER_API_KEY!, > secret: process.env.POLYMARKET_BUILDER_SECRET!, > passphrase: process.env.POLYMARKET_BUILDER_PASSPHRASE!, > }), > }); > ``` > > Call `setupTradingApprovals()` to configure the required allowances: > > ```ts theme={null} > await client.setupTradingApprovals(); > ``` > > The method covers both position systems. It checks existing approvals and > submits only what is missing, so it is safe to call more than once. > > Order placement can recover from missing exchange allowances automatically. Setting them up in advance keeps that work out of your first order. > > Neither `setupTradingApprovals()` nor automatic recovery grants the Neg Risk > Adapter approvals. Submit them with `approveErc20()` and > `approveErc1155ForAll()`: > > ```ts theme={null} > const negRiskAdapter = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"; > > const collateralApproval = await client.approveErc20({ > tokenAddress: "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > spenderAddress: negRiskAdapter, > amount: "max", > }); > await collateralApproval.wait(); > > const outcomeApproval = await client.approveErc1155ForAll({ > tokenAddress: "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", > operatorAddress: negRiskAdapter, > approved: true, > }); > await outcomeApproval.wait(); > ``` > > The first call approves pUSD for buy orders. The second approves Conditional > Tokens for sell orders. > > Both methods return promises that resolve after submission. Call each returned > handle's `wait()` to confirm the approvals before placing orders. > `setupTradingApprovals()` waits for its approval transactions internally. > [tab] Python > > Create an `AsyncSecureClient` with either a Relayer or Builder API key (the > same workflow is available with the synchronous `SecureClient`): > > ```python Relayer API Key theme={null} > import os > > from polymarket import AsyncSecureClient, RelayerApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=RelayerApiKey( > key=os.environ["POLYMARKET_RELAYER_API_KEY"], > address=os.environ["POLYMARKET_RELAYER_API_KEY_ADDRESS"], > ), > ) > ``` > > ```python Builder API Key theme={null} > import os > > from polymarket import AsyncSecureClient, BuilderApiKey > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > api_key=BuilderApiKey( > key=os.environ["POLYMARKET_BUILDER_API_KEY"], > secret=os.environ["POLYMARKET_BUILDER_SECRET"], > passphrase=os.environ["POLYMARKET_BUILDER_PASSPHRASE"], > ), > ) > ``` > > Call `setup_trading_approvals()` to configure the required allowances: > > ```python theme={null} > await client.setup_trading_approvals() > ``` > > The method covers both position systems. It checks existing approvals and > submits only what is missing, so it is safe to call more than once. > > Order placement can recover from missing exchange allowances automatically. Setting them up in advance keeps that work out of your first order. > > Neither `setup_trading_approvals()` nor automatic recovery grants the Neg Risk > Adapter approvals. Grant them once with `approve_erc20()` and > `approve_erc1155_for_all()`: > > ```python theme={null} > neg_risk_adapter = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296" > > collateral_approval = await client.approve_erc20( > token_address="0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > spender_address=neg_risk_adapter, > amount="max", > ) > await collateral_approval.wait() > > outcome_approval = await client.approve_erc1155_for_all( > token_address="0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", > operator_address=neg_risk_adapter, > approved=True, > ) > await outcome_approval.wait() > ``` > > The first call approves pUSD for buy orders. The second approves Conditional > Tokens for sell orders. > [tab] API > > Configure the three exchange contracts and the Neg Risk Adapter so a > Deposit Wallet can trade both position systems. > > > [!NOTE] > > > > The following steps show the Deposit Wallet path. For Safe or Proxy Wallet > > flows, use an SDK that handles the wallet-specific payloads. For EOA trading, > > see [Set Up EOA Trading](#set-up-eoa-trading). > > **1. Check the Required Approvals** > > First, check each allowance before building the transaction so the batch > contains only missing approvals. > > | Asset ledger | Spender or operator | Contract call | > | - | - | - | > | pUSD | Polymarket V2 Exchange | `approve(ProtocolV2Exchange, maxUint256)` | > | pUSD | Standard Exchange | `approve(StandardExchange, maxUint256)` | > | pUSD | Neg Risk Exchange | `approve(NegRiskExchange, maxUint256)` | > | pUSD | Neg Risk Adapter | `approve(NegRiskAdapter, maxUint256)` | > | PositionManager | Polymarket V2 Exchange | `setApprovalForAll(ProtocolV2Exchange, true)` | > | Conditional Tokens | Standard Exchange | `setApprovalForAll(StandardExchange, true)` | > | Conditional Tokens | Neg Risk Exchange | `setApprovalForAll(NegRiskExchange, true)` | > | Conditional Tokens | Neg Risk Adapter | `setApprovalForAll(NegRiskAdapter, true)` | > > Read pUSD approvals with `allowance(wallet, spender)`. Read outcome token > approvals with `isApprovedForAll(wallet, operator)` on Conditional Tokens or > PositionManager. > > | Contract | Address | > | - | - | > | pUSD | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | > | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | > | Conditional Tokens | `0x4D97DCd97eC945f40cF65F87097ACe5EA0476045` | > | Polymarket V2 Exchange | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | > | Standard Exchange | `0xE111180000d2663C0091e4f400237545B87B996B` | > | Neg Risk Exchange | `0xe2222d279d744050d28e00520010520000310F59` | > | Neg Risk Adapter | `0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296` | > > **2. Build the Approval Call List** > > Then, encode the missing ERC-20 and ERC-1155 approval calls. > > ```solidity ERC-20 Approval theme={null} > function approve(address spender, uint256 amount) returns (bool); > ``` > > ```solidity ERC-1155 Approval theme={null} > function setApprovalForAll(address operator, bool approved); > ``` > > Build one call for each missing approval. This example includes all eight. > > ```json theme={null} > [ > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", > "value": "0", > "data": "" > }, > { > "target": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", > "value": "0", > "data": "" > }, > { > "target": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", > "value": "0", > "data": "" > }, > { > "target": "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", > "value": "0", > "data": "" > }, > { > "target": "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", > "value": "0", > "data": "" > } > ] > ``` > > **3. Execute the Approval Batch** > > Use the approval call list as the `calls` in [Execute Gasless > Transactions](#execute-gasless-transactions). Fetch a fresh nonce, sign the > complete batch, submit it, and wait for `STATE_CONFIRMED` before continuing. > > **4. Sync CLOB Allowances** > > Finally, update the CLOB allowance cache: > > ```bash Collateral theme={null} > curl -G "https://clob.polymarket.com/balance-allowance/update" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > --data-urlencode "asset_type=COLLATERAL" \ > --data-urlencode "signature_type=3" > ``` > > Then, refresh the outcome allowance for the position system you trade: > > ```bash Polymarket V2 theme={null} > curl -G "https://clob.polymarket.com/balance-allowance/update" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > --data-urlencode "asset_type=CONDITIONAL-V2" \ > --data-urlencode "token_id=" \ > --data-urlencode "signature_type=3" > ``` > > ```bash CTF theme={null} > curl -G "https://clob.polymarket.com/balance-allowance/update" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_API_KEY: " \ > -H "POLY_PASSPHRASE: " \ > --data-urlencode "asset_type=CONDITIONAL" \ > --data-urlencode "token_id=" \ > --data-urlencode "signature_type=3" > ``` > > Using the signer address and CLOB API credentials from [API > Authentication](/getting-started/api#authentication), create a fresh > `` and generate `` without a request > body. The query parameters are not part of the signed path: > > ```text theme={null} > message = + "GET" + "/balance-allowance/update" > > clob_l2_signature = urlsafeBase64WithPadding( > HMAC-SHA256(base64Decode(), message) > ) > ``` > > Refresh the conditional allowance for each outcome before its first sell order. > Use `CONDITIONAL` with a CTF token ID and `CONDITIONAL-V2` with a Polymarket > Protocol V2 Position ID. Both requests carry the selected ID in `token_id`. *** ## Advanced Options Explore additional wallet and authentication patterns for advanced integrations. ### Derive a Deposit Wallet Address If you need to compute a Deposit Wallet address before deployment, use the deterministic derivation algorithm below. > [!NOTE] > > Deposit Wallets deployed before the June 29, 2026 upgrade use a UUPS proxy. > Deposit Wallets deployed after the upgrade use a beacon proxy. The following > algorithm derives the address for a new Deposit Wallet with a beacon proxy. ```text theme={null} factory = 0x00000000000Fb5C9ADea0298D729A0CB3823Cc07 beacon = 0x7A18EDfe055488A3128f01F563e5B479D92ffc3a walletId = bytes32(signer) // left-pad the signer to 32 bytes args = abi.encode(factory, walletId) salt = keccak256(args) beaconInitCodeHash = SoladyLibClone.initCodeHashERC1967BeaconProxy(beacon, args) depositWallet = CREATE2(factory, salt, beaconInitCodeHash) ``` See [Contract Addresses](/resources/contracts#wallet-factory-contracts) for the current Deposit Wallet factory and beacon. ### Set Up EOA Trading If your EOA is allowlisted for trading, use it as the account wallet. Every onchain action, including token approvals, ERC-20 transfers, splits, merges, and redemptions, is submitted directly from the EOA and requires POL for gas. > [tab] TypeScript > > Pass the signer address as `wallet`. The SDK identifies the account as an > EOA and skips Deposit Wallet deployment. > > ```ts theme={null} > import { createSecureClient } from "@polymarket/client"; > import { privateKey } from "@polymarket/client/viem"; > > const signer = privateKey(process.env.SIGNER_PRIVATE_KEY); > const client = await createSecureClient({ > signer, > wallet: await signer.getAddress(), > }); > ``` > > Methods such as `approveErc20()`, `approveErc1155ForAll()`, `transferErc20()`, > and the position lifecycle methods submit transactions directly from the > signer. For example, set up every required trading approval: > > ```ts theme={null} > await client.setupTradingApprovals(); > ``` > [tab] Python > > Pass the signer address as `wallet`. The SDK identifies the account as an > EOA and skips Deposit Wallet deployment. > > ```python theme={null} > import os > > from polymarket import AsyncSecureClient > > client = await AsyncSecureClient.create( > private_key=os.environ["SIGNER_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_SIGNER_ADDRESS"], > ) > ``` > > Methods such as `approve_erc20()`, `approve_erc1155_for_all()`, > `transfer_erc20()`, and the position lifecycle methods submit transactions > directly from the signer. For example, set up every required trading approval: > > ```python theme={null} > await client.setup_trading_approvals() > ``` > [tab] API > > **1. Set Up Trading Approvals** > > First, approve the CLOB exchange contracts to spend pUSD and manage the > matching outcome token ledger. Submit each required approval transaction > from the EOA and pay gas with POL held at that address. > > See [Set Up Trading Approvals](#set-up-trading-approvals) for the required approvals and contract addresses. > > **2. Create an L1 Signature** > > Then, create an L1 signature to attest to ownership of the EOA. See [API > Authentication](/getting-started/api#authentication) for the complete > signing flow. > > ```json clobAuthTypedData theme={null} > { > "domain": { > "name": "ClobAuthDomain", > "version": "1", > "chainId": 137 > }, > "types": { > "ClobAuth": [ > { "name": "address", "type": "address" }, > { "name": "timestamp", "type": "string" }, > { "name": "nonce", "type": "uint256" }, > { "name": "message", "type": "string" } > ] > }, > "primaryType": "ClobAuth", > "message": { > "address": "", > "timestamp": "", > "nonce": "", > "message": "This message attests that I control the given wallet" > } > } > ``` > > Sign `clobAuthTypedData` with the EOA. The returned signature is ``. > > **3. Create L2 Credentials** > > Finally, create L2 credentials by sending the signer address, > timestamp, nonce, and L1 signature to the CLOB. > > ```bash Create theme={null} > curl -X POST "https://clob.polymarket.com/auth/api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > ```bash Derive theme={null} > curl "https://clob.polymarket.com/auth/derive-api-key" \ > -H "POLY_ADDRESS: " \ > -H "POLY_SIGNATURE: " \ > -H "POLY_TIMESTAMP: " \ > -H "POLY_NONCE: " > ``` > > Store the returned L2 credentials for authenticated requests and order placement. > > ```json Response theme={null} > { > "apiKey": "", > "secret": "", > "passphrase": "" > } > ``` > > See [Place a Limit Order](/trading/place-orders#place-a-limit-order) for the > complete direct API order flow. ### Remote Builder Signing Remote Builder Signing keeps Builder API credentials on your server while a TypeScript client requests signed headers for Builder-authenticated actions. **1. Create a Signing Endpoint** Authenticate and authorize the caller on your server, then sign the request details supplied by the client. ```ts theme={null} import { buildHmacSignature } from "@polymarket/client"; export async function POST(request: Request): Promise { const { body, method, path } = await request.json(); const timestamp = Math.floor(Date.now() / 1000); return Response.json({ POLY_BUILDER_API_KEY: process.env.POLYMARKET_BUILDER_API_KEY!, POLY_BUILDER_PASSPHRASE: process.env.POLYMARKET_BUILDER_PASSPHRASE!, POLY_BUILDER_SIGNATURE: await buildHmacSignature( process.env.POLYMARKET_BUILDER_SECRET!, timestamp, method, path, body, ), POLY_BUILDER_TIMESTAMP: `${timestamp}`, }); } ``` **2. Connect the Client** Pass the user's signer and the signing endpoint to the client. Authenticate signing requests with the application's session credentials or custom headers. ```ts Cookie Session theme={null} import { createSecureClient, remoteBuilderSigning } from "@polymarket/client"; const client = await createSecureClient({ signer, apiKey: remoteBuilderSigning({ url: "/api/builder/sign", credentials: "include", }), }); ``` ```ts Custom Headers theme={null} import { createSecureClient, remoteBuilderSigning } from "@polymarket/client"; const client = await createSecureClient({ signer, apiKey: remoteBuilderSigning({ url: "/api/builder/sign", headers: { Authorization: "Bearer eyJhbGciOiJIUzI1NiJ9.…", }, }), }); ``` The Builder API credentials remain on the server. The client receives only the headers for the request being authorized. ### Opt Out of Beacon Upgrades Deposit Wallets deployed after June 29, 2026 use an [ERC-1967 beacon proxy](https://eips.ethereum.org/EIPS/eip-1967#beacon-contract-address). This proxy pattern resolves the implementation for multiple wallets through a shared beacon, allowing Polymarket to send implementation upgrades without changing their addresses. The wallet owner can instead pin the wallet to the implementation that is current when it opts out. The owner-only calls below are submitted directly and require POL for gas. > [!WARNING] > > An opted-out wallet does not receive future security fixes, bug fixes, or > features delivered through beacon upgrades. Review the current implementation > and accept responsibility for maintaining the wallet before opting out. **1. Pause the Wallet** Send a direct onchain transaction from the wallet owner to call `pause()` on the Deposit Wallet. **2. Wait for the Timelock** Read `timelockDelay()` from the Deposit Wallet factory and wait until that interval has elapsed after the wallet was paused. **3. Opt Out** Send another transaction from the wallet owner to call `optOut()` on the Deposit Wallet. This pins the wallet to the beacon implementation that is current when the transaction executes. **4. Unpause the Wallet** Call `unpause()` from the wallet owner to clear the paused state. To resume receiving beacon upgrades, repeat the pause and timelock steps, call `optIn()`, and then unpause the wallet. Review the beacon's current default implementation before opting back in. # Get rate limit tier Source: https://docs.polymarket.com/api-reference/account/get-rate-limit-tier /api-spec/clob-openapi.yaml get /v1/user/rate-limit-tier Returns the [trading rate limit tier](/api-reference/trading-rate-limits) currently assigned to your signer. The tier returned is the one for the signer address of the API credentials used. The response reflects the most recent tier refresh, so a change in volume can take up to three hours to appear. # Get builder volume over time Source: https://docs.polymarket.com/api-reference/boards/get-builder-volume-over-time https://data-api.polymarket.com/v2/openapi.json get /v2/builders/volume The per-builder volume time series. `?interval=` is the **bucket width**, not a window: `day` (default) returns every day on record bucketed daily, `week` and `month` bucket accordingly, and `all` buckets by calendar YEAR. `?limit=` bounds how many of the most recent buckets come back (default 30); buckets, not rows, so a period is never returned half-populated. `timePeriod` is accepted as an alias for `interval`. `rank` is the builder's placing **within its own bucket**, so it moves along the series. `volume` is in SHARES; see `/v2/builders/leaderboard`. Not paginated: `data` is the array with no `pagination`, the `/v2/oi` shape. Rows arrive newest bucket first, ranked within each. # Get the builders leaderboard Source: https://docs.polymarket.com/api-reference/boards/get-the-builders-leaderboard https://data-api.polymarket.com/v2/openapi.json get /v2/builders/leaderboard The ranked board of builders by volume. `?time_period=` is `day` (default), `week`, `month` or `all` and selects the **window**; one row per builder in it. Deeper pages come only from `?cursor=`. A cursor **pins the window it was minted on**, so following it needs no `?time_period=`; and passing a different one is a `400` rather than a silent re-point, since an offset from one board means nothing on another. `volume` is in SHARES, not USDC, the same unit as `/v2/leaderboard`'s `volume`. `active_users` counts distinct makers in the window. `builder` is a display name that falls back to `builder_code` for a builder with no profile, so key on `builder_code` and render `builder`. # Get the trader leaderboard Source: https://docs.polymarket.com/api-reference/boards/get-the-trader-leaderboard https://data-api.polymarket.com/v2/openapi.json get /v2/leaderboard The ranked board of realized PnL, combos included. `?time_period=` is `day` (default), `week`, `month` or `all`; `?category=` is `overall` (default) or a market category; `?sort_by=` picks the `PNL` (default) or `VOLUME` board. Deeper pages come only from `?cursor=`. A cursor **pins the board it was minted on**; sort, window and category; so following it needs no params at all, and restating a different one is a `400` rather than a silent re-point (the builders-board pattern). `?user=` answers a different question; one wallet's standing, carrying **both** the PnL and volume ranks in a single object rather than a page. A rank of `0` there means unranked for that board, not first. `sort_by`, `limit` and `cursor` do not apply to that arm. **`rank` ties and skips**: tied users share a rank and the next one jumps, so a partition's highest rank approaches its row count. Page with the cursor; never compute a page from a rank. Finite windows (day/week/month) serve the MARKED equity change net of flows; they move with unrealized marks; `all` is the realized-only lifetime ledger. `volume` is in shares, not USDC. # List the biggest wins Source: https://docs.polymarket.com/api-reference/boards/list-the-biggest-wins https://data-api.polymarket.com/v2/openapi.json get /v2/biggest-winners The biggest single winning positions. One row per winning POSITION, not per user: `pnl` is `final_value - initial_value` for that position, and the window (`?time_period=`, default `day`) is on when it resolved. `?category=` narrows to a market category. Deeper pages come only from `?cursor=`, which **pins the window and category it was minted on**; restating a different one is a `400`, not a silent re-point. Combo wins are first-class rows here, tagged `kind = "combo"`. They carry a `' / '`-joined title of their legs and no Gamma event; `event_id` is `0` and `event_slug` empty; so **branch on `kind` before building an event link**. # Get comments by comment id Source: https://docs.polymarket.com/api-reference/comments/get-comments-by-comment-id /api-spec/gamma-openapi.yaml get /comments/{id} # Get comments by user address Source: https://docs.polymarket.com/api-reference/comments/get-comments-by-user-address /api-spec/gamma-openapi.yaml get /comments/user_address/{user_address} # List comments Source: https://docs.polymarket.com/api-reference/comments/list-comments /api-spec/gamma-openapi.yaml get /comments # Get midpoint price Source: https://docs.polymarket.com/api-reference/data/get-midpoint-price /api-spec/clob-openapi.yaml get /midpoint Retrieves the midpoint price for a specific token ID. The midpoint is calculated as the average of the best bid and best ask prices. # Get server time Source: https://docs.polymarket.com/api-reference/data/get-server-time /api-spec/clob-openapi.yaml get /time Returns the current Unix timestamp of the server. This can be used to synchronize client time with server time. # Get event by id Source: https://docs.polymarket.com/api-reference/events/get-event-by-id /api-spec/gamma-openapi.yaml get /events/{id} # Get event by slug Source: https://docs.polymarket.com/api-reference/events/get-event-by-slug /api-spec/gamma-openapi.yaml get /events/slug/{slug} # Get event tags Source: https://docs.polymarket.com/api-reference/events/get-event-tags /api-spec/gamma-openapi.yaml get /events/{id}/tags # List events Source: https://docs.polymarket.com/api-reference/events/list-events /api-spec/gamma-openapi.yaml get /events # List events (keyset pagination) Source: https://docs.polymarket.com/api-reference/events/list-events-keyset-pagination /api-spec/gamma-openapi.yaml get /events/keyset Returns events using cursor-based (keyset) pagination for stable, efficient paging through large result sets. Use `next_cursor` from each response as `after_cursor` in the next request. The `offset` parameter is explicitly rejected; use `after_cursor` instead. # List account activity Source: https://docs.polymarket.com/api-reference/feeds/list-account-activity https://data-api.polymarket.com/v2/openapi.json get /v2/activity Keyset-paginated activity feed (trades, splits, merges, redeems, …) in the standard `{ data, pagination }` envelope. Ordering is `(block_timestamp, sequence_id)`, `DESC` by default or `ASC` via `sort_direction=ASC`; both keyset-seekable. Value sorts (`CASH`/`TOKENS`) have no seek anchor and are rejected with `400` rather than silently re-served as page one. The cursor binds the direction it was minted under and the resume ADOPTS it, so a replay cannot flip the walk mid-stream. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # List trades Source: https://docs.polymarket.com/api-reference/feeds/list-trades https://data-api.polymarket.com/v2/openapi.json get /v2/trades Keyset-paginated trade feed in the standard `{ data, pagination }` envelope. Pass `?cursor=` from a prior response's `next_cursor` to fetch the next page; it carries both the page size and the `(block_timestamp, sequence_id)` seek anchor, so deep pages cost the same as shallow ones. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # Geographic Restrictions Source: https://docs.polymarket.com/api-reference/geoblock Check geographic restrictions before placing orders on the Polymarket API Polymarket restricts order placement from certain geographic locations due to regulatory requirements and compliance with international sanctions. Before placing orders, builders should verify the location. > [!WARNING] > > Orders submitted from blocked regions will be rejected. Implement geoblock > checks in your application to provide users with appropriate feedback before > they attempt to trade. *** ## Geoblock Endpoint Check the geographic eligibility of the requesting IP address: ```bash theme={null} GET https://polymarket.com/api/geoblock ``` > [!NOTE] > > This endpoint is on `polymarket.com`, not the API servers. ### Response ```json theme={null} { "blocked": true, "ip": "203.0.113.42", "country": "US", "region": "NY" } ``` | Field | Type | Description | | - | - | - | | `blocked` | boolean | Whether the user is blocked from placing orders | | `ip` | string | Detected IP address | | `country` | string | ISO 3166-1 alpha-2 country code | | `region` | string | Region/state code | *** ## Restricted Jurisdictions Restrictions fall into three groups. **Block completely** means no new orders and no closing of existing positions. **Close-only** means users can close existing positions but cannot open new ones. Each group notes whether it applies on the frontend, the API, or both. Codes are ISO 3166-1 alpha-2 for countries and ISO 3166-2 for sub-national regions. ### OFAC-Sanctioned Jurisdictions (Block Completely) Blocked on both the frontend and the API. No new orders, and existing positions cannot be closed. | Jurisdiction | Code | | - | - | | Iran | IR | | Syria | SY | | Cuba | CU | | North Korea | KP | | Ukraine — Crimea | UA-43 | | Ukraine — Donetsk | UA-14 | | Ukraine — Luhansk | UA-09 | ### Regulatory-Restricted Jurisdictions (Close-Only on Frontend and API) Users can close existing positions but cannot open new ones, on both the frontend and the API. | Jurisdiction | Code | | - | - | | Argentina | AR | | Australia | AU | | Belarus | BY | | Belgium | BE | | Burundi | BI | | Brazil | BR | | Canada — British Columbia | CA-BC | | Canada — Ontario | CA-ON | | Canada — Alberta | CA-AB | | Canada — Quebec | CA-QC | | Central African Republic | CF | | Congo (Kinshasa) | CD | | Ethiopia | ET | | France | FR | | Germany | DE | | Iraq | IQ | | Italy | IT | | Lebanon | LB | | Libya | LY | | Myanmar | MM | | New Zealand | NZ | | Nicaragua | NI | | North Korea | KP | | Poland | PL | | Russia | RU | | Singapore | SG | | Somalia | SO | | Slovakia | SK | | South Sudan | SS | | Sudan | SD | | Taiwan | TW | | Thailand | TH | | United Kingdom | GB | | United States | US | | United States Minor Outlying Islands | UM | | Venezuela | VE | | Yemen | YE | | Zimbabwe | ZW | ### Regulatory-Restricted Jurisdictions (Close-Only on Frontend) Close-only on the Polymarket frontend; the API itself is not restricted. | Jurisdiction | Code | | - | - | | Ireland | IE | | Japan | JP | | Malta (Sports Only) | MT | | Netherlands | NL | | South Korea | KR | *** ## Blocking Logic The geoblocking system includes: 1. **OFAC-Sanctioned Countries**: Countries sanctioned by the U.S. Office of Foreign Assets Control (OFAC) 2. **Additional Regulatory Restrictions**: Countries added for specific regulatory compliance reasons *** ## Server Infrastructure and Co-Location * **Primary Servers**: eu-west-2 * **Closest Non-Georestricted Region**: eu-west-1 > [!TIP] > > **Direct co-location form.** Users who complete the [KYC/KYB > form](https://docs.google.com/forms/d/e/1FAIpQLSfY-3Dl3yxq8HKFjFad8YzKZmm0k3Gdg29HD6gL-K-AmI6KXw/viewform) can get access to co-locate > directly in `eu-west-2` for the lowest possible latency to Polymarket's > primary servers. > [!WARNING] > > Co-location is available to market makers and individual traders operating on > their own account. It is not available to Builder Program participants or > third-party applications executing trades on behalf of end users. *** ## Usage Examples > [tab] TypeScript > > ```typescript theme={null} > interface GeoblockResponse { > blocked: boolean; > ip: string; > country: string; > region: string; > } > > async function checkGeoblock(): Promise { > const response = await fetch("https://polymarket.com/api/geoblock"); > return response.json(); > } > > // Usage > const geo = await checkGeoblock(); > > if (geo.blocked) { > console.log(`Trading not available in ${geo.country}`); > } else { > console.log("Trading available"); > } > ``` > [tab] Python > > ```python theme={null} > import requests > > def check_geoblock() -> dict: > response = requests.get("https://polymarket.com/api/geoblock") > return response.json() > > # Usage > geo = check_geoblock() > > if geo["blocked"]: > print(f"Trading not available in {geo['country']}") > else: > print("Trading available") > ``` *** ## Why These Restrictions Geographic restrictions are implemented to ensure compliance with: * International sanctions and embargoes * Local financial regulations * Gambling and prediction market laws * Anti-money laundering (AML) requirements * Know Your Customer (KYC) regulations If you believe you are incorrectly restricted or have questions about geographic availability, please contact [Polymarket Support](https://polymarket.com/support). *** ## Next Steps > [card] [Authentication](/getting-started/api#authentication) > > Learn how to authenticate trading requests. > [card] [Place Orders](/trading/quickstart) > > Start placing orders (from eligible regions). # Get fee rate Source: https://docs.polymarket.com/api-reference/market-data/get-fee-rate /api-spec/clob-openapi.yaml get /fee-rate Retrieves the base fee rate for a specific token ID. The fee rate can be provided either as a query parameter or as a path parameter. # Get fee rate by path parameter Source: https://docs.polymarket.com/api-reference/market-data/get-fee-rate-by-path-parameter /api-spec/clob-openapi.yaml get /fee-rate/{token_id} Retrieves the base fee rate for a specific token ID using the token ID as a path parameter. # Get last trade price Source: https://docs.polymarket.com/api-reference/market-data/get-last-trade-price /api-spec/clob-openapi.yaml get /last-trade-price Retrieves the last trade price and side for a specific token ID. Returns default values of "0.5" for price and empty string for side if no trades found. # Get last trade prices (query parameters) Source: https://docs.polymarket.com/api-reference/market-data/get-last-trade-prices-query-parameters /api-spec/clob-openapi.yaml get /last-trades-prices Retrieves last trade prices for multiple token IDs using query parameters. Maximum 500 token IDs can be requested per call. # Get last trade prices (request body) Source: https://docs.polymarket.com/api-reference/market-data/get-last-trade-prices-request-body /api-spec/clob-openapi.yaml post /last-trades-prices Retrieves last trade prices for multiple token IDs using a request body. Maximum 500 token IDs can be requested per call. # Get market price Source: https://docs.polymarket.com/api-reference/market-data/get-market-price /api-spec/clob-openapi.yaml get /price Retrieves the best market price for a specific token ID and side (bid or ask). Returns the best bid price for BUY side or best ask price for SELL side. # Get market prices (query parameters) Source: https://docs.polymarket.com/api-reference/market-data/get-market-prices-query-parameters /api-spec/clob-openapi.yaml get /prices Retrieves market prices for multiple token IDs and sides using query parameters. # Get market prices (request body) Source: https://docs.polymarket.com/api-reference/market-data/get-market-prices-request-body /api-spec/clob-openapi.yaml post /prices Retrieves market prices for multiple token IDs and sides using a request body. Each request must include both token_id and side. # Get midpoint prices (query parameters) Source: https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-query-parameters /api-spec/clob-openapi.yaml get /midpoints Retrieves midpoint prices for multiple token IDs using query parameters. The midpoint is calculated as the average of the best bid and best ask prices. # Get midpoint prices (request body) Source: https://docs.polymarket.com/api-reference/market-data/get-midpoint-prices-request-body /api-spec/clob-openapi.yaml post /midpoints Retrieves midpoint prices for multiple token IDs using a request body. The midpoint is calculated as the average of the best bid and best ask prices. # Get order book Source: https://docs.polymarket.com/api-reference/market-data/get-order-book /api-spec/clob-openapi.yaml get /book Retrieves the order book summary for a specific token ID. Includes bids, asks, market details, and last trade price. # Get order books (request body) Source: https://docs.polymarket.com/api-reference/market-data/get-order-books-request-body /api-spec/clob-openapi.yaml post /books Retrieves order book summaries for multiple token IDs using a request body. # Get spread Source: https://docs.polymarket.com/api-reference/market-data/get-spread /api-spec/clob-openapi.yaml get /spread Retrieves the spread for a specific token ID. The spread is the difference between the best ask and best bid prices. # Get spreads Source: https://docs.polymarket.com/api-reference/market-data/get-spreads /api-spec/clob-openapi.yaml post /spreads Retrieves spreads for multiple token IDs. The spread is the difference between the best ask and best bid prices. # Get tick size Source: https://docs.polymarket.com/api-reference/market-data/get-tick-size /api-spec/clob-openapi.yaml get /tick-size Retrieves the minimum tick size (price increment) for a specific token ID. The tick size can be provided either as a query parameter or as a path parameter. # Get tick size by path parameter Source: https://docs.polymarket.com/api-reference/market-data/get-tick-size-by-path-parameter /api-spec/clob-openapi.yaml get /tick-size/{token_id} Retrieves the minimum tick size (price increment) for a specific token ID using the token ID as a path parameter. # Get a token's price history Source: https://docs.polymarket.com/api-reference/markets/get-a-tokens-price-history https://data-api.polymarket.com/v2/openapi.json get /v2/prices-history The price-history series for one outcome token, or a single point-in-time observation. Three window forms, exactly one per request: `start` (with optional `end`), `interval`, or `as_of`. Points are served oldest-first; pass `?cursor=` from a prior response's `next_cursor` for the next page. `interval=max` (or `all`) serves the market's whole life, back to 2022 for the oldest markets, at 12-hour buckets unless `bucket_seconds` says otherwise; explicit `start`/`end` windows cap at 15 days, so the presets are the long-range path. The series ends with a **terminal point**: the latest observation inside the window, which is a real tick and so can fall between bucket boundaries. Nothing may assume uniform spacing (sparse data already forbids that), and each point's `resolution_seconds` says what window it was observed in. **Availability is graded by resolution.** The 3-hour and 12-hour series are permanent (back to 2022-11-18); the fine grains are windowed, with these MINIMUMS: 1-minute data at least 7 days, 5-minute at least 60, 30-minute at least 90. Floors, not exact horizons: data expires in multi-day chunks, so a grain usually reaches a few days further back than its minimum. Coverage is measured per request, never assumed from a table, so `bucket_seconds=60` over a window starting a month ago is an incompatible pair: both values are valid, and there is no data at their intersection. The two ways of asking behave differently on purpose: * **`bucket_seconds` sent** is served exactly as asked, so over a window whose resolution has expired you get an empty page rather than a silent substitution. * **`bucket_seconds` omitted** lets the server choose a width that can actually serve the window: the finest tier grain whose series stays under ~2,500 points, except that a window wider than 12 hours never defaults to the 60-second grain (ask for `bucket_seconds=60` explicitly when you want it over a longer window), and coarsened further if that grain does not reach the window's start. A window up to 12 hours keeps 1-minute detail (an hour 60 points, 12 hours 720); beyond that it moves to a materialized tier (a day 288, three days 864, a week 2,016, fifteen days 720). Send `bucket_seconds` when you want a specific density instead. A RESOLVED market's series ends with one settlement point: the on-chain payout of the requested token (0 lost, 1 won, fractional for voided or split resolutions) at `resolution_seconds` 0, placed one bucket edge past the last stored row and clamped to an explicit window's `end`. It appears only on the final page of a paginated walk, and only once the resolution is settled on-chain; an unresolved market's series is unchanged. `resolution_seconds` on every point reports what it was served at, so read it instead of assuming the width a recent window would have given you. For a multi-day window prefer a grain-aligned `bucket_seconds` (300, 1800, 10800, 43200) or omit it; a 60-second width over days is the one shape that is both slow and, past 7 days, empty. # Get batch prices history Source: https://docs.polymarket.com/api-reference/markets/get-batch-prices-history /api-spec/clob-openapi.yaml post /batch-prices-history Retrieve historical price data for multiple markets in a single request. # Get CLOB market info Source: https://docs.polymarket.com/api-reference/markets/get-clob-market-info /api-spec/clob-openapi.yaml get /clob-markets/{condition_id} Returns all CLOB-level parameters for a market in a single call — tokens, tick size, base fees, rewards, RFQ status, and fee details. # Get live volume for an event Source: https://docs.polymarket.com/api-reference/markets/get-live-volume-for-an-event https://data-api.polymarket.com/v2/openapi.json get /v2/live-volume Cumulative one-side (taker) volume per market. Pass `?event_id=` as a comma-separated list of integer event ids (aliases `id` / `eventId`); every market under those events is returned, `taker_volume` descending, with `taker_volume_total` their sum. A list spans events. Unlike the feeds this is not paginated; `data` is the object with no `pagination`. Unparseable ids are ignored; a request whose ids are *all* unparseable is a 400 rather than an empty 200, so a typo cannot read as "no volume". Ids are sorted and deduplicated before the lookup, so `?event_id=20,10` and `?event_id=10,20` are the same request and share a cache entry. At most 20 distinct event ids per request, the same selector ceiling the `condition=` lists carry: every named event contributes all of its markets to a single aggregation, so the list is what sizes the request. # Get market by id Source: https://docs.polymarket.com/api-reference/markets/get-market-by-id /api-spec/gamma-openapi.yaml get /markets/{id} # Get market by slug Source: https://docs.polymarket.com/api-reference/markets/get-market-by-slug /api-spec/gamma-openapi.yaml get /markets/slug/{slug} # Get market by token Source: https://docs.polymarket.com/api-reference/markets/get-market-by-token /api-spec/clob-openapi.yaml get /markets-by-token/{token_id} Returns the parent market for a given token ID. Useful when you have a token ID and need to resolve its parent market without knowing the condition ID in advance. # Get market tags by id Source: https://docs.polymarket.com/api-reference/markets/get-market-tags-by-id /api-spec/gamma-openapi.yaml get /markets/{id}/tags # Get open interest Source: https://docs.polymarket.com/api-reference/markets/get-open-interest https://data-api.polymarket.com/v2/openapi.json get /v2/oi Priced gross open interest per market. Pass `?condition=` as a comma-separated list of condition ids (aliases `condition_id` / `conditionId`, matching the feeds); omit it for the single global figure (`condition_id = "GLOBAL"`, still a one-element array). Every requested id that resolves to a servable market (indexed, active, not archived; any id family) returns a row, with `value: 0` when nothing is held; an id absent from `data` did not resolve to a servable market. A malformed id is a `400` naming the value, so absence carries that one meaning and nothing else. Unlike the feeds this is not paginated; `data` is the row array with no `pagination`. # Get prices history Source: https://docs.polymarket.com/api-reference/markets/get-prices-history /api-spec/clob-openapi.yaml get /prices-history Retrieve historical price data for a market. # Get resolution state Source: https://docs.polymarket.com/api-reference/markets/get-resolution-state https://data-api.polymarket.com/v2/openapi.json get /v2/resolutions Complete resolution state by one selector family. Supply exactly one of `question_id`, `condition`, or `event_id`. Condition and event selectors accept comma-separated values and return condition-grain rows in deterministic order, preferring native V2 lifecycle, then UMA lifecycle, then terminal CTF state. Misses return `{ "data": [] }`. # Get sampling markets Source: https://docs.polymarket.com/api-reference/markets/get-sampling-markets /api-spec/clob-openapi.yaml get /sampling-markets # Get sampling simplified markets Source: https://docs.polymarket.com/api-reference/markets/get-sampling-simplified-markets /api-spec/clob-openapi.yaml get /sampling-simplified-markets # Get simplified markets Source: https://docs.polymarket.com/api-reference/markets/get-simplified-markets /api-spec/clob-openapi.yaml get /simplified-markets # List a market's top holders Source: https://docs.polymarket.com/api-reference/markets/list-a-markets-top-holders https://data-api.polymarket.com/v2/openapi.json get /v2/holders Top holders of a market, netted per user and grouped by outcome token. `?condition=` (CSV of `condition_id`) is required (400 otherwise). `?limit=` (default 100, max 1000; v2 family-uniform) sizes the page **per outcome token**; `?min_balance=` filters the served amount. `?include_pnl=true` opts each holder row into the position economics (entry price and cost, current price and value, realized, unrealized and total profit) and switches the amounts to per-side gross balances, so a wallet holding both outcomes appears under both tokens. The default response is unchanged. This mode serves one market's table at a time: exactly one `condition` and `limit` at most 100 (400 otherwise, including via a cursor that carries a wider window). A malformed condition id is a `400` naming the value; a well-formed one that resolves to no holdings serves an empty `data` array, which is the meaningful zero-state. Deeper pages come only from `?cursor=` (which carries the page window and overrides `limit`). Page walks advance every token group together, so a group leaves `data` once its token is exhausted while others keep paging; no rows are lost, but merge pages by `token_id`, not by array position. # List markets Source: https://docs.polymarket.com/api-reference/markets/list-markets /api-spec/gamma-openapi.yaml get /markets # List markets (keyset pagination) Source: https://docs.polymarket.com/api-reference/markets/list-markets-keyset-pagination /api-spec/gamma-openapi.yaml get /markets/keyset Returns markets using cursor-based (keyset) pagination for stable, efficient paging through large result sets. Use `next_cursor` from each response as `after_cursor` in the next request. The `offset` parameter is explicitly rejected; use `after_cursor` instead. # Look up tokens Source: https://docs.polymarket.com/api-reference/markets/look-up-tokens https://data-api.polymarket.com/v2/openapi.json get /v2/tokens Resolves token ids, or the tokens of conditions, to their condition, module, outcome, market, event and neg-risk question index in one call. Exactly one selector per request. `?token_id=`: a comma-separated list of up to 50 decimal token ids (alias `token_ids`); elements are trimmed, leading zeros stripped and duplicates collapsed to their first position. `data` holds one row per known id in request order; an unknown id is simply absent (never a `404`), and an all-unknown request returns an empty array. `?condition=`: a comma-separated list of up to 10 condition selectors (aliases `condition_id`, `conditionId`), each `0x` plus 62 or 64 hex digits, lower-cased and deduplicated. A ConditionalTokens condition id returns the market's tokens (for a market carried over to polymarket-v2, its whole family: the ConditionalTokens pair, then the polymarket-v2 pair); a neg-risk market id returns every market of the structure; a polymarket-v2 condition id (the value a combo leg carries as `leg_condition_id`) returns that condition only; the 66-character condition id of a native polymarket-v2 market returns that market; the on-chain event id of a polymarket-v2 neg-risk structure returns every question of it. `data` holds the rows grouped by selector in request order, then by question index, market, module and outcome slot; an unknown value contributes nothing. A malformed value, more values than the cap, both selectors or neither is a `400`. `condition_id` is the market's condition id in its 66-character form, the value the other routes carry; `structural_condition_id` is the on-chain polymarket-v2 condition id in the same 66-character form, filled on every polymarket-v2 token, null on `v1_ctf`, and accepted back as a `condition` selector. `module` names the contract family: `v1_ctf` is the ConditionalTokens market (module 0) and every other value is a polymarket-v2 module. Reference fields never change; `closed`, `resolved`, `final_price` and `outcome` may lag by up to a minute. Not paginated: `data` is the row array with no `pagination`. # Get public profile by wallet address Source: https://docs.polymarket.com/api-reference/profiles/get-public-profile-by-wallet-address /api-spec/gamma-openapi.yaml get /public-profile # Get current rebated fees for a maker Source: https://docs.polymarket.com/api-reference/rebates/get-current-rebated-fees-for-a-maker /api-spec/clob-openapi.yaml get /rebates/current Returns the current rebated fees for a maker address on a given date. Returns null when the maker has no rebated-fee rows. Each entry includes the condition ID, asset address, and the USDC amount rebated. This endpoint does not require authentication. # Get a transaction by ID Source: https://docs.polymarket.com/api-reference/relayer/get-a-transaction-by-id /api-spec/relayer-openapi.yaml get /transaction Gets a transaction submitted to the Relayer. Takes in a required transaction ID as a query parameter. Poll this endpoint with the `transactionID` returned from `POST /submit` to retrieve the onchain `transactionHash` once the transaction has been broadcast. # Get current nonce for a user Source: https://docs.polymarket.com/api-reference/relayer/get-current-nonce-for-a-user /api-spec/relayer-openapi.yaml get /nonce Gets the current Proxy or Safe nonce for a user. Takes in the user's signer address and the type of nonce to retrieve. # Get recent transactions for a user Source: https://docs.polymarket.com/api-reference/relayer/get-recent-transactions-for-a-user /api-spec/relayer-openapi.yaml get /transactions Gets the most recent transactions submitted to the Relayer, owned by a specific user. Authenticated using Builder API Keys or Relayer API Keys. **Builder API Key auth headers:** - `POLY_BUILDER_API_KEY` - `POLY_BUILDER_TIMESTAMP` - `POLY_BUILDER_PASSPHRASE` - `POLY_BUILDER_SIGNATURE` **Relayer API Key auth headers:** - `RELAYER_API_KEY` - `RELAYER_API_KEY_ADDRESS` # Submit a transaction Source: https://docs.polymarket.com/api-reference/relayer/submit-a-transaction /api-spec/relayer-openapi.yaml post /submit Submit a transaction request to the Relayer. Authenticated using Builder API Keys or Relayer API Keys. Returns immediately with the `transactionID` and a `state` of `STATE_NEW`. The onchain transaction hash is **not** included in this response — poll `GET /transaction` with the returned `transactionID` to retrieve the `transactionHash` once the transaction has been broadcast. **Builder API Key auth headers:** - `POLY_BUILDER_API_KEY` - `POLY_BUILDER_TIMESTAMP` - `POLY_BUILDER_PASSPHRASE` - `POLY_BUILDER_SIGNATURE` **Relayer API Key auth headers:** - `RELAYER_API_KEY` - `RELAYER_API_KEY_ADDRESS` # Get current active rewards configurations Source: https://docs.polymarket.com/api-reference/rewards/get-current-active-rewards-configurations /api-spec/clob-openapi.yaml get /rewards/markets/current Returns all current active rewards configurations grouped by market. When `sponsored=true`, returns sponsored reward configurations instead. Results are paginated (500 items per page). Use next_cursor to fetch subsequent pages. A next_cursor value of "LTE=" indicates the last page. # Get earnings for user by date Source: https://docs.polymarket.com/api-reference/rewards/get-earnings-for-user-by-date /api-spec/clob-openapi.yaml get /rewards/user Returns an array of user earnings per market for a provided day. Requires CLOB L2 Auth headers. Results are paginated (100 items per page). Use next_cursor to fetch subsequent pages. A next_cursor value of "LTE=" indicates the last page. # Get multiple markets with rewards Source: https://docs.polymarket.com/api-reference/rewards/get-multiple-markets-with-rewards /api-spec/clob-openapi.yaml get /rewards/markets/multi Returns a list of active markets with their reward configurations. Supports text search, tag filtering, numeric filters, and sorting. Results are paginated (100 items per page by default). Use next_cursor to fetch subsequent pages. A next_cursor value of "LTE=" indicates the last page. # Get raw rewards for a specific market Source: https://docs.polymarket.com/api-reference/rewards/get-raw-rewards-for-a-specific-market /api-spec/clob-openapi.yaml get /rewards/markets/{condition_id} Returns an array of present and future rewards configured on a market. When `sponsored=true`, sponsored daily rates are folded into each config's `rate_per_day` . Results are paginated (100 items per page). Use next_cursor to fetch subsequent pages. A next_cursor value of "LTE=" indicates the last page. # Get reward percentages for user Source: https://docs.polymarket.com/api-reference/rewards/get-reward-percentages-for-user /api-spec/clob-openapi.yaml get /rewards/user/percentages Returns the real-time percentages of rewards that a user is earning per market. The response is a map of condition_id to the percentage of total rewards the user is currently earning in that market. Requires CLOB L2 Auth headers. # Get total earnings for user by date Source: https://docs.polymarket.com/api-reference/rewards/get-total-earnings-for-user-by-date /api-spec/clob-openapi.yaml get /rewards/user/total Returns the summed total rewards earnings for a user on a provided day, grouped by asset address. Requires CLOB L2 Auth headers. # Get user earnings and markets configuration Source: https://docs.polymarket.com/api-reference/rewards/get-user-earnings-and-markets-configuration /api-spec/clob-openapi.yaml get /rewards/user/markets Returns an array of current rewards including user earnings and live percentages per market for a provided day. Results are paginated (100 items per page by default, max 500). Use next_cursor to fetch subsequent pages. A next_cursor value of "LTE=" indicates the last page. Requires CLOB L2 Auth headers. Optional features: - Search by question/description using the `q` parameter - Filter by tag slugs using `tag_slug` parameter (multiple values are OR'ed) - Filter by favorite markets using `favorite_markets=true` - Sort by various fields using `order_by` and `position` parameters # Search markets, events, and profiles Source: https://docs.polymarket.com/api-reference/search/search-markets-events-and-profiles /api-spec/gamma-openapi.yaml get /public-search # Get series by id Source: https://docs.polymarket.com/api-reference/series/get-series-by-id /api-spec/gamma-openapi.yaml get /series/{id} # List series Source: https://docs.polymarket.com/api-reference/series/list-series /api-spec/gamma-openapi.yaml get /series # Get data freshness Source: https://docs.polymarket.com/api-reference/service/get-data-freshness https://data-api.polymarket.com/v2/openapi.json get /v2/status How fresh the data behind this API is. `/readyz` answers whether this pod can reach its datastore; this answers how far behind chain head what you are reading is. Two halves, because each is blind exactly where the other sees: * `serving`; the projections that turn ingested rows into what the feeds read (`activity_feed` enrichment, `custody_balances` ingestion, the PnL engine). Each carries its own clock, so this is the only half that can see "everything stopped". `lag_seconds` is the worst age across them and `worst` names which one, so a single stalled projection cannot hide behind two healthy ones. * `ingestion`; one crawl cursor per `(contract, event)`, summarised as the tail, the furthest-behind block, and the worst few cursors BY NAME. Every reading here is relative or positional, so under a total stall it reads green; that is why `serving` exists alongside it. Streams that are dormant by design are dropped from `ingestion` rather than reported, because they sit arbitrarily far back forever and would otherwise fill the list and push the stream you care about off it. Takes no parameters and is not paginated. Served from a snapshot refreshed in the background, never computed on the request: `computed_at` and `age_seconds` say how old it is, so a stalled refresher or a datastore outage shows up as a growing age rather than a 500. Before the first refresh lands there is nothing to serve and this answers `503`; "not measured yet" and "measured, no lag" are different claims. # Get sports metadata information Source: https://docs.polymarket.com/api-reference/sports/get-sports-metadata-information /api-spec/gamma-openapi.yaml get /sports # Get valid sports market types Source: https://docs.polymarket.com/api-reference/sports/get-valid-sports-market-types /api-spec/gamma-openapi.yaml get /sports/market-types # List teams Source: https://docs.polymarket.com/api-reference/sports/list-teams /api-spec/gamma-openapi.yaml get /teams # Get related tags (relationships) by tag id Source: https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id /api-spec/gamma-openapi.yaml get /tags/{id}/related-tags # Get related tags (relationships) by tag slug Source: https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-slug /api-spec/gamma-openapi.yaml get /tags/slug/{slug}/related-tags # Get tag by id Source: https://docs.polymarket.com/api-reference/tags/get-tag-by-id /api-spec/gamma-openapi.yaml get /tags/{id} # Get tag by slug Source: https://docs.polymarket.com/api-reference/tags/get-tag-by-slug /api-spec/gamma-openapi.yaml get /tags/slug/{slug} # Get tags related to a tag id Source: https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id /api-spec/gamma-openapi.yaml get /tags/{id}/related-tags/tags # Get tags related to a tag slug Source: https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-slug /api-spec/gamma-openapi.yaml get /tags/slug/{slug}/related-tags/tags # List tags Source: https://docs.polymarket.com/api-reference/tags/list-tags /api-spec/gamma-openapi.yaml get /tags # Cancel all orders Source: https://docs.polymarket.com/api-reference/trade/cancel-all-orders /api-spec/clob-openapi.yaml delete /cancel-all Cancels all open orders for the authenticated user. Works even in cancel-only mode. # Cancel multiple orders Source: https://docs.polymarket.com/api-reference/trade/cancel-multiple-orders /api-spec/clob-openapi.yaml delete /orders Cancels multiple orders by their IDs. Maximum 1000 orders per request. Duplicate order IDs in the request are automatically ignored. Works even in cancel-only mode. # Cancel orders for a market Source: https://docs.polymarket.com/api-reference/trade/cancel-orders-for-a-market /api-spec/clob-openapi.yaml delete /cancel-market-orders Cancels all open orders for the authenticated user in a specific market (condition) and asset. Works even in cancel-only mode. # Cancel single order Source: https://docs.polymarket.com/api-reference/trade/cancel-single-order /api-spec/clob-openapi.yaml delete /order Cancels a single order by its ID. Works even in cancel-only mode. # Cancel wallet orders Source: https://docs.polymarket.com/api-reference/trade/cancel-wallet-orders /api-spec/clob-openapi.yaml delete /cancel-wallet-orders Cancels orders on the deposit wallet across all API keys, including orders from expired session signers. Also served at `/v1/gateway/cancel-wallet-orders`. Only the wallet owner can call this endpoint. Send L2 headers with `POLY_ADDRESS` set to the owner EOA and the owner's API key. Session signers receive 403 and must use `DELETE /order`, `DELETE /orders` or `DELETE /cancel-all`, which only cancel orders placed with their own API key. Set exactly one of `order_ids` or `all`. Unknown orders, orders from another maker, and already canceled orders are returned in `not_canceled` with the reason `order not found on the caller's deposit wallet`. Shares the cancel rate-limit bucket with `DELETE /orders` and `DELETE /cancel-all`. With `order_ids`, each ID costs one token up front. With `all`, the request costs one token up front and is then charged for the number of orders actually canceled. Revoking a session signer immediately triggers the relayer to cancel its open orders. After cancellation, canceling those IDs returns them in `not_canceled`. Authorization and revocation changes can take up to about 5 seconds to appear here. Production rollout: this route currently returns an nginx 404 page until load-balancer routing is enabled. The production feature flag must also be enabled. A disabled application endpoint returns a JSON 404 response instead. # Get builder trades Source: https://docs.polymarket.com/api-reference/trade/get-builder-trades /api-spec/clob-openapi.yaml get /builder/trades Retrieves trades attributed to a builder code. # Get order scoring status Source: https://docs.polymarket.com/api-reference/trade/get-order-scoring-status /api-spec/clob-openapi.yaml get /order-scoring Checks if a specific order is currently scoring for rewards. An order is considered "scoring" if it meets all the criteria for earning maker rewards: - The order is live on a rewards-eligible market - The order meets the minimum size requirements - The order is within the valid spread range - The order has been live for the required duration # Get single order by ID Source: https://docs.polymarket.com/api-reference/trade/get-single-order-by-id /api-spec/clob-openapi.yaml get /data/order/{orderID} Retrieves a specific order by its ID (order hash) for the authenticated user, including canceled or fully matched orders. Builder-authenticated clients can also use this endpoint to retrieve orders attributed to their builder account. # Get trades Source: https://docs.polymarket.com/api-reference/trade/get-trades /api-spec/clob-openapi.yaml get /data/trades Retrieves trades for the authenticated user. Returns paginated results. Requires readonly or level 2 API key authentication. # Get user orders Source: https://docs.polymarket.com/api-reference/trade/get-user-orders /api-spec/clob-openapi.yaml get /data/orders Retrieves live orders for the authenticated user. Returns paginated results. When filtering by asset_id, also include the market condition ID in market. From December 14, 2026, asset-only requests return HTTP 400 (asset_id requires market). Unfiltered and market-only queries remain supported. Filtering by id returns that order regardless of status, including canceled or fully matched orders. Builder-authenticated clients can also use this endpoint to retrieve orders attributed to their builder account. > [!WARNING] > > Filtering by `id` only returns canceled and fully matched orders within the last hour. > Listen to the [user stream](/trading/realtime-order-updates#user-stream) for fuller data. > Historical fills remain in [get trades](/api-reference/trade/get-trades). # Get wallet open orders Source: https://docs.polymarket.com/api-reference/trade/get-wallet-open-orders /api-spec/clob-openapi.yaml get /data/wallet-open-orders Lists every live order on the caller's deposit wallet, regardless of which signer or API key placed it. Authenticate with L2 headers or `POLY_READONLY_API_KEY` and `POLY_ADDRESS`. `POLY_ADDRESS` must be the wallet owner or one of its non-revoked session signers. Results are newest first, in pages of about 500. A page can be short or empty while `next_cursor` is still set. Keep paging with `cursor` until `next_cursor` is empty. A deposit wallet supports at most 15 non-revoked session signers. Expired signers count toward this limit; revoke them to free a slot. Authorizing or revoking a signer can take up to about 5 seconds to appear in this endpoint and wallet-wide cancellation. Revoking a signer immediately triggers cancellation of all its open orders by the relayer; those orders no longer appear here after cancellation. # Post a new order Source: https://docs.polymarket.com/api-reference/trade/post-a-new-order /api-spec/clob-openapi.yaml post /order Creates a new order in the order book. When placing an order as a session signer, use the deposit wallet as both `maker` and `signer`, with the POLY_1271 signature wrapped in a session-signer envelope. # Post multiple orders Source: https://docs.polymarket.com/api-reference/trade/post-multiple-orders /api-spec/clob-openapi.yaml post /orders Creates multiple new orders in the order book. Orders are processed in parallel. Maximum 15 orders per request. # Send heartbeat Source: https://docs.polymarket.com/api-reference/trade/send-heartbeat /api-spec/clob-openapi.yaml post /heartbeats Sends one legacy order heartbeat for the authenticated API key. The first accepted send enables timeout cancellation for all open orders owned by that API key, across markets and processes. Keep sending accepted heartbeats every 5 seconds. No scheduler or disarm operation is provided; stopping sends or closing a client leaves the deadline active. It shares the key's registration with POST /v1/heartbeats and resets the expected modern heartbeat ID to an empty string. After 10 seconds without an accepted send, a five-second scan removes the registration and queues a best-effort cancel-all attempt. Cancellation timing and success are not guaranteed. Later accepted sends register again. A lost response may follow an accepted send. WebSocket keepalive does not refresh this deadline. Stop placing orders and explicitly cancel/verify orders you intend to remove before shutdown. # CLOB Trading Rate Limits Source: https://docs.polymarket.com/api-reference/trading-rate-limits Per-signer token-bucket limits for CLOB order and cancellation requests Polymarket evaluates CLOB order and cancellation requests against separate token buckets for each signer address. The signer address is the address associated with your CLOB API credentials. Activity in one bucket does not consume capacity from the other. > [!WARNING] > > Beginning July 24, 2026, the limiter will run in warning mode for two weeks. > Requests will continue to be processed during this period. A request that > would be rejected after live enforcement begins will include > `Poly-RateLimit-Warning: true`. Monitor this header and adjust your request > patterns before live enforcement begins. Polymarket will announce when live > enforcement begins. > [!NOTE] > > These per-signer limits are separate from the existing [Cloudflare IP-based > limits](/api-reference/rate-limits), which remain unchanged. ## How Rate Limits Work Each signer has an order bucket and a cancel bucket: | Bucket | Request | Token Cost | | - | - | - | | Order | `POST /order` | 1 | | Order | `POST /orders` | Number of orders in a non-empty batch | | Cancel | `DELETE /order` | 1 | | Cancel | `DELETE /orders` | Number of submitted order IDs | | Cancel | `DELETE /cancel-all` | 1 plus the number of orders canceled | | Cancel | `DELETE /cancel-market-orders` | 1 plus the number of matching orders canceled | ### Refill and Burst Capacity Tokens refill continuously at the rate assigned to the current tier. Burst capacity is the maximum number of tokens a bucket can hold. A full bucket can spend up to that capacity immediately; after the burst is consumed, new tokens become available at the refill rate. Calculate the duration of a full burst as: ```text theme={null} burst_seconds = burst / rate_per_sec ``` ### Batch Requests Under live enforcement, a batch is admitted only when the bucket contains enough tokens for every entry. Otherwise, the entire request is rejected and no entries are processed. This all-or-nothing rule applies to the rate-limit check; an admitted batch retains its normal per-order response behavior. A batch whose token cost exceeds the tier's burst capacity can never be admitted as one request. Split it into smaller batches. ### Cancel All and Cancel Market Orders The number of orders that will be canceled is not known when `DELETE /cancel-all` or `DELETE /cancel-market-orders` begins. Each request first consumes one cancel token. After the cancellation result is known, the bucket is debited one additional token for every order successfully canceled. For tiers that allow a negative cancel balance, this second debit can put the bucket into debt. Future cancel requests remain blocked until the bucket has enough tokens for the next request. Other tiers floor the post-cancel balance at zero regardless of debit size. ## Volume Tiers Buckets are scoped to the signer address. Tier eligibility follows the cumulative trading volume of the maker wallet, even when it differs from the signer address. The volume window is currently 30 days, and tier assignments refresh every three hours. | Tier | 30-Day Volume | Order Rate (tokens/s) | Order Burst (tokens) | Cancel Rate (tokens/s) | Cancel Burst (tokens) | Negative Cancel Balance | | - | -: | -: | -: | -: | -: | :-: | | Standard | — | 40 | 60 | 80 | 120 | Yes | | Copper | \$30,000+ | 60 | 90 | 120 | 180 | Yes | | Bronze | \$50,000+ | 80 | 120 | 160 | 240 | Yes | | Silver | \$100,000+ | 200 | 300 | 400 | 600 | Yes | | Gold | \$500,000+ | 400 | 600 | 800 | 1,200 | Yes | | Platinum | \$2.5M+ | 450 | 675 | 900 | 1,350 | No | | Diamond | \$5M+ | 525 | 787 | 1,050 | 1,575 | No | | Elite | \$10M+ | 600 | 900 | 1,200 | 1,800 | No | Tier thresholds, the volume window, and rate limits may change as the system is tuned. Polymarket will provide advance notice of significant changes. ### Check Your Tier Call [`GET /v1/user/rate-limit-tier`](/api-reference/account/get-rate-limit-tier) to read the tier currently assigned to your signer. ## Response Headers Responses include the following headers when the limiter successfully evaluates a covered request: | Header | Description | | - | - | | `Poly-RateLimit-Remaining` | Current token balance for the applicable bucket after rate-limit accounting | | `Poly-RateLimit-Reset` | Unix timestamp when the current rate-limit wait period ends | | `Poly-RateLimit-Tier` | Rate-limit tier applied to the request | The following headers appear only in specific cases: | Header | Description | | - | - | | `Retry-After` | Retry delay in seconds; included on `429` responses | | `Poly-RateLimit-Warning` | `true` in warning mode when live enforcement would have rejected the request | `Poly-RateLimit-Reset` is not the time when the bucket will be completely full. On a `429` response for a request whose token cost fits within burst capacity, it indicates when enough tokens are expected for the attempted request. On an admitted request, it may be the current timestamp. `Poly-RateLimit-Remaining` can be negative after `DELETE /cancel-all` or `DELETE /cancel-market-orders` for tiers that allow a negative cancel balance. Before sending a large batch, compare its token cost with the remaining balance. ## Handle 429 Responses After live enforcement begins, a request that requires more tokens than the applicable bucket contains returns `429 Too Many Requests`. For a request whose token cost is within the tier's burst capacity, `Retry-After` gives the minimum delay before retrying. You do not need to wait for the bucket to refill completely. If the request costs more than the burst capacity, split it into smaller requests instead of retrying it unchanged. ## Get Help Contact [support@polymarket.com](mailto:support@polymarket.com) if you have questions about your tier, believe your wallet qualifies for a higher tier, recently moved trading activity to a new address, or believe you are being limited incorrectly. # Get a user's PnL series Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-pnl-series https://data-api.polymarket.com/v2/openapi.json get /v2/user-pnl Complete cumulative native-PnL atoms and compositions. # Get a user's profile stats Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-profile-stats https://data-api.polymarket.com/v2/openapi.json get /v2/user-stats The profile card for one wallet in a single call. `?user=` is required. Returns `{ data: { trades, biggest_win, views, join_date, all_time_pnl } }`, or `{ data: null }` when the wallet is not a known user. **`data: null` and a row of zeros mean different things.** `null` is "no such user"; zeros are "this user exists but has never traded, never won and has no profile views". `trades` counts DISTINCT MARKETS traded, not individual trades. It is exact, not estimated. `biggest_win` is the best single **resolved** position win in USDC, market and combo arms unified, and `0` when the wallet has no win over $1. `join_date` is epoch seconds, or `null` when unknown. `all_time_pnl` is the newest persisted cumulative `/v2/user-pnl` point at its actual observation timestamp. It is `null` when the user exists but no observation has been published yet. For the composition card: trading realized is `realized_market_pnl + realized_combo_pnl`; LP realized is `realized_lp_pnl`; rebates, yield, rewards, referral, and fees paid map to their same-named fields (`fees_paid` is refunds minus charges). `volume`, `volume_usdc`, and `trade_count` are cumulative maker-attributed canonical fill metrics. Not paginated: one row by construction, so `data` is the bare object with no `pagination`; the `/v2/value` shape. # Get a user's trading volume Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume https://data-api.polymarket.com/v2/openapi.json get /v2/user-volume One wallet's trading volume over a window, in both units side by side. `?user=` is required. `?start=` / `?end=` are epoch seconds, inclusive and optional: omitted or `0` disables a bound (full history). Volume is tracked in whole UTC days, so each bound is floored to its UTC day; the served window is the smallest whole-day window containing `[start, end]`. Returns `{ data: { volume, volume_usdc, trade_count } }`; exactly one row by construction (the view aggregates with no GROUP BY), zeros for a wallet with no trades in the window. An inverted window is zeros too, not an error. `volume` is both-sides SHARES; `volume_usdc` is the same measure in USD; the endpoint that shows the unit convention side by side: the bare name is the natural unit, `_usdc` is the denomination, the same pairing as `current_size` / `entry_cost_usdc` on `/v2/positions`. # Get portfolio value Source: https://docs.polymarket.com/api-reference/wallet/get-portfolio-value https://data-api.polymarket.com/v2/openapi.json get /v2/value The user's portfolio value: single-market holdings marked to market plus unresolved combo positions at cost basis. `?user=` is required (400 otherwise). `?condition=` (CSV of `condition_id`) scopes the single-market term, and any condition filter excludes the portfolio-level combo term. `data` is a single object; a user with no positions yields `{ "data": { "proxy_wallet": …, "value": 0 } }`. # Get wallet approvals Source: https://docs.polymarket.com/api-reference/wallet/get-wallet-approvals https://data-api.polymarket.com/v2/openapi.json get /v2/approvals Polygon token/operator approval state for one wallet. `?user=` must be an EVM address. The complete served catalog is returned in canonical order under `{ data }`; this endpoint is not paginated. # List positions for a user or market Source: https://docs.polymarket.com/api-reference/wallet/list-positions-for-a-user-or-market https://data-api.polymarket.com/v2/openapi.json get /v2/positions A keyset page of positions in the standard `{ data, pagination }` envelope. One route serves a user's open book, their closed book (`status=CLOSED`), and a market's holders (market anchor). At least one of `user`/`condition` is required. Supplying both anchors on the user and applies `condition` as a narrowing filter. `status` defaults to `OPEN`, which is the **superset**: a settled-but-unredeemed winner still holds its tokens, so it is an open position whose condition resolved. `REDEEMABLE` narrows to that subset, and each row echoes its own `status`. Resume contract: a `next_cursor` binds the `status`/`sortBy`/`sortDirection` the walk started with. To follow it, send `cursor` together with the same `user` or `condition` anchor used on the first page; a bare `?cursor=` request returns 400. The token is the authority on the spine and the total order, and the handler adopts all three from it. Restating them is allowed and must agree; **explicitly** contradicting one is a 400, because replaying an anchor under a different spine or order would silently walk a different result set. Omitting them is not a contradiction; a defaulted `status` is the absence of a choice, not a request for `OPEN`. User CLOSED residual sorts bind their realized-PnL ranking in the signed cursor kind. Earlier cursors for those sorts return 400 and require restarting pagination without `cursor`, because their numeric anchor has ambiguous units. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # Apply Referral Code Source: https://docs.polymarket.com/api-reference/apply-referral-code /api-spec/perps-openapi.json post /v1/account/referral Apply a referral code to the authenticated account after signup. Accounts can only apply a referral code if they do not already have one. Request Weight: **1** # Approve or revoke builder fees with an account owner signature Source: https://docs.polymarket.com/api-reference/approve-or-revoke-builder-fees-with-an-account-owner-signature /api-spec/perps-openapi.json post /v1/account/builder-approvals # Create bridge addresses Source: https://docs.polymarket.com/api-reference/bridge/create-bridge-addresses /api-spec/bridge-openapi.yaml post /deposit # Create withdrawal addresses Source: https://docs.polymarket.com/api-reference/bridge/create-withdrawal-addresses /api-spec/bridge-openapi.yaml post /withdraw # Get a quote Source: https://docs.polymarket.com/api-reference/bridge/get-a-quote /api-spec/bridge-openapi.yaml post /quote # Get supported assets Source: https://docs.polymarket.com/api-reference/bridge/get-supported-assets /api-spec/bridge-openapi.yaml get /supported-assets # Get transaction status Source: https://docs.polymarket.com/api-reference/bridge/get-transaction-status /api-spec/bridge-openapi.yaml get /status/{address} Returns the deposits and withdrawals seen at a bridge address, newest first. Responses are cursor-paginated: each request returns one page plus a `nextCursor`. To read the full history, pass each `nextCursor` back as `cursor` until it comes back null. To track only recent activity, keep requesting the first page without a cursor. # Cancel All Orders Source: https://docs.polymarket.com/api-reference/cancel-all-orders /api-spec/perps-openapi.json delete /v1/trade/orders/all Cancel all open orders for the authenticated account on one instrument. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1**Action Weight: **0** # Cancel Orders Source: https://docs.polymarket.com/api-reference/cancel-orders /api-spec/perps-openapi.json delete /v1/trade/orders Cancel orders. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1 + floor(n / 20)**Action Weight: **0** # Cancel Orders COID Source: https://docs.polymarket.com/api-reference/cancel-orders-coid /api-spec/perps-openapi.json delete /v1/trade/orders-coid Cancel orders by client order ID. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1 + floor(n / 20)**Action Weight: **0** # Check Invite Code Source: https://docs.polymarket.com/api-reference/check-invite-code /api-spec/perps-openapi.json get /v1/info/invite Check whether an invite code can be used. When `address` is provided, the response is invalid if that address already has an account. Request Weight: **1** # Get combo markets Source: https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets /api-spec/combos-rfq-openapi.yaml get /v1/rfq/combo-markets Returns active markets that can be used as combo legs, ordered by volume descending. This endpoint is public and does not require CLOB authentication. Entries in `position_ids`, `outcomes`, and `outcome_prices` correspond by array index (`[0]` is YES, `[1]` is NO). Use `next_cursor` unchanged in the next request; a value of `null` indicates the final page. # Create Account Invite Source: https://docs.polymarket.com/api-reference/create-account-invite /api-spec/perps-openapi.json post /v1/account/invite Create or return the authenticated account's primary invite code. The call is idempotent for accounts that already have a primary invite code. Request Weight: **1** # Create Orders Source: https://docs.polymarket.com/api-reference/create-orders /api-spec/perps-openapi.json post /v1/trade/orders Create new orders. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1 + floor(n / 20)**Action Weight: **1 / order** # Create Proxy Source: https://docs.polymarket.com/api-reference/create-proxy /api-spec/perps-openapi.json post /v1/account/proxy Create a new proxy to sign orders. Returns an API secret for private account access. Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). Request Weight: **1** # Data API v2 Source: https://docs.polymarket.com/api-reference/data-api/overview Read wallet portfolios, trade and activity feeds, market state, and ranked leaderboards through one consistent response contract. The Data API answers what happened and who holds what: wallet portfolios and PnL, trade and activity feeds, per-market state such as holders and open interest, and ranked boards. Version 2 serves every read behind one contract, a shared response envelope, cursor pagination, and a unified identifier vocabulary, so a client written against one endpoint already knows how to consume the rest. All v2 routes are served from: ``` https://data-api.polymarket.com/v2 ``` No API key or authentication is required. ## Make a First Request Fetch a wallet's current positions: ```bash theme={null} curl "https://data-api.polymarket.com/v2/positions?user=0x983eedfbd75803602e4a6e6ea9aab6dc6b9c6748&limit=1" ``` Every response wraps its payload in `data`; paginated routes add a `pagination` object (row fields trimmed here for brevity): ```json theme={null} { "data": [ { "proxy_wallet": "0x983eedfbd75803602e4a6e6ea9aab6dc6b9c6748", "condition_id": "0xd9b06e2fd9ddb7ab61c9e3d5d8e074c555802478bbf75145804ff709a4246f79", "token_id": "31974447302330162086995746309500877260929998201718217388109724292047967921664", "outcome": "Yes", "title": "Will ŠK Slovan Bratislava win on 2026-08-19?", "status": "REDEEMABLE", "current_size": 86780.64, "avg_price": 0.5203, "entry_cost_usdc": 45159.4653, "current_value": 0.0, "realized_pnl": -1082.5533, "unrealized_pnl": -45159.4653 } ], "pagination": { "limit": 1, "offset": 0, "has_more": true, "next_cursor": "eyJkYXRhIjp7InR5cGUiOiJwb3NpdGlvbnMi…" } } ``` A documented miss is `data: null` or an empty list, never an error. Each endpoint's reference page describes its full row shape and every filter. ## Paginate With Cursors Pagination is cursor-only; there is no `offset` query parameter. To walk a result set: 1. Send the first request with an optional `limit` (each endpoint documents its default and maximum). 2. Read `pagination.next_cursor` from the response and re-send the request with `cursor=`. 3. Stop when `next_cursor` is `null`. `has_more` is exact, so an empty or short page does not mean the walk is over. Cursors are opaque, signed, and typed per endpoint. Two rules keep a walk consistent: * On the feeds (`/v2/trades`, `/v2/activity`, `/v2/activity/combos`), re-send the same filters on every page. The cursor carries only its seek anchor, so changing a filter mid-walk silently re-anchors the feed. * Where a cursor binds its query (positions, boards, combo positions), restating the same values is fine, but contradicting them returns a `400`. On `/v2/positions`, keep sending the same `user` or `condition` anchor and all filters, including `title`, any narrowing `condition`, and `start`/`end`. These filters are not carried by the cursor; omitting them can broaden the result set. The cursor binds the anchor, status, sort, and direction. On `/v2/positions/combos`, keep sending `user` alongside the cursor. On `/v2/holders`, keep sending `condition`. Other routes that bind the query can resume with the bare cursor. The `limit` parameter only applies to the first page; once a `cursor` is supplied, the cursor's own page size wins. The `offset` field in `pagination` is display metadata for numbering rows across pages, not a request parameter. ## Shared Conventions Every v2 endpoint follows the same vocabulary and encoding rules. ### Identifiers | Identifier | Meaning | | - | - | | `condition` | The unified query key for on-chain condition ids (`0x`-prefixed, 64 hex chars). `condition_id` and `conditionId` are accepted aliases. Accepts up to 20 distinct comma-separated values where lists are allowed. | | `event_id` | An event id, as served by the Gamma API's `/events` routes. | | `market_id` | A market id, as served by the Gamma API's `/markets` routes. Carried in response rows next to the on-chain `condition_id`. | | `token_id` | An outcome token id. The key for `/v2/prices-history`. | Query parameters accept both `snake_case` and `camelCase` spellings. ### Units and Sentinels * Bare `volume` and `size` values are outcome **shares**; fields suffixed `_usdc` are USD amounts; volumes prefixed `taker_` count one side of each trade. * All amounts are JSON numbers. * `outcome_index: 999` means the outcome could not be labeled. * A missing or `null` numeric field means unavailable, never zero. ### Time Windows Windowed routes take `start` and `end` as epoch seconds. Treatment of an omitted or `0` bound differs by route (for example, `/v2/activity` floors an omitted `start` to three years back, while `/v2/prices-history` rejects a `0` bound with a `400`), so check the parameter documentation on each endpoint page before relying on a default. ### Price History Resolution and Availability `/v2/prices-history` serves each token from a graded store: a rolling raw window (one-minute serving) plus five-minute, thirty-minute, three-hour, and twelve-hour series. The coarse pair is **permanent**, so every token's full history is always available at twelve-hour grain (and at three-hour grain from July 2026 onward); the fine grains are windowed. The availability **minimums** are: raw at least 7 days, five-minute at least 60 days, thirty-minute at least 90 days. These are floors, not exact horizons: data expires in multi-day chunks, so a grain usually reaches a few days further back than its minimum. `bucket_seconds=60` over a window starting a month ago is therefore an incompatible pair: both values are valid, and there is no data at their intersection. The two ways of asking behave differently on purpose: * **Send `bucket_seconds`** and the request means exactly that grid: the response holds every stored observation snapped to it and nothing else. Over a range where the store has nothing at or below that grain the page is empty, and where the stored history is coarser than the grid the page is sparse. Both are correct answers, never a silent substitution at a different width. * **Omit it** and the server measures, per request, which series actually cover this token and window, and serves the densest one: sized to the span, then coarsened only as far as coverage requires. Clients should not build their own availability tables; coverage is discovered from the data on every request, and it extends as the store grows. Two consequences worth internalizing: * On a pinned request, `resolution_seconds` echoes the requested grid, not the density of what filled it. Counting rows is the only density measure. * Deep history predates the fine grains: before July 2026 the store's finest observations are three-hour or twelve-hour points, so a pinned fine bucket over old ranges returns those observations on your grid, sparsely. For a multi-day window, use `bucket_seconds` of 300, 1800, 10800, or 43200, or omit it. A 60-second width over several days is both slow and, past the raw window, empty. ### Errors and Rate Limits Request errors return a `400` with a message envelope: ```json theme={null} { "error": "required query param 'user' or 'condition' not provided" } ``` Heavy load answers with `429` and a `Retry-After` header; retry after the given delay. The IP-based request limits for `/v2` routes are listed on the [Rate Limits](/api-reference/rate-limits) page. ## Endpoints > [accordion] Wallet > > | Endpoint | Returns | > | - | - | > | `GET /v2/positions` | Positions for a user or market, across the whole lifecycle (`OPEN`, `REDEEMABLE`, `REDEEMABLE_LOST`, `MERGEABLE`, `CLOSED`) | > | `GET /v2/positions/combos` | Combo positions | > | `GET /v2/value` | Portfolio value | > | `GET /v2/approvals` | Wallet approvals | > | `GET /v2/user-pnl` | [A user's PnL series](/trading/wallet-activity#wallet-pnl-history) | > | `GET /v2/user-stats` | [A user's profile stats](/trading/wallet-activity#wallet-stats) | > | `GET /v2/user-volume` | [A user's trading volume](/trading/wallet-activity#wallet-trading-volume) | > [accordion] Feeds > > | Endpoint | Returns | > | - | - | > | `GET /v2/trades` | Trades for a wallet, market, event, or the global feed | > | `GET /v2/activity` | Account activity | > | `GET /v2/activity/combos` | Combo activity | > [accordion] Markets > > | Endpoint | Returns | > | - | - | > | `GET /v2/holders` | A market's top holders | > | `GET /v2/oi` | Open interest | > | `GET /v2/live-volume` | Live volume for an event | > | `GET /v2/prices-history` | A token's price history | > | `GET /v2/resolutions` | [Resolution state](/market-data/public-analytics#market-resolution) | > | `GET /v2/tokens` | [Token lookup](/market-data/public-analytics#token-lookup): token ids or conditions to markets, outcomes and neg-risk structure | > [accordion] Boards > > | Endpoint | Returns | > | - | - | > | `GET /v2/leaderboard` | The trader leaderboard | > | `GET /v2/biggest-winners` | [The biggest wins](/market-data/public-analytics#biggest-winners) | > | `GET /v2/builders/leaderboard` | The builders leaderboard | > | `GET /v2/builders/volume` | Builder volume over time | > [accordion] Service > > | Endpoint | Returns | > | - | - | > | `GET /v2/status` | Data freshness | The complete machine-readable contract is published at [`https://data-api.polymarket.com/v2/openapi.json`](https://data-api.polymarket.com/v2/openapi.json), with an interactive explorer at [`https://data-api.polymarket.com/v2/docs`](https://data-api.polymarket.com/v2/docs). ## Next Steps * Coming from the v1 Data API routes? See [Migrate from Data API v1 to v2](/migrate/data-api-v1-to-v2). * Browse the endpoint pages in the sidebar for full parameter and response documentation. # Delete Proxy Source: https://docs.polymarket.com/api-reference/delete-proxy /api-spec/perps-openapi.json delete /v1/account/proxy Delete a proxy by address. Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). Request Weight: **1** # List combo activity Source: https://docs.polymarket.com/api-reference/feeds/list-combo-activity https://data-api.polymarket.com/v2/openapi.json get /v2/activity/combos Keyset-paginated combo lifecycle + redemption feed for a user, in the standard `{ data, pagination }` envelope. Pass `?cursor=` from a prior response's `next_cursor` to fetch the next page. Unlike the activity feed, the anchor behind the cursor is `(block_number, log_index)`; this endpoint's total order. A malformed `condition` combo condition id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state. # Get Account Backstop Transfers Source: https://docs.polymarket.com/api-reference/get-account-backstop-transfers /api-spec/perps-openapi.json get /v1/account/backstops Get exact quote cash transfers for backstops of the authenticated account. Defaults to the last 90 days. Rows are ordered newest first. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Request Weight: **10** Cached 2s — a request served from cache costs **1** # Get Account Limits Source: https://docs.polymarket.com/api-reference/get-account-limits /api-spec/perps-openapi.json get /v1/account/limits Get the authenticated account's effective rate-limit allowances for its current volume-based tier: order-action rate, open-order cap, and the display-only messages-per-minute figure. `open_orders` reflects the account's current live open-order count; the rate-usage counters (`actions_per_minute`, `actions_burst`, and `reset`) are not tracked here and are reported as 0. Request Weight: **2** # Get Account Referral Source: https://docs.polymarket.com/api-reference/get-account-referral /api-spec/perps-openapi.json get /v1/account/referral Get the authenticated account's invite code, parent referral code, direct referral count, and fee share rate. Request Weight: **1** # Get Account Rewards Source: https://docs.polymarket.com/api-reference/get-account-rewards /api-spec/perps-openapi.json get /v1/account/rewards Get per-instrument daily liquidity reward shares for the authenticated account. Reward periods run from 12:00 UTC to 12:00 UTC and are labeled by their UTC end date. The first reward period starts at 2026-07-06 12:00 UTC. If no date range is provided, the latest computed reward period is returned. Request Weight: **2** # Get Account Stats Source: https://docs.polymarket.com/api-reference/get-account-stats /api-spec/perps-openapi.json get /v1/account/stats Get the authenticated account's 7-day trading stats (taker volume, maker volume, account maker share, and entity maker share when applicable). Stats are cached by UTC day and may be stale by up to 24 hours. Request Weight: **2** # Get authenticated builder receipts Source: https://docs.polymarket.com/api-reference/get-authenticated-builder-receipts /api-spec/perps-openapi.json get /v1/account/builder-earnings Returns this account's builder credits only. The time window is inclusive, defaults to the last seven days, and is bounded to 90 days. Supply the same start_timestamp, end_timestamp and as_of_sequence to compare list and summary. Older receipts remain queryable by selecting a past window. Zero-fee eligible fills count toward volume. Each receipt identifies only the attributed trader's main wallet and own order details, including its signed platform fee and total_fee. client_order_id is omitted when the order did not supply one. Credits are ordinary collateral, not a claim balance. Recover a disconnected builder fill feed through this endpoint using overlapping windows and earning_id deduplication. The live feed can precede indexing. Retry REST until as_of_sequence covers the event. # Get authenticated builder settled earnings summary Source: https://docs.polymarket.com/api-reference/get-authenticated-builder-settled-earnings-summary /api-spec/perps-openapi.json get /v1/account/builder-earnings-summary Returns this account's builder credits only. The time window is inclusive, defaults to the last seven days, and is bounded to 90 days. Supply the same start_timestamp, end_timestamp and as_of_sequence to compare list and summary. Older receipts remain queryable by selecting a past window. Zero-fee eligible fills count toward volume and trader_count. trader_count deduplicates trading accounts across assets, markets and maker/taker roles within this window/cutoff. active_approval_count instead reflects current positive grants to this builder, excluding revocations, independent of this window/cutoff and builder enablement. Credits are ordinary collateral, not a claim balance. # Get Auto-Cancel Status Source: https://docs.polymarket.com/api-reference/get-auto-cancel-status /api-spec/perps-openapi.json get /v1/account/auto-cancel Get the current auto-cancel status for the authenticated account: the armed deadline, how many times the switch has fired today, and when the daily counter resets. Request Weight: **1** # Get Balances Source: https://docs.polymarket.com/api-reference/get-balances /api-spec/perps-openapi.json get /v1/account/balances Get asset balances for the authenticated account. Request Weight: **2** # Get BBO Source: https://docs.polymarket.com/api-reference/get-bbo /api-spec/perps-openapi.json get /v1/info/bbo Get best bid and offer for all instruments. Request Weight: **2** # Get Book Source: https://docs.polymarket.com/api-reference/get-book /api-spec/perps-openapi.json get /v1/info/book Get book for an instrument. Request Weight: Depth 10: **2** Depth 100: **5** Depth 500: **10** Depth 1000: **20** # Get builder profile and eligibility Source: https://docs.polymarket.com/api-reference/get-builder-profile-and-eligibility /api-spec/perps-openapi.json get /v1/info/builder Public builder profile for an address. Returns the saved display name and current registration, enablement, platform admission and fee-cap fields. The name is null for unregistered addresses or builders without a saved name. # Get Collateral Assets Source: https://docs.polymarket.com/api-reference/get-collateral-assets /api-spec/perps-openapi.json get /v1/info/assets Get a list of collateral assets. Request Weight: **2** # Get Credentials Source: https://docs.polymarket.com/api-reference/get-credentials /api-spec/perps-openapi.json get /v1/account/credentials Get the account ID, address, and proxy keys for the authenticated account. Request Weight: **2** # Get Current Position Fills Source: https://docs.polymarket.com/api-reference/get-current-position-fills /api-spec/perps-openapi.json get /v1/info/position-fills Get every fill in a registered account's current open position cycle for one instrument. A cycle begins when the position opens from flat or flips direction. For a flip, every fill from the flipping engine event belongs to the new cycle so a fill is never split between cycles. Returns an empty page when the account has no open position for the instrument. Maximum of 100 entries returned per request. Results are ordered by time; use `sort` to choose newest-first (`desc`, default) or oldest-first (`asc`). To page through more than 100 fills, pass the opaque `cursor` returned by the previous page and keep `sort` unchanged. Each page verifies that the cursor still describes the account's current position cycle. If that position changes while pagination is in progress, the cursor returns `400` and pagination must restart from the first page. Cycle discovery for a position inherited from a gateway snapshot is limited to 250,000 account-history rows. A cycle older than that bound returns `413` rather than allowing a public request to run an unbounded ClickHouse scan. Positions opened or flipped after gateway startup carry their cycle boundary directly and do not use this discovery scan. Request Weight: **10** Cached 2s — a request served from cache costs **1** # Get Deposits Source: https://docs.polymarket.com/api-reference/get-deposits /api-spec/perps-openapi.json get /v1/account/deposits Get deposit history for the authenticated account. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Request Weight: **10** # Get Equity Source: https://docs.polymarket.com/api-reference/get-equity /api-spec/perps-openapi.json get /v1/account/equity Get equity history for the authenticated account. If no end time is provided, the current time will be used. Each point is the last equity sample in its `interval` bucket, stamped with that sample's own timestamp rather than the bucket's start — so every timestamp falls within the requested window. Buckets are aligned to the Unix epoch. Equity history is served at one-minute resolution, so `1s` is served as `1m`. Maximum of 1000 entries returned per request — of buckets, so a coarser interval covers a longer window before `more` is set. When `more` is true, page by re-requesting from one millisecond past the last timestamp returned; that always lands on the next bucket, never back inside the one just served. Request Weight: **10** # Get Exchange Info Source: https://docs.polymarket.com/api-reference/get-exchange-info /api-spec/perps-openapi.json get /v1/info/exchange Get exchange information. Request Weight: **2** # Get Exchange Statistics Source: https://docs.polymarket.com/api-reference/get-exchange-statistics /api-spec/perps-openapi.json get /v1/info/exchange-stats Get aggregate statistics for all pUSD-quoted Polymarket perpetual markets. The time window is half-open: trades at `start_timestamp` are included and trades at `end_timestamp` are excluded. The maximum window is 31 days. Open interest is the one-sided USD notional from the latest complete sample before `end_timestamp`; its value and timestamp are null when no complete sample is available. Fees are gross positive maker and taker trading fees. Rebates, incentives, and referral payments are excluded. Request Weight: **10** Cached 5m — a request served from cache costs **1** # Get Fees Source: https://docs.polymarket.com/api-reference/get-fees /api-spec/perps-openapi.json get /v1/info/fees Get the fee tier schedule for each instrument type and category. Request Weight: **2** # Get Fills Source: https://docs.polymarket.com/api-reference/get-fills /api-spec/perps-openapi.json get /v1/account/fills Get fill history for the authenticated account. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Results are ordered by time; use `sort` to choose newest-first (`desc`, default) or oldest-first (`asc`). To page through more than 100 fills, pass the `cursor` returned by the previous page (keep `sort` consistent across pages). Passing the trade ID of the last fill from the previous page is also still accepted. Pass `instrument_id` to narrow the page to one instrument's fills; the window, cursor and sort apply unchanged. Request Weight: **10** # Get Funding Charges Source: https://docs.polymarket.com/api-reference/get-funding-charges /api-spec/perps-openapi.json get /v1/account/funding Get funding payment history for the authenticated account. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Request Weight: **10** # Get Historical Funding Source: https://docs.polymarket.com/api-reference/get-historical-funding /api-spec/perps-openapi.json get /v1/info/funding Get public funding rate history for an instrument. Maximum of 100 entries returned per request. Request Weight: **10** # Get Index Source: https://docs.polymarket.com/api-reference/get-index /api-spec/perps-openapi.json get /v1/info/index Get index price and the list of constituents for an asset. Request Weight: **2** # Get Instrument Config Source: https://docs.polymarket.com/api-reference/get-instrument-config /api-spec/perps-openapi.json get /v1/account/config Get resolved per-instrument configuration (leverage and margin mode) for the authenticated account. Each setting resolves independently: explicit per-instrument setting, then exchange-managed account-group default, then instrument maximum leverage and isolated margin. Group leverage is capped at the instrument maximum; a group cross default resolves to isolated on isolated-only instruments. Group defaults apply to new listings and never overwrite explicit settings. Use the leverage update operations to set explicit per-instrument overrides. Request Weight: **2** # Get Instruments Source: https://docs.polymarket.com/api-reference/get-instruments /api-spec/perps-openapi.json get /v1/info/instruments Get enabled instruments. When instrument_id is supplied, a permanently settled instrument is also returned, including its final settlement record. Other disabled instruments remain excluded. The presence of settlement means the instrument is delisted and cannot trade. Request Weight: **2** # Get Internal Transfers Source: https://docs.polymarket.com/api-reference/get-internal-transfers /api-spec/perps-openapi.json get /v1/account/internal-transfers Get settled internal transfer history for the authenticated account. Returns both inbound and outbound transfers unless `direction` narrows the page to one side; a value other than `in` or `out` is refused. Request Weight: **10** # Get Klines Source: https://docs.polymarket.com/api-reference/get-klines /api-spec/perps-openapi.json get /v1/info/klines Get klines for an instrument. If no end time is provided, the current time will be used. Maximum of 1000 entries returned per request. Request Weight: **5** # Get Leaderboard Source: https://docs.polymarket.com/api-reference/get-leaderboard /api-spec/perps-openapi.json get /v1/info/leaderboard Get the global perpetuals leaderboard, ranked by PnL, notional volume, current account value, or ROI across all instruments. Windows are anchored to calendar UTC boundaries: `day` starts at 00:00 UTC today, `week` at Monday 00:00 UTC, `month` at the first of the month 00:00 UTC, and `all` at exchange launch. PnL is realized PnL minus trading fees plus funding payments, consistent with the account PnL endpoint; unrealized PnL is excluded. Notional is the USD value of all fills in the window. Every entry carries both metrics; `rank` is the position under the requested `sort_by`. ROI sorting uses the served, rounded window ROI in descending order, with ties broken by higher PnL, higher notional, then the older account. It uses the same eligible accounts as PnL and notional, with no additional minimum equity or volume requirement. The optional `address` row reports its rank under the same ordering, including ranks beyond the pageable top 1000. PnL, notional, and account value are raw numeric strings from the engine. Account value is current equity (collateral value plus unrealized PnL). The background census advances by at most 8,192 accounts on each 60-second poller tick, so a full publication can span multiple ticks as the account population grows. For account-value sorting, `timestamp` is the earlier of the published census start and the historical window's computation time, so stale membership and PnL remain observable if a historical rebuild fails. When sorting by account value, the requested window still determines which accounts and historical PnL/notional metrics are included, while the ranking uses their current equity. Accounts whose equity cannot be computed are excluded from that ranking. When unrealized PnL is unavailable (for example, due to stale marks), the display field falls back to collateral value on PnL/notional entries and address lookups; it does not establish an equity rank. `total` counts accounts with published equity in that window. `sort_by=account_value` returns 503 while the first completed census is warming. PnL and notional rankings remain available during that warm-up. Clients are responsible for decimal and currency presentation formatting. Rankings are recomputed periodically; `timestamp` is the computation time. Returns 25 entries by default and at most 100 per request; only the top 1000 ranks are pageable (`offset + limit` must not exceed 1000). Provide `address` to additionally return that account's row regardless of rank. An address with no activity in the window returns zero metrics and no rank. Request Weight: **5** Cached 5s — a request served from cache costs **1** # Get Limit Tiers Source: https://docs.polymarket.com/api-reference/get-limit-tiers /api-spec/perps-openapi.json get /v1/info/limit-tiers Get the list of account limit tiers. Action and open-order fields are enforced per account; legacy request-rate fields are not used for gateway request enforcement. Request Weight: **2** # Get Mark Price History Source: https://docs.polymarket.com/api-reference/get-mark-price-history /api-spec/perps-openapi.json get /v1/info/mark-history Get mark price history for an instrument, bucketed by interval. If no end time is provided, the current time will be used. Maximum of 1000 entries returned per request. Only buckets with at least one mark update are included. For intervals of a minute or coarser, a bucket cut mid-way by `end_timestamp` may be omitted, or may reflect the window's last mark at one-minute fidelity. Request Weight: **5** Cached for 2s. A request served from cache costs **1** # Get Notifications Source: https://docs.polymarket.com/api-reference/get-notifications /api-spec/perps-openapi.json get /v1/account/notifications Get the authenticated account's notifications, newest first. Results come in pages. Pass the cursor returned by the previous page to fetch the next, older one. If your WebSocket connection dropped or you received a resync frame, pass since_seq to backfill anything you may have missed; the same notification can show up again at the edges of the window, so deduplicate by id. While paging through a backfill, keep sending the same since_seq with each cursor so every page stays inside the same window. The response also includes your unread count and durable_source_seq, which tells you how far the notification store has caught up. If a backfill has not yet reached your target sequence, wait briefly and retry with the same since_seq. Request Weight: **10** # Get Open Orders Source: https://docs.polymarket.com/api-reference/get-open-orders /api-spec/perps-openapi.json get /v1/account/open-orders Get open orders for the authenticated account. Request Weight: With instrument ID: **1** Without instrument ID: **20** # Get Orders Source: https://docs.polymarket.com/api-reference/get-orders /api-spec/perps-openapi.json get /v1/account/orders Get historical order snapshots for the authenticated account from the order history database. Returns the latest known state for each matching order, including accepted, open, partial, filled, and cancelled orders. For currently resting orders only, use Get Open Orders. Maximum of 100 entries returned per request. Request Weight: With order ID: **1** Without order ID: **10** # Get PnL Source: https://docs.polymarket.com/api-reference/get-pnl /api-spec/perps-openapi.json get /v1/account/pnl Get PnL history for the authenticated account. If no end time is provided, the current time will be used. Each point is the PnL realized inside its `interval` bucket — not a running total. Buckets are aligned to the Unix epoch, and one in which nothing was realized is omitted, so the series is sparse. A point is stamped with the last populated hour in its bucket, not with the bucket's start, so every returned timestamp falls within the requested window. Window bounds select whole one-hour rollup rows before coarser buckets are formed. Maximum of 1000 entries returned per request — of buckets, so a coarser interval covers a longer window before `more` is set. When `more` is true, page by re-requesting from one millisecond past the last timestamp returned; that always lands on the next bucket, never back inside the one just served. Request Weight: **10** # Get Portfolio Source: https://docs.polymarket.com/api-reference/get-portfolio /api-spec/perps-openapi.json get /v1/account/portfolio Get current portfolio snapshot including open positions, margin summary, and withdrawable balance. Request Weight: **2** # Get Position Share Card Snapshots Source: https://docs.polymarket.com/api-reference/get-position-share-card-snapshots /api-spec/perps-openapi.json post /v1/info/position-snapshots Build share-card numbers, candles and trade markers for a registered account. Supply up to 20 active instruments and 4 historical fills, with at least one selection. History keys use instrument_id, trade_id and the public fill timestamp in milliseconds. Trade IDs are UInt64 decimal strings; returned IDs omit leading zeroes. Duplicates and explicit null arrays are rejected. Weight is max(10, active + 7 × history). Responses use Cache-Control: private, no-store. The route is public; valid owner authentication reveals leverage and pnl_percent. Both fields are null for anonymous callers and other accounts. Invalid supplied credentials return 401. Active snapshots use captured state; history ends after the selected fill. A fill that closes a cycle, fully or by crossing, returns that closed cycle's card. The cycle it opens is served by the active card or by its later fills. PositionCardSnapshot defines valuation, PnL and leverage availability. Results preserve order within active and history. Only ok items contain snapshot. not_found means no current position or owned fill within history_as_of_at; gateways may have different horizons. history_pending means a known fill or a position needing bootstrap is ahead of completed history, or the self-match index coverage gate is not armed for historical cards; retry with backoff. history_limit means the reconstruction window lacks the opener. resource_limit means a row, memory or chart bound was exceeded. temporarily_unavailable includes deadlines and transient pricing or dependency failures. unavailable includes unsafe accounting, self-matches, backstop transfers, non-fill repairs and legacy multi-leg selections with unknowable fill order. Candles include the selected minute's aggregate, without a per-fill cutoff inside it. Charts retain the left boundary bucket and at least one hour of context, with at most 22 candles and 256 markers. Unknown accounts and malformed input return 400. Admission and shared dependency failures return 503; retry with backoff. HTTP 413 is reserved for an oversized request body. Request Weight: **max(10, active + 7 × history)** # Get Public Fills Source: https://docs.polymarket.com/api-reference/get-public-fills /api-spec/perps-openapi.json get /v1/info/fills Get fill history for a registered account address. Rows include order IDs, exchange and builder fees, and position accounting. Builder identity and rate are omitted on this public surface. The default window starts 30 days before request time. When instrument_id is provided, returns only fills for that instrument and reads at most 250,000 physical rows; reads exceeding this cap return HTTP 413. Filtered reads cap the end time at the current time and, when the start is omitted, start 30 days before that effective end time. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Results are ordered by time; use `sort` to choose newest-first (`desc`, default) or oldest-first (`asc`). To page through more than 100 fills, pass the `cursor` returned by the previous page (keep `sort` consistent across pages). Passing the trade ID of the last fill from the previous page is also accepted for unfiltered requests. When instrument_id is set, legacy numeric cursors are rejected with HTTP 400; use the returned keyset cursor. Request Weight: **10** Cached 2s — a request served from cache costs **1** # Get Public Portfolio Source: https://docs.polymarket.com/api-reference/get-public-portfolio /api-spec/perps-openapi.json get /v1/info/portfolio Get public portfolio for an address including equity and open positions. Request Weight: **5** # Get Recent Trades Source: https://docs.polymarket.com/api-reference/get-recent-trades /api-spec/perps-openapi.json get /v1/info/trades Get public trades for an instrument. Maximum of 100 entries returned per request. Request Weight: **10** # Get Registration Source: https://docs.polymarket.com/api-reference/get-registration /api-spec/perps-openapi.json get /v1/info/registered Check whether an address has a Perps account. Registration is permanent, so a `true` answer never changes; a `false` answer flips as soon as the address registers. Request Weight: **1** Cached — `true` up to 1 day at the edge, `false` up to 10s # Get Server Time Source: https://docs.polymarket.com/api-reference/get-server-time /api-spec/perps-openapi.json get /v1/info/time Get server time. Request Weight: **1** # Get Statistics Source: https://docs.polymarket.com/api-reference/get-statistics /api-spec/perps-openapi.json get /v1/info/statistics Get last 24-hour statistics for all instruments. Request Weight: **2** # Get Tickers Source: https://docs.polymarket.com/api-reference/get-tickers /api-spec/perps-openapi.json get /v1/info/tickers Get all instrument tickers with live market data. Request Weight: **2** # Get Trading Competition Source: https://docs.polymarket.com/api-reference/get-trading-competition /api-spec/perps-openapi.json get /v1/info/competition Settings, status and prize table of one competition: its markets and boosts (also for upcoming competitions), the qualification minimum, the market the "Start Trading" button opens (the boosted market with the most 24-hour volume, else the top market overall), and when the leaderboard was last updated. Score is PnL × √(boosted volume). PnL counts realized and (when `count_unrealized`) unrealized PnL on positions opened during the competition, after fees and funding. Boosts multiply volume only. Request Weight: **1** Cached 1s # Get Trading Competition Account Source: https://docs.polymarket.com/api-reference/get-trading-competition-account /api-spec/perps-openapi.json get /v1/info/competition/account One account's standing: rank and score once qualified, otherwise its volume so far and how much more it needs to rank; projected or won prize; places and score from the prize zone; every position it held when the competition started, by market, and whether it has since been closed. An address with no activity returns zero figures and no rank. Request Weight: **1** # Get Trading Competition Leaderboard Source: https://docs.polymarket.com/api-reference/get-trading-competition-leaderboard /api-spec/perps-openapi.json get /v1/info/competition/leaderboard Ranked leaderboard rows at any depth. Only accounts that reached the minimum volume are ranked; ties go to higher boosted volume, then the earlier first qualifying fill. `prize` is the projected prize while live and the prize won once the competition ends. `updated_at` is the event time the standings reflect ("Updated X seconds ago"). With `include_unqualified=true` on a ranked board, the rows still short of the entry gate follow the ranked ones, unranked and without a prize, by score with the same tie-breaks. Only live accounts with volume are listed; disqualified and under-review accounts never are. `total` and `offset` then count across both, and every entry carries `qualified`. Returns 50 entries by default and at most 100 per request. Request Weight: **1** Cached 1s # Get Trading Competition Widget Source: https://docs.polymarket.com/api-reference/get-trading-competition-widget /api-spec/perps-openapi.json get /v1/info/competition/widget The live competition at a glance for the trading page: when it ends, and, with `address`, that account's rank and progress toward the qualification minimum. Designed to be polled; it reads only the published standings. Without a live competition only `timestamp` is set. Request Weight: **1** # Get Trading Competitions Source: https://docs.polymarket.com/api-reference/get-trading-competitions /api-spec/perps-openapi.json get /v1/info/competitions List trading competitions for the carousel, newest first, with the live competition's ID (for "Back to live") and the one the Competitions tab should open on: the live competition, else the next upcoming one, else the most recently ended one. Internal competitions are listed only when `address` is on their allowlist. This is a display filter, not access control: the info API is unauthenticated, and an internal competition can be read by ID. Request Weight: **1** # Get Withdrawals Source: https://docs.polymarket.com/api-reference/get-withdrawals /api-spec/perps-openapi.json get /v1/account/withdrawals Get withdrawal history for the authenticated account. If no end time is provided, the current time will be used. Maximum of 100 entries returned per request. Request Weight: **10** # Internal Transfer Source: https://docs.polymarket.com/api-reference/internal-transfer /api-spec/perps-openapi.json post /v1/account/internal-transfer Submit a signed internal ledger transfer between two exchange accounts. Sign with the source account owner or a non-expired trading key registered to the source account. Trading-key signatures require both accounts to belong to the same nonzero, exchange-managed account group. Owner signatures remain valid regardless of group membership. Expired trading keys receive `proxy_expired`; other authorization failures receive `signer_does_not_match_account`. An unknown destination receives 400 `destination account not found`. A 503 does not prove that the transfer was not submitted. Retry with backoff, honoring `Retry-After` when present, and resend the exact original signed request. Do not create a fresh signature, salt, or timestamp for the retry: it would identify a separate transfer. A `signature_already_used` rejection does not confirm whether the original transfer completed. Request Weight: **1** # PolyBolt WebSocket Source: https://docs.polymarket.com/api-reference/live-data/overview Stream crypto, equity and TWAP reference prices over one WebSocket connection. PolyBolt streams crypto, equity and TWAP reference prices over a single connection. Subscriptions require CLOB API credentials. For existing RTDS integrations, see [Migrate from RTDS to PolyBolt](/migrate/rtds-to-polybolt). > [!WARNING] > > Price subscriptions must name a provider. > Subscriptions served by Chainlink also require your Chainlink API key. See > [Send Your Chainlink API Key](#send-your-chainlink-api-key) and [Pin a Price > Provider](#pin-a-price-provider). ## Connect Open a WebSocket connection to: ```text theme={null} wss://ws-live-v2.polymarket.com/ws ``` Choose a channel, authenticate, then send a subscription request. ## Channels | Channel | Data | Filter | Access | | - | - | - | - | | `price.crypto` | Crypto reference prices | `{"symbol": "btcusd", "provider": "chainlink"}` | CLOB API credentials | | `price.equity` | Stock, ETF, forex, metal and commodity reference prices | `{"symbol": "aapl", "provider": "pyth"}` | CLOB API credentials | | `price.crypto.twap` | 60-second time-weighted average prices (TWAP) from Chainlink | `{"symbol": "btcusd", "window_seconds": 60, "provider": "chainlink"}` | CLOB API credentials | | `price.equity.twap` | 60-second forex TWAP prices from Chainlink (`eurusd` and `usdjpy`) | `{"symbol": "eurusd", "window_seconds": 60, "provider": "chainlink"}` | CLOB API credentials | Use lowercase symbols, and name the provider in every filter (see [Pin a Price Provider](#pin-a-price-provider)). ## Authenticate for Gated Channels Send your [CLOB API credentials](/getting-started/api#authentication) on the open connection before subscribing: ```json theme={null} { "op": "auth", "rid": "a1", "auth": { "apiKey": "", "secret": "", "passphrase": "" } } ``` Wait for the server to confirm authentication: ```json theme={null} { "op": "authed", "rid": "a1" } ``` ### Send Your Chainlink API Key Subscriptions served by Chainlink, including TWAP, require your Chainlink API key in addition to CLOB API credentials. > [!NOTE] > > Request a Chainlink API Key using [this form](https://institutional.polymarket.com/request-chainlink-api-key). > [tab] TypeScript > > Use an authenticated [SecureClient](/trading/wallets-auth) and pass your key as `providerApiKey` with the Chainlink provider. > > ```ts theme={null} > import { PriceProvider } from "@polymarket/client"; > > const stream = await client.subscribe([ > { > topic: "prices.crypto.twap", > symbols: ["btcusd"], > provider: PriceProvider.Chainlink, > providerApiKey: "", > }, > ]); > > try { > for await (const event of stream) { > // event: CryptoTwapPriceEvent > } > } finally { > await stream.close(); > } > ``` > [tab] Python > > Use an authenticated [AsyncSecureClient](/trading/wallets-auth) and pass your key as `provider_api_key` with the Chainlink provider. > > ```python theme={null} > from polymarket.streams import CryptoTwapPriceSpec > > async with await client.subscribe( > CryptoTwapPriceSpec( > symbols=["btcusd"], > provider="chainlink", > provider_api_key="", > ) > ) as stream: > async for event in stream: > # event: CryptoTwapPriceEvent > pass > ``` > [tab] API > > Send `chainlink_api_key` in the first `auth` frame alongside your CLOB API credentials. To change the key, open a new connection. > > ```json theme={null} > { > "op": "auth", > "rid": "a1", > "auth": { > "apiKey": "", > "secret": "", > "passphrase": "" > }, > "chainlink_api_key": "" > } > ``` Subscriptions served by other providers do not need an API key for now. If a requested provider falls back to Chainlink, the key is still required. The server reports authentication problems with an error acknowledgement, for example: ```json theme={null} { "op": "error", "code": "auth_required", "channel": "price.crypto", "rid": "s1" } ``` These errors leave the connection open: | Code | Meaning | Action | | - | - | - | | `auth_required` | The subscription was sent before authentication. | Authenticate, then resend the subscription. | | `auth_invalid` | The credentials were rejected. | Correct the credentials before retrying. | | `auth_unavailable` | Authentication is temporarily unavailable. | Wait, then retry authentication. | | `chainlink_key_required` | A subscription served by Chainlink was sent on a connection authenticated without a Chainlink API key. | Open a new connection, authenticate with `chainlink_api_key`, then resend the subscription. | `chainlink_key_required` also carries a numeric `status` of `4010`. It is not a close code: the connection stays open. ## Subscribe Send the channels and filters you want to follow. This request subscribes to the BTC reference price from Chainlink on a connection authenticated with your Chainlink API key: ```json theme={null} { "op": "subscribe", "rid": "s1", "subscriptions": [ { "channel": "price.crypto", "filter": { "symbol": "btcusd", "provider": "chainlink" } } ] } ``` A batch counts as one request against the rate limit. ### Pin a Price Provider Crypto and equity prices can come from more than one vendor. Every payload names its producer in `source`. Choose one by adding `provider` to the filter: ```json theme={null} { "op": "subscribe", "rid": "s2", "subscriptions": [ { "channel": "price.crypto", "filter": { "symbol": "btcusd", "provider": "pyth" } } ] } ``` `provider` accepts `chainlink`, `pyth` or `binance`. Binance serves `price.crypto` only, with USDT spot closes under the canonical USD symbol. The `subscribed` acknowledgement names the provider actually served. A pin the server cannot serve for that symbol falls back to the symbol's default provider, and the acknowledgement names the fallback, so always read the acknowledgement rather than assuming the pin held. The TWAP channels are served by Chainlink only, so pin `chainlink` there. Values other than `chainlink`, `pyth` or `binance` are rejected with a `bad_filter` error. `provider` is required on `price.crypto`, `price.equity`, `price.crypto.twap` and `price.equity.twap`. A subscription without `provider` answers this error, and the connection stays open: ```json theme={null} { "op": "error", "code": "provider_required", "status": 4011, "channel": "price.crypto", "rid": "s2" } ``` ### Read the Market Status Equity markets close: exchanges keep session hours, and metals and forex pause daily and over the weekend. On `price.equity` and `price.equity.twap`, each payload says whether the market of the instrument it prices is trading, so you can show "closed at" a price instead of a price that silently stops moving. `market_status` is `open`, `closed` or `unknown` (the vendor reported that it cannot determine the status). It is absent when the producer states nothing: treat an absent status as not stated, never as open. The status belongs to the provider's series, because it describes the instrument that provider prices. Chainlink's equity products trade around the clock, so a symbol served by Chainlink can read `open` on a weekend while the same symbol pinned to `pyth` follows its exchange session and reads `closed`. When the status changes without a new price, you receive a normal update that repeats the last price with the new status and `is_carried_forward: true`: ```json theme={null} { "v": 1, "channel": "price.equity", "seq": 41, "ts": 1792526399800, "payload": { "symbol": "aapl", "value": 262.71, "full_accuracy_value": "262.71", "timestamp": 1792526399800, "received_at": 1792526401200, "is_carried_forward": true, "source": "pyth", "market_status": "closed" } } ``` That update shares its `timestamp` and `value` with the update before it, so never discard an update only because its `timestamp` repeats. While a series is `closed` or `unknown`, its snapshot also carries the last price point even when it is older than two minutes, and the snapshot's `ts` is that point's time. Re-read `market_status` from the snapshot after every reconnect. SDK 0.14.0 and later expose this field as `payload.marketStatus` in TypeScript and `payload.market_status` in Python, on snapshots and live updates. See [Read the Market Status](/market-data/realtime-data#read-the-market-status) for TypeScript, Python, and API examples. ## Envelope Data envelopes carry snapshots and live updates. Acknowledgements report the result of a request. ```json Live Update theme={null} { "v": 1, "channel": "price.crypto", "seq": 2, "ts": 1788973001000, "payload": { "symbol": "btcusd", "value": 64126.0, "full_accuracy_value": "64126.00000000", "timestamp": 1788973001000, "source": "chainlink" } } ``` ```json Snapshot theme={null} { "v": 1, "channel": "price.crypto", "seq": 1, "ts": 1788973000000, "snapshot": true, "payload": { "symbol": "btcusd", "source": "chainlink", "data": [ { "timestamp": 1788972880000, "value": 64123.5, "full_accuracy_value": "64123.50000000" }, { "timestamp": 1788972881000, "value": 64125.1, "full_accuracy_value": "64125.10000000" } ] } } ``` ```json Acknowledgement theme={null} { "op": "subscribed", "channel": "price.crypto", "rid": "s1", "provider": "chainlink" } ``` Acknowledgements echo `rid` when the request includes it. | `op` | Meaning | | - | - | | `authed` | Authentication succeeded. You can subscribe to gated channels. | | `subscribed` | The subscription was accepted. `channel` identifies the channel; on price channels, `provider` names the vendor served. | | `unsubscribed` | The unsubscribe request was accepted. `channel` identifies the channel. | | `pong` | The server received your application-level `ping` request. | | `error` | The request failed. `code` identifies the reason. Policy violations can also close the connection. | `chainlink_key_required` and `provider_required` errors also carry a numeric `status`, `4010` and `4011`. Neither closes the connection. Each new subscription receives an acknowledgement and one snapshot. Seed local state from the snapshot, then apply the latest price. Snapshots contain the preceding two minutes of prices, with an empty `data` array when no recent data is available. Repeating an existing channel and filter returns another acknowledgement without a new snapshot. For data envelopes: * `seq` is consecutive per connection and per channel, including snapshots. It resets on reconnect. * `ts` is the producer's event time in Unix milliseconds. * `snapshot: true` identifies the initial snapshot. * `dropped`, when present, counts frames dropped on that channel since the last delivered frame because the client fell behind. * `source` names the vendor that produced the price (`pyth`, `massive` or `chainlink`): on every point of a live update and once per snapshot batch. On single-provider channels it is constant; on `price.crypto` and the equity channels a symbol's vendor can change between connections, so re-read it after every reconnect. * `market_status`, on the equity channels, is `open`, `closed` or `unknown`: on every live update and once per snapshot batch, absent when not stated. See [Read the Market Status](#read-the-market-status). Compare sequence numbers only within the same connection and channel. See the [Live Data Channel](/api-reference/wss/polybolt) for every message schema and `https://ws-live-v2.polymarket.com/asyncapi.json` for the machine-readable contract. ## Unsubscribe Send the same channel and filter with `op: "unsubscribe"` to stop a subscription: ```json theme={null} { "op": "unsubscribe", "subscriptions": [ { "channel": "price.crypto", "filter": { "symbol": "btcusd", "provider": "chainlink" } } ] } ``` The server confirms with `unsubscribed`. Both `subscribe` and `unsubscribe` accept a single `channel` and `filter` or a `subscriptions` array. ## Supported Symbols ### Crypto Prices | Channel | Symbols | | - | - | | `price.crypto` | `btcusd`, `ethusd`, `solusd`, `xrpusd`, `dogeusd`, `hypeusd`, `bnbusd`, `zecusd` | | `price.crypto.twap` | `btcusd`, `ethusd`, `solusd`, `xrpusd`, `dogeusd`, `hypeusd`, `bnbusd`, `zecusd` | | `price.equity.twap` | `eurusd`, `usdjpy` | For the TWAP channels, use `window_seconds: 60`. Other windows do not provide data. Every `price.crypto` symbol is served by Chainlink, its default provider, and by Binance. `btcusd`, `ethusd`, `solusd`, `xrpusd`, `dogeusd` and `bnbusd` are also served by Pyth; on `hypeusd` and `zecusd` a `pyth` pin falls back to Chainlink. `price.crypto.twap` is Chainlink only. ### Equity Prices `price.equity` supports these lowercase symbols: | Asset class | Symbols | | - | - | | Stocks | `aapl`, `tsla`, `msft`, `googl`, `amzn`, `meta`, `nvda`, `nflx`, `pltr`, `open`, `rklb`, `abnb`, `coin`, `hood`, `spcx`, `intc`, `mstr`, `crcl`, `mu` | | ETFs | `qqq`, `spy`, `ewy`, `vxx` | | Forex | `eurusd`, `gbpusd`, `usdcad`, `usdjpy`, `usdkrw`, `usdchf`, `usdmxn`, `usdzar`, `usdbrl`, `usdnok`, `usdsek`, `usdtry`, `dxy` | | Precious metals | `xauusd`, `xagusd` | `dxy` is the US Dollar Index. Each equity symbol has a default provider, which serves any pin the symbol does not support, including every `binance` pin: | Symbols | Default | Pinnable | | - | - | - | | `xauusd`, `xagusd`, `nvda`, `googl`, `tsla`, `spcx`, `mu` | `chainlink` | `pyth` | | `intc`, `mstr`, `crcl`, `wti`, `brent`, `natgas` | `chainlink` | none | | `eurusd`, `usdjpy` | `pyth` | `chainlink` | | Every other equity symbol | `pyth` | none | Commodities serve under `cll` (WTI crude oil futures) and `hn` (Henry Hub natural gas futures) from Pyth, `wti` (WTI crude oil futures), `brent` (Brent crude oil futures) and `natgas` (natural gas futures) from Chainlink, and `cc3m` (the copper 3-month contract price in USD). Each futures symbol keeps one symbol as its contract rolls. `cll` and `hn` move to the next contract at the open of the current contract's third-to-last trading session, the Active Month the WTI and natural gas Up or Down markets resolve on. `wti`, `brent` and `natgas` follow Chainlink's own roll schedule. `cc3m` is a single continuous contract. ## Limits and Liveness | Limit | Value | On breach | | - | - | - | | Active subscriptions per connection | 64 `(channel, filter)` pairs | `sub_limit` error, then close `4008` | | Subscribe or unsubscribe frames | 20 per second (a batch counts once) | `rate_limited` error, then close `4008` | | Frame size | 64 KB | close `4008` | | Auth frames per connection | 8 | `auth_attempts` error, then close `4008` | The server sends a WebSocket ping every 25 seconds. Standard clients answer automatically. Two missed pongs close the connection with `4002`. You can also send `{ "op": "ping" }` to check the connection at the application level. The server responds with `pong`. ## Close Codes and Reconnecting Choose the retry behavior based on the close code: | Code | Meaning | Client behavior | | - | - | - | | `4001` | Authentication failed | Fix authentication before reconnecting. | | `4002` | Slow consumer or pong timeout | Retry with exponential backoff and jitter. Reduce subscription load if this repeats. | | `4003` | Server draining | Reconnect after a uniformly random delay of 0 to 10 seconds. | | `4008` | Policy violation | Fix the request or limit violation before reconnecting. | | `1006` | Abnormal disconnect | Retry with exponential backoff and full jitter, starting at 1 second and capped at 30 seconds. | If the connection is refused with HTTP `429` or `503`, use `Retry-After` as the minimum wait and add jitter. Browser clients see handshake failures as `1006` and should use exponential backoff with full jitter. After reconnecting, authenticate again for gated channels and resend your subscriptions with their `provider` pins. Initialize from the new snapshots and re-read `source`: a crypto or equity symbol can legitimately arrive from a different vendor than before the reconnect. Sequence numbers start over. # Cancel a quote Source: https://docs.polymarket.com/api-reference/maker/cancel-a-quote /api-spec/combos-rfq-openapi.yaml post /v1/maker/quotes/cancel Cancel an active maker quote before it is selected. Requires CLOB L2 authentication for the maker role. `signer_address` and `maker_address` must match the authenticated identity. # Confirm or decline last look Source: https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look /api-spec/combos-rfq-openapi.yaml post /v1/maker/confirmations Respond to a last-look confirmation request for a selected quote. Requires CLOB L2 authentication for the maker role. `decision` must be `CONFIRM` or `DECLINE`. # Submit a quote Source: https://docs.polymarket.com/api-reference/maker/submit-a-quote /api-spec/combos-rfq-openapi.yaml post /v1/maker/quotes Submit a signed maker quote for an active RFQ. Requires CLOB L2 authentication for the maker role. REST does not assign a quote ID — generate `quote_id` client-side. # Mark Notifications Read Source: https://docs.polymarket.com/api-reference/mark-notifications-read /api-spec/perps-openapi.json post /v1/account/notifications/read Mark notifications as read. Send a list of notification ids, or a before cursor to mark everything up to and including that point. You can only mark your own notifications. Request Weight: **2** # Modify Orders Source: https://docs.polymarket.com/api-reference/modify-orders /api-spec/perps-openapi.json patch /v1/trade/orders Modify the price and total quantity of existing orders by exchange order ID. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1 + floor(n / 20)**Action Weight: **1 / order** # Modify Orders COID Source: https://docs.polymarket.com/api-reference/modify-orders-coid /api-spec/perps-openapi.json patch /v1/trade/orders-coid Modify the price and total quantity of existing orders by client order ID. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1 + floor(n / 20)**Action Weight: **1 / order** # Geographic Restrictions Source: https://docs.polymarket.com/api-reference/perps/geographic-restrictions Jurisdictions where Polymarket Perps order placement is not permitted Polymarket restricts order placement from certain geographic locations to comply with regulatory requirements and international sanctions. Users in restricted jurisdictions cannot place Perps orders. ## Restricted Jurisdictions Order placement is not permitted from: * United States * Canada * Cuba * Iran * North Korea * Syria * Crimea * Donetsk * Luhansk > [!WARNING] > > This list can change. Additional restrictions may apply under Polymarket > notices or applicable law. ## For Builders If you're integrating Perps, enforce these restrictions before submitting orders for a user: * Verify the end user's location before [placing orders](/perps/trading#place-orders). * Block order submission entirely for users in any of the listed jurisdictions. Do not only display a warning. * Apply the same check to any flow that results in a new position, including programmatic strategies that act on behalf of a user. Read-only market data is not subject to these restrictions. # Overview Source: https://docs.polymarket.com/api-reference/perps/overview Explore the APIs available for building with Polymarket Perps. ## APIs The Perps API is available over HTTP and WebSocket, with public market data and authenticated trading and account operations on both. > [card] HTTP API > > `https://api.perpetuals.polymarket.com` > > Make request-response calls for market data, trading, and account > management. > [card] WebSocket API > > `wss://ws.perpetuals.polymarket.com/v1/ws` > > Stream public and private updates, or send trading actions over a persistent > connection. ## Before You Integrate > [card] [Authentication](/perps/authenticated-sessions) > > Set up credentials for private HTTP and WebSocket access. > [card] [Rate Limits](/api-reference/perps/rate-limits) > > Review request, trading action, and WebSocket limits. > [card] [Geographic Restrictions](/api-reference/perps/geographic-restrictions) > > Check where Perps order placement is available. ## Correlate Requests with Exchange Logs Every HTTP response the exchange produces — including errors and overload responses — carries an `x-pmp-pod` header identifying the gateway pod that produced it. WebSocket handshake responses carry the same header, on both the successful `101` upgrade and handshake rejections. Record it with your request logs so your traffic can be matched against exchange logs when you work with support. The value is the gateway pod name, or a hexadecimal process instance ID when the pod name is unavailable. It is correlation metadata only: pods are not addressable, and a cached response keeps the identity of the pod that originally produced it. Responses to malformed HTTP carry no header. Browsers can read the header through CORS, but browser WebSocket APIs do not expose handshake headers — authenticated WebSocket sessions instead receive the pod identity in the successful auth acknowledgement, described in [Authenticated Sessions](/perps/authenticated-sessions). Treat the header and the field as optional: responses from older pods omit them during a rolling deploy. # Rate Limits Source: https://docs.polymarket.com/api-reference/perps/rate-limits IP rate limits, action rate limits, and WebSocket limits for Perps integrations Perps uses separate rate-limit buckets for different traffic types. Hitting one bucket does not consume another bucket, so request volume, account trading actions, and WebSocket traffic should be monitored separately. ## How Limits Work Use the error type to identify which bucket rejected the request or message. | Bucket | Scope | Applies To | Error | | - | - | - | - | | IP | IP address | HTTP request volume | HTTP `429` or `ip_rate_limited` | | Action | Perps account | Order placement and trade actions | `action_rate_limited` | | WebSocket message | IP address | Inbound WebSocket messages | `message_rate_limited` | | WebSocket subscription | WebSocket link | Active subscriptions on one socket | Per-channel subscription error when the subscription cap is exhausted | ## IP Rate Limits Every IP address gets **1,000 weighted tokens per minute**. Each HTTP request consumes tokens equal to its request weight. Use scoped requests when possible. Broad, unfiltered reads consume more of the IP budget than narrow reads. | Request Pattern | Weight | | - | - | | Lightweight reads | 1 | | Broad unfiltered reads | Up to 20 | | Order book depth 10 | 2 | | Order book depth 100 | 5 | | Order book depth 500 | 10 | | Order book depth 1000 | 20 | | Batch order actions | `1 + floor(n / 20)`, where `n` is order count | | Account orders by ID | 1 | | Account orders without ID | 10 | | Open orders by instrument | 1 | | Open orders without instrument | 20 | ## Action Rate Limits Every account has an action budget from its current limit tier. The default tier is **5,000 action tokens per minute** with an open-order cap of **1,000**. Action limits are account-scoped, not IP-scoped. Batching can reduce IP weight, but it does not reduce the number of order actions consumed. | Action | Action Cost | | - | - | | Place one order | 1 token | | Place 10 orders | 10 tokens | | Auto-cancel request | 10 tokens | | Open-order count | Limited by account tier cap | Legacy request-rate fields on limit-tier responses are not used for request-rate enforcement. Use the IP bucket for request volume and the action bucket for account trading activity. ## WebSocket Limits WebSocket connections have separate limits for connection count, active subscriptions, and inbound messages. | Limit | Scope | Value | | - | - | - | | Concurrent connections | IP address | 50 WebSocket connections | | Active subscriptions | Connection | 100 active subscriptions | | Inbound messages | IP address | 1,000 messages per minute | | Subscribe message | Message | 1 message token | | Unsubscribe message | Message | 1 message token | | Trade post message | Message | Same batch-size weighting as trade | | Other post messages | Message | 1 message token | ## Integration Guidance * Scope reads whenever possible. For example, request one instrument's open orders instead of all open orders. * Batch order placement when it reduces request volume, but do not expect batching to reduce action-token usage. * Treat `429`, `ip_rate_limited`, `action_rate_limited`, and `message_rate_limited` as retryable after backoff. * Track active WebSocket subscriptions per connection so reconnects do not accidentally exceed the subscription cap. * If you operate many users behind shared infrastructure, monitor IP usage separately from account action usage. # Read builder approvals, including retained revoked versions Source: https://docs.polymarket.com/api-reference/read-builder-approvals-including-retained-revoked-versions /api-spec/perps-openapi.json get /v1/account/builder-approvals # Get all relayer API keys Source: https://docs.polymarket.com/api-reference/relayer-api-keys/get-all-relayer-api-keys /api-spec/relayer-openapi.yaml get /relayer/api/keys Returns all relayer API keys for the authenticated address. Auth allowed: Gamma auth or Relayer API key auth (`RELAYER_API_KEY` + `RELAYER_API_KEY_ADDRESS`). # Check if a wallet is deployed Source: https://docs.polymarket.com/api-reference/relayer/check-if-a-wallet-is-deployed /api-spec/relayer-openapi.yaml get /deployed Returns whether the wallet at the given address is deployed onchain. Use the `type` query parameter to choose which wallet type to check: - Pass user's Polymarket `SAFE` address (default): Gnosis Safe (SignatureType `2`). - Pass user's Polymarket `WALLET` Deposit Wallet address: Deposit Wallet (signatureType `3`). See the [Deposit Wallet Guide](/trading/deposit-wallets) for setup. Omitting `type` is equivalent to `type=SAFE`. # Get relayer address and nonce Source: https://docs.polymarket.com/api-reference/relayer/get-relayer-address-and-nonce /api-spec/relayer-openapi.yaml get /relay-payload Fetches the relayer address and nonce for a specific user. Takes in the user's signer address and the type of nonce to retrieve. # Set Auto-Cancel Source: https://docs.polymarket.com/api-reference/set-auto-cancel /api-spec/perps-openapi.json patch /v1/trade/auto-cancel Set a dead man's switch that cancels all your open orders at the chosen time. The time must be at least 5 seconds in the future. Send 0 to clear an active schedule without triggering it; posting a new time replaces the current one. The switch fires once, then clears itself. It does not cover orders you place after it fires, so re-arm it if you still need protection. An account can trigger auto-cancel up to 1000 times per UTC day. After that, the API rejects new schedules with the error `auto_cancel_daily_limit_reached` until the next UTC day. Clearing a schedule is always allowed. To check the active deadline and today's trigger count, call [Get Auto-Cancel Status](/api-reference/get-auto-cancel-status). Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1**Action Weight: **10** # Test Connection Source: https://docs.polymarket.com/api-reference/test-connection /api-spec/perps-openapi.json get /v1/info/ping Test connection to the server. Request Weight: **1** # Update Isolated Margin Source: https://docs.polymarket.com/api-reference/update-isolated-margin /api-spec/perps-openapi.json patch /v1/trade/margin Adjust the signed collateral allocation for an existing isolated position. Use a positive amount to add margin and a negative amount to remove it. A removal may include unrealized isolated profit, but the resulting isolated position equity (allocation + unrealized PnL - settled funding) must remain at or above the position's current required initial margin. Both additions and removals are rejected while the account is in cross liquidation or the target isolated position is in isolated liquidation. An isolated liquidation on another instrument does not block this request. Cancel-only mode does not gate margin adjustments. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Gateway signature validation rejects a stale or future-skewed timestamp as `invalid signature`. A request that passes gateway validation can still fail sequencer freshness revalidation with `invalid_margin_signature_timestamp`. Reusing the exact signed request rejects with `signature_already_used`. Request Weight: **1**Action Weight: **1** # Update Leverage Source: https://docs.polymarket.com/api-reference/update-leverage /api-spec/perps-openapi.json patch /v1/trade/leverage Update leverage for an instrument. Each setting resolves independently: explicit per-instrument setting, then exchange-managed account-group default, then instrument maximum leverage and isolated margin. Group leverage is capped at the instrument maximum; a group cross default resolves to isolated on isolated-only instruments. Group defaults apply to new listings and never overwrite explicit settings. This operation sets both settings explicitly; GET /v1/account/config reports resolved values. Submit the current resolved pair to preserve it against later group changes. Leverage bounds and BLP locks also apply to unchanged values. Set your preferred leverage and margin mode after listing and before placing your first order. An unknown instrument ID (never listed) is rejected with `instrument_not_found`; a disabled instrument is not rejected merely because it is disabled. Margin mode can change only when the account has no position and no open orders in that instrument, including orders awaiting risk approval or execution. Close the position and cancel all orders before switching between isolated and cross margin. A position blocks a mode change with `position_exists`; open orders block it with `open_orders_exist`. Leverage changes within the same mode remain subject to leverage limits and margin checks. Leverage must be positive (`lev: 0` returns 400); exceeding the instrument maximum returns `invalid_leverage`. BLP-subscribed instruments reject leverage or mode updates with `blp_leverage_locked`; unsubscribe before changing the configuration. Requires proxy signature, see [proxy signing](/http/signing#2-proxy-signing). Request Weight: **1**Action Weight: **1** # Update Leverage for Multiple Instruments Source: https://docs.polymarket.com/api-reference/update-leverage-for-multiple-instruments /api-spec/perps-openapi.json patch /v1/trade/leverage/batch Update leverage for up to 100 unique instruments. Updates are processed sequentially and are not atomic. If only some responses arrive before the gateway deadline, missing item results use `internal_error`; whether those updates applied is unknown. If no responses arrive, the request returns 503 — retryable, since each update is an idempotent leverage/margin-type set that converges to the same value whether or not the original attempt was admitted. Each setting resolves independently: explicit per-instrument setting, then exchange-managed account-group default, then instrument maximum leverage and isolated margin. Group leverage is capped at the instrument maximum; a group cross default resolves to isolated on isolated-only instruments. Group defaults apply to new listings and never overwrite explicit settings. This operation sets both settings explicitly; GET /v1/account/config reports resolved values. Submit the current resolved pair to preserve it against later group changes. Leverage bounds and BLP locks also apply to unchanged values. Set your preferred leverage and margin mode after listing and before placing your first order. An unknown instrument ID (never listed) is rejected with `instrument_not_found`; a disabled instrument is not rejected merely because it is disabled. Margin mode can change only when the account has no position and no open orders in that instrument, including orders awaiting risk approval or execution. Close the position and cancel all orders before switching between isolated and cross margin. A position blocks a mode change with `position_exists`; open orders block it with `open_orders_exist`. Leverage changes within the same mode remain subject to leverage limits and margin checks. Leverage must be positive (`lev: 0` returns 400); exceeding the instrument maximum returns `invalid_leverage`. BLP-subscribed instruments reject leverage or mode updates with `blp_leverage_locked`; unsubscribe before changing the configuration. Requires proxy signature, see [Update Leverage](/perps/trading#update-leverage). Request Weight: **1 + floor(n / 20)**Action Weight: **1 / instrument** # Update your builder display name Source: https://docs.polymarket.com/api-reference/update-your-builder-display-name /api-spec/perps-openapi.json patch /v1/account/builder Sign with the owner wallet of an existing registered Perps builder using the standard signed-operation format: op.type is updateBuilder and op.args contains only name. No Admin credentials or trading proxy are needed. The signer determines the account; no address or version parameter is accepted. Names are trimmed and must contain 1 to 100 Unicode characters without control characters. Name edits use last-write-wins. Repeating the saved name succeeds. Disabled builders can edit their name. This operation does not change registration, enablement, the platform admission switch, approvals or fees. # List combo positions Source: https://docs.polymarket.com/api-reference/wallet/list-combo-positions https://data-api.polymarket.com/v2/openapi.json get /v2/positions/combos Combo positions for a user, in the standard `{ data, pagination }` envelope. Sorts: `FIRST_ENTRY` (default) | `ENTRY_COST` (+ `CURRENT_VALUE` alias) | `UPDATED`, each with `sort_direction`. `FIRST_ENTRY DESC` pages by the two-state keyset anchor `(first_entry_at_micros, combo_condition_id, outcome_index)` (NULL micros = the NULL tail); `UPDATED ASC` by the single-state `(updated_at_micros, …)` anchor; every other combination by an offset-shaped token. The cursor binds sort + direction and the resume ADOPTS them, so a replay cannot flip or re-sort the walk mid-stream. It binds the cohort; `user`/`status`/`condition`/`updated_after`/ `updated_before`; the same way: following a page needs nothing but `?user=` (always required here) and `?cursor=`, and restating a filter is allowed but must agree. Omitting one is not a contradiction, it is the absence of a choice; **contradicting** one is a 400, because the token's walk state only means anything against the cohort it was minted on. Incremental sync: `updated_after`/`updated_before` are an INCLUSIVE epoch-second window on `updated_at`. Without a `status` filter, either bound switches the response to the mirror-complete sync view (every live row, not only held ones); a `status` filter keeps its own visibility. The upper end is always capped by a short stability ceiling (~90s behind now) so a mirror never reads rows that may still move. Pair with `sortBy=UPDATED&sortDirection=ASC` for the stable sync order. A malformed `condition` combo condition id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state. # Live Data Channel Source: https://docs.polymarket.com/api-reference/websockets/live-data-channel Send JSON text frames tagged with op. The server answers every op with an ack or an error ack (never a close, except for policy breaches, close 4008, and an expired Access Token, close 1008) and pushes envelopes for subscribed channels. Limits per connection: 64 active (channel, filter) subscriptions, 20 subscribe or unsubscribe frames per second (a batch frame counts once), 64 KB per frame, 8 auth attempts. The server sends a WebSocket ping every 25 seconds; two missed pongs close 4002. Close codes: 4001 authentication failed on a presented credential, 4002 slow consumer or pong timeout, 4003 server draining (reconnect once after a uniform 0 to 10 s delay), 4008 policy violation (fix the client; do not reconnect blindly), which also closes a socket that neither passed authentication nor registered a subscription within the server's unengaged timeout (120 seconds by default, reason text unengaged) once that rule is enforced, 1008 authentication expired (a connection authenticated with an Access Token whose last accepted token expired, 30 second leeway included, with no renewal; refresh the token and reconnect). # Withdraw Source: https://docs.polymarket.com/api-reference/withdraw /api-spec/perps-openapi.json post /v1/account/withdraw Submit a signed withdrawal request. Requires EOA signature, see [EOA signing](/http/signing#1-eoa-signing). The `amount` field is the raw token amount including decimals (e.g. `"100000000"` for 100 USDC). This must match the `uint256 amount` value used in the EIP-712 `Withdraw` signature. The `ts` field is Unix seconds (not milliseconds) because the on-chain contract validates it against `block.timestamp`. It must also match the `uint64 ts` in the signed EIP-712 struct. Request Weight: **1** # Market Channel Source: https://docs.polymarket.com/api-reference/wss/market Public WebSocket for real-time orderbook, price, and market lifecycle updates. # Modify Orders Source: https://docs.polymarket.com/api-reference/wss/perps-modify-orders Perps WebSocket order modification by order ID. # Ping Source: https://docs.polymarket.com/api-reference/wss/perps-ping Perps WebSocket heartbeat. # Place Orders Source: https://docs.polymarket.com/api-reference/wss/perps-place-orders Perps WebSocket order placement. # Live Data Channel Source: https://docs.polymarket.com/api-reference/wss/polybolt PolyBolt WebSocket message reference for crypto, equity and TWAP reference prices. # Quoter Gateway Source: https://docs.polymarket.com/api-reference/wss/rfq Authenticated WebSocket for combinatorial RFQ quoters — receive requests, submit quotes, confirm last look, and track execution. # Sports Channel Source: https://docs.polymarket.com/api-reference/wss/sports Public WebSocket for real-time sports match results. # User Channel Source: https://docs.polymarket.com/api-reference/wss/user Authenticated WebSocket for real-time order and trade updates. # Authentication Source: https://docs.polymarket.com/api-reference/rfq-trades/authentication Sign every RFQ Trades Partner API request, and the trade status stream's handshake, with your partner API key. Every request is signed with your partner API key. Polymarket identifies your platform from the key and never from the request body, so a request can only read and create your own trades. The API key identifies your platform. It does not authorize moving funds: each counterparty authorizes its own side through its [order signature](/partners/rfq-trades#sign-the-orders). ## Your API Key Polymarket issues each partner an API key during onboarding: * **Key ID**: the public half, sent on every request. * **Secret**: a base64url-encoded string, shared once through a secure channel. Decode it to bytes before using it as the HMAC key. ## Sign a Request Sign every request except `GET /v1/time`: **1. Create the Request Timestamp** First, create a new Unix timestamp in seconds for each request. It must be within 30 seconds of server time, in either direction. See [Keep Your Clock in Sync](#keep-your-clock-in-sync). **2. Create the Request Signature** Next, concatenate the timestamp, the uppercase HTTP method, the request path, and the exact serialized body you send, with no separators. Then sign the result with your API key's secret, decoded from base64url: ```text theme={null} rfq_timestamp = method = "POST" request_path = "/v1/rfq-trades/validate" body = message = rfq_timestamp + method + request_path + body rfq_signature = urlsafeBase64WithPadding( HMAC-SHA256(base64UrlDecode(), message) ) ``` Where: * `request_path` is the URL path only. The query string is not signed. * `body` is the exact bytes sent. For a `GET`, it is empty. Serialize the body once and reuse that string for both the signature and the request, to avoid mismatches from key ordering or whitespace. * `rfq_signature` is base64url-encoded **with padding** (RFC 4648 §5). It is not hex and not standard base64. These helpers create the three headers for a request: ```typescript TypeScript theme={null} import { createHmac } from "node:crypto"; const keyId = process.env.RFQ_KEY_ID!; const secret = Buffer.from(process.env.RFQ_SECRET!, "base64url"); function signRequest(method: string, path: string, body = "") { const timestamp = Math.floor(Date.now() / 1000).toString(); const signature = createHmac("sha256", secret) .update(timestamp + method.toUpperCase() + path + body) .digest("base64") // Node's "base64url" digest drops the padding. .replace(/\+/g, "-") .replace(/\//g, "_"); return { "RFQ-Key-Id": keyId, "RFQ-Timestamp": timestamp, "RFQ-Signature": signature, }; } const body = JSON.stringify({ marketId: "253591" /* ... */ }); await fetch( "https://external-rfq-partner.polymarket.com/v1/rfq-trades/validate", { method: "POST", headers: { "Content-Type": "application/json", ...signRequest("POST", "/v1/rfq-trades/validate", body), }, body, }, ); ``` ```python Python theme={null} import base64 import hashlib import hmac import os import time KEY_ID = os.environ["RFQ_KEY_ID"] SECRET = base64.urlsafe_b64decode(os.environ["RFQ_SECRET"]) def sign_request(method: str, path: str, body: bytes = b"") -> dict[str, str]: timestamp = str(int(time.time())) message = timestamp.encode() + method.upper().encode() + path.encode() + body digest = hmac.new(SECRET, message, hashlib.sha256).digest() return { "RFQ-Key-Id": KEY_ID, "RFQ-Timestamp": timestamp, "RFQ-Signature": base64.urlsafe_b64encode(digest).decode(), } ``` > [accordion] Test vector > > Use these inputs to check your implementation: > > | Input | Value | > | - | - | > | Secret (base64url) | `MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY=` | > | `RFQ-Timestamp` | `1753185296` | > | Method | `POST` | > | Path | `/v1/rfq-trades/validate` | > | Body | `{"marketId":"253591"}` | > | Expected `RFQ-Signature` | `H-yYb9AqRHJ7ysPVyqTxdT83YWWUB8KvS4okVchrrcU=` | **3. Send an Authenticated Request** Finally, send the key ID, the timestamp, and the signature as headers. This request validates the terms of a trade: ```bash theme={null} curl -X POST "https://external-rfq-partner.polymarket.com/v1/rfq-trades/validate" \ -H "Content-Type: application/json" \ -H "RFQ-Key-Id: " \ -H "RFQ-Timestamp: " \ -H "RFQ-Signature: " \ --data '{ "marketId": "253591", "operation": "split", "price": "0.65", "shares": "1500000000", "parties": { "yes": { "maker": "", "signatureType": 3 }, "no": { "maker": "", "signatureType": 3 } } }' ``` Every authenticated request uses the same three headers: | Header | Value | | - | - | | `RFQ-Key-Id` | Your API key ID | | `RFQ-Timestamp` | The Unix timestamp used to build the signature | | `RFQ-Signature` | The signature from the previous step | ## Keep Your Clock in Sync `RFQ-Timestamp` must be within 30 seconds of server time, in either direction. Keep your clock NTP-synced. If your requests start failing with `401`, compare your clock with the server's: `GET /v1/time` needs no authentication. ```bash theme={null} curl "https://external-rfq-partner.polymarket.com/v1/time" ``` The response body gives the server time: ```json theme={null} { "serverTime": "2026-07-24T12:34:56Z", "timestamp": 1784896496 } ``` `timestamp` is the server time in Unix seconds, in the same format as `RFQ-Timestamp`. ## Authenticate the WebSocket The trade status stream is authenticated once, on the upgrade request. Sign it like any `GET`, with an empty body, and send the same three headers on the handshake: ```text theme={null} message = + "GET" + "/v1/ws/rfq-trades" ``` The stream then delivers only your own trades. See [Track the Trade](/partners/rfq-trades#track-the-trade). ## Authentication Errors A request that fails authentication returns `401` with code `authentication_failed`. Missing headers, a timestamp that isn't whole Unix seconds, and a timestamp outside the 30-second window each have their own message. An unknown or revoked key ID and a signature mismatch share one generic message, for security. # Get an RFQ Trade Source: https://docs.polymarket.com/api-reference/rfq-trades/get-trade api-spec/rfq-partner-openapi.yaml GET /v1/rfq-trades/{tradeId} Read a trade's current status, the source of truth for its outcome. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Overview Source: https://docs.polymarket.com/api-reference/rfq-trades/overview Explore the RFQ Trades Partner API for settling trades matched on your platform. ## APIs The RFQ Trades Partner API settles trades that your platform matched off Polymarket, over HTTP for requests and over WebSocket for trade status. Access is by invitation: see the [Institutional Overview](/partners/overview) for who it is for and how to request access. > [card] HTTP API > > `https://external-rfq-partner.polymarket.com` > > Validate, prepare, submit, and read RFQ trades. > [card] WebSocket API > > `wss://external-rfq-partner.polymarket.com/v1/ws/rfq-trades` > > Stream your trades' status changes. The testing environment's base URL is shared during onboarding, together with test API keys for that environment. ## Before You Integrate > [card] [Authentication](/api-reference/rfq-trades/authentication) > > Sign every request with your partner API key. > [card] [Trade Flow](/partners/rfq-trades) > > Find a market, then validate, sign, submit, and track a trade. > [card] [Errors](/partners/rfq-trades#errors) > > Read the error envelope and every rejection reason. # Prepare an RFQ Trade Source: https://docs.polymarket.com/api-reference/rfq-trades/prepare api-spec/rfq-partner-openapi.yaml POST /v1/rfq-trades/prepare Build both unsigned orders, their signing payloads, and the fee each side will pay. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Get a Market's Price Band Source: https://docs.polymarket.com/api-reference/rfq-trades/price-band api-spec/rfq-partner-openapi.yaml GET /v1/markets/{marketId}/price-band Read the price band an RFQ trade on this market must fall inside, for both outcome tokens. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Get Server Time Source: https://docs.polymarket.com/api-reference/rfq-trades/server-time api-spec/rfq-partner-openapi.yaml GET /v1/time Read the server clock that request timestamps are checked against. No authentication needed. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Submit an RFQ Trade Source: https://docs.polymarket.com/api-reference/rfq-trades/submit api-spec/rfq-partner-openapi.yaml POST /v1/rfq-trades Submit both signed orders. The trade is accepted as PENDING and executes asynchronously. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Validate an RFQ Trade Source: https://docs.polymarket.com/api-reference/rfq-trades/validate api-spec/rfq-partner-openapi.yaml POST /v1/rfq-trades/validate Run every check a submission of the agreed terms would run, without storing anything. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Auth Source: https://docs.polymarket.com/api-reference/wss/perps-auth Perps WebSocket authentication. # Auto Cancel Source: https://docs.polymarket.com/api-reference/wss/perps-auto-cancel Perps WebSocket dead man's switch updates. # Balances Source: https://docs.polymarket.com/api-reference/wss/perps-balances Perps WebSocket private balance updates. # BBO Source: https://docs.polymarket.com/api-reference/wss/perps-bbo Perps WebSocket best bid and offer updates. # Book Source: https://docs.polymarket.com/api-reference/wss/perps-book Perps WebSocket order book updates. The book channel pushes a full snapshot every 100 ms for each subscribed instrument. Subscribe to `book::{iid}` for the top 20 bid and ask levels, or opt in to `book::{iid}::50` for the top 50 levels per side. The 50-level form provides deeper order book visibility than the default snapshot. Each push replaces the prior state; it is not a delta. Levels in `data.b` are sorted from highest to lowest price, and levels in `data.a` are sorted from lowest to highest price. If a side has fewer levels than the selected depth, the snapshot includes all available levels on that side. > [!NOTE] > > Allowed depths are exactly 20 and 50. `book::{iid}::20` is an alias of > `book::{iid}`; updates for either subscription use the canonical > `ch: "book::{iid}"`. Updates for `book::{iid}::50` use > `ch: "book::{iid}::50"`. Other suffixes are rejected like any unknown channel > with `{"status":"err","error":"invalid channel"}` in the response `data` > array. You can subscribe to both depths on one connection, and each counts as > one subscription toward the per-connection limit. # Builder Fills Source: https://docs.polymarket.com/api-reference/wss/perps-builder-fills Live attributed fills for an authenticated Perps builder. # Cancel All Orders Source: https://docs.polymarket.com/api-reference/wss/perps-cancel-all Perps WebSocket cancellation of all open orders. # Cancel Orders Source: https://docs.polymarket.com/api-reference/wss/perps-cancel-orders Perps WebSocket order cancellation by order ID. # Cancel Orders by Client Order ID Source: https://docs.polymarket.com/api-reference/wss/perps-cancel-orders-coid Perps WebSocket order cancellation by client order ID. # Deposits Source: https://docs.polymarket.com/api-reference/wss/perps-deposits Perps WebSocket private deposit updates. # Fills Source: https://docs.polymarket.com/api-reference/wss/perps-fills Perps WebSocket private fill updates. # Funding Source: https://docs.polymarket.com/api-reference/wss/perps-funding Perps WebSocket private funding updates. # Klines Source: https://docs.polymarket.com/api-reference/wss/perps-klines Perps WebSocket candle updates. # Modify Orders by Client Order ID Source: https://docs.polymarket.com/api-reference/wss/perps-modify-orders-coid Perps WebSocket order modification by client order ID. # Notifications Source: https://docs.polymarket.com/api-reference/wss/perps-notifications Perps WebSocket private notification updates. # Orders Source: https://docs.polymarket.com/api-reference/wss/perps-orders Perps WebSocket private order updates. # Portfolio Source: https://docs.polymarket.com/api-reference/wss/perps-portfolio Perps WebSocket private portfolio updates. # Statistics Source: https://docs.polymarket.com/api-reference/wss/perps-statistics Perps WebSocket 24-hour statistics updates. # Tickers Source: https://docs.polymarket.com/api-reference/wss/perps-tickers Perps WebSocket ticker updates. # TP/SL Source: https://docs.polymarket.com/api-reference/wss/perps-tpsl Perps WebSocket private TP/SL lifecycle updates. # Trades Source: https://docs.polymarket.com/api-reference/wss/perps-trades Perps WebSocket public trade updates. # Update Leverage Source: https://docs.polymarket.com/api-reference/wss/perps-update-leverage Perps WebSocket leverage updates. # Update Leverages Source: https://docs.polymarket.com/api-reference/wss/perps-update-leverages Perps WebSocket batch leverage updates. # Update Isolated Margin Source: https://docs.polymarket.com/api-reference/wss/perps-update-margin Add or remove margin from an isolated Perps position over WebSocket. # Withdrawals Source: https://docs.polymarket.com/api-reference/wss/perps-withdrawals Perps WebSocket private withdrawal updates. # Trade Status Stream Source: https://docs.polymarket.com/api-reference/wss/rfq-trades WebSocket stream of your RFQ trades' status changes, authenticated once on the upgrade request. See the [RFQ Trades Partner API guide](/partners/rfq-trades) for the full trade flow. # Perps Changelog Source: https://docs.polymarket.com/changelog/perps Recent changes to the Polymarket Perps API and platform Notable changes to the Polymarket Perps API. **Nov 10, 2026** Reduce-only closes, tiered maintenance, and cancel-on-disconnect No endpoints or required request fields are removed. Check reduce-only closes and competition states before the deploy. Everything else is additive. **Changed** * **Reduce-only IOC closes.** A closing limit order now skips stale quotes beyond the favourable edge of the market's price band. A close that previously filled can return `ioc_no_fill`, or fill partly and end `ioc_expired`. The stale maker order stays open. Use fills and your remaining position to confirm a close; an accepted order is not proof that the position closed. * **Tiered maintenance.** Deployment alone keeps current margin rules. We plan to switch tiered maintenance on during this maintenance window, after a fresh safety check, and will confirm when it is live. Once activated, larger positions use maintenance requirements from the market's risk tiers. Maintenance amounts, liquidation prices, and warning levels can change; liquidation can move closer. A position stop loss beyond the new liquidation price can be refused with existing `tp_sl_trigger_past_liquidation`. Existing stops are not moved for you. Review maintenance cover and stop levels when activation is confirmed. * **Competition states.** `row_state` no longer returns `under_review`. Maker share and order rate no longer automatically put traders under review. Liquidity-reward entity members and operator-disqualified traders remain excluded. Stop relying on `under_review`; eligible traders appear as ordinary `live` / `provisional` rows. Rankings and projected prizes can change. * **Malformed WebSocket frames.** Concurrent sockets now return `invalid_request` where some bad frames previously returned `invalid request`, and retain a recoverable request ID. Update handlers that depend on that exact text. **Added** * **Largest positions.** Public `GET /v1/info/largest-positions` takes `instrument_id`, optional `limit` (default 10, maximum 100), and `offset`. Only the top 1,000 ranks are pageable. Returns account, side, size, entry price, notional, and unrealized PnL, ranked by notional. The insurance fund is excluded. Weight 5, or 1 on a cache hit; cached for 2 seconds. Invalid instrument or page bounds return `400`; a missing or stale mark returns `503`. * **Opt-in WebSocket cancel-on-disconnect.** Send a signed `cancelOnDisconnect` post with scope `session`, `account`, or `off`. Every new connection starts `off`; re-arm after reconnect. `session` covers qualifying orders created on that socket after arming. `account` cancels the account's open orders, chases, TWAPs, and odds orders across markets when the server detects disconnection. TP/SL and untriggered conditional orders remain. Prefer `session` for multiple sockets or fast reconnects: `account` scope can cancel quotes already placed by a replacement socket. Protection also fires during gateway deploys. Keep `autoCancel` armed: an abrupt gateway crash cannot send disconnect cancels. Armed sockets track at most 65,536 order IDs; if none can be pruned, new creates return `open_orders_limit`. Arm and disarm cost one WebSocket message and 10 account action units. **Clarified** * New and updated error identifiers are documented on [Errors](/perps/errors). `stock_split_unit_mismatch` is reserved for automatic stock splits, which stay disabled in production on this deploy. **Rollout** Order placement pauses during the window and cancels keep working. WebSocket connections drop when the gateway restarts; reconnect and resubscribe. After opting into cancel-on-disconnect, gateway restarts also cancel covered orders. **Nov 5, 2026** Address book on withdrawals, trading-key self-delete, and batched market reads No removed endpoints, routes, or fields. Two behaviour changes to check before the deploy: the withdrawal address book is enforced on withdrawals and internal transfers, and a trading key can now delete itself. Everything else is additive. **Changed** * **Withdrawals and internal transfers.** The Polymarket address book now applies to `POST /v1/account/withdraw` and `POST /v1/account/internal-transfer`. Owners who have enrolled in the address book can withdraw only to an active address-book entry, and cannot transfer to accounts outside their own account group. Transfers between their own accounts are unaffected. A refused destination returns `403` `withdrawal_not_allowlisted`. Every withdrawal looks up the address book. If that lookup fails, the request returns `503` `address_book_unavailable` with `Retry-After: 1`. Nothing was submitted. Retry `address_book_unavailable` with backoff. Treat `withdrawal_not_allowlisted` as final until the destination is added to the book. * **Trading-key self-delete.** `DELETE /v1/account/proxy` can now be signed by the key being deleted. The request format is unchanged. Self-delete is refused for 60 seconds after the key is registered or rotated: `422` `proxy_registration_newer_than_signature`. Wait, then sign a fresh request. A key with no recorded registration time is refused with `422` `proxy_registration_timestamp_missing`. The owner can still delete it. The owner deleting a different key works as before, immediately. **Added** * **Batched market snapshots.** `GET /v1/info/markets` takes `instrument_ids` (up to 50), `curated_list`, and `include=sparkline,totals`. It returns `{ markets, totals? }`. Request weight is 2. * **Unqualified competition traders.** Add `include_unqualified=true` to `GET /v1/info/competition/leaderboard`. Without the parameter, the output is unchanged. * **Portfolio sequencing fields.** `GET /v1/account/portfolio` adds `sequence`, and each position adds `sequence` and `share_unit_version` (`0` before any split). Accept unknown fields. * **Stock-split read surfaces.** `GET /v1/info/stock-splits`, authenticated `GET /v1/account/trade-history`, and the WebSocket channels `corporate-actions::` and private `trade-history`. All are empty until a split is scheduled. **Clarified** * New error identifiers for withdrawals, address-book lookup, and proxy self-delete are documented on [Errors](/perps/errors). **Rollout** Order placement pauses during the window and cancels keep working. Retail WebSocket connections drop when the gateway restarts; reconnect and resubscribe. **Oct 29, 2026** 24h statistics open price, per-market fees and funding, pre-IPO category No removed endpoints, routes, or fields, and no new error codes. One behaviour change to check before the deploy: the 24-hour `open_price` in market statistics now uses the mark price at the start of the 24-hour window. Everything else is additive. **Changed** * **24-hour statistics `open_price`.** `GET /v1/info/statistics` and the WebSocket `statistics::` / `statistics::all` channels now set `open` to the mark price at the start of the rolling 24-hour window. The rule is: the last mark in the ten minutes before the window start; else the first mark inside the window; else the previous trade-based open. Trade klines and volume are unchanged. Displayed 24h % change can move when this ships. If you computed change from the old trade-based open, update your calculation or labels. **Added** * **Per-market fee overrides.** `GET /v1/info/instruments` rows add `fee_override`. It is `null` when there is none; otherwise `{ start_time, end_time | null, tiers: [{ taker_fee_rate, maker_fee_rate }] }`, with times in milliseconds and rates as decimal strings. Inside the window, an account pays `tiers[its fee tier]` on that market. Outside the window, the normal schedule applies. A stored window can be scheduled or expired; its presence does not mean it is active. On fills, use the charged fee on each fill rather than recomputing from the standard schedule. * **Fees by instrument.** `GET /v1/info/fees?instrument_id=N` returns that market's effective fee schedule right now, plus its override. Without the parameter, the response is unchanged. A non-numeric or out-of-range `instrument_id` returns `400`. An unknown or unlisted market returns `404`. * **Per-market funding multipliers.** `GET /v1/info/instruments` rows add `funding_multiplier`. It is `null` when there is none; otherwise `{ multiplier, start_time, end_time | null }`. A funding period uses the multiplier when the period starts inside the window. The whole period uses it, with no proration. Existing funding caps still apply. Published funding rates and settlements already include it. * **`pre_ipo` instrument category.** The public category filter accepts `pre_ipo` (for example `GET /v1/info/instruments?category=pre_ipo`). Fees, funding, and risk settings are unchanged by the category. If your client rejects unknown enum values, add `pre_ipo` before any market is assigned to it. The Anthropic listing (`ANT`) will use this category with a fee override and separate liquidity and open-interest reward terms when operators activate it; that activation will be announced separately. * **SBE schema version 57.** Binary feed consumers must accept schema version 57 before the deploy. New message templates: `1028 SetPerpetualFeeSchedule` and `1029 SetPerpetualFundingMultiplier`. Funding messages append fields: `UpdatePerpetualFunding.fundingMultiplier` and `ChargeFunding.settlementFundingMultiplier`. Older funding payloads mean a multiplier of `1`. JSON REST and WebSocket clients need no change. **Clarified** * **OpenAPI spec.** `docs/http/http.json` documents the new instrument fields, the `instrument_id` selector on `/v1/info/fees`, the `pre_ipo` category, and the statistics `open` rule. There are no new WebSocket channels or order-status values. **Not Yet Active** * **Odds orders.** Placement stays disabled in production. The unreleased v2 stack makes no changes to your live integration. **Fixed** * **Tail latency during state snapshots.** Each periodic state snapshot (every \~1.5–2 minutes) no longer recomputes isolated-margin totals for every account. That recompute briefly stalled the event stream on every service at once and showed up as order-placement p99 spikes. On a replay of production traffic, a snapshot's processing cost fell from 27 ms to 0.002 ms with identical resulting state. Staging traffic differs from production, so the exact production improvement will be measured after the deploy. Fill pricing on markets without a fee override measured within 0.2% of the previous release. **Rollout** Order placement pauses during the window and cancels keep working. Retail WebSocket connections drop when the gateway restarts; reconnect and resubscribe. **Oct 27, 2026** Read-only WebSocket keys, ticker filtering, and competition market stats No removed endpoints and no removed or renamed fields on live routes. A new WebSocket error is `read_only_key`. Rate limits change for read-only WebSocket keys: separate budgets and at most four connections per account per gateway. WebSocket message shapes and live order statuses are unchanged; read-only sockets now refuse signed writes. No margin, liquidation, order-entry, or cancel rule changes. Check ticker filtering and total-PnL chart freshness before the deploy. **Changed** * **Read-only WebSocket keys.** Authenticating with a proxy labelled `read-only:…` fixes that socket's role as read-only, even if you retained its signing key. Every parsed post except `ping` and `auth` now returns `read_only_key` before signature verification. Refused posts still consume the message budget; once exhausted, the response is `message_rate_limited`. Private subscriptions remain available. All read-only keys of an account share a separate connection cap: four per gateway, or the account tier's cap if smaller. Auth-attempt, connection-open, and message budgets are separated from trading sockets; configured tier rates stay the same. Without an explicit WebSocket tier, read-only messages use a separate per-IP budget of 1,000/minute (burst 50), and read-only auth attempts are 16/minute (burst 16\). The initial auth frame still consumes the shared pre-auth IP budget (1,000/minute, burst 50). Keep signing keys free of the `read-only:` label, reconnect with the intended key, and consolidate read-only connections within the cap. Re-authenticating an already-bound socket does not change its role. * **Ticker filtering.** `GET /v1/info/tickers` now honours the previously ignored `instrument_id` query parameter. Omit filters if you need every enabled market; a supplied filter can now narrow the array or return `[]`. * **Total-PnL chart buckets.** `GET /v2/info/pnl` returns completed UTC minutes only. The effective end is the earlier of `end_timestamp` and now, rounded down to the minute, exclusive. Charts can lag by up to one minute plus storage delay; a window containing no completed minute can return no points. Allow for that lag in charts and freshness alerts. This endpoint is served by the live engine despite its URL prefix. * **Per-market mark bands.** Operators can configure a market's mark-to-index band. The pricer uses the tighter of that band and `1 / max_leverage`. Existing instruments retain the 50 bps (0.5%) default unless explicitly changed; the release does not widen any band automatically. The setting is admin-only and adds no field to public instrument responses. **Added** * **Ticker trader counts and symbol filter.** `GET /v1/info/tickers` adds numeric `long_count` and `short_count`. Each counts trading accounts with a nonzero net position on that side, including market makers and fund accounts; a zero position counts on neither side. Counts refresh with the existing two-second ticker cache. WebSocket tickers are unchanged. Optional `symbol` matches the canonical symbol exactly and case-sensitively. Unknown or disabled markets return `[]`. When both `symbol` and `instrument_id` are supplied, both must match. The response remains an array. * **Markets traded in competitions.** Competition standings and results add `instruments_traded` (distinct eligible markets with counted volume inside the competition window) and `top_instrument_ids` (up to three markets by counted unboosted volume, descending, ties by instrument ID). Both are absent for results stored before this release; `top_instrument_ids` is `[]` when there are no counted fills. **Clarified** * **OpenAPI spec.** `docs/http/http.json` documents the ticker counts and filter, the completed-minute total-PnL rule, and odds-only changes that are not live in production. `docs/ws/ws.json` is unchanged: no new live subscription channels or order-status values. Read-only-key refusal and budgets are documented on [Errors](/perps/errors#websocket-errors). **Not Yet Active** * **Odds orders.** Placement stays disabled in production and returns `404`. Odds-only changes add `GET /v1/account/odds-orders/history`, end reasons and filled/remaining quantities, and change the references response to `{references, markets}` with expanded field names. Five new odds-only domain errors are reserved: `not_eligible` (186), `blocked` (187), `no_capacity` (188), `held` (189), and `market_full` (190). They do not affect live trading. The unreleased v2 stack makes no changes to your live integration. **Rollout** No latency change is expected. The primary sequencer ends the rollout in the same availability zone as the gateways, as it has been since 22 October. Order placement pauses during the window and cancels keep working. Retail WebSocket connections drop when the gateway restarts; reconnect and resubscribe. **Oct 22, 2026** Builder stats, proxy management rules, and read-only key restrictions No removed endpoints, no removed or renamed fields, no new error identifiers, no rate-limit changes, and no WebSocket message changes. One behaviour change to trading-key (proxy) management applies from the deploy — read it if you create or delete proxies programmatically. **Changed** * **Proxy (trading key) management on `POST` / `DELETE /v1/account/proxy`.** Another account's main wallet can no longer be registered as a proxy. Create-proxy returns `400` `proxy is an account address`; a request that reaches the engine anyway is rejected with the existing `proxy_already_exists`. Registering your own main address as your own proxy still works. An account's main wallet always manages its own account's proxies, even if another account has listed that wallet as a proxy. The old `400` `must be signed by main address, not proxy` no longer fires in that case. A signer that owns no account and is only listed as some account's proxy is now accepted on create-proxy: it onboards a new account of its own (whitelist still applies) and registers the proxy there — never on the account that listed it. Consequence: if you sign create-proxy with a trading key instead of the main wallet, you now get a separate, empty account owned by that key instead of a `400`. Delete is unchanged: a signer with no account still gets `400` `must be signed by main address, not proxy`. Sign create-proxy and delete-proxy with the account's main wallet, as documented. Never with a trading key. * **Read-only API keys.** A proxy whose label starts with `read-only:` now gets `403` on `POST /v1/account/invite`, `POST /v1/account/referral`, `POST /v1/blp/enroll`, and `POST /v1/account/notifications/read`. Every private `GET` and the private WebSocket channels are unchanged. Only if you have labelled a trading key `read-only:…`: rename it or use another key. Self-service read-only key creation ships separately. * **Competition tie-break timestamp.** `GET /v1/info/competition/leaderboard` entries and `GET /v1/info/competition/account` gain optional `first_fill_at` (ms): the account's first counted fill; absent when unknown or when there are no counted fills. * **Order-path latency.** Since 20 October the order path carried an extra \~1 ms at the median; tail latencies were unaffected. This rollout removes it. If you alert on latency baselines, expect the median to drop back by about 1 ms after the window. **Added** * **Public builder statistics.** `GET /v1/info/builder-stats?address=…&period=…` is public, with no authentication. `period` is one of `1d`, `1w`, `1m`, `1y`, or `alltime` (rolling 24 h / 7 d / 30 d / 365 d, or all history). Returns `address`, optional `name`, `period`, `start_timestamp`, `end_timestamp` (ms), `as_of_sequence`, `user_count`, and `data[]` with one entry per `fee_asset`: `volume`, `exchange_fee` (signed; includes negative maker rebates), `builder_fee`, and `volume_by_asset[]` per market. Maker and taker sides count separately, zero-builder-fee fills included; disabled builders still report history. Cached 30 s; a miss costs 10 rate-limit units. * **Builder display names.** `GET /v1/info/builder` gains nullable `name` (live since 20 Oct, now part of this release). `PATCH /v1/account/builder` renames a registered builder — signed by the builder account's owner wallet, `op.type`: `"updateBuilder"`, `op.args.name` only; trimmed, 1–100 characters, no control characters; last write wins; repeating the saved name succeeds; disabled builders can rename. Nothing else about the builder changes. **Clarified** * **OpenAPI spec.** `portfolio.cumulative_funding` and `fee_tier` are now typed nullable in the HTTP and WebSocket specs. v1 still always returns a value for both; generated clients will see them as optional. The spec adds `GET /v1/info/builder-stats`, `PATCH /v1/account/builder`, and the new create/delete-proxy rules. **Not Yet Active** * **Odds orders.** `POST /v1/trade/odds-orders` returns `404` and `GET /v1/info/odds-references` returns an empty list. This release updates odds documentation and the odds-references fields (`acct_cap`, `class`, `underlying`); none of it affects you until odds orders launch, which we'll announce separately. **Rollout** Order placement pauses during the window and cancels keep working. Retail WebSocket connections drop once when the gateway restarts; reconnect and resubscribe. **Oct 20, 2026** Builder self-registration, total-PnL history, and recently-traded instruments No breaking changes to existing request or response fields. No authentication changes. **Added** * **Builder self-registration.** `POST /v1/account/builder` lets a builder register a display name without admin credentials. Sign with the owner wallet of an existing account using the standard signed-operation format and supply the name in `args.name`. Repeating registration with the same name is safe. A different name for an already-named builder returns `409` and is not overwritten. An admin-disabled builder receives `400` `builder_not_enabled`. * **Lifetime total-PnL history.** `GET /v2/info/pnl?address=…&interval=…` is public. Total PnL is equity (including unrealized) minus cumulative net capital: deposits, withdrawals, and internal transfers, including reward and referral payouts. Fees, funding, and builder income stay inside PnL, so do not subtract them again. A bucket whose capital history is unknown is returned as unavailable, not zero. * **Recently traded instruments.** `GET /v1/account/recently-traded` (authenticated) returns up to 10 perpetual instruments the account acted on most recently, newest first, each with the time of the latest action. Actions that count include placing, modifying, or filling an order (including closing a position), placing or cancelling a TP/SL, changing leverage or margin mode, and adding or removing isolated margin. Activity older than 90 days is not listed, and only currently enabled instruments are returned. The ranking builds up from activity after the release, so an account with no activity since then gets an empty list. **Changed** * **Portfolio coverage.** `GET /v1/account/portfolio` and public portfolio responses gain `coverage.collateral`. On v1 it always returns `"configured"`. * **Pricing status on tickers and index.** Ticker rows (REST and the `tickers` WebSocket channel) and index entries gain an optional `pricing_status` object describing the instrument's engine pricing mode. It is omitted for instruments outside the pricing protocol. * **Public trades paging.** `GET /v1/info/trades` accepts `cursor` and `sort` (`desc` default, `asc`) and returns a cursor for the next page. Every trade in a dense millisecond is now reachable. * **Public fills by market.** `GET /v1/info/fills?instrument_id=…` now returns only that market's fills. Before, the parameter was accepted and ignored. Filtered reads scan at most 250,000 rows; larger scans return `413` — narrow the time window. With `instrument_id`, the end time is capped at now. Without `start_timestamp`, the window starts 30 days before that end. With `instrument_id`, paging needs the returned keyset cursor; the legacy last-trade-ID cursor returns `400`. Unfiltered requests behave as before. **Fixed** * **Pathological JSON depth.** Request bodies and WebSocket messages nested more deeply than JSON parsing allows are now rejected as a normal parse error. Before, they could crash the connection's gateway process. No real client sends anything close to this depth. **Clarified** * **OpenAPI spec alignment.** `docs/http/http.json` now describes exactly the routes the production gateway serves. Removed: `/v1/info/executions` and other v2-only routes that were never served by v1. Added: `/v1/info/account-tiers` and `/v1/info/perps-whitelist`, which were missing. Fills, position-fills, and trades match production shapes again. Integers carry `x-js-safe-integer`; all v1 IDs fit in a JavaScript number. **Rollout** Order placement pauses during the window and cancels keep working, as usual. Retail WebSocket connections drop once when the gateway restarts; reconnect and resubscribe. **Oct 6, 2026** Concurrent WebSocket posts on the retail gateway No breaking changes for clients that match WebSocket responses by `id`. The rollout reconnected each active retail WebSocket connection once. **Changed** * **Concurrent WebSocket posts (retail gateway).** Signed posts that carry an `id` (order create, modify, cancel, cancel by client order id, leverage, and margin) now run up to 16 at a time per connection on `wss://ws.perpetuals.polymarket.com`, matching the behavior the MM gateway has had since Sep 1. Responses return in completion order: match them by `id`, not by position. Posts naming the same client order id or order id keep their send order. `cancelAll`, leverage, and margin updates act as connection-wide barriers. Posts without an `id` stay serial among themselves but are not ordered after earlier `id`-carrying posts still in flight. For strict ordering, await each response before sending the next post, or omit `id` on every post. **Oct 6, 2026** Leaderboard entries carry ROI No breaking changes for clients that ignore unknown fields; strict schema validators must add one required field. **Changed** * **Leaderboard entries gain a required `roi` field.** Every ranked entry and the optional `address=` row on `GET /v1/info/leaderboard` now carries `roi`: the window's return on investment as a fraction string (`"0.4527"` is 45.27%), computed as `pnl / max(100, starting_equity + max_net_deposits)`. `pnl` is the same value served on the row, so the two always agree; `starting_equity` is the account's equity just before the window start (0 for `all`); `max_net_deposits` is the peak cumulative net deposit during the window, never negative, so withdrawing profits cannot inflate the ratio. Values are rounded half-even to 6 decimal places with trailing zeros removed, and `"0"` when `pnl` is 0. Display-only: `sort_by` accepts no new values. **Sep 30, 2026** Statistics retain the current hour, and WebSocket klines publish the newest candle No breaking changes. Field names, wire types, and examples are unchanged; only 24-hour statistics values and kline selection move. **Fixed** * **Statistics now include the in-progress hour.** `GET /v1/info/statistics` and the WebSocket `statistics` channel previously dropped the current hourly candle whenever the rolling 24-hour window spanned 25 populated hours. The `klines` series stays oldest-first with at most 24 buckets, but now keeps the in-progress hour and drops the oldest populated bucket instead, so a 24-hour high or low derived from the returned buckets reflects the current hour. `open_price` still reports the open of the earliest populated candle in the full window — its start rounded down to the minute — even when that bucket is omitted from the returned series, and is `"0"` when the window has no candles. * **WebSocket `klines` subscriptions publish the newest populated candle.** The poller previously could emit an older hourly bucket; it now selects the newest populated candle in its lookback. REST klines pagination is unchanged. **Docs** * **`volume` was always quote-asset notional.** The statistics `volume` field description previously said "in contracts"; it is the sum of price times quantity over the window, as a numeric string. Values are unchanged. **Sep 29, 2026** Earlier WebSocket order replies and steadier matching under floods **Fixed** * **WebSocket order replies can arrive earlier.** The gateway now yields between broadcast batches, so the reply to an order you just sent is no longer held behind a long run of market-data frames. Payloads and notification IDs are unchanged. Correlate replies by request id; do not assume a burst of broadcasts always arrives before a later reply on the same socket. Public snapshot updates may spread across a few more batches in busy periods; content and cadence targets are unchanged. * **Matching stays responsive under order floods.** Order acknowledgement latency should stay flat during market-wide re-quote bursts. **Sep 27, 2026** Required fill fields, rewards date params, and instrument close-only statuses No breaking changes to order placement, cancellation, or authentication. Fill objects gain three required fields, and `GET /v1/account/rewards` now rejects `start_timestamp` / `end_timestamp` with `400`. Parsers should accept two new terminal order statuses and two new instrument fields for delisting. TWAP controls, position share-card snapshots, display symbols, and the builder-codes read surface are usable. TWAP order entry, chase limits, GTD, partial TP/SL closes, builder attribution, trailing stops, and synthetic pricing ship switched off. Expect one WebSocket reconnect and a short cancel-only window. **Changed** * **Fills gain three required fields.** Every fill on `GET /v1/account/fills`, `GET /v1/info/fills`, `GET /v1/info/trades`, and the WebSocket `fills` channel now includes `settlement` (boolean — `true` only for a position closed by instrument settlement), `builder_fee` (string, `"0"` until builder codes are enabled), and `total_fee` (string — exchange fee plus builder fee). `pnl` is unchanged: realized PnL before fees; subtract `total_fee` once for the net result. Strict schema validators must add the three fields. * **`GET /v1/account/rewards` no longer accepts `start_timestamp` or `end_timestamp`.** They were previously ignored; they now return `400` with `invalid start_timestamp` / `invalid end_timestamp`. Use `date`, `start_date`, and `end_date`. * **Two new terminal order statuses: `instrument_close_only` and `instrument_settled`.** Operators can put an instrument into close-only — orders that would increase exposure are rejected with `instrument_close_only`, resting increase-exposure orders are canceled with that status, reduce-only trading continues — and later settle and delist it. Remaining positions close at the trailing 30-minute time-weighted index average with no fee; remaining orders cancel with `instrument_settled`; further orders are rejected with `instrument_settled`. Settlement fills arrive as normal fills with `settlement: true`. Nothing is delisted by this release. Add the statuses now so strict parsers do not fail the first time it happens. * **Two new fields on `GET /v1/info/instruments`.** `close_only` (boolean, always present) and `settlement` (object with `sequence`, `timestamp`, `price`, `insurance_debit`; present only after settlement). Instruments may also carry an optional `display_symbol`; `symbol` is unchanged. * **SBE schema version 49.** Market-maker binary streams stamp schema 49\. All changes are appended fields or new messages; decoders that ignore fields beyond their compiled version keep working. Anything that asserts the schema version must accept `49`. * **`exp` on signed requests is now capped instead of rejected.** A value beyond now + 5 s is clamped to now + 5 s (previously refused with `command expiry too far in future`). A value at or before the server clock is still rejected with `400` `command expired`. Omitted still defaults to 5 s. * **Fee-tier volume can be aggregated across an account group.** Opt-in per group, set by us on request. Your 14-day volume for tier assignment becomes the group's combined volume. Nothing changes unless you ask for aggregation. **Fixed** * **Insolvent shells are settled automatically.** An account left with negative cash and no open positions is now settled against the insurance fund by the liquidator instead of sitting negative indefinitely. Backstop Liquidity Providers are never named for these. * **Fewer spurious sign-outs on the web identity path.** A stalled session-cookie verification is retried once instead of being cached as logged out. Proxy authentication is unchanged. * **`GET /v1/info/registered` on the public host** now adds `must-revalidate` to its existing cache lifetime. **Added** * **TWAP controls.** `DELETE /v1/trade/twaps`, `PATCH /v1/trade/twaps` (pause/resume), and `GET /v1/account/twaps` are live. Creating a TWAP (`POST /v1/trade/twaps`) returns `404` until we announce it. * **Position share-card snapshots.** `POST /v1/info/position-snapshots` returns active and historical position snapshots for an address; public, or authenticated if you send proxy headers. * **Builder codes — read surface only.** `approveBuilder`, `GET /v1/account/builder-approvals`, `/builder-earnings`, `/builder-earnings-summary`, `GET /v1/info/builder`, an optional `builder` `{address, fee_rate}` on order requests, and a private `builderFills` WebSocket channel are deployed. Attribution is not enabled: sending `builder` today returns `builder_codes_disabled`. * **Public market-data cache lifetime.** Public host `200`s carry `Cache-Control: public, max-age=…` matching the route's server-side cache window (live since Sep 22). Market-maker hosts send no cache lifetime. **Rollout** The market-maker gateway is briefly unavailable while its pods roll, so WebSocket connections to the MM gateway drop once and need to reconnect. The exchange is in cancel-only mode for the duration: cancels, liquidations, deposits, withdrawals, and funding keep working; new orders are rejected until the window closes. While cancel-only is on, a cancel that races an order's acceptance is answered `order_in_flight`; held cancels resume when the window closes. **Sep 21, 2026** Reversal margin at worst executable price, rounded volume strings, and daily reward rows No breaking changes to order placement, cancellation, authentication, or market data. Orders that flip a position now reserve margin at the worst executable price, so some reversals that used to pass can return `insufficient_margin`. Volume, notional, and candle strings are correctly rounded, and daily liquidity and open-interest reward rows appear after 12:05 UTC. Trailing stop-loss, TWAP, and good-till-date are in this build but not enabled. Expect one WebSocket reconnect and a short cancel-only window. **Changed** * **Reversing a position reserves more margin.** An order that, together with your resting and in-flight same-side orders, would take your position through zero is now margined for its closing leg at the worst price it could fill at — its own limit, or the trade price band edge for a market order — instead of at mark. Isolated: the closing leg reserves the loss from your entry to that executable price; a profitable close at that price reserves nothing extra. Cross: an adverse-side order larger than your position adds mark-to-executable distance across the whole order on top of normal initial margin. Two-sided quotes that straddle the mark add nothing. Orders that used to pass can now be refused with `insufficient_margin`, and `available_order_margin` plus withdrawable amount read lower while such a ladder rests. Non-reversing orders are unchanged. If you flip via market orders or aggressive limits, check `available_order_margin` first or size the reversal in two steps. * **Rounded volume, notional, and candle strings.** `high`, `low`, and `volume` on `GET /v1/info/klines` and `klines::*`; volume and notional on `GET /v1/info/statistics` and `statistics::*`, `GET /v1/info/exchange-stats`, `GET /v1/account/stats`, `GET /v1/info/leaderboard`, and referral history/children are now rounded to at most six decimals (`"23.923000000000002"` becomes `"23.923"`). `open` and `close` are unchanged. Numeric consumers see no change; byte-comparing cached strings will see diffs. Fee-tier volume inputs are not rounded. All-time leaderboard and referral-children volumes above roughly \$9B may still carry float artefacts. * **Daily reward rows arrive automatically.** `GET /v1/account/rewards` gains a new date row for liquidity and open-interest rewards shortly after 12:05 UTC, with `reward_distributed: false`. Distribution is unchanged. Poll after 12:05 UTC. Referral accrual is unchanged. **Fixed** * **Fewer order-path errors.** A stalled risk evaluator now releases and re-evaluates decisions in place instead of restarting. The post-deploy history/info probe runs from one process instead of every gateway pod, which removes the ClickHouse 5xx burst after a rollout. The MM REST pool keeps idle upstream connections open for 300 s instead of 60 s. * **Liquidations after an outage resume gradually.** Escalation and sizing clocks no longer advance while the risk evaluator is unavailable or an instrument is held, so an in-progress liquidation resumes with normal partial clips instead of a full-size close. * **Isolated-margin backing accounting is now in effect.** An isolated-position backstop transfers the position's live backing amount rather than its legacy margin amount. No request or response shape changes; recipients keep reading the transferred amount from `GET /v1/account/backstops`. * **Fee tier floors.** `fee_tier` on the portfolio and the fees you are charged now respect an account floor when Polymarket sets one. No account has a floor today, and a floor can only raise your tier. **Clarified** * **Market session categories.** The sessions page now lists `Weekend` and `Closed` alongside Regular, Premarket, Postmarket, Overnight, Halted, and Unknown, and drops `Disrupted`, which never existed in the engine. No instrument uses the new categories yet. **Rollout** The market-maker gateway is briefly unavailable while its pods roll, so WebSocket connections to the MM gateway drop once and need to reconnect. The exchange is in cancel-only mode for the duration: cancels, liquidations, deposits, withdrawals, and funding keep working; new orders are rejected until the window closes. While cancel-only is on, a cancel that races an order's acceptance is answered `order_in_flight`; held cancels resume when the window closes. **Sep 17, 2026** Held cancels during accept, 503 on engine timeouts, and reduce-only displacement No breaking changes to order placement, authentication, or market data. Cancels that arrive while an order is still being accepted now succeed, several cancel and account routes return `503` instead of `500` when the engine times out, a more aggressive reduce-only order can displace your own less aggressive resting reduce-only orders, and isolated-margin accounts get a stricter check when a ladder could reverse a position. Market makers should see fewer connection errors on the MM REST host. Expect one WebSocket reconnect and a short cancel-only window. **Changed** * **Cancel while an order is still being accepted now works.** A cancel that reached the matching engine a few milliseconds after `createOrders` returns used to be refused with `order_in_flight`. The cancel is now held and applied when the accept lands: success if the order was removed, or `order_already_terminal` if it filled or was rejected first. You will still see `order_in_flight` for an order in the taker-delay queue, while the account is being liquidated, or while the exchange is in cancel-only mode. Do not treat `order_already_terminal` as a failure to retry, and do not send the same cancel twice in that window — the second returns `order_not_pending_engine`. Ordinary resting-cancel/fill races still return `order_not_found`. * **Engine time-outs on cancel and account routes now return `503`.** When the engine does not answer in time, cancel, modify, leverage, margin, auto-cancel, withdraw, internal transfer, and delete-trading-key routes return `503` with `{"status":"err","error":"service_unavailable"}` instead of `500` `internal_error`. The WebSocket forms carry the same `error`. Treat it as retryable with a short backoff. Unlike other `503`s, this one does not prove the request was not applied — a retry may find the cancel already done. These routes are safe to repeat. `createOrders` and trading-key creation still return `500` on a time-out so a blind retry cannot duplicate an order. * **A more aggressive reduce-only order now cancels your own less aggressive resting reduce-only orders.** A restable reduce-only order priced more aggressively (higher bid or lower offer) displaces your strictly less aggressive resting reduce-only orders on that side, least aggressive first, until it fits. Displaced orders are reported with status `reduce_only_expired`. At equal prices the resting order keeps priority. If the new order still does not fit, the old trim/`reduce_only_invalid` behavior applies. IOC and FOK reduce-only orders are unaffected. A fired stop-loss can displace a resting take-profit on a GTC bracket. Displaced orders cancel attached TP/SL children too. Handle `reduce_only_expired` as a normal cancellation. * **Isolated margin: stricter check when a ladder could reverse a position.** On isolated-margin accounts, an order that could flip your position — counting resting and in-flight same-side orders — is now margined at the worst case across those orders. Orders that used to pass can now be rejected with `insufficient_margin`, and available-margin figures show the larger reservation while such a ladder rests. This mostly affects desks quoting far from the mark against a small position. Canceling the far leg or adding collateral clears it. Spurious `invalid_leverage` rejections when two same-side orders arrived a few milliseconds apart are gone. Cross-margin accounts are unaffected. * **Cancel-by-client-order-id wait is now about 100 ms** (was 50 ms), so a cancel racing its create is applied more often. If the order never appears, `order_unknown` arrives after about 100 ms. **Fixed** * **Far fewer connection errors on the MM REST host.** Per-server ceilings are doubled (per-IP in-flight 128 → 256) and MM edge connection pools stay warm. If you throttled yourself to about 128 in-flight requests per IP, you can raise that to 256. * **Funding after a service restart** no longer carries a previous, already-settled hour's premium into the new hour's rate. Steady-state funding is unchanged. **Added** * **`fee_tier` on the portfolio.** `GET /v1/account/portfolio` and the private WebSocket `portfolio` channel now include `fee_tier`, a zero-based index into the `tiers` array of `/v1/info/fees`. It is required, so clients with strict schema validation must add it. A tier change shows on the next portfolio push (every 5 s). * **Backstop history.** `GET /v1/account/backstops` lists transfers where your account received or provided backstop liquidity. Newest first, 100 per page, cursor pagination, 90-day default window. For a short time after the deploy it may return an empty list with `coverage.notes` containing `account_backstop_history not yet migrated`. * **Server identity for support.** Application-generated HTTP responses and WebSocket handshakes now carry an `x-pmp-pod` header, and a successful WebSocket auth reply includes `data.pod`. Log it alongside the `ref` of any error you report; do not route on it. Treat `data.pod` as optional during rolling deploys. * **Instrument logos.** Instrument objects on `/v1/info/instruments` and `/v1/account/favorites` may gain an optional `logo` object with `light` and `dark` SVG URLs. Instruments without a logo omit the key. **Clarified** * **Margin-mode changes.** Switching an instrument between isolated and cross requires no position and no open orders on that instrument. A position blocks the change with `position_exists`; open orders block it with `open_orders_exist`. Both codes already existed. * **Per-account limits** on signed actions per minute and open orders have been in force since May and are assigned by 14-day volume. Caps and usage are on `GET /v1/account/limits`. REST request rate is limited per IP, not per account. **Rollout** The market-maker gateway is briefly unavailable while its pods roll, so WebSocket connections to the MM gateway drop once and need to reconnect. The exchange is in cancel-only mode for the duration: cancels, liquidations, deposits, withdrawals, and funding keep working; new orders are rejected until the window closes. While cancel-only is on, a cancel that races an order's acceptance is answered `order_in_flight` as before; held cancels resume when the window closes. **Sep 15, 2026** Trading-key internal transfers within account groups; Retry-After on internal-transfer 503s No breaking changes. Trading keys can now move collateral between accounts in the same exchange-managed account group. Owner-signed internal transfers are unchanged. **Changed** * **Trading-key internal transfers within account groups.** A non-expired trading key registered to the source account can sign `POST /v1/account/internal-transfer` when source and destination share the same nonzero account group. The key must belong to the source account, and an ungrouped source or destination does not qualify. Owner signatures keep working regardless of groups, and withdrawals still require the owner key. An expired trading key on this route receives `proxy_expired` instead of `signer_does_not_match_account`. A gateway that cannot prove its state is fresh enough to authorize the transfer returns `503` `service_unavailable` with `Retry-After: 1` without submitting anything. * **Every handler-produced `503` on `POST /v1/account/internal-transfer` now carries `Retry-After: 1`.** Load-shed `503`s already did. A freshness or load-shed rejection happens before submission, but an engine response timeout can occur after submission. Retry after the header's delay using the exact original signed request; do not generate a new signature, salt, or timestamp. A replay rejection does not establish the original transfer outcome. **Sep 15, 2026** Gateway pod identity: x-pmp-pod response header and pod field on auth acknowledgements No changes to request shapes, authentication inputs, or existing response fields. Responses gain correlation metadata identifying the gateway pod that produced them, so your request logs can be matched against exchange logs. **Added** * **`x-pmp-pod` response header.** Every application-generated HTTP response — including errors and overload responses — and every WebSocket handshake response (the successful `101` upgrade and handshake rejections) carries the identity of the gateway pod that produced it. Browsers can read it through CORS. Responses to malformed HTTP carry no header, and a cached response keeps the identity of the pod that originally produced it. The value is correlation metadata only; pods are not addressable. * **`pod` in successful WebSocket auth acknowledgements.** The `data` object of a successful `auth` acknowledgement now includes `pod` with the same identity for the pod serving the connection. Auth failures and all other acknowledgements are unchanged. Treat the header and the field as optional: older pods omit them during a rolling deploy. **Sep 14, 2026** Non-paginated history routes reject cursor; 50-level book and leaderboard account-value sort No breaking changes to order placement, cancellation, authentication, or market data. Fourteen history and info routes now reject a `cursor` query parameter they used to ignore. Order-path latency should come back down after the September 8 increase, exact order lookups should return far fewer `503`s, and the index price for Hyperliquid-sourced instruments is corrected. Optional: a 50-level order book channel and an account-value sort on the leaderboard. Expect one WebSocket reconnect on the market-maker gateway during the maintenance window. **Changed** * **Sending `cursor` to a non-paginated route now returns `400`.** These routes page by time window, never by cursor, and never returned one. Until now a `cursor` key on them was silently ignored and you got the first page. After this release any value — including an empty `cursor=` — is refused with `400` and the error `invalid cursor`: `GET /v1/account/deposits`, `/v1/account/equity`, `/v1/account/funding`, `/v1/account/internal-transfers`, `/v1/account/pnl`, `/v1/account/referral-history`, `/v1/account/rewards`, `/v1/account/withdrawals`, `GET /v1/info/equity`, `/v1/info/funding`, `/v1/info/klines`, `/v1/info/mark-history`, `/v1/info/pnl`, `/v1/info/trades`. If your client has a generic pagination helper that forwards `cursor` to every history call, stop it from doing so on these routes. Routes that do paginate by cursor (fills, orders, trades history, referral children, favorites) are unchanged. * **Leaderboard `account_value` is now a cached census value.** `GET /v1/info/leaderboard` entries and address lookups already carried an `account_value` string. It is now produced by a background census that advances by at most 8,192 accounts per 60-second tick, so on a large population a full pass spans several ticks and the value can be a few minutes old. When an account's unrealized PnL cannot be computed (a stale mark on one of its instruments), the field shows collateral value only, the same way `/v1/info/portfolio` does. Treat it as indicative equity. Use the response timestamp to judge freshness. PnL and notional rankings, and every request parameter, are unchanged. * **Open-interest reward floor.** OI rewards for reward dates from 2026-09-07 require a combined entity daily-average gross open interest of at least \$5M (previously \$1M). Earlier dates keep the \$1M floor if recomputed. Reward periods run 12:00 UTC to 12:00 UTC and are labeled by their end date, so the first period under the new floor ended 2026-09-07 12:00 UTC. The 6% APR, the daily averaging, the uncapped reward math, and the `/v1/account/rewards` response shape are unchanged. The release aligns the API documentation with terms that have applied since that period. **Fixed** * **Index price for Hyperliquid-sourced instruments.** On instruments whose index is sourced from Hyperliquid, the index lane was consuming the venue's `markPx` (a perpetual mark, carrying that venue's basis) instead of its `oraclePx`. It now consumes `oraclePx`, and the mark lane continues to consume `markPx`. The effect is largest where the two diverge most — WTI, Brent, and other commodity and equity markets, where the basis ran roughly 60–70 bps. Expect the published index on those instruments to step to the corrected value on deploy; mark, funding, and margin all follow the index, so a small one-time move in funding rate on those markets is normal. No request or response shape changes. * **Lower, steadier order and cancel round-trip times.** Since the September 8 release, market-data publication sat on the same path that sequences orders and stopped coalescing requests, which several desks measured as higher REST latency. This release moves publication off that path and batches requests that arrive together. Order-path latency should come back down and stay flatter under load. * **Fewer `503`s on exact order lookups.** An exact `GET /v1/account/orders` lookup by `order_id` or `client_order_id` that the gateway does not hold in memory now opens with a single combined existence probe instead of a full aggregate on every miss. If your client polls for client order ids in bursts, particularly ids the exchange never received, you should see far fewer `503` responses on this route under load. Results are unchanged. * **Fewer read errors right after a deployment.** Leaderboard data is now rebuilt with a bounded, shared query, which removes the source of the brief 5xx burst on public read routes that followed the last deployment. **Added** * **50-level order book over WebSocket.** Subscribe to `book::{iid}::50` for the top 50 levels per side, pushed every 100 ms like the existing channel. `book::{iid}` and `book::{iid}::20` are the same subscription and keep delivering the top 20 exactly as today; frames for both carry the canonical `ch: "book::{iid}"`, while frames for the 50-level form carry `ch: "book::{iid}::50"`. Frame shape is otherwise identical, and each push is a full snapshot, not a delta. Any other suffix — including `::100`, `::0`, and `::050` — is refused at subscribe time with `invalid channel`. You can subscribe to both depths on one connection; each counts as one subscription toward the per-connection limit. * **Web app favorites.** The web app's favorites feature turns on with this deploy; it uses the Polymarket web session cookie and does not affect trading integrations. * **Leaderboard sorted by current account value.** `GET /v1/info/leaderboard?sort_by=account_value` ranks the accounts active in the requested window by their current equity. An account whose equity cannot be computed has no rank under this sort (a collateral-only display value does not establish one), and `total` counts only accounts with a published value. Right after a deployment each API server answers this sort with `503` for a few minutes while its first census completes — back off and retry; PnL and notional sorts stay available throughout. **Clarified** * **`order_not_found` is returned only when canceling a TP/SL trigger** by an id that does not exist or is not yours. Canceling a regular order never returns it: an unknown or foreign order id gives `order_not_in_orderbook`, and a client order id that does not resolve gives `order_unknown`. * **Withdrawing an asset that does not count as collateral.** Such a balance sits outside every margin calculation, so withdrawing it cannot itself trigger a margin call. If your account carries a cross-basis shortfall, the balance is treated as recoverable value backing that shortfall. For a priced asset, the shortfall is subtracted from the combined value of every priced non-collateral asset you hold — not just the one you are withdrawing — and what remains is converted back at price and capped at your balance, so the amount released can be less than you expect if other non-collateral holdings draw on the same shortfall. For an unpriced asset there is nothing to value a partial hold-back at, so the request is refused with `insufficient_balance` until the shortfall clears. The same all-or-nothing refusal applies when the shortfall itself cannot be established, for example when a cross position has no mark price. This rule is not new; it is now written down on the margin docs page. **Not Yet Active** * **Isolated-margin backing accounting** (backstop liquidity providers and the insurance fund). Once activated, an isolated-position backstop transfers the position's live backing amount rather than its legacy margin amount to the recipient. No request or response shape changes; recipients keep using the amount actually transferred. We will announce the activation date. * **Account groups for self-trade prevention**, the stricter liquidation-stop check, and per-account rate-limit tiers remain inactive. Nothing changes unless you ask to be grouped, and we will notify you before enabling tiers. **Rollout** The market-maker gateway is briefly unavailable while its pods roll, so WebSocket connections to the MM gateway drop once and need to reconnect. The exchange is in cancel-only mode for the duration: cancels, liquidations, deposits, withdrawals, and funding keep working; new orders are rejected until the window closes. This release also moves the matching engine's sequencer to the new build, so plan for one reconnect and a short cancel-only period. **Sep 8, 2026** Cancel-by-coid grace window, stricter filter validation, and faster rejected-order lookups Cancel-by-coid grace window, stricter filter validation, and faster rejected-order lookups. No breaking changes. **Added** * **`GET /v1/info/exchange-stats`.** Public, unauthenticated exchange-wide statistics for all pUSD-quoted perpetuals: matched USD volume, gross maker plus taker fees, and one-sided open interest with its sample timestamp. Half-open window `[start_timestamp, end_timestamp)` up to 31 days. Request weight 10, or 1 when served from cache; responses cached 5 minutes. * **`instrument_id` filter on `GET /v1/account/fills`.** Optional, returns only that instrument's fills. Window, cursor, and sort are unchanged. **Changed** * **Cancel-by-coid waits for a racing create.** A cancel by client order id arriving just before its create is sequenced previously returned `order_unknown` and needed a retry. The gateway now waits up to 50ms of sequencer time for the create to appear and applies the cancel if it does — which covers the full range of races we see in production, where the create lands 10–49ms behind the cancel. You'll see fewer `order_unknown` rejects, and you can drop client-side retry loops for the sub-50ms case. A `coid` that never becomes an order still returns `order_unknown`, but up to 50ms later than before, so reject latency on those rises accordingly. In a batch mixing a racing `coid` with a never-created one, the racing cancel is forwarded when the batch resolves rather than the instant its create lands. Single-`coid` cancels, cancels of already-live orders, and `order_already_terminal` are unaffected. * **`GET /v1/account/internal-transfers` accepts a direction filter.** `direction=in` or `direction=out`, relative to your account. Any other value now returns `400` with `unknown variant …, expected in or out`; previously an unrecognized value was silently ignored. Omitting the parameter changes nothing. * **Unsupported WebSocket kline intervals are refused at subscribe.** `klines::::` accepts `1s` `1m` `5m` `15m` `30m` `1h` `4h` `6h` `12h` `1d` `1w`, unchanged. Any other interval now returns `{"status":"err","error":"invalid channel: …"}` instead of acknowledging the subscription and then never delivering data. If your client treats a non-ok ack as fatal, subscribe only with supported intervals. **Fixed** * **Exact order lookups for rejected orders no longer shed under load.** Looking up a single order by `order_id` or `client_order_id` where risk rejected it before it reached the book is now answered from the gateway's recent-outcome memory rather than a database read. Same empty page, faster, and no longer returns `503` when the gateway is busy. If you poll for a rejected order's status, this removes those `503`s. One caveat, and it only applies if you reuse client order ids. Where a `client_order_id` was booked earlier, then reused and rejected, a lookup by that id can return `[]` for up to 120 seconds after the rejection even though the earlier order still exists in history. Don't treat an empty page inside that window as proof the earlier booking never happened — look it up by `order_id` instead. Clients that never reuse client order ids are unaffected. **Not Yet Active** * **Favorites API.** `/v1/account/favorites` is a Polymarket web-session endpoint for the web app's market selector. Returns `404` until enabled and is not relevant to trading integrations. * **Stricter liquidation-stop check.** Operator-enabled later. A liquidation stop will be refused unless the account is provably recovered at the moment it applies, so an account may stay in the liquidating state slightly longer during adverse price moves. No API shape change. * **Per-account rate-limit tiers.** Still inactive, carried over from an earlier release. We'll notify you before enabling. Default tier when live: 5,000 actions/min with burst 250, 1,000 WS messages/min, 1,000 open orders, 30 connects/min. **Rollout** The market-maker gateway rolls pod by pod during the window, so MM WebSocket connections will drop once and need to reconnect. The exchange is in cancel-only mode for the duration: cancels, liquidations, deposits, withdrawals, and funding continue; new orders are rejected until the window closes. **Sep 4, 2026** OI reward eligibility threshold increased to \$5M The OI reward eligibility threshold is now $5M of combined daily average gross OI per rewards entity, up from $1M. Accounts without an entity mapping qualify independently. The 6% APR rate and calculation on the account's full daily average gross OI across all instruments are unchanged. **Sep 2, 2026** Exchange statistics endpoint added Added `GET /v1/info/exchange-stats`, a public endpoint returning aggregate statistics for all pUSD-quoted perpetual markets over a required `[start_timestamp, end_timestamp)` window of up to 31 days: matched USD volume, gross positive maker and taker trading fees (rebates, incentives, and referral payments excluded), and one-sided open interest in USD notional with its sample time, taken from the latest complete sample before the window end — both null when no complete sample is available. Responses are cached for five minutes; a request costs weight 10, and a request served from cache costs 1. **Sep 1, 2026** Concurrent WebSocket posts and HTTP overload shedding Concurrent WebSocket posts and HTTP overload shedding. No breaking changes. **Added** * **Concurrent WebSocket posts (MM gateway).** Up to 16 signed writes per connection now run concurrently. Posts touching the same order, by client order id or engine order id, still reach the engine in send order. `cancelAll` and leverage or margin updates act as barriers. Responses can arrive out of order across different orders: send a unique `id` and match on it. Ordering is per connection. * **HTTP overload shedding.** Requests over the server or per-IP concurrency limit are shed before execution: `503`, `{"status":"err","error":"service_unavailable"}`, with `Retry-After`. Batch routes return a one-element array. The request did not execute, so retry with backoff. The per-IP cap is 128 in-flight on the MM API against healthy usage under 10. Tell us if you NAT many bots through one IP. **Changed** * **Cancel by client order id.** A recently completed order now returns `order_already_terminal`, not `order_unknown`. A cancel racing its own order's creation waits briefly (\~1ms, capped at 150ms) and succeeds instead of answering `order_unknown`. TP/SL `coid`s are unchanged. * **Funding.** Funding for a just-closed window now settles even if you flattened or flipped just before settlement was sequenced; previously the window could be skipped for the whole instrument. Drop any assumption that a closed position means no funding. * **Reduce-only market closes.** These now fill only within the price band around the last mark. Expect partial fills or `ioc_no_fill` on a dislocated book. Quotes resting far outside the band will no longer be hit by them. * **Balances.** REST `value` is now the USD equivalent at the asset's index price, not the raw amount: same for pUSD, different for other collateral. `balance` uses asset-native decimals, matching WebSocket. * **`429` shape on modify routes.** `PATCH /v1/trade/orders` and `PATCH /v1/trade/orders-coid` return the one-element array instead of a bare object. * **Idle connections.** HTTP connections with no complete header for 120s are closed. A per-pod ceiling resets excess connections rather than serving a `503`. **Fixed** * **Deposits.** Many-per-transaction deposits credit reliably; a batching edge case could previously delay or drop credits. * **Price continuity.** The index survives a full outage of one oracle source, with marks, margin, and funding still updating. Don't assume prices freeze when a provider goes down. * **Referrals.** Concurrent binds for one account resolve to one winner; the loser gets HTTP `400`, `account already has a referrer`. **Not Yet Active** * **Pending-modify expiry.** A modify left risk-undecided for 200ms will be swept: the order stays open and you retry with a new `modify_id`. We'll notify before enabling. * **Per-account rate-limit tiers.** Still inactive. We'll notify before activation. **Rollout** The public gateway fleet moves to dedicated hardware during this window. WebSocket connections drop once; standard reconnects cover it. **Aug 24, 2026** Response timestamps, rejection references, and liquidation metadata Rejections and acknowledgements now carry inspectable timing, every WebSocket push is stamped with engine event time, and backstop liquidation fills include optional metadata. **Added** * **Timestamps on rejections.** All rejection responses — orders, cancels, modifies, withdrawals, and transfers — now include `ts` (engine decision time), `arts` (gateway arrival time), and `ref` (a support reference for locating the server-side trace). All three are nullable, except on cancel rejections where `ts` is always present. * **Timestamps on acknowledgements.** Accepted create-order items now include `ts` and `arts`. Accepted cancels, which already carried `ts`, now also include `arts`. * **Event time on every WebSocket push.** Push envelopes across all channels now carry `ets`, the engine event time for the update. This field is always present and is the one to use for event-time analysis. * **Liquidation metadata on fills.** Fills and trades from backstop liquidations carry an optional `liquidation_details` object with `mark`, `method`, and `liquidated_user`. Available on private WebSocket fills, `GET /v1/account/fills`, position fills, and public trades. The anonymous trade tape omits `liquidated_user`. Ordinary order-book liquidations do not carry this object yet — only backstop liquidations, where `method` is `backstop`. The object is absent where metadata was not captured. **Changed** * **WebSocket envelope `ts` is now server send time.** Push frames previously stamped the envelope `ts` with internal stream time, which could lag actual send time on quiet channels or during catch-up. Engine event time is now carried separately in `ets`. Per-item `ts` inside `data` is unchanged. If you measure latency as `local_receive − envelope_ts`, your values will decrease after this release. Earlier measurements included server-internal lag and are not comparable — re-baseline at the deploy timestamp. * **Backstop liquidations publish fills to both parties.** The liquidated account and each absorbing account now receive private WebSocket fills for backstop liquidations. The liquidated account previously received no fills event. These fills are system-generated, with order id `0` and no client order id, matching the shape of ADL fills. * **`order_already_terminal` replaces `order_not_in_orderbook` for terminal orders.** Canceling an order that has already filled or canceled now returns `order_already_terminal` to the order's owner. Unknown and foreign order ids continue to return `order_not_in_orderbook`. Treat unrecognized error codes as non-retryable. **Fixed** * **`FillsUpdate.data` and `TradesUpdate.data` are documented as arrays.** The specification previously described objects. The wire format is unchanged; regenerate your client/bindings if you generated the object form. | Field | Meaning | | - | - | | Request `ts` | Client send time | | `arts` | Gateway arrival time | | Item `ts` | Engine decision time | | Envelope `ts` | Server send time | | `ets` | Engine event time | **Aug 16, 2026** Current position fills endpoint added Added `GET /v1/info/position-fills`, a public endpoint returning every fill in a registered account's current open position cycle for one instrument. A cycle begins when the position opens from flat or flips direction, and a multi-leg flip stays in one cycle. Pages of up to 100 fills are linked by an opaque `cursor` returned alongside the data; the cursor is validated against the live position on every page and returns `400` if the position changed mid-pagination. `GET /v1/account/fills` has returned the same opaque `cursor` field since Jul 24 — passing the last fill's trade ID as `cursor` still works there. **Aug 14, 2026** Equity and PnL history honour the requested interval `GET /v1/account/equity` and `GET /v1/account/pnl` now bucket the returned series by the `interval` query parameter. Previously the parameter was validated but ignored: every accepted value returned the same fixed-granularity series (per minute for equity, per hour for PnL), and long windows were truncated at 1000 rows instead of aggregated. Each equity point is now the last sample in its interval bucket; each PnL point is the PnL realized inside its bucket — not a running total — and empty buckets are omitted. Buckets are aligned to the Unix epoch, points keep real sample timestamps, and the 1000-entry cap now counts buckets, so a coarser interval covers a longer window before `more` is set. Responses for the finest intervals (`1m` equity, `1h` PnL) are unchanged. **Aug 13, 2026** Deposit and withdrawal history amounts are always decimal token units `GET /v1/account/deposits` and `GET /v1/account/withdrawals` now serialize every `amount` (and withdrawal `fee`) in decimal token units, e.g. `"10"` for 10 pUSD. Previously, deposit rows in `pending` or `removed` status reported raw on-chain base units (`"10000000"` for the same 10 pUSD), and pending withdrawal rows could serve base-unit amounts and fees as well, so rows for the same transfer disagreed on units across statuses. Clients that divided pending amounts by `10^decimals` to compensate must drop that conversion. Confirmed rows and the WebSocket `deposits` and `withdrawals` channels are unchanged — they were already decimal. Signed operation inputs (`POST /v1/account/withdraw`) still take base-unit amounts matching the EIP-712 signature. **Aug 11, 2026** Fill history flags maker fills executed under liquidation `GET /v1/account/fills` and account trade history previously reported `liquidation: false` on every maker fill, even when the maker's own account was under liquidation on the instrument — while the WebSocket `fills` channel already reported `liq: true` for the same fill. The two surfaces now agree: any maker or taker fill on an instrument in the account's active liquidation scope reports `liquidation: true`. Rows written before the change are unaffected. Such maker legs are also excluded from leaderboard win counts. **Aug 10, 2026** Fills gain an adl flag; liq no longer set on ADL counterparty legs Fill entries now carry a required boolean `adl` field on both the WebSocket `fills` channel and `GET /v1/account/fills`, set on both legs of an auto-deleveraging match. Behavior change: the counterparty leg of an ADL match previously reported `liq: true` on the WebSocket `fills` channel; it now reports `liq: false`. `liq` marks only the leg whose own position is being liquidated. Clients that detect forced closes via `liq` alone will no longer see ADL counterparty fills — check `adl` as well. **Aug 8, 2026** Position deleveraged notification added Added the `position_deleveraged` notification, sent to the counterparty of an auto-deleveraging match when its profitable position is closed or reduced to settle a liquidation on the other side. Delivered on the WebSocket `notifications` channel and in the notifications history. **Aug 7, 2026** Exchange info reports engine version and cancel-only state `GET /v1/info/exchange` now includes `engine_version`, the engine release version of the build serving the response. The response also documents `cancel_only`, which reports whether the exchange is in cancel-only (maintenance) mode; the flag has been returned since maintenance mode shipped on Jul 15. **Aug 6, 2026** Portfolio margin summary includes available order margin The portfolio response and `portfolio` WebSocket channel now include `margin.available_order_margin`: the collateral available for additional order initial margin after existing exposure, open orders, orders and isolated-margin additions awaiting risk processing, and pending withdrawals or transfers. **Jul 6, 2026** Cancel all orders added Added `DELETE /v1/trade/orders/all` to cancel all open orders in one request, optionally scoped to a single instrument. Available in the SDKs as `cancelAllOrders` (TypeScript) and `cancel_all_orders` (Python). **Jun 11, 2026** Cancel responses include order IDs Cancel responses now include `oid` and `coid` fields. **Jun 10, 2026** Taker delay added for immediately matching orders Added a 20ms taker delay for orders that immediately match on entry. **Jun 9, 2026** Reduce-only orders added Added the reduce-only field to order submission and order updates. **Jun 8, 2026** Auto-cancel and rate-limit updates
  • Added `PATCH /v1/trade/auto-cancel` to arm or clear a dead man's switch that cancels all open orders at a specified time.
  • Added `GET /v1/account/auto-cancel` to check the current auto-cancel status, trigger count, and daily reset time.
  • Auto-cancel is limited to 1000 triggers per UTC day per account.
  • Added `updateLeverage` and `autoCancel` WebSocket post messages.
  • `portfolio` and `balances` WebSocket channels no longer push updates on every order or fill, only periodically.
  • Rate limit error messages now distinguish between `ip_rate_limited`, `action_rate_limited`, and `message_rate_limited`.
# Predictions Changelog Source: https://docs.polymarket.com/changelog/predictions Important changes to Polymarket prediction markets, including the CLOB, APIs, web application, and mobile applications. **Nov 16, 2026** Upcoming: DeFi fee and rebate changes ## Upcoming DeFi Fee and Rebate Changes **Effective November 20, 2026 at 23:59 UTC**, Polymarket DeFi on [Polymarket.com](https://polymarket.com) will update its fees and rebates: * Taker fee coefficients will change by category. Geopolitics stays fee-free. * Taker rebate rates for Gold, Platinum, and Diamond will decrease. Obsidian will stay at 50%, and a new Onyx tier will pay 60%. The Bronze and Silver tiers, category multipliers, and one-time level-up bonuses will be removed. Price weighting stays. * Maker rebates will move from daily market-wide pools to volume tiers paying 3%, 7%, 10%, or 15% of the taker fees generated by eligible maker fills. Liquidity rewards remain unchanged. See the [full November fee and rebate changes](/programs/fee-and-rebate-changes-november-2026) for category rates, tier thresholds, and volume calculations. Current rules apply until then. **Nov 16, 2026** PolyBolt: Chainlink API keys and required providers * From November 30, 2026 at 00:00 UTC, price subscriptions require an explicit provider. Subscriptions served by Chainlink, including TWAP, also require your Chainlink API key. See [PolyBolt authentication](/api-reference/live-data/overview#send-your-chainlink-api-key). > [!NOTE] > > Request a Chainlink API Key using [this form](https://institutional.polymarket.com/request-chainlink-api-key). **Nov 12, 2026** Polymarket Protocol V2 support in Python and Rust * [Python `py-clob-client-v2 1.2.2`](https://pypi.org/project/py-clob-client-v2/1.2.2/) and [Rust `polymarket_client_sdk_v2 0.9.1`](https://crates.io/crates/polymarket_client_sdk_v2/0.9.1) add support for signing orders for Polymarket Protocol V2 markets on Polygon Amoy Testnet (chain ID `80002`). * The Python CLOB client remains deprecated. Follow the [unified SDK migration guide](/migrate/clob-sdk-to-unified-sdk) to move to `polymarket-client`. **Nov 11, 2026** CLOB API deprecations take effect Dec 14 On `https://clob.polymarket.com`, three order and trade query changes take effect on December 14. Update your integration before then to avoid failed requests. * **`associate_trades` is deprecated on CLOB order and trade responses.** Do not use it to track fills. * **`GET https://clob.polymarket.com/data/orders` requires `market` when filtering by `asset_id`.** Requests with only `asset_id` return `400` (`asset_id requires market`). * **`GET https://clob.polymarket.com/orders` and `GET https://clob.polymarket.com/v1/trade/open-orders` no longer support `asset_id` or `token_id` filters.** To filter open orders by asset, use `GET https://clob.polymarket.com/data/orders` with `asset_id` and `market`. **Nov 11, 2026** Relayer supported contracts * **Polymarket Relayer Policy Change**: From 11/11/2026, the relayer will only relay transactions that interact with Polymarket contracts and a short list of supported third-party contracts. All other transactions will be rejected. **Nov 10, 2026** PolyBolt: energy futures on price.equity * **New symbols**: `wti`, `brent` and `natgas` join `price.equity`, served by Chainlink with `market_status`. See [Supported Symbols](/api-reference/live-data/overview#supported-symbols). * **Contract rolls**: `cll` and `hn` (Pyth) now move to the next contract at the open of the current contract's third-to-last trading session, the Active Month the WTI and natural gas Up or Down markets resolve on. `wti`, `brent` and `natgas` follow Chainlink's own roll schedule. * **Chainlink prices**: `full_accuracy_value` on Chainlink-sourced prices now carries at most 15 significant digits, dropping floating-point artifacts such as `3.2091000000000003`. **Nov 5, 2026** PolyBolt: dxy, and Pyth pins on spcx and mu * **New symbol**: `dxy` (the US Dollar Index) joins `price.equity`, served by Pyth, the feed the DXY markets resolve on. * **Pyth on `spcx` and `mu`**: both still default to Chainlink and can now be pinned to `pyth`, the feed their markets resolve on. See [Pin a Price Provider](/api-reference/live-data/overview#pin-a-price-provider). **Nov 2, 2026** Data API v1 retirement * **Data API v1 retires on November 2, 2026**: the legacy Data API reference has been removed. Follow the [v1 to v2 migration guide](/migrate/data-api-v1-to-v2) for route mappings, response changes, and cursor pagination. * **Accounting snapshots retire too**: `GET /v1/accounting/snapshot` has no V2 replacement for its ZIP/CSV export. Remove calls to this route rather than changing its version prefix. **Oct 21, 2026** PolyBolt: seven new forex pairs on price.equity * **New symbols**: `usdchf`, `usdmxn`, `usdzar`, `usdbrl`, `usdnok`, `usdsek` and `usdtry` join `price.equity`, served by Pyth (the feeds the forex up-or-down markets resolve on). See [Supported Symbols](/api-reference/live-data/overview#supported-symbols). * `usdbrl` trades on weekdays only, so outside those hours its `market_status` reads `closed` and the snapshot carries the closing price. **Oct 21, 2026** PolyBolt: market status on equity prices * **New field**: `price.equity` and `price.equity.twap` payloads carry `market_status` (`open`, `closed` or `unknown`) on every live update and once per snapshot batch, so a client can tell a closed market from a stalled price. The field is additive and absent when the producer states nothing; treat absent as not stated. See [Read the Market Status](/api-reference/live-data/overview#read-the-market-status). * **Status changes arrive as updates**: a change without a new price repeats the last price with the new status and `is_carried_forward: true`, so an update can share its `timestamp` with the one before it. Do not discard updates only because their `timestamp` repeats. * **Closed snapshots keep the closing price**: while a series is `closed` or `unknown`, its snapshot carries the last price point even when it is older than two minutes. * **Per provider**: the status describes the instrument each provider prices. Chainlink's around-the-clock equity products read `open` outside exchange hours, while a symbol pinned to `pyth` follows its exchange session. * **SDKs**: the TypeScript and Python SDKs do not expose `market_status` yet; read it from the raw WebSocket payload. The machine-readable contract at `https://ws-live-v2.polymarket.com/asyncapi.json` carries the field. **Oct 7, 2026** Data API: /v2/tokens, plus the fixes shipped since September 28 * **New endpoint**: `GET /v2/tokens` resolves up to 50 ERC-1155 token ids per call (`token_id`, request order kept, unknown ids absent) or lists every token of up to 10 conditions (`condition`). A condition selector is any id the other routes carry: a ConditionalTokens condition id, a neg-risk market id (every market of the structure, in question order), a polymarket-v2 condition id in its 64- or 66-character form, or the on-chain event id of a polymarket-v2 neg-risk structure. Exactly one selector per request. See [Token Lookup](/market-data/public-analytics#token-lookup). * **One row per token**: `condition_id` in the 66-character form every route uses, `structural_condition_id` (the polymarket-v2 id in the same form, null on ConditionalTokens tokens), `module` (`v1_ctf` is the ConditionalTokens market; every other value is a polymarket-v2 module), outcome slot and label, the opposite token, on-chain settlement (`resolved`, `final_price`), market and event identity, and `question_index` for both neg-risk families. Not exposed in the TypeScript and Python SDKs yet; call the route over HTTP. * **`/v2/trades`**: a request with `user` and several `condition` values now reads one bounded stream per market and merges them, instead of scanning the wallet's whole history. Same rows and order, faster pages. * **`/v2/activity`**: rows for combo tokens carry their overall `Yes`/`No` outcome and outcome index on trades and redemptions. They were blank. * **Settled tokens priced at settlement**: on `/v2/positions` with a `condition` selector and on `/v2/oi`, a resolved outcome is valued at its settlement payout (0 or 1) before the last order-book mid, so a stale book on a settled market no longer moves current values or open interest. * **`/v2/positions`**: rows carry `first_entry_at`, the epoch seconds of the position's first acquisition (buy, split, mint, migration or transfer in), `0` when none is recorded; the same unit and sentinel as `last_event_at`, and an integer unlike the string `first_entry_at` on `/v2/positions/combos`. For a user's `CLOSED` positions, `sort_by=TOKENS`, `CURRENT_VALUE`, `PRICE` and `UNREALIZED_PNL` describe a holding that no longer exists and are served in `REALIZED_PNL` order; cursors minted for those four sorts before this change return `400`, so restart the walk from the first page. * **CORS**: `/v2` answers `access-control-allow-origin: *` to every origin, as v1 always did. * **`/v2/prices-history`**: a token with no data at or before the requested window answers empty immediately, and `as_of` now serves an asset whose history lives only in the finer tiers instead of returning nothing. * **`/v2/resolutions`**: answers are cached for up to 5 seconds while any row is live, and for up to 10 minutes once every row in the answer is resolved, so a new proposal, dispute or expiry can take up to 5 seconds to appear. `log_index` on a row now identifies the oracle request's `RequestPrice` log, reconciled for the newest requests every 3 minutes. **Oct 2, 2026** PolyBolt: price.crypto defaults to Chainlink, with provider pins and two new symbols * **Chainlink-first crypto prices**: `price.crypto` now serves Chainlink prices by default on every symbol, matching `price.equity`. Subscriptions that omit `filter.provider` see `source: "chainlink"` from their next connection onward, so re-read `source` after every reconnect and treat the value set as open. * **Provider pins on `price.crypto`**: `filter.provider` (`chainlink` or `pyth`) now works on the crypto channel. Pyth remains available on `btcusd`, `ethusd`, `solusd`, `xrpusd`, `dogeusd` and `bnbusd`; the `subscribed` acknowledgement names the provider actually served, falling back to the symbol's default when the pin cannot be served. See [Pin a Price Provider](/api-reference/live-data/overview#pin-a-price-provider). * **New symbols**: `hypeusd` and `zecusd` join `price.crypto` (Chainlink only), aligning the spot catalog with `price.crypto.twap`'s eight symbols. * The machine-readable contract at `https://ws-live-v2.polymarket.com/asyncapi.json` and the [migration guide](/migrate/rtds-to-polybolt) carry all of the above. **Sep 29, 2026** PolyBolt: forex TWAPs, price provenance, and provider pins * **New channel**: `price.equity.twap` streams 60-second Chainlink TWAP prices for `eurusd` and `usdjpy`, with the same envelope, snapshot and filter shape as `price.crypto.twap`. See [PolyBolt WebSocket](/api-reference/live-data/overview). * **`source` on every price payload**: `price.crypto`, `price.crypto.twap`, `price.equity` and `price.equity.twap` payloads now name their producing vendor (`pyth`, `massive` or `chainlink`) on every live update and once per snapshot batch. The field is additive; on the equity channels a symbol's vendor can change between connections, so re-read it after every reconnect. * **Provider pins (rolling out)**: on the equity channels, `filter.provider` (`chainlink` or `pyth`) requests a specific vendor and the `subscribed` acknowledgement names the provider actually served, falling back to the symbol's default when the pin cannot be served. Where the selector is not yet enabled the field is accepted and ignored. See [Pin a Price Provider](/api-reference/live-data/overview#pin-a-price-provider). * **New symbols**: `zecusd` joins `price.crypto.twap`; `spcx`, `intc`, `mstr`, `crcl` and `mu` join `price.equity`. Equity defaults now come from Chainlink wherever Chainlink serves the symbol. * The machine-readable contract at `https://ws-live-v2.polymarket.com/asyncapi.json` and the [Live Data Channel](/api-reference/wss/polybolt) reference carry all of the above. **Sep 28, 2026** Data API: settlement estimates on /v2/resolutions * **New optional fields**: rows from `GET /v2/resolutions` can now carry `expected_settlement_time` (RFC3339 UTC) and `settlement_time_basis`. Both are omitted when no estimate applies, so existing clients are unaffected. * **What the basis means**: `managed_proposal_expiration` and `proposal_expiration` mark the end of a live UMA proposal's challenge window, `liveness` the end of a proposal window on Polymarket's v2 oracle, and `dvm_round_estimate` the earliest end of the UMA voting round a disputed market can settle in. These are estimates, not deadlines: a disputed vote can roll into a later round, and a proposal past its window that is still under review returns no estimate while `extended_review` is `true`. See [Market Resolution](/market-data/public-analytics#market-resolution). * **SDKs**: the TypeScript and Python `Resolution` types do not expose these fields yet; read them from the HTTP response in the meantime. **Sep 15, 2026** PolyBolt WebSocket: real-time prices on one socket * **New socket**: `wss://ws-live-v2.polymarket.com/ws` streams licensed crypto, equity and Chainlink TWAP reference prices (`price.crypto`, `price.equity`, `price.crypto.twap`, CLOB API credentials required) with one envelope shape, a snapshot on every subscribe, a dense per-channel `seq`, and typed close codes. See [PolyBolt WebSocket](/api-reference/live-data/overview) and the [Live Data Channel](/api-reference/wss/polybolt) message reference. * **RTDS is legacy** for reference prices: `crypto_prices`, `crypto_prices_chainlink` and `equity_prices` map to the new channels in [Migrating from RTDS](/migrate/rtds-to-polybolt). The `comments` topic stays on RTDS for now. **Sep 4, 2026** Data API v2 release * **New API**: Data API v2 is live at `https://data-api.polymarket.com/v2` for wallet activity, market data, and trader and builder analytics. Start with the [Data API overview](/api-reference/data-api/overview) or [Migrating from v1](/migrate/data-api-v1-to-v2). * **Response contract**: Every endpoint wraps its payload in `data`. Paginated reads add `pagination` with opaque cursors (no offset parameter). Each endpoint takes snake_case parameters with camelCase aliases, names on-chain ids `condition`/`condition_id`, encodes money and size as JSON numbers (bare fields are shares, `_usdc` fields are USD), and signals load with `429` plus `Retry-After`. * **New capabilities over v1**: cumulative wallet PnL series (`/v2/user-pnl`), profile stats (`/v2/user-stats`), windowed wallet volume (`/v2/user-volume`), the biggest-winners board, builder leaderboard and volume, per-holder position economics (`/v2/holders?include_pnl=true`), and resolution lifecycle reads (`/v2/resolutions`). * **Price history moves to the data host**: `GET /v2/prices-history` replaces the CLOB-hosted route, with three explicit window forms (`interval`, `start`/`end`, `as_of`), second-based `bucket_seconds`, and cursor pagination. * **TypeScript SDK**: The SDK's Data API methods now use v2. See the [SDK changelog](/changelog/sdks). * **Rate limits**: per-family limits are published on [Rate Limits](/api-reference/rate-limits). * **v1 status**: `/v1` keeps serving unchanged but is frozen. New fields and endpoints land on v2 only. The v1 reference lives under **Data API v1 (Legacy)**. * **Higher taker delay**: The taker delay on crypto markets is now `150ms`, up from `50ms`. The change took effect on **September 4 at 14:00 UTC (10:00 AM ET)**. **Aug 17, 2026** Crypto taker delay reduced to 50ms * **Lower taker delay**: The taker delay on crypto markets is now `50ms`, down from `250ms`. The change took effect on **August 17 at 11:00 UTC (7:00 AM ET)**. **Aug 14, 2026** 5-minute crypto markets moved to a 60-second Chainlink TWAP * **Longer TWAP window**: All 5-minute crypto markets now resolve using a `60-second` Chainlink TWAP, replacing the `30-second` window introduced on August 7. The change took effect at **00:00 UTC**. * **Updated documentation**: See [Chainlink TWAP Prices](/market-data/realtime-data#twap-prices). **Aug 10, 2026** Data API: per-outcome redemption activity, position fee basis fields, and event artwork fallback * **Redemptions are now reported per outcome**: on `GET /activity`, a `REDEEM` row carries the outcome it settles in `asset`, `outcome`, and `outcomeIndex`, with `size` as the tokens burned for that outcome and `usdcSize` as that outcome's payout. Redeeming both sides of a market returns **two rows** — one per outcome — where a single combined row appeared before, and the losing outcome's `usdcSize` is `0`. Sum `usdcSize` across a transaction's rows to get the total payout. See [Resolution](/concepts/resolution). * **New position basis fields**: `GET /positions` entries can include `grossInitialValue`, the remaining entry basis including attributed buy fees, and `entryFeesUsdc`, that fee component. `initialValue` and `avgPrice` keep their existing fee-exclusive meaning, so the fee-exclusive basis is `grossInitialValue - entryFeesUsdc`. Both fields are optional — treat an omitted field as unavailable, not as zero. See [Positions and Tokens](/concepts/positions-tokens). * **New `includeArchived` filter**: `GET /positions` accepts `includeArchived` to return positions in archived markets that are still active. Archived positions remain excluded by default, so existing clients are unaffected. * **Event artwork fallback**: `icon` on `GET /activity` and `GET /trades` now falls back to the market image, then the parent event's icon and image, when a market has no icon of its own. Previously these rows returned an empty `icon`. **Aug 7, 2026** Chainlink TWAP resolution for crypto up/down markets * **TWAP-based resolution**: Crypto up/down markets now resolve using Chainlink-computed time-weighted average prices instead of a single price snapshot. * **Opening and settlement prices**: Both the price to beat and the final settlement price come from the applicable TWAP feed. * **Averaging windows**: 5-minute markets use a `30-second` lookback; 15-minute and 4-hour markets use a `60-second` lookback. * **Developer access**: See [Chainlink TWAP Prices](/market-data/realtime-data#twap-prices) for the current streaming workflow. **Jul 17, 2026** Latency improvements and order response changes — Friday July 24, 04:00 UTC * **Rollout Friday, July 24 at 04:00 UTC**: An async commit pipeline cuts matching latency. `POST /order` and `POST /orders` will no longer return `transactionHashes` on successful FAK/FOK matches — you get `tradeIDs` instead. `tradeIDs` behavior is unchanged; websocket fills are unaffected. * **SDK users**: Bump to the latest CLOB client (TypeScript, Python, Rust) before rollout — it resolves hashes from `tradeIDs` for you. * **Custom REST integrations**: If you depend on inline `transactionHashes`, poll trades by `tradeID` until each has a hash or returns `FAILED`. See [TypeScript](https://github.com/Polymarket/clob-client-v2/pull/89), [Python](https://github.com/Polymarket/py-clob-client-v2/pull/101), and [Rust](https://github.com/Polymarket/rs-clob-client-v2/pull/83). **Jul 14, 2026** Relayer: deprecating CLOB v1 Neg Risk Adapter * **Old adapter retired**: Relayer calls to the CLOB v1 Neg Risk Adapter (`0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296`) are being deprecated. CLOB v2 integrations should use the current Neg Risk Adapter at `0xadA2005600Dec949baf300f4C6120000bDB6eAab` for all pUSD-collateral actions. * **Grace period for redeems**: Relayer redeems targeting the old adapter remain available until **Friday, July 17, 2026 at 00:00 UTC**. After that, relayer calls to the old address are fully retired. * **Updated documentation**: See [Contracts](/resources/contracts). **Jul 10, 2026** Sports taker fee and maker rebate update * **Sports fee coefficient**: The sports taker fee rate increases from `0.03` to `0.05` at midnight UTC. * **Sports maker rebate**: The sports maker rebate decreases from 25% to 15% of collected taker fees. * **Updated documentation**: [Fees](/trading/fees) and [Maker Rebates Program](/programs/maker-rebates). **Jul 2, 2026** World Cup markets decimalized to a 0.0025 (0.25¢) tick size * **Finer tick size for World Cup markets**: All World Cup *to advance*, *moneyline*, *spreads*, and *totals* markets are now decimalized to a **0.0025 (0.25¢)** tick size. This lets you execute at smaller ticks and tighter spreads for the most competitive prices. Applies only to those World Cup markets — see [Place Orders](/trading/place-orders). **Jun 25, 2026** Bridge API: optional X-Builder-Code header * **New optional header**: `POST /deposit` and `POST /withdraw` now accept an `X-Builder-Code` header (bytes32 hex) for builder attribution. Without it, requests still succeed but return a `missing_builder_code` warning; a malformed code returns `400`. See [Deposit](/trading/bridge/deposit) and [Withdraw](/trading/bridge/withdraw). **Jun 15, 2026** CLOB DELETE /orders maximum batch size reduced to 1000 * **`DELETE /orders` limit**: The maximum number of order IDs per cancel request is now `1000`. Split larger cancellation batches across multiple requests. **Jun 1, 2026** Increased CLOB order rate limits Raised burst and sustained rate limits for several CLOB trading endpoints. * CLOB POST /order - 120000 every 10 minutes (200/s) - (SUSTAINED) * CLOB DELETE /order - 120000 every 10 minutes (200/s) - (SUSTAINED) * CLOB POST /orders - 2000 every 10s (200/s) - (BURST) * CLOB DELETE /orders - 2000 every 10s (200/s) - (BURST) See [Rate Limits](/api-reference/rate-limits) for the full table. **May 18, 2026** Data API: builderCode added to /v1/builders/leaderboard and /v1/builders/volume * **New field**: Both `GET /v1/builders/leaderboard` and `GET /v1/builders/volume` now include a `builderCode` string on each entry — the builder's onchain attribution code as attached to orders via `builderCode` (see [Migrating to CLOB V2](/v2-migration)). * **Additive change**: existing clients are unaffected. Legacy builders without a registered code return an empty string. **May 14, 2026** GET /markets/keyset maximum limit reduced to 100 * **`GET /markets/keyset` limit**: The maximum `limit` value is now `100`. Requests should use `after_cursor`/`next_cursor` to paginate through larger result sets. **Apr 28, 2026** CLOB V2 is live on production Polymarket's CLOB V2 upgrade is live on `https://clob.polymarket.com`. * **Production URL unchanged**: V2 now runs on the standard CLOB host. New integrations should use `https://clob.polymarket.com`. * **No V1 compatibility**: Legacy V1 SDKs and V1-signed orders are no longer supported on production. * **Open orders wiped**: Resting orders from before the cutover did not migrate and must be re-created with V2 signing. * **Migration guide**: See [Migrating to CLOB V2](/v2-migration) for the SDK, raw order signing, pUSD, and builder attribution changes. **Apr 21, 2026** Relayer API: POST /submit returns immediately without transactionHash * **Faster `POST /submit` responses**: The Relayer's `POST /submit` endpoint now returns immediately with just `{ transactionID, state: "STATE_NEW" }`. The `transactionHash` field has been removed from the submit response to improve performance. * **How to get the hash**: Poll [`GET /transaction`](/api-reference/relayer/get-a-transaction-by-id) with the returned `transactionID` to retrieve the onchain `transactionHash` once the transaction has been broadcast. **Apr 17, 2026** CLOB V2: upgrades go live April 28 at \~11:00 UTC, with \~1 hour of downtime Polymarket is shipping a coordinated upgrade: **new Exchange contracts, a rewritten CLOB backend, and a new collateral token (pUSD)**. **Exchange upgrades go live April 28, 2026 at \~11:00 UTC with \~1 hour of downtime.** All integrations must migrate to the V2 SDK before the cutover — there will be no backward compatibility after go-live. **Full walkthrough:** [Migrating to CLOB V2](/v2-migration). Follow [Discord](https://discord.gg/polymarket), Telegram, and [status.polymarket.com](https://status.polymarket.com) for the exact start time. **Historical pre-cutover note:** before go-live, integrations could test against `https://clob-v2.polymarket.com`. As of April 28, V2 runs on `https://clob.polymarket.com`. **What's changing** * New Exchange contracts (CTF Exchange V2 + Neg Risk CTF Exchange V2) * **pUSD** replaces USDC.e as the collateral token (standard ERC-20 on Polygon, backed by USDC, backing enforced onchain) * Order struct: `nonce`, `feeRateBps`, `taker` removed — `timestamp` (ms), `metadata`, `builder` added * Fees are now set at match time — no more `feeRateBps` on orders * Builder attribution is native via `builderCode` on orders (no more `builder-signing-sdk`) * EIP-712 Exchange domain version bumps from `"1"` to `"2"` (ClobAuth stays at `"1"`) **What you need to do** * Install the V2 SDK — [`@polymarket/clob-client-v2`](https://www.npmjs.com/package/@polymarket/clob-client-v2) or [`py-clob-client-v2`](https://pypi.org/project/py-clob-client-v2/) — and remove the legacy `clob-client` / `py-clob-client` packages * Update constructor from positional args to options object; rename `chainId` → `chain` * Remove `feeRateBps`, `nonce`, and `taker` from your order creation code * If you're a builder, copy your code from [Settings → Builder](https://polymarket.com/settings?tab=builder) and attach it to orders * If you sign orders without the SDK, update the `verifyingContract` and the signed Order fields — see [For API users](/v2-migration#for-api-users) * Plan for all open orders to be wiped at cutover **During the window:** Trading will be paused for \~1 hour on April 28 starting around 11:00 UTC. The SDK's hot-swap mechanism will auto-refresh the client when V2 goes live — no manual action needed if you're on the latest SDK. **Apr 13, 2026** Bridge API: added support link for bridging issues * **Support contact**: Added a link to [our Bridge API provider's support](https://intercom.help/funxyz/en/articles/10732578-contact-us) (Fun.xyz) for failed, stuck, or compliance-held bridge transactions. See [Deposit Status](/trading/bridge/status). **Apr 10, 2026** New keyset pagination endpoints for markets and events * **New endpoints**: Added `GET /markets/keyset` and `GET /events/keyset` for cursor-based pagination, replacing offset-based `GET /markets` and `GET /events`. * **How it works**: These use an opaque `after_cursor`/`next_cursor` token instead of `offset`, providing stable and efficient paging through large result sets. Same filters, same response shape per item — the only differences are the wrapper response (`{ "markets": [...], "next_cursor": "..." }`) and the rejection of `offset`. * **Migration**: The existing `GET /markets` and `GET /events` endpoints remain available but will be deprecated in a future release. New integrations should use the keyset variants. **Apr 9, 2026** GET /markets: closed defaults to false * **`closed` default change**: The `closed` query parameter on `GET /markets` now defaults to `false`. Closed markets are excluded from results unless you explicitly pass `closed=true`. **April 8, 2026** Increased API Rate Limits Increased burst and sustained rate limits for several CLOB trading endpoints. * CLOB POST /order - 5000 every 10s (500/s) - (BURST) * CLOB POST /order - 48000 every 10 minutes (80/s) * CLOB DELETE /order - 5000 every 10s (500/s) - (BURST) * CLOB DELETE /order - 48000 every 10 minutes (80/s) * CLOB POST /orders - 1500 every 10s (150/s) - (BURST) * CLOB POST /orders - 21000 every 10 minutes (35/s) * CLOB DELETE /cancel-market-orders - 1500 every 10s (150/s) - (BURST) * CLOB DELETE /cancel-market-orders - 21000 every 10 minutes (35/s) See [Rate Limits](/api-reference/rate-limits) for the full table. **Mar 31, 2026** REST API Fee Fields Update * **Fee calculation source**: Fees should now be calculated using the `feeSchedule` object within a market. **Mar 30, 2026** Fee Structure V2 * **New fee categories**: Fees now apply to Crypto, Sports, Finance, Politics, Economics, Culture, Weather, Tech, Mentions, and Other / General markets with updated rates per category. Geopolitical and world events markets remain fee-free. * **Updated documentation**: [Trading Fees](/trading/fees) and [Maker Rebates Program](/programs/maker-rebates). **Mar 17, 2026** March Madness: \$2M+ in Liquidity Rewards * **March Madness Liquidity Rewards**: Adding \$2M+ in liquidity rewards to both live and pregame markets. * **How it works**: Liquidity rewards are payments for placing competitive bids. Rewards are paid out based on the size of your orders, how close they are to the midpoint, and how consistently they are quoted relative to other liquidity providers. Orders must be active on the book for a minimum of **3.5 seconds** to be eligible. **Daily reward rates for markets (subject to change):** **48 hours before GameStartTime:** * \$7.5k for full game ML market * \$500 for 5 other markets (most recently created full game spread, most recently created full game total, 1st half ML, most recently created 1st half spread, most recently created 1st half total) **From game live to game completion (note: rewards are expressed in daily rates):** * \$60k for full game ML * \$4k for most recently created full game spread and most recently created full game total **From game live to halftime (note: rewards are expressed in daily rates):** * \$8k for 1st half ML, most recently created 1st half spread, most recently created 1st half total * **Markets**: [Browse March Madness markets](https://polymarket.com/sports/cbb/games) * **More details**: [Liquidity Rewards documentation](/programs/liquidity-rewards) **Mar 1, 2026** Taker Fees & Maker Rebates: All Crypto Markets * **Crypto market fees expansion**: Starting March 6, 2026, taker fees and maker rebates extend to all crypto markets including 1H, 4H, daily, and weekly. The same fee structure as existing crypto markets applies. Only new markets created after March 6 are affected. * **Updated documentation**: [Trading Fees](/trading/fees) and [Maker Rebates Program](/programs/maker-rebates) updated to reflect all crypto market coverage. **Feb 12, 2026** 5-Minute Crypto Markets * **5-minute crypto markets**: Launched with taker fees enabled. Fees follow the same curve as 15-minute crypto markets, peaking at 1.56% at 50% probability. * **Maker Rebates**: Liquidity providers earn daily USDC rebates funded by taker fees, same as 15-minute crypto markets. **Feb 11, 2026** Taker Fees & Maker Rebates: NCAAB and Serie A * **Sports market fees**: Taker fees to be enabled on NCAAB (college basketball) and Serie A markets on February 18, 2026. * **Per-market rebate calculation**: Rebates are now calculated per market, makers only compete with other makers in the same market. * **Updated documentation**: [Maker Rebates Program](/programs/maker-rebates) updated with sports fee tables and parameters. **Jan 28, 2026** Bridge API: Withdrawal Endpoint * **Withdrawal Endpoint**: New `/withdraw` endpoint to bridge USDC.e from Polymarket to any supported chain and token. * **Multi-chain withdrawals**: Withdraw to EVM chains (Ethereum, Arbitrum, Base, etc.), Solana, and Bitcoin. * **Updated documentation**: Bridge API docs updated to reflect deposit and withdrawal functionality. **Jan 16, 2026** Docs Update: RTDS documentation * RTDS docs updated to reflect RTDS supports **comments** and **crypto prices** only. * Removed legacy CLOB references and `clob_auth` from RTDS docs. **Jan 16, 2026** Docs Update: Maker Rebates Program * **Maker Rebates Program**: Updated funding schedule with distribution method (volume-weighted vs fee-curve weighted). * **Fee-curve weighted rebates**: Documented fee-equivalent formula and rebate calculation. * **FAQ**: Clarified how rebates are calculated during fee-curve weighted periods. **Jan 6, 2026** New API Features * **Releases**: Daily Releases timing * **HeartBeats API**: HeartBeats endpoint for monitoring connection status and canceling orders * **Post Only Orders**: Orders that are rejected if they would immediately match against an existing order **Jan 5, 2026** Taker Fees & Maker Rebates * **Taker Fees**: Enabled on 15-minute crypto markets. Fees vary by price and peak at 1.56% at 50% probability. * **Maker Rebates**: Daily USDC rebates paid to liquidity providers, funded by taker fees. **Sept 24, 2025** Polymarket Real-Time Data Socket (RTDS) official release * **Crypto Price Feeds**: Access real-time cryptocurrency prices from two sources (Binance & Chainlink) * **Comment Streaming**: Real-time updates for comment events including new comments, replies, and reactions * **Dynamic Subscriptions**: Add, remove, and modify subscriptions without reconnecting * **TypeScript Client**: Official TypeScript client available at [real-time-data-client](https://github.com/Polymarket/real-time-data-client) For complete documentation, see [Market Data](/market-data/overview). **September 15, 2025** WSS price_change event update * There has been a significant change to the structure of the price change message. This update will be applied at 11PM UTC September 15, 2025. We apologize for the short notice * Please see [Real-Time Data](/market-data/realtime-data) for details. **August 26, 2025** Updated /trades and /activity endpoints * Reduced maximum values for query parameters on Data-API /trades and /activity: * `limit`: 500 * `offset`: 1,000 **August 21, 2025** Batch Orders Increase * The batch orders limit has been increased from 5 -> 15. Read more about the batch orders functionality [here](/trading/place-orders#post-a-batch-of-orders). **July 23, 2025** Get Book(s) update * We’re adding new fields to the `get-book` and `get-books` CLOB endpoints to include key market metadata that previously required separate queries. * `min_order_size` * type: string * description: Minimum price increment. * `neg_risk` * type: boolean * description: Boolean indicating whether the market is neg_risk. * `tick_size` * type: string * description: Minimum price increment. **June 3, 2025** New Batch Orders Endpoint * We’re excited to roll out a highly requested feature: **order batching**. With this new endpoint, users can now submit up to five trades in a single request. To help you get started, we’ve included sample code demonstrating how to use it. Please see [Place Orders](/trading/place-orders) for more details. **June 3, 2025** Change to /data/trades * We're adding a new `side` field to the `MakerOrder` portion of the trade object. This field will indicate whether the maker order is a `buy` or `sell`, helping to clarify trade events where the maker side was previously ambiguous. For more details, refer to the MakerOrder object on the [Manage Orders](/trading/manage-orders) page. **May 28, 2025** Websocket Changes * The 100 token subscription limit has been removed for the Markets channel. You can now subscribe to as many token IDs as needed for your use case. * New Subscribe Field `initial_dump` * Optional field to indicate whether you want to receive the initial order book state when subscribing to a token or list of tokens. * `default: true` **May 28, 2025** New FAK Order Type We’re excited to introduce a new order type soon to be available to all users: Fill and Kill (FAK). FAK orders behave similarly to the well-known Fill or Kill (FOK) orders, but with a key difference: * FAK will fill as many shares as possible immediately at your specified price, and any remaining unfilled portion will be canceled. * Unlike FOK, which requires the entire order to fill instantly or be canceled, FAK is more flexible and aims to capture partial fills if possible. **May 15, 2025** Increased API Rate Limits All API users will enjoy increased rate limits for the CLOB endpoints. * CLOB - /books (website) (300req - 10s / Throttle requests over the maximum configured rate) * CLOB - /books (50 req - 10s / Throttle requests over the maximum configured rate) * CLOB - /price (100req - 10s / Throttle requests over the maximum configured rate) * CLOB markets/0x (50req / 10s - Throttle requests over the maximum configured rate) * CLOB POST /order - 500 every 10s (50/s) - (BURST) - Throttle requests over the maximum configured rate * CLOB POST /order - 3000 every 10 minutes (5/s) - Throttle requests over the maximum configured rate * CLOB DELETE /order - 500 every 10s (50/s) - (BURST) - Throttle requests over the maximum configured rate * DELETE /order - 3000 every 10 minutes (5/s) - Throttle requests over the maximum configured rate # SDK Changelog Source: https://docs.polymarket.com/changelog/sdks Recent changes to the official SDKs. > [tab] TypeScript > > ### `0.20.0` > > * Breaking change: `listOpenOrders(...)` now requires a nonblank market condition ID in `market` when filtering by `assetId` or the deprecated `tokenId` alias. Asset-only queries throw `UserInputError` before sending a request. Unfiltered and market-only queries remain supported. > > ```diff theme={null} > -const pages = client.listOpenOrders({ assetId }); > +const pages = client.listOpenOrders({ assetId, market: conditionId }); > ``` > > * `OpenOrder.associateTrades` is deprecated and defaults to an empty array when omitted from a response, preserving legacy values when present. Use `sizeMatched` for cumulative fills, or `listAccountTrades()` for individual fills matched by `takerOrderId` or `makerOrders[].orderId`. An empty `associateTrades` array does not mean an order has no fills. > > ### `0.19.0` > > * Added `providerApiKey` to authenticated crypto and equity spot and TWAP price subscriptions. Set `provider: PriceProvider.Chainlink` to authenticate with your Chainlink API key; the key is ignored for other providers. > > ### `0.18.0` > > * Added `listWalletOpenOrders(...)` to list open orders across a Deposit Wallet, including orders placed by its session keys. Each order reports the `signerAddress` that placed it and a nullable `owner`. Filter by `market`, `assetId`, or 1 to 50 `signerAddresses`. > * Added `cancelWalletOrders({ orderIds })` and `cancelAllWalletOrders()` so the Deposit Wallet owner can cancel orders placed by any of its signers. `listOpenOrders`, `cancelOrder`, `cancelOrders`, and `cancelAll` still cover only orders placed with the client's own credentials. > * Session-key authorization and revocation now accept `relayerApiKey(...)` as well as `builderApiKey(...)` and `remoteBuilderSigning(...)`. > > ### `0.17.0` > > * Added `DIRECTIONAL_SPLIT`, `DIRECTIONAL_MERGE`, `THRESHOLD_COMPOSE`, and `THRESHOLD_DECOMPOSE` activity types and `listActivity(...)` filters. Threshold rows report the moved line position as `shares` and identify its market with `conditionId`; no collateral moves. Presentation fields are optional on range-event rows. > * Unknown activity types no longer fail an activity page. They carry shared account fields and an `OpaqueActivityType`. Breaking type change: `activity.type` is no longer assignable to `string` or usable as a record key. Convert it explicitly, and add a `default` branch to exhaustive switches to handle unlisted types: > > ```diff theme={null} > -const type: string = activity.type; > -const label = labels[activity.type]; > +const type = String(activity.type); > +const label = labels[type] ?? "Other"; > ``` > > * Added Binance as an opt-in crypto spot price provider. Binance quotes use USDT spot closes under canonical USD symbols; omitting the provider keeps the existing default. > * Reduced retained heap after importing `@polymarket/client` by about 20% and raised the Zod requirement to `^4.6.7`. > * Collection limits now fail without per-item validation noise. When invalid input is closest to one accepted shape, `UserInputError` lists only that shape's issues. > > ### `0.16.0` > > * Breaking change: removed `downloadAccountingSnapshot` from public and secure clients and the standalone action, along with `DownloadAccountingSnapshotRequest`, `SecureDownloadAccountingSnapshotRequest`, and `DownloadAccountingSnapshotError`. Remove calls and imports for this download. There is no replacement ZIP/CSV export; portfolio, position, and activity reads do not provide an equivalent archive. > > ```diff theme={null} > -const snapshot = await client.downloadAccountingSnapshot({ user: address }); > +// Remove the snapshot download and code that consumes its archive. > ``` > > ### `0.15.0` > > * Protected market BUYs now round shares down so orders can match at `maxPrice` without increasing the signed spend. Final fee-adjusted amounts are checked against the finest supported tick; the SDK refreshes market metadata once before rejecting an amount that cannot preserve the price bound. > * Exported `MINIMUM_TICK_SIZE_VALUE` from `@polymarket/bindings`. > * Added `market.trading.takerDelayMs` for the taker delay in milliseconds. `market.trading.secondsDelay` is deprecated in favor of this field. > * Experimental Perps instrument reads, category filters, and fee schedules now accept `pre_ipo` and future category strings. Breaking enum change: use `PerpsKnownInstrumentCategory` for named values. `PerpsInstrumentCategory` remains available as a type accepting known values and future strings: > > ```diff theme={null} > -import { PerpsInstrumentCategory } from "@polymarket/client"; > +import { PerpsKnownInstrumentCategory } from "@polymarket/client"; > > -const category = PerpsInstrumentCategory.Crypto; > +const category = PerpsKnownInstrumentCategory.Crypto; > ``` > > * Perps instruments now expose optional `feeOverride` and `fundingMultiplier` windows. Stored windows can be scheduled or expired; their presence alone does not mean they are active. > > ### `0.14.0` > > * Breaking dependency change: `@polymarket/types@0.3.0` removes `unwrap` and the `neverthrow` re-exports. Service requests return promises that resolve parsed data and reject with SDK errors. Use `{ responseType: "raw" }` when you need the response object. Import any independently used `neverthrow` APIs from your own dependency. Remove `unwrap` when awaiting SDK requests: > > ```diff theme={null} > -import { unwrap } from "@polymarket/types"; > > -const result = await unwrap(client.predictions.get("/v1/markets")); > +const result = await client.predictions.get("/v1/markets"); > ``` > > * Breaking activity-type change: `SplitActivity`, `MergeActivity`, and `RedeemActivity` now include Combo variants. Combo rows have `isCombo: true`, a `ComboConditionId`, optional titles, and no market URL slugs. Narrow the existing activity guard before accessing those fields: > > ```diff theme={null} > -if (activity.type === "SPLIT") { > +if (activity.type === "SPLIT" && !activity.isCombo) { > console.log(activity.slug, activity.eventSlug); > } > ``` > > * Combo splits, merges, and redemptions accept missing presentation metadata. Combo trades and redemptions retain token outcomes; blank labels and index `999` become `undefined`, while index zero is preserved. Automatic redemption remains `REDEEM`. > * Added experimental custom `fetch` and per-read `signal`, `retries`, and `timeout` controls. HTTP requests, including RPC, default to a 30-second timeout; set milliseconds or `false` per read. Retry budgets default to two retries per request and are independent for each pagination request. > * Added experimental `predictions` requests with SDK/runtime metadata, preserved rejection details, and no automatic retry of prediction mutations. > * Added `closed: "any"` for market/event discovery, event protocol-version selection, and oracle request/event ID, resolution-status, and protocol discovery filters. Existing open-only defaults remain unchanged. > * Added filtered reward-market discovery, current maker rebates by date/address, and outcome-token reference lookup. > * Added authenticated one-shot order heartbeats and mismatch-ID recovery. The first accepted send enables API-key-wide timeout cancellation with no disarm operation. Callers own scheduling and ID serialization; cancellation after expiry is best effort. > * Equity spot and TWAP events now expose optional provider-specific `marketStatus`. Omission means not stated, never implicitly open. Spot status-only updates may repeat the price timestamp with `isCarriedForward: true`; do not deduplicate by timestamp alone. Older unstated spot frames retain the cached stated status; snapshots can include an older closing price. > * Automatic pagination raises `UnexpectedResponseError` on a missing or repeated continuation cursor after yielding fetched pages. Discard rejected obsolete closed-position cursors and restart manually; wallet-anchored closed-position listings retain realized-PnL ordering. > * Added Polymarket V2 neg-risk workflows using market condition IDs; low-level helpers retain explicit protocol event IDs. > * Experimental Perps now retain fill ADL/liquidation details and instrument filters, available order margin, fee tiers, position ADL index, instrument display metadata, and exchange event horizons. Zero event horizons become `null`; synthetic recovery does not invent one. Visibility metadata does not establish trading eligibility. Internal-transfer history continues past verified complete millisecond overlaps without duplicate or skipped rows. > * Added native/sponsored earnings breakdowns, sponsored queries, and taker-tier upgrade notifications. > * New-market `gameStartTime` now normalizes Postgres datetime strings to ISO 8601 and empty values to `null`. User order websocket events retain `INVALID` and `CANCELED_*` statuses instead of dropping them. > * Resolution lifecycle rows may retain the initial request log index while their transaction hash identifies a later event; do not combine them as a log locator. Condition-resolution fallback rows carry their own event metadata. > > ### `0.13.0` > > * `fetchTradingApprovalsState(...)` now reads indexed approval state from the configured data endpoint. Recent grants and revocations may take time to appear; RPC overrides no longer affect these reads, and failures surface without an RPC fallback. Trading setup continues to check approvals on chain. Incomplete or mismatched snapshots raise `UnexpectedResponseError`. > * Added 60-second equity TWAP subscriptions through `prices.equity.twap`. > * Price subscriptions now accept a Chainlink or Pyth provider and an `onSubscribed` callback that reports the confirmed provider on acceptance and after reconnects. > * Realtime price updates and history snapshots now expose their source through `PriceSource` and `KnownPriceSource`. Cached history resets when the source changes. > * Positions now expose `firstEntryAt` in epoch milliseconds, or `undefined` when unrecorded. > * Added a case-insensitive `title` filter to `listPositions(...)`, retained across pages and cursor replay. Patterns accept up to 200 Unicode characters; `%` and `_` keep their wildcard meaning. > * Added `PositionSortBy.Price`. Redeemable listings retain winners-first ordering, and closed wallet listings retain realized-PnL ordering. > * Resolution records now expose optional `expectedSettlementTime` and `settlementTimeBasis`. These are earliest settlement estimates, not guaranteed deadlines. > * Added experimental Perps GTD orders with separate order expiry, batch validation, signing, and order updates. > * Added experimental Perps chase creation, active reads, and cancellation, with chase identities on child orders. > * Added experimental Perps TWAP creation, active reads, pause, resume, and cancellation. > * Position TP/SL triggers now accept a quantity for partial exits; omitting it still closes the full position. > * Added experimental trailing market stop losses for orders and positions, including partial exits, activation events, and trailing metadata. > * Added experimental public and authenticated position snapshots, with exact trade IDs and a result for each selection. > * Added a public Perps registration lookup. > * Perps instruments now expose close-only state, settlement records, and display labels. Trades and fills expose settlement flags. > * Added ordered batch Perps leverage updates with a rejection result for each instrument. > * Perps notification history and session events now include `position_deleveraged`. Exhaustive notification handlers must handle this new variant; Perps remains experimental: > > ```diff theme={null} > switch (notification.type) { > + case "position_deleveraged": > + console.log(notification.sizeClosed, notification.price, notification.pnl); > + break; > } > ``` > > * Perps sessions now emit server resync signals with the catch-up sequence and timestamp. Backfill from the last processed notification sequence and deduplicate by notification ID. > * Order history and private updates now accept current terminal Perps statuses, including instrument retirement, fill-time margin failures, and order limits. > * `RequestRejectedError.retryAfter` and `RateLimitError.retryAfter` now accept HTTP-date `Retry-After` headers as nonnegative whole seconds. Retry policy is unchanged. > > ### `0.12.0` > > * Added Perps builder-code support. > * Added owner-signed Perps internal transfers and paginated transfer history. > * Perps cancellations now expose typed rejection reasons and retry transient `order_in_flight` results with bounded backoff. > * Added `PositionStatus.RedeemableLost` and `PositionStatus.Mergeable` filters to `listPositions(...)`. Public clients require `user` for lost-position reads; mergeable reads default to sorting by `TOKENS` and fall back to the broader open listing without a user. Secure clients select the authenticated wallet. Returned `Position.status` values remain `OPEN`, `REDEEMABLE`, or `CLOSED`, represented by `PositionRowStatus`. > * `listComments(...)` can page through a whole thread when `holdersOnly` and `getPositions` are unset or false and `order` is omitted, `id`, or `createdAt`. Comment and event cursors are bound to their query and reject reuse with different arguments. Previously saved cursors remain usable with the same arguments. > * Comment reads using other options, including reads by user address, stop automatic iteration at the supported offset depth; search stops after 100 pages. The final accessible page exposes `limitReached: true` when completeness is unknown. Explicitly following a cursor past the limit throws `PaginationLimitError`. > * Splitting, merging, and redeeming positions now select the protocol from the market's `version`. Missing versions or identifiers required by that protocol raise `UnexpectedResponseError`. > * Added `CONDITIONAL-V2` balance and allowance reads and refreshes, and use the Protocol V2 position selector when recovering a Protocol V2 sell order after approval. `AssetType` is now exported from `@polymarket/client`. > * Account trade pages now accept missing or empty transaction hashes as `undefined`. Callers that assumed every trade had a hash must handle its absence: > > ```diff theme={null} > -const shortHash = trade.transactionHash.slice(0, 10); > +const shortHash = trade.transactionHash?.slice(0, 10); > ``` > > * Sports-list and event responses now preserve the sport's `name`. > > ### `0.11.0` > > * Added authenticated PolyBolt crypto, 60-second TWAP, and equity price streams through `SecureClient.subscribe(...)`, with history snapshots, exact decimal prices, shared connections, and automatic reconnects. Use `prices.crypto`, `prices.crypto.twap`, or `prices.equity`; crypto symbols must be canonical USD pairs such as `btcusd`. Rejections expose a machine-readable `RequestRejectedError.code`. Event sequence numbers are scoped to each channel and connection and reset on reconnect. Legacy price topics remain deprecated, with removal planned one month after this release. Migrating Binance prices changes USDT quotes to USD; 30-second TWAP has no replacement. See the [SDK migration guide](/migrate/rtds-to-polybolt#migrate-sdks-to-polybolt). > > Given an authenticated `SecureClient`, migrate a crypto subscription as follows: > > ```diff theme={null} > const stream = await client.subscribe([ > - { topic: "prices.crypto.chainlink", symbols: ["btc/usd"] }, > + { topic: "prices.crypto", symbols: ["btcusd"] }, > ]); > ``` > > * Added explicit `EIP712Domain` types to authentication, Deposit Wallet order and batch, and Perps signing payloads for signers that require complete typed data. > * Exported `OrderPostStatus` from `@polymarket/client` so callers can compare accepted order statuses without importing the bindings package. > > ### `0.10.0` > > * Breaking change: trade, activity, position, and Combo feeds now use server cursors and automatically retry transient rate limits. Restart scans with a new first page; previously saved cursors are not reusable. Replace `market` filters with `conditionId` and top-level `start`/`end` with `window`. Time windows accept epoch seconds or `Date` values; `window: "full"` requests full history. Condition filters accept at most 20 distinct IDs. > > ```diff theme={null} > const pages = client.listActivity({ > user, > - market: [conditionId], > - start, > - end, > + conditionId: [conditionId], > + window: { start, end }, > }); > ``` > > * Breaking change: `listPositions(...)` now covers open, redeemable, and closed positions. Replace `listClosedPositions(...)` with `status: PositionStatus.Closed`, and `listMarketPositions(...)` with a public client's `listPositions({ conditionId })`. Market-holder results are individual positions rather than groups by outcome. The default `Open` status includes redeemable positions. > > ```diff theme={null} > +import { PositionStatus } from "@polymarket/client"; > > -const pages = client.listClosedPositions({ user }); > +const pages = client.listPositions({ user, status: PositionStatus.Closed }); > ``` > > * Breaking change: secure `listPositions(...)` always selects the authenticated wallet and rejects `user: null`. Use a public client to list a market's holders. > > ```diff theme={null} > -const pages = secureClient.listPositions({ user: null, market: [conditionId] }); > +const pages = publicClient.listPositions({ conditionId }); > ``` > > * Breaking change: position rows expose `currentSize`, `currentPrice`, `totalSize`, and explicit fee-exclusive entry economics. Money, size, price, and PnL values use decimal strings; `entryFeesUsdc` is disclosed separately and must not be deducted from `entryCostUsdc` again. Optional feed metadata now uses `undefined` for absent values, and returned timestamps use epoch milliseconds. > > ```diff theme={null} > -const shares = position.size; > -const price = position.curPrice; > -const bought = position.totalBought; > +const shares = position.currentSize; > +const price = position.currentPrice; > +const bought = position.totalSize; > ``` > > * Breaking change: request vocabularies now use exported enums, including `SortDirection`, `TradeFilterType`, `PositionFilterType`, `PositionSortBy`, `ComboPositionSortBy`, and `TipSide`. Replace the removed `Side` type with `OrderSide`. > > ```diff theme={null} > -import type { Side } from "@polymarket/client"; > +import { OrderSide } from "@polymarket/client"; > > -const side: Side = "BUY"; > +const side = OrderSide.BUY; > ``` > > * Added migration activity through `ActivityType.MIGRATION` and `MigrationActivity`, plus tip activity through `ActivityType.TIP` and `TipSide`. Combo positions now support `ComboPositionStatus.Redeemable` as a sole status filter. > * Breaking change: Combo activity includes `positionId` on every row and removes `transactionAt`, `logIndex`, and `moduleId`. Use `timestamp` for the activity time. > > ```diff theme={null} > -const occurredAt = activity.transactionAt; > +const occurredAt = activity.timestamp; > ``` > > * Breaking change: `listMarketHolders(...)` now returns a paginator. Pass `conditionIds` and `pageSize`; `minBalance` is measured in display shares. Optional `includePnl` adds gross holdings and position economics for one condition ID with a page size of at most 100. Merge outcome groups across pages by `assetId`. > > ```diff theme={null} > -const holders = await client.listMarketHolders({ market: [conditionId], limit: 10 }); > +const pages = client.listMarketHolders({ conditionIds: [conditionId], pageSize: 10 }); > +const firstPage = await pages.firstPage(); > +const holders = firstPage.items; > ``` > > * Breaking change: `fetchPortfolioValue(...)` returns one `PortfolioValue` with a decimal-string `value`, and accepts `conditionIds` instead of `market`. Position and portfolio reads also canonicalize Polymarket Protocol V2 condition IDs. > > ```diff theme={null} > -const [portfolio] = await client.fetchPortfolioValue({ user, market: [conditionId] }); > +const portfolio = await client.fetchPortfolioValue({ user, conditionIds: [conditionId] }); > ``` > > * Added `fetchUserStats(...)`, `fetchUserPnl(...)`, and `fetchUserVolume(...)` for account analytics, with authenticated-wallet defaults on secure clients. Breaking change: replace `fetchTradedMarketCount(...)` with the exact distinct-market count on `fetchUserStats(...)`. It returns `null` for an unknown user. > > ```diff theme={null} > -const count = (await client.fetchTradedMarketCount({ user })).traded; > +const stats = await client.fetchUserStats({ user }); > +const count = stats?.tradedMarketCount ?? null; > ``` > > * Breaking change: replace `fetchPriceHistory(...)` with cursor-paginated `listPriceHistory(...)`. Pass `assetId` and exactly one time selection: `interval`, `start` with optional `end`, or `asOf`. Replace minute-based `fidelity` with `bucketSeconds`; omit it for automatic resolution. Explicit ranges span at most 15 days. Each point includes a decimal-string price, epoch-millisecond timestamp, and `resolutionSeconds`. > > ```diff theme={null} > +import { PriceHistoryInterval } from "@polymarket/client"; > > -const history = await client.fetchPriceHistory({ assetId, interval: "1d", fidelity: 60 }); > +const pages = client.listPriceHistory({ > + assetId, > + interval: PriceHistoryInterval.OneDay, > + bucketSeconds: 3600, > +}); > +const firstPage = await pages.firstPage(); > +const history = firstPage.items; > ``` > > * Breaking change: replace `listOpenInterest(...)` with `fetchOpenInterest(...)` and pass `conditionIds` for selected markets. Values represent priced gross open interest in USDC. > > ```diff theme={null} > -const openInterest = await client.listOpenInterest({ market: [conditionId] }); > +const openInterest = await client.fetchOpenInterest({ conditionIds: [conditionId] }); > ``` > > * Breaking change: `fetchEventLiveVolume(...)` accepts `eventIds` and returns cumulative taker volume in shares, with market rows in `markets` and a decimal-string `takerVolumeTotal`. > > ```diff theme={null} > -const volume = await client.fetchEventLiveVolume({ id: eventId }); > +const volume = await client.fetchEventLiveVolume({ eventIds: [eventId] }); > ``` > > * Breaking change: builder rankings now return cursor-paginated `BuilderStanding` rows. Builder volume returns complete `BuilderVolumePoint` date buckets; `bucketLimit` bounds buckets rather than builder rows. Replace `timePeriod` with `window` for rankings or `interval` for volume. Use `BuilderVolumeInterval.Year` for yearly buckets. > > ```diff theme={null} > +import { BuilderVolumeInterval, LeaderboardWindow } from "@polymarket/client"; > > -const pages = client.listBuilderLeaderboard({ timePeriod: "MONTH" }); > -const volume = await client.fetchBuilderVolume({ timePeriod: "MONTH" }); > +const pages = client.listBuilderLeaderboard({ window: LeaderboardWindow.Month }); > +const volume = await client.fetchBuilderVolume({ interval: BuilderVolumeInterval.Month }); > ``` > > * Breaking change: trader rankings use cursor pagination, `window`, and `sortBy`; the list no longer accepts `user` or `userName` filters. Use `fetchTraderLeaderboardStanding({ user })` for one wallet's standing. Added `listBiggestWinners(...)` with market and Combo variants. > > ```diff theme={null} > +import { LeaderboardWindow, TraderLeaderboardSort } from "@polymarket/client"; > > -const pages = client.listTraderLeaderboard({ timePeriod: "MONTH", orderBy: "PNL" }); > +const pages = client.listTraderLeaderboard({ > + window: LeaderboardWindow.Month, > + sortBy: TraderLeaderboardSort.Pnl, > +}); > ``` > > * Added `fetchResolutions(...)` for resolution lifecycle lookups by question, condition, or event, with typed timestamps, transaction metadata, payouts, and finality. Unset values are omitted. > * Combo leg markets now preserve `question`, `groupItemTitle`, `sportsMarketType`, `line`, and `outcomes`. Trade activity tolerates unknown outcome metadata. > > ### `0.9.0` > > * Order estimation, preparation, creation, and placement now accept protocol-neutral `assetId` values. Structured Polymarket Protocol V2 position IDs select Polymarket Protocol V2 routing automatically, while `tokenId` remains available as a deprecated alias. > * Added `fetchTradingApprovalsState(...)` for reading a wallet's missing trading approvals without a signer or transaction workflow. Malformed approval-check responses now raise `UnexpectedResponseError`. > * Markets and events now expose their protocol through `version`, and markets expose Combo eligibility through `market.state.comboStatus`. Combo status values introduced after this release pass through as strings. > * Secure account reads now reject invalid request values and `user: null` with `UserInputError` instead of silently selecting the wallet or throwing an untyped error. > * Session Key authorization and revocation submissions now allow up to five minutes for relayer validation and broadcast. > * Breaking change: `revokeSessionKey(...)` now resolves to `void` once the Session Key leaves the active registry. The backend continues canceling orders and finalizing the on-chain revocation asynchronously. See [Revoke a Session Key](/trading/session-keys#revoke-a-session-key). > > ```diff theme={null} > -const revocation = await secureClient.revokeSessionKey({ > +await secureClient.revokeSessionKey({ > address: sessionKeyAddress, > }); > ``` > > * Team entries on event and team-list responses now preserve their `ordering` value. > * Breaking change: removed legacy AMM fields from market and event models, along with the `marketMakerAddresses` filter on `listMarkets(...)`. Responses that still contain the removed fields continue to parse, but those values are ignored. Use the supported CLOB metrics where applicable. > > ```diff theme={null} > -const volume = market.metrics.volumeAmm; > +const volume = market.metrics.volumeClob; > ``` > > ### `0.8.1` > > * `client.authorizeSessionKey(...)` no longer accepts `validUntil`. This is a breaking change. Each Session Key authorization expires after 180 days. Revoke a Session Key to end access sooner. > > ```diff theme={null} > const authorization = await client.authorizeSessionKey({ > address: sessionKeyAddress, > - validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), > }); > ``` > > ### `0.8.0` > > * Added protocol-neutral `assetId` and `conditionId` fields to CLOB reads, filters, realtime events, and Data API responses. The deprecated `tokenId`, `tokenIds`, and `market` aliases still work. > * Position lifecycle methods now split, merge, and redeem ordinary Polymarket Protocol V2 positions. Redemption by position ID supports binary, negative-risk, and Combo positions. > * `setupTradingApprovals()` and `prepareTradingApprovals()` now include the Polymarket Protocol V2 binary and negative-risk modules. > * Combo market discovery now exposes whether a market is `pending` and excludes pending markets when selecting live RFQ legs. > * Live volume reads now return `null` for empty market identifiers. > * Renamed the low-level CTF and Router transaction builders and their error guards to contract-specific names. This is a breaking change for callers that import them directly. > > ```diff theme={null} > import { > - mergePositionsCall, > - mergeV2Call, > - redeemV2Call, > - splitPositionCall, > - splitV2Call, > + ctfMergePositionsCall, > + ctfSplitPositionCall, > + routerMergeCall, > + routerRedeemCall, > + routerSplitCall, > } from "@polymarket/client"; > ``` > > ### `0.7.0` > > * Added scoped Deposit Wallet session keys through `client.authorizeSessionKey(...)`, `client.fetchSessionKeys()`, and `client.revokeSessionKey(...)`. Secure clients can use an authorized session signer for ordinary operations. Scopes default to `ALL`; known scopes are enumerated while newer scope strings remain usable. > * Account notifications now use a `NotificationType`-discriminated union with a typed payload for every supported kind. `fetchNotifications(...)` omits kinds unknown to this SDK version and rejects a response when a recognized kind has a malformed payload. > * `RateLimitError.rateLimit` now carries the `Poly-RateLimit-*` state returned with a rejection. Pass `onRateLimitUpdate` when creating a client to receive per-signer bucket, remaining, reset, tier, and warning updates from any response that reports them. > * Order estimation, preparation, creation, and placement now accept Polymarket Protocol V2 position IDs and route them through Exchange V3 signing and trading approvals. Existing token-ID orders remain supported. > * `listComboPositions(...)` now accepts either one status or an array of statuses. > * `RequestRejectedError.restriction` distinguishes matching-engine restarts from post-only mode, and `retryAfter` falls back to the response body's `retry_after_seconds` value when the header is absent. Batch post-only rejections now use the `post_only_mode` order error code. > * Order preparation now tolerates insignificant floating-point drift on valid tick-grid prices and uses exact fixed-point amount calculations. CLOB salts that cannot round-trip through a JavaScript number are rejected before submission. > * Breaking change: deprecated `CtfConditionId` type, use ConditionId\` instead. > > ```diff theme={null} > -import type { CtfConditionId } from "@polymarket/client"; > +import type { ConditionId } from "@polymarket/client"; > ``` > > ### `0.6.0` > > * Added requester-side Combos RFQ support through `client.requestComboQuote(...)`, `client.acceptComboQuote(...)`, and `client.waitForComboFill(...)`. You can also call `fetchRfqStatus` from `@polymarket/client/actions`. Authenticate requests with `builderApiKey(...)` or `remoteBuilderSigning(...)`. Winning quotes can be stored as JSON, and SELL quotes include the exact post-fee `netReceive`. No-quote, decline, and expiry outcomes return values. Gateway rejections throw `RfqRequestRejectedError`. > * Market outcomes now include a nullable Polymarket Protocol V2 `positionId` alongside the CLOB `tokenId`. New code should use the protocol-neutral `ConditionId`, `ConditionIdSchema`, `OptionalConditionIdSchema`, and `toConditionId`. The CTF-named aliases and market-level `positionIds` array remain available for compatibility but are deprecated. > * Breaking change: `client.fetchLastTradePrice(...)` now returns `LastTradePrice | null`. It returns `null` when the token has not traded. `client.fetchLastTradePrices(...)` leaves untraded tokens out of the response, so match results by `tokenId` instead of array position. > > ```diff theme={null} > -const price = (await client.fetchLastTradePrice({ tokenId })).price; > +const lastTrade = await client.fetchLastTradePrice({ tokenId }); > +const price = lastTrade?.price ?? null; > ``` > > ### `0.5.0` > > * Added a Perps dead man's switch: `session.armAutoCancel()` schedules a one-shot cancel-all, `session.disarmAutoCancel()` clears it, and `session.fetchAutoCancelStatus()` reports the current deadline and daily trigger usage. Arming after the daily limit raises `AutoCancelDailyLimitError`. > * Perps funding history and realtime funding events now include a required `id`, typed as `PerpsFundingPaymentId`. > * Fixed `session.placeOrder()` missing private order updates that arrive before the command acknowledgement. When the caller omits a client order ID, the SDK now generates one before submitting the order. > > ### `0.4.0` > > * Added `PerpsSession.updateMargin`, which adjusts isolated margin for an instrument position. Positive `amount` values add margin; negative values remove it. > * Repeated order preparation now caches market configuration and platform and builder fees. If cached tick data rejects a limit or protected market price, the SDK fetches current metadata once before returning the input error. > * Unprotected market orders now derive depth, price, tick size, and exchange selection from one live order book response. `maxSpend` remains an estimated all-in spend target based on recently resolved fees, not a hard cap. > * `AcceptedOrderResponse.orderId` is now typed as `OrderId`. > * Breaking TypeScript type change: `OrderBook.tickSize` is now a numeric `TickSizeValue` instead of a `DecimalString`. > > ```diff theme={null} > -const isOneCentTick = orderBook.tickSize === "0.01"; > +const isOneCentTick = orderBook.tickSize === 0.01; > ``` > > ### `0.3.0` > > * Added typed 30-second and 60-second Chainlink TWAP realtime subscriptions. `subscribe` validates subscription input when called: an unsupported TWAP window throws `UserInputError` before the connection opens. > * Added Perps account notifications: `session.listNotifications()`, `session.fetchUnreadNotificationsCount()`, `session.markNotificationsRead()`, and a `notifications` session WebSocket channel with typed `notification` events. > * Perps fills pagination now uses the API-native cursor and adds a `sort` direction option (newest first by default). Previously issued SDK-encoded fills cursors no longer work. > * Added the `DEPOSIT`, `WITHDRAWAL`, and `TAKER_REBATE` activity types. `listActivity` now returns all activity types by default, including deposits and withdrawals. > * `RequestRejectedError` and `RateLimitError` now expose `retryAfter` from the `Retry-After` response header. > * Fixes: > * Open order `createdAt` and `expiresAt` now parse epoch-seconds wire timestamps correctly instead of treating them as milliseconds. > * RFQ quote rejections now carry the granular Combos quote-validation error codes instead of a generic validation failure. > * Deposit Wallet gasless and Collateral Return submits now self-heal nonce mismatches: when the relayer rejects a batch and reports the on-chain nonce, the SDK re-signs the batch with that nonce and resubmits it once. > * Cursor-paginated reads no longer report the per-page item count as `Page.totalCount`. Use `page.items.length` instead. > > ### `0.2.0` > > * Added `client.waitForOrderFillSettlement(order)`, which waits until every fill in an order response reaches a terminal settlement outcome and returns the settlement transaction hashes. Matched order responses are no longer guaranteed to include `transactionsHashes`; use this method to obtain hashes reliably. > * `ClobTrade.status` is now typed with the shared `TradeStatus` enum instead of a plain string. > * Added Collateral Return support: `planCollateralReturn` returns an inspectable plan and `executeCollateralReturnPlan` signs and submits it for Deposit Wallet, Safe, and Proxy accounts, returning a transaction handle. > * Added `isolatedOnly` to `PerpsInstrument`, indicating whether the instrument supports only isolated margin. > * Added volume-based fee tiers to the Perps fee schedule: each `PerpsFeeScheduleEntry` carries a `tiers` array of `PerpsFeeTier` values, including negative maker rebate rates. > * Perps withdrawal statuses are now forward-compatible: known statuses are enumerated in `PerpsKnownWithdrawalStatus`, which adds `failed`, and statuses introduced after a release flow through as plain strings instead of failing the response parse. > * Deprecated the `PerpsWithdrawalStatus` value alias; migrate enum member access: > > ```diff theme={null} > -if (withdrawal.status === PerpsWithdrawalStatus.Confirmed) { > +if (withdrawal.status === PerpsKnownWithdrawalStatus.Confirmed) { > ``` > > * Fixed offset-paginated list methods silently stopping after the first page when `pageSize` reached the server's limit cap. `pageSize` is now validated per endpoint and values above the cap are rejected with `UserInputError`. A full page reports `hasMore: true`; when a collection ends exactly on a page boundary, the final page is empty. > * Limit and protected market order prices must be a multiple of the market tick size. Off-grid prices (for example `0.007` on a `0.005` tick market) are now rejected client-side instead of by the exchange after signing. > > ### `0.1.0` > > * Graduated the SDK to the stable 0.x release line, marked Perps APIs as experimental, and removed deprecated compatibility APIs. > * Added Perps support for reduce-only orders, account stats, cancel-all, TP/SL metadata and placement, batched fill and trade frames, and stricter order request validation. > * Added `conditionId` aliases to CLOB order book, open order, trade, and builder trade models while keeping `market` available as a deprecated alias. > * Typed CLOB cancellation results with branded `OrderId` values for `canceled` and `notCanceled` keys. > > ### `0.1.0-beta.18` > > * `setupTradingApprovals` and `prepareTradingApprovals` no longer request approvals for the retired CLOB v1 Neg Risk Adapter. > * Streams drop unknown or unreadable WebSocket frames instead of closing the connection. RFQ quoter sessions no longer fail with `TransportError` on an unrecognized frame; a caller waiting on an unreadable acknowledgement fails through its acknowledgement timeout instead. > * Removed `RfqKnownInboundMessageSchema` from `@polymarket/bindings`; each RFQ inbound message schema declares its own object shape directly. > > ### `0.1.0-beta.17` > > * RFQ quoter sessions now keep running when the server introduces new error codes. `RfqErrorCode` is an open type: known codes are enumerated in `RfqKnownErrorCode`, and unrecognized codes flow through rejection errors as plain strings. > * Deprecated the `RfqErrorCode` value alias; migrate enum member access: > > ```diff theme={null} > -if (error.code === RfqErrorCode.RateLimited) { > +if (error.code === RfqKnownErrorCode.RateLimited) { > ``` > > * Added `ConnectionLostError` carrying the WebSocket close `code` and `reason`. Losing an RFQ session connection now rejects in-flight operations and fails the session iterator with it, instead of ending the event loop silently. Closing the session still ends iteration cleanly. > * Streamed market and user events normalize empty-string optional decimal fields (for example a trade's `feeRateBps` or a price change's `bestBid` and `bestAsk`) to `null`. > * Batch price reads (`fetchPrices`, `fetchMidpoints`, `fetchSpreads`) return `TokenId`-keyed records of branded decimal strings. > * Perps sessions handle fills and trades frames that batch multiple entries. > > ### `0.1.0-beta.16` > > * Added `RESOLVED_PARTIAL` to `ComboPositionStatus` so Combo positions that resolve at a fractional payout (for example a voided leg) parse correctly instead of failing validation. > > ### `0.1.0-beta.15` > > * Combo activity now parses the canonical `type` field returned by the Data API, instead of deriving lifecycle actions from legacy fields. > > ### `0.1.0-beta.14` > > * Added SDK pagination for Combo lifecycle activity and server-cursor pagination for Combo positions. > * Added Combo position sync request fields and exposed `outcome` and `redeemable` on Combo positions. > * Branded Combo activity row IDs. > * Breaking beta change: Combo activity and position fields now use `wallet`, `amount`, and `payout`; Combo activity rows no longer expose `moduleKind`. > > ```diff theme={null} > -activity.userAddress > -activity.amountUsdc > -redeemActivity.payoutUsdc > -position.userAddress > +activity.wallet > +activity.amount > +redeemActivity.payout > +position.wallet > ``` > > ### `0.1.0-beta.13` > > * Added `listMarketClarifications` for reading market clarification text with SDK-owned pagination and market, event, state, question, and transaction filters. > * Fixed legacy Proxy wallet gasless execution and added live Safe and Proxy wallet coverage. > * Resolve closed markets when preparing market position redemptions. > * Gasless transaction handles now wait for relayer transactions to reach confirmed state before resolving. > > ### `0.1.0-beta.12` > > * Require GTD limit order expirations to be at least 3 minutes in the future. > > ### `0.1.0-beta.11` > > * Support CLOB order tick sizes `0.005` and `0.0025`. > * Pagination request cursors now infer the branded pagination cursor type. > > ### `0.1.0-beta.10` > > * Preserve already-deployed legacy UUPS Deposit Wallets when `createSecureClient` resolves the default wallet, while new Deposit Wallet deployments use the beacon factory path. > > ### `0.1.0-beta.9` > > * Added `PriceHistoryInterval` and `SearchSort` exports, preserved `groupItemTitle` on normalized markets, and published `expectPrivateKey` from `@polymarket/types`. > > ### `0.1.0-beta.8` > > * RFQ quoter sessions now emit typed `trade` events for confirmed Combos fills. > * RFQ rejection errors now expose `errorId` values and parse `INVALID_SIGNATURE` and `INTERNAL_ERROR` codes. > > ### `0.1.0-beta.7` > > * Added `parentEventId` to `Event` so child events can link back to their parent event. > * Added `maxPrice` and `minPrice` protection fields to market order requests. > * Handle legacy multi-outcome markets more safely: `listMarkets` skips markets that cannot be represented by the binary market model, and `fetchMarket` returns a typed SDK error for unsupported markets. > * Normalize empty-string order and activity fields to SDK values: decimal amounts become `"0"`, missing maker order fee rates become `null`, and missing trade or position market icons become `null`. > * Parse Combo trade activity rows with an `isCombo` discriminated union. > * Support new Combos RFQ websocket error codes for balance, allowance, and pre-execution reservation failures. > * Broad user websocket subscriptions now omit market filters so all-market streams receive trade events. > * Retry rejected JSON-RPC `eth_call` batches by splitting them into smaller batches. > > ### `0.1.0-beta.6` > > * Point Combos RFQ endpoints at the production domains: `combos-rfq-api.polymarket.com` (REST) and `combos-rfq-gateway-quoter.polymarket.com` (quoter WebSocket). > > ### `0.1.0-beta.5` > > * Added `listComboMarkets` for fetching the Combo market catalog with typed bindings and SDK-owned pagination. See [Combos](/trading/combos/overview). > * Parse RFQ quote rejections that use the `SUBMISSION_WINDOW_CLOSED` gateway error code. > > ### `0.1.0-beta.4` > > * Added Combos support for multi-leg RFQ positions. See [Combos](/trading/combos/overview). > * Reject whitespace-only search queries and trim leading or trailing search input. > * `ConditionId` is now deprecated in favor of `CtfConditionId`; existing > `ConditionId` exports remain available as deprecated aliases. > > ### `0.1.0-beta.3` > > **Secure client setup now defaults to the Deposit Wallet flow** > > `createSecureClient` can now derive and use the signer's deterministic Deposit > Wallet when you omit `wallet`. If you already know which Polymarket wallet you > want to use, keep passing `wallet`. > > ```diff theme={null} > const secureClient = await createSecureClient({ > - wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", > signer, > }); > ``` > > If you want to keep account selection explicit, no change is required: > > ```ts theme={null} > const secureClient = await createSecureClient({ > wallet: "YOUR_POLYMARKET_WALLET_ADDRESS", > signer, > }); > ``` > > **`setupTradingApprovals()` now waits internally** > > You no longer need to wait on the returned handle. Call the method once before > trading; it is safe to call again if approvals are already set. > > ```diff theme={null} > -const handle = await secureClient.setupTradingApprovals(); > -await handle.wait(); > +await secureClient.setupTradingApprovals(); > ``` > > **Gasless setup helpers are deprecated** > > You no longer need to call `isGaslessReady()` or `setupGaslessWallet()` in the > normal setup path. Create the secure client, then set up trading approvals. > > ```diff theme={null} > -const ready = await secureClient.isGaslessReady(); > - > -if (!ready) { > - secureClient = await secureClient.setupGaslessWallet(); > -} > - > await secureClient.setupTradingApprovals(); > ``` > > ### `0.1.0-beta.2` > > First beta release of the unified TypeScript SDK. Install the beta package with > your package manager: > > ```bash theme={null} > pnpm add @polymarket/client@beta > ``` > [tab] Python > > ### `0.20.0` > > * Breaking change: `list_open_orders(...)` now requires a nonblank market condition ID in `market` when filtering by `asset_id` or the deprecated `token_id` alias. Asset-only queries raise `UserInputError` when the paginator fetches a page. Unfiltered and market-only queries remain supported. This applies to sync and async clients. > > ```diff theme={null} > -pages = client.list_open_orders(asset_id=asset_id) > +pages = client.list_open_orders(asset_id=asset_id, market=condition_id) > ``` > > * `OpenOrder.associate_trades` is deprecated and defaults to an empty tuple when omitted from a response, preserving legacy values when present. Use `size_matched` for cumulative fills, or `list_account_trades()` for individual fills matched by `taker_order_id` or `maker_orders[].order_id`. An empty `associate_trades` tuple does not mean an order has no fills. > > ### `0.19.0` > > * Added `provider_api_key` to authenticated crypto and equity spot and TWAP price subscription specs. Set `provider="chainlink"` to authenticate with your Chainlink API key; the key is ignored for other providers. > > ### `0.18.0` > > * Added `list_wallet_open_orders(...)` to list open orders across a Deposit Wallet, including orders placed by its session keys. Each `WalletOpenOrder` reports the `signer_address` that placed it and a nullable `owner`. Filter by `market`, `asset_id`, or 1 to 50 `signer_addresses`. > * Added `cancel_wallet_orders(order_ids=...)` and `cancel_all_wallet_orders()` so the Deposit Wallet owner can cancel orders placed by any of its signers. `list_open_orders`, `cancel_order`, `cancel_orders`, and `cancel_all` still cover only orders placed with the client's own credentials. > * Session-key authorization and revocation now accept `api_key=RelayerApiKey(...)` as well as `api_key=BuilderApiKey(...)`. Authorization previously required a builder API key. > > ### `0.17.0` > > * Added `DIRECTIONAL_SPLIT`, `DIRECTIONAL_MERGE`, `THRESHOLD_COMPOSE`, and `THRESHOLD_DECOMPOSE` activity types and `list_activity(...)` filters. Threshold rows report the moved line position as `shares` and identify its market with `condition_id`; no collateral moves. Presentation fields are optional on range-event rows. > * Activity types absent from `ActivityType` remain available as `UnknownActivity`, with shared account fields and the full row in `raw`. > * Added Binance as an opt-in crypto spot price provider. Binance quotes use USDT spot closes under canonical USD symbols; omitting the provider keeps the existing default. > > ### `0.16.0` > > * Breaking change: removed `download_accounting_snapshot` from `PublicClient`, `SecureClient`, `AsyncPublicClient`, and `AsyncSecureClient`. Remove calls to this download. There is no replacement ZIP/CSV export; portfolio, position, and activity reads do not provide an equivalent archive. > > ```diff theme={null} > -snapshot = await client.download_accounting_snapshot(user=address) > +# Remove the snapshot download and code that consumes its archive. > ``` > > ### `0.15.0` > > * Added `market.trading.taker_delay_ms` for the taker delay in milliseconds. `market.trading.seconds_delay` is deprecated in favor of this field. > * Experimental Perps instrument reads, category filters, and fee schedules now accept `pre_ipo` and future category strings. Known returned categories use `PerpsKnownInstrumentCategory`; unknown categories remain strings. > * Perps instruments now expose optional `fee_override` and `funding_multiplier` windows. Stored windows can be scheduled or expired; their presence alone does not mean they are active. > * Added `instrument_id` to `fetch_perps_fees(...)` on async clients to read effective instrument fee schedules, including their stored override windows. Omitting it still returns category fee schedules. > > ### `0.14.0` > > * Added filtered reward-market discovery, current maker rebates by date/address, and outcome-token reference lookup. > * Added authenticated one-shot order heartbeats and mismatch-ID recovery. The first accepted send enables API-key-wide timeout cancellation with no disarm operation. Callers own scheduling and ID serialization. Cancellation after expiry is best effort. > * Sync and async automatic pagination now reject repeated continuation cursors and cycles with `UnexpectedResponseError`, after yielding fetched pages and before another duplicate request. Resumed walks seed the guard with their initial cursor. Normal completion and `limit_reached` retain precedence. > * Equity spot and TWAP events now expose `EquityMarketStatus` and optional `market_status`. `None` means not stated, never implicitly open. Spot status-only updates may repeat the price timestamp with `is_carried_forward=True`. Do not deduplicate by timestamp alone. Older unstated spot frames retain the cached stated status. Snapshots can include an older closing price. > * Combo trades and redemptions retain token `outcome` and `outcome_index`. Blank labels and index `999` become `None`, while index zero is preserved. Split/merge/redemption activity retains `is_combo`, and redemption keeps the public `RedeemActivity` class. Check optional presentation and URL fields before using them. Automatic redemption remains `REDEEM`. > * Added oracle metadata and request-ID, event-ID, resolution-status, and protocol filters. Event protocol-version selection is preserved through pagination. > * Added native/sponsored earnings breakdowns, sponsored queries, and taker-tier upgrade notifications. > * New-market `game_start_time` accepts Postgres datetime strings while preserving timestamp units and validation errors. Known user order statuses have named enum constants, including `INVALID` and cancellation reasons. Future values remain preserved. > * Experimental Perps retain fill risk details and instrument filters, portfolio margin/risk tiers, instrument visibility/logos, and exchange event horizons independently of send time. Unknown zero horizons become `None`. Synthetic recovery does not invent one. Visibility metadata does not establish trading eligibility. Complete millisecond transfer-history pages continue without duplicate or skipped rows. > * Obsolete closed-position cursors require a manual restart. Resolution lifecycle rows may retain the initial request log index while their transaction hash identifies a later event. Do not combine them as a log locator. Condition-resolution fallback rows carry their own event metadata. > > ### `0.13.0` > > * `get_trading_approvals_state(...)` now reads indexed approval state from the configured environment. Recent grants and revocations may take time to appear; RPC overrides no longer affect these reads, and failures surface without an RPC fallback. Trading setup continues to check approvals on chain. Incomplete or mismatched snapshots raise `UnexpectedResponseError`. > * Added 60-second equity TWAP subscriptions through `EquityTwapPriceSpec`. > * Price specs now accept a Chainlink or Pyth provider. Realtime updates and history snapshots expose their source, and cached history resets when the source changes. > * Corrected the return types for subscriptions combining three price topics. > * Positions now expose optional timezone-aware `first_entry_at` values. > * Added a case-insensitive `title` filter to `list_positions(...)`, retained across pages. Patterns accept up to 200 characters; `%` and `_` keep their wildcard meaning. > * Added `sort_by="PRICE"` to position listings. Redeemable listings retain winners-first ordering, and closed wallet listings retain realized-PnL ordering. > * Resolution records now expose optional `expected_settlement_time` and `settlement_time_basis`. These are earliest settlement estimates, not guaranteed deadlines. > * Added experimental Perps GTD orders with separate order expiry, batch validation, signing, and order updates. > * Added experimental Perps chase creation, active reads, and cancellation through the async session. > * Added experimental Perps TWAP creation, active reads, pause, resume, and cancellation through the async session. > * Position TP/SL triggers now accept a quantity for partial exits; omitting it still closes the full position. > * Added experimental trailing stop losses, partial exits, activation events, and live trailing metadata, including support for small numeric activation prices. > * Added experimental public and owner position snapshots through async clients and sessions, with exact trade IDs and a result for each selection. > * Added a public Perps registration lookup on async clients. > * Perps instruments now expose close-only state, settlement records, and display labels. Trades and fills expose settlement flags. > * Added ordered batch Perps leverage updates with a rejection result for each instrument and stricter response validation. > * Added paginated Perps internal transfer history through the async session. > * Perps notification history and session events now include `position_deleveraged`. Exhaustive notification handlers must handle this new variant; Perps remains experimental: > > ```diff theme={null} > match notification.type: > + case "position_deleveraged": > + print(notification.size_closed, notification.price, notification.pnl) > ``` > > * Order history and private updates now accept current terminal Perps statuses, including instrument retirement, fill-time margin failures, and order limits. > * Perps cancellations now expose typed rejection reasons and retry transient `order_in_flight` results with bounded backoff. If a later attempt fails, `PerpsCancelRetryError` preserves earlier outcomes and pending request indexes for reconciliation. > * Rejection and rate-limit errors now accept HTTP-date `Retry-After` headers as nonnegative whole seconds. Retry policy is unchanged. > > ### `0.12.0` > > * Added experimental Perps builder-code support through the async session: approve fees with an explicit `max_fee_rate`, revoke approval, read builder earnings, and receive builder receipts with `include_builder_fills=True`. Selecting a builder restores existing consent; it does not grant new consent. Fills expose `builder_fee` and `total_fee`, while `fee` remains the exchange fee. > * Added `REDEEMABLE_LOST` and `MERGEABLE` filters to `list_positions(...)` for still-held zero-payout positions and live complementary positions. Both require a wallet; secure clients use the authenticated wallet. Returned `Position.status` values remain `OPEN`, `REDEEMABLE`, or `CLOSED`, represented by `PositionRowStatus`. Mergeable listings default to sorting by `TOKENS`. > * `list_comments(...)` can page through a whole thread when `holders_only` and `get_positions` are unset or false and `order` is omitted, `id`, or `createdAt`. These cursors are bound to the parent, order, and direction; reusing one for a different query raises an error. Previously saved cursors remain usable with the same arguments. > * Comment reads using other options, including reads by user address, stop automatic iteration at the supported offset depth and expose `page.limit_reached=True`. Explicitly following a cursor beyond that depth raises `PaginationLimitError`. Pandas and Arrow exports preserve the depth-limit signal; Polars exports warn because they cannot retain it. > * Splitting, merging, and redeeming positions now select the protocol from the market's `version`. Missing versions or identifiers required by that protocol raise `UnexpectedResponseError`. > * Account trade pages now accept missing or empty transaction hashes as `None`. Callers that assumed every trade had a hash must handle its absence: > > ```diff theme={null} > -short_hash = trade.transaction_hash[:10] > +short_hash = trade.transaction_hash[:10] if trade.transaction_hash is not None else None > ``` > > * Sports metadata now preserves the sport's `name`. > > ### `0.11.0` > > * Added authenticated PolyBolt crypto, 60-second TWAP, and equity price streams through `AsyncSecureClient.subscribe(...)`, with history snapshots, exact decimal prices, automatic reconnects, typed price events, and isolated filter rejections. Use `CryptoPriceSpec`, `CryptoTwapPriceSpec`, or `EquityPriceSpec` from `polymarket.streams`; crypto symbols must be canonical USD pairs such as `btcusd`, while equity prices use the instrument's quote currency. Legacy price specs remain deprecated. Migrating Binance prices changes USDT quotes to USD; 30-second TWAP has no replacement. See the [SDK migration guide](/migrate/rtds-to-polybolt#migrate-sdks-to-polybolt). > > Given an authenticated `AsyncSecureClient`, migrate a crypto subscription as follows: > > ```diff theme={null} > -from polymarket.streams import CryptoPricesSpec > +from polymarket.streams import CryptoPriceSpec > > stream = await client.subscribe([ > - CryptoPricesSpec(topic="prices.crypto.chainlink", symbols=["btc/usd"]), > + CryptoPriceSpec(symbols=["btcusd"]), > ]) > ``` > > * Protected market BUY orders round shares so they can cross at `max_price` while preserving the cap across tick-size refinements. When rounding cannot preserve the cap, the SDK refreshes market metadata once before rejecting the order. > * `list_markets(...)` sorts `order="volume"` and `order="liquidity"` numerically. Previously saved cursors with these sort fields are incompatible; restart from the first page after upgrading. > > ```diff theme={null} > pages = client.list_markets(order="volume") > -page = await pages.from_cursor(saved_cursor).first_page() > +page = await pages.first_page() > ``` > > ### `0.10.0` > > * Breaking change: trade, activity, position, and Combo reads now use server cursors. Restart scans from the first page when upgrading from `0.9.0`. Replace `market` filters with `condition_id`. Time bounds accept epoch seconds or timezone-aware `datetime` values. Use `full_history=True` without `start` or `end` to request full history. Position reads remain unbounded by default, including holdings without an activity timestamp. > > ```diff theme={null} > pages = client.list_activity( > user=user, > - market=[condition_id], > + condition_id=[condition_id], > ) > ``` > > * Breaking change: `list_positions(...)` replaces `list_closed_positions(...)` and `list_market_positions(...)`. Use `status="CLOSED"` for closed positions and `status="REDEEMABLE"` for redeemable positions. For a market's holders, use a public client's `list_positions(condition_id=condition_id)`. Secure clients default to the authenticated wallet. Market position results are individual `Position` rows. > > ```diff theme={null} > -pages = client.list_closed_positions(user=user) > +pages = client.list_positions(user=user, status="CLOSED") > ``` > > * Breaking change: position rows now expose `current_size`, `current_price`, `total_size`, and explicit entry costs and fees. Prices, sizes, PnL, and percentages use `Decimal`. `entry_cost_usdc` excludes fees. Do not subtract `entry_fees_usdc` from it again. > > ```diff theme={null} > -shares = position.size > -price = position.cur_price > -bought = position.total_bought > +shares = position.current_size > +price = position.current_price > +bought = position.total_size > ``` > > * Breaking change: replace `get_market_holders(...)` with the paginated `list_market_holders(...)`. Pass `condition_ids` and `page_size`. Merge outcome groups across pages by `asset_id`. `include_pnl=True` adds position economics for one condition with a maximum page size of 100. > > ```diff theme={null} > -holders = await client.get_market_holders(market=[condition_id], limit=10) > +pages = client.list_market_holders(condition_ids=[condition_id], page_size=10) > +page = await pages.first_page() > +holders = page.items > ``` > > * Breaking change: `get_portfolio_value(...)` returns one `PortfolioValue` instead of a tuple. Portfolio and open-interest filters now use `condition_ids`. > > ```diff theme={null} > -values = await client.get_portfolio_values(user=user, market=[condition_id]) > -value = values[0].value > +portfolio = await client.get_portfolio_value(user=user, condition_ids=[condition_id]) > +value = portfolio.value > > -interest = await client.get_open_interests(market=[condition_id]) > +interest = await client.get_open_interests(condition_ids=[condition_id]) > ``` > > * Added `get_user_stats(...)`, `get_user_pnl(...)`, and `get_user_volume(...)` for wallet analytics. Breaking change: replace `get_traded_market_count(...)` with `UserStats.traded_market_count`. Statistics return `None` when unavailable. Secure clients default these reads to the authenticated wallet. > > ```diff theme={null} > -count = (await client.get_traded_market_count(user=user)).traded > +stats = await client.get_user_stats(user=user) > +count = stats.traded_market_count if stats is not None else None > ``` > > * Breaking change: replace `get_price_history(...)` with the paginated `list_price_history(...)`. Use `asset_id`, `start`/`end`, and `bucket_seconds` instead of `token_id`, `start_ts`/`end_ts`, and minute-based `fidelity`. Select an interval, a window of at most 15 days, or an exact `as_of` timestamp. Price points now expose `timestamp`, `price`, and `resolution_seconds`. > > ```diff theme={null} > -points = await client.get_price_history(asset_id=asset_id, interval="1d", fidelity=1) > +pages = client.list_price_history(asset_id=asset_id, interval="1d", bucket_seconds=60) > +page = await pages.first_page() > +points = page.items > ``` > > * Breaking change: trader and builder leaderboards now take lowercase `window` values. Trader sorting uses `sort_by`. Use `get_trader_leaderboard_standing(user=...)` for an individual wallet's rankings. Added `list_biggest_winners(...)` for winning market and Combo positions. > > ```diff theme={null} > -pages = client.list_trader_leaderboard(time_period="DAY", order_by="PNL") > +pages = client.list_trader_leaderboard(window="day", sort_by="PNL") > > -pages = client.list_builder_leaderboard(time_period="DAY") > +pages = client.list_builder_leaderboard(window="day") > ``` > > * Breaking change: `get_builder_volumes(...)` returns `BuilderVolumePoint` calendar buckets. Use `interval` and `bucket_limit`, which counts dates rather than rows. > > ```diff theme={null} > -volumes = await client.get_builder_volumes(time_period="DAY") > +volumes = await client.get_builder_volumes(interval="day", bucket_limit=30) > ``` > > * Breaking change: `get_event_live_volume(...)` accepts integer `event_ids` and returns one combined `LiveVolume`. Read `taker_volume_total` for total shares and `markets` for the breakdown. > > ```diff theme={null} > -volumes = await client.get_event_live_volumes(id=str(event_id)) > +volume = await client.get_event_live_volume(event_ids=[event_id]) > ``` > > * Added `get_resolutions(...)` for resolution status and payouts by question, conditions, or events. Resolution payouts preserve their values through serialization and parsing. > * Breaking change: Combo position sorting now uses separate `sort_by` and `sort_direction` arguments. Status filters accept multiple values, except `"REDEEMABLE"`, which must be used alone. Update bounds accept epoch seconds or timezone-aware `datetime` values. > > ```diff theme={null} > -pages = client.list_combo_positions(user=user, sort="current_value_desc") > +pages = client.list_combo_positions(user=user, sort_by="CURRENT_VALUE", sort_direction="DESC") > ``` > > * Added typed migration and tip activity and public activity/status enums. Breaking change: Combo activity now exposes `position_id` and uses `timestamp` instead of `transaction_at`. `log_index` and `module_id` are removed. > > ```diff theme={null} > -occurred_at = activity.transaction_at > +occurred_at = activity.timestamp > ``` > > * Data reads now retry short-lived rate limits. Invalid filters, time bounds, event IDs, and cursor inputs raise `UserInputError`. Malformed response identities raise `UnexpectedResponseError`. > * Fixed UTC interpretation of date-only timestamps, preservation of full position history and zero-valued Combo update bounds, and dataframe exports containing both enum and string activity values. > > ### `0.9.0` > > * Added protocol-neutral `asset_id` and `condition_id` fields across CLOB reads, filters, realtime events, and Data API responses. Pass a CTF token ID or Polymarket Protocol V2 position ID through `asset_id`; the deprecated `token_id`, `token_ids`, and `market` aliases remain available for compatibility. > * Order estimation, creation, and placement now route Polymarket Protocol V2 position IDs through Exchange V3, and `setup_trading_approvals()` includes the Polymarket Protocol V2 binary and negative-risk modules. > * Position lifecycle methods now split and merge ordinary Polymarket Protocol V2 positions. `merge_multiple_positions(...)` accepts Polymarket Protocol V2 `position_id` requests, and `redeem_positions(position_id=...)` redeems a resolved Polymarket Protocol V2 position. > > ### `0.8.0` > > * Markets and events now expose their protocol through `version`, and markets expose Combo eligibility through `market.state.combo_status`. Combo status values introduced after this release pass through as strings. > * Team entries on event and team-list responses now preserve their `ordering` value. > * Breaking change: `revoke_session_key(...)` now returns `None` once the Session Key leaves the active registry. The SDK retries transient registry reads, while the backend continues canceling orders and finalizing the on-chain revocation asynchronously. See [Revoke a Session Key](/trading/session-keys#revoke-a-session-key). > > ```diff theme={null} > -transaction = await secure_client.revoke_session_key( > +await secure_client.revoke_session_key( > address=session_key_address, > ) > ``` > > * Session Key authorization and revocation submissions now allow up to five minutes for relayer validation and broadcast. > > ### `0.7.1` > > * `authorize_session_key(...)` no longer accepts `valid_until`. This is a breaking change. Each Session Key authorization expires after 180 days. Revoke a Session Key to end access sooner. > > ```diff theme={null} > authorization = await secure_client.authorize_session_key( > address=session_key_address, > - valid_until=datetime.now(UTC) + timedelta(days=30), > ) > ``` > > ### `0.7.0` > > * Added scoped Deposit Wallet session keys through `authorize_session_key(...)`, `fetch_session_keys()`, and `revoke_session_key(...)` on secure clients. Secure clients can use an authorized session signer for ordinary operations. Scopes default to `ALL`; known scopes are enumerated while newer scope strings remain usable. > * `RateLimitError.rate_limit` now carries the `Poly-RateLimit-*` state returned with a rejection. Pass `on_rate_limit_update` when creating a client to receive per-signer rate-limit updates from any response that reports them. > * Added `get_trading_approvals_state(...)` to public and secure clients so applications can inspect missing ERC-20 and ERC-1155 approvals without submitting transactions. > * `RequestRejectedError.restriction` now distinguishes matching-engine restarts, cancel-only mode, and post-only mode. `retry_after` falls back to the response body's `retry_after_seconds` value when the header is absent. > * Breaking change: account notifications are now a `NotificationType`-discriminated union whose payloads are typed Pydantic models instead of arbitrary mappings. Narrow on `notification.type`, then read payload fields as attributes. > > ```diff theme={null} > -if notification.type == 2: > - order_id = notification.payload["order_id"] > +if notification.type == NotificationType.ORDER_FILL: > + order_id = notification.payload.order_id > ``` > > ### `0.6.0` > > * Added requester-side Combos RFQ support to `SecureClient` and `AsyncSecureClient` through `request_combo_quote(...)`, `accept_combo_quote(...)`, `wait_for_combo_fill(...)`, and `fetch_rfq_status(...)`. Pass a Builder API key through `api_key=`. `ComboQuote` values can be serialized, and SELL quotes include the exact post-fee `net_receive`. No-quote, decline, expiry, and terminal failure outcomes return values. Gateway rejections raise `RfqRequestRejectedError`. > * Breaking change: `get_last_trade_price(...)` now returns `LastTradePrice | None`. Untraded tokens return `None` instead of a `Decimal("0.5")` placeholder. `get_last_trade_prices(...)` leaves untraded tokens out of the response, so match results by `token_id` instead of array position. > > ```diff theme={null} > -price = client.get_last_trade_price(token_id=token_id).price > +last_trade = client.get_last_trade_price(token_id=token_id) > +price = last_trade.price if last_trade is not None else None > ``` > > ### `0.5.0` > > * Added a Perps dead man's switch: `session.arm_auto_cancel()` schedules a one-shot cancel-all, `session.disarm_auto_cancel()` clears it, and `session.fetch_auto_cancel_status()` reports the current deadline and daily trigger usage. Arming after the daily limit raises `AutoCancelDailyLimitError`. > * Perps funding history and realtime funding events now include a required `id`, typed as `PerpsFundingPaymentId`. > * Fixed `session.place_order()` missing private order updates that arrive before the command acknowledgement. When the caller omits a client order ID, the SDK now generates one before submitting the order. > * Order placement now caches market configuration and platform and builder fees, reducing repeated metadata reads while refreshing stale tick data before returning an input error. > > ### `0.4.0` > > * Added async `PerpsSession.update_margin`, which adjusts isolated margin for an instrument position. Positive `amount` values add margin; negative values remove it. > * `AcceptedOrder.order_id` is now typed as `OrderId`. > > ### `0.3.0` > > * Added typed 30-second and 60-second Chainlink TWAP realtime subscriptions. > * Added Perps account notifications: `session.list_notifications()` with the account's `unread` count on each page, `session.mark_notifications_read()`, and a `notifications` session WebSocket channel with typed `notification` events. > * Perps fills pagination now uses the API-native cursor, and `list_fills` accepts a `sort` direction (newest first by default). > * Added the `DEPOSIT`, `WITHDRAWAL`, and `TAKER_REBATE` activity types. `list_activity` now returns all activity types by default, including deposits and withdrawals. > * `RequestRejectedError` now exposes `retry_after` from the `Retry-After` response header or a `retry_after_seconds` response field. > * Fixes: > * RFQ quote rejections now carry the granular Combos quote-validation error codes instead of a generic validation failure. > * Deposit Wallet gasless and Collateral Return submits now self-heal nonce mismatches: when the relayer rejects a batch and reports the on-chain nonce, the SDK re-signs the batch with that nonce and resubmits it once. > * Collateral Return operation `event_id` values are now typed as `EventId`. > > ### `0.2.0` > > * Added `wait_for_order_fill_settlement`, which waits until every fill in an order response reaches a terminal settlement outcome and returns the settlement transaction hashes. > * Added Collateral Return support to secure clients: `plan_collateral_return` returns an inspectable plan and `execute_collateral_return_plan` signs and submits it for Deposit Wallet, Safe, and Proxy accounts, returning a transaction handle. > * Added `isolated_only` to Perps instruments, indicating whether the instrument supports only isolated margin. > * Added volume-based fee tiers to the Perps fee schedule, including negative maker rebate rates, typed with `PerpsFeeTier`. > * Perps withdrawal statuses are now forward-compatible: known statuses are enumerated in `PerpsKnownWithdrawalStatus`, which adds `failed`, and statuses introduced after a release flow through as plain strings instead of failing the response parse. `list_withdrawals` accepts `withdrawal_status="failed"`. > * Fixed offset-paginated reads silently stopping after the first page when `page_size` reached the server's limit cap. `page_size` is now validated per endpoint and values above the cap raise `UserInputError`. A full page reports `has_more=True`; when a collection ends exactly on a page boundary, the final page is empty. > * CLOB cursor-paginated reads no longer report the per-page row count as `Page.total_count`; it was never the total across pages. Use the page items instead: > > ```diff theme={null} > -count = page.total_count > +count = len(page.items) > ``` > > * Open orders with no expiration now parse `expires_at` as `None`. GTC orders report a zero expiration, which previously parsed as the Unix epoch. > > ### `0.1.0` > > * Graduated the SDK to the stable 0.x release line, marked Perps APIs as experimental, and removed deprecated beta compatibility APIs. > * Added `condition_id` aliases to CLOB models while keeping `market` available as a deprecated alias. > * Typed CLOB cancellation result IDs with `OrderId`. > * Streams drop unknown or unreadable WebSocket frames instead of closing the connection. > * Limit and market order helpers reject prices that are not a multiple of the market tick size. > > ### `0.1.0b21` > > * `setup_trading_approvals` no longer requests approvals for the retired CLOB v1 Neg Risk Adapter. > > ### `0.1.0b20` > > * RFQ quoter sessions now keep running when the server introduces new error codes: unrecognized codes are carried on rejection errors as plain strings, while known codes stay typed through the `RfqErrorCode` enum. > * Added `ConnectionLostError` carrying the WebSocket close `code` and `reason`. Losing an RFQ session connection now raises it from in-flight operations and the session iterator, instead of a generic `TransportError`. Closing the session still ends iteration cleanly. > * Optional decimal fields on streamed market and user events treat empty strings as absent (for example a trade's `fee_rate_bps` or a price change's `best_bid` and `best_ask`). > * Batch price reads return `TokenId`-keyed maps. > * Perps streams handle fill and trade frames that batch multiple entries. > > ### `0.1.0b19` > > * Added `RESOLVED_PARTIAL` to `ComboPositionStatus` so Combo positions that resolve at a fractional payout (for example a voided leg) parse correctly instead of failing validation. > > ### `0.1.0b18` > > * Combo activity now parses the canonical `type` field returned by the Data API, instead of deriving lifecycle actions from legacy fields. > > ### `0.1.0b17` > > * Added SDK pagination for Combo lifecycle activity and server-cursor pagination for Combo positions. > * Added typed overloads for market, event, and tag lookups, mutually-exclusive lookup arguments, and `redeem_positions`. > * Added trade time filters. > * Hardened Combo pagination filters and branded Combo activity IDs. > * Breaking beta change: Combo activity and position fields now use `wallet`, `amount`, and `payout`; Combo activity rows no longer expose `module_kind`. > > ```diff theme={null} > -activity.user_address > -activity.amount_usdc > -redeem_activity.payout_usdc > -position.user_address > +activity.wallet > +activity.amount > +redeem_activity.payout > +position.wallet > ``` > > ### `0.1.0b16` > > * Fixed Deposit Wallet trading setup approvals to use the current Protocol V2 auto-redeem operator. > > ### `0.1.0b15` > > * Added support for Perps. > > ### `0.1.0b14` > > * Added builder API key management for creating, fetching, and revoking builder API keys. > * Added support for merging multiple positions in one request. > * Added runnable Python SDK examples for common integration workflows. > * Resolve closed markets when redeeming positions. > * Gasless transaction handles now wait for relayer transactions to reach confirmed state before resolving. > > ### `0.1.0b13` > > * Require GTD limit order expirations to be at least 3 minutes in the future. > > ### `0.1.0b12` > > * Support CLOB order tick sizes `0.005` and `0.0025`. > > ### `0.1.0b11` > > * Preserve already-deployed legacy UUPS Deposit Wallets when secure clients resolve the default wallet, while new Deposit Wallet deployments use the beacon factory path. > * Retry rejected JSON-RPC batches by splitting them into smaller batches. > * Added typed Gamma search sort fields for search requests. > > ### `0.1.0b10` > > * Preserve `group_item_title` on market responses so grouped market titles remain available after normalization. > > ### `0.1.0b9` > > * RFQ quoter sessions now emit typed `RfqTradeEvent` events for confirmed Combos fills. > * RFQ rejection errors now expose `error_id` values and parse `INVALID_SIGNATURE` and `INTERNAL_ERROR` codes. > > ### `0.1.0b8` > > * Added `parent_event_id` to `Event` so child events can link back to their parent event. > * Added `max_price` and `min_price` protection fields to market order requests. > * Handle legacy multi-outcome market listings more safely by omitting markets that cannot be represented by the binary market model. > * Normalize empty-string trade and position market icons to `None`. > * Parse Combo trade activity rows correctly. > * Support new Combos RFQ error codes for balance, allowance, and pre-execution reservation failures. > * Broad user websocket subscriptions now omit market filters so all-market streams receive trade events. > > ### `0.1.0b7` > > * Point Combos RFQ endpoints at the production domains: `combos-rfq-api.polymarket.com` (REST) and `combos-rfq-gateway-quoter.polymarket.com` (quoter WebSocket). > > ### `0.1.0b6` > > * Added `list_combo_markets` for fetching the Combo market catalog with SDK pagination. See [Combos](/trading/combos/overview). > * Parse RFQ quote rejections that use the `SUBMISSION_WINDOW_CLOSED` gateway error code. > > ### `0.1.0b5` > > * Added Combos support for multi-leg RFQ positions. See [Combos](/trading/combos/overview). > * Added notebook-friendly model display for Jupyter workflows. > * `ConditionId` is now deprecated in favor of `CtfConditionId`; existing > `ConditionId` exports remain available as deprecated aliases. > > ### `0.1.0b4` > > * Added dataframe conversion support for SDK models and response collections. > > **Secure client setup now defaults to the Deposit Wallet flow** > > `AsyncSecureClient.create` can now derive and use the signer's deterministic > Deposit Wallet when you omit `wallet`. If you already know which Polymarket > wallet you want to use, keep passing `wallet`. > > ```diff theme={null} > secure_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > - wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > If you want to keep account selection explicit, no change is required: > > ```python theme={null} > secure_client = await AsyncSecureClient.create( > private_key=os.environ["POLYMARKET_PRIVATE_KEY"], > wallet=os.environ["POLYMARKET_WALLET_ADDRESS"], > ) > ``` > > **`setup_trading_approvals()` now waits internally** > > You no longer need to wait on the returned handle. Call the method once before > trading; it is safe to call again if approvals are already set. > > ```diff theme={null} > -handle = await secure_client.setup_trading_approvals() > -await handle.wait() > +await secure_client.setup_trading_approvals() > ``` > > **Gasless setup helpers are deprecated** > > You no longer need to call `is_gasless_ready()` or `setup_gasless_wallet()` in > the normal setup path. Create the secure client, then set up trading approvals. > > ```diff theme={null} > -ready = await secure_client.is_gasless_ready() > - > -if not ready: > - secure_client = await secure_client.setup_gasless_wallet() > - > await secure_client.setup_trading_approvals() > ``` > > ### `0.1.0b1` > > First beta release of the unified Python SDK. Install the beta package with your > package manager: > > ```bash theme={null} > uv add polymarket-client > ``` # Get builder volume over time Source: https://docs.polymarket.com/api-reference/boards/get-builder-volume-over-time https://data-api.polymarket.com/v2/openapi.json get /v2/builders/volume The per-builder volume time series. `?interval=` is the **bucket width**, not a window: `day` (default) returns every day on record bucketed daily, `week` and `month` bucket accordingly, and `all` buckets by calendar YEAR. `?limit=` bounds how many of the most recent buckets come back (default 30); buckets, not rows, so a period is never returned half-populated. `timePeriod` is accepted as an alias for `interval`. `rank` is the builder's placing **within its own bucket**, so it moves along the series. `volume` is in SHARES; see `/v2/builders/leaderboard`. Not paginated: `data` is the array with no `pagination`, the `/v2/oi` shape. Rows arrive newest bucket first, ranked within each. # Get the builders leaderboard Source: https://docs.polymarket.com/api-reference/boards/get-the-builders-leaderboard https://data-api.polymarket.com/v2/openapi.json get /v2/builders/leaderboard The ranked board of builders by volume. `?time_period=` is `day` (default), `week`, `month` or `all` and selects the **window**; one row per builder in it. Deeper pages come only from `?cursor=`. A cursor **pins the window it was minted on**, so following it needs no `?time_period=`; and passing a different one is a `400` rather than a silent re-point, since an offset from one board means nothing on another. `volume` is in SHARES, not USDC, the same unit as `/v2/leaderboard`'s `volume`. `active_users` counts distinct makers in the window. `builder` is a display name that falls back to `builder_code` for a builder with no profile, so key on `builder_code` and render `builder`. # Get the trader leaderboard Source: https://docs.polymarket.com/api-reference/boards/get-the-trader-leaderboard https://data-api.polymarket.com/v2/openapi.json get /v2/leaderboard The ranked board of realized PnL, combos included. `?time_period=` is `day` (default), `week`, `month` or `all`; `?category=` is `overall` (default) or a market category; `?sort_by=` picks the `PNL` (default) or `VOLUME` board. Deeper pages come only from `?cursor=`. A cursor **pins the board it was minted on**; sort, window and category; so following it needs no params at all, and restating a different one is a `400` rather than a silent re-point (the builders-board pattern). `?user=` answers a different question; one wallet's standing, carrying **both** the PnL and volume ranks in a single object rather than a page. A rank of `0` there means unranked for that board, not first. `sort_by`, `limit` and `cursor` do not apply to that arm. **`rank` ties and skips**: tied users share a rank and the next one jumps, so a partition's highest rank approaches its row count. Page with the cursor; never compute a page from a rank. Finite windows (day/week/month) serve the MARKED equity change net of flows; they move with unrealized marks; `all` is the realized-only lifetime ledger. `volume` is in shares, not USDC. # List the biggest wins Source: https://docs.polymarket.com/api-reference/boards/list-the-biggest-wins https://data-api.polymarket.com/v2/openapi.json get /v2/biggest-winners The biggest single winning positions. One row per winning POSITION, not per user: `pnl` is `final_value - initial_value` for that position, and the window (`?time_period=`, default `day`) is on when it resolved. `?category=` narrows to a market category. Deeper pages come only from `?cursor=`, which **pins the window and category it was minted on**; restating a different one is a `400`, not a silent re-point. Combo wins are first-class rows here, tagged `kind = "combo"`. They carry a `' / '`-joined title of their legs and no Gamma event; `event_id` is `0` and `event_slug` empty; so **branch on `kind` before building an event link**. # List account activity Source: https://docs.polymarket.com/api-reference/feeds/list-account-activity https://data-api.polymarket.com/v2/openapi.json get /v2/activity Keyset-paginated activity feed (trades, splits, merges, redeems, …) in the standard `{ data, pagination }` envelope. Ordering is `(block_timestamp, sequence_id)`, `DESC` by default or `ASC` via `sort_direction=ASC`; both keyset-seekable. Value sorts (`CASH`/`TOKENS`) have no seek anchor and are rejected with `400` rather than silently re-served as page one. The cursor binds the direction it was minted under and the resume ADOPTS it, so a replay cannot flip the walk mid-stream. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # List combo activity Source: https://docs.polymarket.com/api-reference/feeds/list-combo-activity https://data-api.polymarket.com/v2/openapi.json get /v2/activity/combos Keyset-paginated combo lifecycle + redemption feed for a user, in the standard `{ data, pagination }` envelope. Pass `?cursor=` from a prior response's `next_cursor` to fetch the next page. Unlike the activity feed, the anchor behind the cursor is `(block_number, log_index)`; this endpoint's total order. A malformed `condition` combo condition id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state. # List trades Source: https://docs.polymarket.com/api-reference/feeds/list-trades https://data-api.polymarket.com/v2/openapi.json get /v2/trades Keyset-paginated trade feed in the standard `{ data, pagination }` envelope. Pass `?cursor=` from a prior response's `next_cursor` to fetch the next page; it carries both the page size and the `(block_timestamp, sequence_id)` seek anchor, so deep pages cost the same as shallow ones. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # Get a token's price history Source: https://docs.polymarket.com/api-reference/markets/get-a-tokens-price-history https://data-api.polymarket.com/v2/openapi.json get /v2/prices-history The price-history series for one outcome token, or a single point-in-time observation. Three window forms, exactly one per request: `start` (with optional `end`), `interval`, or `as_of`. Points are served oldest-first; pass `?cursor=` from a prior response's `next_cursor` for the next page. `interval=max` (or `all`) serves the market's whole life, back to 2022 for the oldest markets, at 12-hour buckets unless `bucket_seconds` says otherwise; explicit `start`/`end` windows cap at 15 days, so the presets are the long-range path. The series ends with a **terminal point**: the latest observation inside the window, which is a real tick and so can fall between bucket boundaries. Nothing may assume uniform spacing (sparse data already forbids that), and each point's `resolution_seconds` says what window it was observed in. **Availability is graded by resolution.** The 3-hour and 12-hour series are permanent (back to 2022-11-18); the fine grains are windowed, with these MINIMUMS: 1-minute data at least 7 days, 5-minute at least 60, 30-minute at least 90. Floors, not exact horizons: data expires in multi-day chunks, so a grain usually reaches a few days further back than its minimum. Coverage is measured per request, never assumed from a table, so `bucket_seconds=60` over a window starting a month ago is an incompatible pair: both values are valid, and there is no data at their intersection. The two ways of asking behave differently on purpose: * **`bucket_seconds` sent** is served exactly as asked, so over a window whose resolution has expired you get an empty page rather than a silent substitution. * **`bucket_seconds` omitted** lets the server choose a width that can actually serve the window: the finest tier grain whose series stays under ~2,500 points, except that a window wider than 12 hours never defaults to the 60-second grain (ask for `bucket_seconds=60` explicitly when you want it over a longer window), and coarsened further if that grain does not reach the window's start. A window up to 12 hours keeps 1-minute detail (an hour 60 points, 12 hours 720); beyond that it moves to a materialized tier (a day 288, three days 864, a week 2,016, fifteen days 720). Send `bucket_seconds` when you want a specific density instead. A RESOLVED market's series ends with one settlement point: the on-chain payout of the requested token (0 lost, 1 won, fractional for voided or split resolutions) at `resolution_seconds` 0, placed one bucket edge past the last stored row and clamped to an explicit window's `end`. It appears only on the final page of a paginated walk, and only once the resolution is settled on-chain; an unresolved market's series is unchanged. `resolution_seconds` on every point reports what it was served at, so read it instead of assuming the width a recent window would have given you. For a multi-day window prefer a grain-aligned `bucket_seconds` (300, 1800, 10800, 43200) or omit it; a 60-second width over days is the one shape that is both slow and, past 7 days, empty. # Get live volume for an event Source: https://docs.polymarket.com/api-reference/markets/get-live-volume-for-an-event https://data-api.polymarket.com/v2/openapi.json get /v2/live-volume Cumulative one-side (taker) volume per market. Pass `?event_id=` as a comma-separated list of integer event ids (aliases `id` / `eventId`); every market under those events is returned, `taker_volume` descending, with `taker_volume_total` their sum. A list spans events. Unlike the feeds this is not paginated; `data` is the object with no `pagination`. Unparseable ids are ignored; a request whose ids are *all* unparseable is a 400 rather than an empty 200, so a typo cannot read as "no volume". Ids are sorted and deduplicated before the lookup, so `?event_id=20,10` and `?event_id=10,20` are the same request and share a cache entry. At most 20 distinct event ids per request, the same selector ceiling the `condition=` lists carry: every named event contributes all of its markets to a single aggregation, so the list is what sizes the request. # Get open interest Source: https://docs.polymarket.com/api-reference/markets/get-open-interest https://data-api.polymarket.com/v2/openapi.json get /v2/oi Priced gross open interest per market. Pass `?condition=` as a comma-separated list of condition ids (aliases `condition_id` / `conditionId`, matching the feeds); omit it for the single global figure (`condition_id = "GLOBAL"`, still a one-element array). Every requested id that resolves to a servable market (indexed, active, not archived; any id family) returns a row, with `value: 0` when nothing is held; an id absent from `data` did not resolve to a servable market. A malformed id is a `400` naming the value, so absence carries that one meaning and nothing else. Unlike the feeds this is not paginated; `data` is the row array with no `pagination`. # Get resolution state Source: https://docs.polymarket.com/api-reference/markets/get-resolution-state https://data-api.polymarket.com/v2/openapi.json get /v2/resolutions Complete resolution state by one selector family. Supply exactly one of `question_id`, `condition`, or `event_id`. Condition and event selectors accept comma-separated values and return condition-grain rows in deterministic order, preferring native V2 lifecycle, then UMA lifecycle, then terminal CTF state. Misses return `{ "data": [] }`. # List a market's top holders Source: https://docs.polymarket.com/api-reference/markets/list-a-markets-top-holders https://data-api.polymarket.com/v2/openapi.json get /v2/holders Top holders of a market, netted per user and grouped by outcome token. `?condition=` (CSV of `condition_id`) is required (400 otherwise). `?limit=` (default 100, max 1000; v2 family-uniform) sizes the page **per outcome token**; `?min_balance=` filters the served amount. `?include_pnl=true` opts each holder row into the position economics (entry price and cost, current price and value, realized, unrealized and total profit) and switches the amounts to per-side gross balances, so a wallet holding both outcomes appears under both tokens. The default response is unchanged. This mode serves one market's table at a time: exactly one `condition` and `limit` at most 100 (400 otherwise, including via a cursor that carries a wider window). A malformed condition id is a `400` naming the value; a well-formed one that resolves to no holdings serves an empty `data` array, which is the meaningful zero-state. Deeper pages come only from `?cursor=` (which carries the page window and overrides `limit`). Page walks advance every token group together, so a group leaves `data` once its token is exhausted while others keep paging; no rows are lost, but merge pages by `token_id`, not by array position. # Look up tokens Source: https://docs.polymarket.com/api-reference/markets/look-up-tokens https://data-api.polymarket.com/v2/openapi.json get /v2/tokens Resolves token ids, or the tokens of conditions, to their condition, module, outcome, market, event and neg-risk question index in one call. Exactly one selector per request. `?token_id=`: a comma-separated list of up to 50 decimal token ids (alias `token_ids`); elements are trimmed, leading zeros stripped and duplicates collapsed to their first position. `data` holds one row per known id in request order; an unknown id is simply absent (never a `404`), and an all-unknown request returns an empty array. `?condition=`: a comma-separated list of up to 10 condition selectors (aliases `condition_id`, `conditionId`), each `0x` plus 62 or 64 hex digits, lower-cased and deduplicated. A ConditionalTokens condition id returns the market's tokens (for a market carried over to polymarket-v2, its whole family: the ConditionalTokens pair, then the polymarket-v2 pair); a neg-risk market id returns every market of the structure; a polymarket-v2 condition id (the value a combo leg carries as `leg_condition_id`) returns that condition only; the 66-character condition id of a native polymarket-v2 market returns that market; the on-chain event id of a polymarket-v2 neg-risk structure returns every question of it. `data` holds the rows grouped by selector in request order, then by question index, market, module and outcome slot; an unknown value contributes nothing. A malformed value, more values than the cap, both selectors or neither is a `400`. `condition_id` is the market's condition id in its 66-character form, the value the other routes carry; `structural_condition_id` is the on-chain polymarket-v2 condition id in the same 66-character form, filled on every polymarket-v2 token, null on `v1_ctf`, and accepted back as a `condition` selector. `module` names the contract family: `v1_ctf` is the ConditionalTokens market (module 0) and every other value is a polymarket-v2 module. Reference fields never change; `closed`, `resolved`, `final_price` and `outcome` may lag by up to a minute. Not paginated: `data` is the row array with no `pagination`. # Get data freshness Source: https://docs.polymarket.com/api-reference/service/get-data-freshness https://data-api.polymarket.com/v2/openapi.json get /v2/status How fresh the data behind this API is. `/readyz` answers whether this pod can reach its datastore; this answers how far behind chain head what you are reading is. Two halves, because each is blind exactly where the other sees: * `serving`; the projections that turn ingested rows into what the feeds read (`activity_feed` enrichment, `custody_balances` ingestion, the PnL engine). Each carries its own clock, so this is the only half that can see "everything stopped". `lag_seconds` is the worst age across them and `worst` names which one, so a single stalled projection cannot hide behind two healthy ones. * `ingestion`; one crawl cursor per `(contract, event)`, summarised as the tail, the furthest-behind block, and the worst few cursors BY NAME. Every reading here is relative or positional, so under a total stall it reads green; that is why `serving` exists alongside it. Streams that are dormant by design are dropped from `ingestion` rather than reported, because they sit arbitrarily far back forever and would otherwise fill the list and push the stream you care about off it. Takes no parameters and is not paginated. Served from a snapshot refreshed in the background, never computed on the request: `computed_at` and `age_seconds` say how old it is, so a stalled refresher or a datastore outage shows up as a growing age rather than a 500. Before the first refresh lands there is nothing to serve and this answers `503`; "not measured yet" and "measured, no lag" are different claims. # Get a user's PnL series Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-pnl-series https://data-api.polymarket.com/v2/openapi.json get /v2/user-pnl Complete cumulative native-PnL atoms and compositions. # Get a user's profile stats Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-profile-stats https://data-api.polymarket.com/v2/openapi.json get /v2/user-stats The profile card for one wallet in a single call. `?user=` is required. Returns `{ data: { trades, biggest_win, views, join_date, all_time_pnl } }`, or `{ data: null }` when the wallet is not a known user. **`data: null` and a row of zeros mean different things.** `null` is "no such user"; zeros are "this user exists but has never traded, never won and has no profile views". `trades` counts DISTINCT MARKETS traded, not individual trades. It is exact, not estimated. `biggest_win` is the best single **resolved** position win in USDC, market and combo arms unified, and `0` when the wallet has no win over $1. `join_date` is epoch seconds, or `null` when unknown. `all_time_pnl` is the newest persisted cumulative `/v2/user-pnl` point at its actual observation timestamp. It is `null` when the user exists but no observation has been published yet. For the composition card: trading realized is `realized_market_pnl + realized_combo_pnl`; LP realized is `realized_lp_pnl`; rebates, yield, rewards, referral, and fees paid map to their same-named fields (`fees_paid` is refunds minus charges). `volume`, `volume_usdc`, and `trade_count` are cumulative maker-attributed canonical fill metrics. Not paginated: one row by construction, so `data` is the bare object with no `pagination`; the `/v2/value` shape. # Get a user's trading volume Source: https://docs.polymarket.com/api-reference/wallet/get-a-users-trading-volume https://data-api.polymarket.com/v2/openapi.json get /v2/user-volume One wallet's trading volume over a window, in both units side by side. `?user=` is required. `?start=` / `?end=` are epoch seconds, inclusive and optional: omitted or `0` disables a bound (full history). Volume is tracked in whole UTC days, so each bound is floored to its UTC day; the served window is the smallest whole-day window containing `[start, end]`. Returns `{ data: { volume, volume_usdc, trade_count } }`; exactly one row by construction (the view aggregates with no GROUP BY), zeros for a wallet with no trades in the window. An inverted window is zeros too, not an error. `volume` is both-sides SHARES; `volume_usdc` is the same measure in USD; the endpoint that shows the unit convention side by side: the bare name is the natural unit, `_usdc` is the denomination, the same pairing as `current_size` / `entry_cost_usdc` on `/v2/positions`. # Get portfolio value Source: https://docs.polymarket.com/api-reference/wallet/get-portfolio-value https://data-api.polymarket.com/v2/openapi.json get /v2/value The user's portfolio value: single-market holdings marked to market plus unresolved combo positions at cost basis. `?user=` is required (400 otherwise). `?condition=` (CSV of `condition_id`) scopes the single-market term, and any condition filter excludes the portfolio-level combo term. `data` is a single object; a user with no positions yields `{ "data": { "proxy_wallet": …, "value": 0 } }`. # Get wallet approvals Source: https://docs.polymarket.com/api-reference/wallet/get-wallet-approvals https://data-api.polymarket.com/v2/openapi.json get /v2/approvals Polygon token/operator approval state for one wallet. `?user=` must be an EVM address. The complete served catalog is returned in canonical order under `{ data }`; this endpoint is not paginated. # List combo positions Source: https://docs.polymarket.com/api-reference/wallet/list-combo-positions https://data-api.polymarket.com/v2/openapi.json get /v2/positions/combos Combo positions for a user, in the standard `{ data, pagination }` envelope. Sorts: `FIRST_ENTRY` (default) | `ENTRY_COST` (+ `CURRENT_VALUE` alias) | `UPDATED`, each with `sort_direction`. `FIRST_ENTRY DESC` pages by the two-state keyset anchor `(first_entry_at_micros, combo_condition_id, outcome_index)` (NULL micros = the NULL tail); `UPDATED ASC` by the single-state `(updated_at_micros, …)` anchor; every other combination by an offset-shaped token. The cursor binds sort + direction and the resume ADOPTS them, so a replay cannot flip or re-sort the walk mid-stream. It binds the cohort; `user`/`status`/`condition`/`updated_after`/ `updated_before`; the same way: following a page needs nothing but `?user=` (always required here) and `?cursor=`, and restating a filter is allowed but must agree. Omitting one is not a contradiction, it is the absence of a choice; **contradicting** one is a 400, because the token's walk state only means anything against the cohort it was minted on. Incremental sync: `updated_after`/`updated_before` are an INCLUSIVE epoch-second window on `updated_at`. Without a `status` filter, either bound switches the response to the mirror-complete sync view (every live row, not only held ones); a `status` filter keeps its own visibility. The upper end is always capped by a short stability ceiling (~90s behind now) so a mirror never reads rows that may still move. Pair with `sortBy=UPDATED&sortDirection=ASC` for the stable sync order. A malformed `condition` combo condition id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state. # List positions for a user or market Source: https://docs.polymarket.com/api-reference/wallet/list-positions-for-a-user-or-market https://data-api.polymarket.com/v2/openapi.json get /v2/positions A keyset page of positions in the standard `{ data, pagination }` envelope. One route serves a user's open book, their closed book (`status=CLOSED`), and a market's holders (market anchor). At least one of `user`/`condition` is required. Supplying both anchors on the user and applies `condition` as a narrowing filter. `status` defaults to `OPEN`, which is the **superset**: a settled-but-unredeemed winner still holds its tokens, so it is an open position whose condition resolved. `REDEEMABLE` narrows to that subset, and each row echoes its own `status`. Resume contract: a `next_cursor` binds the `status`/`sortBy`/`sortDirection` the walk started with. To follow it, send `cursor` together with the same `user` or `condition` anchor used on the first page; a bare `?cursor=` request returns 400. The token is the authority on the spine and the total order, and the handler adopts all three from it. Restating them is allowed and must agree; **explicitly** contradicting one is a 400, because replaying an anchor under a different spine or order would silently walk a different result set. Omitting them is not a contradiction; a defaulted `status` is the absence of a choice, not a request for `OPEN`. User CLOSED residual sorts bind their realized-PnL ranking in the signed cursor kind. Earlier cursors for those sorts return 400 and require restarting pagination without `cursor`, because their numeric anchor has ambiguous units. A malformed `condition` id is a `400` naming the value; a well-formed one that matches nothing serves an empty `data` array, which is the meaningful zero-state; absence means the market is not servable, and only that. # Live Data Channel Source: https://docs.polymarket.com/api-reference/websockets/live-data-channel Send JSON text frames tagged with op. The server answers every op with an ack or an error ack (never a close, except for policy breaches, close 4008, and an expired Access Token, close 1008) and pushes envelopes for subscribed channels. Limits per connection: 64 active (channel, filter) subscriptions, 20 subscribe or unsubscribe frames per second (a batch frame counts once), 64 KB per frame, 8 auth attempts. The server sends a WebSocket ping every 25 seconds; two missed pongs close 4002. Close codes: 4001 authentication failed on a presented credential, 4002 slow consumer or pong timeout, 4003 server draining (reconnect once after a uniform 0 to 10 s delay), 4008 policy violation (fix the client; do not reconnect blindly), which also closes a socket that neither passed authentication nor registered a subscription within the server's unengaged timeout (120 seconds by default, reason text unengaged) once that rule is enforced, 1008 authentication expired (a connection authenticated with an Access Token whose last accepted token expired, 30 second leeway included, with no renewal; refresh the token and reconnect).