# Polymarket — full corpus # LLM Wiki An open-source template for building LLM-powered knowledge bases, following [Andrej Karpathy's "LLM Wiki" pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). You provide raw sources. The LLM reads them, writes structured wiki pages, cross-links everything, and maintains it over time. You never edit the wiki directly — you curate sources and ask questions. ## How It Works The system has three layers: ``` raw/ Sources you collect (articles, transcripts, notes, PDFs) wiki/ LLM-written & maintained pages (summaries, concepts, entities, syntheses) CLAUDE.md Schema that tells the LLM how to structure everything ``` Three operations drive the workflow: | Operation | Trigger | What happens | |-----------|---------|--------------| | **Ingest** | "ingest raw/my-source.txt" | LLM reads the source, creates a summary page, creates/updates concept and entity pages, adds cross-links, updates the index and log | | **Query** | Ask any question | LLM searches the wiki, synthesizes an answer with citations, optionally creates a synthesis page for novel insights | | **Lint** | "lint" or "health check" | LLM audits all pages for orphans, contradictions, missing links, incomplete sections, and low-confidence claims — fixes what it can, reports the rest | ## Quick Start 1. **Clone this repo** ```bash git clone https://github.com/YOUR_USERNAME/llm-wiki.git my-knowledge-base cd my-knowledge-base ``` 2. **Customize CLAUDE.md** for your domain - Update the Purpose section with your topic - Replace the placeholder tagging taxonomy with your own categories - Adjust confidence level descriptions if needed - Everything else (workflows, page formats, linking rules) works as-is 3. **Drop sources into `raw/`** - Text files, transcripts, articles, notes — any plain text - These are immutable once added; the LLM never modifies them 4. **Tell the LLM to ingest** ``` ingest raw/my-first-source.txt ``` The LLM will create summary pages, concept pages, entity pages, cross-links, and update the index. 5. **Ask questions** ``` What are the key differences between X and Y? ``` The LLM answers from the wiki, citing specific pages. 6. **Run health checks** ``` lint ``` The LLM audits the wiki and fixes issues. ## Directory Structure ``` . ├── CLAUDE.md # Schema — the LLM's instructions ├── raw/ # Your source documents (immutable) └── wiki/ ├── index.md # Master catalog of all pages ├── log.md # Append-only activity log ├── dashboard.md # Dataview dashboard (Obsidian) ├── analytics.md # Charts View analytics (Obsidian) ├── flashcards.md # Spaced repetition cards ├── summaries/ # One page per source document ├── concepts/ # Concept and framework pages ├── entities/ # People, tools, organizations, etc. ├── syntheses/ # Cross-cutting analyses and comparisons ├── journal/ # Research/session journal entries │ └── template.md # Journal entry template └── presentations/ # Marp slide decks ``` ## Enhancements This template includes several extras beyond the core wiki pattern: ### Dataview Dashboard (`wiki/dashboard.md`) Live queries that surface low-confidence pages, recent updates, concepts by tag, and pages with the most sources. Requires the [Dataview](https://github.com/blacksmithgu/obsidian-dataview) Obsidian plugin. ### Charts View Analytics (`wiki/analytics.md`) Visual analytics with pie charts, bar charts, and word clouds. Requires the [Charts View](https://github.com/caronchen/obsidian-chartsview-plugin) Obsidian plugin. ### Mermaid Diagrams Use Mermaid code blocks in any wiki page to create flowcharts, sequence diagrams, or concept maps. Native support in Obsidian and GitHub. ### Marp Slides (`wiki/presentations/`) Create slide decks from markdown using [Marp](https://marp.app/). Drop presentation files in this directory. ### Research Journal (`wiki/journal/`) Track your research sessions, experiments, or applied work with the included template. The LLM can reference journal entries when answering queries. ### Spaced Repetition (`wiki/flashcards.md`) Flashcards in the format used by the [Spaced Repetition](https://github.com/st3v3nmw/obsidian-spaced-repetition) Obsidian plugin. Ask the LLM to generate flashcards from any wiki page. ### MCP Server This repo works with Claude Code's MCP server capabilities. Point an MCP-compatible client at this repo and the LLM can read/write the wiki programmatically. ## Customizing for Your Domain The schema in `CLAUDE.md` is domain-agnostic. To adapt it: 1. **Purpose** — Describe your knowledge domain in one paragraph 2. **Tagging taxonomy** — Replace placeholder categories with your own (e.g., for a cooking KB: `cuisine`, `technique`, `ingredient`, `equipment`) 3. **Confidence levels** — Adjust the descriptions to match your domain's evidence standards 4. **Entity types** — Update the entity page description to match what entities mean in your domain (people, tools, companies, etc.) 5. **Journal template** — Customize `wiki/journal/template.md` for your workflow Everything else — page format, linking conventions, workflows, rules — is universal and works across domains. ## Example Domains This template works for any knowledge-intensive topic: - **Research notes** — papers, experiments, methodologies - **Book analysis** — themes, characters, author techniques - **Competitive analysis** — companies, products, market trends - **Course notes** — lectures, readings, key concepts - **Personal development** — frameworks, habits, book summaries - **Technical documentation** — APIs, architectures, design patterns - **Hobby deep-dives** — any subject you want to master ## License MIT --- title: "Polymarket Knowledge Base — Index" type: index updated: 2026-07-07 polymarket_apis: "gamma / clob / data / perps / bridge / combos-rfq" --- # Polymarket — Knowledge Base Polymarket is the largest prediction-market platform (on Polygon, chain `137`), now also offering leveraged perpetual futures. Its API surface spans **five+ hosts** — Gamma (`gamma-api`), CLOB (`clob`), Data (`data-api`), Perps (`api.perpetuals`), Bridge (`bridge`), and Combos RFQ — and knowing which host answers which question is the single biggest source of integration error. This wiki covers the market data model, order placement, pricing, positions, fees, rewards, RFQ, funds movement, and the perps product, with verbatim routes and parameters. Master catalog — every page appears here. ## Concepts ### Getting started - [[concepts/what-is-polymarket]] — the platform, the API families, SDKs, restrictions - [[concepts/authentication]] — CLOB L1/L2 signing, Perps and Relayer auth, rate limits ### Trading & pricing - [[concepts/placing-orders]] — create/cancel/query orders, order args, auto-cancel - [[concepts/order-book-and-pricing]] — book, midpoint, spread, tick size, price history - [[concepts/rfq-and-quotes]] — the combinatorial RFQ / last-look maker system - [[concepts/perps-trading]] — perpetual futures: instruments, index, funding ### Market & account data - [[concepts/markets-and-events]] — the event/market/token model, Gamma vs CLOB lookups - [[concepts/positions-and-portfolio]] — positions, portfolio value, PnL, balances - [[concepts/trades-and-activity]] — fills, trade history, user activity, stats - [[concepts/tags-search-and-metadata]] — search, tags, series, teams, comments, profiles ### Fees, rewards & funds - [[concepts/fees]] — fee schedule, maker rebates, limit tiers, account limits - [[concepts/rewards-and-earnings]] — liquidity + OI rewards, earnings queries - [[concepts/deposits-withdrawals-transfers]] — bridging, proxy wallets, collateral, transactions - [[concepts/accounts-and-referrals]] — invites/referrals, relayer keys, accounting export, leaderboards ## Entities - [[entities/py-clob-client]] — the Python CLOB client (archived; migrate to py-sdk) - [[entities/clob-client]] — the TypeScript CLOB client (archived; migrate to ts-sdk) ## Syntheses - [[syntheses/api-surface-map]] — which of the five+ API hosts answers which question - [[syntheses/clob-vs-perps]] — prediction-market shares vs leveraged perpetuals - [[syntheses/order-types-and-execution]] — direct CLOB orders vs RFQ maker quotes ## Statistics - **Total pages**: 19 - **Concepts**: 14 - **Entities**: 2 - **Summaries**: 0 - **Syntheses**: 3 --- title: "Accounts, Referrals, and Leaderboards" type: concept tags: [accounts, referrals, invites, relayer-keys, leaderboards, builders, server-time, accounting] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-apply-referral-code.md", "raw/llms_txt_doc-check-invite-code.md", "raw/llms_txt_doc-create-account-invite.md", "raw/llms_txt_doc-get-account-referral.md", "raw/llms_txt_doc-get-all-relayer-api-keys.md", "raw/llms_txt_doc-download-an-accounting-snapshot-zip-of-csvs.md", "raw/llms_txt_doc-get-server-time.md", "raw/llms_txt_doc-get-server-time-2.md", "raw/llms_txt_doc-get-aggregated-builder-leaderboard.md", "raw/llms_txt_doc-get-daily-builder-volume-time-series.md", "raw/llms_txt_doc-get-trader-leaderboard-rankings.md"] confidence: high --- ## Definition This cluster covers account lifecycle plumbing: **invite/referral codes** that gate and reward signups, **relayer API keys** for authenticating relayer calls, an **accounting snapshot** export, **server time** for request signing, and the public **builder** and **trader leaderboards**. Referral, invite, and relayer-key management live on the Perps HTTP API (`https://api.perpetuals.polymarket.com`); leaderboards and accounting export live on the Data API (`https://data-api.polymarket.com`); server time is offered by both the CLOB and Perps APIs. ## How It Works **Invites and referrals (Perps API)**: - `GET /v1/info/invite?code=` (**Check Invite Code**) - public. Returns `{ valid }`; optional `address` makes the response invalid if that address already has an account. Request Weight: 1. - `POST /v1/account/invite` (**Create Account Invite**, requires `POLYMARKET-PROXY` + `POLYMARKET-SECRET`) - creates or returns the account's primary invite code; **idempotent** if one already exists. Returns `status`, `code`, `referrals_available`, `cooldown_ms` (null for lifetime caps). Request Weight: 1. - `POST /v1/account/referral` (**Apply Referral Code**, proxy/secret auth) - body `{ code }`. An account can only apply a referral code **if it does not already have one**. Request Weight: 1. - `GET /v1/account/referral` (**Get Account Referral**, proxy/secret auth) - returns the account's `code`, optional `parent` code, `children_count` (directly referred accounts), `referrals_left`, and `fee_share_rate` (**defaults to 0.2**). Request Weight: 1. **Relayer API keys** - `GET /relayer/api/keys` on the Relayer API (`https://relayer-v2.polymarket.com`) returns all relayer API keys for the authenticated address (each `apiKey`, `address`, `createdAt`, `updatedAt`); empty array if none. Auth: **Gamma auth or Relayer API key auth** (`RELAYER_API_KEY` + `RELAYER_API_KEY_ADDRESS`). Note: relayer API keys can only be **created** using Gamma auth, and every address can create a **maximum of 100 keys**. **Accounting export (Data API)** - `GET /v1/accounting/snapshot?user=
` returns a **ZIP of CSVs** (`positions.csv` and `equity.csv`). `user` is required. **Server time** - two independent endpoints: - CLOB `GET /time` - returns an integer **Unix timestamp in seconds** (e.g. `1234567890`). - Perps `GET /v1/info/time` - returns `{ time }` where `time` is a **millisecond** timestamp (e.g. `1767225600000`). Request Weight: 1. **Leaderboards (Data API)**: - `GET /v1/leaderboard` (**Get trader leaderboard rankings**) - params `category` (enum incl. `OVERALL`, `POLITICS`, `SPORTS`, `ESPORTS`, `CRYPTO`, `CULTURE`, `MENTIONS`, `WEATHER`, `ECONOMICS`, `TECH`, `FINANCE`; default `OVERALL`), `timePeriod` (`DAY`/`WEEK`/`MONTH`/`ALL`, default `DAY`), `orderBy` (`PNL`/`VOL`, default `PNL`), `limit` (default 25, 1-50), `offset` (0-1000), and single-user filters `user` / `userName`. Entries carry `rank`, `proxyWallet`, `userName`, `vol`, `pnl`, `xUsername`, `verifiedBadge`. - `GET /v1/builders/leaderboard` (**Get aggregated builder leaderboard**) - params `timePeriod` (default `DAY`), `limit` (default 25, 0-50), `offset` (0-1000). Entries carry `rank`, `builder`, `builderCode` (onchain attribution code attached to orders via `builderCode`; empty for legacy builders), `volume`, `activeUsers`, `verified`, `builderLogo`. - `GET /v1/builders/volume` (**Get daily builder volume time-series**) - param `timePeriod` (default `DAY`). Returns daily `BuilderVolumeEntry` records (`dt` ISO 8601, `builder`, `builderCode`, `volume`, `activeUsers`, `rank`). ## Key Parameters - `code` - invite/referral code; required for check and apply. - `address` / `user` - the account under check, export, or leaderboard filter. - `fee_share_rate` - referral fee share, defaulting to `0.2`. - `category`, `timePeriod`, `orderBy`, `limit`, `offset` - leaderboard controls. - `RELAYER_API_KEY` + `RELAYER_API_KEY_ADDRESS` - relayer key auth headers. ## When To Use - Validate an invite before onboarding a user: `GET /v1/info/invite`. - Get or mint your shareable invite code: `POST /v1/account/invite`. - Attribute yourself to a referrer post-signup: `POST /v1/account/referral` (once only). - Sync request-signing clocks: `GET /time` (CLOB) or `GET /v1/info/time` (Perps). - Export accounting records: `GET /v1/accounting/snapshot`. - Rank traders or builders: the Data API leaderboard endpoints. ## Risks & Pitfalls - Applying a referral code is **one-shot**: it fails if the account already has one. - The two server-time endpoints return **different units** - CLOB `/time` is **seconds**, Perps `/v1/info/time` is **milliseconds**. Pick the one matching what you sign. - Relayer keys can be **listed** with a relayer key but only **created** with Gamma auth; the 100-key-per-address cap applies. - `builderCode` is empty for legacy builders without a registered code - do not treat empty as an error. - The accounting snapshot is a binary **ZIP** (`application/zip`), not JSON. - `Create Account Invite` is idempotent - repeat calls return the existing code, not a new one. ## Related Concepts - [[concepts/authentication]] - proxy/secret, Gamma, and relayer key auth. - [[concepts/deposits-withdrawals-transfers]] - relayer transaction submission using the same key families. - [[concepts/fees]] - how `fee_share_rate` interacts with fees. - [[concepts/positions-and-portfolio]] - the positions/equity the accounting snapshot exports. - [[concepts/trades-and-activity]] - the volume that feeds leaderboards. - [[syntheses/api-surface-map]] - the full endpoint catalog. ## Sources - raw/llms_txt_doc-check-invite-code.md - `GET /v1/info/invite` - raw/llms_txt_doc-create-account-invite.md - `POST /v1/account/invite` - raw/llms_txt_doc-apply-referral-code.md - `POST /v1/account/referral` - raw/llms_txt_doc-get-account-referral.md - `GET /v1/account/referral` - raw/llms_txt_doc-get-all-relayer-api-keys.md - `GET /relayer/api/keys` - raw/llms_txt_doc-download-an-accounting-snapshot-zip-of-csvs.md - `GET /v1/accounting/snapshot` - raw/llms_txt_doc-get-server-time.md - CLOB `GET /time` (seconds) - raw/llms_txt_doc-get-server-time-2.md - Perps `GET /v1/info/time` (milliseconds) - raw/llms_txt_doc-get-aggregated-builder-leaderboard.md - `GET /v1/builders/leaderboard` - raw/llms_txt_doc-get-daily-builder-volume-time-series.md - `GET /v1/builders/volume` - raw/llms_txt_doc-get-trader-leaderboard-rankings.md - `GET /v1/leaderboard` --- title: "Authentication" type: concept tags: [authentication, clob, api-keys, eip-712, hmac, signing, nonce, rate-limits, relayer, foundational] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-authentication.md", "raw/llms_txt_doc-get-credentials.md", "raw/llms_txt_doc-get-current-nonce-for-a-user.md", "raw/llms_txt_doc-get-relayer-address-and-nonce.md", "raw/llms_txt_doc-rate-limits.md"] confidence: high --- # Authentication ## Definition The Gamma API and Data API are fully public - no authentication required. The **CLOB API** uses two levels of authentication for its trading endpoints: **L1 (Private Key)** and **L2 (API Key)**. CLOB read endpoints (orderbook, prices, spreads) require no auth. The separate **Perps HTTP API** and **Relayer API** use their own credential schemes. Trading is non-custodial: the private key stays with the user, and even with L2 headers present, methods that create orders still require the user to sign the order payload. ## How It Works **L1 authentication** uses the wallet's private key to sign an EIP-712 message placed in the request header. It proves ownership of the private key and is used for: creating API credentials, deriving existing API credentials, and signing/creating orders locally. **L2 authentication** uses API credentials (`apiKey`, `secret`, `passphrase`) generated from L1 auth. These authenticate requests to the CLOB API and are signed with HMAC-SHA256. L2 is used for: cancelling or getting a user's open orders, checking balances and allowances, and posting signed orders. **Getting credentials.** With the SDK, call `createOrDeriveApiKey()` (TypeScript) / `create_or_derive_api_key()` (Python), which creates new credentials or derives existing ones. Via REST, `POST https://clob.polymarket.com/auth/api-key` creates credentials and `GET https://clob.polymarket.com/auth/derive-api-key` derives them. Both return: ```json { "apiKey": "550e8400-e29b-41d4-a716-446655440000", "secret": "base64EncodedSecretString", "passphrase": "randomPassphraseString" } ``` The L1 request requires these headers; `POLY_SIGNATURE` is the CLOB EIP-712 signature over the `ClobAuth` struct (domain `name: "ClobAuthDomain"`, `version: "1"`, `chainId: 137`; fields `address`, `timestamp`, `nonce`, `message` where message = `"This message attests that I control the given wallet"`): | Header | Description | | ---------------- | ---------------------- | | `POLY_ADDRESS` | Polygon signer address | | `POLY_SIGNATURE` | CLOB EIP-712 signature | | `POLY_TIMESTAMP` | Current UNIX timestamp | | `POLY_NONCE` | Nonce (default: 0) | **L2 headers.** All CLOB trading endpoints require these 5 headers. The `POLY_SIGNATURE` for L2 is an HMAC-SHA256 signature created using the API `secret`: | Header | Description | | ----------------- | ----------------------------- | | `POLY_ADDRESS` | Polygon signer address | | `POLY_SIGNATURE` | HMAC signature for request | | `POLY_TIMESTAMP` | Current UNIX timestamp | | `POLY_API_KEY` | User's API `apiKey` value | | `POLY_PASSPHRASE` | User's API `passphrase` value | **Perps and Relayer credentials.** The Perps HTTP API authenticates with `POLYMARKET-PROXY` (proxy address) and `POLYMARKET-SECRET` (corresponding proxy secret) headers; missing/invalid credentials return `401` with `error: unauthorized`. `GET /v1/account/credentials` returns the account `address` and its proxy `keys` (each with `proxy`, optional `label`, and `expiry` in ms). The Relayer API supports Relayer API keys (`RELAYER_API_KEY` and `RELAYER_API_KEY_ADDRESS`, which must match the address owning the key); keys can only be created using Gamma auth, and every address may create at most 100 keys. ## Key Parameters - **Signature types and funder** (set when initializing the L2 client): EOA `0` (standard wallet, funder is the EOA and needs POL for gas); POLY_PROXY `1` (existing Polymarket proxy wallet, Magic Link email/Google login); GNOSIS_SAFE `2` (existing Gnosis Safe flow); POLY_1271 `3` (deposit-wallet flow for new API users; funder is the deposit wallet, orders validated via ERC-1271). New API users should use deposit wallets with `POLY_1271`. - **Nonces.** `GET https://relayer-v2.polymarket.com/nonce?address=&type=` returns `{ "nonce": "31" }` (the current Proxy or Safe nonce). `GET /relay-payload` with the same params returns the relayer `address` plus `nonce`. Bad params return `400` with `error: invalid address` or `error: invalid type`. - **create-vs-derive**: A given nonce creates one API key. Reusing it errors `NONCE_ALREADY_USED`; use `deriveApiKey()` with the same nonce to recover, or a different nonce with `createApiKey()`. ## When To Use - Use **L1** to bootstrap: obtain or derive your `apiKey`/`secret`/`passphrase`, and to sign order payloads locally. - Use **L2** for all ongoing CLOB trading requests (place, cancel, query orders, check balances). See [[concepts/placing-orders|placing orders]]. - Use **Perps proxy/secret** credentials for [[concepts/perps-trading|perps]] endpoints; use **Relayer** keys/nonces for [[concepts/deposits-withdrawals-transfers|gasless deposits/withdrawals]]. ## Risks & Pitfalls - **Never expose private keys or the API secret.** Store keys in env vars; do all request signing on the server, never in client-side code. - **`INVALID_SIGNATURE`** - private key incorrect or malformed; verify it is a valid hex string starting with `0x` and matches the intended address. - **`NONCE_ALREADY_USED`** - the nonce already created an API key; derive with the same nonce or use a new one. - **Invalid funder address** - check your profile address at polymarket.com/settings; if the wallet has never logged in to Polymarket, deploy it before creating L2 auth. - **Lost credentials AND nonce** - unrecoverable; you must `createApiKey()` fresh and save the new nonce. - **Rate limits** (Cloudflare, sliding windows, throttled not rejected): CLOB general `9,000 req / 10s`; API key endpoints `100 req / 10s`; `GET` balance allowance `200 req / 10s`, `UPDATE` `50 req / 10s`. Gamma general `4,000 req / 10s`; Data API general `1,000 req / 10s`. Relayer `/submit` is `25 req / 1 min`. Perps `429` responses distinguish `ip_rate_limited`, `action_rate_limited`, and `open_orders_limit`, and may include a `Retry-After` header (whole seconds). See [[concepts/order-book-and-pricing|order book and pricing]] and [[concepts/placing-orders|placing orders]] for trading-endpoint burst/sustained limits. ## Related Concepts - [[concepts/what-is-polymarket|What is Polymarket]] - [[concepts/placing-orders|Placing orders]] - [[concepts/order-book-and-pricing|Order book and pricing]] - [[concepts/deposits-withdrawals-transfers|Deposits, withdrawals, and transfers]] - [[concepts/perps-trading|Perps trading]] - [[entities/clob-client|clob-client]] ## Sources - `raw/llms_txt_doc-authentication.md` - `raw/llms_txt_doc-get-credentials.md` - `raw/llms_txt_doc-get-current-nonce-for-a-user.md` - `raw/llms_txt_doc-get-relayer-address-and-nonce.md` - `raw/llms_txt_doc-rate-limits.md` --- title: "Deposits, Withdrawals, and Transfers" type: concept tags: [deposits, withdrawals, bridge, transfers, proxy, collateral, relayer, transactions] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-deposits.md", "raw/llms_txt_doc-get-withdrawals.md", "raw/llms_txt_doc-create-bridge-addresses.md", "raw/llms_txt_doc-create-withdrawal-addresses.md", "raw/llms_txt_doc-internal-transfer.md", "raw/llms_txt_doc-get-internal-transfers.md", "raw/llms_txt_doc-get-collateral-assets.md", "raw/llms_txt_doc-get-supported-assets.md", "raw/llms_txt_doc-create-proxy.md", "raw/llms_txt_doc-delete-proxy.md", "raw/llms_txt_doc-check-if-a-wallet-is-deployed.md", "raw/llms_txt_doc-submit-a-transaction.md", "raw/llms_txt_doc-get-transaction-status.md", "raw/llms_txt_doc-get-a-transaction-by-id.md", "raw/llms_txt_doc-get-recent-transactions-for-a-user.md"] confidence: high --- ## Definition Moving money into, out of, and around Polymarket spans three services: the **Bridge API** (`https://bridge.polymarket.com`) for cross-chain deposits/withdrawals and asset discovery; the **Perps HTTP API** (`https://api.perpetuals.polymarket.com`) for account deposit/withdrawal history, internal ledger transfers, proxy management, and collateral info; and the **Relayer API** (`https://relayer-v2.polymarket.com`) for gasless onchain transaction submission and wallet-deployment checks. Collateral is USDC (6 decimals). ## How It Works **Bridging in/out (Bridge API)**: - `POST /deposit` (**Create bridge addresses**) - body `{ address }` (your Polymarket wallet, credited as pUSD). Returns per-network bridge addresses `evm`, `svm`, `btc`. Optional `X-Builder-Code` header (bytes32 hex) attributes the request; omitting it returns a `missing_builder_code` warning, malformed returns 400. - `POST /withdraw` (**Create withdrawal addresses**) - body `{ address, toChainId, toTokenAddress, recipientAddr }`. Returns the same address object. - `GET /supported-assets` - list of `SupportedAsset` (`chainId`, `chainName`, `token`, `minCheckoutUsd`, e.g. `45`) giving minimum USD for deposits/withdrawals. **Account history (Perps API, require `POLYMARKET-PROXY` + `POLYMARKET-SECRET`)**: - `GET /v1/account/deposits` - params `deposit_status` (`pending`/`confirmed`/`removed`), `hash`, `start_timestamp`, `end_timestamp` (ms). Max 100 entries. Fields include `amount` (raw token amount incl. decimals, e.g. `"100000000"` = 100 USDC), `confirmations`, `required_confirmations`. Request Weight: 10. - `GET /v1/account/withdrawals` - params `withdrawal_status` (`pending`/`confirmed`/`removed`/`failed`), `hash`, timestamps. Adds `withdraw_id` and `fee`. Request Weight: 10. **Internal transfers (Perps API)**: - `POST /v1/account/internal-transfer` - signed ledger transfer between two exchange accounts using the standard signed-op flow. Body: `op` (`type: internalTransfer`, `args`: `account`, `token`, `amount`, `to`), plus `sig`, `salt`, `ts`, optional `label`. Returns `transfer_id`. A `422` means the transfer was rejected on its merits (e.g. `insufficient_balance`, transfer to self). Request Weight: 1. - `GET /v1/account/internal-transfers` - settled history (inbound and outbound), params `start_timestamp`/`end_timestamp`. Each entry has `direction` (`in`/`out`), `counterparty`, optional `label`. Request Weight: 10. **Proxy wallets (Perps API)** - a proxy signs orders on behalf of an owner: - `POST /v1/account/proxy` (**Create Proxy**) - requires **EOA signature**. Body `op` (`type: createProxy`, `args`: `owner`, `proxy`, `expiry`), `sig`, `salt`, `ts`, optional `label`, `code`. Returns an API `secret` for private account access. `422` if the proxy already exists. - `DELETE /v1/account/proxy` (**Delete Proxy**) - requires EOA signature. Body `op` (`type: deleteProxy`, `args`: `proxy`), `sig`, `salt`, `ts`. **Collateral (Perps API)** - `GET /v1/info/assets` (**Get Collateral Assets**) returns `Asset` entries: `asset` (e.g. `USDC`), `address`, `decimals` (`6`), `collateral_ratio` (`"1.00"`), `withdrawal_fee` (`"5.00"`). Request Weight: 2. **Onchain transactions (Relayer API)** - gasless submission via **Builder API Keys** (`POLY_BUILDER_API_KEY`, `POLY_BUILDER_TIMESTAMP`, `POLY_BUILDER_PASSPHRASE`, `POLY_BUILDER_SIGNATURE`) or **Relayer API Keys** (`RELAYER_API_KEY`, `RELAYER_API_KEY_ADDRESS`): - `POST /submit` - body `from`, `to`, `proxyWallet`, `data`, `nonce`, `signature`, `signatureParams`, `type` (`SAFE`/`PROXY`). Returns immediately with `transactionID` and `state: STATE_NEW`; the onchain hash is **not** included - poll for it. - `GET /transaction?id=` - poll to retrieve `transactionHash` once broadcast. `state` enum: `STATE_NEW`, `STATE_EXECUTED`, `STATE_MINED`, `STATE_CONFIRMED`, `STATE_INVALID`, `STATE_FAILED`. - `GET /transactions` - most recent transactions owned by a user (same auth). - `GET /deployed?address=&type=SAFE|WALLET` (**Check if a wallet is deployed**) - returns `{ deployed }`. `type=SAFE` (Gnosis Safe, signatureType 2) is the default; `type=WALLET` checks a Deposit Wallet (signatureType 3). **Bridge transaction status** - `GET /status/{address}` returns bridge `transactions` with `status` enum `DEPOSIT_DETECTED`, `PROCESSING`, `ORIGIN_TX_CONFIRMED`, `SUBMITTED`, `COMPLETED`, `FAILED`; `txHash` appears only when `COMPLETED`. ## Key Parameters - `address` - your Polymarket wallet (deposit) or source wallet (withdraw / status). - `toChainId`, `toTokenAddress`, `recipientAddr` - destination for `POST /withdraw`. - `deposit_status` / `withdrawal_status`, `hash`, `start_timestamp`, `end_timestamp` - history filters. - `op.args` + `sig`/`salt`/`ts` - the signed-op envelope for transfers and proxy ops. - `transactionID` / `id`, `type` (`SAFE`/`WALLET`) - relayer transaction and wallet-check params. ## When To Use - Fund an account: `POST /deposit`, then send to the returned chain address; track via Bridge `GET /status/{address}`. - Withdraw cross-chain: `POST /withdraw` with destination chain/token/recipient. - Rebalance between exchange accounts: `POST /v1/account/internal-transfer`. - Delegate signing: `POST /v1/account/proxy`; revoke with `DELETE`. - Submit gasless onchain actions: relayer `POST /submit`, then poll `GET /transaction`. ## Risks & Pitfalls - `amount` is a **raw token amount including decimals** (e.g. `"100000000"` = 100 USDC), not a human decimal. - Withdrawals sign the timestamp in **Unix seconds** (must match the on-chain EIP-712 struct verified against `block.timestamp`), whereas most operations use Unix milliseconds for `ts`. - Relayer `POST /submit` returns **no transaction hash** - you must poll `GET /transaction` for it. - Proxy creation and deletion require an **EOA signature** (not proxy/L2 auth); a re-create returns `422` if the proxy already exists. - Only certain chains/tokens are supported - check `GET /supported-assets` and honor `minCheckoutUsd` before bridging. - The withdrawal `fee` (example `"5.00"`) and collateral `withdrawal_fee` are decimalized asset units. ## Related Concepts - [[concepts/authentication]] - proxy/secret, builder, and relayer key auth schemes. - [[concepts/accounts-and-referrals]] - relayer API keys and account setup. - [[concepts/positions-and-portfolio]] - balances the collateral backs. - [[concepts/rfq-and-quotes]] - the Bridge API also serves swap quotes. - [[concepts/perps-trading]] - the venue whose collateral/transfers this covers. - [[syntheses/api-surface-map]] - the full endpoint catalog. ## Sources - raw/llms_txt_doc-get-deposits.md - `GET /v1/account/deposits` - raw/llms_txt_doc-get-withdrawals.md - `GET /v1/account/withdrawals` - raw/llms_txt_doc-create-bridge-addresses.md - `POST /deposit` - raw/llms_txt_doc-create-withdrawal-addresses.md - `POST /withdraw` - raw/llms_txt_doc-internal-transfer.md - `POST /v1/account/internal-transfer` - raw/llms_txt_doc-get-internal-transfers.md - `GET /v1/account/internal-transfers` - raw/llms_txt_doc-get-collateral-assets.md - `GET /v1/info/assets` - raw/llms_txt_doc-get-supported-assets.md - `GET /supported-assets` - raw/llms_txt_doc-create-proxy.md - `POST /v1/account/proxy` - raw/llms_txt_doc-delete-proxy.md - `DELETE /v1/account/proxy` - raw/llms_txt_doc-check-if-a-wallet-is-deployed.md - `GET /deployed` - raw/llms_txt_doc-submit-a-transaction.md - `POST /submit` - raw/llms_txt_doc-get-transaction-status.md - Bridge `GET /status/{address}` - raw/llms_txt_doc-get-a-transaction-by-id.md - `GET /transaction` - raw/llms_txt_doc-get-recent-transactions-for-a-user.md - `GET /transactions` --- title: "Fees, Rebates, and Account Limits" type: concept tags: [fees, rebates, limits, maker, taker, perps, clob] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-fees.md", "raw/llms_txt_doc-get-fee-rate.md", "raw/llms_txt_doc-get-fee-rate-by-path-parameter.md", "raw/llms_txt_doc-get-current-rebated-fees-for-a-maker.md", "raw/llms_txt_doc-get-limit-tiers.md", "raw/llms_txt_doc-get-account-limits.md"] confidence: high --- ## Definition Polymarket charges trading fees that differ between its two venues. The **Perps HTTP API** (`https://api.perpetuals.polymarket.com`) exposes a maker/taker fee schedule that scales with the account's trailing 30-day volume tier. The **CLOB API** (`https://clob.polymarket.com`) exposes a flat per-token base fee (in basis points) plus a separate maker **rebate** program. Alongside fees, both venues enforce **rate/action limits** and an **open-order cap** by volume-based tier. ## How It Works **Perps fee schedule** - `GET /v1/info/fees` returns a `fee_schedule` array of `FeeScheduleEntry` objects keyed by `instrument_type` (enum: `perpetual`) and `category` (enum: `equity`, `commodity`, `index`, `crypto`). Each entry carries a `taker_fee_rate` and `maker_fee_rate`, both returned as strings. The rates returned are the **$0-tier defaults**; the account's actual rate on each fill depends on its trailing 30-day volume tier. Example defaults: `taker_fee_rate` `"0.0004"`, `maker_fee_rate` `"0.000125"`. The maker rate is positive at lower tiers, **zero at the $500M tier, and a rebate (negative) at the top tier**. Request Weight: 2. **CLOB base fee** - the fee for a specific token can be fetched two ways, both returning `{ base_fee }` as an integer in **basis points** (example `30`): - `GET /fee-rate?token_id=` (query parameter, optional) - `GET /fee-rate/{token_id}` (path parameter, required) **Maker rebates (CLOB)** - `GET /rebates/current` returns the rebated fees for a maker on a given date. This endpoint does **not** require authentication. Required query params: `date` (YYYY-MM-DD) and `maker_address` (Ethereum address). Each entry includes `date`, `condition_id`, `asset_address`, `maker_address`, and `rebated_fees_usdc` (a string, e.g. `"0.237519"`). **Limit tiers (Perps)** - `GET /v1/info/limit-tiers` returns an array of `LimitTier` objects. Enforced fields are per-account: `actions_per_minute_limit` (example `300`) and `open_orders_limit` (example `1000`). Tiers are keyed by `min_volume_14d` (string, e.g. `"0"`). The `rate_per_minute_limit` (example `1200`) and `rate_burst_limit` are **legacy** fields not used for gateway enforcement. `messages_per_minute` (example `300`) is display-only and equals `actions_per_minute_limit`. **Account limits (Perps)** - `GET /v1/account/limits` (requires `POLYMARKET-PROXY` + `POLYMARKET-SECRET` headers) returns the authenticated account's effective allowances for its current volume tier. `open_orders` reflects the current live open-order count; the rate-usage counters (`actions_per_minute`, `actions_burst`, `reset`) are not tracked here and are reported as `0`. Request Weight: 2. ## Key Parameters - `token_id` - asset ID for CLOB `GET /fee-rate` (query, optional) and `GET /fee-rate/{token_id}` (path, required). - `date` + `maker_address` - both required for `GET /rebates/current`. - `instrument_type` / `category` - key the perps fee schedule. - `min_volume_14d` - the volume threshold that selects a limit tier. - `actions_per_minute_limit` (300), `open_orders_limit` (1000) - the enforced perps caps. - `base_fee` - CLOB fee in basis points (integer, e.g. 30). ## When To Use - Read `GET /v1/info/fees` before quoting perps to know your maker/taker cost at the $0 tier, then adjust for your volume tier. - Read `GET /fee-rate/{token_id}` to price a CLOB order's fee for a specific outcome token. - Poll `GET /rebates/current` to reconcile maker rebate accrual per market per day. - Read `GET /v1/account/limits` to check your live open-order headroom before placing more resting orders. ## Risks & Pitfalls - The perps schedule returns **$0-tier defaults only** - do not assume they are your effective rates. Effective rates scale down with 30-day volume. - CLOB fees are **basis points**; perps rates are **decimal fractions** returned as strings - different units, do not mix them. - `open_orders_limit` is a **capacity** limit, not a rate limit. On a `429` with `error: open_orders_limit` there is no `Retry-After`; waiting does not free slots - cancel resting orders or wait for fills. - `429` errors distinguish `ip_rate_limited`, `action_rate_limited`, and `open_orders_limit`. Only the first two carry a `Retry-After` header. - `rate_per_minute_limit` / `rate_burst_limit` in limit tiers are legacy and not enforced at the gateway - do not rely on them for capacity planning. ## Related Concepts - [[concepts/rewards-and-earnings]] - the maker liquidity-rewards program, distinct from rebates. - [[concepts/perps-trading]] - the perpetuals venue whose fee schedule this describes. - [[concepts/placing-orders]] - where maker/taker classification is set. - [[concepts/authentication]] - the `POLYMARKET-PROXY`/`POLYMARKET-SECRET` and CLOB auth headers these endpoints require. - [[syntheses/clob-vs-perps]] - how the two venues' fee models differ. - [[syntheses/api-surface-map]] - the full endpoint catalog. ## Sources - raw/llms_txt_doc-get-fees.md - `GET /v1/info/fees` - raw/llms_txt_doc-get-fee-rate.md - `GET /fee-rate` - raw/llms_txt_doc-get-fee-rate-by-path-parameter.md - `GET /fee-rate/{token_id}` - raw/llms_txt_doc-get-current-rebated-fees-for-a-maker.md - `GET /rebates/current` - raw/llms_txt_doc-get-limit-tiers.md - `GET /v1/info/limit-tiers` - raw/llms_txt_doc-get-account-limits.md - `GET /v1/account/limits` --- title: "Markets and Events" type: concept tags: [markets, events, gamma-api, clob-api, negative-risk, combos, pagination] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-market-by-id.md", "raw/llms_txt_doc-get-market-by-slug.md", "raw/llms_txt_doc-get-market-by-token.md", "raw/llms_txt_doc-list-markets.md", "raw/llms_txt_doc-list-markets-keyset-pagination.md", "raw/llms_txt_doc-get-clob-market-info.md", "raw/llms_txt_doc-get-simplified-markets.md", "raw/llms_txt_doc-get-sampling-markets.md", "raw/llms_txt_doc-get-sampling-simplified-markets.md", "raw/llms_txt_doc-get-combo-markets.md", "raw/llms_txt_doc-negative-risk-markets.md", "raw/llms_txt_doc-get-event-by-id.md", "raw/llms_txt_doc-get-event-by-slug.md", "raw/llms_txt_doc-list-events.md", "raw/llms_txt_doc-list-events-keyset-pagination.md", "raw/llms_txt_doc-get-exchange-info.md"] confidence: high --- ## Data Model: Events, Markets, Tokens Polymarket organizes prediction markets in a hierarchy. An **Event** (e.g. "Who will win the 2024 Presidential Election?") groups one or more **Markets**. Each binary Market has a `conditionId` and two outcome **tokens** (a Yes/primary token and a No/secondary token) identified by `clobTokenIds`. Trading happens per token on the CLOB; see [[concepts/order-book-and-pricing|Order Book and Pricing]]. Two APIs describe markets. The **Gamma API** (`https://gamma-api.polymarket.com`) serves rich metadata; the **CLOB API** (`https://clob.polymarket.com`, staging `https://clob-staging.polymarket.com`) serves trading parameters. A full [[syntheses/api-surface-map|API Surface Map]] compares them. Key Gamma `Market` fields (verbatim): `id`, `question`, `conditionId`, `slug`, `clobTokenIds`, `outcomes`, `outcomePrices`, `volume`, `liquidity`, `volumeNum`, `liquidityNum`, `active`, `closed`, `archived`, `restricted`, `enableOrderBook`, `orderPriceMinTickSize`, `orderMinSize`, `acceptingOrders`, `bestBid`, `bestAsk`, `lastTradePrice`, `spread`, `umaResolutionStatus`, `rewardsMinSize`, `rewardsMaxSpread`, `rfqEnabled`, `feesEnabled`, `negRiskOther`, `startDate`, `endDate`, `events`, `categories`, `tags`, `feeSchedule`. Note `outcomes`, `outcomePrices`, and `clobTokenIds` are JSON-encoded **strings**, not arrays. Key `Event` fields: `id`, `ticker`, `slug`, `title`, `description`, `startDate`, `endDate`, `active`, `closed`, `archived`, `featured`, `liquidity`, `volume`, `openInterest`, `commentCount`, `negRisk`, `negRiskMarketID`, `negRiskFeeBips`, `enableNegRisk`, `markets`, `series`, `tags`, `collections`. Nested `Series`, `Category`, `Tag`, `Collection` objects are embedded. ## Fetching a Single Market or Event Gamma single-object routes: - `GET /markets/{id}` (`getMarket`) - path `id` (integer); query `include_tag` (boolean) -> `Market`; `404` if not found. - `GET /markets/slug/{slug}` (`getMarketBySlug`) - path `slug`; query `include_tag` -> `Market`. - `GET /events/{id}` (`getEvent`) - query `include_chat`, `include_template` -> `Event`. - `GET /events/slug/{slug}` (`getEventBySlug`) - query `include_chat`, `include_template` -> `Event`. CLOB single-market routes: - `GET /markets-by-token/{token_id}` (`getMarketByToken`) - resolves a token's parent market without knowing the condition ID. Returns `condition_id`, `primary_token_id` (the Yes token), `secondary_token_id` (the No token). Errors: `400` empty token_id, `404` not found, `500`. - `GET /clob-markets/{condition_id}` (`getClobMarketInfo`) - all CLOB parameters in one call, returning `ClobMarketDetails`: `gst` (game start time), `r` (rewards), `t` (tokens, each `{t: token_id, o: outcome}`), `mos` (minimum order size), `mts` (minimum tick size), `mbf`/`tbf` (maker/taker base fee, bps), `rfqe` (RFQ enabled), `itode` (taker order delay enabled; 250 ms window, omitted when false), `ibce` (Blockaid check), `fd` (fee details `{r: rate, e: exponent, to: takerOnly}`), `oas` (minimum order age, seconds). ## Listing Markets and Events Offset pagination (Gamma): - `GET /markets` (`listMarkets`) -> array of `Market`. Filters: `limit`, `offset`, `order`, `ascending`, `id`, `slug`, `clob_token_ids`, `condition_ids`, `market_maker_address`, `liquidity_num_min`/`_max`, `volume_num_min`/`_max`, `start_date_min`/`_max`, `end_date_min`/`_max`, `tag_id`, `related_tags`, `cyom`, `uma_resolution_status`, `game_id`, `sports_market_types`, `rewards_min_size`, `question_ids`, `include_tag`, `closed` (default `false`). - `GET /events` (`listEvents`) -> array of `Event`. Filters include `limit`, `offset`, `order`, `ascending`, `id`, `tag_id`, `exclude_tag_id`, `slug`, `tag_slug`, `related_tags`, `active`, `archived`, `featured`, `cyom`, `include_chat`, `include_template`, `recurrence`, `closed`, `liquidity_min`/`_max`, `volume_min`/`_max`, `start_date_min`/`_max`, `end_date_min`/`_max`. Keyset (cursor) pagination is preferred for large result sets: use `next_cursor` from each response as `after_cursor` in the next request. `offset` is **explicitly rejected (422)**. - `GET /markets/keyset` (`listMarketsKeyset`) -> `KeysetMarketsResponse` `{markets, next_cursor}`. `limit` max 100, default 20. `next_cursor` is present only when returned markets equal the limit; omitted on the last page. Adds `decimalized`, `tag_match`, `rfq_enabled`, `locale`. Errors `422`/`500`/`503` (503 = keyset not configured). - `GET /events/keyset` (`listEventsKeyset`) - `limit` max 500, default 20. Adds many filters: `live`, `title_search`, `start_time_min`/`_max`, `series_id`, `event_date`, `event_week`, `featured_order`, `created_by`, `parent_event_id`, `include_children`, `partner_slug`, `include_best_lines`, `locale`. CLOB list routes (all take `next_cursor`): - `GET /sampling-markets` (`getSamplingMarkets`) -> `PaginatedMarkets` (full CLOB `Market` with `tokens`, `rewards`, `neg_risk`, `minimum_order_size`, `minimum_tick_size`). - `GET /simplified-markets` (`getSimplifiedMarkets`) and `GET /sampling-simplified-markets` -> `PaginatedSimplifiedMarkets` `{limit, next_cursor, count, data}`; each `SimplifiedMarket` = `condition_id`, `rewards`, `tokens` (`{token_id, outcome, price, winner}`), `active`, `closed`, `archived`, `accepting_orders`. Sampling variants only return markets with active rewards. ## Combo Markets and Negative Risk `GET /v1/rfq/combo-markets` (`getComboMarkets`, base `https://combos-rfq-api.polymarket.com`, public) returns active markets usable as combo legs, volume-descending. Params: `limit` (default 50, max 100), `cursor`, `exclude` (comma-separated condition IDs). Each `ComboMarket`: `id`, `condition_id`, `position_ids` (`[0]` YES, `[1]` NO), `slug`, `title`, `outcomes`, `outcome_prices`, `image`, `volume`, `tags`. `next_cursor` is `null` on the final page. See [[concepts/rfq-and-quotes|RFQ and Quotes]]. **Negative risk** is a mechanism for multi-outcome events where only one outcome wins: a No share in any market converts into 1 Yes share in every other market, via the Neg Risk Adapter contract. Identify it with `negRisk: true` on events/markets. **Augmented neg risk** (new outcomes can emerge post-launch) is flagged when both `enableNegRisk` and `negRiskAugmented` are `true`; only trade **named** outcomes. When ordering, always pass `negRisk: true` / `neg_risk: True` regardless of standard vs augmented (see [[concepts/placing-orders|Placing Orders]]). ## Exchange Info `GET /v1/info/exchange` (`getExchange`, Perps API `https://api.perpetuals.polymarket.com`, Request Weight 2) returns the EIP-712 domain: `name` (e.g. "Polymarket"), `version`, `chain_id` (137 = Polygon), `contract`. ## Related Concepts - [[concepts/order-book-and-pricing|Order Book and Pricing]] - [[concepts/positions-and-portfolio|Positions and Portfolio]] - [[concepts/tags-search-and-metadata|Tags, Search and Metadata]] - [[syntheses/api-surface-map|API Surface Map]] ## Sources Gamma and CLOB market/event reference pages listed in frontmatter `sources`. --- title: "Order Book and Pricing" type: concept tags: [clob, market-data, order-book, pricing, midpoint, spread, tick-size, bbo, klines, price-history, perps] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-book.md", "raw/llms_txt_doc-get-order-book.md", "raw/llms_txt_doc-get-bbo.md", "raw/llms_txt_doc-get-midpoint-price.md", "raw/llms_txt_doc-get-spread.md", "raw/llms_txt_doc-get-spreads.md", "raw/llms_txt_doc-get-last-trade-price.md", "raw/llms_txt_doc-get-tick-size.md", "raw/llms_txt_doc-get-market-price.md", "raw/llms_txt_doc-get-prices-history.md", "raw/llms_txt_doc-get-klines.md"] confidence: high --- # Order Book and Pricing ## Definition These read endpoints expose live market microstructure - the order book, best prices, midpoints, spreads, tick sizes, last trade, and historical prices. They span **two APIs**: the **CLOB API** (`https://clob.polymarket.com`) serves prediction-market data keyed by `token_id`; the **Perps HTTP API** (`https://api.perpetuals.polymarket.com`) serves perpetual-futures data keyed by integer `instrument_id`. Almost all of these endpoints are public (no auth). Prices are expressed as decimal strings; prediction-market outcome prices sit between 0 and 1. See [[concepts/what-is-polymarket|what is Polymarket]] and [[syntheses/clob-vs-perps|CLOB vs perps]] for the two-world split. ## How It Works **CLOB order book** - `GET /book?token_id=` returns an `OrderBookSummary`: `market` (condition ID), `asset_id` (token ID), `timestamp`, `hash`, `bids` (sorted price descending), `asks` (sorted price ascending), `min_order_size`, `tick_size`, `neg_risk`, and `last_trade_price`. Each level is an `OrderSummary` `{ price, size }` (strings). `404` = "No orderbook exists for the requested token id". **Perps book** - `GET /v1/info/book?instrument_id=&depth=` returns a `Book` with `instrument_id`, `bids`, `asks`, `timestamp`, `sequence`. Levels are `["price", "quantity"]` string pairs, e.g. `["100.00", "10.00"]`. `depth` enum: `10`, `100` (default), `500`, `1000`; request weight scales `2`/`5`/`10`/`20` respectively. **Best bid/offer (perps)** - `GET /v1/info/bbo` (optional `instrument_id`) returns an array of `BBO` objects: `instrument_id`, `bid_price`, `bid_quantity`, `ask_price`, `ask_quantity`, `timestamp`. Request weight `2`. **Midpoint (CLOB)** - `GET /midpoint?token_id=` returns `{ "mid_price": "0.45" }`, the average of best bid and best ask. **Spread (CLOB)** - `GET /spread?token_id=` returns `{ "spread": "0.02" }`, best ask minus best bid. Batch: `POST /spreads` with a JSON array of `{ token_id, side? }` objects returns a map of token ID to spread string, e.g. `{ "0xabc...": "0.02" }`. **Market price (CLOB)** - `GET /price?token_id=&side=` returns `{ "price": 0.45 }` (a decimal number): the best bid for `BUY`, best ask for `SELL`. Both params required. **Last trade price (CLOB)** - `GET /last-trade-price?token_id=` returns `{ "price", "side" }` where `side` is `BUY`, `SELL`, or `""`. If no trades found, defaults are price `"0.5"` and empty-string side. **Tick size (CLOB)** - `GET /tick-size?token_id=` (token_id optional; also available as a path parameter) returns `{ "minimum_tick_size": 0.01 }` (number). `404` = "market not found". **Price history (CLOB)** - `GET /prices-history?market=` returns `{ "history": [ { "t", "p" } ] }` (uint32 timestamp, float price). Optional params: `startTs`, `endTs` (Unix), `interval` (`max`|`all`|`1m`|`1w`|`1d`|`6h`|`1h`), `fidelity` (accuracy in minutes, default 1). **Klines/candles (perps)** - `GET /v1/info/klines` returns `{ "data": [...], "more": bool }`, max 1000 entries. Each kline is an array: `[open_time_ms, "open", "high", "low", "close", "volume", trade_count]`. Required params: `instrument_id`, `interval`, `start_timestamp`; optional `end_timestamp` (defaults to now). Request weight `5`. ## Key Parameters - **Identifiers**: CLOB endpoints use `token_id` (also called `asset_id`); perps endpoints use integer `instrument_id`. The CLOB book also surfaces the `market` condition ID and `neg_risk` (negative-risk) flag - see [[concepts/markets-and-events|markets and events]]. - **`interval` (prices-history)**: `max`, `all`, `1m`, `1w`, `1d`, `6h`, `1h`. - **`interval` (klines)**: `1s`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w`. - **`depth` (perps book)**: `10`, `100` (default), `500`, `1000`. - **`fidelity` (prices-history)**: data accuracy in minutes, default `1`. - **Value formats**: CLOB `/book`, `/midpoint`, `/spread`, `/last-trade-price` return prices as strings; `/price` and `/tick-size` return numbers. ## When To Use - Reading the full book depth: CLOB `GET /book` (prediction markets) or perps `GET /v1/info/book`. - Just the top of book: perps `GET /v1/info/bbo`, or CLOB `GET /price` per side. - Fair-value estimate: CLOB `GET /midpoint`. - Liquidity/quality check before trading: CLOB `GET /spread` or batch `POST /spreads`. - Validating an order price is on-tick before submitting: CLOB `GET /tick-size` - feeds directly into [[concepts/placing-orders|placing orders]]. - Charting/backtesting: CLOB `GET /prices-history` (line series) or perps `GET /v1/info/klines` (OHLCV candles). ## Risks & Pitfalls - **Do not mix the two APIs.** `/book` (CLOB, `token_id`) and `/v1/info/book` (perps, `instrument_id`) are different endpoints with different response shapes (`OrderBookSummary` vs `Book`). Levels differ too: CLOB uses `{ price, size }` objects; perps uses `["price", "quantity"]` arrays. - **Last trade price defaults are not real trades.** `"0.5"` / empty side means "no trades found," not a genuine mid. - **`404 No orderbook exists`** is returned by `/book`, `/midpoint`, `/spread`, and `/price` for tokens without a live book - handle it distinctly from `400 Invalid token id`. - **Pagination/limits**: klines return at most 1000 entries with a `more` flag; page with `start_timestamp`/`end_timestamp`. - **Rate limits** (CLOB market data, per 10s): `/book` 1,500, `/books` 500, `/price` 1,500, `/prices` 500, `/midpoint` 1,500, `/midpoints` 500, `/prices-history` 1,000, market tick size 200. See [[concepts/authentication|authentication]] for the full table. - **Number vs string prices** vary by endpoint; parse accordingly to avoid precision bugs. ## Related Concepts - [[concepts/placing-orders|Placing orders]] - [[concepts/what-is-polymarket|What is Polymarket]] - [[concepts/authentication|Authentication]] - [[concepts/markets-and-events|Markets and events]] - [[concepts/perps-trading|Perps trading]] - [[concepts/trades-and-activity|Trades and activity]] - [[syntheses/clob-vs-perps|CLOB vs perps]] - [[syntheses/order-types-and-execution|Order types and execution]] ## Sources - `raw/llms_txt_doc-get-book.md` - `raw/llms_txt_doc-get-order-book.md` - `raw/llms_txt_doc-get-bbo.md` - `raw/llms_txt_doc-get-midpoint-price.md` - `raw/llms_txt_doc-get-spread.md` - `raw/llms_txt_doc-get-spreads.md` - `raw/llms_txt_doc-get-last-trade-price.md` - `raw/llms_txt_doc-get-tick-size.md` - `raw/llms_txt_doc-get-market-price.md` - `raw/llms_txt_doc-get-prices-history.md` - `raw/llms_txt_doc-get-klines.md` --- title: "Perps Trading" type: concept tags: [perps, perpetuals, instruments, funding, leverage, api] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-instruments.md", "raw/llms_txt_doc-get-instrument-config.md", "raw/llms_txt_doc-get-index.md", "raw/llms_txt_doc-get-tickers.md", "raw/llms_txt_doc-get-historical-funding.md", "raw/llms_txt_doc-get-funding-charges.md", "raw/llms_txt_doc-get-supported-assets.md"] source_url: "https://docs.polymarket.com/api-reference/get-instruments.md" confidence: high --- # Perps Trading ## Definition Perps (perpetual futures) are a distinct Polymarket product served by its own **Polymarket Perps HTTP API** at `https://api.perpetuals.polymarket.com`. Unlike prediction markets (binary outcome shares that resolve to $0 or $1), perps are leveraged, non-expiring contracts on an underlying asset's price, held open with margin and kept aligned to the index through periodic funding payments. Each tradable contract is an **instrument** (for example `NVDA-USDC`) quoted in USDC. ## How It Works Every instrument has `instrument_type: perpetual` and a `category` of `equity`, `commodity`, `index`, or `crypto`. The API exposes public market-data routes and authenticated account routes: - `GET /v1/info/instruments` -- list all instruments and their trading rules. - `GET /v1/info/index` -- index price plus the weighted list of constituents (for example a `chainlink` source at `NVDA/USD`) for an asset. - `GET /v1/info/tickers` -- live per-instrument market data. - `GET /v1/info/funding` -- public funding-rate history (max 100 entries/request). - `GET /v1/account/funding` -- funding-payment history for the authenticated account (max 100 entries/request; defaults end time to now). - `GET /v1/account/config` -- the authenticated account's per-instrument leverage and margin mode. The index price is built from external constituents (source, symbol, weight, price). Each ticker returns `index_price`, `mark_price`, `last_price`, `mid_price`, `open_interest` (in number of contracts), `funding_rate`, and `next_funding` (a Unix-ms timestamp). Funding is exchanged at the `funding_interval` (example `1h`): longs and shorts pay or receive `funding_rate` on their `size` (signed contracts, positive = long, negative = short), settled in USDC. An account funding record carries `instrument_id`, `size`, `funding_rate`, `funding_asset` (example `USDC`), `funding` (paid in USD), and `timestamp`. The two `/v1/account/*` routes are authenticated with the `POLYMARKET-PROXY` (proxy address) and `POLYMARKET-SECRET` (proxy secret) headers; the `/v1/info/*` market-data routes are public. ## Key Parameters Per-instrument rules returned by `GET /v1/info/instruments`: - `symbol`, `base_asset`, `quote_asset` (example `NVDA-USDC`, `NVDA`, `USDC`). - `funding_interval` (example `1h`). - `quantity_decimals` / `price_decimals` (non-integer prices max 5 significant figures; integer prices allowed regardless). - `price_bounds` (percentage, example `0.05`). - `liquidation_fee` (rate, example `0.025`). - `max_leverage` (example `20`) and `risk_tiers` -- an array of `{ lower_bound, max_leverage }` so leverage steps down as position size grows. - `min_notional`, `max_market_notional`, `max_limit_notional`, `max_order_count` (example `200`). Account config (`GET /v1/account/config`): `instrument_id`, `leverage` (example `10`), and `cross` (boolean -- whether cross margin mode is used). USDC is the collateral/quote asset. The separate Bridge API (`GET https://bridge.polymarket.com/supported-assets`) lists which tokens (name, symbol such as `USDC`, address, decimals) and chains can fund an account, each with a `minCheckoutUsd`. ## When To Use Use perps when you want leveraged, directional, non-expiring exposure to an asset's price (crypto, equities, commodities, indices) rather than a stake on a discrete event outcome. Read `/v1/info/tickers` for live mark/funding, poll `/v1/info/funding` to model carry cost, and check `/v1/account/config` before sizing an order so the applied leverage and margin mode are known. ## Risks & Pitfalls - **Funding is a recurring carry cost**, charged each `funding_interval`; a held position accrues `funding` in USD indefinitely. - **Leverage is tiered**: the headline `max_leverage` only applies within the first `risk_tiers` band; larger positions get lower max leverage, and breaching margin triggers a `liquidation_fee`. - **Notional caps** (`min_notional`, `max_market_notional`, `max_limit_notional`) and `max_order_count` reject oversized or excessive orders. - Rate limits are distinct: `ip_rate_limited` and `action_rate_limited` return `Retry-After`, but `open_orders_limit` is a capacity limit -- waiting does not free slots; cancel resting orders instead. ## Related Concepts - [[syntheses/clob-vs-perps]] -- prediction-market CLOB vs perpetual futures. - [[syntheses/api-surface-map]] -- where the Perps API sits among Polymarket APIs. - [[syntheses/order-types-and-execution]] -- perps order fields and matching. ## Sources `raw/llms_txt_doc-get-instruments.md`, `raw/llms_txt_doc-get-instrument-config.md`, `raw/llms_txt_doc-get-index.md`, `raw/llms_txt_doc-get-tickers.md`, `raw/llms_txt_doc-get-historical-funding.md`, `raw/llms_txt_doc-get-funding-charges.md`, `raw/llms_txt_doc-get-supported-assets.md`. --- title: "Placing Orders" type: concept tags: [orders, trading, perps, order-lifecycle, cancel, auto-cancel, time-in-force, tpsl, clob] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-create-orders.md", "raw/llms_txt_doc-cancel-orders.md", "raw/llms_txt_doc-cancel-orders-coid.md", "raw/llms_txt_doc-get-open-orders.md", "raw/llms_txt_doc-get-orders.md", "raw/llms_txt_doc-set-auto-cancel.md", "raw/llms_txt_doc-get-auto-cancel-status.md"] confidence: high --- # Placing Orders ## Definition The order-management endpoints documented here belong to the **Perps HTTP API** (`https://api.perpetuals.polymarket.com`). They cover the full order lifecycle: create, cancel (by order ID or client order ID), query resting and historical orders, and arm a dead-man-switch (auto-cancel). Orders reference an integer instrument (`iid`/`instrument_id`), carry a signed operation envelope, and are authenticated with the account's `POLYMARKET-PROXY`/`POLYMARKET-SECRET` credentials (read endpoints) plus a proxy signature on the operation body. See [[concepts/order-book-and-pricing|order book and pricing]] for the CLOB prediction-market book, and [[syntheses/order-types-and-execution|order types and execution]] for a cross-cutting view. ## How It Works **Create Orders** - `POST /v1/trade/orders`. Request weight `1 + floor(n / 20)`, action weight `1 / order`. Requires a proxy signature. The body is an `OrderRequest`: `op` (with `type: createOrders`, an `args` array of `CreateOrder`, and optional `grp` TPSL grouping enum `order`|`position`), plus the `BaseOp` fields `sig`, `salt`, `ts`, and optional `exp` (command expiry). It returns an array of `OrderResponse` ACKs (`OrderAccepted` = `{ status: "ok", oid, coid? }` or `OrderRejected` = `{ status: "err", oid?, coid?, error }`). The response is an ACK only - fetch the actual order result via Get Orders. **Cancel Orders** - `DELETE /v1/trade/orders`. Request weight `1 + floor(n / 20)`, action weight `0`. Body `op.type: cancelOrders` with `args` = array of order IDs (`oid`). Cancelling an order with attached TP/SL children cascades: children are cancelled with reason `ParentCancelled`. Returns `CancelResponse[]` (`CancelAccepted`/`CancelRejected`). **Cancel Orders COID** - `DELETE /v1/trade/orders-coid`. Same weights. Body `op.type: cancelOrdersCOID` with `args` = array of client order IDs (`coid`). Same cascade behavior and response shape. **Get Open Orders** - `GET /v1/account/open-orders`. Returns currently resting orders for the authenticated account. Optional `instrument_id` query param. Request weight: `1` with instrument ID, `20` without. Auth: `POLYMARKET-PROXY` + `POLYMARKET-SECRET`. **Get Orders** - `GET /v1/account/orders`. Historical order snapshots from the order-history database; returns the latest known state for each matching order (accepted, open, partial, filled, cancelled). Max 100 entries per request. Query params: `order_id`, `client_order_id`, `instrument_id`, `start_timestamp`, `end_timestamp` (all optional). Request weight: `1` with order ID, `10` without. For currently resting orders only, use Get Open Orders. Both order-query endpoints return `OrderData` objects with: `order_id`, `instrument_id`, `buy`, `price`, `quantity`, `tif`, `post_only`, `ro`, `status`, `resting_quantity`, `filled_quantity`, `created_timestamp`, `updated_timestamp`, optional `client_order_id`, and an optional `tpsl` block for conditional orders. ## Key Parameters **`CreateOrder` fields** (required: `iid`, `buy`, `qty`): | Field | Meaning | | ----- | ------- | | `iid` | Instrument ID (integer) | | `buy` | Is buy (boolean) | | `p` | Price, e.g. `"100.00"` (string) | | `qty` | Quantity in number of contracts, e.g. `"10.00"` (string) | | `tif` | Time in force: `gtc`, `ioc`, or `fok` | | `po` | Post only (boolean, default `false`) | | `ro` | Reduce only (boolean, default `false`) | | `c` | Client order ID (`coid`), 32 lowercase hex chars, pattern `^[0-9a-f]{32}$` | | `tr` | Optional trigger: `market` (bool, executes as market order), `trp` (trigger price, e.g. `"110.00"`), `tpsl` (`tp` or `sl`) | **`BaseOp` envelope** (required on create/cancel/auto-cancel): `sig` (hex signature), `salt` (integer), `ts` (request timestamp - Unix ms for most operations, Unix seconds for withdrawals). Optional `exp` is the command expiry in Unix ms; it can shorten request validity but cannot extend it, and is **not** an order auto-cancel time. **TP/SL fields** (`TpSlOrderFields` on `OrderData`): `kind` (`tp`/`sl`), `scope` (`order` = child of a parent entry, quantity required; `position` = attached to an open position, v1 always closes the full position so `qty` must be `"0"`), `trp` (trigger price), `parent_oid`, `armed_qty`, `slip_bps` (market-trigger slippage cap in basis points, 0-10000; `0` = per-instrument default). **Auto-cancel (dead-man-switch)** - `PATCH /v1/trade/auto-cancel`. Request weight `1`, action weight `10`. Body `op.type: autoCancel` with `args.time` (Unix ms). `time` must be at least 5 seconds in the future, or `0` to clear a schedule without triggering. Posting a new auto-cancel replaces the previous one. It is one-shot: after firing, open orders are cancelled and the schedule clears; orders placed after the fire are unaffected. Each account may trigger auto-cancel at most **10 times per UTC day** (`daily_limit: 10`), else `auto_cancel_daily_limit_reached`; clearing (`time: 0`) is always allowed. Response echoes `{ status: "ok", deadline }`. `GET /v1/account/auto-cancel` returns `deadline`, `triggered` (fires today, resets 00:00 UTC), `daily_limit`, and `next_reset` (Unix-ms next UTC midnight). ## When To Use - Create resting or immediate orders on a perps instrument with Create Orders; choose `tif` per execution goal (see [[syntheses/order-types-and-execution|order types and execution]]). - Use client order IDs (`coid`) to cancel idempotently via Cancel Orders COID without tracking server-assigned `oid`s. - Arm auto-cancel as a safety net for bots so open orders self-cancel if your process dies. - Reconcile state with Get Open Orders (live) and Get Orders (history) - see [[concepts/positions-and-portfolio|positions and portfolio]] and [[concepts/trades-and-activity|trades and activity]]. ## Risks & Pitfalls - **The create response is an ACK, not a fill.** Always fetch the real result with Get Orders; a `200` array can still contain per-order `OrderRejected` entries. - **Cancel cascades to TP/SL children** with reason `ParentCancelled` - do not treat child cancellations as independent failures. - **`open_orders_limit`** (a `429` variant) is a capacity cap, not a rate limit: waiting does not free slots. Cancel resting orders or wait for fills. `Retry-After` is absent on this error but present on `ip_rate_limited`/`action_rate_limited`. - **Trading rate limits** (CLOB, burst / sustained): `POST /order` 5,000/10s / 120,000/10min; `DELETE /order` 5,000/10s / 120,000/10min; `POST /orders` 2,000/10s / 21,000/10min; `DELETE /orders` 2,000/10s / 15,000/10min; `DELETE /cancel-all` 250/10s / 6,000/10min; `DELETE /cancel-market-orders` 1,500/10s / 21,000/10min. - **Timestamp units differ**: most `ts` values are Unix ms, but withdrawals use Unix seconds. - Even with valid credentials, order creation still requires a signed payload - see [[concepts/authentication|authentication]]. ## Related Concepts - [[concepts/authentication|Authentication]] - [[concepts/order-book-and-pricing|Order book and pricing]] - [[concepts/perps-trading|Perps trading]] - [[concepts/positions-and-portfolio|Positions and portfolio]] - [[concepts/trades-and-activity|Trades and activity]] - [[syntheses/order-types-and-execution|Order types and execution]] - [[entities/clob-client|clob-client]] ## Sources - `raw/llms_txt_doc-create-orders.md` - `raw/llms_txt_doc-cancel-orders.md` - `raw/llms_txt_doc-cancel-orders-coid.md` - `raw/llms_txt_doc-get-open-orders.md` - `raw/llms_txt_doc-get-orders.md` - `raw/llms_txt_doc-set-auto-cancel.md` - `raw/llms_txt_doc-get-auto-cancel-status.md` --- title: "Positions and Portfolio" type: concept tags: [positions, portfolio, pnl, balances, holders, open-interest, data-api, perps-api] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-current-positions-for-a-user.md", "raw/llms_txt_doc-get-closed-positions-for-a-user.md", "raw/llms_txt_doc-get-positions-for-a-market.md", "raw/llms_txt_doc-get-portfolio.md", "raw/llms_txt_doc-get-public-portfolio.md", "raw/llms_txt_doc-get-pnl.md", "raw/llms_txt_doc-get-equity.md", "raw/llms_txt_doc-get-balances.md", "raw/llms_txt_doc-get-total-value-of-a-user-s-positions.md", "raw/llms_txt_doc-get-top-holders-for-markets.md", "raw/llms_txt_doc-get-open-interest.md"] confidence: high --- ## Two Position Systems Polymarket exposes positions through two distinct APIs. The **Data API** (`https://data-api.polymarket.com`) reports prediction-market (CLOB) positions keyed by condition ID and outcome token, and is mostly public (queried by wallet address). The **Perps API** (`https://api.perpetuals.polymarket.com`) reports perpetual-futures positions with margin, leverage, and liquidation, and its account routes require authentication. The two are not interchangeable; see [[syntheses/clob-vs-perps|CLOB vs Perps]] and [[concepts/perps-trading|Perps Trading]]. ## Prediction-Market Positions (Data API) `GET /positions` (current positions for a user). Query: `user` (required, `0x`-prefixed 40-hex address), `market` (comma-separated condition IDs, mutually exclusive with `eventId`), `eventId` (comma-separated event IDs, mutually exclusive with `market`), `sizeThreshold` (default 1), `redeemable` (default false), `mergeable` (default false), `limit` (default 100, max 500), `offset` (max 10000), `sortBy` (`CURRENT`, `INITIAL`, `TOKENS`, `CASHPNL`, `PERCENTPNL`, `TITLE`, `RESOLVING`, `PRICE`, `AVGPRICE`; default `TOKENS`), `sortDirection` (`ASC`/`DESC`, default `DESC`), `title` (max 100). Returns an array of `Position`: `proxyWallet`, `asset`, `conditionId`, `size`, `avgPrice`, `initialValue`, `currentValue`, `cashPnl`, `percentPnl`, `totalBought`, `realizedPnl`, `percentRealizedPnl`, `curPrice`, `redeemable`, `mergeable`, `title`, `slug`, `icon`, `eventSlug`, `outcome`, `outcomeIndex`, `oppositeOutcome`, `oppositeAsset`, `endDate`, `negativeRisk`. `GET /closed-positions` (settled/exited positions). Same `user`/`market`/`eventId`/`title` filters; `limit` default 10 (max 50), `offset` max 100000, `sortBy` (`REALIZEDPNL`, `TITLE`, `PRICE`, `AVGPRICE`, `TIMESTAMP`; default `REALIZEDPNL`). Each `ClosedPosition`: `proxyWallet`, `asset`, `conditionId`, `avgPrice`, `totalBought`, `realizedPnl`, `curPrice`, `timestamp`, `title`, `slug`, `icon`, `eventSlug`, `outcome`, `outcomeIndex`, `oppositeOutcome`, `oppositeAsset`, `endDate`. `GET /v1/market-positions` (all holders' positions for one market). Query: `market` (required condition ID), `user` (optional single wallet), `status` (`OPEN` = size > 0.01, `CLOSED` = size <= 0.01, `ALL`; default `ALL`), `sortBy` (`TOKENS`, `CASH_PNL`, `REALIZED_PNL`, `TOTAL_PNL`; default `TOTAL_PNL`), `sortDirection`, `limit` (default 50, max 500), `offset`. Returns `MetaMarketPositionV1` objects `{token, positions}` where each `MarketPositionV1` adds profile fields (`name`, `profileImage`, `verified`) plus `avgPrice`, `size`, `currPrice`, `currentValue`, `cashPnl`, `totalBought`, `realizedPnl`, `totalPnl`, `outcome`, `outcomeIndex`. ## Aggregate Value, Holders, Open Interest (Data API) - `GET /value` - total value of a user's positions. Query `user` (required), `market` (comma-separated condition IDs). Returns array of `Value` `{user, value}`. - `GET /holders` - top holders for markets. Query `limit` (default 20, **max 20**), `market` (required, comma-separated condition IDs), `minBalance` (default 1, max 999999). Returns array of `MetaHolder` `{token, holders}`; each `Holder`: `proxyWallet`, `bio`, `asset`, `pseudonym`, `amount`, `displayUsernamePublic`, `outcomeIndex`, `name`, `profileImage`, `profileImageOptimized`. - `GET /oi` - open interest. Query `market` (comma-separated condition IDs). Returns array of `OpenInterest` `{market, value}`. ## Perps Portfolio, PnL, Equity, Balances These live on the Perps API. Account routes authenticate with the `POLYMARKET-PROXY` (proxy address) and `POLYMARKET-SECRET` (proxy secret) headers; see [[concepts/authentication|Authentication]]. `GET /v1/account/portfolio` (`getPortfolio`, Request Weight 2, authenticated) - current portfolio snapshot. Returns `Portfolio` `{positions, margin, withdrawable, in_liquidation, timestamp}`. Each `PortfolioPosition`: `instrument_id`, `symbol` (e.g. `NVDA-USDC`), `size` (signed contracts; positive = long, negative = short), `entry_price`, `leverage`, `cross`, `initial_margin`, `maintenance_margin`, `position_value`, `liquidation_price`, `unrealized_pnl`, `return_on_equity`, `cumulative_funding`. `MarginSummary`: `total_account_value`, `total_initial_margin`, `total_maintenance_margin`, `total_position_value`. `withdrawable` is the withdrawable USD balance; `in_liquidation` flags liquidation; `timestamp` is milliseconds. `GET /v1/info/portfolio` (`getPublicPortfolio`, Request Weight 5, public) - query `address` (required). Returns `PublicPortfolio` `{positions, equity, timestamp}`; each `PublicPortfolioPosition` is the reduced set `instrument_id`, `symbol`, `size`, `entry_price`, `unrealized_pnl`, `return_on_equity`. `GET /v1/account/pnl` (`getPnlHistory`, Request Weight 10, authenticated) - `interval` (required; `1h`, `4h`, `1d`, `1w`), `start_timestamp` (required, ms), `end_timestamp` (optional; defaults to now). Returns `PnlHistory` `{data, more}` where `data` is an array of `[timestamp, pnl]` pairs (pnl as a string, e.g. `"100.50"`), max 1000 entries; `more` signals additional data. `GET /v1/account/equity` (`getEquityHistory`, authenticated) - `interval` (required; `1s`, `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w`), `start_timestamp` (required), `end_timestamp` (optional). Returns `EquityHistory` `{data, more}`, `data` an array of `[timestamp, equity]` pairs, max 1000. `GET /v1/account/balances` (`getBalances`, authenticated) - returns an array of `Balance` `{asset, balance, value}` where `value` is the USD value. ## Notes and Pitfalls - Data API `market` and `eventId` filters are mutually exclusive on `/positions`, `/closed-positions`, and `/activity`. - The `/holders` `limit` caps at 20, unlike other list endpoints. - Perps `size` is signed; a negative value is a short. PnL and equity timestamps are Unix milliseconds; values are returned as strings. - Realized profit-and-loss is exposed on both closed prediction positions (`realizedPnl`) and perps history (`/v1/account/pnl`). ## Related Concepts - [[concepts/trades-and-activity|Trades and Activity]] - [[concepts/markets-and-events|Markets and Events]] - [[concepts/perps-trading|Perps Trading]] - [[syntheses/clob-vs-perps|CLOB vs Perps]] ## Sources Data API and Perps API position/portfolio reference pages listed in frontmatter `sources`. --- title: "Rewards and Earnings" type: concept tags: [rewards, earnings, liquidity, maker, open-interest, clob, perps] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-account-rewards.md", "raw/llms_txt_doc-get-current-active-rewards-configurations.md", "raw/llms_txt_doc-get-multiple-markets-with-rewards.md", "raw/llms_txt_doc-get-raw-rewards-for-a-specific-market.md", "raw/llms_txt_doc-get-reward-percentages-for-user.md", "raw/llms_txt_doc-get-earnings-for-user-by-date.md", "raw/llms_txt_doc-get-total-earnings-for-user-by-date.md", "raw/llms_txt_doc-get-user-earnings-and-markets-configuration.md"] confidence: high --- ## Definition Polymarket runs two distinct reward systems. The **CLOB liquidity-rewards program** pays market makers who post qualifying resting orders in configured markets; a market's reward budget is split among makers by their contribution, and earnings accrue per market per UTC day. The **Perps open-interest (OI) rewards** program (a separate mechanism on the Perps HTTP API) pays APR on the account's average gross open interest. Both are queried through their own endpoint families. ## How It Works **CLOB rewards configuration** - every reward config is scoped to a market (`condition_id`) with eligibility gates `rewards_max_spread` and `rewards_min_size`, plus a `rewards_config` array giving `asset_address`, `start_date`, `end_date`, `rate_per_day`, and `total_rewards`. - `GET /rewards/markets/current` - all active configs grouped by market. `sponsored=true` returns sponsored configs. Paginated 500/page; `next_cursor` of `"LTE="` marks the last page. Fields include `native_daily_rate`, `sponsored_daily_rate`, `total_daily_rate`, `sponsors_count`. - `GET /rewards/markets/multi` - active markets with rewards plus trading metrics; supports `q`, repeatable `tag_slug`/`event_id`, `event_title`, numeric filters (`min_volume_24hr`, `max_spread`, `min_price`, ...), `order_by` (enum incl. `rate_per_day`, `volume_24hr`, `competitiveness`), `position` (`ASC`/`DESC`), `page_size` (default 100, max 500), `next_cursor`. - `GET /rewards/markets/{condition_id}` - present and future reward configs for one market. `sponsored=true` folds sponsored daily rates into each config's `rate_per_day`. Paginated 100/page. **User earnings (CLOB, require L2 auth headers)**: - `GET /rewards/user?date=YYYY-MM-DD` - per-market earnings for one day (`date`, `condition_id`, `asset_address`, `maker_address`, `earnings`, `asset_rate`). Paginated 100/page. `date` required. - `GET /rewards/user/total?date=YYYY-MM-DD` - summed earnings for the day, grouped by `asset_address`. `date` required. - `GET /rewards/user/markets` - current rewards with the user's live earnings and `earning_percentage` per market, plus rich filters (`q`, `tag_slug`, `favorite_markets`, `only_open_orders`, `only_open_positions`, `order_by`, `position`, `page_size` max 500). `date` optional (defaults to current date). - `GET /rewards/user/percentages` - real-time map of `condition_id` -> percentage of total rewards the user is currently earning in that market. Several of these accept `signature_type` (`0` EOA, `1` POLY_PROXY, `2` POLY_GNOSIS_SAFE) and `maker_address` for address derivation, and `sponsored` to select sponsored earnings. **Perps OI rewards** - `GET /v1/account/rewards` (requires `POLYMARKET-PROXY` + `POLYMARKET-SECRET`) returns per-instrument daily liquidity reward shares. Reward periods run **12:00 UTC to 12:00 UTC**, labeled by their UTC end date. **OI rewards pay 6% APR** on the account's full daily average gross OI across all instruments **when the combined daily average gross OI of its rewards entity is at least $1M**; accounts without an entity mapping qualify independently. The first reward period starts **2026-05-08 12:00 UTC**. Params: `date`, `start_date`, `end_date`, `limit`. Response carries `maker_share_7d` (rolling 7-day account maker volume / total exchange volume), `reward_distributed`, a per-instrument `breakdown`, and `oi_rewards` (`account_oi`, `reward_amount`). Request Weight: 2. ## Key Parameters - `condition_id` - market identifier for reward config lookups. - `rewards_max_spread`, `rewards_min_size` - eligibility gates for maker orders. - `rate_per_day`, `total_rewards`, `asset_address` - the reward budget per config. - `date` - required for `/rewards/user` and `/rewards/user/total`; optional (defaults to today) for `/rewards/user/markets`. - `sponsored` - selects or folds in sponsored rewards. - `next_cursor` - pagination; `"LTE="` means last page. ## When To Use - Discover which markets pay rewards and how much: `GET /rewards/markets/current` or `/rewards/markets/multi`. - Check your live share in a market before committing liquidity: `GET /rewards/user/percentages`. - Reconcile daily accruals: `GET /rewards/user` (per market) and `GET /rewards/user/total` (summed by asset). - Track perps OI rewards accrual: `GET /v1/account/rewards`. ## Risks & Pitfalls - Do not conflate the two systems: **CLOB liquidity rewards** (per-market maker rewards on `clob.polymarket.com`) and **Perps OI rewards** (`api.perpetuals.polymarket.com`) have different qualification, cadence, and endpoints. - CLOB user-earnings endpoints require **L2 auth headers**; `maker_address` alone does not authenticate - with API-KEY auth you must also pass the correct `signature_type`. - OI rewards' 6% APR is gated on the **rewards entity** reaching $1M average gross OI, not just your individual account (unless you have no entity mapping). - `id` on `/rewards/markets/current` configs is always `0`; use `/rewards/markets/{condition_id}` for real config IDs. - Reward periods are UTC 12:00-12:00 windows - a "day" is not midnight-aligned. ## Related Concepts - [[concepts/fees]] - maker rebates, a separate maker incentive. - [[concepts/placing-orders]] - posting the resting maker orders that earn rewards. - [[concepts/order-book-and-pricing]] - spread and size that gate eligibility. - [[concepts/perps-trading]] - the venue behind OI rewards. - [[concepts/authentication]] - the L2 and proxy headers these endpoints need. - [[syntheses/api-surface-map]] - the full endpoint catalog. ## Sources - raw/llms_txt_doc-get-account-rewards.md - `GET /v1/account/rewards` - raw/llms_txt_doc-get-current-active-rewards-configurations.md - `GET /rewards/markets/current` - raw/llms_txt_doc-get-multiple-markets-with-rewards.md - `GET /rewards/markets/multi` - raw/llms_txt_doc-get-raw-rewards-for-a-specific-market.md - `GET /rewards/markets/{condition_id}` - raw/llms_txt_doc-get-reward-percentages-for-user.md - `GET /rewards/user/percentages` - raw/llms_txt_doc-get-earnings-for-user-by-date.md - `GET /rewards/user` - raw/llms_txt_doc-get-total-earnings-for-user-by-date.md - `GET /rewards/user/total` - raw/llms_txt_doc-get-user-earnings-and-markets-configuration.md - `GET /rewards/user/markets` --- title: "RFQ, Quotes, and Last Look" type: concept tags: [rfq, quotes, last-look, maker, combinatorial, bridge, exchange-v3] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-a-quote.md", "raw/llms_txt_doc-submit-a-quote.md", "raw/llms_txt_doc-cancel-a-quote.md", "raw/llms_txt_doc-confirm-or-decline-last-look.md"] confidence: high --- ## Definition The **Combinatorial RFQ (Request-for-Quote)** system is a quote-driven trading path that is distinct from the central limit order book (CLOB). A requester asks for a price on a combinatorial position (built from one or more market legs); market makers (**quoters**) submit signed quotes during a competition window; the engine assembles a fill bundle; and selected makers get a **last-look** confirmation before onchain execution. It runs on its own service, `https://combos-rfq-api.polymarket.com`, and trades **settle through Exchange v3**. A separate, unrelated "Get a quote" endpoint on the Bridge API produces swap/bridge price quotes (see below). ## How It Works **Conventions**: all `*_e6` fields are six-decimal fixed-point values encoded as **strings**; all timestamps are **Unix milliseconds** (integer; zero/omitted means unset). Errors return `{ "error": "..." }`. Maker endpoints (all POST, all require **CLOB L2 authentication** for the maker role, via `POLY_API_KEY`/`POLY_ADDRESS`/`POLY_SIGNATURE`/`POLY_PASSPHRASE`/`POLY_TIMESTAMP`): - **`POST /v1/maker/quotes`** - submit a signed maker quote for an active RFQ. **REST does not assign a quote ID - generate `quote_id` client-side.** Body: `quote_id`, `rfq_id`, `signer_address`, `maker_address`, `signature_type`, `price_e6`, `size_e6` (fillable share count; note this differs from the request's size unit), optional `valid_until` (Unix ms), and a `signed_order` (Exchange v3 order). Returns the current `RFQSnapshot`. - **`POST /v1/maker/quotes/cancel`** - cancel an active quote before it is selected. Body: `rfq_id`, `quote_id`, `signer_address`, `maker_address`, `signature_type`; `signer_address` and `maker_address` must match the authenticated identity. Returns the updated `RFQSnapshot`. - **`POST /v1/maker/confirmations`** - respond to a **last-look** confirmation for a selected quote. Body adds `decision` (`CONFIRM` or `DECLINE`). Returns a `MakerConfirmationResult` (a snapshot and/or an `ExecutionHandoff`, depending on whether the confirmation completed the bundle). **RFQ lifecycle** (`RFQStatus` enum): `CREATED` -> `COLLECTING_QUOTES` -> `AWAITING_REQUESTER_ACCEPTANCE` -> `AWAITING_MAKER_CONFIRMATION` -> `EXECUTING` -> `FILLED`, with terminal branches `FAILED`, `EXPIRED`, `CANCELED`, `REJECTED`. The `RFQSnapshot` exposes the timing windows `competition_started_at` / `competition_ends_at` and `confirmation_started_at` / `confirmation_ends_at` (all Unix ms), the selected `bundle` (a `FillBundle` with `requested_shares_e6`, optional `requested_notional_e6` for BUY RFQs, `blended_price_e6`, and per-maker `allocations`), and `maker_confirmations` (each with `decision` = `CONFIRM`/`DECLINE`/`TIMED_OUT`). **Request shape**: an `RFQRequest` carries `leg_position_ids`, `condition_id`, `yes_position_id`/`no_position_id`, `direction` (`BUY`/`SELL`), `side` (`YES`/`NO` - currently only `YES` is supported), and `requested_size` whose `unit` is `notional` for requester BUY RFQs and `shares` for requester SELL RFQs. **Signed order** (`ExchangeV3Order`): `salt`, `maker`, `signer`, `tokenId` (YES or NO combo position ID), `makerAmount`, `takerAmount` (both six-decimal base units), `side` (`0` BUY / `1` SELL), `signatureType` (`0` EOA, `1` POLY_PROXY, `2` GNOSIS_SAFE, `3` POLY_1271), `timestamp` (Unix seconds as string), and an EIP-712 `signature`. **Bridge "Get a quote"** (separate) - `POST /quote` on `https://bridge.polymarket.com` prices a cross-chain swap/bridge. Body: `fromAmountBaseUnit`, `fromChainId`, `fromTokenAddress`, `recipientAddress`, `toChainId`, `toTokenAddress`. Returns `quoteId`, `estCheckoutTimeMs`, `estInputUsd`/`estOutputUsd`, `estToTokenBaseUnit`, and an `estFeeBreakdown` (`gasUsd`, `maxSlippage`, `minReceived`, `swapImpact`, ...). This is not part of the RFQ maker flow. ## Key Parameters - `rfq_id`, `quote_id` - RFQ and maker-quote identifiers; `quote_id` is client-generated. - `price_e6`, `size_e6` - six-decimal fixed-point strings; `size_e6` is a share count. - `signature_type` - `0`/`1`/`2`/`3` per CLOB signature type. - `decision` - `CONFIRM` or `DECLINE` for last look. - `valid_until` - optional quote expiry in Unix ms. ## When To Use - Quote as a market maker: submit with `POST /v1/maker/quotes`, adjust or withdraw with `.../cancel`, and honor selection via `POST /v1/maker/confirmations`. - Use the RFQ path (over the CLOB) for **combinatorial** positions spanning multiple legs. - Use the Bridge `POST /quote` only to price moving funds across chains, not to trade. ## Risks & Pitfalls - The Bridge "Get a quote" endpoint shares the word "quote" but is unrelated to RFQ - do not confuse the two hosts or flows. - You must generate `quote_id` yourself for REST submissions; the server will not mint one. - `size_e6` on a quote is a **share count** and may differ from the request's size unit (notional vs shares). - HTTP `409` (Conflict, e.g. `competition window closed`) means the RFQ is not in a state that accepts the command - check `status` in the last snapshot. - A last-look `TIMED_OUT` maker confirmation counts against the fill; respond within the confirmation window. - `signer_address`/`maker_address` must match the authenticated L2 identity or the call returns `403` (`auth address mismatch`). ## Related Concepts - [[concepts/placing-orders]] - the CLOB order path this system parallels. - [[concepts/authentication]] - CLOB L2 headers required for maker endpoints. - [[concepts/deposits-withdrawals-transfers]] - the Bridge API that also serves swap quotes. - [[syntheses/clob-vs-perps]] and [[syntheses/order-types-and-execution]] - how RFQ fits the execution landscape. - [[syntheses/api-surface-map]] - the full endpoint catalog. ## Sources - raw/llms_txt_doc-submit-a-quote.md - `POST /v1/maker/quotes` - raw/llms_txt_doc-cancel-a-quote.md - `POST /v1/maker/quotes/cancel` - raw/llms_txt_doc-confirm-or-decline-last-look.md - `POST /v1/maker/confirmations` - raw/llms_txt_doc-get-a-quote.md - Bridge `POST /quote` (swap/bridge quote, distinct from RFQ) --- title: "Tags, Search and Metadata" type: concept tags: [search, tags, series, teams, sports, comments, profiles, gamma-api, discovery] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-search-markets-events-and-profiles.md", "raw/llms_txt_doc-get-tag-by-id.md", "raw/llms_txt_doc-get-tag-by-slug.md", "raw/llms_txt_doc-get-tags-related-to-a-tag-id.md", "raw/llms_txt_doc-get-tags-related-to-a-tag-slug.md", "raw/llms_txt_doc-get-related-tags-relationships-by-tag-id.md", "raw/llms_txt_doc-get-related-tags-relationships-by-tag-slug.md", "raw/llms_txt_doc-get-event-tags.md", "raw/llms_txt_doc-get-market-tags-by-id.md", "raw/llms_txt_doc-list-series.md", "raw/llms_txt_doc-get-series-by-id.md", "raw/llms_txt_doc-list-teams.md", "raw/llms_txt_doc-get-sports-metadata-information.md", "raw/llms_txt_doc-get-valid-sports-market-types.md", "raw/llms_txt_doc-list-comments.md", "raw/llms_txt_doc-get-comments-by-comment-id.md", "raw/llms_txt_doc-get-comments-by-user-address.md", "raw/llms_txt_doc-get-public-profile-by-wallet-address.md"] confidence: high --- ## Overview This is the discovery layer of the **Gamma API** (`https://gamma-api.polymarket.com`): full-text search, the tag taxonomy that organizes markets and events, recurring **series**, sports **teams**/metadata, **comments**, and public **profiles**. These endpoints power browsing and filtering that feed the fetch routes in [[concepts/markets-and-events|Markets and Events]]. ## Search `GET /public-search` (`publicSearch`) searches markets, events, and profiles. Query: `q` (required), `cache` (boolean), `events_status` (string), `limit_per_type` (integer), `page` (integer), `events_tag` (array of string), `keep_closed_markets` (integer), `sort` (string), `ascending` (boolean), `search_tags` (boolean), `search_profiles` (boolean), `recurrence` (string), `exclude_tag_id` (array of integer), `optimized` (boolean). Returns `Search` `{events, tags, profiles, pagination}` - parallel result arrays plus pagination metadata. ## Tags A `Tag` object: `id`, `label`, `slug`, `forceShow`, `publishedAt`, `createdBy`, `updatedBy`, `createdAt`, `updatedAt`, `forceHide`, `isCarousel`. Fetch and traverse tags: - `GET /tags/{id}` (`getTag`) - path `id`; query `include_template` -> `Tag`. - `GET /tags/slug/{slug}` (`getTagBySlug`) - query `include_template` -> `Tag`. - `GET /tags/{id}/related-tags/tags` (`getTagsRelatedToATagById`) - query `omit_empty` (boolean), `status` (`active`, `closed`, `all`) -> array of `Tag`. - `GET /tags/slug/{slug}/related-tags/tags` (`getTagsRelatedToATagBySlug`) - same query -> array of `Tag`. - `GET /tags/{id}/related-tags` (`getRelatedTagsById`) - query `omit_empty`, `status` -> array of `RelatedTag`. - `GET /tags/slug/{slug}/related-tags` (`getRelatedTagsBySlug`) - same -> array of `RelatedTag`. The distinction: the `.../related-tags/tags` routes return full `Tag` objects, while the `.../related-tags` routes return the **relationship** rows `RelatedTag` `{id, tagID, relatedTagID, rank}` (the edges, with a `rank`). Reverse lookups from an entity to its tags: - `GET /events/{id}/tags` (`getEventTags`) -> array of `Tag`. - `GET /markets/{id}/tags` (`getMarketTags`) -> array of `Tag`. Tag IDs and slugs are also accepted as filters (`tag_id`, `tag_slug`, `related_tags`, `exclude_tag_id`, `tag_match`) on the market/event list endpoints. ## Series A `Series` is a recurring grouping of events (e.g. a weekly game series). Fields include `id`, `ticker`, `slug`, `title`, `subtitle`, `seriesType`, `recurrence`, `description`, `image`, `icon`, `layout`, `active`, `closed`, `archived`, `new`, `featured`, `restricted`, `volume24hr`, `volume`, `liquidity`, `startDate`, `pythTokenID`, `cgAssetName`, `score`, `events`, `collections`, `categories`, `tags`, `commentCount`, `chats`. - `GET /series` (`listSeries`) -> array of `Series`. Query: `limit`, `offset`, `order`, `ascending`, `slug`, `categories_ids`, `categories_labels`, `closed`, `include_chat`, `recurrence`, `exclude_events`. - `GET /series/{id}` (`getSeries`) - query `include_chat` -> `Series`. ## Sports Teams and Metadata - `GET /teams` (`listTeams`) -> array of `Team`. Query filters `league`, `name`, `abbreviation`. `Team`: `id`, `name`, `league`, `record`, `logo`, `abbreviation`, `alias`, `createdAt`, `updatedAt`. - `GET /sports` (`getSportsMetadata`) -> array of `SportsMetadata`: `sport` (identifier/abbreviation), `image` (logo URL), `resolution`, `ordering` (preferred display order, typically "home" or "away"), `tags`, `series`. - `GET /sports/market-types` (`getSportsMarketTypes`) -> `SportsMarketTypesResponse` `{marketTypes}`, a list of all valid sports market-type strings. These correspond to the `sports_market_types` / `sportsMarketType` filters and fields on markets. ## Comments A `Comment`: `id`, `body`, `parentEntityType`, `parentEntityID`, `parentCommentID`, `userAddress`, `replyAddress`, `createdAt`, `updatedAt`, `profile`, `reactions`, `reportCount`, `reactionCount`, `name`, `pseudonym`, `displayUsernamePublic`, `bio`, `isMod`, `isCreator`, `proxyWallet`, `baseAddress`, `profileImage`, `profileImageOptimized`, `positions`. - `GET /comments` (`listComments`) -> array of `Comment`. Query: `limit`, `offset`, `order`, `ascending`, `parent_entity_type` (`Event`, `Series`, `market`), `parent_entity_id`, `get_positions`, `holders_only`. - `GET /comments/{id}` (`getCommentsByCommentId`) - path `id` (required), query `get_positions` -> array of `Comment` (the comment and its thread). - `GET /comments/user_address/{user_address}` (`getCommentsByUserAddress`) - path `user_address` (required) -> array of `Comment`. ## Public Profiles `GET /public-profile` (`getPublicProfile`) - query `address` (required) -> `PublicProfileResponse`: `createdAt` (ISO 8601), `proxyWallet`, `profileImage`, `displayUsernamePublic`, `bio`, `pseudonym` (auto-generated), `name` (user-chosen display name), `users` (associated user objects), `xUsername` (X/Twitter handle), `verifiedBadge`. Errors return `PublicProfileError`. Profiles also surface embedded in search results, trades, holders, and comments. ## Notes and Pitfalls - Tag traversal has two families: `/tags/.../related-tags/tags` returns hydrated `Tag` objects; `/tags/.../related-tags` returns `RelatedTag` edge rows (`tagID` -> `relatedTagID`, with `rank`). Choose by whether you need labels or the graph. - `parent_entity_type` on comments accepts `Event`, `Series`, and lowercase `market`. - Both `id`- and `slug`-keyed variants exist for tags, series, events, and markets; slugs are stable, human-readable identifiers. ## Related Concepts - [[concepts/markets-and-events|Markets and Events]] - [[concepts/positions-and-portfolio|Positions and Portfolio]] - [[concepts/accounts-and-referrals|Accounts and Referrals]] - [[syntheses/api-surface-map|API Surface Map]] ## Sources Gamma API search, tag, series, sports, comment, and profile reference pages listed in frontmatter `sources`. --- title: "Trades and Activity" type: concept tags: [trades, fills, activity, statistics, account-stats, combos, data-api, perps-api] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-get-fills.md", "raw/llms_txt_doc-get-trades-for-a-user-or-markets.md", "raw/llms_txt_doc-get-recent-trades.md", "raw/llms_txt_doc-get-user-activity.md", "raw/llms_txt_doc-get-user-combo-activity.md", "raw/llms_txt_doc-get-statistics.md", "raw/llms_txt_doc-get-account-stats.md", "raw/llms_txt_doc-get-total-markets-a-user-has-traded.md"] confidence: high --- ## Overview Trade and activity history spans the same two backends as positions. The **Data API** (`https://data-api.polymarket.com`) serves prediction-market trades and a rich per-user activity ledger keyed by wallet address (mostly public). The **Perps API** (`https://api.perpetuals.polymarket.com`) serves perpetual-futures fills (your own, authenticated) and a public trade tape per instrument. See [[concepts/positions-and-portfolio|Positions and Portfolio]] and [[syntheses/clob-vs-perps|CLOB vs Perps]]. ## Prediction-Market Trades (Data API) `GET /trades` (trades for a user or markets). Query: `limit` (default 100, max 10000), `offset` (max 10000), `takerOnly` (default `true`), `filterType` (`CASH` or `TOKENS`), `filterAmount` (min 0), `market` (comma-separated condition IDs, mutually exclusive with `eventId`), `eventId` (comma-separated), `user`, `side` (`BUY`/`SELL`), `start` and `end` (epoch **seconds**). For `start`, omit or pass `0` for the default window (most recent ~3 years); pass a positive epoch (e.g. `1`) to retrieve full history. `end` defaults to the current time; rows newer than `end` are excluded. Each `Trade`: `proxyWallet`, `side` (`BUY`/`SELL`), `asset`, `conditionId`, `size`, `price`, `timestamp`, `title`, `slug`, `icon`, `eventSlug`, `outcome`, `outcomeIndex`, `name`, `pseudonym`, `bio`, `profileImage`, `profileImageOptimized`, `transactionHash`. ## User Activity Ledger (Data API) `GET /activity` (user activity) is the unified on-chain ledger. Query: `limit` (default 100, max 500), `offset` (max 10000), `user` (required), `market` (comma-separated condition IDs, mutually exclusive with `eventId`), `eventId`, `type` (array of `TRADE`, `SPLIT`, `MERGE`, `REDEEM`, `REWARD`, `CONVERSION`, `DEPOSIT`, `WITHDRAWAL`, `YIELD`, `MAKER_REBATE`, `TAKER_REBATE`, `REFERRAL_REWARD`), `start` and `end` (epoch seconds; same window semantics as `/trades`), `sortBy` (`TIMESTAMP`, `TOKENS`, `CASH`; default `TIMESTAMP`), `sortDirection` (`ASC`/`DESC`, default `DESC`), `side` (`BUY`/`SELL`). Each `Activity`: `proxyWallet`, `timestamp`, `conditionId`, `type` (same enum), `size`, `usdcSize`, `transactionHash`, `price`, `asset`, `side`, `outcomeIndex`, `slug`, `icon`, `eventSlug`, `outcome`, `name`, `pseudonym`, `bio`, `profileImage`, `profileImageOptimized`, and `isCombo`. `isCombo` is `true` when the row is part of a combinatorial (multi-market) position; it is a flag only - the row's `conditionId` equals the combo's `combo_condition_id`, which you pass to `/v1/activity/combos` (or `/v1/positions/combos`) via `market_id` to fetch legs and detail. It is omitted on non-combo rows. `GET /v1/activity/combos` (user combo activity) returns combo lifecycle and redeem events (split / merge / convert / compress / wrap / unwrap / redeem) with a per-leg breakdown; it is the combo counterpart to `/activity` trade rows (also available at `/v1/data/user/{address}/activity/combos`). Query: `user` (required), `market_id` (comma-separated `combo_condition_id` values, i.e. the `market_id` of `isCombo` rows), `limit` (default 50, max 500), `offset`, `cursor` (opaque continuation token from `pagination.next_cursor`; when present it supersedes `offset`). Returns `CombosActivityResponse` `{activity, pagination}`. Each `ComboActivity`: `id`, `event_kind` (deprecated - use `type`), `side` (deprecated: `Split`/`Merge`/`Convert`/`Compress`/`Wrap`/`Unwrap`/`Redeem`), `module_kind` (always `Combinatorial`), `user_address`, `combo_condition_id`, `combo_position_id`, `module_id`, `amount_usdc` (null on redeems), `payout_usdc` (null on lifecycle events), `timestamp`, `tx_dttm` (RFC3339 UTC), `tx_hash`, `log_index`, `block_number`, and `legs`. Each `ComboLeg`: `leg_index`, `leg_position_id`, `leg_condition_id` (distinct from the combo's), `leg_outcome_index`, `leg_outcome_label`. `Pagination`: `limit`, `offset`, `has_more`, `next_cursor` (opaque, null when `has_more` is false; pass back verbatim as `?cursor=`). `GET /traded` (total markets a user has traded). Query `user` (required). Returns `Traded` `{user, traded}` where `traded` is an integer count. ## Perps Fills and Trade Tape (Perps API) `GET /v1/account/fills` (`getFills`, authenticated with `POLYMARKET-PROXY` / `POLYMARKET-SECRET`) - your own fill history. Query `start_timestamp`, `end_timestamp` (both optional, ms; `end` defaults to now). **Max 100 entries per request.** Returns `AccountTrades` `{data, more}`. Each `AccountTradeData`: `trade_id`, `order_id`, `instrument_id`, `side`, `price`, `quantity`, `taker`, `fee`, `fee_asset`, `previous_size`, `previous_entry_price`, `pnl`, `liquidation`, `timestamp`, `hash`. `GET /v1/info/trades` (`getTrades`, public) - public trade tape for one instrument. Query `instrument_id` (required), `start_timestamp`, `end_timestamp`. Max 100 entries. Returns `Trades` `{data, more}`; each `TradeData`: `trade_id`, `instrument_id`, `side` (`long`/`short`), `price`, `quantity`, `timestamp`, `hash` (on-chain tx hash, `"0x"` if not yet mined). ## Statistics and Account Stats (Perps API) `GET /v1/info/statistics` (`getStatistics`, public) - query `instrument_id` (optional). Returns an array of `Statistic`: `instrument_id`, `symbol`, `volume` (24-hour volume in contracts), `open_price` (price from 24 hours ago), and `klines` (last 24-hour kline arrays; each kline = `[open time, open, high, low, close, volume, number of trades]`). `GET /v1/account/stats` (`getAccountStats`, authenticated) - the account's rolling 7-day trading stats. Cached by UTC day and may be stale by up to 24 hours. Returns `AccountStats`: `volume_7d`, `taker_volume_7d`, `maker_volume_7d`, `account_maker_share_7d` (account maker volume / total exchange volume), plus `entity_maker_share_7d`, `entity_id`, and `entity_name` when the account belongs to a liquidity-rewards entity. These feed [[concepts/rewards-and-earnings|Rewards and Earnings]] and [[concepts/fees|Fees]]. ## Notes - `/fills` (private, your trades) vs `/v1/info/trades` (public tape) vs Data API `/trades` (prediction markets) are three separate feeds - pick by backend and privacy. - Data API `start`/`end` are epoch **seconds**; Perps timestamps are Unix **milliseconds**. ## Related Concepts - [[concepts/positions-and-portfolio|Positions and Portfolio]] - [[concepts/rewards-and-earnings|Rewards and Earnings]] - [[concepts/deposits-withdrawals-transfers|Deposits, Withdrawals and Transfers]] - [[concepts/markets-and-events|Markets and Events]] ## Sources Data API and Perps API trade/activity reference pages listed in frontmatter `sources`. --- title: "What Is Polymarket" type: concept tags: [polymarket, prediction-markets, api, clob, gamma, data-api, perps, overview, foundational] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-introduction.md", "raw/llms_txt_doc-geographic-restrictions.md", "raw/llms_txt_doc-clients-sdks.md"] confidence: high --- # What Is Polymarket ## Definition Polymarket is the world's largest prediction market, offering programmatic access to market data and trading through a set of public and authenticated HTTP APIs. It runs on Polygon (chain ID `137`), where market outcomes are tradable ERC-1155-style outcome tokens priced between 0 and 1 (interpreted as probabilities). Beyond binary/multi-outcome prediction markets settled through a central-limit order book (CLOB), Polymarket also operates a newer **perpetual futures** venue with its own HTTP API. Trading is non-custodial: users sign orders locally and retain control of their private keys. ## How It Works The platform is served by three primary APIs, each handling a different domain, plus two supporting services: - **Gamma API** (`https://gamma-api.polymarket.com`) - Markets, events, tags, series, comments, sports, search, and public profiles. The primary API for discovering and browsing market data. Fully public, no auth. - **Data API** (`https://data-api.polymarket.com`) - User positions, trades, activity, holder data, open interest, leaderboards, and builder analytics. Fully public, no auth. - **CLOB API** (`https://clob.polymarket.com`) - Orderbook data, pricing, midpoints, spreads, and price history, plus order placement, cancellation, and other trading operations. Has both public read endpoints (orderbook, prices) and authenticated trading endpoints. A staging host exists at `https://clob-staging.polymarket.com`. - **Bridge API** (`https://bridge.polymarket.com`) - Handles deposits and withdrawals. Bridges are not handled by Polymarket directly; it is a proxy of the fun.xyz service. - **Perps HTTP API** (`https://api.perpetuals.polymarket.com`) - The perpetual-futures trading system: instruments, order placement/cancellation, positions, funding, and market data (book, BBO, klines). Uses integer `instrument_id` and `POLYMARKET-PROXY`/`POLYMARKET-SECRET` credentials rather than the CLOB's `token_id` and `POLY_*` headers. See [[concepts/perps-trading|perps trading]]. A companion Relayer API (`https://relayer-v2.polymarket.com`) submits and tracks gasless transactions. The [[syntheses/api-surface-map|API surface map]] and [[syntheses/clob-vs-perps|CLOB vs perps]] pages catalog which endpoints live where. **Official SDKs.** Polymarket ships open-source clients in three languages, all supporting the full CLOB API (market data, order management, authentication): | Language | Package | Repository | | ---------- | ---------------------------- | -------------------------------------------------- | | TypeScript | `@polymarket/clob-client-v2` | github.com/Polymarket/clob-client-v2 | | Python | `py-clob-client-v2` | github.com/Polymarket/py-clob-client-v2 | | Rust | `polymarket_client_sdk_v2` | github.com/Polymarket/rs-clob-client-v2 | Installation: `npm install @polymarket/clob-client-v2 viem`, `pip install py-clob-client-v2`, or `cargo add polymarket_client_sdk_v2 --features clob`. Each repo includes working examples in its `/examples` directory. See [[entities/clob-client|clob-client]] and [[entities/py-clob-client|py-clob-client]]. A separate **Relayer SDK** handles gasless transactions and deposit-wallet creation: `@polymarket/builder-relayer-client` (TypeScript) and `py-builder-relayer-client` (Python). ## Key Parameters - **Chain**: Polygon mainnet, chain ID `137`. - **API base URLs**: Gamma `gamma-api.polymarket.com`; Data `data-api.polymarket.com`; CLOB `clob.polymarket.com`; Perps `api.perpetuals.polymarket.com`; Bridge `bridge.polymarket.com`; Relayer `relayer-v2.polymarket.com`. - **Auth boundary**: Gamma and Data are fully public. CLOB read endpoints (orderbook, prices, spreads) are public; CLOB trading requires all 5 `POLY_*` L2 headers. See [[concepts/authentication|authentication]]. - **Geoblock endpoint**: `GET https://polymarket.com/api/geoblock` (on `polymarket.com`, not the API servers) returns `{ "blocked", "ip", "country", "region" }`. ## When To Use - Use the **Gamma API** to discover and browse markets, events, tags, and profiles - see [[concepts/markets-and-events|markets and events]] and [[concepts/tags-search-and-metadata|tags, search, and metadata]]. - Use the **Data API** to read user positions, trades, and activity - see [[concepts/positions-and-portfolio|positions and portfolio]] and [[concepts/trades-and-activity|trades and activity]]. - Use the **CLOB API** to read live prices and the book, and to place/cancel orders on prediction markets - see [[concepts/order-book-and-pricing|order book and pricing]] and [[concepts/placing-orders|placing orders]]. - Use the **Perps HTTP API** for perpetual-futures instruments and trading. ## Risks & Pitfalls - **Geographic restrictions.** Polymarket restricts order placement from certain jurisdictions for regulatory and sanctions compliance. Orders submitted from blocked regions are rejected. Check `GET https://polymarket.com/api/geoblock` before placing orders. Restrictions fall into three groups: **OFAC-sanctioned** jurisdictions are blocked completely on frontend and API (Iran `IR`, Syria `SY`, Cuba `CU`, North Korea `KP`, and Crimea/Donetsk/Luhansk `UA-43`/`UA-14`/`UA-09`) - no new orders and existing positions cannot be closed. A larger **close-only on frontend and API** group (including United States `US`, United Kingdom `GB`, France `FR`, Germany `DE`, Canada provinces, Singapore `SG`, etc.) lets users close but not open positions. A third group (Japan `JP`, Netherlands `NL`, Malta `MT` sports-only) is close-only on the frontend only. - **Server region.** Primary servers run in `eu-west-2`; the closest non-georestricted region is `eu-west-1`. KYC/KYB-verified users can co-locate in `eu-west-2` for lowest latency. - **Do not confuse the two trading worlds.** CLOB prediction markets use `token_id` and `POLY_*` auth; perps use `instrument_id` and `POLYMARKET-PROXY`/`POLYMARKET-SECRET`. Endpoint routes differ (`/book` vs `/v1/info/book`). - **Never commit private keys** to version control; store them in environment variables or secure key management. ## Related Concepts - [[concepts/authentication|Authentication]] - [[concepts/order-book-and-pricing|Order book and pricing]] - [[concepts/placing-orders|Placing orders]] - [[concepts/markets-and-events|Markets and events]] - [[concepts/perps-trading|Perps trading]] - [[syntheses/api-surface-map|API surface map]] - [[syntheses/clob-vs-perps|CLOB vs perps]] - [[entities/clob-client|clob-client]] ## Sources - `raw/llms_txt_doc-introduction.md` - `raw/llms_txt_doc-geographic-restrictions.md` - `raw/llms_txt_doc-clients-sdks.md` --- title: "clob-client" type: entity tags: [client, typescript, clob, sdk, orders, signing] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/github_doc-readme-md-2.md", "raw/llms_txt_doc-clients-sdks.md"] source_url: "https://github.com/Polymarket/clob-client/blob/main/README.md" confidence: high --- # clob-client ## Overview `clob-client` is the **TypeScript** client for the Polymarket CLOB -- `Polymarket/clob-client`, published on npm as `@polymarket/clob-client`. It signs and posts orders and reads market data against `https://clob.polymarket.com`. > [!WARNING] > This repository has been archived and is no longer maintained. The client is > no longer functional and should not be used for new or existing integrations. > Please migrate to our new unified SDK: https://github.com/Polymarket/ts-sdk The newer generation client is `@polymarket/clob-client-v2` (see [[concepts/authentication]]); the Python counterpart is [[entities/py-clob-client]]. ## Characteristics - Language: TypeScript / Node. - Signer via `ethers` `Wallet` (private key) or a viem `WalletClient`. - `funder` is your Polymarket Profile Address (where you send USDC). - `signatureType`: `0` Browser Wallet (MetaMask, Coinbase Wallet, etc.), `1` Magic/Email Login. - Order placement needs the market's `tickSize` and `negRisk` flag, obtained from the Gamma Markets API get-markets endpoint. - By default API errors return as `{ error, status }` objects; pass `throwOnError: true` as the last constructor argument to throw `ApiError`. ## How to Use Install (from the README usage comments): ```ts // npm install @polymarket/clob-client // npm install ethers ``` Client initialization and placing a GTC order: ```ts import { ApiKeyCreds, ClobClient, OrderType, Side, } from "@polymarket/clob-client"; import { Wallet } from "@ethersproject/wallet"; const host = 'https://clob.polymarket.com'; const funder = ''; // This is your Polymarket Profile Address, where you send UDSC to. const signer = new Wallet(""); // This is your Private Key. If using email login export from https://reveal.magic.link/polymarket otherwise export from your Web3 Application // In general don't create a new API key, always derive or createOrDerive const creds = new ClobClient(host, 137, signer).createOrDeriveApiKey(); //0: Browser Wallet(Metamask, Coinbase Wallet, etc) //1: Magic/Email Login const signatureType = 1; (async () => { const clobClient = new ClobClient(host, 137, signer, await creds, signatureType, funder); const resp2 = await clobClient.createAndPostOrder( { tokenID: "", //Use https://docs.polymarket.com/developers/gamma-markets-api/get-markets to grab a sample token price: 0.01, side: Side.BUY, size: 5, }, { tickSize: "0.001",negRisk: false }, //You'll need to adjust these based on the market. Get the tickSize and negRisk T/F from the get-markets above //{ tickSize: "0.001",negRisk: true }, OrderType.GTC, ); console.log(resp2) })(); ``` Using a viem `WalletClient` instead of ethers: ```ts import { ClobClient } from "@polymarket/clob-client"; import { createWalletClient, http } from "viem"; import { polygon } from "viem/chains"; import { privateKeyToAccount } from "viem/accounts"; const host = "https://clob.polymarket.com"; const account = privateKeyToAccount("0x..."); const walletClient = createWalletClient({ account, chain: polygon, transport: http(), }); const clobClient = new ClobClient(host, 137, walletClient); ``` ## Related Entities - [[entities/py-clob-client]] -- the Python CLOB client. - [[concepts/authentication]] -- L1/L2 auth and API credentials. - [[syntheses/order-types-and-execution]] -- CLOB order types vs RFQ. --- title: "py-clob-client" type: entity tags: [client, python, clob, sdk, orders, signing] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/github_doc-readme-md.md", "raw/llms_txt_doc-clients-sdks.md"] source_url: "https://github.com/Polymarket/py-clob-client/blob/main/README.md" confidence: high --- # py-clob-client ## Overview `py-clob-client` is the **Python** client for the Polymarket Central Limit Order Book (CLOB) -- `Polymarket/py-clob-client`, published on PyPI as `py-clob-client`. It wraps market-data reads, order signing, and order management for the CLOB API at `https://clob.polymarket.com`. > [!WARNING] > This repository has been archived and is no longer maintained. The client is > no longer functional and should not be used for new or existing integrations. > Please migrate to our new unified SDK: https://github.com/Polymarket/py-sdk The newer generation client is `py-clob-client-v2` (see [[concepts/authentication]] and [[entities/clob-client]] for the TypeScript counterpart). ## Characteristics - Language: Python 3.9+. - Requires a **private key** that owns funds on Polymarket; optionally a **proxy/funder address** for email or smart-contract wallets. - Authentication levels: Level 0 (no auth, read-only), and authenticated trading via API creds derived from the private key (`create_or_derive_api_creds`). - `signature_type`: `0` standard EOA (MetaMask/hardware), `1` email/Magic wallet, `2` browser wallet proxy. - Prices are dollars from 0.00 to 1.00; shares are whole or fractional outcome tokens. Token IDs come from the Gamma Markets API get-markets endpoint. ## How to Use Install from PyPI (Python 3.9>): ```bash pip install py-clob-client ``` Read-only quickstart: ```python from py_clob_client.client import ClobClient client = ClobClient("https://clob.polymarket.com") # Level 0 (no auth) ok = client.get_ok() time = client.get_server_time() print(ok, time) ``` Start trading (EOA), initializing the client and setting API creds: ```python from py_clob_client.client import ClobClient HOST = "https://clob.polymarket.com" CHAIN_ID = 137 PRIVATE_KEY = "" FUNDER = "" client = ClobClient( HOST, # The CLOB API endpoint key=PRIVATE_KEY, # Your wallet's private key chain_id=CHAIN_ID, # Polygon chain ID (137) signature_type=1, # 1 for email/Magic wallet signatures funder=FUNDER # Address that holds your funds ) client.set_api_creds(client.create_or_derive_api_creds()) ``` Place a limit order (shares at a price): ```python from py_clob_client.client import ClobClient from py_clob_client.clob_types import OrderArgs, OrderType from py_clob_client.order_builder.constants import BUY order = OrderArgs(token_id="", price=0.01, size=5.0, side=BUY) signed = client.create_order(order) resp = client.post_order(signed, OrderType.GTC) print(resp) ``` Place a market order (buy by $ amount): ```python from py_clob_client.clob_types import MarketOrderArgs, OrderType from py_clob_client.order_builder.constants import BUY mo = MarketOrderArgs(token_id="", amount=25.0, side=BUY, order_type=OrderType.FOK) signed = client.create_market_order(mo) resp = client.post_order(signed, OrderType.FOK) print(resp) ``` Note: EOA/MetaMask users must set USDC and Conditional Token allowances (for the main exchange, neg-risk, and neg-risk adapter contracts) before trading; email/Magic wallets have allowances set automatically. ## Related Entities - [[entities/clob-client]] -- the TypeScript CLOB client. - [[concepts/authentication]] -- L1/L2 auth and API credentials. - [[syntheses/order-types-and-execution]] -- CLOB order types vs RFQ. --- title: "Activity Log" type: log --- # Activity Log Append-only record of all wiki changes. ## Format Each entry follows this format: ``` ### YYYY-MM-DD HH:MM — [Action Type] - **Source/Trigger**: what initiated the action - **Pages created**: list of new pages - **Pages updated**: list of updated pages - **Notes**: any contradictions flagged, decisions made ``` --- ### 2026-04-08 00:00 — Setup - **Source/Trigger**: Repository initialized - **Pages created**: index.md, log.md, dashboard.md, analytics.md, flashcards.md - **Pages updated**: none - **Notes**: Empty knowledge base ready for first source ingestion --- title: "API Surface Map" type: synthesis tags: [api, routing, gamma, data-api, clob, perps, rfq, bridge, websocket, navigation] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-introduction.md", "raw/llms_txt_doc-authentication.md", "raw/llms_txt_doc-get-open-interest.md", "raw/llms_txt_doc-get-instruments.md", "raw/llms_txt_doc-submit-a-quote.md", "raw/llms_txt_doc-get-a-quote.md", "raw/llms_txt-llms-txt-index.md"] source_url: "https://docs.polymarket.com/api-reference/introduction.md" confidence: high --- # API Surface Map ## Comparison Polymarket is served by several separate APIs, each on its own host. This is the routing table: pick the family by the question you are answering. | API family | Base host | Auth | Answers | | --- | --- | --- | --- | | Gamma API | `https://gamma-api.polymarket.com` | Public | Markets, events, tags, series, comments, sports, search, public profiles -- discovering/browsing market metadata | | Data API | `https://data-api.polymarket.com` | Public | User positions, trades, activity, holder data, open interest (`GET /oi`), leaderboards, builder analytics | | CLOB API | `https://clob.polymarket.com` | Public reads + L2 for trading | Orderbook, prices, midpoints, spreads, price history; order placement/cancellation | | Perps API | `https://api.perpetuals.polymarket.com` | Public info + proxy/secret for account | Perpetual instruments, index, tickers, funding, perp orders | | Bridge API | `https://bridge.polymarket.com` | Public | Deposits/withdrawals: `POST /quote`, `GET /supported-assets` (proxy of fun.xyz) | | Combinatorial RFQ API | `https://combos-rfq-api.polymarket.com` | CLOB L2 (maker) | Combo-market catalog + maker quote/confirm commands | | WebSocket (WSS) | `docs.polymarket.com/api-reference/wss/*` | Public + authenticated channels | Real-time orderbook/price (Market Channel), user order/trade updates (User Channel), sports, and per-topic Perps/RFQ streams | ## Analysis Per the Introduction, the platform is "served by three separate APIs, each handling a different domain" -- Gamma, Data, and CLOB -- with a separate Bridge API for deposits and withdrawals. Perps and the Combinatorial RFQ system add two more hosts, and real-time updates arrive over WebSocket channels. **Route by intent:** - "What markets/events exist? metadata, tags, search, profiles" -> **Gamma API**. - "What has a user done? positions, trades, activity, holders, open interest, leaderboards" -> **Data API** (for example `GET /oi` returns per-market `{ market, value }`). - "Read the book / prices, or place and cancel prediction-market orders" -> **CLOB API** (reads public; trading needs L2). - "Perpetual futures: instruments, mark/index, funding, perp orders" -> **Perps API** (`/v1/info/*` public, `/v1/account/*` and `/v1/trade/*` for the account). - "Move funds in/out" -> **Bridge API** (`/quote`, `/supported-assets`). - "Market-maker quoting on combos (RFQ / last-look)" -> **Combinatorial RFQ API** (`POST /v1/maker/quotes`, `POST /v1/maker/confirmations`). - "Stream live data or fills" -> **WebSocket** channels. **Auth boundary.** The Gamma API and Data API are fully public. The CLOB API has public read endpoints (orderbook, prices, spreads) and authenticated trading endpoints that require all five `POLY_*` L2 headers (`POLY_ADDRESS`, `POLY_SIGNATURE`, `POLY_TIMESTAMP`, `POLY_API_KEY`, `POLY_PASSPHRASE`). The RFQ maker endpoints reuse those same CLOB L2 credentials. Perps account routes use a different pair, `POLYMARKET-PROXY` / `POLYMARKET-SECRET`. See [[concepts/authentication]]. ## Recommendations - Discover a market and its `token_id` on **Gamma**, then trade on **CLOB** and read your fills/positions on the **Data API** -- three hosts, one workflow. - Do not look for order placement on Gamma/Data (read-only); only CLOB, Perps, and RFQ accept orders/quotes. - For low-latency needs (live book, fills), subscribe to **WebSocket** channels instead of polling REST. - Keep the two auth schemes straight: `POLY_*` L2 headers for CLOB/RFQ, `POLYMARKET-PROXY`/`POLYMARKET-SECRET` for Perps account routes. ## Pages Compared - [[concepts/authentication]] - [[concepts/what-is-polymarket]] - [[concepts/perps-trading]] - [[concepts/rfq-and-quotes]] - [[syntheses/clob-vs-perps]] - [[syntheses/order-types-and-execution]] --- title: "CLOB (Prediction Markets) vs Perps" type: synthesis tags: [clob, perps, prediction-markets, perpetuals, comparison, funding, leverage] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-introduction.md", "raw/llms_txt_doc-get-instruments.md", "raw/llms_txt_doc-get-tickers.md", "raw/llms_txt_doc-get-historical-funding.md", "raw/llms_txt_doc-create-orders.md"] confidence: high --- # CLOB (Prediction Markets) vs Perps ## Comparison Polymarket runs two distinct trading products on two separate APIs. | Dimension | Prediction-market CLOB | Perpetual futures (Perps) | | --- | --- | --- | | API host | `https://clob.polymarket.com` | `https://api.perpetuals.polymarket.com` | | Instrument | Binary outcome shares (YES/NO conditional tokens) | Perpetual contracts on an asset (`instrument_type: perpetual`) | | Categories | Event markets (politics, sports, etc.) | `equity`, `commodity`, `index`, `crypto` | | Price meaning | Dollars 0.00 to 1.00 = probability of outcome | Asset price (mark/index), example `160.00` | | Settlement | Resolves to $0 or $1 on the real-world outcome | Never expires; kept to index via funding | | Leverage | None (fully collateralized shares) | Up to `max_leverage` (example 20), tiered by `risk_tiers` | | Carry cost | None | Funding paid/received each `funding_interval` (example 1h) | | Position risk | Bounded (share value in [0, 1]) | Liquidation with `liquidation_fee` if margin breached | ## Analysis **Prediction-market CLOB.** As the Introduction states, the CLOB API provides "Orderbook data, pricing, midpoints, spreads, and price history. Also handles order placement, cancellation, and other trading operations." You trade shares of a discrete outcome; a YES share worth $0.65 encodes a 65% implied probability and pays $1 if the event resolves true, $0 otherwise. There is no leverage and no ongoing carry -- the whole position value is the collateral. Discovery of markets and token IDs happens on the Gamma API. **Perps.** Perps are non-expiring leveraged contracts. Each instrument (`GET /v1/info/instruments`) is quoted in USDC (example `NVDA-USDC`) and carries trading rules: `funding_interval`, `price_bounds`, `liquidation_fee`, `max_leverage`, tiered `risk_tiers`, and notional caps. Live state comes from `GET /v1/info/tickers` (`index_price`, `mark_price`, `funding_rate`, `open_interest`, `next_funding`). The `funding_rate` is a periodic payment between longs and shorts (history at `GET /v1/info/funding`) that tethers the contract's mark price to the underlying index. Perps orders (`POST /v1/trade/orders`) carry perp-specific fields absent from prediction markets: `tif` (`gtc`/`ioc`/`fok`), `po` (post-only), `ro` (reduce-only), and optional `tr` triggers (`tp`/`sl`) -- because you are managing a leveraged, long-lived position, not buying a fixed-value share. **Mechanically**, CLOB positions are bounded and self-liquidating at resolution; perps positions must be actively margined, cost funding over time, and can be force-liquidated. The two products do not share order plumbing or hosts. ## Recommendations - **Betting on a discrete real-world outcome** (election, game, yes/no event): use the prediction-market CLOB. No funding, no liquidation, bounded downside. - **Directional/leveraged exposure to a continuous price** (a stock, a commodity, crypto) without an expiry: use Perps -- but budget for funding as a recurring carry cost and respect tiered leverage and liquidation risk. - **Short-lived, small directional bets** where you don't want margin management: prefer CLOB shares; the price already encodes probability and downside is capped. - Before sizing a perp order, read `GET /v1/account/config` (applied leverage and cross/isolated mode) and `GET /v1/info/tickers` (funding and mark). ## Pages Compared - [[concepts/perps-trading]] - [[concepts/what-is-polymarket]] - [[concepts/placing-orders]] - [[syntheses/order-types-and-execution]] - [[syntheses/api-surface-map]] --- title: "Order Types and Execution" type: synthesis tags: [orders, execution, clob, rfq, last-look, limit, market, matching, time-in-force] created: 2026-07-07 updated: 2026-07-07 sources: ["raw/llms_txt_doc-create-orders.md", "raw/github_doc-readme-md.md", "raw/github_doc-readme-md-2.md", "raw/llms_txt_doc-submit-a-quote.md", "raw/llms_txt_doc-confirm-or-decline-last-look.md"] confidence: high --- # Order Types and Execution ## Comparison Polymarket offers two execution models: direct order-book trading (CLOB) and Request-for-Quote (RFQ) with maker last-look. | Dimension | Direct CLOB order | RFQ / last-look quote | | --- | --- | --- | | Who initiates | Taker signs and posts an order to the book | Requester broadcasts an RFQ; makers submit competing quotes | | Matching | Immediate against resting book liquidity | Competition window -> selected bundle -> maker confirmation | | Order/quote types | Limit (price + size), market (buy by $ amount) | Signed maker quote (`price_e6`, `size_e6`, `signed_order`) | | Time in force | `GTC`, `IOC`/`ioc`, `FOK`/`fok` (+ `po` post-only, `ro` reduce-only on perps) | Optional `valid_until` quote expiry; RFQ lifecycle statuses | | Last look | None -- fill is immediate | Yes -- maker may `CONFIRM` or `DECLINE` the selected quote | | Best for | Standard liquid trades, precise price/size control | Large/combo size needing sourced maker liquidity | ## Analysis **Direct CLOB orders.** Through the clients, a taker builds, signs, and posts an order. In `py-clob-client` a **limit order** is `OrderArgs(token_id, price, size, side)` -> `create_order` -> `post_order(signed, OrderType.GTC)`, and a **market order** is `MarketOrderArgs(token_id, amount, side, order_type=OrderType.FOK)` -> `create_market_order` -> `post_order(signed, OrderType.FOK)`. In `clob-client`, `createAndPostOrder({ tokenID, price, side, size }, { tickSize, negRisk }, OrderType.GTC)` does the same in one call. `GTC` rests on the book; `FOK` (fill-or-kill) executes immediately or is rejected. See [[entities/py-clob-client]] and [[entities/clob-client]]. The Perps order endpoint (`POST /v1/trade/orders`) makes the order fields explicit: each `CreateOrder` has `iid`, `buy`, optional `p` (price), `qty`, and `tif` (`gtc` / `ioc` / `fok`), plus `po` (post-only), `ro` (reduce-only), a client order id `c`, and an optional `tr` trigger (`trp` trigger price, `tpsl` = `tp` or `sl`, `market` execute-as-market). Post-only and Fill-or-Kill outcomes surface as order statuses (for example `post_only_rejected`), not request rejections. The response is an ACK array of `OrderAccepted`/`OrderRejected`; the fill result is fetched separately via the get-orders endpoint. **RFQ / last-look.** The Combinatorial RFQ system (`combos-rfq-api.polymarket.com`, CLOB L2 maker auth) is a quote-driven flow. A maker submits a signed quote to an active RFQ via `POST /v1/maker/quotes` -- carrying `quote_id` (generated client-side for REST), `rfq_id`, `price_e6`, `size_e6`, and a signed Exchange v3 order; combinatorial RFQ trades settle through Exchange v3. The RFQ moves through `CREATED` -> `COLLECTING_QUOTES` -> `AWAITING_REQUESTER_ACCEPTANCE` -> `AWAITING_MAKER_CONFIRMATION` -> `EXECUTING` -> `FILLED` (or `FAILED`/`EXPIRED`/ `CANCELED`/`REJECTED`). After the requester selects a bundle, the maker gets a **last-look** request and answers with `POST /v1/maker/confirmations`, where `decision` must be `CONFIRM` or `DECLINE`; a successful confirm can produce an `ExecutionHandoff` for onchain execution. Unlike a resting CLOB order, the maker retains a final right to decline. ## Recommendations - **Use direct CLOB** for ordinary trades on liquid markets where you want a specific price (`GTC` limit) or guaranteed immediacy (`FOK`/`IOC` taker) and no counterparty last-look. - **Use RFQ** when you need sized or combinatorial liquidity that the visible book cannot fill -- accept that a selected maker may `DECLINE` at last look, so the quote is not a firm fill until confirmed. - **Post-only (`po`)** to add liquidity without crossing; **reduce-only (`ro`)** to guarantee an order only closes/reduces an existing (perps) position. - Poll the get-orders endpoint for the true fill result after a perps order ACK; the ACK alone does not confirm execution. ## Pages Compared - [[concepts/placing-orders]] - [[concepts/rfq-and-quotes]] - [[concepts/perps-trading]] - [[entities/py-clob-client]] - [[entities/clob-client]] - [[syntheses/api-surface-map]]