# Deprecated: Backtest Copy PnL — Batch Source: https://docs.polynode.dev/api-reference/backtesting/batch POST /v2/copy-pnl/batch Score multiple wallets in one call. Same math as the single-wallet endpoint. > [!WARNING] > > This V2 on-demand endpoint is deprecated. Use the [V3 Copy PnL batch endpoint](/data/wallets/copy-pnl-batch). V3 supports date windows, optional full-history calculation with explicit fallback, lifetime realized-PnL context, and normal V3 account limits. Its response shape and realized-PnL scope differ from V2; weighted-average position metrics are not reproduced. See the [migration notes](/data/wallets/copy-pnl#migrating-from-v2). ```http theme={null} POST https://api.polynode.dev/v2/copy-pnl/batch ``` Use this when you need to score many wallets at once — for example, ranking a candidate-leader list. The endpoint returns one result per wallet, processed in parallel so 50 wallets don't take 50× single-wallet time. ## Request body | Field | Type | Required | Description | | - | - | - | - | | `addresses` | `string[]` | yes | Array of wallet addresses (Safe proxy or EOA). 1 to 100 entries per call. | | `from` | `string \| number` | no | Window start. `YYYY-MM-DD` (UTC midnight) or unix seconds. Defaults to last 30 days when omitted. | | `to` | `string \| number` | no | Window end. Same format as `from`. Defaults to current time. | | `include_trades` | `boolean` | no | When `true`, every result includes the per-fill `trades` array. Off by default — payloads can grow large quickly. | The `from`/`to` window applies to **every** wallet in the batch — pass per-wallet windows by making separate calls. `?period=` preset is **not supported** in the batch body. Use explicit `from`/`to`. ## Response ``` { count: int, elapsed_ms: int, results: [ /* one entry per address — same shape as the single-wallet endpoint */ ] } ``` Per-result fields are identical to the [single-wallet response](/api-reference/backtesting/copy-pnl#response-fields). ## Example: 3 wallets over a 10-day window Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ -H "Content-Type: application/json" \ -X POST \ -d '{ "addresses": [ "0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7", "0xba4ac793e68eacb93b41566137f25757656a9fa6", "0x4b2995b6c8cc2cf56899ad62ee87c3f70c97716f" ], "from": "2026-04-15", "to": "2026-04-25" }' \ "https://api.polynode.dev/v2/copy-pnl/batch" ``` Response (`200 OK`, abridged): ```json theme={null} { "count": 3, "elapsed_ms": 1948, "results": [ { "wallet": "0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7", "actual_pnl_usdc": -7323.06, "backtest_copy_pnl_usdc": -9664.1, "slippage_amount_usdc": 2341.04, "slippage_cost_rate_pct": 31.97, "toxic_for_copying": true, "trade_count": 1637, "pnl_definition": "cashflow", "applied_filters": { "from": 1776211200, "to": 1777075200, "window_days": null }, "partial": false, "sources": { "...": "..." } }, { "wallet": "0xba4ac793e68eacb93b41566137f25757656a9fa6", "actual_pnl_usdc": 0, "backtest_copy_pnl_usdc": 0, "slippage_amount_usdc": 0, "slippage_cost_rate_pct": null, "toxic_for_copying": false, "trade_count": 0, "pnl_definition": "cashflow", "applied_filters": { "from": 1776211200, "to": 1777075200, "window_days": null }, "partial": false, "sources": { "...": "..." } }, { "wallet": "0x4b2995b6c8cc2cf56899ad62ee87c3f70c97716f", "actual_pnl_usdc": -2637.15, "backtest_copy_pnl_usdc": -2690.17, "slippage_amount_usdc": 53.02, "slippage_cost_rate_pct": 2.01, "toxic_for_copying": false, "trade_count": 12, "pnl_definition": "cashflow", "applied_filters": { "from": 1776211200, "to": 1777075200, "window_days": null }, "partial": false, "sources": { "...": "..." } } ] } ``` Note the second wallet — no on-chain trading activity in the window — returns the standard zero-shape with `slippage_cost_rate_pct: null` (denominator unstable per the spec edge case). Wallets that error individually return `{"wallet": "...", "error": "..."}` instead of the full shape, so a single bad wallet won't fail the whole batch. ## Errors `400 Body must include "addresses": [...]`: ```json theme={null} { "error": "Body must include \"addresses\": [...]." } ``` `400 Invalid wallet`: ```json theme={null} { "error": "Invalid wallet: not-a-wallet" } ``` `400 Too many addresses`: ```json theme={null} { "error": "Max 100 addresses per batch." } ``` Auth errors (`401`, `403`) and rate-limit errors (`429`) are identical to the single-wallet endpoint — see [Backtest Copy PnL](/api-reference/backtesting/copy-pnl#errors). ## Limits and behavior * **Max 100 addresses per call**. * **Typical batch latency** — a 100-wallet batch with average \~1.5s per wallet completes in roughly 20s. * **45-second total timeout**. Heavy batches (many high-volume wallets) may exceed — split the address list across multiple calls if so. * **Same rate limit** as the single endpoint: 1 request per 5 seconds per API key. The batch counts as one request regardless of how many wallets are inside. * **Per-wallet errors don't fail the batch.** A wallet that errors during processing returns `{"wallet": "...", "error": "..."}` in its slot. Other wallets still return their full result. * **Same `partial: true` behavior per wallet** as the single endpoint — extreme high-frequency wallets may flag partial inside their result. # BYOB — Add Wallets Source: https://docs.polynode.dev/api-reference/backtesting/byob-add-wallets POST /v2/copy-pnl/wallets Add wallets to your BYOB tracked-pool. Newly-added wallets get scored within seconds (on-add freshening). ```http theme={null} POST https://api.polynode.dev/v2/copy-pnl/wallets ``` Add one or more wallets to your private BYOB tracked-pool. Wallets are immediately added to the global refresh queue AND scored right away by the on-add freshening pass — usually within \~30 seconds for normal wallets, longer for whales. ## Request body | Field | Type | Required | Description | | - | - | - | - | | `addresses` | `string[]` | yes | Array of valid `0x…` wallet addresses (Safe proxy or EOA). Addresses are normalized to lowercase. Max 1000 per request. | ## Response fields | Field | Type | Description | | - | - | - | | `added` | int | Number of NEW wallets added to your pool (excludes those already tracked) | | `already_tracked` | int | Number of wallets in the request body that were already in your pool | | `total` | int | Current size of your pool after this request | | `max` | int | Hard cap on pool size per API key (currently 1000) | | `capped` | bool | `true` when your request would have exceeded `max` and we accepted only the first N that fit | | `refresh_kicked` | int | Number of newly-added wallets queued for immediate background scoring (matches `added`) | | `hint` | string | Only present when `capped: true` — explains how many of your wallets were dropped | ## Example: fresh add Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ -H "Content-Type: application/json" \ -X POST \ -d '{ "addresses": [ "0xdead0000000000000000000000000000000000aa", "0xdead0000000000000000000000000000000000bb" ] }' \ "https://api.polynode.dev/v2/copy-pnl/wallets" ``` Response (`200 OK`): ```json theme={null} { "added": 2, "already_tracked": 0, "total": 110, "max": 1000, "capped": false, "refresh_kicked": 2 } ``` The two new wallets are now in your pool AND queued for immediate scoring. Within \~30s (faster for small wallets, longer for whales) you'll see them populated in `/v2/copy-pnl/leaderboard`. ## Example: re-add (dedupe) Wallets already in your pool are silently skipped — sending the same address twice doesn't count toward your cap. Request (one wallet already tracked, one new): ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ -H "Content-Type: application/json" \ -X POST \ -d '{ "addresses": [ "0xdead0000000000000000000000000000000000aa", "0xdead0000000000000000000000000000000000cc" ] }' \ "https://api.polynode.dev/v2/copy-pnl/wallets" ``` Response (`200 OK`): ```json theme={null} { "added": 1, "already_tracked": 1, "total": 111, "max": 1000, "capped": false, "refresh_kicked": 1 } ``` Only the genuinely new wallet (`0xdead…cc`) was added and refresh-kicked. The duplicate was a no-op. ## Errors `400 Missing or invalid addresses` (covers: missing `addresses` field, non-string in array, malformed hex): ```json theme={null} { "error": "Body must include \"addresses\" — array of valid 0x… wallet addresses." } ``` `400 Too many addresses in one request`: ```json theme={null} { "error": "At most 1000 wallets per request (and per tenant)." } ``` `401 Missing API key`, `403 Free tier`, `429 Rate limited` — same as the on-demand `/v2/copy-pnl/{wallet}` endpoint. See [Backtest Copy PnL → Errors](/api-reference/backtesting/copy-pnl#errors). ## Notes * **Wallets are normalized to lowercase.** Mixing case across requests is fine; the same wallet in different case won't double-track. * **Within a single request, duplicates are de-duped** before the dedup-against-pool check. So passing the same address twice in one body counts as one. * **Pool isolation:** each API key has its own private pool keyed on the SHA256 of your key. Adding wallets to one pool doesn't affect any other customer. * **On-add freshening** runs in the background — the HTTP response returns within milliseconds even though scoring takes 30s+ to complete. Poll `/v2/copy-pnl/leaderboard` to see scores land. * **Capacity behavior**: if your request would have pushed your pool past `max`, we accept the first N that fit and set `capped: true` plus a `hint` explaining what was dropped. We do NOT reject the entire request. # BYOB — Leaderboard Source: https://docs.polynode.dev/api-reference/backtesting/byob-leaderboard GET /v2/copy-pnl/leaderboard Sub-second sorted, filtered, paginated leaderboard over your tracked-wallet pool. Reads precomputed scores from cache. ```http theme={null} GET https://api.polynode.dev/v2/copy-pnl/leaderboard ``` Query the precomputed leaderboard over your private wallet pool. All reads come from cache — sub-second latency regardless of pool size or window. Sort by any output field, filter out toxic wallets or low-volume traders, paginate. ## Query parameters **period** `string` (default: 30d) Time window the scores were computed against. One of: `7d`, `14d`, `30d`, `60d`, `90d`, `180d`. Scores are precomputed for **all six periods** so any choice is sub-second. **sort\_by** `string` (default: backtest\_copy\_pnl\_usdc) Field to sort by. One of: `backtest_copy_pnl_usdc`, `actual_pnl_usdc`, `slippage_amount_usdc`, `slippage_cost_rate_pct`, `trade_count`. **order** `string` (default: desc) `asc` or `desc`. Wallets with `null` `slippage_cost_rate_pct` (when `abs(actual_pnl) < 1`) always sort last regardless of direction. **limit** `int` (default: 100) Max results to return. 1 to 1000. **offset** `int` (default: 0) Skip the first N results. Useful for paginating beyond `limit`. **min\_trade\_count** `int` (default: 0) Filter out wallets with fewer than N fills in the window. Useful to drop sample-too-small noise. **exclude\_toxic** `boolean` (default: false) When `true`, drops wallets where `slippage_cost_rate_pct > 15`. The leader-selection power filter. ## Response shape | Field | Type | Description | | - | - | - | | `period` | string | Echo of the requested period | | `sort_by` | string | Echo of the sort field | | `order` | string | Echo of the sort direction | | `filters` | object | `{min_trade_count, exclude_toxic}` echo | | `total_in_pool` | int | Total wallets in your pool | | `scored` | int | Wallets with a score for this period | | `filtered_in` | int | Wallets that passed the `min_trade_count` + `exclude_toxic` filters | | `pending` | int | Wallets in your pool with no score yet (newly added or queued for next refresh) | | `errored` | int | Wallets whose last refresh attempt failed (typically heavy whales hitting timeout on long windows) | | `offset` | int | Echo | | `limit` | int | Echo | | `last_refresh` | int (unix) \| null | When the last full refresh cycle completed | | `results` | array | Top N matching rows after filters and sort | | `errored_sample` | array | Up to 10 errored wallets with their last-error message — only present when `errored > 0` | | `pending_sample` | array | Up to 10 pending wallet addresses — only present when `pending > 0` | ### Per-result row | Field | Type | Description | | - | - | - | | `local_rank` | int | 1-indexed rank within your pool (after offset) | | `wallet` | string | Lowercased address | | `actual_pnl_usdc` | number | Cashflow PnL over the period | | `backtest_copy_pnl_usdc` | number | Same walk with 2% slippage | | `slippage_amount_usdc` | number | Dollar friction the copier eats | | `slippage_cost_rate_pct` | number \| null | Friction as % of actual PnL (null when \|actual\| \< \$1) | | `toxic_for_copying` | bool | `true` when rate > 15% | | `trade_count` | int | Number of fills in the window | | `partial` | bool | `true` if the underlying walk hit the per-wallet 180s budget | | `computed_at` | int (unix) | When this specific score was last refreshed — surface this in your UI as freshness signal | ## Example: top 3 by actual\_pnl\_usdc desc ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/leaderboard?period=30d&sort_by=actual_pnl_usdc&order=desc&limit=3" ``` Response (`200 OK`): ```json theme={null} { "period": "30d", "sort_by": "actual_pnl_usdc", "order": "desc", "filters": { "min_trade_count": 0, "exclude_toxic": false }, "total_in_pool": 108, "scored": 104, "filtered_in": 104, "pending": 1, "errored": 3, "offset": 0, "limit": 3, "last_refresh": 1777521943, "results": [ { "local_rank": 1, "wallet": "0x492442eab586f242b53bda933fd5de859c8a3782", "actual_pnl_usdc": 22915787.92, "backtest_copy_pnl_usdc": 22129678.06, "slippage_amount_usdc": 786109.86, "slippage_cost_rate_pct": 3.43, "toxic_for_copying": false, "trade_count": 8045, "partial": false, "computed_at": 1777522146 } ] } ``` ## Example: leader screening — best non-toxic, min volume ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/leaderboard?period=30d&sort_by=slippage_cost_rate_pct&order=asc&exclude_toxic=true&min_trade_count=1000&limit=3" ``` Response (`200 OK`): ```json theme={null} { "period": "30d", "sort_by": "slippage_cost_rate_pct", "order": "asc", "filters": { "min_trade_count": 1000, "exclude_toxic": true }, "total_in_pool": 108, "scored": 104, "filtered_in": 50, "pending": 2, "errored": 2, "offset": 0, "limit": 3, "results": [ { "local_rank": 1, "wallet": "0x9c16127eccf031df45461ef1e04b52ea286a09cb", "actual_pnl_usdc": 102171.68, "backtest_copy_pnl_usdc": 101643.41, "slippage_amount_usdc": 528.27, "slippage_cost_rate_pct": 0.52, "toxic_for_copying": false, "trade_count": 9472, "partial": false, "computed_at": 1777521515 } ] } ``` This is the canonical "find good leaders to copy" query: lowest slippage rate, but only among wallets that have actually traded enough (`min_trade_count: 1000`) and aren't already flagged toxic. ## Example: pagination (offset) ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/leaderboard?period=30d&offset=10&limit=3" ``` Response includes results with `local_rank: 11, 12, 13` — i.e. ranks within your pool start at `offset + 1`. The default sort is `backtest_copy_pnl_usdc desc`. ## Errors `400 Invalid period`: ```json theme={null} { "error": "Invalid period. Allowed: 7d, 14d, 30d, 60d, 90d, 180d" } ``` `400 Invalid sort_by`: ```json theme={null} { "error": "Invalid sort_by. Allowed: backtest_copy_pnl_usdc, actual_pnl_usdc, slippage_amount_usdc, slippage_cost_rate_pct, trade_count" } ``` `400 Invalid order`: ```json theme={null} { "error": "Invalid order. Allowed: asc | desc" } ``` Auth/rate-limit errors mirror the rest of the `/v2/copy-pnl/*` family. ## Notes * **Sub-second.** All scores are precomputed and served from cache. Even a 1000-wallet pool with all six periods scored returns in under 100ms. * **`pending` and `errored` aren't included in `results`.** Use `pending_sample` and `errored_sample` to identify which specific wallets need attention. The `errored_sample` includes the upstream error message — typically `timeout_180s` for the heaviest whales on long windows. * **`computed_at` per row.** Use this to render "as of X minutes ago" in your UI. Newly-added wallets (via on-add freshening) typically have a `computed_at` within \~30s of the add. Periodic refresh updates it once per chunk slot. * **`last_refresh` at top level.** When the most recent full refresh cycle completed. Individual wallets may have been refreshed earlier or later within the cycle — use the per-row `computed_at` field for exact freshness. * **Sort ties + nulls.** When two wallets share the exact sort\_by value, secondary order is undefined. Wallets with `null` `slippage_cost_rate_pct` always sort last when sorting on that field. # BYOB — List Wallets Source: https://docs.polynode.dev/api-reference/backtesting/byob-list-wallets GET /v2/copy-pnl/wallets Return every wallet in your BYOB tracked-pool, sorted lexicographically. ```http theme={null} GET https://api.polynode.dev/v2/copy-pnl/wallets ``` Returns every wallet currently in your private BYOB pool. Useful for showing your tracked-set in a UI, exporting, or auditing what's queued for the leaderboard. ## Response fields | Field | Type | Description | | - | - | - | | `wallets` | `string[]` | Every wallet in your pool, lowercased, sorted lexicographically (stable order) | | `count` | int | Length of the `wallets` array | | `max` | int | Hard cap on pool size per API key (1000) | ## Example Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/wallets" ``` Response (`200 OK`): ```json theme={null} { "wallets": [ "0x000d257d2dc7616feaef4ae0f14600fdf50a758e", "0x01c78f8873c0c86d6b6b92ff627e3802237ee995", "0x034475def048324ad32d87c5fd90e99f0f7b2538", "0x090a9efe46c0e42e4fd598cd81be011ad72f27e7", "0x0979bad57d7a1403db89cbcd9c52bf43f2138d9b" ], "count": 108, "max": 1000 } ``` ## Notes * **Sorted output.** Wallets are returned in lexicographic order, not in the order you added them. The order is stable — useful for paginating through your own pool client-side without surprises. * **No pagination on this endpoint.** The full list returns in one response. With `max: 1000` and \~42 bytes per wallet address, the largest possible payload is well under 50 KB. * **Pool isolation.** Only wallets added by THIS API key are returned. No way to see other customers' pools. * **Includes wallets that haven't been scored yet.** A wallet you just added via `POST /v2/copy-pnl/wallets` shows here immediately, even if its `computed_at` won't appear in the leaderboard for \~30 seconds while on-add freshening runs. # BYOB — Remove Wallets Source: https://docs.polynode.dev/api-reference/backtesting/byob-remove-wallets DELETE /v2/copy-pnl/wallets Remove wallets from your BYOB tracked-pool. Removal is idempotent — re-removing a wallet that's not in the pool returns 0 with no error. ```http theme={null} DELETE https://api.polynode.dev/v2/copy-pnl/wallets ``` Remove one or more wallets from your private BYOB pool. Wallets not in the pool (or already removed) are silently skipped — `removed` reflects only how many wallets were actually present. ## Request body | Field | Type | Required | Description | | - | - | - | - | | `addresses` | `string[]` | yes | Array of `0x…` wallet addresses to remove. Wallets not in your pool are no-ops. | ## Response fields | Field | Type | Description | | - | - | - | | `removed` | int | Number of wallets actually removed from your pool | | `total` | int | Current size of your pool after removal | | `max` | int | Hard cap on pool size per API key (1000) | ## Example: remove an existing wallet Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ -H "Content-Type: application/json" \ -X DELETE \ -d '{ "addresses": [ "0xfeed0000000000000000000000000000000000aa", "0xfeed0000000000000000000000000000000000ff" ] }' \ "https://api.polynode.dev/v2/copy-pnl/wallets" ``` Response (`200 OK`): ```json theme={null} { "removed": 1, "total": 109, "max": 1000 } ``` Only the first wallet was actually in the pool — the second was never tracked, so it's a silent no-op. The response tells you exactly how many were touched. ## Example: idempotent re-remove Calling delete on a wallet already removed is safe — returns `removed: 0` with no error. Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ -H "Content-Type: application/json" \ -X DELETE \ -d '{"addresses": ["0xfeed0000000000000000000000000000000000aa"]}' \ "https://api.polynode.dev/v2/copy-pnl/wallets" ``` Response (`200 OK`): ```json theme={null} { "removed": 0, "total": 109, "max": 1000 } ``` This makes "set my pool to exactly this list" workflows simple — DELETE old, POST new, both safe to re-run. ## Errors `400 Missing or invalid addresses`: ```json theme={null} { "error": "Body must include \"addresses\" — array of valid 0x… wallet addresses." } ``` Same auth/rate-limit errors as the rest of the `/v2/copy-pnl/*` family. ## Notes * **Removal is per-tenant.** Removing a wallet from your pool does NOT remove it from the global refresh queue if other tenants still track it — the wallet's score keeps refreshing for them. Your private query just stops returning that wallet. * **Cached scores survive briefly.** The wallet's last-computed score stays in our cache (24h TTL). If you re-add the same wallet within 24h, the leaderboard will show its existing score immediately while the on-add freshening kicks off a fresh recompute. * **No bulk-clear endpoint.** To wipe your entire pool, GET your wallet list first, then DELETE all of them in chunks of 1000. # BYOB — Snapshot Source: https://docs.polynode.dev/api-reference/backtesting/byob-snapshot GET /v2/copy-pnl/snapshot Every wallet in your tracked pool with backtest scores across every period in a single response. The headline read for stats-card UIs. ```http theme={null} GET https://api.polynode.dev/v2/copy-pnl/snapshot ``` Returns every wallet currently in your BYOB pool together with their backtest copy-PnL scores across all six time windows (or a chosen subset). One request — no per-period round trips, no client-side stitching. This is the canonical read for any UI that renders stats cards, dashboards, or grids over the entire tracked-wallet set. Pair it with `GET /wallets` if you need to render the empty-state pool too. ## Query parameters **periods** `string` (default: 7d,14d,30d,60d,90d,180d) Comma-separated subset of periods to include. Defaults to all six. Useful when you only render a single time window — e.g. `?periods=30d` returns \~1/6 the payload. ## Response shape | Field | Type | Description | | - | - | - | | `total_in_pool` | int | Wallets currently in your pool | | `scored_any` | int | Wallets with a score for at least one of the requested periods | | `errored_any` | int | Wallets whose last refresh attempt failed (heavy whales hitting timeout on long windows) | | `pending_any` | int | Wallets with no score yet (newly added or queued for the next refresh) | | `periods` | string\[] | Echo of the periods returned (matches input or default order) | | `last_refresh` | int (unix) \| null | When the last full refresh cycle completed | | `wallets` | array | One entry per pooled wallet (see below) | ### Per-wallet entry | Field | Type | Description | | - | - | - | | `wallet` | string | Lowercased address | | `periods` | object | Map keyed by period (`7d`, `14d`, …). Each value is the score blob, or `null` if that specific period is pending | | `error` | object | Only present if this wallet's last refresh errored. `{ error: string, ts: int }` | ### Per-period score blob | Field | Type | Description | | - | - | - | | `actual_pnl_usdc` | number | Cashflow PnL the wallet realized over the period | | `backtest_copy_pnl_usdc` | number | Same trade walk with 2 % slippage on every entry/exit | | `slippage_amount_usdc` | number | Dollar friction the copier eats | | `slippage_cost_rate_pct` | number \| null | Friction as % of `\|actual_pnl\|` (null when `\|actual\| < $1`) | | `toxic_for_copying` | bool | `true` when rate > 15 % | | `trade_count` | int | Number of fills in the window | | `partial` | bool | `true` if the underlying walk hit the per-wallet 180 s budget | | `computed_at` | int (unix) | When this specific score was last refreshed | ## Examples ### Full snapshot (default) ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/snapshot" ``` Response (`200 OK`, abridged): ```json theme={null} { "total_in_pool": 108, "scored_any": 107, "errored_any": 1, "pending_any": 0, "periods": ["7d", "14d", "30d", "60d", "90d", "180d"], "last_refresh": 1777545636, "wallets": [ { "wallet": "0x000d257d2dc7616feaef4ae0f14600fdf50a758e", "periods": { "7d": { "actual_pnl_usdc": 104635.85, "backtest_copy_pnl_usdc": 101463.76, "slippage_amount_usdc": 3172.09, "slippage_cost_rate_pct": 3.03, "toxic_for_copying": false, "trade_count": 90, "partial": false, "computed_at": 1777544903 }, "14d": { "actual_pnl_usdc": -123675.90, "backtest_copy_pnl_usdc": -134838.05, "slippage_amount_usdc": 11162.15, "slippage_cost_rate_pct": 9.03, "toxic_for_copying": false, "trade_count": 458, "partial": false, "computed_at": 1777544903 }, "30d": { "actual_pnl_usdc": 317864.92, "backtest_copy_pnl_usdc": 266790.44, "slippage_amount_usdc": 51074.48, "slippage_cost_rate_pct": 16.07, "toxic_for_copying": true, "trade_count": 2253, "partial": false, "computed_at": 1777544903 }, "60d": { "actual_pnl_usdc": -66101.80, "backtest_copy_pnl_usdc": -181792.53, "slippage_amount_usdc": 115690.73, "slippage_cost_rate_pct": 175.02, "toxic_for_copying": true, "trade_count": 5916, "partial": false, "computed_at": 1777544903 }, "90d": { "actual_pnl_usdc": 289034.81, "backtest_copy_pnl_usdc": 122089.67, "slippage_amount_usdc": 166945.14, "slippage_cost_rate_pct": 57.76, "toxic_for_copying": true, "trade_count": 8761, "partial": false, "computed_at": 1777544903 }, "180d": { "actual_pnl_usdc": 665955.87, "backtest_copy_pnl_usdc": 311352.42, "slippage_amount_usdc": 354603.45, "slippage_cost_rate_pct": 53.25, "toxic_for_copying": true, "trade_count": 18545, "partial": false, "computed_at": 1777544903 } } } ] } ``` ### Subset of periods ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/snapshot?periods=7d,30d" ``` Returns the same shape but with only the requested periods inside each `wallets[].periods` object. Use this when your UI only renders a single window — payload drops proportionally. ## Performance | Pool size | Periods | Payload | Latency (warm) | | - | - | - | - | | 100 wallets | all 6 | \~150 KB | \~70 ms | | 100 wallets | 1 | \~30 KB | under 30 ms | | 1000 wallets | all 6 | \~1.5 MB | \~500 ms | | 1000 wallets | 1 | \~250 KB | \~100 ms | All reads come from the precomputed score cache. ## Notes * **`scored_any` vs `scored` on the leaderboard.** A wallet counts as `scored_any` here if it has a score for *at least one* of the requested periods. The leaderboard's `scored` is per-requested-period. * **Per-period `null`.** A wallet may be scored for `30d` but `null` for `180d` (heavy whales often time out on long windows). Read each period's value independently. * **`error` is wallet-global.** A single `error` object per wallet covers the most recent refresh failure across any period. Use it to surface "X wallets retrying" in your UI. * **No pagination.** This endpoint always returns the full pool. Use the leaderboard endpoint with `limit`/`offset` if you need server-side paging — that's the trade-off vs the one-shot snapshot. * **Race-safe with adds.** Wallets you add via `POST /v2/copy-pnl/wallets` show up here immediately, with `null` periods until the on-add freshening finishes (\~30 s). # Deprecated: Backtest Copy PnL Source: https://docs.polynode.dev/api-reference/backtesting/copy-pnl GET /v2/copy-pnl/{wallet} Score a wallet for copy-trading quality. Returns realized PnL, cashflow PnL, simulated copier PnL with 2% slippage friction, and a toxic-for-copying flag. > [!WARNING] > > This V2 on-demand endpoint is deprecated. Use the [V3 Copy PnL single-wallet endpoint](/data/wallets/copy-pnl). V3 supports date windows, optional full-history calculation with explicit fallback, lifetime realized-PnL context, and normal V3 account limits. Its response shape and realized-PnL scope differ from V2; weighted-average position metrics are not reproduced. See the [migration notes](/data/wallets/copy-pnl#migrating-from-v2). ```http theme={null} GET https://api.polynode.dev/v2/copy-pnl/{wallet} ``` ## TL;DR — which PnL field do you actually want? This endpoint returns **two different PnL numbers** that can look very different for the same wallet. Pick the right one for your use case: | Field | What it answers | When to use | | - | - | - | | `total_realized_pnl_usdc` | "Did this wallet **make money** trading?" | **Default for customer-facing UI.** Closest to what other trading platforms call "PnL". Equivalent to summing per-position WAVG-realized PnL across every position the wallet touched. | | `actual_pnl_usdc` | "How much **net cash** moved through this wallet's USDC balance from trading?" | Diagnostic / slippage-analysis. Used for `slippage_*` fields. Inflated for active wallets that hold inventory. | **Both numbers are correct** — they measure different things. See [the worked example below](#understanding-cashflow-pnl-vs-realized-pnl) for the math. ## Path parameters **wallet** `string` *required* The Polymarket wallet address (Safe proxy or EOA, normalized to lowercase). ## Query parameters **period** `string` (default: 30d) Convenience window preset. One of: `7d`, `14d`, `30d`, `60d`, `90d`, `180d`. Anchored to "now". If you pass `period`, you don't need `from`. **from** `string | number` Start of the window. Accepts `YYYY-MM-DD` (UTC midnight) or unix seconds. Overrides `period` if both are passed. **to** `string | number` End of the window. Same format as `from`. Defaults to current time when omitted. **include\_trades** `boolean` (default: false) When `1` or `true`, response includes a `trades` array with one entry per fill (`ts`, `side`, `price`, `shares`, `actual_usd`, `backtest_usd`). Useful for transparency and debugging. ## Response fields | Field | Type | Description | | | | | | | | - | - | - | - | - | - | - | - | - | | `wallet` | string | Echo of the requested wallet (lowercased) | | | | | | | | **`total_realized_pnl_usdc`** | **number** | **Realized PnL: signed sum of per-position WAVG-realized P/L across every position the matcher touched in the window. Counts only profit/loss on positions the wallet actually closed (or partially closed). Recommended primary "PnL" for customer UI.** | | | | | | | | `actual_pnl_usdc` | number | **Cashflow PnL** over the window: `-buys + sells + settlements`. Counts every USDC inflow/outflow from trading. Includes inventory bought but not yet sold (so often very negative for active buyers). Used as input to slippage formula. | | | | | | | | `backtest_copy_pnl_usdc` | number | Same cashflow walk with 2% slippage applied to buys (capped at \$1) and sells. Settlements unchanged. | | | | | | | | `slippage_amount_usdc` | number | `actual_pnl_usdc − backtest_copy_pnl_usdc`. The dollar friction the copier eats. | | | | | | | | `slippage_cost_rate_pct` | number \| null | `slippage / abs(actual_pnl) × 100`. `null` when `abs(actual_pnl) < 1` (denominator unstable). | | | | | | | | `toxic_for_copying` | boolean | `true` when `slippage_cost_rate_pct > 15`. | | | | | | | | `trade_count` | int | Number of fills walked in the window. | | | | | | | | `positions_closed` | int | Count of positions that contributed non-zero realized PnL in the window. | | | | | | | | `avg_entry_prob_weighted` | number \| null | PnL-weighted average entry probability across closed positions. \`Σ(entry\_price × | realized | ) / Σ | realized | `. Null when `Σ | realized | \< \$1\`. | | `avg_hold_seconds_weighted` | number \| null | PnL-weighted average hold duration. Currently always `null` (WAVG matcher doesn't track per-segment timestamps; planned for future). | | | | | | | | `pnl_definition` | string | Always `"cashflow"` for `actual_pnl_usdc`. Reminds callers `actual_pnl_usdc` differs from PM website PnL (which marks open positions). | | | | | | | | `applied_filters` | object | Resolved `from` (unix), `to` (unix), and `window_days` (only set when default 30d window was used). | | | | | | | | `partial` | boolean | `true` if the underlying walk hit the 30s budget and returned incomplete data. | | | | | | | | `sources` | object | Breakdown: `window_trades`, `window_activity`, per-event-type counts, `cashflow_breakdown` (buys/sells/settlements), `fifo_breakdown` (matcher diagnostics including `total_realized_pnl_usdc`). For transparency. | | | | | | | | `trades` | array | Only present when `include_trades=1`. One entry per fill. | | | | | | | ## Understanding cashflow PnL vs realized PnL The most common source of confusion with this endpoint is "why don't `actual_pnl_usdc` and `total_realized_pnl_usdc` agree?" — they're answering different questions. **Worked example.** A wallet's first 30 days: ``` Day | Action | actual_pnl_usdc | total_realized_pnl_usdc -----+-----------------------+-----------------+------------------------- 1 | BUY 100 YES @ $0.40 | -$40.00 | $0.00 5 | SELL 50 YES @ $0.60 | -$10.00 | +$10.00 10 | BUY 100 YES @ $0.50 | -$60.00 | +$10.00 15 | SELL 80 YES @ $0.55 | -$16.00 | +$17.20 30 | (still hold 70) | -$16.00 | +$17.20 ``` **Final state explained:** * `actual_pnl_usdc = -$16` — the wallet paid out \$16 more USDC than it received over the 30 days. * `total_realized_pnl_usdc = +$17.20` — actual trading profit on the 130 shares the wallet closed. * The wallet still HOLDS 70 shares (cost basis \$32.20). Cashflow counts that as money "spent". Realized ignores it. **Reconciliation:** `cashflow_pnl + cost_basis_of_open_positions ≈ realized_pnl`. In this example: `-$16 + $32.20 = $16.20 ≈ $17.20` (small rounding from WAVG cost basis updates). **Which to use:** * For "did the wallet make money trading?" → **`total_realized_pnl_usdc`**. This is what trading platforms typically call "PnL" and what users intuitively expect. * For "how much net cash flowed through this wallet?" → `actual_pnl_usdc`. Useful for liquidity analysis and the slippage formula, but **not** what most people mean by "PnL". * For copy-trading slippage analysis → use `slippage_*` fields (which are derived from cashflow). The slippage formula needs apples-to-apples cashflow comparison; this is why `actual_pnl_usdc` is defined as cashflow. **One-line summary:** realized = closed-trade profit; cashflow = USDC delta in/out of the wallet. They reconcile when the wallet holds zero open inventory. *** ## Example: default 30-day window Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7" ``` Response (`200 OK`): ```json theme={null} { "wallet": "0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7", "actual_pnl_usdc": -5697.9, "backtest_copy_pnl_usdc": -8932.81, "slippage_amount_usdc": 3234.91, "slippage_cost_rate_pct": 56.77, "toxic_for_copying": true, "trade_count": 1726, "avg_entry_prob_weighted": 0.4892, "avg_hold_seconds_weighted": null, "positions_closed": 142, "total_realized_pnl_usdc": -2412.06, "pnl_definition": "cashflow", "applied_filters": { "from": 1774916101, "to": 1777508101, "window_days": 30 }, "partial": false, "sources": { "window_trades": 1726, "window_activity": 51, "activity_breakdown": { "redemption": 51 }, "cashflow_breakdown": { "actual_buy_cost": 85766.5, "actual_sell_rev": 77266.87, "settlement_in": 2801.73, "settlement_out": 0 }, "fifo_breakdown": { "over_sells": 3, "unresolved_activity": 0, "total_abs_pnl_usdc": 4823.18, "total_realized_pnl_usdc": -2412.06 }, "fetch_ms": 1361 } } ``` Reading this response: the wallet's **realized** trading P/L is \*\*-$2,412** (lost ~$2.4K on 142 positions that closed in the window). The **cashflow** says \*\*-$5,697** — the extra $3,285 is the cost basis of positions still open at window-end (inventory the wallet bought but hasn't sold yet). For "did this wallet make money?" the answer is `total_realized_pnl_usdc` — and the answer is no. ## Example: 7-day window via preset Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/0x9977760c6bd6f824cac834d1a36ee99478d63020?period=7d" ``` Response (`200 OK`): ```json theme={null} { "wallet": "0x9977760c6bd6f824cac834d1a36ee99478d63020", "actual_pnl_usdc": 8082.45, "backtest_copy_pnl_usdc": 7077.07, "slippage_amount_usdc": 1005.38, "slippage_cost_rate_pct": 12.44, "toxic_for_copying": false, "trade_count": 1753, "avg_entry_prob_weighted": 0.5210, "avg_hold_seconds_weighted": null, "positions_closed": 87, "total_realized_pnl_usdc": 6428.91, "pnl_definition": "cashflow", "applied_filters": { "from": 1776903319, "to": 1777508119, "window_days": null }, "partial": false, "sources": { "window_trades": 1753, "window_activity": 144, "activity_breakdown": { "redemption": 144 }, "cashflow_breakdown": { "actual_buy_cost": 339438.1, "actual_sell_rev": 596.28, "settlement_in": 346924.27, "settlement_out": 0 }, "fifo_breakdown": { "over_sells": 0, "unresolved_activity": 0, "total_abs_pnl_usdc": 12857.82, "total_realized_pnl_usdc": 6428.91 }, "fetch_ms": 632 } } ``` ## Example: explicit date range Request — score the window from April 15 to April 25 inclusive: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/0x9977760c6bd6f824cac834d1a36ee99478d63020?from=2026-04-15&to=2026-04-25" ``` Response (`200 OK`): ```json theme={null} { "wallet": "0x9977760c6bd6f824cac834d1a36ee99478d63020", "actual_pnl_usdc": -70450.73, "backtest_copy_pnl_usdc": -74413.34, "slippage_amount_usdc": 3962.61, "slippage_cost_rate_pct": 5.62, "toxic_for_copying": false, "trade_count": 3787, "pnl_definition": "cashflow", "applied_filters": { "from": 1776211200, "to": 1777075200, "window_days": null }, "partial": false, "sources": { "...": "..." } } ``` ## Example: per-fill drill-down Request: ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7?period=7d&include_trades=1" ``` Response (`200 OK`, truncated): ```json theme={null} { "wallet": "0x0c73d8abc3cd918bc62d0204e33ee05c3f5a68e7", "actual_pnl_usdc": -5027.89, "backtest_copy_pnl_usdc": -6783.42, "slippage_amount_usdc": 1755.53, "slippage_cost_rate_pct": 34.92, "toxic_for_copying": true, "trade_count": 838, "pnl_definition": "cashflow", "trades": [ { "ts": 1777232322, "side": "BUY", "price": 0.7916, "shares": 252.66, "actual_usd": 200, "backtest_usd": 204 }, { "ts": 1777232322, "side": "SELL", "price": 0.21, "shares": 48, "actual_usd": 10.08, "backtest_usd": 9.88 } ] } ``` ## Errors `400 Invalid period`: ```json theme={null} { "error": "Invalid period. Allowed: 7d, 14d, 30d, 60d, 90d, 180d" } ``` `401 No API key`: ```json theme={null} { "error": "API key required. Pass via ?key= or x-api-key header." } ``` `403 Free tier`: ```json theme={null} { "error": "V2 endpoints require a paid plan. See polynode.dev/pricing for details." } ``` `429 Rate limited`: ```json theme={null} { "error": "copy-pnl rate limited (1 req per 5s per key).", "retryAfterMs": 4231 } ``` The `Retry-After` header (in seconds, rounded up) is also set on 429 responses. The rate limit is shared across all `/v2/copy-pnl/*` calls per API key — calling the endpoint with different wallets or different params still counts toward the same 1 req per 5 seconds budget. ## Notes * **Wallet address is case-insensitive**. Internally lowercased. * **Time precision**: when `from` is `YYYY-MM-DD`, it resolves to that date at 00:00 UTC. Pass unix seconds for sub-day precision. * **Settlement events** (redemption, merge, split, neg\_risk\_conversion) are processed at face value on both `actual_pnl` and `backtest_copy_pnl`, so they cancel out in `slippage_amount` but remain in the absolute PnL numbers. * **High-volume wallets**: the underlying walk is paginated by time bucket and runs in parallel. Wallets with up to \~1.6M fills in the window have been validated. Beyond that, pass a tighter window or expect `partial: true`. # Backtesting Overview Source: https://docs.polynode.dev/api-reference/backtesting/overview Estimate copying slippage from recent wallet fills with V3 Copy PnL. Use V3 Copy PnL to compare gross trading cash flow with a fixed copying-slippage simulation over recent fills or an explicitly selected date window, with optional full-history calculation. Polynode computes the result from its indexed data. | Endpoint | Purpose | | - | - | | [GET /v3/wallets//copy-pnl](/data/wallets/copy-pnl) | Calculate one wallet. | | [POST /v3/copy-pnl/batch](/data/wallets/copy-pnl-batch) | Calculate up to 100 input wallets, with individual results and errors. | The copier pays 2% more on buys, capped at 1 USDC per share, and receives 2% less on sells. Settlement cash flows receive no simulated slippage. Read the [calculation and coverage details](/data/wallets/copy-pnl#calculation) before interpreting the result: fees and opening inventory value are excluded, and open positions are not marked to market. The default recent cap is 50,000 fills per wallet. Date filters, automatic history expansion with an explicit fallback, and strict full-history mode are available. Each response also includes separately scoped lifetime realized-PnL context with update metadata. V3 uses normal account REST limits without V2's five-second throttle. Results can be cached for 30 seconds, and large uncached batches can return individual deadline errors. ## Legacy V2 The [V2 single-wallet](/api-reference/backtesting/copy-pnl) and [V2 batch](/api-reference/backtesting/batch) on-demand endpoints are deprecated. Follow the [V3 migration notes](/data/wallets/copy-pnl#migrating-from-v2); the response and selection window differ. The older BYOB tracked-wallet pool, snapshot, and leaderboard are separate legacy features. V3 Copy PnL does not replace or refresh them. Their historical references remain available in the Backtesting navigation. # Add Wallets Source: https://docs.polynode.dev/api-reference/byol/add-wallets POST /v2/leaderboard/wallets Add wallets to your tracked leaderboard set. Add one or more Polymarket proxy wallet addresses to your BYOL set. Newly added wallets are tracked immediately in the background and will appear in your leaderboard queries within seconds. ``` POST /v2/leaderboard/wallets ``` ## Authentication Pass your API key via query parameter `?key=`, header `x-api-key`, or `Authorization: Bearer`. ## Request body ```json theme={null} { "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] } ``` **wallets** `string[]` *required* Array of Polymarket proxy wallet addresses. Each must be a valid Ethereum address (`0x` + 40 hex characters). Maximum 500 wallets per request. ## Response ```json theme={null} { "added": 2, "already_tracked": 0, "total": 106, "limit": 5000 } ``` | Field | Type | Description | | - | - | - | | `added` | number | Number of new wallets added | | `already_tracked` | number | Wallets that were already in your set (not counted toward the limit) | | `total` | number | Total wallets now in your set | | `limit` | number | Maximum wallets allowed (5,000) | ## Deduplication If you add wallets that are already in your set, they are silently ignored. This means you can safely re-send your full wallet list without worrying about duplicates. ```json theme={null} // Request: adding 2 wallets that are already tracked { "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] } // Response: nothing was added, total unchanged { "added": 0, "already_tracked": 2, "total": 106, "limit": 5000 } ``` ## Examples ```bash cURL theme={null} curl -X POST "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] }' ``` ```javascript JavaScript theme={null} const response = await fetch( "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ wallets: [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] }) } ); const data = await response.json(); console.log(`Added: ${data.added}, Total: ${data.total}`); ``` ```python Python theme={null} import requests response = requests.post( "https://api.polynode.dev/v2/leaderboard/wallets", params={"key": "YOUR_API_KEY"}, json={ "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] } ) data = response.json() print(f"Added: {data['added']}, Total: {data['total']}") ``` > [!NOTE] > > Newly added wallets are fetched immediately in the background. They typically appear in leaderboard queries within a few seconds. # Get Leaderboard Source: https://docs.polynode.dev/api-reference/byol/get-leaderboard GET /v2/leaderboard/custom Query your custom leaderboard ranked by P&L or volume, filtered by time period and category. Returns your custom leaderboard built from the wallets in your BYOL set. By default, returns all categories in a single response. You can also filter to a specific category. ``` GET /v2/leaderboard/custom ``` ## Authentication Pass your API key via query parameter `?key=`, header `x-api-key`, or `Authorization: Bearer`. ## Parameters **timePeriod** `string` (default: all) Time period for P\&L and volume. Matches Polymarket's leaderboard tabs. * `day` — Today * `week` — Last 7 days * `month` — Last 30 days * `all` — All time **category** `string` (default: all) Market category filter. Use `all` to get every category in one response, or specify one: * `all` — Returns all categories grouped in a `categories` object (default) * `overall` — All markets combined * `politics` `sports` `crypto` `finance` `tech` `weather` `culture` `mentions` **orderBy** `string` (default: pnl) Sort metric. `pnl` (Profit/Loss) or `vol` (Volume). **limit** `number` (default: 50) Maximum entries per category. Max 500. **offset** `number` (default: 0) Pagination offset. ## Response: all categories (default) When `category=all` or omitted, the response groups results by category. Each category is sorted and ranked independently. ```bash theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=all&key=YOUR_API_KEY" ``` ```json theme={null} { "timePeriod": "all", "category": "all", "orderBy": "pnl", "offset": 0, "limit": 50, "lastRefreshed": "2026-04-01T16:04:19.000Z", "categories": { "overall": [ { "localRank": 1, "rank": "1", "proxyWallet": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "userName": "Theo4", "xUsername": "", "verifiedBadge": false, "vol": 43013258.52, "pnl": 22053933.75, "profileImage": "" }, { "localRank": 2, "rank": "8", "proxyWallet": "0x8119010a6e589062aa03583bb3f39ca632d9f887", "userName": "PrincessCaro", "xUsername": "", "verifiedBadge": false, "vol": 23520809.95, "pnl": 6083643.10, "profileImage": "" }, { "localRank": 3, "rank": "5004", "proxyWallet": "0xb595d09ce5bbc4d39e3b3d04e80c402d2c8d5922", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 2467445.01, "pnl": 22617.64, "profileImage": "" } ], "politics": [ { "localRank": 1, "rank": "1", "proxyWallet": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "userName": "Theo4", "xUsername": "", "verifiedBadge": false, "vol": 43012710.75, "pnl": 22053952.53, "profileImage": "" } ], "sports": [ { "localRank": 1, "rank": "1696", "proxyWallet": "0xb595d09ce5bbc4d39e3b3d04e80c402d2c8d5922", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 2466252.61, "pnl": 22677.91, "profileImage": "" } ], "crypto": [...], "finance": [...], "tech": [], "weather": [], "culture": [...], "mentions": [...] } } ``` ## Response: single category When you specify a category like `category=crypto`, the response is a flat leaderboard with a `total` count. ```bash theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=week&category=crypto&key=YOUR_API_KEY" ``` ```json theme={null} { "timePeriod": "week", "category": "crypto", "orderBy": "pnl", "total": 6, "offset": 0, "limit": 50, "lastRefreshed": "2026-04-01T16:04:19.000Z", "leaderboard": [ { "localRank": 1, "rank": "551", "proxyWallet": "0x53decedc72531ef57b2d54b5542c509e233c822f", "userName": "jack118", "xUsername": "", "verifiedBadge": false, "vol": 0, "pnl": 11077.58, "profileImage": "" }, { "localRank": 2, "rank": "34808", "proxyWallet": "0x05d5e0403427a6223f5673b3234ac9405c19db37", "userName": "0x05d5e0403427a6223f5673b3234ac9405c19db37", "xUsername": "", "verifiedBadge": false, "vol": 0, "pnl": 23.24, "profileImage": "" } ] } ``` ## Response: sorted by volume ```bash theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=month&category=overall&orderBy=vol&limit=5&key=YOUR_API_KEY" ``` ```json theme={null} { "timePeriod": "month", "category": "overall", "orderBy": "vol", "total": 18, "offset": 0, "limit": 5, "lastRefreshed": "2026-04-01T16:04:19.000Z", "leaderboard": [ { "localRank": 1, "rank": "1086", "proxyWallet": "0xb595d09ce5bbc4d39e3b3d04e80c402d2c8d5922", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 43406.94, "pnl": 22107.49, "profileImage": "" }, { "localRank": 2, "rank": "129764", "proxyWallet": "0xc0220b02ad4cf50f8d612dbb3aa7783973266494", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 25.75, "pnl": 11.87, "profileImage": "" } ] } ``` ## Response: today's activity ```bash theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=day&category=sports&key=YOUR_API_KEY" ``` ```json theme={null} { "timePeriod": "day", "category": "sports", "orderBy": "pnl", "total": 9, "offset": 0, "limit": 50, "lastRefreshed": "2026-04-01T16:04:19.000Z", "leaderboard": [ { "localRank": 1, "rank": "768", "proxyWallet": "0xb595d09ce5bbc4d39e3b3d04e80c402d2c8d5922", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 43406.94, "pnl": 516.36, "profileImage": "" }, { "localRank": 2, "rank": "96658", "proxyWallet": "0x1116147499ba1da24081a5f09077cdbc4586997c", "userName": "...", "xUsername": "", "verifiedBadge": false, "vol": 0, "pnl": 0.13, "profileImage": "" } ] } ``` ## Top-level response fields | Field | Type | Description | | - | - | - | | `timePeriod` | string | The time period used for this query | | `category` | string | `"all"` or the specific category queried | | `orderBy` | string | Sort metric used (`pnl` or `vol`) | | `total` | number | Total wallets with data for this query (single-category mode only) | | `offset` | number | Pagination offset | | `limit` | number | Maximum entries returned | | `lastRefreshed` | string | ISO timestamp of the last background data refresh | | `categories` | object | Leaderboard entries grouped by category (when `category=all`) | | `leaderboard` | array | Flat leaderboard entries (when a specific category is requested) | ## Leaderboard entry fields | Field | Type | Description | | - | - | - | | `localRank` | number | Rank within your custom leaderboard set | | `rank` | string | Global rank on Polymarket's leaderboard. This is a string matching Polymarket's API format. | | `proxyWallet` | string | Polymarket proxy wallet address | | `userName` | string | Polymarket display name | | `xUsername` | string | Twitter/X username (if set) | | `verifiedBadge` | boolean | Polymarket verified badge | | `vol` | number | Trading volume (USD) for this time period | | `pnl` | number | Profit/Loss (USD) for this time period | | `profileImage` | string | Profile image URL | ## Code examples ### Get everything for the current week ```bash cURL theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=week&key=YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=week&key=YOUR_API_KEY" ); const data = await response.json(); // All 9 categories in one response for (const [category, traders] of Object.entries(data.categories)) { if (traders.length > 0) { console.log(`${category}: ${traders.length} traders`); console.log(` Top trader: ${traders[0].userName} ($${traders[0].pnl.toFixed(2)})`); } } ``` ```python Python theme={null} import requests response = requests.get( "https://api.polynode.dev/v2/leaderboard/custom", params={"timePeriod": "week", "key": "YOUR_API_KEY"} ) data = response.json() for category, traders in data["categories"].items(): if traders: top = traders[0] print(f"{category}: {len(traders)} traders, top: {top['userName']} (${top['pnl']:,.2f})") ``` ### Get a single category ```bash cURL theme={null} curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=month&category=crypto&orderBy=pnl&key=YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=month&category=crypto&orderBy=pnl&key=YOUR_API_KEY" ); const data = await response.json(); // Flat leaderboard array console.log(`${data.total} traders in crypto this month`); for (const trader of data.leaderboard || []) { console.log(`#${trader.localRank} ${trader.userName} — $${trader.pnl.toFixed(2)} P&L (global rank: ${trader.rank})`); } ``` ```python Python theme={null} import requests response = requests.get( "https://api.polynode.dev/v2/leaderboard/custom", params={ "timePeriod": "month", "category": "crypto", "orderBy": "pnl", "key": "YOUR_API_KEY" } ) data = response.json() print(f"{data['total']} traders in crypto this month") for trader in data["leaderboard"]: print(f"#{trader['localRank']} {trader['userName']} — ${trader['pnl']:,.2f} (global #{trader['rank']})") ``` ### Sort by volume, paginated ```bash cURL theme={null} # Top 10 by volume, all time curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=all&category=overall&orderBy=vol&limit=10&key=YOUR_API_KEY" # Next 10 curl "https://api.polynode.dev/v2/leaderboard/custom?timePeriod=all&category=overall&orderBy=vol&limit=10&offset=10&key=YOUR_API_KEY" ``` ```javascript JavaScript theme={null} // Paginate through all results let offset = 0; const limit = 50; while (true) { const response = await fetch( `https://api.polynode.dev/v2/leaderboard/custom?timePeriod=all&category=overall&orderBy=vol&limit=${limit}&offset=${offset}&key=YOUR_API_KEY` ); const data = await response.json(); for (const trader of data.leaderboard || []) { console.log(`#${trader.localRank} ${trader.userName} — $${trader.vol.toFixed(2)} volume`); } if (!data.leaderboard || data.leaderboard.length < limit) break; offset += limit; // Respect rate limit: 1 request per 5 seconds await new Promise(resolve => setTimeout(resolve, 5000)); } ``` ## Rate limiting This endpoint is rate limited to **1 request per 5 seconds** per API key. If you exceed this, you'll get a 429 response: ```json theme={null} { "error": "Leaderboard is rate limited to 1 request per 5 seconds.", "retryAfterMs": 3784 } ``` | Field | Type | Description | | - | - | - | | `error` | string | Error message | | `retryAfterMs` | number | Milliseconds to wait before retrying | The response also includes a `Retry-After` header (in seconds). > [!NOTE] > > Data refreshes every \~30 minutes in the background. Repeat requests within 60 seconds are served from an in-memory cache for maximum speed. # List Wallets Source: https://docs.polynode.dev/api-reference/byol/list-wallets GET /v2/leaderboard/wallets List all wallets currently in your tracked leaderboard set. Returns every wallet address in your BYOL set along with your wallet limit. ``` GET /v2/leaderboard/wallets ``` ## Authentication Pass your API key via query parameter `?key=`, header `x-api-key`, or `Authorization: Bearer`. ## Response ```json theme={null} { "wallets": [ "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "0xb595d09ce5bbc4d39e3b3d04e80c402d2c8d5922", "0x53decedc72531ef57b2d54b5542c509e233c822f", "0xd252bce657d99d4e943708a8d7a2b3222da2775b", "0x05d5e0403427a6223f5673b3234ac9405c19db37" ], "count": 104, "limit": 5000 } ``` | Field | Type | Description | | - | - | - | | `wallets` | string\[] | All wallet addresses in your set | | `count` | number | Total number of wallets | | `limit` | number | Maximum wallets allowed (5,000) | ## Examples ```bash cURL theme={null} curl "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY" ``` ```javascript JavaScript theme={null} const response = await fetch( "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY" ); const data = await response.json(); console.log(`Tracking ${data.count} wallets (limit: ${data.limit})`); ``` ```python Python theme={null} import requests response = requests.get( "https://api.polynode.dev/v2/leaderboard/wallets", params={"key": "YOUR_API_KEY"} ) data = response.json() print(f"Tracking {data['count']} wallets (limit: {data['limit']})") ``` # BYOL Overview Source: https://docs.polynode.dev/api-reference/byol/overview Bring Your Own Leaderboard. Track any set of Polymarket wallets and get a private, ranked leaderboard with P&L across all time periods and categories. BYOL (Bring Your Own Leaderboard) lets you build a custom Polymarket leaderboard from any set of wallets you choose. Add the wallets you care about, and polynode continuously tracks their P\&L, volume, and global rank across every time period and category that Polymarket tracks. ## How it works 1. **Add wallets** you want to track via the API 2. polynode tracks every wallet across all time periods and categories in the background (\~30 min refresh cycle) 3. **Query your leaderboard** by time period, category, or get everything at once 4. Each API key has its own private wallet set. Your wallets and leaderboard are completely isolated from other users. ## What you get back Every wallet in your set is tracked across: **4 time periods** matching Polymarket's leaderboard: * `day` (Today) * `week` (Weekly) * `month` (Monthly) * `all` (All time) **9 categories:** * `overall` `politics` `sports` `crypto` `finance` `tech` `weather` `culture` `mentions` **2 sort options:** * `pnl` (Profit/Loss) * `vol` (Volume) The response fields match Polymarket's leaderboard format exactly: `rank`, `proxyWallet`, `userName`, `xUsername`, `verifiedBadge`, `vol`, `pnl`, `profileImage`. We add `localRank` to show where each wallet ranks within your custom set. ## Limits * **5,000 wallets max** per API key * Free tier keys cannot access BYOL. Any paid tier has full access. * Adding a wallet that's already in your set doesn't count toward the limit ## Endpoints | Method | Endpoint | Description | | - | - | - | | `POST` | `/v2/leaderboard/wallets` | Add wallets to your tracked set | | `DELETE` | `/v2/leaderboard/wallets` | Remove wallets from your set | | `GET` | `/v2/leaderboard/wallets` | List all wallets in your set | | `GET` | `/v2/leaderboard/custom` | Query your leaderboard | # Remove Wallets Source: https://docs.polynode.dev/api-reference/byol/remove-wallets DELETE /v2/leaderboard/wallets Remove wallets from your tracked leaderboard set. Remove one or more wallets from your BYOL set. They will no longer appear in your leaderboard queries. ``` DELETE /v2/leaderboard/wallets ``` ## Authentication Pass your API key via query parameter `?key=`, header `x-api-key`, or `Authorization: Bearer`. ## Request body ```json theme={null} { "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] } ``` **wallets** `string[]` *required* Array of wallet addresses to remove from your set. ## Response ```json theme={null} { "removed": 2, "total": 104 } ``` | Field | Type | Description | | - | - | - | | `removed` | number | Number of wallets removed | | `total` | number | Remaining wallets in your set | ## Examples ```bash cURL theme={null} curl -X DELETE "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] }' ``` ```javascript JavaScript theme={null} const response = await fetch( "https://api.polynode.dev/v2/leaderboard/wallets?key=YOUR_API_KEY", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ wallets: [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] }) } ); const data = await response.json(); console.log(`Removed: ${data.removed}, Remaining: ${data.total}`); ``` ```python Python theme={null} import requests response = requests.delete( "https://api.polynode.dev/v2/leaderboard/wallets", params={"key": "YOUR_API_KEY"}, json={ "wallets": [ "0x94f199fb7789f1aef7fff6b758d6b375100f4c7a", "0xe9ad918c7678cd38b12603a762e638a5d1ee7091" ] } ) data = response.json() print(f"Removed: {data['removed']}, Remaining: {data['total']}") ``` > [!NOTE] > > Removing a wallet from your set does not affect other API keys that may be tracking the same wallet. # Active 5-Minute Markets Source: https://docs.polynode.dev/api-reference/crypto/active GET /v1/crypto/active Currently active 5-minute up-or-down markets for all 7 coins. Returns the currently active 5-minute up-or-down markets for all 7 supported coins. These markets rotate every 5 minutes. Each response includes token IDs, outcomes, and current odds for immediate trading. ```json theme={null} { "markets": [ { "id": "312746", "slug": "btc-updown-5m-1774674300", "title": "Bitcoin Up or Down - March 28, 1:05AM-1:10AM ET", "active": true, "closed": false, "startDate": "2026-03-27T05:16:04.211285Z", "endDate": "2026-03-28T05:10:00Z", "markets": [ { "question": "Bitcoin Up or Down - March 28, 1:05AM-1:10AM ET", "conditionId": "0x...", "outcomes": ["Up", "Down"], "outcomePrices": [0.465, 0.535], "tokenId": "12345...", "active": true, "closed": false } ] } ], "count": 7, "windowStart": 1774674300 } ``` > [!NOTE] > > Cached for 30 seconds. The `windowStart` field is the epoch timestamp of the current 5-minute window. Use this as the `window` parameter for the [Price to Beat](/api-reference/crypto/price) endpoint. # Oracle Candles Source: https://docs.polynode.dev/api-reference/crypto/candles GET /v1/crypto/candles 5-minute OHLC candles from PolyNode's live Chainlink tick archive. Returns 5-minute OHLC candles from PolyNode's live Chainlink tick archive for a given crypto asset. Approximately 30 candles (\~2.5 hours of history) are returned. These are the same oracle prices used to resolve Polymarket's short-form crypto markets. ```json theme={null} { "candles": [ { "time": 1774665300, "open": 65954.03, "high": 65992.01, "low": 65947.14, "close": 65949.69 }, { "time": 1774665600, "open": 65949.69, "high": 65987.20, "low": 65949.69, "close": 65987.20 } ] } ``` > [!NOTE] > > Cached for about 5 seconds. The `symbol` parameter accepts bare asset symbols like `BTC` and feed names like `BTC/USD`. Each candle's `time` field is a Unix epoch timestamp marking the start of that 5-minute window. # Crypto Markets Source: https://docs.polynode.dev/api-reference/crypto/markets GET /v1/crypto/markets All crypto prediction markets with liquidity, volume, and open interest. Returns all currently active crypto prediction markets on Polymarket, including monthly, weekly, and daily markets across 7 supported assets (BTC, ETH, SOL, BNB, XRP, DOGE, HYPE). ```json theme={null} { "events": [ { "id": "238474", "slug": "what-price-will-bitcoin-hit-in-march-2026", "title": "What price will Bitcoin hit in March?", "startDate": "2026-03-01T05:20:27.791222Z", "endDate": "2026-04-01T04:00:00Z", "active": true, "volume": 88886711.74, "volume24hr": 5733750.73, "liquidity": 6074250.39, "openInterest": 12827944.10, "seriesSlug": "bitcoin-hit-price-monthly", "markets": [ { "id": "1629442", "question": "$100,000?", "conditionId": "0x...", "outcomes": ["Yes", "No"], "outcomePrices": [0.045, 0.955], "volume": 24084104.74, "liquidity": 2028310.67, "active": true, "closed": false, "groupItemTitle": "↑ 150,000" } ] } ] } ``` > [!NOTE] > > Cached for 3 minutes. # Price to Beat Source: https://docs.polynode.dev/api-reference/crypto/price GET /v1/crypto/price Open and close price for a specific crypto market window. Returns the opening and current closing price for a crypto market window. This is the "price to beat" for short-form markets. The `openPrice` is the Chainlink oracle price at market open. The `closePrice` updates in real time until the window completes (`completed: true`). ```json theme={null} { "openPrice": 66285.01, "closePrice": 66238.61, "timestamp": 1774674466843, "completed": false, "incomplete": true, "cached": false } ``` > [!NOTE] > > Real-time. No cache. `closePrice` is locked in the instant a window ends — no waiting. The `window` parameter is a Unix epoch timestamp. Get window timestamps from the `/v1/crypto/active` endpoint. # Crypto Series Source: https://docs.polynode.dev/api-reference/crypto/series GET /v1/crypto/series Recurring crypto market series. Returns all recurring crypto market series across different intervals (5m, 15m, 1h, 4h, daily, weekly, monthly). Each series generates new markets on its recurrence schedule. ```json theme={null} { "series": [ { "id": "10422", "slug": "xrp-up-or-down-15m", "title": "XRP Up or Down 15m", "recurrence": "15m", "active": true, "eventCount": null }, { "id": "10065", "slug": "ethereum-neg-risk-weekly", "title": "Ethereum Neg Risk Weekly", "recurrence": "weekly", "active": true, "eventCount": null } ], "count": 7 } ``` > [!NOTE] > > Cached for 5 minutes. # Historical Price Ticks Source: https://docs.polynode.dev/api-reference/crypto/ticks GET /v1/crypto/ticks Historical 1-second crypto price ticks for short-form chart backfill. Returns historical 1-second price ticks for the same crypto feeds available on the `price_feed` WebSocket stream. Use this endpoint to backfill a 5-minute, 15-minute, or 1-hour chart when a user opens it part way through the market window, then keep the chart current with live `price_feed` events. **symbol** `string` *required* Asset symbol. One of `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, `HYPE`. **from** `number` *required* Start of the range as a Unix timestamp in milliseconds. **to** `number` *required* End of the range as a Unix timestamp in milliseconds. **limit** `number` (default: 10000) Maximum ticks to return. Max 100000. ```bash theme={null} curl -H "x-api-key: YOUR_API_KEY" \ "https://api.polynode.dev/v1/crypto/ticks?symbol=BTC&from=1780458961000&to=1780459082000&limit=5" ``` ```json theme={null} { "symbol": "BTC", "feed": "BTC/USD", "from": 1780458961000, "to": 1780459082000, "limit": 5, "count": 5, "truncated": true, "ticks": [ { "id": "1780458962000-0", "type": "price_feed", "feed": "BTC/USD", "timestamp": 1780458962, "timestamp_ms": 1780458962000, "data": { "feed": "BTC/USD", "price": 65869.02124677686, "bid": 65865.65936734258, "ask": 65870.4120597498, "timestamp": 1780458962 } } ] } ``` ## Range limits Each request can cover up to 24 hours. If `truncated` is `true`, the response hit the requested `limit`; request a narrower time range or increase `limit` to retrieve more ticks. Historical availability starts when tick collection was enabled. Ranges before available history return an empty `ticks` array. ## Chart backfill For a 15-minute market, request ticks from the market window start to now, render those points, then append live WebSocket `price_feed` events as they arrive. ```javascript theme={null} const apiKey = "YOUR_API_KEY"; const symbol = "BTC"; const now = Date.now(); const windowStart = Math.floor(now / 1000 / 900) * 900 * 1000; const url = new URL("https://api.polynode.dev/v1/crypto/ticks"); url.searchParams.set("symbol", symbol); url.searchParams.set("from", String(windowStart)); url.searchParams.set("to", String(now)); url.searchParams.set("limit", "2000"); const response = await fetch(url, { headers: { "x-api-key": apiKey } }); const history = await response.json(); const points = history.ticks.map((tick) => ({ t: tick.timestamp_ms, price: tick.data.price })); console.log(points.at(0), points.at(-1)); ``` ## Pair with the live stream The response uses the same Chainlink price event shape as the WebSocket `price_feed` stream. Historical responses also include an `id` and `timestamp_ms` for replay and deduplication. ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=YOUR_API_KEY"); ws.addEventListener("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "chainlink", filters: { feeds: ["BTC/USD"] } })); }); ws.addEventListener("message", (event) => { const msg = JSON.parse(event.data); if (msg.type !== "price_feed") return; const point = { t: msg.data.timestamp * 1000, price: msg.data.price }; console.log(point); }); ``` # Candles (Trade-Indexed OHLCV) Source: https://docs.polynode.dev/api-reference/onchain/candles GET /v2/onchain/candles/{token_id} Server-built OHLCV candles from real onchain trades. Anchor-based pagination with buy/sell volume split, VWAP, and trade counts. Resolutions from 1m to 1d. Build OHLCV candles directly from settled CLOB fills. Each candle includes open, high, low, close, total volume in USD and shares, buy and sell volume split, trade count, and VWAP. Backed by the same trade source as `/v2/onchain/trades`, so candles and trades stay in lockstep. Pagination is **anchor-based** rather than range-based. Each request returns up to 1000 trades worth of candles, anchored at a timestamp, block, or transaction hash. Walk older history by passing the cursor from the previous response. This is the same model used by major exchange APIs (Binance, Kraken, Coinbase) and avoids open-ended range queries timing out on hot markets. The response includes a `window.duration_seconds` field so callers immediately see how dense the market is — a hot market may pack 500 trades into 10 seconds, while a sleepy market may span weeks. ## Which candles endpoint should I use? PolyNode exposes three candle-shaped endpoints. They cover different data sources and are not interchangeable. | Endpoint | Source | Best for | | - | - | - | | `GET /v2/onchain/candles/{token_id}` | Real settled CLOB fills on Polygon | Charting any Polymarket outcome token with full history, VWAP, and buy/sell split. **This is the endpoint you want for a price chart.** | | `GET /v1/candles/{token_id}` | Live rolling in-memory buffer | Short, live tail of recent activity. No historical depth, no pagination. Useful as a lightweight live poll but not for charts. | | `GET /v1/crypto/candles` | Chainlink oracle feed | 5-minute OHLC for crypto assets (BTC, ETH, SOL…). These are the same prices that resolve Polymarket's short-form crypto markets — not CLOB trade data. | If you're building a chart for a Polymarket market, use `/v2/onchain/candles`. ## Build a chart in 2 calls The fastest way to go from "I have an API key" to "I have candles on screen." Every response below is a real capture — you can paste the curls and get back the same shape. ### 1. Find a market and grab the token you want to chart `/v2/movers` returns the biggest daily movers with the full outcomes array already enriched — one REST call gives you the `token_id` for both the Yes and No outcome without any extra lookups. ```bash theme={null} curl "https://api.polynode.dev/v2/movers?limit=3" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "markets": [ { "id": "1707841", "slug": "israel-x-hezbollah-ceasefire-by-april-30-2026-989-656", "question": "Israel x Hezbollah ceasefire by April 30, 2026?", "condition_id": "0xc7140ddb5ae5dc94d4553fb05d4600816f33ff024844cebe8326f4c41c4a1a47", "outcomes": [ { "name": "Yes", "token_id": "71076253073516159380702286801576688253388973161726933428722204989810362065275", "price": 0.674 }, { "name": "No", "token_id": "38902668316823899581329108924389881286009857048696806385615295625967267371713", "price": 0.326 } ], "one_day_price_change": 0.3815 } ] } ``` `outcomes[0].token_id` is the Yes side. That's the identifier you pass to the candles endpoint. `/v2/trending` has the exact same shape if you'd rather chart what's popular than what's moving. ### 2. Pull candles for that token ```bash theme={null} TOKEN=71076253073516159380702286801576688253388973161726933428722204989810362065275 curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN?resolution=5m&limit=500" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "token_id": "71076253073516159380702286801576688253388973161726933428722204989810362065275", "resolution": "5m", "window": { "start_ts": 1776274178, "end_ts": 1776278436, "trade_count": 500, "duration_seconds": 4258 }, "count": 16, "candles": [ { "time": 1776273900000, "open": 0.82, "high": 0.8221, "low": 0.82, "close": 0.82, "volume": 1842.3, "trades": 16, "vwap": 0.8205 }, { "time": 1776274200000, "open": 0.831, "high": 0.8349, "low": 0.765, "close": 0.781, "volume": 6194.1, "trades": 49, "vwap": 0.7912 }, { "time": 1776276600000, "open": 0.741, "high": 0.766, "low": 0.62, "close": 0.62, "volume": 9338.7, "trades": 68, "vwap": 0.6823 } ], "pagination": { "older_end_ts": 1776274177, "newer_start_ts": 1776278437 }, "question": "Israel x Hezbollah ceasefire by April 30, 2026?", "outcome": "Yes", "condition_id": "0xc7140ddb5ae5dc94d4553fb05d4600816f33ff024844cebe8326f4c41c4a1a47", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/israel+lebanon+dove+flags.png" } ``` The `window.duration_seconds` tells you the 500 trades covered \~71 minutes of wall time — a moderately active market. The header fields (`question`, `outcome`, `image`, `condition_id`) are included so a chart header can render in the same round trip. That's the full loop: discover → chart, two REST calls, everything you need. ### 3. Walk older history Each response returns `pagination.older_end_ts`. Pass it back as `anchor_ts` on the next call to fetch the window immediately before it. ```bash theme={null} # Older page, using the anchor from the previous response curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN?resolution=5m&limit=500&anchor_ts=1776274177" \ -H "x-api-key: YOUR_KEY" ``` Real response header from this exact call: ```json theme={null} { "window": { "start_ts": 1776267442, "end_ts": 1776274174, "trade_count": 500, "duration_seconds": 6732 }, "count": 23, "pagination": { "older_end_ts": 1776267441, "newer_start_ts": 1776274175 } } ``` Same token, 500 older trades, 23 candles over \~112 minutes. Keep walking by chaining `older_end_ts → anchor_ts` until you have the depth you need. ## Request ``` GET /v2/onchain/candles/{token_id} ``` You can also pass the market identifier as a query parameter instead of a path parameter: ``` GET /v2/onchain/candles?token_id=... ``` ### Path parameters | Parameter | Type | Required | Description | | - | - | - | - | | `token_id` | string | One of these | Outcome token ID. Can also be passed as `?token_id=` query param. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `token_id` | string | — | Outcome token ID (alternative to path param) | | `condition_id` | string | — | Condition ID. Errors if the condition has multiple outcomes — pass `token_id` to disambiguate. | | `market_slug` | string | — | Market slug. Errors if the slug has multiple outcomes — pass `token_id` to disambiguate. | | `resolution` | string | `1h` | Bucket size: `1m`, `5m`, `15m`, `1h`, `4h`, `1d` | | `limit` | integer | `500` | Trades per page. Clamped to `[100, 1000]`. The candles are built from this trade window. | | `direction` | string | `before` | `before` returns the `limit` trades ending at the anchor (newest-first walk). `after` returns the `limit` trades starting at the anchor (oldest-first walk). | | `anchor_ts` | integer | now | Unix timestamp anchor | | `anchor_block` | integer | — | Polygon block number anchor. Resolved to its block timestamp. | | `anchor_tx` | string | — | Polygon transaction hash anchor. Resolved to its block timestamp. | | `gap_fill` | boolean | `false` | When `true`, empty buckets between active candles are filled with flat carry-forward candles (`O=H=L=C=prev_close`, `volume=0`). | Exactly one of `token_id`, `condition_id`, or `market_slug` is required. If multiple anchor params are passed, precedence is `anchor_tx > anchor_block > anchor_ts`. ## Response ```json theme={null} { "token_id": "85713379202339219190689591569895900631137520291992037720582155738835687752247", "resolution": "1m", "window": { "start_ts": 1776276218, "end_ts": 1776276228, "trade_count": 500, "duration_seconds": 10 }, "count": 1, "candles": [ { "time": 1776276180000, "open": 0.78, "high": 0.93, "low": 0.77, "close": 0.9, "volume": 7941.87, "volume_shares": 9094.21, "volume_buy": 1569.20, "volume_sell": 6372.67, "trades": 500, "vwap": 0.8733 } ], "pagination": { "older_end_ts": 1776276217, "newer_start_ts": 1776276229 }, "question": "Bitcoin Up or Down - April 15, 2:00PM-2:05PM ET", "slug": "btc-updown-5m-1776276000", "outcome": "Up", "condition_id": "0x...", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png" } ``` ### Candle fields | Field | Type | Description | | - | - | - | | `time` | number | Bucket start time in milliseconds since epoch (TradingView convention) | | `open` | number | First trade price in the bucket | | `high` | number | Highest trade price in the bucket | | `low` | number | Lowest trade price in the bucket | | `close` | number | Last trade price in the bucket | | `volume` | number | Total volume in USD | | `volume_shares` | number | Total volume in outcome shares | | `volume_buy` | number | USD volume where the taker was buying the outcome token (aggressor buys) | | `volume_sell` | number | USD volume where the taker was selling the outcome token (aggressor sells) | | `trades` | number | Count of fills in the bucket | | `vwap` | number | Volume-weighted average price for the bucket | ### Window fields | Field | Type | Description | | - | - | - | | `window.start_ts` | number | Unix timestamp of the oldest trade in the window | | `window.end_ts` | number | Unix timestamp of the newest trade in the window | | `window.trade_count` | number | Number of trades that built these candles | | `window.duration_seconds` | number | Wall-clock span of the window. Use this to gauge market density. | ### Pagination fields | Field | Type | Description | | - | - | - | | `pagination.older_end_ts` | number | Pass as `anchor_ts` with `direction=before` to fetch the next older window | | `pagination.newer_start_ts` | number | Pass as `anchor_ts` with `direction=after` to fetch the next newer window | ### Market enrichment fields `question`, `slug`, `outcome`, `condition_id`, and `image` are pulled from our market index. Returned alongside the candles so a chart can render header metadata in one round trip. ## Examples ### Default — last 500 trades, 1h buckets ```bash cURL theme={null} curl "https://api.polynode.dev/v2/onchain/candles/85713379202339219190689591569895900631137520291992037720582155738835687752247?resolution=1h" \ -H "x-api-key: YOUR_KEY" ``` ```javascript Node.js theme={null} const tokenId = "85713379202339219190689591569895900631137520291992037720582155738835687752247"; const resp = await fetch( `https://api.polynode.dev/v2/onchain/candles/${tokenId}?resolution=1h`, { headers: { "x-api-key": "YOUR_KEY" } } ); const data = await resp.json(); console.log(`${data.window.trade_count} trades over ${data.window.duration_seconds}s`); data.candles.forEach(c => console.log(c.time, c.open, c.high, c.low, c.close, c.volume)); ``` ```python Python theme={null} import requests token_id = "85713379202339219190689591569895900631137520291992037720582155738835687752247" resp = requests.get( f"https://api.polynode.dev/v2/onchain/candles/{token_id}", params={"resolution": "1h"}, headers={"x-api-key": "YOUR_KEY"}, ) data = resp.json() print(f"{data['window']['trade_count']} trades over {data['window']['duration_seconds']}s") for c in data["candles"]: print(c["time"], c["open"], c["high"], c["low"], c["close"], c["volume"]) ``` ### Walking backwards through history Each response includes `pagination.older_end_ts`. Pass that as `anchor_ts` to fetch the previous window. ```bash theme={null} # First page — most recent 500 trades curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=15m&limit=500" \ -H "x-api-key: YOUR_KEY" # Next page — 500 trades older than the first curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=15m&limit=500&anchor_ts=OLDER_END_TS_FROM_PREVIOUS" \ -H "x-api-key: YOUR_KEY" ``` ### Forward walk from a starting point Use `direction=after` to walk forward from a specific timestamp. ```bash theme={null} # Earliest 500 trades on this market curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=1h&direction=after&anchor_ts=0" \ -H "x-api-key: YOUR_KEY" ``` ### Anchor by block number Useful when you want to align candles to a specific Polygon block — for example to compare against another onchain event. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=5m&anchor_block=70000000" \ -H "x-api-key: YOUR_KEY" ``` ### Anchor by transaction hash Same idea, but resolved from a transaction hash. Useful for "show me what the chart looked like around this trade." ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=1m&anchor_tx=0xfffff7ed9080f46d7975f905e7f9358c436a1b177c6e19e54510c3ba6dcfddc4" \ -H "x-api-key: YOUR_KEY" ``` ### Gap-filled candles By default, buckets with zero trades are simply absent from the response. Set `gap_fill=true` to fill them with flat carry-forward candles for charting libraries that expect a continuous time axis. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=1m&gap_fill=true" \ -H "x-api-key: YOUR_KEY" ``` ## Error responses | Status | Response | Condition | | - | - | - | | 400 | `{"error": "token_id, condition_id, or market_slug required"}` | No market identifier passed | | 400 | `{"error": "Invalid resolution. Use one of: 1m, 5m, 15m, 1h, 4h, 1d"}` | Bad `resolution` value | | 400 | `{"error": "condition_id resolves to multiple outcomes — pass token_id to select one"}` | Multi-outcome `condition_id` | | 400 | `{"error": "market_slug resolves to multiple outcomes — pass token_id to select one"}` | Multi-outcome `market_slug` | | 401 | `{"error": "API key required. Pass via ?key= or x-api-key header."}` | Missing API key | | 403 | `{"error": "V2 endpoints require a paid plan. See polynode.dev/pricing for details."}` | Free tier key | | 429 | `{"error": "Rate limited. N req/s for your tier.", "retryAfterMs": ...}` | Rate limited | ## Notes * Candles are built from real onchain fills, not midpoint snapshots. Sparse markets will show sparse candles. * `volume_buy` and `volume_sell` are taker-side attributions — i.e. the side that lifted/hit the book. Same convention as every major exchange API. * The trade window is fixed-page, not range-bound. To cover a long history, walk pages via `pagination.older_end_ts`. Use `window.duration_seconds` in each response to gauge market density up front. * Block and transaction anchors are resolved via Polygon RPC and cached for 24 hours — repeated queries against the same anchor are free after the first hit. * Responses are cached server-side for 5 minutes per unique anchor, direction, and limit. # Global Open Interest Source: https://docs.polynode.dev/api-reference/onchain/global-oi GET /v2/onchain/oi Total platform-wide open interest from onchain data. Returns the total open interest across the entire Polymarket platform, sourced from onchain data. ## Request ``` GET /v2/onchain/oi ``` No parameters required. ## Response ```json theme={null} { "source": "onchain", "open_interest_usdc": 488484168.103811 } ``` | Field | Type | Description | | - | - | - | | `open_interest_usdc` | number | Total platform open interest in USDC | ## Example ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/oi" \ -H "x-api-key: YOUR_KEY" ``` # Market Open Interest Source: https://docs.polynode.dev/api-reference/onchain/market-oi GET /v2/onchain/markets/{condition_id}/oi Onchain open interest for a specific market. Returns the current open interest for a specific market, sourced from onchain data. Enriched with market metadata. ## Request ``` GET /v2/onchain/markets/{condition_id}/oi ``` | Parameter | Type | Location | Description | | - | - | - | - | | `condition_id` | string | path | Market condition ID (0x-prefixed, 64 hex chars) | ## Response ```json theme={null} { "condition_id": "0x8180fee481707671aa45de84a9c3740ab607f3f2643b456e0380afb02d12cf7d", "source": "onchain", "found": true, "market": "Bitcoin Up or Down - March 28, 10:55AM-11:00AM ET", "slug": "btc-updown-5m-1774709700", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "open_interest_usdc": 393.153937 } ``` | Field | Type | Description | | - | - | - | | `found` | boolean | Whether the market was found onchain | | `market` | string | Market question | | `slug` | string | Market slug | | `image` | string | Market image URL | | `open_interest_usdc` | number | Current open interest in USDC | ## Example ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/markets/0x8180fee481707671aa45de84a9c3740ab607f3f2643b456e0380afb02d12cf7d/oi" \ -H "x-api-key: YOUR_KEY" ``` # Trade History (Market) Source: https://docs.polynode.dev/api-reference/onchain/market-trades GET /v2/onchain/markets/{token_id}/trades Complete onchain trade history for any market token. Returns every onchain trade fill for a specific market token, enriched with market metadata. > [!TIP] > > **Want the entire market in one call?** Use [Trade History (Market) — Bulk](/api-reference/onchain/market-trades-all) (Growth plan and above). Returns up to 250K trades in a single response, no pagination. ## Quick start — get the most recent 100 trades ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/markets/{token_id}/trades?limit=100" \ -H "x-api-key: YOUR_KEY" ``` Default `limit=100`, max `limit=1000`. That's all most apps need. ## Get every trade in the market (full history) To walk the entire history, add `?cursor=` (empty value) to the first request, then **for each next page, copy `pagination.cursor` from the response back into the URL**. Stop when `pagination.has_more` is `false`. Three complete copy-paste scripts that walk an entire market: ```python Python theme={null} import requests API_KEY = "YOUR_KEY" TOKEN_ID = "21743669032210695168079601505378236205866986767926346409604806906483294819314" def get_all_trades(token_id): cursor = "" # empty string = first page all_trades = [] while True: r = requests.get( f"https://api.polynode.dev/v2/onchain/markets/{token_id}/trades", params={"limit": 1000, "cursor": cursor}, headers={"x-api-key": API_KEY}, ).json() all_trades.extend(r["trades"]) if not r["pagination"]["has_more"]: break cursor = r["pagination"]["cursor"] # feed this into the next request return all_trades trades = get_all_trades(TOKEN_ID) print(f"got {len(trades)} trades") ``` ```javascript JavaScript theme={null} const API_KEY = "YOUR_KEY"; const TOKEN_ID = "21743669032210695168079601505378236205866986767926346409604806906483294819314"; async function getAllTrades(tokenId) { let cursor = ""; // empty string = first page const allTrades = []; while (true) { const url = `https://api.polynode.dev/v2/onchain/markets/${tokenId}/trades` + `?limit=1000&cursor=${encodeURIComponent(cursor)}`; const r = await fetch(url, { headers: { "x-api-key": API_KEY } }).then(r => r.json()); allTrades.push(...r.trades); if (!r.pagination.has_more) break; cursor = r.pagination.cursor; // feed this into the next request } return allTrades; } const trades = await getAllTrades(TOKEN_ID); console.log(`got ${trades.length} trades`); ``` ```bash bash theme={null} KEY="YOUR_KEY" TOKEN_ID="21743669032210695168079601505378236205866986767926346409604806906483294819314" CURSOR="" TOTAL=0 while true; do RESP=$(curl -s "https://api.polynode.dev/v2/onchain/markets/$TOKEN_ID/trades?limit=1000&cursor=$CURSOR" \ -H "x-api-key: $KEY") COUNT=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['count'])") HAS_MORE=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['pagination']['has_more'])") TOTAL=$((TOTAL + COUNT)) echo "got $COUNT trades, total: $TOTAL" [ "$HAS_MORE" = "False" ] && break CURSOR=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['pagination']['cursor'])") done ``` **Real run** (heavy market, walked live with the Python script above): ``` got 1000 trades (total: 1000) got 1000 trades (total: 2000) got 1000 trades (total: 3000) ... got 1000 trades (total: 20000) DONE. 20,000 trades in 24 seconds. ``` Each page takes \~1 second regardless of how deep you go — the loop just keeps running until `has_more` is `false`. ## Request ``` GET /v2/onchain/markets/{token_id}/trades?limit=100 GET /v2/onchain/markets/{token_id}/trades?limit=1000&cursor= ``` | Parameter | Type | Location | Description | | - | - | - | - | | `token_id` | string | path | CTF token ID (numeric string) | | `limit` | integer | query | Max results per page (default 100, max 1000) | | `cursor` | string | query | Pass empty string `?cursor=` for first page, then echo back `pagination.cursor` from each response. Required to walk past the first page reliably on large markets. | | `offset` | integer | query | Alternative to cursor: skip first N. Fast for the first \~25K results then degrades. Use `cursor` for anything bigger. | ## Response ```json theme={null} { "token_id": "110959653450933276250915064669875552310439627880508793089816880777942697720191", "source": "onchain", "count": 3, "market": "US x Iran ceasefire extended by April 22, 2026?", "slug": "us-x-iran-ceasefire-extended-by-april-22-2026", "outcome": "No", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/us-x-iran-ceasefire-by-Cgmx3GCuOwjs.jpg", "condition_id": "0x1d2787cb8aed975d092b2799ed6f4083e9445f7420cdc09e9d47e7d54356c6cd", "pagination": { "limit": 3, "has_more": true, "cursor": "1777595648:0xeae6ca0aeb75fc866ddb29d3a4b2cd15382895b923fe05b9315445d6346d1c47_0x49ddd1e169186d350488e3d62f58452fe76862c5f81f33987e659759e2c66100" }, "trades": [ { "tx_hash": "0x044dc412fa97d972fae1e77f8a30e769b7bea339cc3a27b5045e5668b513a520", "order_hash": "0x6b3d58dcf19f26a0b2f325bc43dc793765d1abeedfc449a3c5be38b6523613c9", "timestamp": 1777595650, "maker": "0x84571f1bf97a5c710cbe51daff2dd4556cc887fd", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "maker_asset_id": "0", "taker_asset_id": "110959653450933276250915064669875552310439627880508793089816880777942697720191", "maker_amount": 617.382, "taker_amount": 618, "fee": 0, "direction": "BUY", "side": "maker" } ] } ``` | Field | Type | Description | | - | - | - | | `count` | integer | Number of trades in this response | | `pagination.has_more` | boolean | `true` if more pages available — keep paginating | | `pagination.cursor` | string | Pass this back as `?cursor=` for the next page | | `market` | string | Market question | | `slug` | string | Market slug | | `outcome` | string | Outcome label for this token | | `image` | string | Market image URL | | `condition_id` | string | Market condition ID | | `trades[].tx_hash` | string | Transaction hash | | `trades[].order_hash` | string | Order hash that was filled | | `trades[].timestamp` | number | Unix timestamp | | `trades[].maker` | string | Maker wallet | | `trades[].taker` | string | Taker wallet | | `trades[].maker_asset_id` | string | Asset the maker provided (`"0"` = USDC) | | `trades[].taker_asset_id` | string | Asset the taker provided | | `trades[].maker_amount` | number | Amount maker provided | | `trades[].taker_amount` | number | Amount taker provided | | `trades[].fee` | number | Fee (USDC) | | `trades[].direction` | string | `"BUY"` or `"SELL"` from the buyer's perspective on this fill | | `trades[].side` | string | Always `"maker"` for this endpoint | # Trade History (Market) — Bulk Source: https://docs.polynode.dev/api-reference/onchain/market-trades-all GET /v2/onchain/markets/{token_id}/trades/all Return every trade for a market token in a single response. Growth plan or above. > [!WARNING] > > **Growth plan or above only.** This endpoint returns the **entire** trade history for a market token in **one response** — no client-side pagination, no offset bookkeeping. Because a single call can return tens of thousands of fills (and tens of MB of JSON), it's gated to the **Growth plan and above**. Starter and free tier requests receive `403`. > > * Hard cap: **250,000 trades per call** — beyond that, response includes `"partial": true` with `"partial_reason": "hard_cap_250000"` > * Wall-clock budget: **180 seconds** — first cold-cache call on a busy market may take 1-3 minutes > * Cache: full results cached **5 minutes**. Repeat calls return in under 1 second > * Typical payload: 1-50 MB. Worst case (capped): 100-200 MB JSON Returns every onchain trade fill for one market token in a single response. The server walks the full trade history with parallel time-bucketed queries server-side — you don't need to paginate. Each trade is enriched with market metadata. This is the right endpoint when you want **bulk-export** a market for analysis, indexing, or backtesting. For interactive UIs that just need the most recent N fills, use the standard [Market Trade History](/api-reference/onchain/market-trades) instead. ## Request ``` GET /v2/onchain/markets/{token_id}/trades/all?from=&to= ``` | Parameter | Type | Location | Description | | - | - | - | - | | `token_id` | string | path | CTF token ID (numeric string) | | `from` | integer | query | Optional start of window in unix seconds. Default: 2024-01-01 (covers all Polymarket history) | | `to` | integer | query | Optional end of window in unix seconds. Default: now | ## Response ```json theme={null} { "token_id": "21743669032210695168079601505378236205866986767926346409604806906483294819314", "from_ts": 1774588800, "to_ts": 1775817600, "count": 27601, "partial": false, "partial_reason": null, "fetched_in_ms": 5437, "cache": "miss", "trades": [ { "tx_hash": "0xa73ccafda4acf5473d65ce9b6ed9f9e41861ea2ae0b5c0a8bb5cfd3869583fdf", "order_hash": "0x3e5baca0ae04010bfe01ec0a0a3fe8b6e291ca8373bb4803f31620754f83a17d", "timestamp": 1775817557, "maker": "0x4ef7e2e97735a144c35c04bf22bcac184d3221be", "taker": "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "token_id": "21743669032210695168079601505378236205866986767926346409604806906483294819314", "direction": "SELL", "price": 0.545, "shares": 1827.47, "usd": 995.99, "fee": 0 } ] } ``` ## Response fields | Field | Type | Description | | - | - | - | | `token_id` | string | The CTF token ID requested | | `from_ts` / `to_ts` | integer | Resolved time window in unix seconds | | `count` | integer | Total trades returned (≤ 250,000) | | `partial` | boolean | `true` if either the 250K hard cap or the 180s wall-clock budget was hit before the full window was walked | | `partial_reason` | string \| null | `"hard_cap_250000"` or `"wall_clock_180s"` when partial; otherwise `null` | | `fetched_in_ms` | integer | Server-side fetch time. Cached calls show the original miss time | | `cache` | string | `"hit"` if served from Redis cache, `"miss"` if freshly walked | | `trades` | array | All trades, sorted by `timestamp` descending (newest first) | ## Trade fields | Field | Type | Description | | - | - | - | | `tx_hash` | string | Polygon transaction hash | | `order_hash` | string | Order hash from the exchange | | `timestamp` | integer | Unix seconds when the fill settled | | `maker` | string | Maker address | | `taker` | string | Taker address | | `token_id` | string | The outcome token id (echoes the request param) | | `direction` | string | `"BUY"` or `"SELL"` from the maker's perspective | | `price` | number | USDC per share, 4-decimal precision | | `shares` | number | Outcome tokens traded | | `usd` | number | USDC notional | | `fee` | number | Maker fee paid (USDC) | ## Example: full lifetime of a market ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/markets/21743669032210695168079601505378236205866986767926346409604806906483294819314/trades/all?key=$YOUR_KEY" ``` ## Example: window inside a longer-running market ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/markets/$TOKEN/trades/all?from=1774588800&to=1775817600&key=$YOUR_KEY" ``` ## Errors `403 Tier required`: ```json theme={null} { "error": "/trades/all requires the Growth plan or above. Your tier: starter. See polynode.dev/pricing." } ``` `401 No API key`: ```json theme={null} { "error": "API key required. Pass via ?key= or x-api-key header." } ``` ## Notes * For a multi-token market (binary YES/NO), call this endpoint **twice** — once per `token_id`. A `condition_id` variant that returns both tokens in one call is on the roadmap. * `partial: true` results are **not cached**. Subsequent calls re-attempt the full walk. Tighten the time window with `from`/`to` if you keep hitting the cap. * Cache key is `(token_id, from_ts, to_ts)`. Different windows are cached independently. Default-window calls (no `from`/`to`) share a cache slot. * The walk is parallelized — total bandwidth use is moderate even for huge markets. # Market Volume Source: https://docs.polynode.dev/api-reference/onchain/market-volume GET /v2/onchain/markets/{token_id}/volume Lifetime onchain volume statistics for any market token. Returns lifetime trading volume statistics for a specific market token, sourced directly from onchain settlement data. Enriched with market metadata. ## Request ``` GET /v2/onchain/markets/{token_id}/volume ``` | Parameter | Type | Location | Description | | - | - | - | - | | `token_id` | string | path | CTF token ID (numeric string) | ## Response ```json theme={null} { "token_id": "21912724974096796009916816278814088615574660931588091764221331842149572809887", "source": "onchain", "found": true, "market": "Bitcoin Up or Down - March 28, 9:55PM-10:00PM ET", "slug": "btc-updown-5m-1774749300", "outcome": "Up", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "condition_id": "0xb91dbc2ba7f0d33c71fca765909e98b2023af855f1d69b82d5fd59732085700d", "total_trades": 2886, "buys": 2609, "sells": 277, "volume_usdc": 31054.394523, "buy_volume_usdc": 29482.48427, "sell_volume_usdc": 1571.910253 } ``` | Field | Type | Description | | - | - | - | | `found` | boolean | Whether the token was found onchain | | `market` | string | Market question | | `slug` | string | Market slug | | `outcome` | string | Outcome label for this token | | `image` | string | Market image URL | | `condition_id` | string | Market condition ID | | `total_trades` | number | Lifetime number of fills | | `buys` | number | Number of buy fills | | `sells` | number | Number of sell fills | | `volume_usdc` | number | Total volume in USDC | | `buy_volume_usdc` | number | Buy-side volume in USDC | | `sell_volume_usdc` | number | Sell-side volume in USDC | ## Example ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/markets/21912724974096796009916816278814088615574660931588091764221331842149572809887/volume" \ -H "x-api-key: YOUR_KEY" ``` # Positions (All) Source: https://docs.polynode.dev/api-reference/onchain/positions GET /v2/onchain/positions Query every position on Polymarket. Filter by wallet, market, status, or minimum size. Full history with cursor pagination. Search and filter all Polymarket positions across every wallet. Each position is enriched with market metadata and includes realized P\&L, average entry price, and current size. Sourced directly from onchain settlement data. ## Request ``` GET /v2/onchain/positions ``` ### Query parameters | Parameter | Type | Required | Description | | - | - | - | - | | `wallet` | string | No | Filter by wallet address | | `market_slug` | string | No | Filter by market slug (e.g. `will-zohran-mamdani-win-the-2025-nyc-mayoral-election`) | | `condition_id` | string | No | Filter by condition ID (0x-prefixed, 64 hex chars) | | `token_id` | string | No | Filter by outcome token ID | | `status` | string | No | `open` (size > 0), `closed` (size = 0), or `all` (default) | | `min_size` | number | No | Minimum position size in shares | | `limit` | integer | No | Results per page (1-500, default 100) | | `order` | string | No | Sort direction: `desc` (default, most recent first) or `asc`. When `wallet` is set, results are ordered by the wallet's most recent on-chain activity per position. Otherwise, ordered by position ID. | | `pagination_key` | string | No | Cursor from a previous response to fetch the next page. Not used for wallet queries (see Pagination). | ### Identifying markets * **`market_slug`** — human-readable URL slug from Polymarket. Returns positions for all outcomes. * **`condition_id`** — unique condition identifier. Returns positions for all outcomes. * **`token_id`** — specific outcome token. Returns positions for only that outcome. ## Response ```json theme={null} { "count": 2, "pagination": { "limit": 2, "has_more": true, "pagination_key": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639-99881503238784655670984673100655147508393351942279611133016622634826369070119" }, "positions": [ { "wallet": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "token_id": "99949662063403569895321097192043694236016212986254553767097648841549016857591", "size": 0.012785, "avg_price": 0.859999, "realized_pnl": 0.16, "unrealized_pnl": 0.02, "current_price": 0.88, "market_status": "live", "total_bought": 1.16, "market": "Will FC Bayern Munchen win on 2026-04-07?", "market_slug": "ucl-rma1-bay1-2026-04-07-bay1", "outcome": "Yes", "condition_id": "0x5f5c8d8fa28d77b5552562f32393ac199fb6b92ed1c1e2239e29c09f7e4eb3f5", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/champions-league-pic-QIUFsL8vaDdq.png" }, { "wallet": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "token_id": "99881503238784655670984673100655147508393351942279611133016622634826369070119", "size": 0, "avg_price": 0.98, "realized_pnl": 0.1, "unrealized_pnl": 0, "current_price": null, "market_status": "closed", "total_bought": 5, "market": "Solana Up or Down - December 30, 10:30PM-10:45PM ET", "market_slug": "sol-updown-15m-1767151800", "outcome": "Down", "condition_id": "0xa7f50f1bd65e8fd1790117b3b162dc03489df7b89cd35f4b1093792691b8a327", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/SOL+fullsize.png" } ] } ``` ### Position fields | Field | Type | Description | | - | - | - | | `wallet` | string | Wallet address holding the position | | `token_id` | string | Outcome token ID | | `size` | number | Current position size in shares. `0` means the position is fully exited. | | `avg_price` | number | Average entry price (0 to 1) | | `realized_pnl` | number | Realized profit/loss in USD. Reflects gains/losses from closed portions of the position and from onchain redemptions of resolved markets. Stays `0` for resolved-but-not-yet-redeemed positions; check `redeemable` to detect those. | | `unrealized_pnl` | number | Unrealized profit/loss in USD on the remaining open shares. For resolved markets, uses the final settlement price (`1.0` for winners, `0.0` for losers). For live markets, uses the current market price. Returns `0` when `size = 0`. Byte-identical to Polymarket's `cashPnl` field for any position covered by both. | | `current_price` | number \| null | Price used to compute `unrealized_pnl`. `1.0` or `0.0` for resolved markets (derived deterministically from on-chain `payoutNumerators`), the live market price for active markets, and `null` when `size = 0` or no price is available. | | `market_status` | string | One of: `"live"` (market still trading), `"resolved-win"` (market resolved, this outcome won), `"resolved-loss"` (market resolved, this outcome lost), or `"closed"` (position fully exited, `size = 0`). A fifth value `"resolved-unknown"` may appear briefly for very old markets while resolution data is catching up. Never `"live"` when `resolved_at` is set. | | `won` | boolean \| undefined | Present only on `resolved-win` / `resolved-loss` rows. `true` when this outcome won, `false` when it lost. Derived from on-chain payouts. | | `winning_outcome_index` | number \| undefined | Present only on resolved rows. Numeric index of the outcome that won (0 or 1 for binary markets). Pair with `outcome_index` to know whether this row is the winning side. | | `outcome_index` | number \| undefined | Numeric index of this row's outcome within the market's outcomes array (0 or 1 for binary markets). Stable across the API regardless of how the UI labels the outcome (`Yes`/`No`, team names, etc.). Use this for cross-row joins instead of parsing `outcome` strings. | | `total_bought` | number | Total amount bought in USD over the lifetime of the position. | | `initial_value` | number \| undefined | Cost basis in USD of the currently held shares (`size × cost_per_share`). Use this if you need the basis number that matches Polymarket `cashPnl` and what users see in the Polymarket UI. | | `redeemable` | boolean \| undefined | `true` when the market has resolved and the user can call redeem on the CTF contract to claim payout (or accept loss). Useful for detecting "resolved-but-not-redeemed" positions: filter `market_status = "resolved-loss"` AND `redeemable = true` for unclaimed losses, or `market_status = "resolved-win"` AND `redeemable = true` for unclaimed wins. | | `opposite_asset` | string \| undefined | Token ID of the OPPOSITE outcome on the same market (the binary counterpart). Useful for fetching the matching position on the other side without re-resolving the condition. | | `market` | string | Market question text | | `market_slug` | string | Market URL slug | | `outcome` | string | Outcome label (e.g. "Yes", "No") | | `condition_id` | string | Market condition ID | | `image` | string \| null | Market image URL. `null` for some delisted or niche markets. | | `event_slug` | string \| null | Parent **event** slug, distinct from the per-row market `slug`. For multi-market events (NBA games with several lines, election markets with several candidates, FIFA World Cup with one market per team), this is the parent the markets share. For single-market events, equals the market slug. `null` when event metadata is not yet known. | | `last_activity` | number \| undefined | Unix timestamp of the wallet's most recent fill on this position. Present only when querying by `wallet`. Positions with no fill history (e.g. acquired purely via split/merge/redemption) omit this field and sort to the end. | | `last_trade_at` | number \| null | Unix seconds. Latest fill on this token across V1 + V2 exchanges. Same data as `last_activity` but always present (`null` instead of omitted) for consistent shape. Use either; `last_trade_at` is preferred for new integrations. | | `closed_at` | number \| null | Unix seconds. Latest moment this wallet redeemed any outcome of the market for collateral. `null` when the wallet has not redeemed (open positions, positions sold to zero pre-resolution, or wins held but not yet redeemed). | | `resolved_at` | number \| null | Unix seconds. Moment the market was resolved on-chain (when payouts became redeemable). `null` for markets that resolved before polynode began tracking, or for markets that have not yet resolved. Recent markets are fully covered. | ### Pagination fields | Field | Type | Description | | - | - | - | | `count` | number | Number of positions in this response | | `pagination.limit` | number | Requested page size | | `pagination.has_more` | boolean | `true` if more results exist beyond this page | | `pagination.pagination_key` | string | Pass this as `pagination_key` in the next request to get the next page | ## Examples ### All positions for a wallet ```bash cURL theme={null} curl "https://api.polynode.dev/v2/onchain/positions?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&limit=100" \ -H "x-api-key: YOUR_KEY" ``` ```javascript Node.js theme={null} const resp = await fetch( "https://api.polynode.dev/v2/onchain/positions?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&limit=100", { headers: { "x-api-key": "YOUR_KEY" } } ); const data = await resp.json(); console.log(data.positions); ``` ```python Python theme={null} import requests resp = requests.get( "https://api.polynode.dev/v2/onchain/positions", params={"wallet": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "limit": 100}, headers={"x-api-key": "YOUR_KEY"}, ) data = resp.json() print(data["positions"]) ``` ### Open positions only Use `status=open` to get only positions with a non-zero size. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/positions?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&status=open&limit=100" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 2, "pagination": { "limit": 2, "has_more": true, "pagination_key": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639-99504617..." }, "positions": [ { "wallet": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "token_id": "99949662063403569895321097192043694236016212986254553767097648841549016857591", "size": 0.012785, "avg_price": 0.859999, "realized_pnl": 0.16, "unrealized_pnl": 0.02, "current_price": 0.88, "market_status": "live", "total_bought": 1.16, "market": "Will FC Bayern Munchen win on 2026-04-07?", "market_slug": "ucl-rma1-bay1-2026-04-07-bay1", "outcome": "Yes", "condition_id": "0x5f5c8d8fa28d77b5552562f32393ac199fb6b92ed1c1e2239e29c09f7e4eb3f5", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/champions-league-pic-QIUFsL8vaDdq.png" } ] } ``` ### Who holds a market Use `market_slug` to see all wallets with positions on a specific market. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/positions?market_slug=will-zohran-mamdani-win-the-2025-nyc-mayoral-election&status=open&limit=50" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 2, "pagination": { "limit": 2, "has_more": true, "pagination_key": "0xfffe254008792df0c325325a75a3c6e7aaed436a-10583236..." }, "positions": [ { "wallet": "0xffff3840fbf40fd2e193c01cc299cdf1262cffaf", "token_id": "33945469250963963541781051637999677727672635213493648594066577298999471399137", "size": 0.009534, "avg_price": 0.947999, "realized_pnl": -0.54, "unrealized_pnl": -5.07, "current_price": 0.416, "market_status": "live", "total_bought": 539.03, "market": "Will Zohran Mamdani win the 2025 NYC mayoral election?", "market_slug": "will-zohran-mamdani-win-the-2025-nyc-mayoral-election", "outcome": "Yes", "condition_id": "0xebddfcf7b4401dade8b4031770a1ab942b01854f3bed453d5df9425cd9f211a9", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-zohran-mamdani-win-the-2025-nyc-mayoral-election-EscSJQTT6hWg.jpg" } ] } ``` ### Large positions Use `min_size` to find positions above a threshold. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/positions?min_size=100&limit=20" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 2, "pagination": { "limit": 2, "has_more": true, "pagination_key": "0xffffffe1e093aacd21e4e281e66d543fb0b23455-98495912..." }, "positions": [ { "wallet": "0xffffffe1e093aacd21e4e281e66d543fb0b23455", "token_id": "98813479054803844837498343855179110721772056323529222930302029314504656450267", "size": 1100, "avg_price": 0.003636, "realized_pnl": 0, "unrealized_pnl": -3.96, "current_price": 0, "market_status": "resolved-loss", "total_bought": 1100, "market": "Bitcoin Up or Down - February 5, 9:45AM-10:00AM ET", "market_slug": "btc-updown-15m-1770302700", "outcome": "Up", "condition_id": "0x3ec09263f6fb247e65635d52c2787dc0f46806f153124e138f42ad03411198b4", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png" } ] } ``` ### Combined filters Filter by wallet, market, and status at once. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/positions?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&market_slug=ucl-rma1-bay1-2026-04-07-bay1&status=open&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ### Pagination **Wallet queries** return every position for the wallet in a single response (up to 500), sorted by most recent on-chain activity. No pagination needed — request `limit=500` and read all results. `has_more` is always `false` and no cursor is returned. Wallets with more than 500 lifetime positions are capped at 500. **Non-wallet queries** (filtering by `market_slug`, `condition_id`, `token_id`, or `min_size` alone) use cursor-based pagination for iterating through large result sets. ```bash theme={null} # First page curl "https://api.polynode.dev/v2/onchain/positions?min_size=100&limit=100" \ -H "x-api-key: YOUR_KEY" # Next page curl "https://api.polynode.dev/v2/onchain/positions?min_size=100&limit=100&pagination_key=CURSOR_FROM_PREVIOUS" \ -H "x-api-key: YOUR_KEY" ``` ## Error responses | Status | Response | Condition | | - | - | - | | 400 | `{"error": "market_slug not found"}` | Invalid or unknown `market_slug` | | 400 | `{"error": "condition_id not found"}` | Invalid or unknown `condition_id` | | 401 | `{"error": "API key required. Pass via ?key= or x-api-key header."}` | Missing API key | | 403 | `{"error": "V2 endpoints require a paid plan. See polynode.dev/pricing for details."}` | Free tier key | | 429 | `{"error": "Rate limited. N req/s for your tier.", "retryAfterMs": ...}` | Rate limited | ## Notes * Position data is sourced from onchain settlement records. Every position that was ever opened on Polymarket is included. * The `realized_pnl` field reflects actual profit/loss from closed portions of the position, including onchain redemptions of resolved markets. For open positions, it reflects any partial closes. * The `unrealized_pnl` field shows the paper profit/loss on the remaining open shares. For resolved markets, this uses the final settlement price ($1 for winners, $0 for losers). For active markets, the current market price is used. * `market_status` lets clients distinguish live-tradable positions from positions on resolved markets that the wallet never redeemed. Resolved-and-never-redeemed positions still have `size > 0` and will show the correct terminal `unrealized_pnl`. * Market metadata (`market`, `market_slug`, `outcome`, `condition_id`, `image`) is enriched from our index. Very old or delisted markets may not have metadata. * When querying by `wallet`, the sort key is the timestamp of the most recent fill for each position, not the position's close date. A position bought months ago and held to resolution (closed only via redemption) will sort by its original buy date. ## Verifying parity with Polymarket Per-position fields on this endpoint match Polymarket's `data-api.polymarket.com/positions` byte-for-byte. Anyone can verify directly with the standalone Node script below — no internal access required. ### Field map | polynode field | Polymarket field | | - | - | | `token_id` | `asset` | | `condition_id` | `conditionId` | | `size` | `size` | | `avg_price` | `avgPrice` | | `realized_pnl` | `realizedPnl` | | `unrealized_pnl` | `cashPnl` | | `current_price` | `curPrice` | | `outcome` | `outcome` | ### Self-test script (Node 18+, no dependencies) ```javascript theme={null} // Save as parity_demo.mjs and run with: // POLYNODE_KEY=pn_live_xxx node parity_demo.mjs const KEY = process.env.POLYNODE_KEY; const WALLET = process.argv[2]; const [pm, us] = await Promise.all([ fetch(`https://data-api.polymarket.com/positions?user=${WALLET}&sizeThreshold=0&limit=2000`, { headers: { 'User-Agent': 'Mozilla/5.0' } }).then(r => r.json()), fetch(`https://api.polynode.dev/v2/onchain/positions?wallet=${WALLET}&status=all&limit=2000`, { headers: { 'x-api-key': KEY } }).then(r => r.json()).then(j => Array.isArray(j) ? j : (j.positions ?? [])), ]); const pmByPid = new Map(pm.map(p => [String(p.asset), p])); const usByPid = new Map(us.map(p => [String(p.token_id), p])); const shared = [...pmByPid.keys()].filter(k => usByPid.has(k)); let exact = 0, sub_dollar = 0; for (const pid of shared) { const p = pmByPid.get(pid), u = usByPid.get(pid); const avgDiff = Math.abs(Number(p.avgPrice) - Number(u.avg_price)); const pnlDiff = Math.abs(Number(p.realizedPnl) - Number(u.realized_pnl)); if (avgDiff < 0.005 && pnlDiff < 0.01) exact++; if (pnlDiff < 1.0) sub_dollar++; console.log(` ${pid.slice(0,8)}… PM realPnl=${Number(p.realizedPnl).toFixed(2).padStart(10)} Us realPnl=${Number(u.realized_pnl).toFixed(2).padStart(10)} Δ=${pnlDiff.toFixed(4)}`); } console.log(`\n byte-perfect: ${exact}/${shared.length} sub-$1: ${sub_dollar}/${shared.length}`); ``` Run against any wallet to confirm. Validated 2026-04-30 across diverse wallets at 100 % byte-perfect match on every shared open position. ### What this proves If you trust Polymarket's positions page, you can trust ours — they're computing the same thing from the same on-chain events. Use this script as ongoing regression coverage in your own integration if PnL accuracy is critical to your product. # Trade History (All) Source: https://docs.polynode.dev/api-reference/onchain/trades GET /v2/onchain/trades Query every trade ever executed on Polymarket. Filter by wallet, market, time range, or minimum size. Full history with cursor pagination. Search and filter the complete history of Polymarket trades. Every CLOB fill is enriched with market metadata. Supports filtering by wallet, market (via slug, condition ID, or token ID), time range, and minimum trade size. When no filters are provided, returns the most recent trades from the last 24 hours. Add any filter to query the full history. ## Request ``` GET /v2/onchain/trades ``` ### Query parameters | Parameter | Type | Required | Description | | - | - | - | - | | `wallet` | string | No | Filter by wallet address (matches both maker and taker sides) | | `market_slug` | string | No | Filter by market slug (e.g. `will-zohran-mamdani-win-the-2025-nyc-mayoral-election`) | | `condition_id` | string | No | Filter by condition ID (0x-prefixed, 64 hex chars) | | `token_id` | string | No | Filter by outcome token ID | | `start_time` | integer | No | Unix timestamp — only return trades after this time | | `end_time` | integer | No | Unix timestamp — only return trades before this time | | `min_total` | number | No | Minimum trade size in USD | | `limit` | integer | No | Results per page (1-500, default 100) | | `order` | string | No | Sort by timestamp: `desc` (newest first, default) or `asc` (oldest first). Using `asc` without any filter returns an error. | | `sort_by` | string | No | Set to `order_hash` to cluster fills by order. All fills from the same limit order appear adjacent, sorted by time within each group. Groups ordered by most recent fill. Default sort is by timestamp. | | `group_by` | string | No | Set to `order_hash` to aggregate fills into one row per order. Each row contains `total_amount_usd`, `total_shares`, `avg_price`, `fill_count`, `first_fill_at`, `last_fill_at`, and `tx_hashes`. See [Group by order](#group-by-order) below. | | `pagination_key` | string | No | Cursor from a previous response to fetch the next page | ### Identifying markets There are three ways to filter trades by market: * **`market_slug`** — the human-readable URL slug from Polymarket (e.g. `will-zohran-mamdani-win-the-2025-nyc-mayoral-election`). Easiest to use. * **`condition_id`** — the unique condition identifier for a market. Returns trades for all outcomes (Yes and No). * **`token_id`** — the specific outcome token. Returns trades for only that outcome. You can combine market filters with `wallet` to find a specific wallet's trades on a specific market. ## Response ```json theme={null} { "count": 2, "pagination": { "limit": 2, "has_more": true, "pagination_key": "0xfffff7ed9080f46d7975f905e7f9358c436a1b177c6e19e54510c3ba6dcfddc4_0x09c8f6c7a148a83dfc968b1d9aece6ddb43a7a0e1bc2b1cb4b38356bb32220f0" }, "trades": [ { "timestamp": 1775668111, "tx_hash": "0xfffff7ed9080f46d7975f905e7f9358c436a1b177c6e19e54510c3ba6dcfddc4", "order_hash": "0xd808640f8d06bd5d1fa6f86c149d2a66753a6c86a4580c616a9e170f57f96b02", "maker": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "taker": "0xc5d563a36ae78145c45a50134d48a1215220f80a", "token_id": "3486411672082301675645165272859578340300389072626261580506086464973862637410", "price": 0.92, "amount_usd": 1, "fee_usd": 0.01, "shares": 1.08695, "market": "Will Goztepe SK win on 2026-04-08?", "market_slug": "tur-goz-gal-2026-04-08-goz", "outcome": "No", "condition_id": "0x8c7ec1f6e3694c402bd204a25756d55b34bb294f28677b624e1068450f1dfb1a", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/tur.png" }, { "timestamp": 1775668111, "tx_hash": "0xfffff7ed9080f46d7975f905e7f9358c436a1b177c6e19e54510c3ba6dcfddc4", "order_hash": "0x09c8f6c7a148a83dfc968b1d9aece6ddb43a7a0e1bc2b1cb4b38356bb32220f0", "maker": "0x84ad9c5c547a82ec9a08547b94bd922446e5bfb7", "taker": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "token_id": "107137984184508009127443282317786484656951337636215782600474106740257845898368", "price": 0.08, "amount_usd": 0.09, "fee_usd": 0.11, "shares": 1.08695, "market": "Will Goztepe SK win on 2026-04-08?", "market_slug": "tur-goz-gal-2026-04-08-goz", "outcome": "Yes", "condition_id": "0x8c7ec1f6e3694c402bd204a25756d55b34bb294f28677b624e1068450f1dfb1a", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/tur.png" } ] } ``` ### Trade fields | Field | Type | Description | | - | - | - | | `timestamp` | number | Unix timestamp of the fill | | `tx_hash` | string | Polygon transaction hash | | `order_hash` | string | CLOB order hash that was filled | | `maker` | string | Maker wallet address | | `taker` | string | Taker wallet address | | `token_id` | string | Outcome token ID | | `price` | number | Fill price (0 to 1) | | `amount_usd` | number | Trade size in USD | | `fee_usd` | number | Fee paid in USD | | `shares` | number | Number of outcome shares traded | | `side` | string | Exchange role: `"maker"` or `"taker"`. With `wallet` filter, this is the queried wallet's role on the fill. Without `wallet`, always `"maker"` (see "Direction & side semantics" below). Always present. | | `direction` | string | Trader intent: `"BUY"` or `"SELL"`. With `wallet` filter, from the queried wallet's perspective (`BUY` when the wallet contributed USDC, `SELL` when it contributed outcome tokens). Without `wallet`, from the maker's perspective. Always present. | | `market` | string | Market question text | | `market_slug` | string | Market URL slug | | `outcome` | string | Outcome label (e.g. "Yes", "No") | | `condition_id` | string | Market condition ID | | `image` | string \| null | Market image URL. `null` for some delisted or niche markets. | ### Direction & side semantics `direction` and `side` answer two different questions and are always populated: * **`direction` (`"BUY"` or `"SELL"`)** — what the subject of the row did, economically. They contributed USDC and received outcome shares (`BUY`) or contributed outcome shares and received USDC (`SELL`). * **`side` (`"maker"` or `"taker"`)** — the subject's role on the fill. The `maker` placed a resting limit order; the `taker` aggressed the spread. The "subject" of the row depends on the filter: | Query | Subject of `direction` / `side` | | - | - | | `?wallet=W` (with or without other filters) | The wallet `W`. `side` reflects whether `W` was the maker or taker on each fill. | | Any market-wide filter (no `wallet`): `?condition_id=…`, `?token_id=…`, `?market_slug=…`, or no filter | The **maker** of each fill. On Polymarket's CLOB the maker is always the user who signed the limit order, so `direction` is always a real user's BUY/SELL. `side` is therefore always `"maker"` in this case. | This means a row from a wallet-filtered query and the same row from a market-wide query may report different `direction` values — both are correct, just anchored on different parties (the queried wallet vs. the maker). ### Pagination fields | Field | Type | Description | | - | - | - | | `count` | number | Number of trades in this response | | `pagination.limit` | number | Requested page size | | `pagination.has_more` | boolean | `true` if more results exist beyond this page | | `pagination.pagination_key` | string | Pass this as `pagination_key` in the next request to get the next page | ## Examples ### Recent trades Returns the most recent trades from the last 24 hours. ```bash cURL theme={null} curl "https://api.polynode.dev/v2/onchain/trades?limit=2" \ -H "x-api-key: YOUR_KEY" ``` ```javascript Node.js theme={null} const resp = await fetch( "https://api.polynode.dev/v2/onchain/trades?limit=2", { headers: { "x-api-key": "YOUR_KEY" } } ); const data = await resp.json(); console.log(data.trades); ``` ```python Python theme={null} import requests resp = requests.get( "https://api.polynode.dev/v2/onchain/trades", params={"limit": 2}, headers={"x-api-key": "YOUR_KEY"}, ) data = resp.json() print(data["trades"]) ``` ### Filter by wallet Returns all trades where the wallet was either maker or taker. The `side` field indicates which role the wallet played. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&limit=1" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 1, "pagination": { "limit": 1, "has_more": true, "pagination_key": "0xfffff7ed...d808640f..." }, "trades": [ { "timestamp": 1775668111, "tx_hash": "0xfffff7ed9080f46d7975f905e7f9358c436a1b177c6e19e54510c3ba6dcfddc4", "order_hash": "0xd808640f8d06bd5d1fa6f86c149d2a66753a6c86a4580c616a9e170f57f96b02", "maker": "0xa973ae12882a1c24a75da7a3b52cb01500b2f639", "taker": "0xc5d563a36ae78145c45a50134d48a1215220f80a", "token_id": "34864116720823016756451652728595783403003890726262615805060864649738626374410", "price": 0.92, "amount_usd": 1, "fee_usd": 0.01, "shares": 1.08695, "side": "maker", "market": "Will Goztepe SK win on 2026-04-08?", "market_slug": "tur-goz-gal-2026-04-08-goz", "outcome": "No", "condition_id": "0x8c7ec1f6e3694c402bd204a25756d55b34bb294f28677b624e1068450f1dfb1a", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/tur.png" } ] } ``` ### Filter by market Use `market_slug` to get all trades on a specific market across all wallets. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?market_slug=will-zohran-mamdani-win-the-2025-nyc-mayoral-election&limit=1" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 1, "pagination": { "limit": 1, "has_more": true, "pagination_key": "0xffffffeb...00063fc7..." }, "trades": [ { "timestamp": 1759503806, "tx_hash": "0xffffffeb7983b64a9394a0485c897113ad17ffca0fde8f3fa16aa045396d0582", "order_hash": "0x00063fc790381b8d017b868f153aeed48152c8c7012e33cb4793b3f5c8989b3a", "maker": "0xe05d8c348aee0323cf115c18006a35db54ba2685", "taker": "0xc5d563a36ae78145c45a50134d48a1215220f80a", "token_id": "33945469250963963541781051637999677727672635213493648594066577298999471399137", "price": 0.897, "amount_usd": 100, "fee_usd": 0, "shares": 111.482719, "market": "Will Zohran Mamdani win the 2025 NYC mayoral election?", "market_slug": "will-zohran-mamdani-win-the-2025-nyc-mayoral-election", "outcome": "Yes", "condition_id": "0xebddfcf7b4401dade8b4031770a1ab942b01854f3bed453d5df9425cd9f211a9", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-zohran-mamdani-win-the-2025-nyc-mayoral-election-EscSJQTT6hWg.jpg" } ] } ``` You can also filter by `condition_id` to get both outcomes of a market: ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?condition_id=0xebddfcf7b4401dade8b4031770a1ab942b01854f3bed453d5df9425cd9f211a9&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ### Large trades Use `min_total` to find trades above a USD threshold. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?min_total=100&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 1, "pagination": { "limit": 1, "has_more": true, "pagination_key": "0xffffffeb...a0017d41..." }, "trades": [ { "timestamp": 1759503806, "tx_hash": "0xffffffeb7983b64a9394a0485c897113ad17ffca0fde8f3fa16aa045396d0582", "order_hash": "0xa0017d41adb20f9cb729243b8d8464218d3f2a9e8d24c8e53f36c744c9f250a7", "maker": "0x12d6cccfc7470a3f4bafc53599a4779cbf2cf2a8", "taker": "0xe05d8c348aee0323cf115c18006a35db54ba2685", "token_id": "33945469250963963541781051637999677727672635213493648594066577298999471399137", "price": 0.897, "amount_usd": 100, "fee_usd": 0, "shares": 111.482719, "market": "Will Zohran Mamdani win the 2025 NYC mayoral election?", "market_slug": "will-zohran-mamdani-win-the-2025-nyc-mayoral-election", "outcome": "Yes", "condition_id": "0xebddfcf7b4401dade8b4031770a1ab942b01854f3bed453d5df9425cd9f211a9", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-zohran-mamdani-win-the-2025-nyc-mayoral-election-EscSJQTT6hWg.jpg" } ] } ``` ### Time range Use `start_time` and `end_time` (Unix timestamps) to query a specific window. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?start_time=1775600000&end_time=1775700000&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ### Combined filters Combine any filters. For example, a wallet's trades on a specific market: ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&market_slug=tur-goz-gal-2026-04-08-goz&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ### Pagination Pass the `pagination_key` from the previous response to get the next page. ```bash theme={null} # First page curl "https://api.polynode.dev/v2/onchain/trades?limit=100" \ -H "x-api-key: YOUR_KEY" # Next page curl "https://api.polynode.dev/v2/onchain/trades?limit=100&pagination_key=CURSOR_FROM_PREVIOUS" \ -H "x-api-key: YOUR_KEY" ``` ### Sort by order Use `sort_by=order_hash` to cluster fills from the same limit order together. A single limit order can be filled across many transactions over time. This sort groups all those partial fills adjacently, sorted by timestamp within each order. Orders are ranked by their most recent fill. Every fill is still returned individually with all fields. No data is collapsed or aggregated. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&sort_by=order_hash&limit=100" \ -H "x-api-key: YOUR_KEY" ``` ### Group by order Use `group_by=order_hash` to aggregate all fills from the same limit order into a single row. Each row contains summed totals, a VWAP price, fill count, time range, and a list of transaction hashes. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&group_by=order_hash&limit=100" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "count": 76, "source": "onchain-v2-grouped", "trades": [ { "order_hash": "0x7f69046bdbb2a595667e7ffe24ea285f87f95f7d146333dbc8a7e02948bbe52b", "fill_count": 12, "total_amount_usd": 208.76, "total_shares": 353.82, "avg_price": 0.59, "total_fee_usd": 0.0, "first_fill_at": 1778409433, "last_fill_at": 1778414041, "timestamp": 1778414041, "token_id": "102860925866954003158841129327041711410011624382962867117087237151352260776640", "maker": "0x6ac5bb06a9eb05641fd5e82640268b92f3ab4b6e", "side": "maker", "direction": "BUY", "market": "Pistons vs. Cavaliers", "market_slug": "nba-det-cle-2026-05-11", "outcome": "Cavaliers", "condition_id": "0x52f953bd31997875e5f782fbed7f85b8707aa8fefe95b6854cf5b8c69370b3f0", "tx_hashes": ["0xa7fdeb87...", "0xbb9092bc...", "..."] } ] } ``` #### Grouped trade fields | Field | Type | Description | | - | - | - | | `order_hash` | string | The CLOB order hash (grouping key) | | `fill_count` | number | Number of individual fills aggregated into this row | | `total_amount_usd` | number | Sum of all fill sizes in USD | | `total_shares` | number | Sum of all outcome shares traded | | `avg_price` | number | Volume-weighted average price (`total_amount_usd / total_shares`) | | `total_fee_usd` | number | Sum of all fees in USD | | `first_fill_at` | number | Unix timestamp of the earliest fill | | `last_fill_at` | number | Unix timestamp of the most recent fill | | `timestamp` | number | Same as `last_fill_at` (for compatibility with default sort) | | `tx_hashes` | string\[] | List of unique transaction hashes for all fills | | `token_id` | string | Outcome token ID | | `maker` | string | Maker address (from the first fill) | | `side` | string | Exchange role (from the first fill) | | `direction` | string | Trade direction (from the first fill) | | `market` | string | Market question text | | `market_slug` | string | Market URL slug | | `outcome` | string | Outcome label | | `condition_id` | string | Market condition ID | | `image` | string \| null | Market image URL | ### Oldest first Use `order=asc` to get trades in chronological order. Requires at least one filter. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0xa973ae12882a1c24a75da7a3b52cb01500b2f639&order=asc&limit=10" \ -H "x-api-key: YOUR_KEY" ``` ## Error responses | Status | Response | Condition | | - | - | - | | 400 | `{"error": "order=asc requires at least one filter (wallet, token_id, condition_id, market_slug, or start_time)."}` | `order=asc` without any filter | | 400 | `{"error": "market_slug not found"}` | Invalid or unknown `market_slug` | | 400 | `{"error": "condition_id not found"}` | Invalid or unknown `condition_id` | | 401 | `{"error": "API key required. Pass via ?key= or x-api-key header."}` | Missing API key | | 403 | `{"error": "V2 endpoints require a paid plan. See polynode.dev/pricing for details."}` | Free tier key | | 429 | `{"error": "Rate limited. N req/s for your tier.", "retryAfterMs": ...}` | Rate limited | ## Notes * Without filters, defaults to the last 24 hours for performance. Add `start_time` to query further back. * The `side` field is only included when filtering by `wallet`. Without a wallet filter, there is no perspective to assign a side from. * Market metadata (`market`, `market_slug`, `outcome`, `condition_id`, `image`) is enriched from our index. Very old or delisted markets may not have metadata. * Results are sourced from onchain settlement data. Every fill that settled on Polygon is included. # Wallet Activity Source: https://docs.polynode.dev/api-reference/onchain/wallet-activity GET /v2/onchain/wallets/{address}/activity Onchain activity for a wallet: splits, merges, and multi-outcome conversions. Returns all onchain activity for a wallet including token splits (minting outcome tokens from collateral), merges (burning outcome tokens back to collateral), and neg-risk conversions (multi-outcome market hedging). Each event is enriched with market metadata. This data is not available through Polymarket's API. ## Request ``` GET /v2/onchain/wallets/{address}/activity?limit=100&offset=0 ``` | Parameter | Type | Location | Description | | - | - | - | - | | `address` | string | path | Wallet address (0x-prefixed, 40 hex chars) | | `limit` | integer | query | Max results (default 100, max 1000) | | `offset` | integer | query | Skip first N results for pagination | ## Response ```json theme={null} { "wallet": "0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa", "source": "onchain", "count": 1, "offset": 0, "splits": 0, "merges": 1, "conversions": 0, "events": [ { "type": "merge", "id": "0x583037e505fc38851d81fc129d2eef0cb57a81270d7b5cb9f500dca9a3f898e9_0x5fd", "timestamp": 1774715707, "condition": "0xe84334d8b082ddf50a6aa659bb19283ac94edfd52a5357fb7547c0371bb18084", "amount": 5, "market": "Bitcoin Up or Down - March 28, 12:30PM-12:35PM ET", "slug": "btc-updown-5m-1774715400", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png" } ] } ``` | Field | Type | Description | | - | - | - | | `splits` | number | Count of split events in this page | | `merges` | number | Count of merge events in this page | | `conversions` | number | Count of neg-risk conversion events in this page | | `events[].type` | string | `"split"`, `"merge"`, or `"neg_risk_conversion"` | | `events[].timestamp` | number | Unix timestamp | | `events[].condition` | string | Condition ID | | `events[].amount` | number | USDC amount | | `events[].market` | string | Market question | | `events[].slug` | string | Market slug | | `events[].image` | string | Market image URL | | `events[].neg_risk_market_id` | string | Neg-risk market ID (conversions only) | | `events[].index_set` | string | Index set (conversions only) | | `events[].question_count` | number | Questions in the neg-risk event (conversions only) | ## Event Types **Split** — Collateral deposited and split into outcome tokens. This is how positions are entered via the CTF contract (as opposed to buying on the orderbook). **Merge** — Outcome tokens burned back into collateral. The inverse of a split. Often used when exiting a hedged position. **Neg-risk conversion** — Converting between outcome tokens in a multi-outcome market (e.g., "Who will win the election?" with 5+ candidates). Used for hedging and arbitrage. ## Example ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/wallets/0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa/activity?limit=50" \ -H "x-api-key: YOUR_KEY" ``` # Wallet Redemptions Source: https://docs.polynode.dev/api-reference/onchain/wallet-redemptions GET /v2/onchain/wallets/{address}/redemptions All onchain redemptions for a wallet. See who cashed out, when, and how much. Returns every onchain redemption for a wallet. A redemption is when a user claims their payout after a market resolves. This data is not available through Polymarket's API. Each redemption is enriched with market metadata. ## Request ``` GET /v2/onchain/wallets/{address}/redemptions?limit=100&offset=0 ``` | Parameter | Type | Location | Description | | - | - | - | - | | `address` | string | path | Wallet address (0x-prefixed, 40 hex chars) | | `limit` | integer | query | Max results (default 100, max 1000) | | `offset` | integer | query | Skip first N results for pagination | ## Response ```json theme={null} { "wallet": "0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa", "source": "onchain", "count": 1, "offset": 0, "total_payout": 5, "redemptions": [ { "id": "0x655555bc5091e07a453667c20afe4af5df2e099311670abf86a718dc48998b53_0x678", "timestamp": 1774749134, "condition": "0xedb2d159f7917cedf2ca9fe5b2fe70ba5db7fee23eff951ce8d7f96983cf6a66", "index_sets": ["1", "2"], "payout": 5, "market": "Bitcoin Up or Down - March 28, 9:45PM-9:50PM ET", "slug": "btc-updown-5m-1774748700", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png" } ] } ``` | Field | Type | Description | | - | - | - | | `total_payout` | number | Sum of all payout amounts (USDC) in this page | | `redemptions[].timestamp` | number | Unix timestamp of the redemption | | `redemptions[].condition` | string | Condition ID of the resolved market | | `redemptions[].index_sets` | array | Outcome index sets redeemed | | `redemptions[].payout` | number | USDC payout amount (0 = losing position redeemed) | | `redemptions[].market` | string | Market question | | `redemptions[].slug` | string | Market slug | | `redemptions[].image` | string | Market image URL | ## Example ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/wallets/0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa/redemptions?limit=10" \ -H "x-api-key: YOUR_KEY" ``` # Trade History (Wallet) Source: https://docs.polynode.dev/api-reference/onchain/wallet-trades GET /v2/onchain/wallets/{address}/trades Complete onchain trade fill history for any wallet. Every fill, every counterparty, every fee. Returns every onchain trade fill for a wallet — both maker and taker sides, every fill, every counterparty, every fee. Pulled directly from onchain settlement data, never misses a fill. Each trade is enriched with market metadata (question, slug, outcome, image). > [!TIP] > > **Want the entire wallet's history in one call?** Use [Trade History (Wallet) — Bulk](/api-reference/onchain/wallet-trades-all) (Growth plan and above). Returns up to 250K trades in a single response, no pagination. ## Quick start — get the most recent 100 trades ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/wallets/{address}/trades?limit=100" \ -H "x-api-key: YOUR_KEY" ``` Default `limit=100`, max `limit=1000`. That's all most apps need. ## Get every trade for the wallet (full history) To walk the entire history, add `?cursor=` (empty value) to the first request, then **for each next page, copy `pagination.cursor` from the response back into the URL**. Stop when `pagination.has_more` is `false`. Three complete copy-paste scripts that walk an entire wallet: ```python Python theme={null} import requests API_KEY = "YOUR_KEY" WALLET = "0xc944d399164b4460a4a79184fc6f419027891e0a" def get_all_trades(wallet): cursor = "" # empty string = first page all_trades = [] while True: r = requests.get( f"https://api.polynode.dev/v2/onchain/wallets/{wallet}/trades", params={"limit": 1000, "cursor": cursor}, headers={"x-api-key": API_KEY}, ).json() all_trades.extend(r["trades"]) if not r["pagination"]["has_more"]: break cursor = r["pagination"]["cursor"] # feed this into the next request return all_trades trades = get_all_trades(WALLET) print(f"got {len(trades)} trades") ``` ```javascript JavaScript theme={null} const API_KEY = "YOUR_KEY"; const WALLET = "0xc944d399164b4460a4a79184fc6f419027891e0a"; async function getAllTrades(wallet) { let cursor = ""; // empty string = first page const allTrades = []; while (true) { const url = `https://api.polynode.dev/v2/onchain/wallets/${wallet}/trades` + `?limit=1000&cursor=${encodeURIComponent(cursor)}`; const r = await fetch(url, { headers: { "x-api-key": API_KEY } }).then(r => r.json()); allTrades.push(...r.trades); if (!r.pagination.has_more) break; cursor = r.pagination.cursor; // feed this into the next request } return allTrades; } const trades = await getAllTrades(WALLET); console.log(`got ${trades.length} trades`); ``` ```bash bash theme={null} KEY="YOUR_KEY" WALLET="0xc944d399164b4460a4a79184fc6f419027891e0a" CURSOR="" TOTAL=0 while true; do RESP=$(curl -s "https://api.polynode.dev/v2/onchain/wallets/$WALLET/trades?limit=1000&cursor=$CURSOR" \ -H "x-api-key: $KEY") COUNT=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['count'])") HAS_MORE=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['pagination']['has_more'])") TOTAL=$((TOTAL + COUNT)) echo "got $COUNT trades, total: $TOTAL" [ "$HAS_MORE" = "False" ] && break CURSOR=$(echo "$RESP" | python3 -c "import json,sys;print(json.load(sys.stdin)['pagination']['cursor'])") done ``` Each page takes \~1 second regardless of how many trades the wallet has. The loop just keeps running until `has_more` is `false`. ## Request ``` GET /v2/onchain/wallets/{address}/trades?limit=100 GET /v2/onchain/wallets/{address}/trades?limit=1000&cursor= ``` | Parameter | Type | Location | Description | | - | - | - | - | | `address` | string | path | Wallet address (0x-prefixed, 40 hex chars) | | `limit` | integer | query | Max results per page (default 100, max 1000) | | `cursor` | string | query | Pass empty string `?cursor=` for first page, then echo back `pagination.cursor` from each response. Required to walk past the first page reliably on heavy wallets. | | `offset` | integer | query | Alternative to cursor: skip first N. Fast for the first \~25K results then degrades. Use `cursor` for anything bigger. | ## Response ```json theme={null} { "wallet": "0xc944d399164b4460a4a79184fc6f419027891e0a", "source": "onchain", "count": 1, "pagination": { "limit": 1000, "has_more": false }, "trades": [ { "tx_hash": "0x3611178d615caeab8f1fb32bc6232a32aaf93fc1e2f5bc5c9914ce2ddb9a13c3", "order_hash": "0x8676e03168a3cbf39bc1c695e9419127605bd070ff26e7cd628b662c363a82b5", "timestamp": 1777503244, "maker": "0xc944d399164b4460a4a79184fc6f419027891e0a", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "maker_asset_id": "0", "taker_asset_id": "110959653450933276250915064669875552310439627880508793089816880777942697720191", "maker_amount": 4723.199764, "taker_amount": 4737.412, "fee": 0, "side": "maker", "direction": "BUY", "market": "US x Iran ceasefire extended by April 22, 2026?", "slug": "us-x-iran-ceasefire-extended-by-april-22-2026", "outcome": "No", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/us-x-iran-ceasefire-by-Cgmx3GCuOwjs.jpg" } ] } ``` When `pagination.has_more` is `true`, the response also includes a `pagination.cursor` string — pass that as `?cursor=` for the next request. | Field | Type | Description | | - | - | - | | `count` | integer | Number of trades in this response | | `pagination.has_more` | boolean | `true` if more pages available — keep paginating | | `pagination.cursor` | string | Pass back as `?cursor=` for the next page (only present when `has_more` is `true`) | | `trades[].tx_hash` | string | Transaction hash | | `trades[].timestamp` | number | Unix timestamp of the fill | | `trades[].order_hash` | string | Order hash that was filled | | `trades[].maker` | string | Maker wallet address | | `trades[].taker` | string | Taker wallet address | | `trades[].maker_asset_id` | string | Asset the maker provided (`"0"` = USDC) | | `trades[].taker_asset_id` | string | Asset the taker provided (CTF token ID) | | `trades[].maker_amount` | number | Amount maker provided (USDC) | | `trades[].taker_amount` | number | Amount taker provided (tokens) | | `trades[].fee` | number | Fee paid on this fill (USDC) | | `trades[].side` | string | `"maker"` or `"taker"` relative to the queried wallet — exchange role on this fill | | `trades[].direction` | string | `"BUY"` or `"SELL"` from the queried wallet's perspective. `BUY` = wallet contributed USDC and received outcome tokens. `SELL` = wallet contributed outcome tokens and received USDC. | | `trades[].market` | string | Market question | | `trades[].slug` | string | Market slug | | `trades[].outcome` | string | Outcome label (e.g. "Yes", "Up", "Trump") | | `trades[].image` | string | Market image URL | ## `side` vs `direction` Both fields are populated on every row, and they answer different questions: * **`side`** = was the wallet the **maker** (resting limit order) or **taker** (crossing the spread) on this fill? * **`direction`** = did the wallet **BUY** outcome shares (gave USDC) or **SELL** them (received USDC)? You'll see all four combinations in real wallets — a maker can be a buyer or seller depending on which side of the orderbook they posted to. Same for takers. # Trade History (Wallet) — Bulk Source: https://docs.polynode.dev/api-reference/onchain/wallet-trades-all GET /v2/onchain/wallets/{address}/trades/all Return every trade for a wallet in a single response. Growth plan or above. > [!WARNING] > > **Growth plan or above only.** This endpoint returns the **entire** trade history for a wallet in **one response** — no client-side pagination, no offset bookkeeping. Because a single call can return tens of thousands of fills (and tens of MB of JSON), it's gated to the **Growth plan and above**. Starter and free tier requests receive `403`. > > * Hard cap: **250,000 trades per call** — beyond that, response includes `"partial": true` with `"partial_reason": "hard_cap_250000"` > * Wall-clock budget: **180 seconds** — first cold-cache call on a heavy wallet may take 1-3 minutes > * Cache: full results cached **5 minutes**. Repeat calls return in under 1 second > * Typical payload: 1-50 MB. Worst case (capped): 100-200 MB JSON Returns every onchain trade fill for a wallet in a single response — both maker and taker sides, every counterparty, every fee, complete history. The server walks the full trade record with parallel time-bucketed queries server-side; you don't need to paginate. This is the right endpoint for **bulk-export** of a wallet for analysis, indexing, or backtesting. For interactive UIs that just need the most recent N trades, use the standard [Wallet Trade History](/api-reference/onchain/wallet-trades) instead. ## Request ``` GET /v2/onchain/wallets/{address}/trades/all?from=&to= ``` | Parameter | Type | Location | Description | | - | - | - | - | | `address` | string | path | Wallet address (0x-prefixed, 40 hex chars) | | `from` | integer | query | Optional start of window in unix seconds. Default: 2024-01-01 (covers all Polymarket history) | | `to` | integer | query | Optional end of window in unix seconds. Default: now | ## Response ```json theme={null} { "wallet": "0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa", "from_ts": 1704067200, "to_ts": 1777600000, "count": 8421, "partial": false, "partial_reason": null, "fetched_in_ms": 7813, "cache": "miss", "trades": [ { "tx_hash": "0x2fc63f3efc794d13c747d089d3b42bb9b4539b22216ccb2e6b2ea039ca5bb9ca", "order_hash": "0x84f21e21f5c2a1df3264694a33ec9a8a292b83e163cbda4efe63333243aa08ef", "timestamp": 1774749310, "maker": "0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa", "taker": "0x198098d9c6c1dcb843314b9da212c44396c9a1d0", "token_id": "21912724974096796009916816278814088615574660931588091764221331842149572809887", "direction": "BUY", "price": 0.625, "shares": 4.88, "usd": 3.05, "fee": 0 } ] } ``` ## Response fields | Field | Type | Description | | - | - | - | | `wallet` | string | The wallet address requested (lowercased) | | `from_ts` / `to_ts` | integer | Resolved time window in unix seconds | | `count` | integer | Total trades returned (≤ 250,000) | | `partial` | boolean | `true` if either the 250K hard cap or the 180s wall-clock budget was hit before the full window was walked | | `partial_reason` | string \| null | `"hard_cap_250000"` or `"wall_clock_180s"` when partial; otherwise `null` | | `fetched_in_ms` | integer | Server-side fetch time. Cached calls show the original miss time | | `cache` | string | `"hit"` if served from Redis cache, `"miss"` if freshly walked | | `trades` | array | All trades, sorted by `timestamp` descending (newest first) | ## Trade fields | Field | Type | Description | | - | - | - | | `tx_hash` | string | Polygon transaction hash | | `order_hash` | string | Order hash from the exchange | | `timestamp` | integer | Unix seconds when the fill settled | | `maker` | string | Maker address | | `taker` | string | Taker address | | `token_id` | string | The outcome token id traded in this fill | | `direction` | string | `"BUY"` or `"SELL"` from the maker's perspective | | `price` | number | USDC per share, 4-decimal precision | | `shares` | number | Outcome tokens traded | | `usd` | number | USDC notional | | `fee` | number | Maker fee paid (USDC) | ## Example: full lifetime trade history of a wallet ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/wallets/0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa/trades/all?key=$YOUR_KEY" ``` ## Example: only trades from the last 30 days ```bash theme={null} NOW=$(date +%s); FROM=$((NOW - 2592000)) curl "https://api.polynode.dev/v2/onchain/wallets/0x2f5653a3761f65c5a299f9839eadbd4d4d679ffa/trades/all?from=$FROM&to=$NOW&key=$YOUR_KEY" ``` ## Errors `403 Tier required`: ```json theme={null} { "error": "/trades/all requires the Growth plan or above. Your tier: starter. See polynode.dev/pricing." } ``` `401 No API key`: ```json theme={null} { "error": "API key required. Pass via ?key= or x-api-key header." } ``` ## Notes * `partial: true` results are **not cached**. Subsequent calls re-attempt the full walk. Tighten the time window with `from`/`to` if you keep hitting the cap. * Cache key is `(wallet, from_ts, to_ts)`. Different windows cached independently. * For wallets that consistently exceed the 250K cap, slice into multiple windowed calls and concatenate client-side. Each window cached separately for 5 minutes. * Trades include both maker AND taker sides — every fill the wallet was involved in. No double-counting. # Midpoint Price Source: https://docs.polynode.dev/api-reference/orderbook/midpoint GET /v1/midpoint/{token_id} Returns the midpoint price for a token, calculated as the average of the best bid and best ask. If the book is one-sided (only bids or only asks), the missing side is treated as 0. Response is enriched with PolyNode market metadata. Returns the midpoint price for a token or market, calculated as the average of the best bid and best ask. ## Identifier types The `{token_id}` parameter accepts three types: | Identifier | Format | Returns | | - | - | - | | **Token ID** | All digits, 70+ chars | Single midpoint (Polymarket-compatible) | | **Condition ID** | Starts with `0x` | Midpoints for both outcomes | | **Slug** | Human-readable string | Midpoints for all outcomes in the event | ### By token ID ```bash theme={null} curl "https://api.polynode.dev/v1/midpoint/114694726451307654528948558967898493662917070661203465131156925998487819889437" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "mid": "0.465", "token_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "question": "Netanyahu out by end of 2026?", "slug": "netanyahu-out-before-2027-684-719-226" } ``` ### By condition ID ```bash theme={null} curl "https://api.polynode.dev/v1/midpoint/0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "condition_id": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "question": "Netanyahu out by end of 2026?", "event_title": "Netanyahu out by...?", "outcomes": [ {"outcome": "Yes", "token_id": "11469472645...", "mid": "0.465"}, {"outcome": "No", "token_id": "66255671088...", "mid": "0.535"} ] } ``` ## Calculation ``` midpoint = (best_bid + best_ask) / 2 ``` If the book is one-sided (only bids or only asks), the missing side is treated as 0. This matches Polymarket's behavior. ## Notes * The `mid` value is a decimal string (e.g. `"0.465"`). * Returns a 404 if no book exists for the identifier. # Order Book Source: https://docs.polynode.dev/api-reference/orderbook/order-book GET /v1/orderbook/{token_id} Returns the full order book for a token, including all bid and ask price levels, market properties, and PolyNode metadata enrichment. The response format is compatible with Polymarket's CLOB API. Data is served from PolyNode's live orderbook engine, which maintains real-time state via WebSocket deltas from Polymarket. Returns the full order book for a Polymarket token or market. ## Identifier types The `{token_id}` parameter accepts three identifier types. The response format depends on which type you use: | Identifier | Format | Returns | | - | - | - | | **Token ID** | All digits, 70+ chars | Single book for one outcome (Polymarket-compatible) | | **Condition ID** | Starts with `0x` | Both outcomes for one market (Yes + No) | | **Slug** | Human-readable string | All outcomes across all markets in the event | ### By token ID (single outcome) Best when you already have a specific token ID and want the exact Polymarket-compatible format. ```bash theme={null} curl "https://api.polynode.dev/v1/orderbook/114694726451307654528948558967898493662917070661203465131156925998487819889437" \ -H "x-api-key: YOUR_KEY" ``` Response matches Polymarket's CLOB `/book` format exactly, plus a `metadata` field: ```json theme={null} { "market": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "asset_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "timestamp": "1773901991806", "hash": "b811dc1233a0f250a60018bc94f377955c9a513e", "bids": [ {"price": "0.01", "size": "1130220"}, {"price": "0.02", "size": "76910"}, {"price": "0.46", "size": "18"} ], "asks": [ {"price": "0.99", "size": "24292"}, {"price": "0.98", "size": "2048"}, {"price": "0.47", "size": "687"} ], "min_order_size": "5", "tick_size": "0.01", "neg_risk": false, "last_trade_price": "0.540", "metadata": { "question": "Netanyahu out by end of 2026?", "slug": "netanyahu-out-before-2027-684-719-226", "outcomes": ["Yes", "No"], "condition_id": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/netanyahu-out-in-2025-Vc7bE4GtiJzM.jpg" } } ``` ### By condition ID (both outcomes) Best when you want both sides of a market at once. Condition IDs start with `0x`. ```bash theme={null} curl "https://api.polynode.dev/v1/orderbook/0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96" \ -H "x-api-key: YOUR_KEY" ``` Response wraps both outcomes: ```json theme={null} { "condition_id": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "question": "Netanyahu out by end of 2026?", "event_title": "Netanyahu out by...?", "outcomes": [ { "outcome": "Yes", "token_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "market": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "bids": [{"price": "0.01", "size": "1130220"}, "..."], "asks": [{"price": "0.99", "size": "24292"}, "..."], "min_order_size": "5", "tick_size": "0.01", "neg_risk": false, "last_trade_price": "0.540" }, { "outcome": "No", "token_id": "66255671088804707681511323064315150986307471908131081808279119719218775249892", "market": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "bids": [{"price": "0.01", "size": "821530"}, "..."], "asks": [{"price": "0.99", "size": "13720.65"}, "..."], "min_order_size": "5", "tick_size": "0.01", "neg_risk": false, "last_trade_price": "0.540" } ] } ``` ### By slug (all outcomes across markets) Best for getting a complete view of an event. Slugs are the human-readable event identifiers from Polymarket (e.g. `netanyahu-out-before-2027`). An event may have multiple markets, each with their own outcomes. ```bash theme={null} curl "https://api.polynode.dev/v1/orderbook/netanyahu-out-before-2027" \ -H "x-api-key: YOUR_KEY" ``` Response includes all outcomes across all markets in the event. Same format as the condition ID response, but with `slug` instead of `condition_id` at the top level. ## Fields (single-token response) | Field | Type | Description | | - | - | - | | `market` | string | Market condition ID (hex) | | `asset_id` | string | Token ID | | `timestamp` | string | Unix timestamp in milliseconds | | `hash` | string | 40-character hex hash of the book state | | `bids` | array | Bid price levels, sorted ascending by price | | `asks` | array | Ask price levels, sorted descending by price | | `min_order_size` | string | Minimum order size for this market | | `tick_size` | string | Minimum price increment (e.g. `"0.01"` or `"0.001"`) | | `neg_risk` | boolean | Whether this is a neg-risk market | | `last_trade_price` | string | Last traded price | | `metadata` | object | PolyNode enrichment: question, slug, outcomes, condition\_id, image | ## Notes * `tick_size` and `min_order_size` vary per market. They are sourced from the Gamma API, not hardcoded. * Bids are sorted ascending by price (best bid is the last element). Asks are sorted descending (best ask is the last element). This matches Polymarket's sort order. * If no book exists for the requested identifier, returns a 404 with `{"error": "No orderbook exists for the requested token id"}`. # Bid-Ask Spread Source: https://docs.polynode.dev/api-reference/orderbook/spread GET /v1/spread/{token_id} Returns the bid-ask spread for a token, calculated as the difference between the best ask and best bid price. For one-sided books, the spread equals the best price on the existing side. Response is enriched with PolyNode market metadata. Returns the bid-ask spread for a token or market, calculated as the difference between the best ask and best bid. ## Identifier types The `{token_id}` parameter accepts three types: | Identifier | Format | Returns | | - | - | - | | **Token ID** | All digits, 70+ chars | Single spread (Polymarket-compatible) | | **Condition ID** | Starts with `0x` | Spreads for both outcomes | | **Slug** | Human-readable string | Spreads for all outcomes in the event | ### By token ID ```bash theme={null} curl "https://api.polynode.dev/v1/spread/114694726451307654528948558967898493662917070661203465131156925998487819889437" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "spread": "0.01", "token_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "question": "Netanyahu out by end of 2026?", "slug": "netanyahu-out-before-2027-684-719-226" } ``` ### By condition ID ```bash theme={null} curl "https://api.polynode.dev/v1/spread/0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "condition_id": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "question": "Netanyahu out by end of 2026?", "event_title": "Netanyahu out by...?", "outcomes": [ {"outcome": "Yes", "token_id": "11469472645...", "spread": "0.01"}, {"outcome": "No", "token_id": "66255671088...", "spread": "0.01"} ] } ``` ## Calculation ``` spread = best_ask - best_bid ``` For one-sided books (only bids or only asks), the spread equals the best price on the existing side. ## Notes * The `spread` value is a decimal string (e.g. `"0.01"`). * Returns a 404 if no book exists for the identifier. # API Reference Source: https://docs.polynode.dev/api-reference/overview Start here for PolyNode REST APIs: V3 Polymarket data, wallet analytics, market data, orderbook snapshots, profiles, search, and legacy endpoints. PolyNode exposes authenticated REST APIs for Polymarket market data, wallet analytics, positions, trades, builders, orderbooks, profiles, search, and supporting tools. ## Core APIs | API | Use it for | | - | - | | [V3 Data API](/data/overview) | Polymarket markets, positions, trades, wallet P\&L, builders, combos, rewards, tags, fees, and global stats. | | [Wallet P\&L](/data/wallets/summary) | Wallet summaries, realized P\&L, P\&L events, open positions, and wallet activity. | | [Markets & Search](/data/markets/search) | Market discovery, condition lookups, market-level positions, prices, trades, and candles. | | [Orderbook](/api-reference/orderbook/order-book) | Current orderbook, midpoint, and spread snapshots. | | [Profiles](/api-reference/polymarket-profiles/overview) | Polymarket profile lookup and username setup flows. | | [Onchain V2](/api-reference/onchain/trades) | Legacy onchain V2 trade, position, redemption, volume, and candle endpoints. | ## Base URLs | Surface | Base URL | | - | - | | REST API | `https://api.polynode.dev` | | WebSocket streams | `wss://polynode.dev/ws` | | Orderbook stream | `wss://polynode.dev/orderbook/ws` | ## Authentication Send your API key with either `x-api-key`, `Authorization: Bearer `, or `?key=`. ## Rate Limits REST and streaming limits vary by plan. See [Rate Limits](/guides/rate-limits) for the current public limits, including the separate bucket for heavy trade-history endpoints. # Complete Username Action Source: https://docs.polynode.dev/api-reference/polymarket-profiles/complete-username POST /v3/polymarket/profiles/username/complete Submit wallet signatures and create or change the user's Polymarket username. ```text theme={null} POST /v3/polymarket/profiles/username/complete ``` Completes a previously created username challenge. This endpoint consumes the challenge atomically, verifies both wallet signatures, logs in to Polymarket, creates the profile if needed, and sets the username. > [!WARNING] > > Call this from your backend with the same PolyNode API key that created the challenge. Do not call it directly from the browser. ## Request ```json theme={null} { "challenge_id": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "polymarket_signature": "0x...", "consent_signature": "0x..." } ``` | Field | Type | Required | Description | | - | - | - | - | | `challenge_id` | string | Yes | Challenge id returned by the challenge endpoint | | `address` | string | Yes | Same EOA address used in the challenge | | `username` | string | Yes | Same username used in the challenge | | `polymarket_signature` | string | Yes | Signature of `challenge.polymarket.message` using `personal_sign` | | `consent_signature` | string | Yes | Signature of `challenge.consent` using `eth_signTypedData_v4` | ## Example ```bash theme={null} curl -X POST "https://api.polynode.dev/v3/polymarket/profiles/username/complete" \ -H "content-type: application/json" \ -H "x-api-key: pn_live_..." \ -d '{ "challenge_id": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "polymarket_signature": "0x...", "consent_signature": "0x..." }' ``` ## Response ```json theme={null} { "status": "success", "action": "set_username", "username": "alice123", "address": "0xc3579b0c908f43d50c63951a30c6f72fcea4f6a0", "deposit_wallet": "0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31", "safe_address": "0xba2ef45d0fe68cee6351420b60fb554bbe91bf02", "gamma_user_id": "8313180", "gamma_profile_id": "8391726", "created_profile": true, "changed_username": true, "profile_url": "https://polymarket.com/profile/0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31" } ``` | Field | Type | Description | | - | - | - | | `status` | string | `success` | | `action` | string | `set_username` | | `username` | string | Final requested username | | `address` | string | EOA address, lowercase | | `deposit_wallet` | string | Deterministic Polymarket deposit wallet | | `safe_address` | string | Deterministic Safe address checked during challenge | | `gamma_user_id` | string or null | Polymarket Gamma user id if returned | | `gamma_profile_id` | string or null | Polymarket Gamma profile id if returned | | `created_profile` | boolean | `true` if PolyNode created a new Gamma profile | | `changed_username` | boolean | `true` if PolyNode changed the profile name | | `profile_url` | string | Polymarket profile URL using the deposit wallet address | ## Server checks The endpoint: * loads and consumes the challenge atomically * requires the same PolyNode API key hash that created the challenge * requires exact address, username, action, and challenge id match * verifies the challenge is not expired * recovers the signer from the Polymarket SIWE signature * recovers the signer from the PolyNode consent typed-data signature * requires both recovered addresses to equal the challenge EOA * re-checks username availability unless the current profile already has that username ## Errors | Status | Code | Meaning | | - | - | - | | `400` | `challenge_mismatch` | API key, address, username, action, or challenge id did not match | | `400` | `challenge_expired` | Challenge is older than 10 minutes | | `400` | `signature_invalid` | A signature was malformed or recovered to the wrong address | | `404` | `challenge_not_found` | Challenge was missing, already consumed, or expired from Redis | | `409` | `username_taken` | Username became unavailable before completion | | `409` | `safe_already_deployed` | Derived Safe is deployed but Gamma did not return a user for the session | | `403` | `polymarket_compliance_blocked` | Polymarket rejected the action for compliance or eligibility reasons | | `429` | `rate_limited` | Profile-specific rate limit exceeded | | `502` | `polymarket_login_failed`, `polymarket_profile_create_failed`, `polymarket_profile_update_failed`, or `upstream_unavailable` | Upstream action failed | # Create Username Challenge Source: https://docs.polynode.dev/api-reference/polymarket-profiles/create-challenge POST /v3/polymarket/profiles/username/challenge Create the wallet-signing challenge for a Polymarket username create or update. ```text theme={null} POST /v3/polymarket/profiles/username/challenge ``` Creates a one-time challenge for a user-owned EOA. The response contains: * a Polymarket SIWE message to sign with `personal_sign` * a PolyNode consent typed-data payload to sign with `eth_signTypedData_v4` * derived deposit wallet and Safe addresses The challenge expires after 10 minutes. ## Request ```json theme={null} { "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "action": "set_username" } ``` | Field | Type | Required | Description | | - | - | - | - | | `address` | string | Yes | User EOA address | | `username` | string | Yes | Desired username | | `action` | string | No | Must be `set_username`. Defaults to `set_username`. | ## Example ```bash theme={null} curl -X POST "https://api.polynode.dev/v3/polymarket/profiles/username/challenge" \ -H "content-type: application/json" \ -H "x-api-key: pn_live_..." \ -d '{ "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "action": "set_username" }' ``` ## Response ```json theme={null} { "challenge_id": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "action": "set_username", "expires_at": "2026-05-26T13:03:06Z", "polymarket": { "signature_type": "personal_sign", "message": "polymarket.com wants you to sign in with your Ethereum account:\n0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0\n\nWelcome to Polymarket! Sign to connect.\n\nURI: https://polymarket.com\nVersion: 1\nChain ID: 137\nNonce: 4b7d...\nIssued At: 2026-05-26T12:53:06.000Z\nExpiration Time: 2026-06-02T12:53:06.000Z", "fields": { "domain": "polymarket.com", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "statement": "Welcome to Polymarket! Sign to connect.", "uri": "https://polymarket.com", "version": "1", "chainId": 137, "nonce": "4b7d...", "issuedAt": "2026-05-26T12:53:06.000Z", "expirationTime": "2026-06-02T12:53:06.000Z" } }, "consent": { "signature_type": "typed_data_v4", "domain": { "name": "Polynode", "version": "1", "chainId": 137 }, "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" } ], "PolymarketProfileAction": [ { "name": "action", "type": "string" }, { "name": "address", "type": "address" }, { "name": "username", "type": "string" }, { "name": "challengeId", "type": "string" }, { "name": "expiresAt", "type": "uint256" } ] }, "primaryType": "PolymarketProfileAction", "message": { "action": "set_username", "address": "0xc3579b0c908f43d50c63951a30c6f72fcea4f6a0", "username": "alice123", "challengeId": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "expiresAt": 1779800586 } }, "derived": { "deposit_wallet": "0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31", "safe_address": "0xba2ef45d0fe68cee6351420b60fb554bbe91bf02", "safe_deployed": false } } ``` ## Server checks The endpoint: * validates address and username format * checks Polymarket username availability * fetches a Gamma nonce * builds the exact Polymarket SIWE message * builds PolyNode consent typed data * derives deposit wallet and Safe addresses * checks whether the derived Safe is deployed on Polygon * stores a one-time challenge under a 10 minute TTL ## Errors | Status | Code | Meaning | | - | - | - | | `400` | `invalid_address` or `invalid_username` | Request validation failed | | `400` | `challenge_mismatch` | Unsupported action | | `409` | `username_taken` | Username is not available | | `429` | `rate_limited` | Profile-specific rate limit exceeded | | `502` | `upstream_unavailable` | Polymarket, Gamma, or Polygon RPC failed | # Get Public Profile Source: https://docs.polynode.dev/api-reference/polymarket-profiles/get-profile GET /v3/polymarket/profiles/{address} Read public Polymarket profile state for an EOA address. ```text theme={null} GET /v3/polymarket/profiles/{address} ``` Returns normalized public profile information from Polymarket for an EOA address. ## Path parameters | Parameter | Type | Required | Description | | - | - | - | - | | `address` | string | Yes | EOA address | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/polymarket/profiles/0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0" \ -H "x-api-key: pn_live_..." ``` ```json theme={null} { "address": "0xc3579b0c908f43d50c63951a30c6f72fcea4f6a0", "proxy_wallet": "0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31", "username": "alice123", "pseudonym": "Glistening-Risk", "display_username_public": true, "profile_image": null, "x_username": null, "verified_badge": false, "source": "polymarket" } ``` ## Response fields | Field | Type | Description | | - | - | - | | `address` | string | EOA address requested, lowercase | | `proxy_wallet` | string or null | Polymarket wallet address returned by Gamma | | `username` | string or null | Public profile username | | `pseudonym` | string or null | Polymarket-generated pseudonym | | `display_username_public` | boolean or null | Whether the username is public | | `profile_image` | string or null | Profile image URL if present | | `x_username` | string or null | Linked X username if present | | `verified_badge` | boolean or null | Polymarket verified badge state | | `source` | string | `polymarket` | ## Errors | Status | Code | Meaning | | - | - | - | | `400` | `invalid_address` | Address is not a valid EVM address | | `404` | `profile_not_found` | Polymarket did not return a public profile | | `429` | `rate_limited` | Profile-specific rate limit exceeded | | `502` | `upstream_unavailable` | Polymarket/Gamma profile lookup failed | # Polymarket Profiles Source: https://docs.polynode.dev/api-reference/polymarket-profiles/overview Create or change a Polymarket username from a user-owned EOA wallet. The Polymarket Profiles API is a secure username provisioning flow for apps that manage their own users and wallets. Use it when your user has an EOA wallet and you want to let them set up a Polymarket username without sending private keys or long-lived Polymarket credentials to PolyNode. ## Base URL ```text theme={null} https://api.polynode.dev ``` ## Authentication Every request requires a paid PolyNode API key. ```bash theme={null} curl "https://api.polynode.dev/v3/polymarket/profiles/username-available?username=alice123" \ -H "x-api-key: pn_live_..." ``` Your backend should call these endpoints. Do not expose your API key to browser clients. ## Endpoints | Method | Endpoint | Description | | - | - | - | | `GET` | [`/v3/polymarket/profiles/username-available`](/api-reference/polymarket-profiles/username-available) | Check whether a username is available | | `POST` | [`/v3/polymarket/profiles/username/challenge`](/api-reference/polymarket-profiles/create-challenge) | Create the two wallet-signing payloads | | `POST` | [`/v3/polymarket/profiles/username/complete`](/api-reference/polymarket-profiles/complete-username) | Submit signatures and create or change the username | | `GET` | [`/v3/polymarket/profiles/{address}`](/api-reference/polymarket-profiles/get-profile) | Read public profile state | ## Flow 1. Check the username. 2. Create a challenge for `{address, username, action}`. 3. User signs the Polymarket SIWE message with `personal_sign`. 4. User signs the PolyNode consent typed data with `eth_signTypedData_v4`. 5. Complete the action from your backend. See the [Polymarket Profile Setup guide](/guides/polymarket-profile-setup) for a complete frontend and backend integration. ## Error shape ```json theme={null} { "error": "challenge_mismatch", "message": "challenge fields do not match completion request" } ``` Common error codes: | Code | Meaning | | - | - | | `invalid_address` | Invalid EVM address | | `invalid_username` | Username failed local validation | | `username_taken` | Username is unavailable | | `challenge_not_found` | Challenge expired, already consumed, or missing | | `challenge_expired` | Challenge is older than 10 minutes | | `challenge_mismatch` | Challenge fields or API key do not match | | `signature_invalid` | Wallet signature did not recover to the requested EOA | | `polymarket_compliance_blocked` | Polymarket rejected the action for compliance or eligibility reasons | | `upstream_unavailable` | Polymarket, Gamma, or Polygon RPC failed | | `rate_limited` | Profile-specific rate limit exceeded | # Check Username Availability Source: https://docs.polynode.dev/api-reference/polymarket-profiles/username-available GET /v3/polymarket/profiles/username-available Check whether Polymarket will accept a username. ```text theme={null} GET /v3/polymarket/profiles/username-available ``` Use this endpoint before creating a challenge. It calls Polymarket's username availability check and returns the upstream result. ## Query parameters | Parameter | Type | Required | Description | | - | - | - | - | | `username` | string | Yes | Desired username. Local validation is `^[A-Za-z0-9_]{3,32}$`. Polymarket is still the final authority. | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/polymarket/profiles/username-available?username=alice123" \ -H "x-api-key: pn_live_..." ``` ```json theme={null} { "username": "alice123", "available": true, "source": "polymarket" } ``` Unavailable usernames return `200` with `available: false`: ```json theme={null} { "username": "alice_123", "available": false, "source": "polymarket" } ``` ## Errors | Status | Code | Meaning | | - | - | - | | `400` | `invalid_username` | Missing username or invalid local format | | `401` | varies | Missing or invalid PolyNode API key | | `402` | varies | Paid plan required | | `429` | `rate_limited` | Profile-specific rate limit exceeded | | `502` | `upstream_unavailable` | Polymarket availability check failed | # Market Card Source: https://docs.polynode.dev/api-reference/pricing/market-statistics GET /v1/stats/{token_id} One-shot consolidated summary for a token — condition, outcomes, neg-risk flag, end date, last trade time, current orderbook liquidity, 24h OHLCV, and last price. Saves you from making 3–4 separate calls when you just need a market overview tile. # Online Search API Source: https://docs.polynode.dev/api-reference/search-online GET /v2/search/online Search the public web and return normalized organic results for agent context, market research, and enrichment workflows. > [!NOTE] > > **Beta.** This endpoint is designed for low-volume context enrichment. Results are best-effort, cached, and may be partial when upstream search engines throttle or fail. ## Endpoint ```http theme={null} GET /v2/search/online ``` Search the public web and return normalized organic results. Responses are cached to keep the endpoint lightweight. ```bash theme={null} curl "https://api.polynode.dev/v2/search/online?q=Cavaliers%20Knicks%20injury%20news&max_results=5" \ -H "x-api-key: YOUR_KEY" ``` ## Query parameters | Parameter | Description | | - | - | | `q` | Search query. Required. | | `max_results` | Number of normalized organic results. Defaults to `10`, capped at `20`. | | `engines` | Comma-separated engine adapters. Defaults to `bing,duckduckgo`. `brave` is available as an opt-in adapter. | | `language` | Search language. Defaults to `en-US`. | | `time_range` | Optional freshness filter when supported: `day`, `week`, `month`, `year`. | | `safe_search` | Safe-search mode: `0`, `1`, or `2`. Defaults to `0`. | | `cache_ttl_seconds` | Cache TTL for this query. Defaults to `600`, capped at `3600`. | Rate limit: `3` requests per `10` seconds per API key, in addition to your normal tier limit. ## Response ```json theme={null} { "query": "Cavaliers Knicks injury news", "source": "search_online", "adapter": "searxng", "status": "ok", "cached": false, "engines_requested": ["bing", "duckduckgo"], "unresponsive_engines": [], "result_count": 2, "results": [ { "title": "Cleveland Cavaliers Injury Status - ESPN", "url": "https://www.espn.com/nba/team/injuries/_/name/cle/cleveland-cavaliers", "domain": "espn.com", "snippet": "Visit ESPN for the current injury situation...", "engines": ["duckduckgo"], "score": 1, "category": "general", "published_at": null } ], "answers": [], "suggestions": [], "fetched_at": "2026-05-25T11:10:00.000Z", "elapsed_ms": 1200 } ``` `status` may be `partial` when one engine fails but other engines still return results. # Sports Markets Source: https://docs.polynode.dev/api-reference/sports/sports-markets Polynode sports endpoints expose Polymarket-native sports market data: leagues, teams, games, markets, token IDs, current CLOB prices, and historical price series. These endpoints replace the old sportsbook/OddsJam experiment. They do not return sportsbook odds. They return Polymarket market prices and metadata, normalized around sports games. ## Endpoints | Endpoint | Description | | - | - | | `GET /v2/sports/leagues` | Sports and esports league metadata from Polymarket Gamma | | `GET /v2/sports/summary` | League-level active/live/date summary | | `GET /v2/sports/live` | Backward-compatible live overview derived from `/sports/summary` | | `GET /v2/sports/leagues/{league}/teams` | Teams for a league, with logos and records when available | | `GET /v2/sports/leagues/{league}/games` | Games/events for a league, including markets, token IDs, and Gamma fallback metadata | | `GET /v2/sports/games/{slug}` | Full game/event detail with normalized markets | | `GET /v2/sports/games/by-event/{event_id}` | The same game detail resolved by Polymarket event ID | | `GET /v2/sports/games/by-market/{market_id}` | The parent game detail resolved by Polymarket market ID | | `GET /v2/sports/games/{slug}/state` | Canonical game state: metadata, score fields, markets, current prices, and subscribe payload | | `GET /v2/sports/games/{slug}/context` | Agent-friendly context bundle from generated game queries and optional external sources | | `GET /v2/sports/games/{slug}/prices` | Current bid, ask, midpoint, and spread for game tokens | | `GET /v2/sports/games/{slug}/history` | Batch CLOB price history for game tokens | | `GET /v2/sports/market-types` | Polymarket sports market type codes with PolyNode labels/categories | | `GET /v2/sports/search?q={query}` | Search sports events and teams | The event-ID and market-ID forms support the same `/state`, `/context`, `/prices`, and `/history` suffixes as the slug form. Keep the `by-event` or `by-market` prefix: event IDs and market IDs are separate numeric namespaces, so a bare numeric lookup would be ambiguous. Market-ID responses use the canonical parent event slug and contain the full event's markets. ## Game state ## League games Use league games for schedule discovery, such as listing all active FIFA World Cup match markets: ```bash theme={null} curl "https://api.polynode.dev/v2/sports/leagues/fifwc/games?status=active&sort=startDate&direction=asc&limit=50" \ -H "x-api-key: YOUR_KEY" ``` The response is filtered and sorted by PolyNode after resolving the league code to Polymarket's sports `series_id`. If Polymarket Gamma's primary event listing is unavailable, the response can still succeed through alternate Gamma sources and will include `fallback: true`. If Gamma is fully unavailable and PolyNode has a recent good response, it returns that cached response with `stale: true`. Use this when you want one game-centric object instead of manually joining game metadata, CLOB prices, markets, and websocket subscription details. ```bash theme={null} curl "https://api.polynode.dev/v2/sports/games/nba-cle-nyk-2026-05-31/state?price_limit_tokens=20" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "slug": "nba-cle-nyk-2026-05-31", "title": "Cavaliers vs. Knicks", "status": "scheduled", "source": { "metadata": "polymarket_gamma", "prices": "polymarket_clob", "history": null, "score": "polymarket_gamma" }, "score": { "source": "gamma:event", "score": null, "period": "NS", "live": null, "freshness": "unknown" }, "markets": [ { "question": "Cavaliers vs. Knicks", "sportsMarketType": "moneyline", "clobTokenIds": ["..."], "prices": [ { "outcome": "Cavaliers", "best_bid": "0.31", "best_ask": "0.47", "midpoint": "0.39", "spread": "0.16" } ] } ], "subscribe": { "ws": "wss://ws.polynode.dev/ws", "action": "subscribe", "type": "orderbook", "token_ids": ["..."] } } ``` Add `include_history=true` to include CLOB price history in the same response: ```bash theme={null} curl "https://api.polynode.dev/v2/sports/games/nba-cle-nyk-2026-05-31/state?include_history=true&history_limit_tokens=2&interval=1d" \ -H "x-api-key: YOUR_KEY" ``` ## Game context Use this for agent workflows that need game-specific search context next to the normalized sports object. PolyNode generates a small set of matchup, injury, lineup, news, or market-specific queries from the Polymarket game record, then runs the requested sources. ```bash theme={null} curl "https://api.polynode.dev/v2/sports/games/nba-cle-nyk-2026-05-31/context?sources=x,online&query_set=injuries&max_queries=2&max_per_query=5&include_state=true&price_limit_tokens=20" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "slug": "nba-cle-nyk-2026-05-31", "title": "Cavaliers vs. Knicks", "query_set": "injuries", "generated_queries": [ { "id": "matchup-injuries", "query": "Cavaliers Knicks injury", "reason": "Availability and injury context for both teams." } ], "sources_requested": ["x", "online"], "sources": { "x": { "status": "ok", "result_count": 5, "queries": [ { "query": "Cavaliers Knicks injury", "tweets": [] } ] }, "online": { "status": "ok", "source": "search_online", "adapter": "searxng", "queries": [] } }, "state": { "slug": "nba-cle-nyk-2026-05-31", "markets": [] } } ``` Parameters: | Parameter | Description | | - | - | | `sources` | Comma-separated sources. Defaults to `x`. Supported: `x`, `online`. `web`, `search`, `ddg`, and `ddg_instant` alias to `online`. | | `query_set` | Query strategy. Supported: `default`, `injuries`, `lineups`, `news`, `social`, `markets`. | | `max_queries` | Number of generated queries to run. Defaults to `3`, capped at `5`. | | `max_per_query` | Per-source result count per query. Defaults to `5`, capped at `10`. | | `include_state` | Include the `/state` response in the same payload. Defaults to `false`. | | `price_limit_tokens` | Token cap used when `include_state=true`. Defaults to `20`, capped at `200`. | The `x` source uses the same X Search beta quota and 1 request/second key-level rate limit as `/v2/x/search`. Each generated X query consumes one X Search quota unit. The `online` source uses `/v2/search/online` and returns normalized public web results. ## Current prices ```bash theme={null} curl "https://api.polynode.dev/v2/sports/games/nba-nyk-cle-2026-05-25/prices?limit_tokens=10" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "slug": "nba-nyk-cle-2026-05-25", "title": "Knicks vs. Cavaliers", "source": "polymarket_clob", "count": 10, "total_tokens": 106, "truncated": true, "tokens": [ { "token_id": "36872217940161491972120830074682109141065398170878601426051147635064624582652", "outcome": "Knicks", "question": "Knicks vs. Cavaliers", "market_type": "moneyline", "best_bid": "0.56", "best_ask": "0.57", "midpoint": "0.565", "spread": "0.01" } ], "subscribe": { "ws": "wss://ws.polynode.dev/ws", "action": "subscribe", "type": "orderbook", "token_ids": ["..."] } } ``` ## Price history ```bash theme={null} curl "https://api.polynode.dev/v2/sports/games/nba-nyk-cle-2026-05-25/history?limit_tokens=2" \ -H "x-api-key: YOUR_KEY" ``` `limit_tokens` defaults to `20` and is capped at `20` because Polymarket's batch history endpoint caps requests at 20 market asset IDs. If you do not pass `interval`, `start_ts`, or `end_ts`, PolyNode requests the full available CLOB history with `interval=max`. ```json theme={null} { "slug": "nba-nyk-cle-2026-05-25", "source": "polymarket_clob", "count": 2, "total_tokens": 106, "truncated": true, "tokens": [ { "token_id": "36872217940161491972120830074682109141065398170878601426051147635064624582652", "outcome": "Knicks", "history": [ { "t": 1779615604, "p": 0.555 } ] } ] } ``` ## Notes * `prices` fans out to Polymarket CLOB batch price, midpoint, and spread endpoints. * `history` uses Polymarket CLOB batch price history. Bare `/history` calls default to `interval=max`; pass `interval=1d`, `interval=1w`, or an explicit `start_ts`/`end_ts` window when you want a smaller range. * Scores are included only where Polymarket Gamma has score fields on the event. Use score fields as best-effort metadata, not guaranteed live scoreboard state. * For live orderbook updates, use the returned `subscribe.token_ids` with PolyNode orderbook WebSocket. # Generate API Key Source: https://docs.polynode.dev/api-reference/system/generate-api-key POST /v1/keys Generates a new API key. Rate limited to 1 per IP per day. The key is returned only once and cannot be retrieved again. # Health Check Source: https://docs.polynode.dev/api-reference/system/health-check GET /healthz Liveness probe. Returns 200 OK if the server is running. # Readiness Check Source: https://docs.polynode.dev/api-reference/system/readiness-check GET /readyz Returns 200 if node is connected and Redis is reachable, 503 otherwise. # System Status Source: https://docs.polynode.dev/api-reference/system/system-status GET /v1/status Returns system status including node connectivity, uptime, stream lengths, and state engine summary. # Top Traders (Market) Source: https://docs.polynode.dev/api-reference/wallets/market-positions GET /v1/markets/{id}/positions Every wallet that holds (or has held) a position in a single market, grouped by outcome and sorted by P&L. The 'who's making money on this market' feed. Returns every wallet with a position in a single market, broken out by outcome (e.g. Up/Down or Yes/No) and ranked by P\&L. The natural feed for "top traders on this market" leaderboards, top-X-by-PnL widgets, and per-market trader audits. Path accepts either the **market slug** (e.g. `btc-updown-5m-1777179000`) or the **condition\_id** (e.g. `0xa7ae8a41...`). It does **not** accept an outcome token id — pass the market identifier, not the side. > [!NOTE] > > Field shape is camelCase (`avgPrice`, `realizedPnl`, etc.) — distinct from polynode's V2 onchain endpoints which use snake\_case. Different schemas, different use cases. Default cap is 50 rows per outcome; configurable up to 500. ## Request ``` GET /v1/markets/{slug-or-condition-id}/positions ``` | Parameter | Type | Location | Description | | - | - | - | - | | `id` | string | path | Market slug or condition\_id (`0x…`). **Not** an outcome token id. | | `limit` | integer | query | Max rows per outcome. Default `50`, max `500`. | | `offset` | integer | query | Skip first N rows. | | `sortBy` | string | query | `TOTAL_PNL` (default), `REALIZED_PNL`, `CURRENT_VALUE`, `SIZE`, `INITIAL_VALUE`. | | `sortDirection` | string | query | `DESC` (default) or `ASC`. | | `status` | string | query | `OPEN`, `CLOSED`, or `ALL` (default). | | `min_size` | number | query | Drop positions with `size < min_size` from each outcome. Use `min_size=0.0001` to filter to current holders only (excludes historical participants who closed out to zero). | | `includeTrades` | boolean | query | When `true`, adds `firstTradeAt` / `lastTradeAt` (unix seconds) per row. Heavy — separate 20 req/min rate limit per key. | | `user` | string | query | Filter to a single wallet, or up to 20 wallets comma-separated, scoped to this market. | > [!NOTE] > > `TOTAL_PNL` and `REALIZED_PNL` are sorted by Polymarket's data-api directly. `CURRENT_VALUE`, `SIZE`, and `INITIAL_VALUE` are sorted in-process after the fetch (and after `min_size` if set), so they pair cleanly with the holder-filtering use case. ## Response ```json theme={null} { "condition_id": "0xa7ae8a4119fe00f231e693ed717339dd1e13da4617c79f3b1522ab1aee3965b6", "market_title": "Bitcoin Up or Down - April 26, 12:50AM-12:55AM ET", "slug": "btc-updown-5m-1777179000", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "outcome_names": ["Up", "Down"], "outcomes": [ { "token": "90684694382683135738693577247532961739938461809085935450142382916430459093778", "positions": [ { "proxyWallet": "0x9a1d392572d0e6bfefbf9302101b9e44c8ee86d6", "name": "kq9000", "profileImage": "", "verified": false, "asset": "90684694382683135738693577247532961739938461809085935450142382916430459093778", "conditionId": "0xa7ae8a4119fe00f231e693ed717339dd1e13da4617c79f3b1522ab1aee3965b6", "outcome": "Up", "outcomeIndex": 0, "size": 0, "avgPrice": 0.4592, "currPrice": 1, "currentValue": 0, "totalBought": 1633.1987, "realizedPnl": 812.5754, "cashPnl": 0, "totalPnl": 812.5754, "firstTradeAt": 1777179030, "lastTradeAt": 1777179152 } ] }, { "token": "96824…", "positions": [ "…" ] } ] } ``` ### Top-level fields | Field | Type | Description | | - | - | - | | `condition_id` | string | Market condition id | | `market_title` | string | Human-readable market question | | `slug` | string | Market slug | | `image` | string | Market image URL | | `outcome_names` | string\[] | Ordered outcome labels (`["Up","Down"]`, `["Yes","No"]`, etc.) | | `outcomes[]` | array | One entry per outcome — each holds a `positions` array | | `outcomes[].token` | string | Outcome token id | | `outcomes[].positions[]` | array | Traders with positions in this outcome, sorted by `sortBy` | ### Per-trader fields (`outcomes[].positions[]`) | Field | Type | Description | | - | - | - | | `proxyWallet` | string | Trader address (Gnosis Safe proxy) | | `name` | string | Display name (often empty or auto-generated) | | `profileImage` | string | Profile image URL (often empty) | | `verified` | boolean | Verified flag | | `asset` | string | Outcome token id (same as `outcomes[].token`) | | `conditionId` | string | Market condition id | | `outcome` | string | Outcome label (`"Up"`, `"No"`, etc.) | | `outcomeIndex` | number | 0-based position in `outcome_names` | | `size` | number | Current token balance. `0` = fully exited or never held. | | `avgPrice` | number | Volume-weighted average entry price | | `currPrice` | number | Current market price (or terminal `1.0`/`0.0` for resolved markets) | | `currentValue` | number | Mark-to-market value of remaining shares (`size × currPrice`) | | `totalBought` | number | Lifetime tokens acquired | | `realizedPnl` | number | Realized P\&L from sells + redemptions, in USDC | | `cashPnl` | number | P\&L from cash flows (separate accounting axis) | | `totalPnl` | number | Net portfolio P\&L for this position | | `firstTradeAt` | number | Unix seconds — only with `?includeTrades=true` | | `lastTradeAt` | number | Unix seconds — only with `?includeTrades=true` | ## Examples ### Top 10 traders on a market by total P\&L ```bash theme={null} curl "https://api.polynode.dev/v1/markets/btc-updown-5m-1777179000/positions?limit=10&sortBy=TOTAL_PNL&sortDirection=DESC" \ -H "x-api-key: YOUR_KEY" ``` ### By condition\_id, with first/last trade timestamps ```bash theme={null} curl "https://api.polynode.dev/v1/markets/0xa7ae8a4119fe00f231e693ed717339dd1e13da4617c79f3b1522ab1aee3965b6/positions?includeTrades=true&limit=20" \ -H "x-api-key: YOUR_KEY" ``` ### Drill into specific wallets within a market ```bash theme={null} curl "https://api.polynode.dev/v1/markets/btc-updown-5m-1777179000/positions?user=0x9a1d392572d0e6bfefbf9302101b9e44c8ee86d6,0x44bd2993a69d8b569859ed8c0bf0b946f733f71a" \ -H "x-api-key: YOUR_KEY" ``` ### Closed positions only ```bash theme={null} curl "https://api.polynode.dev/v1/markets/btc-updown-5m-1777179000/positions?status=CLOSED&sortBy=REALIZED_PNL" \ -H "x-api-key: YOUR_KEY" ``` ## Notes * **Default cap of 50 rows** per outcome unless `limit` is set higher (max 500). On very large markets with deep tail traders, paginate with `offset`. * **Sort ties on equal P\&L are non-deterministic** — two wallets at the same `totalPnl` may swap positions between calls. Use `proxyWallet` as a stable secondary key on the client side if you need consistent ordering. * **`size = 0` is normal** on closed positions, redeemed positions, or fully-exited positions. Use `realizedPnl` and `totalBought` to detect history. * **`firstTradeAt` / `lastTradeAt` require `?includeTrades=true`** and trip a separate heavy-endpoint rate limit (20 req/min per key). Don't request it on every refresh — fetch once and cache. ## When to use this vs. other position endpoints | If you want | Use | | - | - | | Top traders ranked on a single market | **This endpoint** | | One wallet's positions across all markets | [`GET /v2/wallets/{addr}/positions/onchain`](/api-reference/wallets/onchain-positions) | | All trades on a market (chronological fill feed) | [`GET /v2/onchain/markets/{tokenId}/trades`](/api-reference/onchain/market-trades) | # Positions & P&L (Wallet) Source: https://docs.polynode.dev/api-reference/wallets/onchain-positions GET /v2/wallets/{address}/positions/onchain Every position a wallet has held — open and closed — with realized + unrealized P&L, per-position activity timestamps, market resolution timestamps, and parent event slugs. Optional time-window filtering. Returns every position a wallet has ever held, including closed positions that no longer appear in the standard positions endpoint. Each position includes precomputed `realized_pnl`, `avg_price`, `total_bought`, plus per-position activity, redemption, and resolution timestamps that let you build leaderboards, trim to a 30-day or 90-day window, or filter to a parent event. The standard `/v1/wallets/{addr}/positions` endpoint only returns open positions. Once a position is fully exited or a market resolves, it disappears. This endpoint fills that gap. ## Request ``` GET /v2/wallets/{address}/positions/onchain ``` | Parameter | Type | Description | | - | - | - | | `address` | path | Wallet address (0x-prefixed, 40 hex chars) | | `since` | query (optional) | Unix seconds. Drop positions whose `last_trade_at` is before this timestamp. | | `until` | query (optional) | Unix seconds. Drop positions whose `last_trade_at` is after this timestamp. | | `tag_slug` | query (optional) | Keep only positions whose market carries this Polymarket event tag (e.g. `nba`, `politics`, `crypto`, `2026-fifa-world-cup-winner-595`). Matches against the per-market `tag_slugs` array. See [Filtering by tag](#filtering-by-tag). | `since`, `until`, and `tag_slug` are all **opt-in**. When none are supplied, the response is identical to a request with no parameters at all — same shape, same aggregates over the full position set. When any is supplied, positions are filtered and aggregates are recomputed (see [Filtering](#filtering-by-activity-window)). ## Response ```json theme={null} { "wallet": "0xbddf61af533ff524d27154e589d2d7a81510c684", "source": "onchain", "count": 879, "open_count": 340, "closed_count": 288, "total_realized_pnl": 17183579.48, "total_unrealized_pnl": -14346997.32, "total_pnl": 2836582.16, "positions_with_pnl": 309, "positions": [ { "token_id": "100424505911492726143069668369640898890012859227903329249368753635028896002613", "size": 0, "avg_price": 0.63, "realized_pnl": 147588.53019, "unrealized_pnl": 0, "current_price": null, "market_status": "closed", "total_bought": 398887.919433, "market": "Will Fulham FC win on 2026-03-21?", "slug": "epl-ful-bur-2026-03-21-ful", "event_slug": "epl-ful-bur-2026-03-21", "outcome": "Yes", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/Repetitive-markets/premier+league.jpg", "condition_id": "0xae68634cb01137acbe26e65790f7268a523ee1519601f2576bd7b067c7c9f9da", "last_trade_at": 1742568134, "closed_at": 1742573012, "resolved_at": 1742572840 } ] } ``` | Field | Type | Description | | - | - | - | | `wallet` | string | Queried wallet address (lowercased) | | `source` | string | Always `"onchain"` | | `count` | number | Total positions returned | | `open_count` | number | Positions with `size > 0` | | `closed_count` | number | Positions with `size = 0` and nonzero `realized_pnl` | | `total_realized_pnl` | number | Sum of `realized_pnl` across all returned positions | | `total_unrealized_pnl` | number | Sum of `unrealized_pnl` across all returned positions. Reflects open-size paper P\&L at current (or terminal) market prices. | | `total_pnl` | number | `total_realized_pnl + total_unrealized_pnl`. Matches the net portfolio PnL shown on a Polymarket profile page. | | `positions_with_pnl` | number | Positions where `realized_pnl != 0` | | `filtered` | boolean | Present **only** when `since` or `until` was supplied. Always `true` in that case. Absent in default responses. | | `applied_filters` | object | Present **only** when filtering. Echoes `{since, until}` (each is the supplied unix seconds or `null`). Absent in default responses. | | `positions[].token_id` | string | CTF token ID (called `asset` on the [closed-positions](/api-reference/wallets/closed-positions) endpoint) | | `positions[].size` | number | Current token balance (0 = fully exited) | | `positions[].avg_price` | number | Volume-weighted average entry price | | `positions[].realized_pnl` | number | Realized profit/loss in USDC | | `positions[].unrealized_pnl` | number | Paper P\&L on remaining open shares. For resolved markets, uses the terminal settlement price (1.0 winner / 0.0 loser). For live markets, uses the current market price. `0` when `size = 0`. | | `positions[].current_price` | number \| null | Price used for `unrealized_pnl`. `1.0` or `0.0` on resolved markets, live market price on active markets, `null` when `size = 0` or no price is available. | | `positions[].market_status` | string | `"live"` / `"resolved-win"` / `"resolved-loss"` / `"resolved-unknown"` / `"closed"`. See [positions feed](/api-reference/onchain/positions#position-fields) for full enum. | | `positions[].total_bought` | number | Total tokens acquired for this position | | `positions[].market` | string | Market question | | `positions[].slug` | string | **Market** slug — identifies the specific market within an event (e.g. `nba-bos-cle-2026-03-08-spread`). | | `positions[].event_slug` | string \| null | **Event** slug — identifies the parent event a market belongs to (e.g. `nba-bos-cle-2026-03-08`). For single-market events, equals `slug`. For multi-market events (NBA games with several lines, election markets with several candidates, FIFA World Cup with one market per team, etc.) this is the parent the markets share. `null` when the event metadata is not yet known. | | `positions[].outcome` | string | Outcome label (e.g. "Yes", "No", "Up") | | `positions[].image` | string | Market image URL | | `positions[].condition_id` | string | Market condition ID | | `positions[].last_trade_at` | number \| null | Unix seconds. Latest fill (maker or taker) on this token across V1 + V2 exchanges. `null` when polynode has no fill history for the token (e.g. positions acquired purely via splits/merges or NegRisk conversion with no later trade). | | `positions[].closed_at` | number \| null | Unix seconds. Latest moment this wallet redeemed any outcome of this market's `condition_id` for collateral. `null` when the wallet has not redeemed (positions sold to zero before resolution, or open positions, or wins held but not yet redeemed). | | `positions[].resolved_at` | number \| null | Unix seconds. Moment the market was resolved on-chain (when payouts became redeemable). `null` for markets that resolved before polynode began tracking, or for markets that have not yet resolved. Recent markets are fully covered. | | `positions[].tag_slugs` | string\[] \| null | Polymarket event-level tags applied to this market. Examples: `["NBA","Basketball","Sports","All"]` for an NBA game market, `["Crypto","Up or Down","Recurring","All"]` for a 5-min crypto market. Order is most-specific → most-general. Tags live on the parent event (markets sharing an `event_slug` share the same `tag_slugs`). `null` only on the rare event that doesn't carry any tag or hasn't been ingested yet. | ## Distinguishing the three timestamp fields These three timestamp fields look similar but answer different questions. Choosing the right one matters when filtering: | Field | Whose action | When | | - | - | - | | `last_trade_at` | The **wallet**'s most recent fill on this exact token | Each fill event (buy or sell) updates this | | `closed_at` | The **wallet**'s most recent collateral redemption for the market | Set when the wallet calls `redeemPositions` on the CTF contract | | `resolved_at` | The **market itself** (not the wallet) becoming redeemable | Set once per market, when the oracle reports payouts on-chain | A position can have `resolved_at` populated and `closed_at` null — the market resolved but the wallet has not yet redeemed. A position can have `closed_at` set and `resolved_at` null — the wallet redeemed during a window polynode does not have full historical resolution coverage for, but the redemption itself was observed. For windowing a leaderboard to "the last 30 days of trading activity," `last_trade_at` is the right field — it captures every position the wallet was active in. For "positions resolved in the last 90 days," `resolved_at` is the right one. For "positions the wallet has actually closed out," `closed_at` is the right one. ## Filtering by activity window `since` and `until` are optional unix-seconds query parameters that filter positions by `last_trade_at`. Designed to support 30d / 90d / 365d leaderboard windows without fetching multi-year history just to trim it client-side. ### Behavior * Both bounds are **inclusive**. * Positions with `last_trade_at = null` are dropped under any active filter — there's no timestamp to compare against. * All seven aggregates (`count`, `open_count`, `closed_count`, `total_realized_pnl`, `total_unrealized_pnl`, `total_pnl`, `positions_with_pnl`) **recompute over the filtered set**. * The response gains two top-level keys to make the shift self-documenting: `filtered: true` and `applied_filters: { since, until }`. These keys are absent from default responses. * Bad inputs return `400` with a descriptive error. ### 30-day window ```bash theme={null} SINCE=$(( $(date -u +%s) - 86400 * 30 )) curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/positions/onchain?since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` ### 90-day window ```bash theme={null} SINCE=$(( $(date -u +%s) - 86400 * 90 )) curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/positions/onchain?since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` ### Bounded range (e.g. Q1 2026) ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?since=1735689600&until=1743465600" \ -H "x-api-key: YOUR_KEY" ``` > [!NOTE] > > **The default response is unaffected by these new params.** When you call this endpoint with no `since`/`until`/`tag_slug`, the response shape and every aggregate is identical to what you got before. The `filtered` and `applied_filters` keys are only added when you opt in. ## Filtering by tag `tag_slug` is an optional query parameter that keeps only positions whose market carries the matching Polymarket event tag. Tags come from Polymarket's event taxonomy — typical values include `nba`, `basketball`, `sports`, `politics`, `crypto`, `fed`, `world`, `2025-predictions`, and event-specific slugs like `2026-fifa-world-cup-winner-595`. Each market inherits the tag set of its parent event, so all 32 markets under "Will X win the World Cup?" share the same tag list. The full set is visible in the per-row `tag_slugs` array on every response. ### Behavior * Match is case-sensitive and exact (`?tag_slug=nba` matches markets whose `tag_slugs` array contains `"nba"`). * Positions with `tag_slugs = null` are dropped under an active filter — same logic as `last_trade_at` for `since`/`until` (cannot match what we don't know). * Aggregates recompute over the filtered set. * `applied_filters.tag_slug` echoes the value back so the response is self-documenting. * Combine with `since` / `until` to get e.g. "all NBA positions in the last 30 days" — all three filters AND together. ### Examples #### All NBA positions for a wallet ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?tag_slug=nba" \ -H "x-api-key: YOUR_KEY" ``` #### All positions tagged to a specific event ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?tag_slug=2026-fifa-world-cup-winner-595" \ -H "x-api-key: YOUR_KEY" ``` This collapses across every children market under the FIFA World Cup winner event. #### Crypto positions in the last 90 days ```bash theme={null} SINCE=$(( $(date -u +%s) - 86400 * 90 )) curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?tag_slug=crypto&since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` ### Discovering available tags Use the dedicated [`/v2/onchain/tags`](/api-reference/onchain/tags) endpoint for the full tag namespace (5,779 tags currently). Returns a flat slug array by default, or `?details=true` for per-tag market counts and timestamps: ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/tags?min_markets=100&details=true" \ -H "x-api-key: YOUR_KEY" ``` The values returned by `/v2/onchain/tags` are the exact strings to pass to `?tag_slug=` here. For a wallet-specific view, you can also fetch the wallet's positions without a filter and read the union of `tag_slugs` across the response — that's the tag namespace the wallet has actually traded in. ## How `realized_pnl` Works Each position's `realized_pnl` reflects the profit or loss after the position is closed (sold or redeemed). For a winning binary position bought at $0.40 that resolves at $1.00: * `avg_price` = 0.40 * `total_bought` = 10,000 (tokens acquired) * Cost basis = 10,000 × $0.40 = $4,000 USDC * Payout at $1.00 = 10,000 × $1.00 = \$10,000 USDC * `realized_pnl` = $10,000 - $4,000 = **\$6,000** The formula: `realized_pnl = total_bought × (1 - avg_price)` for positions that resolve at \$1. Per-position values (`realized_pnl`, `avg_price`, `total_bought`) come from the same onchain settlement data that Polymarket uses. Individual position P\&L matches what Polymarket shows on its portfolio page. ## Which total to use The response returns three portfolio-level totals. Each answers a different question: | Total | Answers | Matches | | - | - | - | | `total_realized_pnl` | How much profit has this wallet actually taken off the table from closed + resolved positions? | Not shown on Polymarket profile | | `total_unrealized_pnl` | What is the paper P\&L on the wallet's currently-held shares at current (or terminal) prices? | Not shown directly | | `total_pnl` | What is the wallet's net portfolio P\&L right now? | The "Profit" number on a Polymarket profile page | `total_pnl` is what most dashboards want — it's the single number users recognize from Polymarket. `total_realized_pnl` is useful for attribution (which markets made money vs which positions are still out). `total_unrealized_pnl` is useful for risk views (how much is still at stake). > [!NOTE] > > `total_pnl = total_realized_pnl + total_unrealized_pnl`. Reach for `total_pnl` when you want a number that matches a Polymarket profile page. Reach for `total_realized_pnl` when you want only closed-out gains. When you supply `since` or `until`, all three totals recompute over the filtered set — the same logic, just narrower input. ## Performance Responses are cached for 5 minutes per wallet. First request for a new wallet takes 200ms-3s depending on position count (up to 20,000 positions supported). Cached responses return in under 50ms. Filter parameters are applied to the cached set; passing `since`/`until` does not invalidate the underlying cache. | Positions | First request | Cached | | - | - | - | | \< 500 | \~1s | \< 50ms | | 500-1,000 | \~1.5s | \< 50ms | | 1,000-5,000 | \~3s | \< 50ms | ## Examples ### Default response (no filter) ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/positions/onchain" \ -H "x-api-key: YOUR_KEY" ``` Returns every position the wallet has held, all-time, with the full set of fields documented above. Default response shape — no `filtered` or `applied_filters` keys. ### Filter to the last 30 days ```bash theme={null} SINCE=$(( $(date -u +%s) - 86400 * 30 )) curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/positions/onchain?since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` ### Filter to a parent event `event_slug` is included on every row, so once you have a wallet's positions you can group them by parent event without an extra round-trip: ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain" \ -H "x-api-key: YOUR_KEY" \ | jq '.positions | group_by(.event_slug) | map({event_slug: .[0].event_slug, market_count: length, pnl: (map(.realized_pnl + .unrealized_pnl) | add)})' ``` This collapses a wallet's positions across the children of an event (e.g. all 32 World Cup winner markets, or the multiple lines of a single NBA game) into one row per event. # Resolve Wallet Source: https://docs.polynode.dev/api-reference/wallets/resolve GET /v1/resolve/{query} Instantly resolve any Polymarket wallet address, EOA, or username. Look up the full identity for any Polymarket user: preferred trading wallet, EOA (externally owned account), username, wallet type, deployment status, and related wallets. Accepts any identifier as input and returns all fields. > [!NOTE] > > If the controlling EOA has a deployed deposit wallet, `safe` returns that deposit wallet and `type` is `"deposit_wallet"` — even when you query the EOA, username, or an older wallet. If no deposit wallet is deployed, `safe` falls back to the existing Safe/proxy wallet. The `safe` field name is kept for backward compatibility; it means the preferred Polymarket trading wallet. **query** `string` *required* One of: * **Wallet address** — any Polymarket trading wallet: deposit wallet, Safe, or proxy wallet (`0x...`, 42 chars) * **EOA address** — externally owned account (`0x...`, 42 chars) * **Username** — Polymarket display name (case-insensitive) ## Understanding Polymarket wallet types Polymarket has used a few different wallet types over the years, depending on how an account signed up. You never need to know which one you're dealing with — pass any address and the endpoint works it out — but here's what the `type` values mean: | `type` | Who has one | | - | - | | `deposit_wallet` | **Every new Polymarket account.** The deposit wallet is the current standard wallet type. | | `safe` | Older accounts that signed up by connecting a browser wallet (MetaMask etc.) — these got a Gnosis Safe. | | `proxy` | Older accounts that signed up with an email or social login — these got a Polymarket proxy wallet. | **"Deposit wallet" vs "beacon wallet":** if you've seen both terms, they're the same thing. Newer deposit wallets are built so Polymarket can upgrade all of them at once — that upgradeable variant is what gets called a "beacon wallet". There's also an earlier standalone variant from before that change. Both behave identically and both resolve here; you never need to tell them apart. One user can have more than one wallet — for example an old Safe from years ago plus a new deposit wallet. ## Wallet type, deployment, and current wallet These fields answer three separate questions: | Field | What it tells you | | - | - | | `wallet_type` | What kind of Polymarket wallet the address is: `deposit_wallet`, `safe`, or `proxy`. | | `deployed` | Whether the wallet contract currently exists on Polygon. | | `current` | Whether this is the trading-wallet address currently selected for the account. This is the address returned in the legacy top-level `safe` field. | The legacy `wallets` object remains deployed-only: an address appears there only after its contract exists on Polygon. The additive `wallet_details` list includes the current address even if it is not deployed yet, plus the user's other deployed wallets. This makes mixed accounts explicit without changing any existing field. For example, this account's current address is a deposit wallet, but its contract has not been deployed yet: ```json theme={null} { "safe": "0xb8fa41b48c092ff003686ddbe64c031a6e275611", "eoa": "0xf6771e0308add4131b56989ca969c84b8c9f2155", "username": "hfheohebe", "type": "deposit_wallet", "wallets": { "deposit_wallet": null, "safe": null, "proxy_wallet": null }, "wallet_details": [ { "address": "0xb8fa41b48c092ff003686ddbe64c031a6e275611", "wallet_type": "deposit_wallet", "deployed": false, "current": true } ] } ``` ## By wallet address (Safe) Look up a Polymarket Safe to get the controlling EOA and username. If that EOA also has a deployed deposit wallet, the response returns the deposit wallet in `safe` instead. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/0xfa85349327a63aa563029737f0492a79dca8f95d" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0xfa85349327a63aa563029737f0492a79dca8f95d", "eoa": "0xc2783891b1d2287345e30f75e0f1ecd189a967d0", "username": "Letsgetit6969", "type": "safe", "wallets": { "deposit_wallet": null, "safe": "0xfa85349327a63aa563029737f0492a79dca8f95d", "proxy_wallet": null } } ``` ## By wallet address (deposit wallet) Look up a deposit wallet to get the controlling EOA. Works for both deposit wallet variants. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "eoa": "0xa60601a4d903af91855c52bfb3814f6ba342f201", "username": null, "type": "deposit_wallet", "wallets": { "deposit_wallet": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "safe": null, "proxy_wallet": null } } ``` ## By EOA address Look up an EOA to find its Polymarket trading wallet and username. Deposit wallets are prioritized when deployed: ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/0x7be2f44bd50761ec940fc5dc535e200b31c69377" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0xd10b418250d9a87e3162de6c8c9bd76b46f011e1", "eoa": "0x7be2f44bd50761ec940fc5dc535e200b31c69377", "username": "KauaiMagic", "type": "deposit_wallet", "wallets": { "deposit_wallet": "0xd10b418250d9a87e3162de6c8c9bd76b46f011e1", "safe": null, "proxy_wallet": null } } ``` ## By wallet address (proxy wallet) Resolve a Polymarket proxy wallet — the wallet type used by accounts created with email or social login. The endpoint returns the controlling EOA, recovered automatically. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/0x16cbe223607a6513ae76d1e3751c78e4eabc2704" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0x16cbe223607a6513ae76d1e3751c78e4eabc2704", "eoa": "0xbe5ba588ab7173b34efc0706b881794951014293", "username": "MRF", "type": "proxy", "wallets": { "deposit_wallet": null, "safe": null, "proxy_wallet": "0x16cbe223607a6513ae76d1e3751c78e4eabc2704" } } ``` ## By username Look up a Polymarket username to find the trading wallet and EOA. Case-insensitive. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/Fredi9999" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0x1f2dd6d473f3e824cd2f8a89d9c69fb96f6ad0cf", "eoa": "0x92fee51e468fcd2467e89300be7ca4b5ed7ccfb3", "username": "Fredi9999", "type": "proxy", "wallets": { "deposit_wallet": null, "safe": null, "proxy_wallet": "0x1f2dd6d473f3e824cd2f8a89d9c69fb96f6ad0cf" } } ``` ## Response fields **safe** `string` *required* Preferred Polymarket trading wallet address. The field name is kept for backward compatibility. If the controlling EOA has a deployed deposit wallet, this is the deposit wallet. Otherwise it is the existing Safe/proxy wallet. **eoa** `string` Externally owned account that controls the trading wallet. This is the signer address. May be `null` in rare cases where it cannot be determined. **username** `string` Polymarket display name. `null` if the user has no profile set. **type** `string` Wallet type for the address returned in `safe`. One of `"deposit_wallet"`, `"safe"`, or `"proxy"` — see [wallet types](#understanding-polymarket-wallet-types) above. `null` only when the resolver cannot verify the wallet's implementation. **wallets** `object` Every Polymarket wallet this user has deployed, by type. Each field is an address or `null`: * `wallets.deposit_wallet` — their deposit wallet (either variant) * `wallets.safe` — their Gnosis Safe * `wallets.proxy_wallet` — their proxy wallet Useful when a user has more than one — for example, matching historical activity on an old Safe with current activity on a new deposit wallet. **wallet\_details** `array` Status for the current wallet and every other deployed wallet associated with the EOA. Each item contains: * `address` — wallet address * `wallet_type` — `"deposit_wallet"`, `"safe"`, or `"proxy"`; rarely `null` when the implementation cannot be verified * `deployed` — `true` when contract code currently exists on Polygon * `current` — `true` for the selected trading-wallet address returned in `safe` Use this list when you need to distinguish wallet type from deployment, or when an account has both a Safe/proxy and a deposit wallet. ## Error responses **404 — Not found** ```json theme={null} {"error": "Address not found."} ``` ```json theme={null} {"error": "Username not found."} ``` ## Coverage The resolver supports every Polymarket wallet type on Polygon: deposit wallets (both variants), Gnosis Safes, and proxy wallets. Cached lookups are sub-millisecond. Uncached lookups resolve in real time, then prefer a deployed deposit wallet when one exists for the resolved EOA. ## Use cases * **Database enrichment** — bulk-resolve trading wallets to EOAs for analytics pipelines * **Profile lookups** — show usernames alongside wallet addresses in your UI * **Cross-referencing** — match on-chain activity (EOA) to the preferred Polymarket trading wallet * **Whale tracking** — identify the EOA behind a trading wallet to track activity across protocols * **Multi-wallet users** — use `wallet_details` to distinguish the current wallet from other deployed wallet types # X Search API Source: https://docs.polynode.dev/api-reference/x-search GET /v2/x/search Beta endpoint for live X (Twitter) search and account-timeline data. Drop social context next to your prediction market data without building your own X integration. > [!NOTE] > > **Beta.** Response shape and quota numbers are stable. We may add optional fields, but no breaking changes. Email `josh@polynode.dev` if you're building something on top of this and need direct support. ## What this is Two read-only endpoints for live X data: * **Search** any text across X. Full operator support (`from:`, `since:`, `min_faves:`, hashtags, exact phrases). * **Account timeline** for any public X handle — most-recent tweets, replies, retweets, and quoted content. Most teams already using polynode for prediction-market data also want to know what's being said on X about a market, an event, or a specific account. Setting up your own X feed is rate-limit hell and a maintenance treadmill — we just do it for you, and you query it like any other polynode endpoint. ## Who this is for * Prediction-market dashboards layering social sentiment over on-chain data. * AI agents that need to factor live X posts into their reasoning about an event. * Research and analytics products that want clean JSON without building their own X integration. ## Base URL ``` https://api.polynode.dev/v2/x ``` ## Authentication Pass your polynode API key on every request — either header works: ```http theme={null} x-api-key: pn_live_... Authorization: Bearer pn_live_... ``` * Free-tier keys are rejected with `402 Payment Required`. Paid plans only. * Hard rate limit: **1 request per second per key**. Two requests on the same key in the same second → the second one gets `429`. * Each successful response (HTTP 200) increments your monthly quota counter. Rejected requests do not. ## Tier quotas | Tier | Searches per month | | - | - | | starter | 500 | | growth | 1,000 | | enterprise | 5,000 | Quotas reset midnight UTC on the 1st of each month. Track your remaining usage in real time via response headers: ``` X-Quota-Used: 47 X-Quota-Limit: 500 ``` ## Endpoints ### `GET /v2/x/search` Search recent X posts by query. **Query params:** | Param | Type | Default | Notes | | - | - | - | - | | `q` | string | required | The search string. URL-encode operators and special characters. | | `max` | int | `20` | Number of tweets to return. Min `1`, max `50`. | **Operator examples:** ``` q=polymarket q=from:Polymarket q=election odds since:2026-04-20 q=#prediction min_faves:100 q="exact phrase" lang:en q=trump until:2026-05-01 ``` **Example request:** ```bash theme={null} curl -H "x-api-key: $PN_KEY" \ "https://api.polynode.dev/v2/x/search?q=polymarket&max=5" ``` **Example response:** ```json theme={null} { "query": "polymarket", "tweets": [ { "id": "2048234907965526306", "text": "Polymarket is showing 65% on Trump for 2024", "created_at": "Sun Apr 26 03:21:58 +0000 2026", "public_metrics": { "retweet_count": 244, "reply_count": 38, "like_count": 1450, "quote_count": 22, "bookmark_count": 87, "impression_count": "184302" }, "author": { "id": "987654321", "name": "Polymarket", "username": "Polymarket" }, "conversation_id": "2048234907965526306", "urls": [ { "url": "https://t.co/...", "expanded_url": "https://polymarket.com/event/...", "display_url": "polymarket.com/event/...", "title": "Will Trump win 2024?", "description": "..." } ], "media": [ { "type": "photo", "url": "https://pbs.twimg.com/media/...", "expanded_url": "..." } ] } ], "result_count": 5, "fetched_at": "2026-04-26T03:35:00Z" } ``` ### `GET /v2/x/user/{handle}/tweets` Get the latest tweets from a specific X account's timeline. **Path params:** | Param | Type | Notes | | - | - | - | | `handle` | string | The X handle without `@`. Letters, digits, underscore only. | **Query params:** | Param | Type | Default | Notes | | - | - | - | - | | `max` | int | `30` | Number of tweets. Min `1`, max `50`. | **Example request:** ```bash theme={null} curl -H "x-api-key: $PN_KEY" \ "https://api.polynode.dev/v2/x/user/Polymarket/tweets?max=10" ``` The response shape is identical to `/v2/x/search`, except the top-level field is `handle` instead of `query`. ## Errors | HTTP | Meaning | | - | - | | 400 / 422 | Invalid params: empty `q`, `max` out of range, or handle contains invalid characters. | | 401 | Missing or invalid API key. | | 402 | Free-tier key; this endpoint requires a paid plan. | | 404 | Handle does not exist (timeline endpoint only). | | 429 | Either the 1 req/sec rate cap, or your monthly quota is exhausted. Check `X-Quota-Used` / `X-Quota-Limit`. | | 502 | Transient upstream issue. Retry after a few seconds. We're alerted automatically. | ## Tweet shape reference Every tweet object can include these fields. Optional fields are only present when relevant. | Field | Type | Always present? | Notes | | - | - | - | - | | `id` | string | yes | Tweet's numeric ID as a string. | | `text` | string | yes | The tweet body. `t.co` shortlinks are pre-expanded to their final destination URLs. | | `created_at` | string | yes | X's native timestamp format (e.g. `Sun Apr 26 03:21:58 +0000 2026`). | | `public_metrics` | object | yes | Counters: `retweet_count`, `reply_count`, `like_count`, `quote_count`, `bookmark_count`, `impression_count`. | | `author` | object | yes | `{ id, name, username }`. | | `conversation_id` | string | yes | The root tweet of the thread this tweet belongs to. | | `urls` | array | optional | Embedded link metadata: `{ url, expanded_url, display_url, title, description }`. | | `media` | array | optional | Photos, videos, GIFs: `{ type, url, expanded_url }` (videos include `video_url` for the highest-bitrate MP4). | | `card` | object | optional | Link preview cards: `{ name, url, title, description, domain, thumbnail_url }`. | | `quoted_tweet` | object | optional | Full tweet object of any quoted post (recursive). | | `article` | string | optional | Long-form X post content rendered as Markdown. | ## Quirks worth knowing * **`created_at` is X's native string format**, not ISO 8601. Parse with `new Date(tweet.created_at)` in JS or `dateutil.parser.parse` in Python. * **`impression_count` is a string**, not an int — X returns it as a string and we pass it through verbatim. Cast on your side if you need a number. * **`text` is post-expansion.** All `t.co` shortlinks are already replaced with their target URLs. The `urls` array also gives you the full expanded metadata (title, description) per link, which is the easiest way to surface link previews in your UI. * **No pagination cursor** in the beta. The `max` cap is 50 per call. To go beyond that, run multiple queries narrowed with `since:` / `until:` operators. * **Search prefers recency.** Live results are ranked newest-first. Combine with `min_faves:N` or `min_retweets:N` if you want to floor on engagement. ## FAQ **Why is search slower than timeline?** Search and timeline take different paths. Timeline is typically \~1-2 seconds. Search is typically 5-7 seconds because the underlying X data path is heavier. This is normal and stable. **Can I get my own quota lifted?** Yes — email `josh@polynode.dev` if you're hitting the cap and want a custom limit. **Will the response shape change?** We may add optional fields (e.g. new metrics X exposes). We will not rename or remove existing fields without versioning the endpoint. Code defensively against optional fields, never against missing ones. # Authentication Source: https://docs.polynode.dev/authentication API key generation, authentication methods, and security. All API endpoints (except `/healthz`, `/readyz`, and `POST /v1/keys`) require an API key. ## Passing the key Two methods are supported: > [tab] Header (recommended) > > ```bash theme={null} > curl -H "x-api-key: pn_live_YOUR_KEY" https://api.polynode.dev/v1/markets > ``` > [tab] Query parameter > > ```bash theme={null} > curl "https://api.polynode.dev/v1/markets?key=pn_live_YOUR_KEY" > ``` For WebSocket connections, use the query parameter: ``` wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY ``` ## Key format API keys use the prefix `pn_live_` followed by a random string. Legacy keys with `qm_live_` prefix are also accepted. ## Account-level usage All active API keys owned by the same account contribute to one shared monthly usage total. Creating, renaming, rotating, or using multiple keys does not create separate allowances or reset usage. The [usage dashboard](https://polynode.dev/dashboard/usage) is authenticated by your signed-in account; you do not submit a raw API key to view it. See [Monthly usage allowances](/guides/rate-limits#monthly-usage-allowances) for the exact meters and included plan capacity. ## Generating a key ```bash theme={null} curl -s -X POST https://api.polynode.dev/v1/keys \ -H "Content-Type: application/json" \ -d '{"name": "my-app"}' ``` | Field | Type | Description | | - | - | - | | `name` | string (optional) | Label for the key. Defaults to "unnamed". | Key generation is rate limited to **1 per IP per day**. > [!WARNING] > > The raw API key is returned only once. It cannot be retrieved after creation — store it securely. ## Security * API keys are **SHA-256 hashed** before storage. The raw key is never persisted. * All traffic should use HTTPS in production. * Rotate keys by generating a new one and decommissioning the old one. ## Error responses | Status | Error | Fix | | - | - | - | | 401 | Missing or invalid API key | Include your key as `x-api-key` header or `?key=` param | | 403 | Invalid or inactive API key | Verify your key is correct, or generate a new one | | 429 | Rate limit exceeded | Reduce request frequency. Free tier: 60 req/min | # Pending signal and observed copy execution: Polynode vs Bravado Source: https://docs.polynode.dev/case-studies/bravado-pending-copy-execution-2026-08-07 An August 7, 2026 study of pending latency, public-stream coverage, observed same-block copy execution, and product breadth. On August 7, 2026, we compared Polynode's pending and confirmed WebSocket paths with Bravado's public trade WebSocket, then checked the observed transactions and fills against Polygon. In a separate on-chain audit, we examined a strongly supported copy-like relationship between a public Polymarket trader and a Bravado-attributed wallet. > [!NOTE] > > This is a Polynode-run, point-in-time study. It measures Bravado's public customer-visible stream and confirmed Bravado-attributed outcomes—not Bravado's private detector or order-submission system. Claims are limited to the recorded date, network vantage point, and identified relationship. > [card] Pending first on 12,665 of 12,665 > > Polynode pending arrived before every overlapping Bravado public trade sighting in the 15-minute headline run. > [card] 2.104-second median lead > > Polynode pending led the Bravado sighting by 2.104 seconds at median and 3.077 seconds at P95. > [card] 97.44% landed in a later block > > Of 1,600 chain-ordered copy-like pairs, 1,559 follower transactions landed after the leader's block. > [card] Combos and perps covered > > Polynode documents dedicated REST and streaming surfaces for combo markets and perps; no equivalent Bravado public surface was found. ## Bottom line Bravado advertises copy fills in the same block as the leader. That was not the typical result in the Bravado-attributed relationship we could verify: **41 of 1,600** causally ordered pairs landed in the leader's block, while **1,559 of 1,600** landed later. Same-block execution occurred, but it was the exception rather than the norm in this sample. The public-stream result explains why the signal boundary matters. We observed no pending lifecycle message on Bravado's public WebSocket. Polynode pending arrived first on every shared confirmed transaction, more than two seconds before the Bravado public sighting at the measured median. A customer reacting only to the observed Bravado stream would already be reacting after mining; Polynode exposes a pre-confirmation window in which customer-owned execution can act. ## The public stream arrived after the pending window The headline run covered **12,705 transactions and 35,218 `OrderFilled` logs** across Polygon blocks 91,580,419–91,581,015. The core interval was 2026-08-07 04:07:32.654–04:22:32.752 UTC. The collector ran on Node.js v24.14.0, Linux x64, from the Europe/Berlin vantage, with a 12-second warm-up, two-block boundary guard, and 20-second confirmation tail. | Path | Unit | Seen | Coverage | Missing | | - | -: | -: | -: | -: | | Polynode pending settlement | Transaction | 12,705 / 12,705 | 100.000% | 0 | | Polynode `status_update` | Transaction | 12,705 / 12,705 | 100.000% | 0 | | Polynode confirmed `trade` | Exact fill | 35,218 / 35,218 | 100.000% | 0 | | Bravado public trade sighting | Transaction | 12,665 / 12,705 | 99.685% | 40 | Bravado's 26,667 live trade messages carried a transaction hash, but no pending marker, lifecycle status, block number, or block-global log index. The missing log index means the public stream can be scored for transaction coverage, but not for exact-fill completeness. The 40 misses were concentrated in one silent-open interval; Polynode and RTDS continued delivering during the scored overlap, but the audit cannot identify the cause. The missing transaction hashes are included in the evidence bundle. | Comparison: Polynode vs Bravado public sighting | Samples | Polynode first | Median lead | P95 lead | | - | -: | -: | -: | -: | | Pending settlement | 12,665 | **100.00%** | **+2.104 s** | **+3.077 s** | | `status_update` | 12,665 | 57.88% | +96.7 ms | +803.6 ms | | Confirmed `trade`, transaction level | 12,665 | 47.84% | -28.2 ms | +707.2 ms | A positive lead means Polynode arrived first. The confirmed paths were close: Bravado led Polynode's confirmed `trade` transaction sighting by 28.2 ms at the median. The measured advantage is specifically Polynode's **pending signal**, not a claim that every Polynode post-mining message beats every Bravado message. Two receipt controls reinforce the lifecycle classification. All **200 of 200** sampled Bravado transaction hashes already had a Polygon receipt when queried immediately after the public message arrived, while Polynode pending had arrived first for all 200. We therefore classify the observed Bravado message as a post-mining trade sighting. > [!NOTE] > > The Bravado and Polymarket RTDS observations were highly correlated: 11,052 of the 11,092 RTDS-seen transaction hashes in the headline window also appeared on Bravado, and RTDS arrived 232 ms earlier at the median. Together with the payload shape, this is consistent with a republished post-trade Polymarket feed. It does **not** establish that RTDS is Bravado's upstream source. RTDS disconnected and reconnected once during the run, so it is used only as an auxiliary overlap comparison, never as ground truth. During the audit, the public endpoint was delivered through Cloudflare's edge; that reveals neither the origin provider nor the origin location. ## Same-block copy execution was uncommon in the attributed sample Polymarket's public builder data identified Bravado as a verified builder and returned **67,206 Bravado-attributed records** spanning January 4 through August 7, 2026. Within that history, one wallet showed a broad, repeatable relationship with the public trader `ferrariChampions2026`. We call the relationship **copy-like**, not proven copy trading. The evidence is unusually strong for public data: | Relationship check | Result | | - | -: | | Eligible follower transactions | 17,916 | | Same-asset, same-side matches 0–10 seconds after the leader | 1,637 (9.137%) | | Markets / assets represented | 813 / 999 | | Median timestamp lag | 3 seconds | | Median absolute price difference | \$0.01 | | Strongest shifted-time control | 127 matches (0.7089%) | | Unshifted lift over strongest control | **12.89×** | ### Why the correlation is not a generic coincidence We reran the same frozen denominator with the relationship deliberately broken in three ways. The strongest negative result is reported in each family. | Rule on the same 17,916 eligible transactions | Matches | Rate | | - | -: | -: | | Observed order: same asset and side, leader 0–10 seconds before | **1,637** | **9.137%** | | Time reversed: same asset and side, leader 0–10 seconds after | 201 | 1.122% | | Strongest of 120 nonzero time shifts from -30 to +30 minutes | 127 | 0.709% | | Opposite side, leader before | 0 | 0.000% | Timing is only part of the signature. The sizing was highly repetitive: the median follower-to-leader notional ratio was 0.13015%, and 1,255 of 1,637 pairs fell between 0.10% and 0.17%. Requiring both that sizing band and a price difference no larger than \$0.03 left **1,212 observed-sequence matches**, versus **32** in the time-reversed control and at most **22** in any shifted-time control. The observed sequence is therefore **37.9×** larger than the strongest joint negative control. The relationship was found exploratorily rather than preregistered, so we do not turn that separation into a formal probability claim. Tight timing alone could reflect two bots reacting to the same live sports signal; the directionality, repeated sizing, close prices, broad market coverage, leader-first ordering, and negative controls make direct copying the stronger explanation. Polygon receipts resolved every pair. Seventy-eight pairs were nominally in the same block, but 37 placed the proposed follower transaction before the leader transaction and therefore could not be causal copies of that leader fill. We excluded those reversals. | Chain-ordered outcome | Pairs | Share | | - | -: | -: | | Same block, leader transaction first | 41 | **2.5625%** | | Follower in a later block | 1,559 | **97.4375%** | | Total | 1,600 | 100% | The follower landed a median of **2 blocks** later and a P90 of **5 blocks** later. This directly tests the observed outcome behind a same-block claim; it does not expose Bravado's private detection time, submission time, rejected orders, missed opportunities, or the wallet's private configuration. ## Product breadth as of August 7, 2026 Bravado's public materials describe a filterable historical Data API and a substantial managed execution layer. Polynode's advantage is earlier, more structured, and broader data coverage. | Capability | Polynode | Bravado public surface reviewed | | - | - | - | | Pending transaction signal | Documented and observed `settlement` lifecycle | No public pending surface documented or observed | | Lifecycle and exact-fill identity | Pending, confirmation updates, and block-global fill identity | Public message lacked status, block number, and log index | | Combo markets | Dedicated REST data and WebSocket events | No dedicated combo API or stream documented or observed | | Perps | Market, wallet, analytics, on-chain, and streaming surfaces | No perps API or stream documented or observed | | Historical and filterable prediction-market data | V3 query catalog, filters, sorting, pagination, and aggregation | REST + WebSocket, filtering, and cursor pagination advertised | | Managed order and copy execution | Data and timing primitives for customer-owned execution | Copy engine and advanced order execution advertised | Bravado's documented split and merge operations are standard conditional-token primitives; they are not evidence of dedicated combo-market coverage. Its backtesting product was labeled **in development** on the audit date. Absence here means that no public surface was found in the reviewed first-party pages and captured stream—not that a private or unreleased implementation cannot exist. ## What this means for latency-sensitive trading For a team building its own copy-trading, rebalancing, alerting, or protective execution system, a post-mining trade stream and a pending stream are not substitutes. The first reports what made it on-chain. The second creates an opportunity to react before confirmation. Polynode's pending feed does not guarantee that a customer's transaction will be included in the same block; gas policy, signing, routing, order construction, and block conditions still matter. It does provide the missing prerequisite: an early signal. In this test, that signal arrived before every overlapping Bravado public sighting and did so **2.104 seconds earlier at the median**. Teams considering a managed copy engine should validate the result they care about directly from receipts. In the attributable relationship studied here, a same-block outcome occurred in 2.56% of causally ordered pairs, not most of them. ## Evidence and claim boundaries All competing callbacks in the timing run were stamped from one process and one monotonic clock. Fully observed block boundaries, independent Polygon logs, receipts, and rechecked block hashes defined the denominator. The exact public endpoint address and connection details are intentionally omitted because they are unnecessary to reproduce the numerical claims from the published evidence. * [Compact evidence summary](/assets/case-studies/2026-08-07-bravado-pending-copy-execution/summary.json) * [Full aggregate negative controls](/assets/case-studies/2026-08-07-bravado-pending-copy-execution/correlation-negative-controls.json) * [Bravado public-stream missing transactions](/assets/case-studies/2026-08-07-bravado-pending-copy-execution/bravado-missing-transactions.json) * [Published artifact checksums](/assets/case-studies/2026-08-07-bravado-pending-copy-execution/checksums.json) The full raw capture, normalized events, receipts, attribution rows, latency samples, source snapshots, and SHA-256 inventories are retained internally. No Bravado API credential was used. ## References * [Bravado homepage and same-block claim](https://www.bravadotrade.com/) * [Bravado Copytrading API](https://www.bravadotrade.com/products/copytrade-api) * [Bravado Data API](https://www.bravadotrade.com/products/data-api) * [Bravado Trade API](https://www.bravadotrade.com/products/trade-api) * [Polynode WebSocket](/websocket/overview) * [Polynode combo markets](/data/combos/overview) * [Polynode perps](/perps/overview) * [Polynode V3 Data API](/data/overview) Last evidence audit: **2026-08-07 04:52 UTC**. # Case studies Source: https://docs.polynode.dev/case-studies/overview Dated, reproducible studies of Polynode performance, coverage, and production behavior. Polynode case studies test a concrete product claim against a defined denominator. Each study records its date, endpoints, subscription semantics, source versions, measurement clock, eligibility window, adverse observations, and limitations. > [card] [Polynode confirmation vs RTDS](/case-studies/pending-confirmed-websocket-latency-2026-08-14) > > Pending delivery, confirmation timing, confirmed-fill timing, and exact on-chain completeness measured on August 14, 2026. > [card] [Polynode vs Bravado](/case-studies/bravado-pending-copy-execution-2026-08-07) > > Pending latency, public-stream coverage, observed same-block copy execution, and product breadth measured on August 7, 2026. > [card] [Polynode vs Struct and RTDS](/case-studies/struct-rtds-websocket-benchmark-2026-08-01) > > WebSocket latency, pending access, and confirmed-fill completeness measured on August 1 and retested on August 4, 2026. > [card] [Polygon block time and Polymarket](/case-studies/polygon-block-time-polymarket-2026-08-04) > > How Polygon's move from 2.0-second to 1.5-second blocks compressed Polymarket's pre-confirmation window without moving Polynode's position in the transaction lifecycle. ## Evidence standard Every benchmark case study should: * define equivalent signals before measuring them; * timestamp all competitors from the same monotonic clock and process; * use an independent completeness denominator when one exists; * exclude partially observed boundary intervals; * preserve per-sample data, missing identifiers, source hashes, and connection lifecycle events; * report unfavorable windows and unavailable comparisons; * separate measured results from broader product claims; * publish code with credentials supplied only at runtime. These are point-in-time measurements, not guarantees about every network location or future provider version. # Pending and confirmed WebSocket delivery: Polynode vs RTDS and Struct Source: https://docs.polynode.dev/case-studies/pending-confirmed-websocket-latency-2026-08-14 An August 14, 2026 production benchmark of Polynode pending detection, confirmation delivery, confirmed fills, and exact on-chain completeness. During an August 14, 2026 Berlin-local measurement window, we raced Polynode's production WebSocket against Polymarket RTDS from an independent Server Two vantage point. A separate three-minute control raced Polynode against Struct's explicit pending subscription. Every callback in each window was timestamped in one Node.js process with one monotonic clock, then checked against Polygon logs from a benchmark-only external RPC. The 30-minute headline window contained **31,030 independently confirmed transactions and 82,092 exact fills**. Polynode represented every transaction and every fill across its pending, confirmation, and confirmed-fill paths. > [!NOTE] > > This is a Polynode-run, point-in-time benchmark. It measures customer-visible WebSocket delivery from one network location and does not guarantee future performance from every region or provider version. The external RPC supplied only post-window chain truth and contributed no competitive arrival timestamps. > [card] 857 ms confirmation lead > > Polynode `status_update` arrived first on 30,316 of 30,328 matched RTDS transactions. > [card] 823 ms confirmed-fill lead > > Polynode's first confirmed `trade` callback arrived first on 30,043 of 30,328 matched transactions. > [card] 2.285-second pending lead > > Polynode pending arrived first on every transaction shared with RTDS. > [card] 100% exact-fill coverage > > Polynode delivered all 82,092 canonical on-chain fills with zero unresolved misses. ## Bottom line The confirmed-path improvement was visible at both lifecycle layers: * Polynode `status_update` led RTDS activity by **856.6 ms at P50**, **1.129 seconds at P75**, and **1.657 seconds at P99**. Polynode arrived first on **99.960%** of matched transactions. * Polynode's first confirmed `trade` callback led RTDS activity by **822.9 ms at P50**, **1.095 seconds at P75**, and **1.609 seconds at P99**. Polynode arrived first on **99.060%** of matched transactions. * Polynode pending led RTDS activity by **2.285 seconds at P50**, **2.724 seconds at P75**, and **3.800 seconds at P99**, arriving first on **100%** of matched transactions. Those latency results are calculated only over shared transaction hashes. RTDS represented 30,328 of 31,030 eligible transactions; its 702 missing transactions are reported as missing and never converted into artificial Polynode wins. Completeness is a separate and stricter audit. Against the full on-chain denominator, Polynode delivered **31,030 of 31,030** pending settlements, **31,030 of 31,030** confirmation updates, **31,030 of 31,030** confirmed-fill transactions, and **82,092 of 82,092** canonical fills. ## Thirty-minute headline: Polynode vs RTDS | Property | Recorded value | | - | - | | Core interval | 2026-08-13 23:06:48.288–23:36:48.381 UTC | | Measurement host | Server Two, independent from the production WebSocket host | | Runtime | Node.js v20.20.0 on Linux x64 | | Eligible blocks | 91,971,589–91,972,785 inclusive | | Core / warm-up / confirmation tail | 1,800 / 15 / 60 seconds | | Chain truth | 31,030 transactions / 82,092 `OrderFilled` logs | | RTDS heartbeat / recovery | Uppercase `PING` every five seconds; resubscribe after ten seconds without global activity | | Boundary guard | Two blocks at each edge | The verifier re-read both boundary blocks after analysis. Their hashes still matched the recorded manifest. ### Coverage | Path | Unit | Seen | Coverage | Missing | | - | -: | -: | -: | -: | | Polynode pending settlement | Transaction | 31,030 / 31,030 | **100.000%** | 0 | | Polynode `status_update` | Transaction | 31,030 / 31,030 | **100.000%** | 0 | | Polynode confirmed `trade` | Transaction | 31,030 / 31,030 | **100.000%** | 0 | | Polynode confirmed `trade` | Exact fill | 82,092 / 82,092 | **100.000%** | 0 | | Polymarket RTDS activity | Transaction | 30,328 / 31,030 | 97.738% | 702 | ### Latency A positive lead means the named Polynode path arrived first. Every percentile uses only matched transaction hashes. | Polynode path vs RTDS activity | Samples | P50 lead | P75 lead | P90 lead | P95 lead | P99 lead | Polynode first | | - | -: | -: | -: | -: | -: | -: | -: | | **Pending settlement** | 30,328 | **+2.285 s** | +2.724 s | +3.109 s | +3.355 s | +3.800 s | **100.000%** | | **Confirmation `status_update`** | 30,328 | **+856.6 ms** | +1.129 s | +1.318 s | +1.440 s | +1.657 s | **99.960%** | | **First confirmed `trade` callback** | 30,328 | **+822.9 ms** | +1.095 s | +1.284 s | +1.407 s | +1.609 s | **99.060%** | RTDS activity is a public timing baseline, not an exact pending or confirmed lifecycle label. The table keeps Polynode's pending, transaction-confirmation, and first confirmed-fill callbacks separate. ### Adverse observations RTDS arrived before Polynode `status_update` for 12 of 30,328 matched transactions. Those 12 transactions occupied two blocks, and the worst observed Polynode loss was **98.0 ms**. RTDS arrived before Polynode's first confirmed `trade` callback for 285 matched transactions across 19 blocks. The worst observed loss was **2.268 seconds**. This first-callback timing result does not affect the exact-fill audit: Polynode still delivered all 82,092 canonical fills. RTDS missed 702 eligible transactions across 24 blocks: | Missing block range | Missing transactions | Recorded behavior | | - | -: | - | | 91,971,841 | 55 | Isolated missing block while activity otherwise continued | | 91,972,084 | 6 | Isolated missing block while activity otherwise continued | | 91,972,297–91,972,303 | 176 | Activity stopped; watchdog reconnected and resubscribed | | 91,972,373–91,972,380 | 174 | Activity stopped; watchdog reconnected and resubscribed | | 91,972,469–91,972,475 | 291 | Activity stopped; watchdog reconnected and resubscribed | The three scored silent intervals were detected only after 10.7–10.8 seconds without global activity. In each case, the missing block run preceded the reconnect and activity resumed immediately after resubscription. A fourth audited reconnect occurred during the post-window confirmation tail and did not change the eligible denominator. ## Explicit Struct-pending control The non-overlapping control requested Struct's documented pending mode directly: ```json theme={null} { "room": "polymarket_trades", "filters": { "status": "pending", "subscribe_all": true } } ``` Struct accepted the subscription with `subscribe_all: true` and an empty `rejected` array. The collector used a raw WebSocket and stamped each callback before JSON parsing. The three-minute scored interval covered **2,863 transactions and 7,590 fills** across blocks 91,971,403–91,971,519. Polynode pending arrived first on all 2,784 matched transactions by **30.023 seconds at P50**. Polynode had also delivered `status_update` before every matched Struct pending callback, by **28.424 seconds at P50**. | Path | Unit | Seen | Coverage | Missing | | - | -: | -: | -: | -: | | Polynode pending settlement | Transaction | 2,863 / 2,863 | **100.000%** | 0 | | Polynode `status_update` | Transaction | 2,863 / 2,863 | **100.000%** | 0 | | Polynode confirmed `trade` | Exact fill | 7,590 / 7,590 | **100.000%** | 0 | | Struct pending | Transaction | 2,784 / 2,863 | 97.241% | 79 | | Polymarket RTDS activity | Transaction | 2,863 / 2,863 | **100.000%** | 0 | | Comparison | Samples | P50 lead | P75 lead | P90 lead | P95 lead | P99 lead | Polynode first | | - | -: | -: | -: | -: | -: | -: | -: | | **Polynode pending vs Struct pending** | 2,784 | **+30.023 s** | +31.993 s | +33.547 s | +34.264 s | +35.565 s | **100.000%** | | **Polynode `status_update` vs Struct pending** | 2,784 | **+28.424 s** | +30.639 s | +32.084 s | +32.960 s | +34.486 s | **100.000%** | The 79 unmatched Struct transactions receive no synthetic latency penalty. They remain missing in the coverage result. ## Signal mapping The feeds do not use identical lifecycle names, so the mapping was fixed before collection. | Question | Polynode | Struct | RTDS | Join key | | - | - | - | - | - | | Pending transaction | `settlement` with `status=pending` | Explicit `status: "pending"` subscription | Public activity baseline only | Transaction hash | | Transaction confirmation | `status_update` | Not requested in the pending-only control | Public activity baseline only | Transaction hash | | Confirmed fill timing | First `trade` callback for the transaction | Not requested in the pending-only control | Public activity baseline only | Transaction hash | | Exact confirmed-fill completeness | Every `trade` fill | Not requested in the pending-only control | Not used as a fill denominator | Transaction hash + block-global log index | | Independent denominator | Polygon `OrderFilled` logs and receipts | Same | Same | Transaction hash + block-global log index | ## Methodology and integrity Server Two connected every compared WebSocket from the same process in each window. `process.hrtime.bigint()` stamped callbacks before parsing or normalization. After warm-up, the harness armed the first eligible block at `tip + 2`; at core completion it closed the denominator at `tip - 2`. The 60-second tail allowed late confirmation callbacks to arrive before analysis. An external Polygon RPC then enumerated every current Polymarket CLOB `OrderFilled` log and receipt in the eligible range. It was a post-window verifier only: it supplied no competitive arrival timestamp and is not part of Polynode's production ingestion or delivery path. The harness extends [Struct's published RTDS benchmark](https://github.com/structbuild/polymarket-rtds-vs-struct-benchmark) with Polynode lifecycle capture and independent exact-fill truth. Both windows used the same immutable source hashes. The TypeScript compiler and all five regression tests passed, both boundary hashes rechecked, the RPC audit recorded zero failures, no raw-frame write backpressure occurred, and every retained artifact passed its SHA-256 inventory. ## Claim boundaries * These are point-in-time measurements from one independent network vantage. * RTDS activity is retained as a public baseline and is not relabeled pending or confirmed. * Confirmed Polygon logs cannot enumerate pending transactions that never confirm. * Missing competitor callbacks are coverage misses, not automatic latency wins. * First confirmed-fill timing is transaction-granular; exact fill completeness is audited separately. * The Struct control and RTDS headline are non-overlapping and are never pooled into one distribution. * The benchmark records observable callbacks and makes no claim about any provider's private implementation. ## Evidence * [Compact result and claim-evidence bundle](/assets/case-studies/2026-08-14-websocket-latency/summary.json) * [Credential-free benchmark source](/assets/case-studies/2026-08-14-websocket-latency/harness-source.json) * [RTDS missing transactions](/assets/case-studies/2026-08-14-websocket-latency/rtds-missing-transactions.json) * [RTDS stalls and competitor-first samples](/assets/case-studies/2026-08-14-websocket-latency/headline-adverse-audit.json) * [Struct missing pending transactions](/assets/case-studies/2026-08-14-websocket-latency/struct-missing-transactions.json) * [Polynode confirmed-fill missing set](/assets/case-studies/2026-08-14-websocket-latency/polynode-confirmed-fill-missing.json) * [Published-artifact checksums](/assets/case-studies/2026-08-14-websocket-latency/checksums.json) The full raw frames, normalized events, Polygon logs and receipts, per-transaction latency samples, lifecycle records, resource audit, missing identifiers, and complete SHA-256 inventories are retained internally. ## References * [Polymarket real-time data reference](https://docs.polymarket.com/market-data/realtime-data) * [Polymarket contract registry](https://docs.polymarket.com/resources/contracts) * [Struct trades-room reference](https://docs.struct.to/websockets/rooms/trades) * [Polynode WebSocket overview](/websocket/overview) * [Polynode settlement event](/websocket/events/settlement) * [Polynode status update event](/websocket/events/status-update) * [Polynode trade event](/websocket/events/trade) Last evidence audit: **2026-08-14 01:48 CEST**. # Polygon cut block time by 25%: what changed for Polymarket Source: https://docs.polynode.dev/case-studies/polygon-block-time-polymarket-2026-08-04 A measured study of Polygon's move from 2.0-second to 1.5-second blocks and the resulting change in Polymarket pre-confirmation timing. Between April and June 2026, Polygon reduced its average block interval from **2.0 seconds to 1.5 seconds**. Over the same period, PolyNode's median lead between first seeing a Polymarket settlement and its eventual block timestamp fell from **3.08 seconds to 2.28 seconds**. That initially looked like a slower feed. It was not. Measured in block intervals, the median moved only from **1.54 blocks to 1.52 blocks**. The 90th percentile was even closer: **1.975 blocks before and 1.973 blocks after**. PolyNode's position in the transaction lifecycle stayed essentially fixed while Polygon shortened the lifecycle itself. This is why a 3–5-second description that matched the earlier data now looks more like two to three seconds in current measurements. > [!NOTE] > > This is a PolyNode-run, point-in-time network study. PolyNode runs its own Polygon node, and the timing data reflects what we observed from that node against canonical Polygon block inclusion. > [card] 25% shorter blocks > > Polygon's measured average cadence moved from 2.0 seconds to 1.5 seconds. > [card] 33.3% more block opportunities > > A 15-minute interval moved from about 450 blocks to about 600. > [card] 0.02-block median change > > PolyNode's median pre-confirmation position moved from 1.54 to 1.52 blocks. > [card] Current result confirmed > > A fresh August 4 observation from our Polygon node remained in the current two-to-three-second range. ## The result The clean before-and-after comparison uses the same measurement on both dates: join a PolyNode pending detection to its later canonical Polygon transaction by hash, then subtract the detection time from the block header timestamp. | Measurement | Polygon cadence | Samples | Median lead | P90 lead | Lead in blocks, median / P90 | | - | -: | -: | -: | -: | -: | | April 14, 2026 | 2.0 s | 602 | 3.08 s | 3.95 s | 1.540 / 1.975 | | July 6, 2026 | 1.5 s | 3,770 | 2.28 s | 2.96 s | 1.520 / 1.973 | | August 4 control: current node observation | 1.5 s | 4,780 | 2.137 s | 2.866 s | 1.425 / 1.911 | The August row is a separately collected observation from PolyNode's own Polygon node and is shown as a current control rather than folded into the before-and-after calculation. If the April distribution is scaled only by the change in block cadence, it predicts: * median: `3.08 × (1.5 / 2.0) = 2.31 seconds`; observed in July: **2.28 seconds**; * P90: `3.95 × (1.5 / 2.0) = 2.9625 seconds`; observed in July: **2.96 seconds**. The cadence-only prediction misses the observed median by 30 milliseconds and the P90 by about 3 milliseconds. That does not prove every component of the network was unchanged, but it is strong evidence that the missing wall-clock second came from Polygon's shorter block interval rather than a one-second regression inside PolyNode. Two larger customer-visible WebSocket windows point to the same current range. In the [August 1 and August 4 benchmark](/case-studies/struct-rtds-websocket-benchmark-2026-08-01), PolyNode pending arrived before its own `status_update` by 2.148 seconds at the median over 18,041 transactions and 2.215 seconds over 18,122 transactions. Those measurements use same-process callback timing rather than block timestamps, so they corroborate the current window without being mixed into the normalized calculation. ![April latency scaled to Polygon's 1.5-second cadence closely predicts the July observation.](https://mintcdn.com/polynode/qKX6heRBUtKu3Q2w/assets/case-studies/2026-08-04-polygon-block-time-polymarket/lead-compression.svg?fit=max\&auto=format\&n=qKX6heRBUtKu3Q2w\&q=85\&s=8ff6dbbbdf0153793a4fc879222e5979) ## What Polygon changed [PIP-75](https://forum.polygon.technology/t/pip-75-change-consensus-time-to-1-second/21376) made two related changes to Polygon's Bor block producer: 1. It lowered the consensus `Period` floor from two seconds to one second. 2. It added a configurable `blockTime` with sub-second precision, based on the parent block's actual announcement time. The distinction matters. PIP-75 did **not** immediately move mainnet to one-second blocks. It created a one-second safety floor and made intermediate operating points such as 1.75 and 1.5 seconds possible without another hardfork. Polygon's [Madhugiri announcement](https://polygon.technology/blog/polygon-speeds-up-by-33-with-madhugiri-hardfork) framed that flexibility as a way to reduce latency and tune future throughput without repeatedly changing consensus rules. The header format did not gain fractional timestamps. `header.Time` remains an integer Unix second, so a real 1.75-second cadence appears in headers as roughly 25% one-second gaps and 75% two-second gaps. A 1.5-second cadence appears as roughly half one-second and half two-second gaps. The average over consecutive headers is the useful number. Our immutable header samples showed the transition directly: | Sample date | Consecutive headers | Mean interval | Integer timestamp-gap distribution | | - | -: | -: | - | | March 26, April 14, and April 24 | 500–1,000 per date | 2.000 s | 100% two-second gaps | | May 15 and June 1 | 500–1,000 per date | 1.750 s | About 25% one-second / 75% two-second | | June 18 and July 6 | 500–1,000 per date | 1.500 s | About 50% one-second / 50% two-second | ## Why Polygon made the change Polygon's public rationale was lower confirmation latency, smoother application UX, and greater payments capacity. Shorter blocks provide more inclusion opportunities per unit of time: moving from 2.0 to 1.5 seconds increases block opportunities from 0.5 to 0.667 per second, or **33.3%**. The change also had a less visible validator-economics consequence. Polygon submits a checkpoint every 5,120 blocks. Faster blocks therefore create more checkpoints per year. [PIP-86](https://forum.polygon.technology/t/pip-86-recalibrate-checkpoint-reward-for-reduced-polygon-block-times/21864) specified corresponding per-checkpoint rewards of 29,414.92 POL at 1.75 seconds and 25,212.79 POL at 1.5 seconds to preserve the targeted annual emission. The proposal estimated that leaving the old reward unchanged at 1.5 seconds would mechanically raise emissions by roughly 1.4×. There is a tradeoff. PIP-75 notes that shorter intervals leave less time for each block to propagate, so validator coordination and block propagation matter more as cadence falls. Polygon chose 1.5 seconds as an operating point above the new one-second consensus floor, not as an arbitrary timestamp edit. > [!NOTE] > > Polygon's later claim of supporting up to [5,000 payments per second](https://polygon.technology/blog/polygon-chain-now-supports-5000-payments-per-second-hitting-the-speed-of-a-card-network-at-a-fraction-of-the-cost) is a capacity result that also reflects gas-limit work. It is not a measurement of sustained mainnet traffic and should not be compared directly with the observed transaction rates below. ## When it happened, and how unusual it was [PIP-86's](https://forum.polygon.technology/t/pip-86-recalibrate-checkpoint-reward-for-reduced-polygon-block-times/21864) planning dates were May 5 for 1.75 seconds and May 19 for 1.5 seconds. Polygon publicly announced the first live reduction on [May 6](https://x.com/0xPolygon/status/2052120167736389721) and the second on [June 3](https://x.com/0xPolygon/status/2062240408030310525). Our headers independently show 1.75 seconds by May 15 and 1.5 seconds by June 18. Polygon described the May change as its **first block-time reduction since genesis**, then made the second reduction four weeks later. This was therefore not a routine historical oscillation. PIP-75 does make future tuning operationally easier, but Polygon has published no recurring schedule for block-time changes. Several earlier upgrades made Polygon faster in other senses and are easy to conflate with this change: * [Aalborg](https://polygon.technology/blog/faster-finality-with-the-aalborg-upgrade-for-polygon-proof-of-stake-network) accelerated deterministic finality with milestones in 2023; it did not shorten the block interval. * [Rio](https://polygon.technology/blog/polygon-launches-major-payments-upgrade-with-rio-faster-lighter-and-easier-to-build) changed block-production and finality architecture in October 2025 and laid groundwork for later timing flexibility. * [Madhugiri](https://polygon.technology/blog/polygon-speeds-up-by-33-with-madhugiri-hardfork) activated PIP-75 in December 2025, but our April 2026 headers were still at 2.0 seconds. * [Giugliano](https://polygon.technology/blog/giugliano-upgrade-faster-confirmations-predictable-fees-and-a-more-resilient-network-for-polygon-chain) introduced earlier block announcements in April 2026. That improved propagation and confirmation signaling; it was not the May–June cadence cut. * [Ithaca](https://polygon.technology/blog/ithaca-upgrade-is-live-payments-on-polygon-chain-are-more-reliable-than-ever) improved producer failover and reliability in July 2026. Headers remained at 1.5 seconds afterward. Finality, early block announcement, gas capacity, and block cadence all affect perceived speed, but they are different mechanisms. ## How this reaches Polymarket [Polymarket documents](https://docs.polymarket.com/concepts/order-lifecycle) a hybrid lifecycle: orders are created and matched offchain; after a match, the operator submits a settlement transaction to Polygon; that transaction is mined and later confirmed. Shorter Polygon blocks do not make the CLOB match orders faster. They affect the part after submission by reducing the wait for the next inclusion opportunity. They also compress the wall-clock interval during which a transaction can be visible in the mempool before it appears in a block. That is exactly the interval PolyNode measures. At an unchanged position of roughly 1.5 block intervals before inclusion: * a 2.0-second chain produces about 3.0 seconds of median lead; * a 1.5-second chain produces about 2.25 seconds of median lead. The same network position therefore yields a smaller number of seconds after the upgrade. For latency-sensitive consumers, the feed did not become less early relative to Polygon; Polygon reached the next block sooner. ## Was higher traffic the cause? The two matched 15-minute snapshots we checked do not support that explanation. We enumerated canonical Polygon transactions and Polymarket `OrderFilled` logs for two April windows and two August windows. | Window | Contract era | Blocks | Polygon tx/s | Polymarket settlement tx/s | Polymarket fills/s | | - | - | -: | -: | -: | -: | | April 14, 01:10–01:25 UTC | V1 | 450 | 121.75 | 38.81 | 111.27 | | April 14, 12:30–12:45 UTC | V1 | 450 | 144.00 | 43.47 | 118.96 | | August 1, 12:30–12:45 UTC | V2 | 600 | 64.68 | 20.14 | 53.89 | | August 4, 01:10–01:25 UTC | V2 | 600 | 71.21 | 20.31 | 57.05 | Across those snapshots, April averaged **132.88 Polygon transactions, 41.14 Polymarket settlement transactions, and 115.11 Polymarket fills per second**. August averaged **67.95, 20.22, and 55.47 per second**, respectively. A fill here is one canonical `OrderFilled` log; a settlement transaction is one unique transaction hash and may contain multiple fills. These are four short windows, not daily averages. They span Polymarket's [April 28 exchange upgrade](https://help.polymarket.com/en/articles/14762452-polymarket-exchange-upgrade-april-28-2026), so they cannot establish a general demand trend or attribute volume changes to contract versions. They do show that today's smaller pending window did not arise because the measured August windows carried more Polygon or Polymarket traffic than the April windows. The credential-free [throughput measurement script](/assets/case-studies/2026-08-04-polygon-block-time-polymarket/measure-polymarket-throughput.mjs) and exact block anchors are included in the [compact evidence bundle](/assets/case-studies/2026-08-04-polygon-block-time-polymarket/summary.json). ## Today's control On August 4, a fresh observation from PolyNode's own Polygon node measured 2.137 seconds of lead at the median and 2.866 seconds at P90 over 4,780 included transactions. That independently confirmed the current two-to-three-second range without changing the before-and-after calculation. ## Can a four-second lead come back? Not consistently under the position measured here. Four seconds on a 1.5-second chain is 2.67 block intervals. The historical P90 was about 1.97 block intervals, and the July P90 is still about 1.97. Recovering a durable four-second P90 now would require observing transactions roughly one full second earlier relative to Polygon block inclusion than the position that produced the old 3.95-second P90. The measurements in this study show no missing second inside the existing comparison; they show that Polygon shortened the wall-clock interval represented by nearly the same number of blocks. For product measurement, a block-relative description is now more durable than a fixed promise in seconds: PolyNode typically observes these settlements around **one to two block intervals before inclusion**, which is currently about **two to three seconds** for the measured population. ## What was already public Polygon's own announcements and [news coverage](https://cointelegraph.com/news/polygon-reduces-block-production-time-175-second) explained the chain-wide speed and payments-capacity changes. Polygon also connected 1.5-second blocks and higher gas capacity to [preparing for Polymarket demand](https://polygon.technology/blog/a-billion-fans-five-weeks-one-network-we-spent-six-months-preparing-polygon-chain-for-the-summers-biggest-sporting-event), without measuring the pending-to-inclusion window. We did not locate a published study that followed both cadence cuts, normalized the before-and-after Polymarket window by block interval, and included a current observation from a Polygon node. Public-search results are not a complete denominator, so this is a description of the material we found, not a claim that nobody else has measured it. ## Method and limitations * The April and July latency rows join pending detections only to transactions later included onchain. Pending transactions that never land are outside that denominator. * April and July use PolyNode's recorded observation time against Polygon's block header timestamp. The August control is a separately collected observation from our Polygon node and is intentionally reported separately. * Polygon header timestamps have one-second resolution. Quantiles over hundreds or thousands of transactions reduce the visible quantization, but the comparison is not a nanosecond benchmark. * The historical rows are retained aggregate measurements. * The traffic rows are four 15-minute snapshots across different Polymarket contract eras. They are not daily averages and do not show that shorter blocks caused more trading, fewer failed settlements, or fewer attacks. * Polygon's published payments-per-second figures are capacity tests, not sustained observed traffic. * All results are date-specific. Polygon can tune block time again under the mechanism enabled by PIP-75. ## The durable takeaway Polygon's timing changed; PolyNode's position relative to it did not materially change. A fixed claim in seconds hid that distinction, while the transaction-level record made it visible. PolyNode has followed Polymarket settlement continuously across the V1 and V2 contract eras, from pending transactions through block inclusion and individual fills. That continuity is the practical value of the platform: when Polygon or Polymarket changes underneath an application, we can measure where the time moved instead of guessing from the number that changed on a chart. Last evidence audit: **2026-08-04 05:20 UTC**. # WebSocket latency and completeness: PolyNode, Struct, and RTDS Source: https://docs.polynode.dev/case-studies/struct-rtds-websocket-benchmark-2026-08-01 Reproducible August 1 and August 4, 2026 benchmarks of pending detection, confirmed fills, and on-chain completeness. On August 1, 2026, we raced PolyNode, Struct, and Polymarket RTDS from one Node.js process, then checked every eligible result against Polygon logs obtained separately through a benchmark-only external Alchemy RPC. On August 4, we repeated the same 15-minute headline configuration with unchanged collector and analysis source, then ran exact-key and explicit pending-only controls. The two headline windows covered **36,163 transactions and 99,237 fills** across 1,195 fully observed Polygon blocks. > [!NOTE] > > These are PolyNode-run, point-in-time smoke tests. The Alchemy endpoint was used only by the benchmark verifier to enumerate confirmed events and recheck boundary blocks. It is not part of PolyNode's production ingestion, `status_update` generation, or WebSocket delivery path, and it supplied no arrival timestamps used in the latency comparisons. All claims below are limited to the recorded configurations, windows, and network vantage point. > [!TIP] > > **August 4 retest.** Struct's documented pending path was again not observed: zero pending events in the 15-minute headline run, zero with the exact August 1 credential, and zero under an explicit `status: "pending"` control. PolyNode `status_update` beat Struct confirmed on all 18,122 matched transactions by **9.265 seconds median**, versus 3.963 seconds on August 1—**2.34× the measured August 1 lead**. PolyNode's confirmation timing relative to RTDS moved only 38.5 ms between the two headline windows while Struct's lag behind RTDS grew by 5.370 seconds, evidence of substantial between-window variability in Struct's confirmed-delivery lane. > [card] No Struct pending—again > > Four August 4 windows, including exact-key and pending-only controls, produced zero Struct pending events. > [card] 9.27-second confirmation lead > > PolyNode `status_update` beat Struct confirmed on all 18,122 August 4 transactions. > [card] 2.34× the August 1 lead > > The measured confirmation lead grew from 3.963 seconds to 9.265 seconds. > [card] 100% confirmed coverage > > PolyNode and Struct each represented all 50,956 August 4 fills after reconciliation. ## August 4 retest: pending still not observed Struct's current [trades-room reference](https://docs.struct.to/websockets/rooms/trades) still defines `status: "all"` as both pending and confirmed, and its [mempool guide](https://docs.struct.to/guides/copy-trading-pending-or-confirmed-trades) says pending events arrive before block confirmation. We reran the published request without a trade-type filter: ```json theme={null} { "room": "polymarket_trades", "filters": { "status": "all", "subscribe_all": true } } ``` The August 4 headline subscription was accepted with `subscribe_all: true`, an empty `rejected` array, and continuous confirmed delivery. It emitted no pending events. The acknowledgment, as on August 1, did not echo the requested `status` field. ### What changed since August 1 Both headline windows used the same host, one-process monotonic clock, source hashes, 12-second warm-up, two-block boundary guard, 30-second confirmation tail, official lowercase RTDS heartbeat, and five-second RTDS silence recovery. | Metric | August 1 | August 4 | Measured change | | - | -: | -: | -: | | Eligible transactions | 18,041 | 18,122 | +81 | | Struct pending events | 0 | 0 | Still not observed | | PolyNode `status_update` vs Struct confirmed, median lead | +3.963 s | **+9.265 s** | **+5.302 s / 2.34×** | | PolyNode `status_update` first | 100.00% | 100.00% | Unchanged | | PolyNode fill vs Struct confirmed record, median lead | +3.862 s | **+8.888 s** | **+5.026 s / 2.30×** | | PolyNode fill first | 99.00% | 98.17% | -0.83 percentage points | | PolyNode `status_update` vs RTDS activity, median lead | -0.171 s | -0.209 s | -0.039 s | | Struct confirmed vs RTDS activity, median lead | -4.118 s | **-9.488 s** | 5.370 s additional Struct lag | | RTDS transaction coverage | 98.537% | 99.559% | +1.022 percentage points | A positive lead means the named left-hand path arrived first. The confirmation lead over Struct increased by **133.8%** between the two measured dates. The RTDS control lane helps locate that shift: PolyNode `status_update` versus RTDS moved only 38.5 ms, while Struct confirmed fell another 5.370 seconds behind RTDS. That triangulation supports **substantial between-window variability in Struct confirmed delivery**, not a claim that every future Struct event or region will behave the same way. ### Access and filter controls The post-run credential audit found that the August 4 headline used a second accepted Struct key rather than the August 1 key. We therefore recovered the exact August 1 credential by its one-way fingerprint and reran the `status: "all"` control. We also ran an explicit `status: "pending"` control. Neither changed the result. | August 4 window | Struct credential | Request | Core | Eligible transactions / fills | Struct pending | Struct confirmed coverage | | - | - | - | -: | -: | -: | -: | | Initial connection probe | Second accepted key | `status: "all"` | 60 s | 1,385 / 3,652 | 0 | 100% | | Explicit pending control | Second accepted key | `status: "pending"` | 45 s | 706 / 1,826 | 0 | Not applicable; no Struct events | | Headline | Second accepted key | `status: "all"` | 900 s | 18,122 / 50,956 | 0 | 100% | | Exact August 1 key control | August 1 key | `status: "all"` | 60 s | 1,673 / 4,482 | 0 | 100% | Across the four non-overlapping August 4 windows, the independent denominator contained 21,886 transactions and 60,916 fills, while Struct emitted zero pending events. We retain these windows separately and do not pool their latency samples because their credentials, status semantics, and durations differ. The exact-key control also reproduced the confirmation result: PolyNode `status_update` arrived first for all 1,673 matched transactions by 9.887 seconds median, and PolyNode fills arrived first for all 4,482 reconciled fills by 9.336 seconds median. Both accepted keys returned an empty `rejected` array; the all-status runs continued delivering confirmed data, and no auth, connection-limit, or out-of-credits close was recorded. > [!NOTE] > > The defensible result is that Struct's documented pending path was **not observed again**, across two accepted credentials and an explicit pending-only request. The benchmark cannot identify why the path was absent, and confirmed logs cannot enumerate pending transactions that never reach the chain. ### August 4 headline window | Property | Recorded value | | - | - | | Core interval | 2026-08-04 01:10:04.218–01:25:04.324 UTC | | Host clock zone | Europe/Berlin, UTC+02:00 | | Runtime | Node.js v24.14.0 on Linux x64 | | Struct SDK | 0.6.7 | | Eligible blocks | 91,400,521–91,401,117 inclusive | | Boundary hashes | `0xc53dbe…c288` through `0x2da733…6192` | | Core / warm-up / confirmation tail | 900 / 12 / 30 seconds | | Chain truth | 18,122 transactions / 50,956 `OrderFilled` logs | | Struct request | `status: "all"`, `subscribe_all: true`, no trade-type filter | | RTDS heartbeat / recovery | Official lowercase `ping`; reconnect after 5 seconds without global activity | The benchmark verifier re-read both boundary blocks after analysis. Their hashes still matched the recorded manifest. #### Coverage | Path | Unit | Seen | Coverage | Missing | | - | -: | -: | -: | -: | | PolyNode pending settlement | Transaction | 18,122 / 18,122 | 100.000% | 0 | | PolyNode `status_update` | Transaction | 18,122 / 18,122 | 100.000% | 0 | | PolyNode confirmed `trade` | Fill | 50,956 / 50,956 | 100.000% | 0 | | Struct pending | Transaction | 0 / 18,122 | 0.000% | 18,122 | | Struct confirmed | Transaction | 18,122 / 18,122 | 100.000% | 0 | | Struct combined confirmed record | Fill | 50,956 / 50,956 | 100.000% | 0 | | RTDS activity | Transaction | 18,042 / 18,122 | 99.559% | 80 | Struct emitted 32,834 direct `OrderFilled` records and 18,122 `OrdersMatched` records. All 50,956 records mapped to the chain denominator with zero unmatched records and zero index/order-hash mismatches, so Struct retained 100% confirmed-fill coverage after reconciliation. #### Latency Every callback was stamped immediately with `process.hrtime.bigint()` in the same process. A positive lead means the left-hand path arrived first. | Comparison: left vs right | Samples | Median left lead | P95 left lead | Left first | | - | -: | -: | -: | -: | | PolyNode pending vs PolyNode `status_update` | 18,122 | +2.215 s | +3.332 s | 100.00% | | ★ **PolyNode `status_update` vs Struct confirmed** | 18,122 | **+9.265 s** | +10.845 s | 100.00% | | PolyNode confirmed fill vs Struct confirmed record | 50,956 | **+8.888 s** | +10.698 s | 98.17% | | ★ **PolyNode pending vs RTDS activity** | 18,042 | +2.005 s | +2.901 s | 100.00% | | PolyNode `status_update` vs RTDS activity | 18,042 | -0.209 s | +0.415 s | 30.09% | | Struct confirmed vs RTDS activity | 18,042 | **-9.488 s** | -8.191 s | 0.00% | The RTDS row again prevents an incorrect claim: RTDS activity led PolyNode `status_update` by 209 ms median. PolyNode's several-second advantage against RTDS belongs to the pending stream; its 9.265-second confirmed advantage is specifically against Struct confirmed. #### Adverse observations Struct arrived first for 934 of 50,956 exact fill pairs across 324 transactions. Every loss was concentrated in the final three eligible blocks, 91,401,115–91,401,117, and the worst PolyNode fill loss was 3.018 seconds. PolyNode `status_update` still beat Struct confirmed for every transaction, including that cluster. RTDS silently stopped delivering global activity for 5.788 seconds. Its 80 misses occupied exactly four blocks, 91,400,687–91,400,690; activity resumed at block 91,400,691 after the watchdog reconnected and resubscribed. The [80 missing transaction hashes](/assets/case-studies/2026-08-04-websocket-retest/rtds-missing-transactions.json) are published for audit. The [August 4 compact evidence bundle](/assets/case-studies/2026-08-04-websocket-retest/headline-summary.json) contains the claim/evidence matrix, exact configuration, cross-date metrics, controls, source hashes, block anchors, adverse clusters, integrity results, and SHA-256 inventory for the full retained archives. ## What the August 1 test established In this window, PolyNode's confirmation signal beat Struct's confirmed signal for all **18,041** matched transactions by **3.963 seconds median**. At exact fill granularity, PolyNode beat Struct on **47,796 of 48,281 fills**, or **98.995%**, by **3.862 seconds median**. PolyNode pending also arrived before RTDS activity for every one of their **17,777** shared transactions, by **1.984 seconds median**. RTDS was not a complete denominator: even with a five-second silence watchdog and automatic resubscription, it represented **17,777 of 18,041** eligible transactions. We did **not** find evidence that Struct was missing confirmed transactions or fills. Struct's documented pending path, however, produced no events in the headline run or any retained test window. That result supports the narrow statement that we could not reproduce Struct pending delivery with the documented request on a fresh, credited account. It does not establish why the events were absent. > [!NOTE] > > **No higher-tier requirement found.** [Struct's own benchmark](https://www.struct.to/blog/polymarket-rtds-vs-struct-trades-ws) says that pending mode is included starting on the free plan, while its [trades-room reference](https://docs.struct.to/websockets/rooms/trades) presents `pending` and `all` as ordinary optional status filters. The August 1 subscription, the August 4 headline with a second accepted key, and the August 4 exact-key control were acknowledged with `subscribe_all: true`, an empty `rejected` array, and continued confirmed delivery. We recorded no authentication, connection-limit, or out-of-credits close; [Struct documents](https://docs.struct.to/guides/errors) exhausted credits as close code `4004`. We therefore found no evidence that a paid plan or enhanced key was required. An undisclosed entitlement cannot be ruled out from outside Struct, but it would contradict the published access claim and was not surfaced to the client. ## Signal mapping The word "trade" does not identify the same lifecycle stage in every feed. We fixed the mapping before collecting data. | Question | PolyNode | Struct | RTDS | Join key | | - | - | - | - | - | | Pending detection | `settlement` with `status=pending` | `received_at` present and `block` absent | `activity/trades` or `activity/orders_matched` as a baseline only | Transaction hash | | Transaction confirmation | `status_update` | First confirmed record carrying `block` | Activity arrival as a baseline only | Transaction hash | | Confirmed fill | `trade` | Confirmed `OrderFilled`, plus the corresponding `OrdersMatched` representation | Not used for fill completeness | Transaction hash + canonical log index | | Completeness truth | Polygon `OrderFilled` logs through the benchmark-only Alchemy verifier | Same | Same | Transaction hash + block-global log index | PolyNode [`status_update`](/websocket/events/status-update) means that a previously pending transaction was confirmed in a Polygon block. It is therefore the transaction-level equivalent used against Struct confirmed. It does not identify every individual fill inside that transaction; PolyNode [`trade`](/websocket/events/trade) is the stricter fill-level comparison. PolyNode [`settlement`](/websocket/events/settlement) with `status=pending` is the pre-confirmation path. RTDS activity is useful as a public timing baseline, but we do not label it as either pending or confirmed. Its official schema is not an exact semantic equivalent of both stages. ## August 1 headline run | Property | Recorded value | | - | - | | Core interval | 2026-08-01 12:30:08.435–12:45:08.523 UTC | | Host clock zone | Europe/Berlin, UTC+02:00 | | Runtime | Node.js v24.14.0 on Linux x64 | | Struct SDK | 0.6.7 | | Eligible blocks | 91,254,927–91,255,524 inclusive | | Boundary hashes | `0xbb804d…24c2` through `0x6c6430…9a67` | | Core / warm-up / confirmation tail | 900 / 12 / 30 seconds | | Chain truth | 18,041 transactions / 48,281 `OrderFilled` logs | | RTDS heartbeat | Official lowercase `ping`, pong-paced | | RTDS recovery | Reconnect and resubscribe after 5 seconds without global activity | | Struct request | `status: "all"`, `subscribe_all: true`, no trade-type filter | The benchmark verifier re-read both boundary blocks after analysis. Their hashes still matched the recorded manifest. ## August 1 coverage results Coverage is measured only inside the fully observed block window. Transaction coverage asks whether a feed surfaced a transaction at least once. Fill coverage requires every individual on-chain execution. | Path | Unit | Seen | Coverage | Missing | | - | -: | -: | -: | -: | | PolyNode pending settlement | Transaction | 18,041 / 18,041 | 100.000% | 0 | | PolyNode `status_update` | Transaction | 18,041 / 18,041 | 100.000% | 0 | | PolyNode confirmed `trade` | Fill | 48,281 / 48,281 | 100.000% | 0 | | Struct pending | Transaction | 0 / 18,041 | 0.000% | 18,041 | | Struct confirmed | Transaction | 18,041 / 18,041 | 100.000% | 0 | | Struct combined confirmed record | Fill | 48,281 / 48,281 | 100.000% | 0 | | RTDS activity | Transaction | 17,777 / 18,041 | 98.537% | 264 | The PolyNode pending row means that every transaction later present in the chain denominator had an earlier PolyNode pending sighting. Confirmed logs cannot prove completeness for pending transactions that never reach the chain. ### Why Struct's strict `OrderFilled` count initially looked low Struct emitted 30,240 `OrderFilled` records and 18,041 `OrdersMatched` records for the 48,281 chain fills. Counting only its `OrderFilled` type would incorrectly report 62.63% coverage. For each transaction, Struct's `OrdersMatched` record carried the taker order hash corresponding to one on-chain `OrderFilled`. We fetched every receipt, translated Struct's receipt-local log indexes to Polygon's block-global indexes, and mapped `OrdersMatched` by unique transaction and order hash. All 48,281 records reconciled with: * zero unmatched records; * zero index/order-hash mismatches; * 30,240 direct receipt-index mappings; * 18,041 unique `OrdersMatched` mappings. The defensible conclusion is therefore **100% Struct confirmed-fill coverage**, not 62.63%. ## August 1 latency results Every callback was stamped immediately with `process.hrtime.bigint()` in the same process. A positive lead means the left-hand path arrived first. Missing events never become artificial zero-latency samples. | Comparison: left vs right | Samples | Median left lead | P95 left lead | Left first | | - | -: | -: | -: | -: | | PolyNode pending vs PolyNode `status_update` | 18,041 | +2.148 s | +3.189 s | 100.00% | | ★ **PolyNode block confirmation (`status_update`) vs Struct confirmed** | 18,041 | +3.963 s | +5.083 s | 100.00% | | PolyNode confirmed fill vs Struct confirmed record | 48,281 | +3.862 s | +5.061 s | 99.00% | | ★ **PolyNode pre-confirmation (pending) vs RTDS activity** | 17,777 | +1.984 s | +2.858 s | 100.00% | | PolyNode block confirmation (`status_update`) vs RTDS activity | 17,777 | -0.171 s | +0.428 s | 34.48% | | Struct confirmed vs RTDS activity | 17,777 | -4.118 s | -2.964 s | 0.00% | ★ The two primary comparisons: PolyNode's confirmed-transaction signal against Struct confirmed, and PolyNode's pre-confirmation signal against RTDS activity. The RTDS comparison is an important check against overclaiming. RTDS activity arrived **171 ms before** PolyNode `status_update` at the median and won 65.52% of their overlaps. It is therefore wrong to describe PolyNode confirmation as several seconds ahead of RTDS. The several-second confirmed advantage is against Struct; the PolyNode advantage against RTDS belongs to the pending signal. ### Adverse fill windows Struct arrived first for 485 fills across 203 transactions. Those losses were concentrated in six blocks: 91,254,964–91,254,965, 91,255,009–91,255,010, and 91,255,121–91,255,122. The worst observed PolyNode loss was 2.187 seconds. Outside those blocks, PolyNode won every exact fill pair. We include the clusters because a median alone would hide them. ## August 1 RTDS continuity The RTDS socket silently stopped delivering global activity three times without first producing an error or close event. The watchdog terminated the open socket and resubscribed each time. | Stall | Last observed block | First block after recovery | Missing eligible blocks | Missing transactions | Activity gap | | -: | -: | -: | - | -: | -: | | 1 | 91,255,272 | 91,255,277 | 91,255,273–91,255,276 | 187 | 7.204 s | | 2 | 91,255,476 | 91,255,481 | 91,255,477–91,255,480 | 77 | 6.966 s | | 3 | After the eligible window | After the eligible window | None eligible | 0 | 6.656 s | The final RTDS coverage was therefore 98.537%, not 100%. The [264 missing transaction hashes](/assets/case-studies/2026-08-01-websocket-benchmark/rtds-missing-transactions.json) are published as a machine-readable audit file. ## Exact collection method ### Requests sent The final run used these literal harness excerpts. `args.structStatus` was `all`, and `args.tradeTypes` was unset. > [tab] Struct > > ```ts theme={null} > const filters: Record = { > status: args.structStatus, > subscribe_all: true, > }; > if (args.tradeTypes?.length) filters.trade_types = args.tradeTypes; > const ack = await socket.subscribe("polymarket_trades", filters as never); > ``` > [tab] PolyNode > > ```ts theme={null} > const request = { action: "subscribe", type: "trades" }; > socket.send(JSON.stringify(request)); > ``` > [tab] Polymarket RTDS > > ```ts theme={null} > const request = { > action: "subscribe", > subscriptions: [ > { topic: "activity", type: "trades" }, > { topic: "activity", type: "orders_matched" }, > ], > }; > current.send(JSON.stringify(request)); > ``` Struct acknowledged `subscribe_all: true`, returned an empty `rejected` array, and streamed confirmed records. Its acknowledgment did not echo the requested `status` field. > [accordion] Run the PolyNode side > > This minimal Node.js client uses the same `trades` subscription and keeps the three lifecycle signals separate. See [WebSocket subscriptions](/websocket/subscribing) for server-side filters. > > ```bash theme={null} > npm install ws > ``` > > ```js theme={null} > import WebSocket from "ws"; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error("Missing POLYNODE_API_KEY"); > > const endpoint = new URL("wss://ws.polynode.dev/ws"); > endpoint.searchParams.set("key", apiKey); > > const ws = new WebSocket(endpoint); > > ws.on("open", () => { > ws.send(JSON.stringify({ action: "subscribe", type: "trades" })); > }); > > ws.on("message", (raw) => { > const message = JSON.parse(raw.toString()); > const items = Array.isArray(message.events) ? message.events : [message]; > > for (const item of items) { > const event = item?.data ?? item; > if (!event || typeof event !== "object") continue; > > if (event.event_type === "settlement" && event.status === "pending") { > console.log("pending", event.tx_hash); > } else if (event.event_type === "status_update") { > console.log("confirmed transaction", event.tx_hash); > } else if (event.event_type === "trade") { > console.log("confirmed fill", event.tx_hash, event.log_index); > } > } > }); > ``` ### Immediate, same-clock stamping ```ts theme={null} function now(): Stamp { return { monoNs: process.hrtime.bigint().toString(), wallMs: Date.now() }; } socket.on("message", (raw: RawData) => { const stamp = now(); const text = raw.toString(); // Parsing and normalization follow the arrival stamp. }); ``` Wall time remains in the artifacts for human auditing. All latency math uses the monotonic nanosecond value. ### Lifecycle classification ```ts theme={null} const isPending = event.received_at != null && event.block == null; recorder.event( "struct", isPending ? "pending" : "confirmed", "trade_stream_update", { tx_hash: normalizeHash(event.hash), log_index: numeric(event.log_index), block_number: numeric(event.block), order_hash: normalizeHash(event.order_hash), trade_type: typeof event.trade_type === "string" ? event.trade_type : undefined, status: isPending ? "pending" : "confirmed", }, stamp, ); if (eventType === "settlement") { recorder.event( "polynode", fields.status === "pending" ? "pending" : "settlement_other", eventType, fields, stamp, ); } else if (eventType === "status_update") { recorder.event("polynode", "confirmed", eventType, fields, stamp); } else if (eventType === "trade") { recorder.event("polynode", "confirmed_fill", eventType, fields, stamp); } ``` This preserves the pending/confirmed classification in [Struct's published benchmark](https://github.com/structbuild/polymarket-rtds-vs-struct-benchmark) while keeping PolyNode's transaction confirmation separate from its individual fills. ### Independent denominator and block boundaries After all three sockets were active and the 12-second warm-up finished, the harness read the Polygon tip and armed the first eligible block at `tip + 2`. At core completion, it ended the denominator at `tip - 2`, then kept sockets open for 30 seconds. The harness queried every known current and legacy Polymarket CLOB exchange for `OrderFilled` logs. It then fetched every eligible receipt. The headline window happened to contain only V2 fills: 39,150 from the standard exchange and 9,131 from the neg-risk exchange. Each confirmed fill was keyed as: ```ts theme={null} function fillKey(txHash: string, logIndex: number): string { return `${txHash}:${logIndex}`; } // Exact latency field used inside the sample object: left_lead_ms: Number(rightNs - leftNs) / 1_000_000, ``` Using only transaction hash would have hidden missing fills because every transaction in this window contained multiple `OrderFilled` logs. ### Reproduction command ```bash theme={null} npm ci npm test npm run check STRUCT_API_KEY='' \ POLYNODE_API_KEY='' \ POLYGON_RPC_URL='' \ npm run bench -- \ --duration-sec 900 \ --warmup-sec 12 \ --tail-sec 30 \ --struct-status all \ --rtds-heartbeat polymarket-lowercase \ --rtds-silence-reconnect-sec 5 \ --out results/headline-15m-2026-08-01 ``` Credentials are read only from environment variables. The artifacts contain redacted endpoints and short one-way fingerprints, never raw keys. ## August 1 control runs and prior windows We retained ten non-overlapping windows totaling 1,995 seconds, 39,992 confirmed transactions, and 107,210 chain fills. Struct emitted zero pending events in every retained window. | Phase | Windows | Core time | Transactions | Fills | Struct pending | Purpose | | - | -: | -: | -: | -: | -: | - | | Instrumentation smokes | 2 | 60 s | 871 | 2,433 | 0 | Validate subscriptions, normalization, and boundaries | | Exact Struct-methodology suite | 5 | 675 s | 13,595 | 36,466 | 0 | Preserve Struct's uppercase `PING` harness behavior | | Official-heartbeat control | 1 | 180 s | 3,673 | 9,832 | 0 | Replace uppercase `PING` with official lowercase `ping` | | Recovery shakedown | 1 | 180 s | 3,812 | 10,198 | 0 | Validate a 10-second silence watchdog | | Headline run | 1 | 900 s | 18,041 | 48,281 | 0 | Official heartbeat plus five-second recovery | The five-window exact-methodology suite produced these pooled results: * PolyNode and Struct each covered 100% of 13,595 confirmed transactions and 36,466 reconciled fills. * PolyNode `status_update` beat Struct confirmed by 4.017 seconds median and arrived first for every transaction. * PolyNode fills beat Struct records by 3.955 seconds median and arrived first for 95.55% of fills. * PolyNode pending beat every RTDS overlap by 1.995 seconds median. * RTDS transaction coverage was 83.96% because two later sockets stayed open but stopped delivering activity. One exact-methodology window contained a nine-block PolyNode fill-latency cluster: PolyNode won 80.87% of fills in that window while retaining 100% coverage. The other four exact windows had PolyNode first on 100% of fills. The official lowercase heartbeat did not by itself prevent RTDS silence. In its isolated 180-second control, RTDS covered 56.00% of eligible transactions and stopped for the final 52 blocks. Recovery improved coverage to 93.94% with a ten-second watchdog and 98.54% with the final five-second watchdog, but WebSocket resubscription cannot replay events lost during the gap. An earlier exploratory `status: "pending"`-only probe on the fresh credited Struct account also produced no pending events while RTDS remained active. Because that exploratory probe did not use the final artifact schema, it is recorded as diagnostic context and excluded from every scored table. ## Artifacts and integrity The [August 4 compact retest bundle](/assets/case-studies/2026-08-04-websocket-retest/headline-summary.json) contains the claim/evidence matrix, headline and control metrics, exact configurations, credential fingerprints, cross-date comparison, lifecycle gap, adverse blocks, source hashes, block anchors, and SHA-256 inventory. The separate [RTDS missing-transaction file](/assets/case-studies/2026-08-04-websocket-retest/rtds-missing-transactions.json) contains all 80 identifiers from the retest gap. The full August 4 headline archive is 493 MB and contains: * 226,513 normalized events; * 226,528 parsed raw frames; * 174,161 latency CSV lines, including the header; * every Polygon `OrderFilled` log and receipt needed for reconciliation; * exact missing identifiers and connection lifecycle events; * readable and machine-readable summaries plus verified SHA-256 checksums. The [August 1 compact result bundle](/assets/case-studies/2026-08-01-websocket-benchmark/headline-summary.json) preserves the original configuration, results, and archive checksums. The [credential-free source bundle](/assets/case-studies/2026-08-01-websocket-benchmark/harness-source.json) contains the complete harness, analyzer, tests, dependency lock, README, and license. Its source hashes match the August 4 collector exactly. For the August 4 retest, the TypeScript compiler and all three analysis regression tests passed. All JSON and NDJSON artifacts parsed, all checksums verified, all 188 RPC audit calls succeeded, both boundary hashes rechecked, and all 50,956 Struct records reconciled with zero unmatched records or identity mismatches. An exact-value scan found none of the tested credentials in source or publishable artifacts. ## Limitations * These are two dates from one network vantage point. They do not guarantee the same latency from every region or in future provider versions. * Two headline windows establish a large measured shift but do not estimate Struct's universal latency variance or justify saying every future Struct window will be inconsistent. * The August 4 headline used a second accepted Struct credential. The exact August 1 credential was retested separately and reproduced zero pending delivery and similar confirmed latency; the separate samples are not pooled. * The traffic was live, not a controlled synthetic workload. Market activity and block density varied. * On-chain logs prove confirmed completeness. They cannot enumerate pending transactions that never confirm. * RTDS is a public activity baseline, not a semantic clone of either pending or confirmed streams. * A five-second watchdog trades faster recovery for more reconnects. Different thresholds change the size of unrecoverable gaps. * Provider-supplied timestamps were retained but never used for cross-provider latency because their clock origins are not comparable. ## References * [Struct's published benchmark methodology](https://www.struct.to/blog/polymarket-rtds-vs-struct-trades-ws) * [Struct's published benchmark source](https://github.com/structbuild/polymarket-rtds-vs-struct-benchmark) * [Struct trade room documentation](https://docs.struct.to/websockets/rooms/trades) * [Struct pending and confirmed copy-trading guide](https://docs.struct.to/guides/copy-trading-pending-or-confirmed-trades) * [Polymarket official real-time data client](https://github.com/Polymarket/real-time-data-client) * [PolyNode WebSocket overview](/websocket/overview) Last evidence audit: **2026-08-04 01:49 UTC**. # Changelog Source: https://docs.polynode.dev/changelog Recent polynode API, SDK, account, and product changes, with older releases preserved in linked weekly archives. ## 2026-11-05 - Pending settlements exclude matches that cannot settle Since November 4, fake Polymarket match transactions naming real traders' wallets have been broadcast to the network. They looked like real pending trades but could never settle on chain. polynode now leaves them out. What's new: * Pending `settlement` events no longer include match transactions that Polymarket's exchange would reject, such as matches sent by a wallet that is not allowed to settle trades. * A `status_update` for a transaction that was included in a block but failed now carries `execution_status: "FAILED"` and no `confirmed_fills`. Before, it could have looked like a normal confirmation. Compatibility: * Successful confirmations are unchanged and omit `execution_status`. * Subscriptions, filters and delivery latency are unchanged. * Treat a trade as final once its `status_update` arrives without `execution_status: "FAILED"`. Docs: [Status Update Event](/websocket/events/status-update#fields) *** ## 2026-10-27 - Combo win rate by time window The Wallet Combo Summary can now count a wallet's combo wins and losses inside a time window, so you can see its win rate over the past day, week or month. What's new: * `GET /v3/wallets/{address}/combos/summary` accepts `period=1d`, `7d`, `30d`, or `custom` with `after` (inclusive) and `before` (exclusive) Unix seconds, the same window rules as the [Combo P\&L Leaderboard](/data/combos/leaderboard). * With a window, `win_count`, `loss_count`, `resolved_count` and `win_rate` count only the combo positions that settled inside it, and the response adds top-level `period` and `window`. A combo settles at its first payout to any holder. * P\&L and position counts on the summary stay all time. Compatibility: * Without a window the response is unchanged. * An invalid window, or `window=` (use `period`), returns 400 `invalid_request`. * Leaderboard rows keep their all-time win and loss counts. Docs: [Wallet Combo Summary](/data/combos/wallet-summary#time-windows) *** ## 2026-10-26 - Combo win and loss counts The Combo wallet summary and every Combo leaderboard row now include each wallet's win count, loss count and win rate. What's new: * `GET /v3/wallets/{address}/combos/summary` and each `GET /v3/combos/leaderboard` row add `win_count`, `loss_count`, `resolved_count` and `win_rate`. * `win_rate` is `win_count / resolved_count` as a 4-decimal fraction string (`"0.6964"` = 69.64%), or `null` when the wallet has no resolved combo. * A combo position is won or lost once its legs resolve. The counts are all time, whether or not the position was redeemed, and on the leaderboard they are not window-scoped (like `open_combo_count`). * `GET /v3/wallets/{address}/combos/positions` now filters by outcome: `status=resolved_win`, `status=resolved_loss`, or `status=resolved` for both. Compatibility: * Every existing field is unchanged; these are new fields only. Docs: [Wallet Combo Summary](/data/combos/wallet-summary#win-and-loss-counts), [Combo P\&L Leaderboard](/data/combos/leaderboard#row-fields), [Wallet Combo Positions](/data/combos/wallet-positions) *** ## 2026-10-22 - Combo leg market metadata and CLOB token IDs Combo WebSocket events now include market metadata on every leg, and each leg's `market.token_ids` now carries the market's CLOB token IDs. What's new: * In `combo_execution`, `combo_status_update` and `combo_lifecycle`, `legs[].market.token_ids` holds the leg market's CLOB token IDs (Polymarket's `clobTokenIds`) in outcome order. These are the IDs used for CLOB order books, prices and orders, so `market.token_ids[outcome_index]` is the CLOB token ID of the leg's selected outcome. * `legs[].market` (title, slug, image, event title and slug, outcomes and CLOB token IDs) is filled on every leg. Leg market metadata is resolved ahead of trading, so it never delays an event. A market Polymarket listed in the last couple of minutes can briefly arrive without it. * For Polymarket Protocol V2 markets, Polymarket's CLOB trades by position ID, so `market.token_ids` carries the market's position IDs for those markets. Compatibility: * Event shapes, subscriptions and filters are unchanged. * `legs[].position_id` and `leg_position_ids` still carry the leg position IDs used by the combo contracts. * The TypeScript, Python and Rust SDK types already include these fields, so no SDK upgrade is needed. Docs: [Combo leg market](/websocket/events/combo-execution#leg-market) *** ## 2026-10-21 - Owner addresses on V3 wallet endpoints V3 wallet endpoints now accept an owner EOA. Pass the EOA and the response combines its Polymarket wallets (Safe, proxy, deposit wallets) that have data, so one call covers an account that holds funds in more than one wallet. What's new: * Pass an owner EOA to `GET /v3/wallets/{address}`, `/pnl`, `/pnl/events`, `/positions`, `/trades`, `/activity`, `/splits`, `/merges`, `/redemptions`, `/fees-paid`, `/nrc`, the wallet combo routes and the wallet credits routes, as `wallet` on `/v3/combos/activity` and `/v3/combos/redemptions`, or inside `POST /v3/wallets/batch`. * Combined responses add a `wallets` array of `{wallet, type}` objects, with `type` one of `eoa`, `safe`, `proxy` or `deposit_wallet`. In `POST /v3/wallets/batch` it sits inside each combined element. List rows add `wallet`, the wallet each row belongs to. * Totals, counts and time-series buckets are summed across the combined wallets. Lists keep their usual sort order and pagination fields, and combining covers the first 10,000 rows (`offset + limit`). Compatibility: * Passing a Safe, proxy or deposit wallet returns just that wallet, exactly as before. So does an EOA that owns no wallets with data. * The new fields are additive. If you key positions by `token_id` or fills by `id`, add `wallet` to the key for combined responses, since two of an owner's wallets can return the same token or fill. * Rebates, rewards, Copy PnL, webhooks, WebSocket filters and the V1 and V2 endpoints are unchanged. Docs: [Owner addresses](/data/overview#owner-addresses) *** ## 2026-10-11 - Polymarket Protocol V2 markets Polymarket is moving newly created markets to Polymarket Protocol V2, its new market system, from around November 2, 2026 (tentative, per Polymarket). Its test markets have traded since October 5, 2026 and run until October 30, 2026. Polymarket Protocol V2 is separate from Polymarket's April 2026 exchange upgrade, which these docs and the `exchange_version: "v2"` field call "V2". Current markets behave exactly as before. What you need to do: * REST and WebSocket: nothing. Same endpoints, same subscriptions, same response shapes. * Trading, split, merge or redeem with our SDK: upgrade to `polynode-sdk` 0.15.0 (npm), `polynode` 0.18.0 (crates.io) or `polynode` 0.15.1 (PyPI) before November 2, 2026. Older versions keep working on current markets, but Polymarket rejects their orders on Protocol V2 markets and no funds move. * SDK short-form market discovery and the redemption watcher: upgrade to the same versions. * Storing outcome ids yourself: use strings, up to 78 digits. What's new: * Protocol V2 markets appear in the same REST routes and WebSocket streams. Their rows and events add `protocol_version: "v2"` and `module` (`"binary"` or `"neg_risk"`). Rows and events without these fields are current markets. * REST rows for Protocol V2 markets also carry `structural_condition_id`, on multi-outcome markets `neg_risk_event_id`, and on resolved markets the exact `payouts_ppm`. * WebSocket trades settled on ExchangeV3 carry `exchange_version: "v3"`. The `exchange` field keeps its two existing values, so typed decoders keep working. * Protocol V2 results arrive as `condition_resolution` oracle events with the usual `payouts`, plus the exact `payouts_ppm` and a `derived` flag. * Condition id parameters and filters accept both the 66-character form and Polymarket's 31-byte form. * The SDKs sign each order for the right exchange automatically, set up the Protocol V2 approvals on the first Protocol V2 order, support split, merge and redeem on Protocol V2 markets, and add `getMarketProtocol()`. * Polymarket's test markets (slugs starting with `polyv2`) appear in wallet, trade and market-id routes and on the streams. Docs: [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2) *** ## 2026-09-02 - Initial replay for fill subscriptions `fills` subscriptions now return recent matching fills immediately after the subscription acknowledgement, using the same flat event shape as live fills. What's new: * `snapshot_count` returns up to the requested number of flat fill events, subject to the account tier limit. * `since` returns matching fills after a Unix-millisecond timestamp within the account tier's lookback window and takes precedence over `snapshot_count`. * Wallet, token, side, and size filters apply consistently to replayed and live fills. * A replay with no matching fills completes explicitly with `{"type":"snapshot","count":0,"events":[]}`. * Existing live fill messages remain unchanged. Each replay item uses the same `{"type":"event","data":{...}}` envelope. Docs: [Subscriptions and filters](/websocket/subscribing) and [WebSocket reconnection](/websocket/overview#reconnection) *** ## 2026-09-01 - Builder profiles and trader analytics Builder profiles now expose daily activity, buy/sell composition, attributed trades, and a dedicated trader leaderboard from one public surface. What's new: * `GET /v3/builders` is the canonical Builder directory and accepts an exact, case-insensitive `name` filter. A documented loop prints every public name and stable Builder code. * Builder detail, trades, daily activity, and trader leaderboard paths accept a code or exact public name. Names, hexadecimal digits, and the optional code prefix are case-insensitive. Shared display names return HTTP `409` and require a code to disambiguate. * `GET /v3/builders/{code}/activity/daily` returns daily volume, fills, active traders, trader-paid fees, buy/sell mix, and bounded recent market/category composition. `GET /v3/builders/activity/daily` compares up to 20 codes. * `GET /v3/builders/{code}/leaderboard` supports `1d`, `7d`, `30d`, and `all`, plus P\&L and Builder-attributed activity sorts. Period, sort, and order are case-insensitive and responses use canonical lowercase values. * Trader leaderboard pages contain at most 100 rows and cover the first 500 ranks through offsets `0`, `100`, `200`, `300`, and `400`. * All-Time P\&L sorts add opt-in `pagination=cursor`. Signed cursors bind the Builder, filters, limit, both returned snapshots, and already-returned identities so one pinned traversal does not repeat a wallet. Historical offset requests and response bodies remain available unchanged. * Cursor continuations carry `next_cursor`, `as_of`, and `pnl_as_of`. If either snapshot advances, HTTP `409` tells the caller to restart at offset `0`. * P\&L remains global Polymarket wallet P\&L for the Builder-active cohort. The activity columns remain Builder-attributed. Docs: [Builder directory](/data/builders/list), [Builder daily activity](/data/builders/daily-activity), and [Builder trader leaderboard](/data/builders/trader-leaderboard) *** ## 2026-08-29 - Combo P\&L leaderboard A dedicated Combo leaderboard now ranks eligible wallets by realized P\&L over 1-day, 7-day, 30-day, or custom windows and by marked All Time P\&L. What's new: * `GET /v3/combos/leaderboard` supports All Time realized, unrealized, and total P\&L plus realized-only fixed and half-open custom windows. * Custom windows accept `after`, `before`, or both as Unix seconds and use `[after, before)` when both bounds are present. * Every response discloses eligible, excluded, transfer-incomplete, and unmarked wallet counts. Excluded wallets are omitted, never zero-filled. * Open positions use the latest Combo fill mark; terminal positions use `1` or `0`. Arbitrary wallet-to-wallet transfer basis is not inferred. * Signed-order maker fills are counted once, and their exchange fees are included in weighted-average cost basis and realized proceeds. * The route is global and does not accept tag or category filters. Docs: [Combo P\&L Leaderboard](/data/combos/leaderboard) *** ## 2026-08-28 - Stable perps activity pagination Archived perps trades, position events, likely liquidations, and wallet collateral flows now support stable cursor pagination. What's new: * Responses return `has_more` and an opaque `next_cursor`. Archived trade responses also preserve the existing `more` field. * Reusing the same route and filters keeps pages disjoint while new activity arrives. Cursors expire after 24 hours. * Wallet-flow deposit and withdrawal totals and counts stay identical across every page in one traversal. * Malformed, expired, route-mismatched, and filter-mismatched cursors return clean HTTP `400` errors. * Cumulative volume delta remains a bounded single-page series and is not part of this cursor contract. Docs: [Archived trades](/perps/market-data/trades), [Position events](/perps/analytics/events), [Liquidations](/perps/analytics/liquidations), and [Wallet flows](/perps/onchain/flows) *** ## 2026-08-27 - Complete market, event, and leaderboard discovery New V3 discovery routes make it possible to walk the full market and event catalogs and build rolling leaderboard navigation without guessing scope names. What's new: * `GET /v3/markets` and `GET /v3/events` provide cursor pagination, open, closed, and inactive status filters, and exact event-slug filtering. * `GET /v3/markets/stats` and `GET /v3/events/stats` return complete catalog and status counts independent of any one page. * `GET /v3/leaderboard/scopes` lists and searches the categories or tags available for 1-day, 7-day, and 30-day realized-P\&L rankings. * `GET /v3/rewards/markets` adds nullable title, slug, image, event, category, and tag context to every listed reward market. Docs: [Market Catalog](/data/markets/catalog), [Event Catalog](/data/events/catalog), and [Leaderboard Scopes](/data/leaderboard/scopes) *** ## 2026-08-27 - Rolling realized-P\&L leaderboards Trader leaderboards now support 1-day, 7-day, and 30-day realized-P\&L rankings across all markets, one category, or one tag. What's new: * Set `period=1d`, `7d`, or `30d` on `GET /v3/leaderboard` or `GET /v3/tags/{slug}/leaderboard`. * Rolling rows are ranked by `realized_pnl` descending and include realized profit, loss, win, position, event, and market counts. Historical unrealized P\&L is not included. * Each request returns up to 100 rows. Rolling pagination is capped at rank 1,000 and shorter rankings end at their last returned row. * A valid category or tag with no realized results in the selected window returns HTTP `200` with an empty leaderboard. * Omitting `period`, or using `period=all`, preserves the existing all-time leaderboard and its sort options. Docs: [Leaderboard](/data/leaderboard/global) and [Tag Leaderboard](/data/leaderboard/tag-leaderboard) *** ## 2026-08-19 - Builder volume aligned with Polymarket's V2 convention Builder volume now counts locally indexed outcome shares, with one share represented as \$1 of par notional. This matches Polymarket's builder-volume convention over the same CLOB V2 history without importing Polymarket's leaderboard totals or pre-V2 attribution. What's new: * `GET /v3/builders` and `GET /v3/builders/{code}` add `volume`, `buy_volume`, and `sell_volume` aliases. * `volume_scope=clob_v2_onchain` and `volume_semantics=outcome_share_par_notional` make the coverage and unit explicit. * Existing fill count, fees, raw maker/taker totals, timestamps, profile metadata, and compatibility fields remain available. * `sort=volume` uses only Polynode's local builder aggregate. Public Polymarket volume is not used as a fallback or ranking input. Docs: [Builder Leaderboard](/data/builders/list) and [Builder Detail](/data/builders/detail) *** ## 2026-08-18 - Query sports games by event or market ID Sports game endpoints can now be queried by Polymarket event ID or market ID. What's new: * Use `/v2/sports/games/by-event/{event_id}` for an event ID. * Use `/v2/sports/games/by-market/{market_id}` for a market ID. The response contains the full parent event and its canonical event slug. * Append `/state`, `/context`, `/prices`, or `/history` to either identifier route for the corresponding game data. * Existing slug-based routes are unchanged. Docs: [Game Detail](/api-reference/sports/game-detail) *** ## 2026-08-18 - Connect Wallet to user-owned V2 orders The TypeScript, Python, and Rust SDKs now provide one documented platform flow from wallet connection through an actual zero-attribution user-owned V2 order. What's new: * TypeScript `polynode-sdk` 0.14.2 provides a browser-memory session, standard viem provider typing, wallet-confirmed USDC.e to pUSD funding, exact order preview/signing, a durable pre-submit order-hash callback, and authenticated open-order reconciliation. * TypeScript 0.14.2, Python `polynode` 0.14.1, and Rust `polynode` 0.17.1 share one browser-safe signing-request and encrypted backend-vault bundle contract. Prepared orders expose the canonical exchange order hash before transport so open orders and fills can be reconciled by exact identity instead of an amount/time heuristic. * Platforms can authorize each connected wallet once, retain wallet-scoped credentials in an encrypted vault, prepare one short-lived order on any worker, send only typed data to the browser, and consume submission state exactly once. * User-owned orders contain zero builder attribution and do not consume a platform's shared builder allowance. Market rules, collateral, API rate limits, and ordinary service limits still apply. * The default fresh deposit-wallet path requires three setup signatures: one ownership message, one EIP-712 approval batch containing all four base-order permissions, and one EIP-712 `ClobAuth` signature. Wallet deployment itself does not require a signature. * A first order therefore requires four total signatures when pUSD is already funded, or five when an SDK-confirmed USDC.e to pUSD conversion is also needed. A returning wallet restored from the encrypted vault has no setup signatures and signs only the exact order. * The guide covers credential sensitivity, account and chain binding, ownership-conditional atomic storage, exception-safe cleanup, minimal dependency installs, and conservative ambiguous-submit reconciliation. Docs: [Connect Wallet to order](/sdks/user-owned-web-app) and [User-owned execution](/sdks/user-owned-execution) *** ## 2026-08-18 - Faster confirmed trade delivery Confirmed `trade` events and `status_update.confirmed_fills` now arrive promptly during high-volume periods. What's improved: * The confirmed-trade payload, receipt-derived values, order hashes, deduplication, and status ordering are unchanged. * A release investigation reproduced 10 to 28-second confirmed-trade delays while status delivery remained current. The corrected path removed that accumulated delay. * The first complete post-release comparison covered 1,886 confirmed trades. Observed delivery measured 246.7 milliseconds ahead at the median, 318.2 milliseconds behind at p90, and 492.4 milliseconds behind at p99. * A separate acceptance window covered 13 consecutive Polygon heads, 340 settlements, and 178 status updates with no gaps, duplicates, reversals, or parse errors. No subscription or parser change is required. Docs: [Trade events](/websocket/events/trade), [Status updates](/websocket/events/status-update), and [Trade tracking](/guides/trade-tracking) *** ## Earlier releases Older entries are grouped into Monday-through-Sunday archive pages for fast, reliable loading. * [August 10-16, 2026](/changelog-august-10-16-2026) * [August 3-9, 2026](/changelog-august-3-9-2026) * [July 27-August 2, 2026](/changelog-july-27-august-2-2026) * [July 20-26, 2026](/changelog-july-20-26-2026) * [July 13-19, 2026](/changelog-july-13-19-2026) * [July 6-12, 2026](/changelog-july-6-12-2026) * [June 29-July 5, 2026](/changelog-june-29-july-5-2026) * [June 22-28, 2026](/changelog-june-22-28-2026) * [June 15-21, 2026](/changelog-june-15-21-2026) * [June 8-14, 2026](/changelog-june-8-14-2026) * [June 1-7, 2026](/changelog-june-1-7-2026) * [May 25-31, 2026](/changelog-may-25-31-2026) * [May 2-24, 2026](/changelog-may-2-24-2026) * [May 1, 2026](/changelog-may-1-2026) * [April 30, 2026](/changelog-april-30-2026) * [April 27, 2026 - Positions](/changelog-april-27-2026-positions) * [April 27, 2026 - Trades](/changelog-april-27-2026-trades) * [April 26, 2026](/changelog-april-26-2026) * [April 17-25, 2026](/changelog-april-17-25-2026) * [April 1-15, 2026](/changelog-april-1-15-2026) * [March 28-31, 2026](/changelog-march-28-31-2026) * [March 15-26, 2026](/changelog-march-15-26-2026) # Changelog — April 1–15, 2026 Source: https://docs.polynode.dev/changelog-april-1-15-2026 Archived PolyNode API and SDK changes from April 1–15, 2026. [← Back to the current changelog](/changelog) ## 2026-04-15 — Trade-based candles endpoint ### New: `GET /v2/onchain/candles/{token_id}` Server-built OHLCV candles from real onchain fills. Each candle includes open, high, low, close, total volume in USD and shares, separate buy and sell volume, trade count, and VWAP. Pagination is anchor-based: each request returns up to 1000 trades worth of candles, anchored at a timestamp, block number, or transaction hash. Walk older history by passing the cursor from the previous response. Same model used by major exchange APIs. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/candles/$TOKEN_ID?resolution=1h" \ -H "x-api-key: YOUR_KEY" ``` Resolutions: `1m`, `5m`, `15m`, `1h`, `4h`, `1d`. Optional `gap_fill=true` for charting libraries that expect a continuous time axis. Full reference at [/api-reference/onchain/candles](/api-reference/onchain/candles). *** ## 2026-04-14 — Positions sort fix + `last_activity` field ### Fixed: `/v2/onchain/positions` wallet queries now sort by recency When querying positions for a specific `wallet`, results are now ordered by the most recent on-chain activity for each position. Previously the `order=desc` parameter did not reflect recency, causing newer positions to appear below older ones. The most recently traded positions now appear at the top. Positions with no fill history (rare — acquired purely via split, merge, or redemption) are placed at the end. ### New: `last_activity` response field Wallet queries now include a `last_activity` field on each position, containing the unix timestamp of the most recent fill for that position. Use it to display "last traded" times in your UI. ```json theme={null} { "wallet": "0x4aefd329896464da0ffb16c4ebcd083a4360c181", "token_id": "99969794444523158222638792918531145371262906249733117976401662588024805483979", "size": 0, "status": "closed", "market": "Suns vs. Lakers", "market_slug": "nba-phx-lal-2026-04-10", "outcome": "Lakers", "last_activity": 1776232830 } ``` ### Pagination behavior Wallet queries return every position for the wallet in a single response (up to 500), ordered by recency. `has_more` is always `false` and no cursor is returned — request `limit=500` once and read all results. Wallets with more than 500 lifetime positions are capped. Non-wallet queries (filtering by `market_slug`, `condition_id`, `token_id`, or `min_size` alone) continue to use cursor-based pagination. *** ## 2026-04-12 — SDK v0.7.0: Fee Escrow + Order History ### New: Per-Order Fee Collection The trading SDK now supports optional per-order fee collection with on-chain escrow. Platforms can charge fees on trades with a single config option. ```bash theme={null} npm install polynode-sdk@0.7.0 ``` ```typescript theme={null} const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...', feeConfig: { feeBps: 50 }, // 0.5% fee }); const result = await trader.order({ tokenId: '...', side: 'BUY', price: 0.55, size: 100, }); console.log(result.feeEscrowTxHash); // on-chain TX hash console.log(result.feeAmount); // "0.0275" USDC ``` * **Automatic fee handling** -- fees are pulled into escrow before the order, distributed on fill, refunded on cancel * **Cancel auto-refund** -- cancelling an order automatically returns the fee to the user's wallet, inline in the same request * **Affiliate revenue sharing** -- split fees with partners on a per-order basis via `affiliate` and `affiliateShareBps` * **72-hour safety net** -- if the operator doesn't settle, users can self-refund on-chain * **Zero overhead when disabled** -- `feeBps: 0` (default) skips the escrow entirely with no behavior change * **7th approval** -- added to `ensureReady()` batch, gasless for Safe wallets ### Improved: Order History Local order history now persists fee escrow data (`feeAmountRaw`, `escrowOrderId`, `feeEscrowTxHash`). Existing databases auto-migrate on first open. No action required. ### SDK Releases * **TypeScript** `polynode-sdk@0.7.1` on [npm](https://www.npmjs.com/package/polynode-sdk) — adds `FeeConfig` export * **Rust** `polynode@0.7.1` on [crates.io](https://crates.io/crates/polynode) — fixes compile error in 0.7.0 * **Python** `polynode@0.7.2` on [PyPI](https://pypi.org/project/polynode/) — fixes `__version__` reporting See the [Fee Escrow Guide](/guides/fee-escrow) for the full workflow, security model, and code examples. *** ## 2026-04-11 — polynode-charts v0.1.5 ### New: `createShortFormOverlay` One-liner to add price-to-beat overlays to any live chart. Renders interval buttons (5m/15m/1h), auto-discovers Polymarket short-form markets, draws a dashed price line, and shows live odds with a countdown timer. ```typescript theme={null} import { createChart, createShortFormOverlay } from 'polynode-charts' const chart = createChart('#btc') const series = chart.addLineSeries({ color: '#f7931a' }) series.setLive(true) chart.timeScale().goLive() createShortFormOverlay(chart, series, { coin: 'btc' }) ``` ### Improvements * **Multi-outcome event discovery** now prioritizes genuine multi-outcome markets (`neg_risk: true`) over resolved binary matches * **`MarketInfo.outcome`** field identifies which side of a binary market each token represents ("Yes" or "No") * **Price-to-beat badge** renders correctly on the right axis for all price ranges * **Orderbook tooltip** no longer stays stuck after data refresh * **Tighter chart padding** for a denser, more professional look *** ## 2026-04-11 — polynode-charts v0.1.0 New npm package for interactive charting in the browser. Zero dependencies, Canvas 2D rendering at 60fps, purpose-built for prediction market data and live crypto price streams. ### Install ```bash theme={null} npm install polynode-charts ``` ### What's included * **Candlestick, line, area, and volume** series types with smooth animation * **Live streaming mode** with lerp animation, pulsing dots, and auto-scroll * **Orderbook visualization** with depth chart and spread display * **Short-form market overlays** — price-to-beat lines with live odds rotation for 5m/15m/1h crypto markets * **Multi-outcome support** for prediction markets (up to 20+ outcomes with auto-assigned colors) * **Built-in data providers** — `PolynodeProvider` (REST), `PolynodeOBProvider` (WebSocket orderbook), `ShortFormProvider` (market discovery + rotation) * **Interactive** pan, zoom, scroll, pinch-to-zoom on mobile * **Crosshair** with snap-to-candle and OHLC tooltip ### Quick start ```typescript theme={null} import { createChart, PolynodeProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) const chart = createChart('#chart', { rightPriceScale: { mode: 'probability' }, }) const series = chart.addCandleSeries({ upColor: '#22c55e', downColor: '#ef4444', }) const data = await provider.candles(tokenId, '1h') series.setData(data) ``` ### Charts documentation Full docs at [Charts SDK Overview](/charts/overview), including API reference, data providers, series types, examples, and configuration. > [!NOTE] > > `polynode-charts` is the **browser visualization** companion to `polynode-sdk` (the Node.js data SDK). They are separate npm packages. Building a frontend? Install both. *** ## 2026-04-09 — Confirmed Fills on Status Updates `status_update` events now include a `confirmed_fills` array with exact execution data from on-chain `OrderFilled` receipt logs. This is the same data source Polymarket's own APIs read. ### What changed * `status_update` events now carry a `confirmed_fills` field — an array of per-fill objects with exact price, size, fee, order hash, maker, taker, and token ID * Each fill is decoded directly from `OrderFilled` receipt logs on the CTF Exchange and NegRisk CTF Exchange contracts * Prices match Polymarket's activity data exactly (verified across 1,300+ fills with zero price discrepancies) ### Why this matters polynode detects settlements 3-5 seconds before on-chain confirmation by decoding transaction calldata from the mempool. For single-maker fills, calldata prices are exact. For multi-maker fills (\~5% of trades), the calldata only has aggregate amounts, so per-maker prices are estimated within 0.01-0.04. With `confirmed_fills`, you now get both: the fast pre-confirmation signal AND the exact on-chain execution data in a single subscription. Use whichever fits your use case. ### Use cases * **Copy trading**: Use the pending `settlement` event (speed matters, price difference is negligible) * **Analytics and bookkeeping**: Use `confirmed_fills` from the `status_update` (exact prices, fees, and sizes) * **Full lifecycle**: Track both to compare pre-confirmation estimates against final execution ### Size difference vs Polymarket `confirmed_fills` reports gross token amounts from the OrderFilled event. Polymarket's activity API reports sizes net of fees. The `fee` field on each fill lets you compute the net amount if needed. ### Confirmed-fill subscription No subscription changes needed. If you already subscribe to `settlements`, you're already receiving `status_update` events with `confirmed_fills`. ```json theme={null} {"action": "subscribe", "type": "settlements"} ``` ### Confirmed-fill documentation * [Status Update Event Reference](/websocket/events/status-update) — updated with `confirmed_fills` schema and examples * [Trade Tracking Guide](/guides/trade-tracking) — when to use pending settlements vs confirmed fills *** ## 2026-04-08 — Redemption Event Streaming New `redemption` event type in the WebSocket stream. Every time a user redeems their outcome tokens after a market resolves, you get a real-time event with the redeemer address, payout amount, condition ID, and full market metadata enrichment. ### WebSocket Stream * New event type: `redemption` — available in the firehose and via `event_types` filter * Decoded from `PayoutRedemption` logs on the Conditional Tokens contract * Includes payout amount in USDC, redeemer wallet, outcome slots redeemed * Enriched with market title, slug, image, tokens map, neg\_risk flag * Filter with `min_size` to see only winning redemptions, or track specific wallets ### Redemption subscription ```json theme={null} {"action": "subscribe", "type": "settlements", "filters": {"event_types": ["redemption"]}} ``` ### Redemption documentation * [Redemption Event Reference](/websocket/events/redemption) — full field reference, examples, and use cases *** ## 2026-04-07 — Polymarket V2 Exchange Support polynode now supports the Polymarket V2 exchange system alongside V1. All V2 contracts have been identified, decoded, and verified against live mainnet data. ### Settlement Stream * V2 settlements are detected and streamed automatically — no subscription changes needed * Same event types: `settlement`, `status_update`, `trade`, `deposit` * PolyUSD wrapping/unwrapping events now included in deposit stream * V2 detection is automatic alongside V1 (both supported simultaneously) ### Trading SDK (Rust v0.6.0, TypeScript v0.6.0, Python v0.7.0) * New `ExchangeVersion::V2` / `exchangeVersion: "v2"` config option * V2 order signing with updated EIP-712 domain (version "2") * `wrapToPolyUsd()` and `unwrapFromPolyUsd()` helper methods * `getPolyUsdBalance()` and `getUsdceBalance()` balance checking * V2 approval management (PolyUSD to V2 exchange contracts) * One config change to switch from V1 to V2 — everything else stays the same ### V2 migration documentation * [V2 Migration Guide](/guides/v2-migration) — what changed, what stayed the same, SDK examples * [PolyUSD Guide](/guides/polyusd) — how to wrap/unwrap PolyUSD with code examples * [V2 Technical Details](/guides/v2-details) — contract addresses, order struct, event signatures (subscribers only) * Deposit and settlement event pages updated with V2 notes ### What We Verified * V2 order placement tested live on the V2 CLOB * EIP-712 order hash matches the live V2 exchange contract on Polygon mainnet * PolyUSD wrapping detected through our event pipeline in real time * All existing market data, token IDs, and enrichment identical between V1 and V2 *** ## 2026-04-05 — Short-Form Docs: Full Field Reference + Orderbook Guide Updated the [Short-Form Markets](/sdks/short-form) documentation with the complete `ShortFormMarket` field reference. All 14 fields are now documented, including `conditionId`, `clobTokenIds`, `windowStart`, `windowEnd`, `outcomes`, and `outcomePrices` which were previously undocumented. Added a new **"Connect the Orderbook to Crypto Markets"** section showing how to pass `clobTokenIds` from a short-form rotation event directly to `OrderbookEngine` for real-time depth data on crypto prediction markets. Includes TypeScript and Rust examples. No SDK changes. All fields were already available in the SDK — this is a docs-only update. *** ## 2026-04-04 — Crypto Price Fix (All SDKs) Fixed stale price-to-beat values in short-form crypto markets. Polymarket changed the variant parameter on their crypto-price endpoint for 5-minute and hourly markets. The SDK now sends the correct values, matching what Polymarket's own frontend uses. **Affected intervals:** 5-minute and hourly. 15-minute was unaffected. ```bash theme={null} npm install polynode-sdk@0.5.9 # TypeScript cargo add polynode@0.5.8 # Rust pip install polynode==0.6.2 # Python ``` *** ## 2026-04-04 — TypeScript SDK v0.5.8 Fixed a bug where `price_feed` events from Chainlink subscriptions were silently dropped in the TypeScript SDK. The `.on('price_feed', ...)` handler now fires correctly. ```typescript theme={null} const sub = await pn.ws .subscribe('chainlink') .feeds(['BTC/USD']) .send(); sub.on('price_feed', (event) => { console.log(`${event.feed}: $${event.price}`); }); ``` Update with `npm install polynode-sdk@0.5.8`. *** ## 2026-04-02 — Position Management (All SDKs) Split, merge, and convert positions directly from the SDK. No need to interact with smart contracts manually. **TypeScript** — gasless execution via the Polymarket relayer: ```typescript theme={null} await trader.split({ conditionId: '0x...', amount: 100 }); await trader.merge({ conditionId: '0x...', amount: 100 }); await trader.convert({ marketId: '0x...', outcomeIndices: [0, 1], amount: 100 }); ``` **Rust & Python** — transaction builders that return ready-to-submit calldata: ```python theme={null} tx = build_split_txn("0x...", 100.0, neg_risk=True) tx = build_convert_txn("0x...", [0, 1], 100.0) ``` * [Position Management guide](/guides/position-management) — full walkthrough with examples * Convert is unique to neg-risk multi-outcome markets (e.g. "Who will win the World Cup?") * TypeScript SDK handles neg-risk vs standard market routing automatically *** ## 2026-04-02 — Positions Converted Event (WebSocket API) New `positions_converted` event type for tracking position conversions on neg-risk multi-outcome markets. When a trader converts NO positions into USDC + YES positions on complementary outcomes (via the NegRiskAdapter `convertPositions` function), this event fires with the full decoded details. ```json theme={null} { "data": { "event_type": "positions_converted", "event_title": "Hungary Parliamentary Election Winner", "stakeholder": "0x30cecdf29f069563ea21b8ae94492e41e53a6b2b", "converted_outcomes": ["Fidesz-KDNP", "TISZA"], "amount": 98, "market_id": "0x355e7310dd6e18ef5fa456de7ce1331bd8c7540c...", "index_set": "0x...0021", "neg_risk": true } } ``` * `converted_outcomes` decodes the bitmask into human-readable outcome names * `event_title` shows the parent multi-outcome event * Included by default in `wallets` and `markets` subscription types * Add explicitly via `event_types: ["positions_converted"]` for other subscription types * Fires \~13 times per minute across all active neg-risk markets *** ## 2026-04-01 — Builder Credentials (All SDKs) ### TypeScript SDK v0.5.7 / Rust SDK v0.5.7 / Python SDK v0.6.1 Platforms can now pass their own Polymarket builder credentials for order attribution. All volume gets credited to your builder profile on the [Builder Leaderboard](https://builders.polymarket.com). ```typescript theme={null} const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...', builderCredentials: { key: process.env.POLY_BUILDER_API_KEY, secret: process.env.POLY_BUILDER_SECRET, passphrase: process.env.POLY_BUILDER_PASSPHRASE, }, }); ``` * Get your builder credentials at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) * polynode never stores your builder credentials. They're used per-request for HMAC signing only. * When omitted, polynode's default builder attribution is used (orders still go through). Install: ```bash theme={null} npm install polynode-sdk@0.5.7 # TypeScript cargo add polynode@0.5.7 # Rust pip install polynode==0.6.1 # Python ``` *** # Changelog — April 17–25, 2026 Source: https://docs.polynode.dev/changelog-april-17-25-2026 Archived PolyNode API and SDK changes from April 17–25, 2026. [← Back to the current changelog](/changelog) ## 2026-04-25 — Pricing section retired: candles deduplicated, "Market Card" introduced The "Pricing" sidebar section has been removed. It contained two endpoints: * **`GET /v1/stats/{token_id}`** — kept, renamed to **Market Card**, moved further down the sidebar (just above "System"). This one is genuinely useful: a single call returns the condition\_id, outcomes, neg-risk flag, end date, current orderbook liquidity, 24h OHLCV summary, and last price. Saves you from chaining 3–4 calls when you just need a market overview tile. * **`GET /v1/candles/{token_id}`** — removed from documentation. It was an in-memory rolling buffer with no historical depth, no pagination, no VWAP, and no buy/sell split. Use **`GET /v2/onchain/candles/{token_id}`** instead — same OHLCV plus VWAP, volume in shares, trade count, full history, and pagination. The endpoint itself still responds on the API for backward compatibility. *** ## 2026-04-25 — Wallet endpoints reorganized: V1 wallet endpoints removed from documentation The "Wallets" and "Onchain" sidebar sections have been merged into a single section called **Wallets / Positions / Onchain**. All wallet, position, and trade endpoints now live in one place — the V2 onchain endpoints. **What changed in the docs:** The seven legacy V1 wallet/market endpoints have been removed from the documentation sidebar. They were inferior duplicates of the V2 onchain equivalents — three of them returned empty or error responses, and the rest lacked PnL, average-price, current-price, and market-status fields that the V2 versions provide directly from chain data. | Removed from docs | Use instead | | - | - | | `GET /v1/wallets/{addr}/positions` | `GET /v2/onchain/positions?wallet=…` | | `GET /v1/wallets/{addr}/closed-positions` | `GET /v2/onchain/positions?wallet=…&status=closed` | | `GET /v1/wallets/positions` (multi-wallet) | Loop `GET /v2/onchain/positions?wallet=…` per wallet | | `GET /v1/wallets/{addr}/trades` | `GET /v2/onchain/wallets/{address}/trades` | | `GET /v1/markets/{id}/positions` | `GET /v2/onchain/positions?token_id=…` | | `GET /v1/markets/{id}/trades` | `GET /v2/onchain/markets/{token_id}/trades` | | `GET /v1/resolve/{query}` | `GET /v2/resolve/{query}` | **Important — backward compatibility preserved:** The V1 endpoints **still respond on the API**. We have not turned them off. If you have integrations hitting the legacy paths, they continue to work exactly as before — we just stopped surfacing them in the documentation because the V2 onchain replacements are strictly better. You should migrate, but you don't have to migrate today. **Why V2 onchain is better:** V1 wallet endpoints returned mostly social-flavored fields (bio, profile picture, pseudonym). V2 onchain endpoints return rich trading-relevant fields: `avg_price`, `realized_pnl`, `unrealized_pnl`, `current_price`, `total_bought`, `market_status`, `order_hash`, `fee`, `maker_amount`, `taker_amount`, `condition_id`, and more. Same data your equity curve, leaderboard, and PnL endpoints already use. *** ## 2026-04-25 — Equity Curve endpoint: faster default + four new query parameters The `/v2/trader/{wallet}/equity` endpoint is faster, more flexible, and more accurate. **Default is now realized-only.** The curve is built from completed P\&L by default — the locked-in result of every closed position, partial sell, and resolution. Same query, same numbers, every time. Whales return in 1–2 seconds (was 8+). If you want mark-to-market on currently-open positions (the old behavior), pass `include_unrealized=1`. That path is still supported, just opt-in now because it adds latency and makes responses non-deterministic as live prices move. **Four new optional query parameters:** | Param | Description | | - | - | | `from=YYYY-MM-DD` | Start date (also accepts unix seconds). | | `to=YYYY-MM-DD` | End date (same format). | | `max_markets=N` | Keep only the most recent N markets the wallet has touched. | | `include_unrealized=1` | Mark-to-market open positions (was the old default). | All four compose. Example — fast realized-only curve over the wallet's last 50 markets in early April: ```bash theme={null} curl "https://api.polynode.dev/v2/trader/{wallet}/equity?from=2026-04-01&to=2026-04-15&max_markets=50&normalize=1" \ -H "Authorization: Bearer YOUR_API_KEY" ``` **New response fields:** `markets_count` (distinct outcome groups in the curve), `applied_filters` (echoes what was applied, useful for debugging), and `partial` (true if the request hit the 10-second server-side cap). **Coverage fix.** Wallets with more than 500 lifetime trades previously had positions whose first-trade timestamp wasn't found, causing those positions to be incorrectly stamped at "now" on the curve. The endpoint now walks all relevant trade history and falls back to sibling-token and redemption timestamps for positions acquired through USDC splits. Curves are dramatically more accurate for active traders. Full reference: [/api-reference/enriched/equity-curve](/api-reference/enriched/equity-curve). *** ## 2026-04-24 — Fee Escrow V2 live on Polygon (pUSD collateral, V2 CLOB) We've deployed a V2 variant of the Fee Escrow contract so platforms building on the V2 CLOB can charge fees in pUSD (V2's native collateral) instead of USDC.e. Both V1 and V2 are live and fully supported — there is no migration. If you're already running V1, nothing changes. **FeeEscrow V2 (new):** | Field | Value | | - | - | | Address | `0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F` | | Collateral | pUSD `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` (6 decimals) | | EIP-712 domain | `name="PolyNodeFeeEscrowV2"`, `version="2"`, chainId 137 | **FeeEscrow V1 (unchanged):** | Field | Value | | - | - | | Address | `0xa11D28433B79D0A88F3119b16A090075752258EA` | | Collateral | USDC.e `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | | EIP-712 domain | `name="PolyNodeFeeEscrow"`, `version="1"`, chainId 137 | The contracts have byte-identical calldata, identical function signatures, and identical semantics. The only functional differences are the collateral token and the domain name / version. The `FeeAuth` typed-data struct is unchanged. **Opting into V2 today:** The cosigner accepts an `escrow_contract` field in `fee_auth`. Absent or set to the V1 address = V1 (default). Set to the V2 address = V2. Sign the `FeeAuth` against the V2 domain when using V2. ```jsonc theme={null} "fee_auth": { "escrow_contract": "0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F", "escrow_order_id": "0x...", "payer": "0xSafe...", "signer": "0xEOA...", "fee_amount": "27500", "deadline": 1777000000, "nonce": 0, "signature": "0x...", // signed against the V2 domain "affiliate": "0xPartnerWallet...", "affiliate_share_bps": 10000 } ``` **SDKs:** V2 fee escrow is wired up in all three SDKs. Set `exchangeVersion` to V2 in your `TraderConfig` and the SDK automatically signs `FeeAuth` against the V2 domain, reads nonces from the V2 contract, approves pUSD against the V2 FeeEscrow during `ensureReady()`, and tells the cosigner to route to the V2 operator. Install: ```bash theme={null} npm install polynode-sdk@0.9.2 pip install "polynode==0.9.2" cargo add polynode@0.12.2 ``` V1 customers: no changes, V1 stays the default. Omit `exchangeVersion` (or set it to V1) and everything keeps working exactly as before. **Validation:** 8/8 end-to-end fork tests pass against the deployed V2 contract, exercising pullFee + distribute (30/70 treasury/affiliate split) + refund + 72-hour claimRefund + every revert path (expired deadline, wrong nonce, tampered signature). The test impersonates a real on-chain pUSD whale to fund the payer. Contract bytecode is a strict 2-change diff from V1 (collateral address + domain strings). Full guide: [/guides/fee-escrow](/guides/fee-escrow). *** ## 2026-04-21 (late) — Unrealized P\&L and market status on positions The `/v2/onchain/positions` and `/v2/wallets/{address}/positions/onchain` endpoints now return unrealized P\&L, the current market price, and a status flag per position — so you don't have to fetch prices separately or special-case resolved markets in client code. **New per-position fields:** * `unrealized_pnl` — paper P\&L on the held size at the current price. For resolved markets, uses the settlement price (1.0 for winners, 0.0 for losers). For live markets, uses the current market price. Returns 0 when `size = 0`. * `current_price` — the price used to compute `unrealized_pnl`. `null` when `size = 0` or no price is available. * `market_status` — one of `live`, `resolved-win`, `resolved-loss`, or `closed`. Lets you tell apart a live-tradable holding from a resolved-but-never-redeemed position without looking up the market separately. **New portfolio totals** on `/v2/wallets/{address}/positions/onchain`: * `total_unrealized_pnl` * `total_pnl` — `total_realized_pnl + total_unrealized_pnl`. This is the number that matches the "Profit" value shown on a Polymarket profile page. Drop-in — every existing field keeps its name and type. *** ## 2026-04-21 (late) — Gasless Safe wrap/unwrap via the Polymarket relayer Patch release. `wrapToPolyUsd` / `unwrapFromPolyUsd` (and their Python/Rust equivalents) now route through the Polymarket relayer automatically when called on a Safe or Proxy wallet — the flow `ensureReady` already uses. Previously these helpers sent the transaction directly from the EOA, which failed for Safe wallets because the funds live in the Safe, not on the EOA, and the EOA has no MATIC for gas. **Install:** ```bash theme={null} npm install polynode-sdk@0.9.1 # TypeScript pip install "polynode>=0.9.1" # Python cargo add polynode@0.12.1 # Rust ``` **Verified end-to-end with real Safe-via-relayer transactions:** * TS: wrap `0xde6c02c3...`, unwrap `0x006cd3dd...` * Python: wrap `0x7de53811...`, unwrap `0xccf9cf32...` * Rust: wrap `0xd80af0f4...`, unwrap `0xd21d6ad6...` All six txs mined on Polygon with `status: 0x1`, funded by third-party relayer EOAs — your EOA only signs the Safe `execTransaction` EIP-712 payload. **Requirements for Safe wrap/unwrap:** pass `builderCredentials` in `TraderConfig`. The SDK uses your Polymarket builder HMAC key to authenticate the relayer submit. Mint one at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder). **Tip — avoid stale-cache order rejection after wrap:** after `wrapToPolyUsd()`, the V2 CLOB's cached balance view is stale for a few seconds. If you place an order immediately, the CLOB can return a cryptic `"error parsing fee rate bps"` instead of the actual "balance not yet visible". Call `await trader.refreshBalanceAllowance()` before the order, or wait \~3 seconds. This is why we don't auto-refresh in wrap — not every wrap is followed by an immediate order. **Also in this patch:** * **Rust:** fixed `encode_unwrap` selector (was `0x39f47693`, correct value is `0x8cc7104f`). All Rust V2 unwraps prior to 0.12.1 hit the wrong contract function and reverted on-chain. * **Rust:** `get_polyusd_balance()` / `get_usdce_balance()` now read the funder address (Safe) instead of the EOA. Previously they always returned 0 for Safe-wallet users. * **Python:** `relayer.py` module added with a minimal Python port of `@polymarket/builder-relayer-client`. Implements EIP-712 Safe tx hashing, EIP-191 personal\_sign via `eth_account`, builder HMAC headers, and `/submit` + `/transaction` polling. *** ## 2026-04-21 — SDK V2 order flow hardening (all three SDKs) End-to-end V2 order placement verified live on `clob-v2.polymarket.com` across all three SDKs. Matched fills tagged with your builder code now appear in the V2 CLOB's `/builder/trades` attribution feed. **Install:** ```bash theme={null} npm install polynode-sdk@0.9.0 # TypeScript pip install "polynode>=0.9.0" # Python cargo add polynode@0.12.0 # Rust ``` **What changed:** * **V2 approvals now include the V1 `NegRiskAdapter`** in the spender list. The V2 CLOB's balance-allowance check monitors this address alongside the two V2 exchanges — orders without this approval were rejected with `"not enough balance / allowance"`. * **New methods: `refreshBalanceAllowance()` / `getBalanceAllowance()`.** The V2 CLOB maintains a cached balance-allowance view per API key; `ensureReady()` now auto-refreshes it after setting V2 approvals so the first order after onboarding goes through. * **Amount math hardened against float-precision edge cases.** Raw-units now derived via string-based decimal conversion instead of `Math.trunc(x * 1e6)` (TS) / `(x * 1_000_000.0) as u64` (Rust), which could truncate to `N-1` for prices that round-trip badly through float. * **V2 order body now matches `@polymarket/clob-client-v2` exactly** — adds `taker`, `postOnly`, `deferExec` fields to the POST payload. * **`checkBalance()` is V2-aware** — reads pUSD on V2, USDC.e on V1. Previously always read USDC.e. * **Market neg-risk detection fix (TS).** The old check treated every market as neg-risk (truthiness of the response object rather than its `neg_risk` field), which signed orders against the wrong exchange on standard markets. **Migration:** drop-in. `trader.order(...)` signature is unchanged; if you're on V2 and your orders were going through before, they still will. If you had a custom `ensureReady`-equivalent flow, you may now drop the manual `/balance-allowance/update` call — `ensureReady()` handles it on fresh V2 approvals. The full V2 wire format, required approvals, fee math, and common failure modes are documented in each SDK at `src/trading/V2_ORDER_FLOW.md` (TS, Rust) / `polynode/trading/V2_ORDER_FLOW.md` (Python). **End-to-end verification (from each public registry, fresh sandbox, real V2 orders against `clob-v2.polymarket.com`):** | SDK | Installed from | V2 order placed | Cancelled | | - | - | - | - | | `polynode-sdk@0.9.0` | `npm install polynode-sdk` | `0xb088a702...` LIVE | ✓ | | `polynode 0.9.0` | `pip install polynode[trading]` | `0x4906757c...` LIVE | ✓ | | `polynode 0.12.0` | `cargo add polynode@0.12` | `0x6d3623c6...` LIVE | ✓ | Each sandbox pulled from the public registry, imported the SDK, placed a real V2 GTC BUY with builder attribution, confirmed `status: "live"` from the V2 CLOB, then cancelled. No local source overrides, no pre-compiled artifacts — same install path a new user follows. **Docs fix also shipped today:** the V2 section of `/sdks/trading` now inlines `ensureReady` / `ensure_ready` so a V2-first reader who pastes only that block hits a copy-paste runnable flow. Previously the snippet silently assumed the reader had already gone through the Quick Start section. *** ## 2026-04-20 — CLOB v2 API launched New paid REST namespace `/clobv2/*` exposing every Polymarket CLOB v2 fill, position, builder, and neg-risk event. **11 endpoints, all enriched with market metadata (question, slug, outcome, image, condition\_id) inline:** * `GET /clobv2/trades` — global fills, filterable by wallet/builder/market/time/size * `GET /clobv2/positions` — every open/closed v2 position * `GET /clobv2/candles/{token_id}` — OHLCV at 1m/5m/15m/1h/4h/1d with VWAP + buy/sell split * `GET /clobv2/wallets/{address}/trades` — per-wallet fill history with `side` * `GET /clobv2/markets/{token_id}/{trades,volume,orderbook}` — per-outcome aggregates * `GET /clobv2/builders` — v2 builder leaderboard (v2-exclusive) * `GET /clobv2/neg-risk/events{,/{parent_id}/children}` — multi-outcome event drilldown * `GET /clobv2/volume/hourly` — platform-wide hourly volume buckets Every list response includes `count`, `pagination.{limit,offset,has_more}`, and rate-limit headers. Paid tier required; free-tier keys receive `402`. See the [overview](/api-reference/clobv2/overview) for auth + numeric-precision conventions. **`/v2/onchain/*` enrichment restored** Trades / wallet-trades / market-trades / market-volume / candles on the legacy `/v2/onchain/*` endpoints now carry `market`, `market_slug`, `outcome`, `image`, and `condition_id` inline again. These fields had been quietly lost during a backend refactor. *** ## 2026-04-19 — Expanded orderbook wire format + Rust SDK 0.11.0 The orderbook WebSocket now delivers PM's full per-level payload so you can maintain a tick-accurate local book without REST polling. Verified at **100% best-bid / 100% best-ask** across 50 concurrent markets. **What's new in the `price_change` message** Every entry in the `assets` array now includes four extra fields: * `size` — the absolute size at that level after the change. `"0"` means the level was removed. * `side` — `"BUY"` (affects bids) or `"SELL"` (affects asks) * `best_bid`, `best_ask` — best bid/ask on the asset after the change Old clients parsing only `{asset_id, price}` are unaffected — the new fields are additive. Multiple distinct levels on the same asset may now appear in one batch; repeat hits on the same `(asset_id, price, side)` within the 250ms coalesce window still merge to last-write-wins. See the [orderbook message reference](/orderbook/messages) for the full field list. **Rust SDK 0.11.0** * `PriceChangeAsset` now carries `size`, `side`, `best_bid`, `best_ask` * New `LocalOrderbook::apply_price_change(&PriceChange)` — apply incremental updates directly to your local book * `OrderbookEngine` automatically applies `price_change` events to its shared state so every `EngineView` stays tick-accurate * `OrderbookUpdate::LastTradePrice(BookTrade)` — executed-trade events now deserialize cleanly (previously dropped) **Install:** ```bash theme={null} cargo add polynode@0.11.0 ``` **Breaking:** none. Enum variants added are additive under existing serde routing. Explicit exhaustive matches on `OrderbookUpdate` will need to handle the new `LastTradePrice` variant — add a `_ => {}` arm or match it explicitly. *** ## 2026-04-19 — V2-ready SDKs released (Rust 0.9.0, TypeScript 0.8.0, Python 0.8.0) All three polynode trading SDKs are now wire-compatible with the Polymarket V2 exchange ahead of the **April 28, 2026 cutover**. Upgrade before then. V1 orders submitted after cutover will be rejected with `order_version_mismatch`. **What changed (all three SDKs):** * V2 CLOB POST body now includes `"expiration": "0"` to match `@polymarket/clob-client-v2`'s wire format * `OrderParams` now exposes a `builder` field (bytes32). Pass your builder code on each order to attribute trades on-chain. Defaults to zero (no attribution). Mint your V2 builder code at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) * All V2 order placement paths live-verified against `clob-v2.polymarket.com` **Install:** ```bash theme={null} cargo add polynode@0.9.0 # Rust npm install polynode-sdk@^0.8.0 # TypeScript pip install "polynode>=0.8.0" # Python ``` **Breaking (Rust only):** `OrderParams` added a required struct field. If you construct `OrderParams { ... }` explicitly without `..Default::default()`, add `builder: None` to your literal. No code change required if you use struct update syntax. See the [V2 Migration Guide](/guides/v2-migration) for the full cutover checklist, the single-line switch, and a troubleshooting reference for common V2 errors. *** ## 2026-04-18 — Rust SDK 0.8.1: batch orderbook API ### New: batch + all-tracked queries Every per-token orderbook method on `OrderbookEngine` and `EngineView` now has a batch and an all-tracked variant. One read lock, one round-trip, results returned as a `HashMap` keyed by token ID. ```rust theme={null} let mids = engine.midpoints(&ids).await; // requested tokens let mids = engine.midpoints_all().await; // every tracked token // Same shape for: spreads / best_bids / best_asks / books let books = engine.books_all().await; // full L2 for everything ``` Tokens not in local state are silently skipped, so callers can pass mixed lists without pre-filtering. ### New: detect inactive markets Each tracked token now records when its local copy was last touched. Use it to find markets that have stopped moving. ```rust theme={null} use std::time::Duration; if let Some(ts) = engine.last_change("token_a").await { println!("last update {:?} ago", ts.elapsed()); } let stale = engine.inactive_since(Duration::from_secs(60)).await; ``` ### New: direct state access `engine.state()` returns the underlying `Arc>` so callers can hold the lock and walk the full state themselves — useful for snapshotting all tokens at one consistent moment or building custom views. ```rust theme={null} let state = engine.state(); let guard = state.read().await; let mids = guard.midpoints_all(); let books = guard.books_all(); ``` ### Install ```bash theme={null} cargo add polynode@0.8.1 ``` All existing per-token methods (`engine.midpoint(id)`, `engine.book(id)`, etc.) are unchanged. This release is purely additive. *** ## 2026-04-17 — Unrealized P\&L + redemption fix ### New: `unrealized_pnl` field on positions Every position returned by `/v2/onchain/positions` now includes an `unrealized_pnl` field showing the paper profit or loss on remaining open shares. * **Resolved markets**: uses the final settlement price ($1 for winners, $0 for losers) * **Active markets**: uses the current market price, refreshed every 15 minutes ### Fixed: realized P\&L for redeemed positions Positions that were closed via onchain payout redemption (rather than selling on the orderbook) now correctly reflect their realized P\&L. Previously, these showed `realized_pnl: 0` even when the position had a gain or loss. *** # Changelog — April 26, 2026 Source: https://docs.polynode.dev/changelog-april-26-2026 Archived PolyNode API and SDK changes from April 26, 2026. [← Back to the current changelog](/changelog) [← Newer entries: April 27 positions](/changelog-april-27-2026-positions) ## 2026-04-26 — New endpoint: `GET /v2/onchain/tags` for tag discovery Lists every tag slug in the polynode taxonomy — currently 5,779 tags. Lightweight by default (just slug strings, 73 KB / 43 ms cold for the full list) or `?details=true` for per-tag enrichment (markets, events, first/last seen). ```bash theme={null} # all tags curl "https://api.polynode.dev/v2/onchain/tags" -H "x-api-key: YOUR_KEY" # top 700 mainstream tags with stats curl "https://api.polynode.dev/v2/onchain/tags?min_markets=100&details=true" \ -H "x-api-key: YOUR_KEY" # discover NBA-related tags curl "https://api.polynode.dev/v2/onchain/tags?prefix=nba&details=true" \ -H "x-api-key: YOUR_KEY" ``` Values returned here are exactly what to pass to `?tag_slug=` on the [wallet positions](/api-reference/wallets/onchain-positions) and [unified positions](/api-reference/onchain/positions) endpoints. Use it to populate filter dropdowns or autocomplete inputs. The underlying materialized view refreshes hourly so newly-added Polymarket tags appear within an hour. *** ## 2026-04-26 — Wallet Positions: `tag_slugs` field + `?tag_slug=` filter Every row of [`GET /v2/wallets/{address}/positions/onchain`](/api-reference/wallets/onchain-positions) now includes a `tag_slugs` array carrying the Polymarket event-level tags that apply to that market — typical values like `nba`, `basketball`, `sports`, `politics`, `crypto`, `fed`, `2025-predictions`, plus event-specific slugs like `2026-fifa-world-cup-winner-595`. Order is most-specific to most-general. A new optional `?tag_slug=` query parameter filters the response to only positions whose market carries that tag. Composes with `since` / `until`, so you can ask for e.g. "all NBA positions traded in the last 30 days" in one request: ```bash theme={null} SINCE=$(( $(date -u +%s) - 86400 * 30 )) curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?tag_slug=nba&since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` When the filter is supplied, aggregates recompute over the filtered set and the response gains `filtered: true` plus `applied_filters: { since, until, tag_slug }` so the behavior is self-documenting. Strictly additive — when no filter param is supplied, the response shape is byte-identical to before. Coverage is effectively universal: tags are populated on every event Polymarket indexes (sampled empirically at 100% in our backfill audit), so any non-test market should return a populated `tag_slugs` array. *** ## 2026-04-26 — Unified Trades: additive `direction` (BUY/SELL) field on `/v2/onchain/trades` [`GET /v2/onchain/trades`](/api-reference/onchain/trades) now also returns `direction` (`"BUY"` / `"SELL"`) on every row when filtered by `wallet` — same semantics as the wallet-trades endpoint, applied to the unified-trades flow. Independent of the existing `side` field. When no wallet anchor is supplied, `direction` is omitted (no perspective to derive against). Strictly additive: every other field is byte-identical to prior responses, and queries without `wallet` are unchanged. Verified live: 1,214 trades cross-checked against Polymarket data-api `side` — zero drift. *** ## 2026-04-26 — Wallet Trades: additive `direction` (BUY/SELL) field Every row of [`GET /v2/onchain/wallets/{address}/trades`](/api-reference/onchain/wallet-trades) now carries a `direction` field with values `"BUY"` or `"SELL"`, derived from whether the queried wallet contributed USDC or outcome tokens on the fill. This is independent of the existing `side` field, which remains the exchange role (`"maker"` / `"taker"`) and is unchanged. The two answer different questions: * `side` — did the wallet provide liquidity or take it? * `direction` — did the wallet enter (BUY) or exit (SELL) outcome shares? All four combinations (`maker`+`BUY`, `maker`+`SELL`, `taker`+`BUY`, `taker`+`SELL`) appear in real responses. Strictly additive — every other field is byte-identical to prior responses. The information `direction` carries was always derivable from `maker_asset_id` / `taker_asset_id` (exactly one is `"0"` on every fill, that's the buyer). This change just makes the derivation explicit so analytics integrations don't have to compute it client-side. *** ## 2026-04-26 — Wallet Positions: per-position timestamps, parent event slug, opt-in window filter Four new fields on every row of [`GET /v2/wallets/{address}/positions/onchain`](/api-reference/wallets/onchain-positions) (and the unified [`GET /v2/onchain/positions`](/api-reference/onchain/positions) feed). Two new optional query parameters for server-side window filtering. Every change is **strictly additive** — calls with no new parameters return responses byte-identical to before. **New per-position fields:** * **`last_trade_at`** — unix seconds. Latest fill on this token across V1 + V2 exchanges. The right field for "active in the last 30 / 90 days" leaderboard windows. * **`closed_at`** — unix seconds. Latest moment the wallet redeemed any outcome of the market for collateral. Distinct from `resolved_at` — `resolved_at` is when the market itself resolved on-chain; `closed_at` is when this specific wallet actually redeemed. * **`resolved_at`** — unix seconds. Moment the market became redeemable (oracle reported payouts on-chain). Recent markets are fully covered; markets that resolved before polynode began tracking return `null`. * **`event_slug`** — the parent **event** slug, distinct from the per-row `slug` (which is the per-market slug). For multi-market events (NBA games with several lines, election markets with multiple candidates, FIFA World Cup with one market per team), `event_slug` is the parent the markets share. For single-market events, `event_slug` equals `slug`. Lets you group positions by event without an extra metadata round-trip. **New optional query parameters** — opt-in only: * **`?since=`** — keep positions whose `last_trade_at >= since`. * **`?until=`** — keep positions whose `last_trade_at <= until`. When either is supplied, all aggregates (`count`, `open_count`, `closed_count`, `total_realized_pnl`, `total_unrealized_pnl`, `total_pnl`, `positions_with_pnl`) recompute over the filtered set, and the response gains two top-level keys to make the shift self-documenting: `filtered: true` and `applied_filters: { since, until }`. These keys are absent from default responses, so existing integrations see zero behavior change. ```bash theme={null} # 30-day window — leaderboard-style request SINCE=$(( $(date -u +%s) - 86400 * 30 )) curl "https://api.polynode.dev/v2/wallets/0x.../positions/onchain?since=$SINCE" \ -H "x-api-key: YOUR_KEY" ``` See the [Positions & P\&L (Wallet)](/api-reference/wallets/onchain-positions) reference for the full field catalog and filtering rules. *** ## 2026-04-26 — X Search API beta New paid endpoints for live X (Twitter) search and account-timeline data. Aimed at teams adding social context next to their prediction-market data — sentiment around a market, replies on a leader's post, what's being said about an event. * **`GET /v2/x/search?q=…&max=…`** — search by query, with full operator support (`from:`, `since:`, `min_faves:`, hashtags, `lang:`). * **`GET /v2/x/user/{handle}/tweets?max=…`** — most-recent tweets from any public X account. Available on starter, growth, and enterprise tiers with monthly quotas of 500 / 1,000 / 5,000. Hard rate cap of 1 request per second per key. Track usage live via `X-Quota-Used` / `X-Quota-Limit` response headers. See the [X Search API guide](/api-reference/x-search) for the full schema and examples. *** # Changelog — April 27, 2026 — Positions Source: https://docs.polynode.dev/changelog-april-27-2026-positions Archived PolyNode position API changes from April 27, 2026. [← Back to the current changelog](/changelog) [Newer: April 30, 2026](/changelog-april-30-2026) · [April 27 trades →](/changelog-april-27-2026-trades) ## 2026-04-27 — Positions: complete Polymarket parity, deterministic resolved-market mark, six new fields, real cursor pagination `/v2/onchain/positions` now matches Polymarket's `data-api` to the cent on every shared position. Verified across six wallets, 627 total shared positions, 100.00% sub-penny match on `unrealized_pnl`. What's new on each position row: * **`initial_value`** — cost basis in USD of currently held shares. Use this when you need the basis number that matches Polymarket `cashPnl`. * **`redeemable`** — `true` when the market has resolved and the user can call redeem to claim payout / accept loss. Filter on this with `market_status` to detect resolved-but-not-yet-redeemed positions. * **`outcome_index`** — numeric index of this row's outcome (0 or 1 for binary markets). Stable across the API regardless of UI label. * **`won`** / **`winning_outcome_index`** — present on `resolved-win` / `resolved-loss` rows. Explicit booleans / ints so consumers don't have to parse outcome label strings. * **`opposite_asset`** — token ID of the binary counterpart outcome on the same market. What's fixed on the math: * **`current_price` is deterministic on resolved markets.** Reads settlement values directly from the CTF contract on Polygon. Returns exactly `1.0` for the winning outcome and `0.0` for the loser, the moment the market settles on chain. * **`market_status` never lies.** Was previously stuck on `"live"` for fresh resolutions when our metadata was behind. Now uses the chain timestamp as the authoritative resolution signal: `"live"`, `"resolved-win"`, `"resolved-loss"`, `"resolved-unknown"`, or `"closed"`. * **`unrealized_pnl` is byte-identical to Polymarket `cashPnl`** for any position covered by both sources. `/v2/onchain/trades` cursor pagination now reports truthful `has_more`. Previously `has_more: false` was returned even when more rows existed beyond the requested `limit`. Walk pages by passing `pagination.pagination_key` back as `?pagination_key=…`. ```bash theme={null} # returns has_more: true with pagination_key now curl "https://api.polynode.dev/v2/onchain/trades?wallet=0x...&limit=2" -H "x-api-key: YOUR_KEY" # walk to the next page curl "https://api.polynode.dev/v2/onchain/trades?wallet=0x...&limit=2&pagination_key=2" -H "x-api-key: YOUR_KEY" ``` Time filters on `/v2/onchain/trades` use **`start_time`** and **`end_time`** (unix seconds), not `from` / `to`. Documented and verified. *** # Changelog — April 27, 2026 — Trades Source: https://docs.polynode.dev/changelog-april-27-2026-trades Archived PolyNode trade API changes from April 27, 2026. [← Back to the current changelog](/changelog) [← April 27 positions](/changelog-april-27-2026-positions) · [Older: April 26, 2026 →](/changelog-april-26-2026) ## 2026-04-27 — Trades: unified schema, `direction` & `side` always present `/v2/onchain/trades`, `/v2/onchain/wallets/{w}/trades`, and `/v2/onchain/markets/{tok}/trades` now return the same `direction` and `side` fields on every row, regardless of which filter combination is passed. Previously these fields appeared only when a `?wallet=` anchor was supplied — market-wide queries (`?condition_id=…`, `?token_id=…`, no filter) omitted both, and consumers had to render two different schemas. ```bash theme={null} # customer's market-wide query — now returns direction+side on every row curl "https://api.polynode.dev/v2/onchain/trades?condition_id=0xb778…&limit=3" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "side": "maker", "direction": "BUY", "maker": "0xdf0d2c…", "taker": "0xb323fd…" } ``` **Anchor rule:** * **With `?wallet=`** — `direction` and `side` are wallet-relative. `direction` is `BUY` when the wallet contributed USDC and received outcome shares, `SELL` when it contributed outcome shares and received USDC. `side` is `maker` when the wallet placed the resting order, `taker` when it crossed the spread. * **Without `?wallet=`** — `direction` is anchored on the **maker** of each fill (the user who signed the limit order; on Polymarket's CLOB this is always a user EOA). `side` is therefore always `"maker"` in this case. This means a single fill viewed from a wallet-filtered query and from a market-wide query may report different `direction` values — both are correct, just anchored on different parties. See the ["Direction & side semantics"](/api-reference/onchain/trades#direction--side-semantics) section on the trades reference page. Strictly additive — calls that previously returned `direction`/`side` continue to return the exact same values. *** # Changelog — April 30, 2026 Source: https://docs.polynode.dev/changelog-april-30-2026 Archived PolyNode API and SDK changes from April 30, 2026. [← Back to the current changelog](/changelog) [Continue to April 27 positions →](/changelog-april-27-2026-positions) ## 2026-04-30 — Backtest Copy PnL: per-position metrics now match Polymarket byte-for-byte The new fields added earlier today (`avg_entry_prob_weighted`, `positions_closed` on `/v2/copy-pnl/*`) now produce values that match Polymarket's own data-api position math. Validated against `data-api.polymarket.com/positions` `realizedPnl` across 30 positions on diverse wallets (standard CTF + neg-risk markets): * **97 %** sub-penny match * **100 %** sub-\$1 match * **100 %** sub-\$10 match No API changes — same field names, same response shape. Existing integrations automatically benefit. Cached values progressively refresh as background scoring cycles complete. *** ## 2026-04-30 — BYOB Snapshot: every wallet × every period in one read New endpoint `GET /v2/copy-pnl/snapshot` returns every wallet in your tracked-wallet pool with backtest copy-PnL scores across all six time windows (`7d`, `14d`, `30d`, `60d`, `90d`, `180d`) in a single response. Built for stats-card UIs and dashboards that need the whole pool at once instead of issuing one request per period. * **One request** — no per-period round trips, no client-side stitching. * **Sub-second cached** — 100 wallets × 6 periods returns in \~70 ms / \~150 KB. 1000 wallets × 6 periods in \~500 ms / \~1.5 MB. * **Optional period subset** via `?periods=7d,30d` to drop payload when you only need one window. * **Per-wallet error reporting** — heavy whales that errored on the most recent refresh surface their failure reason inline, so your UI can render "X wallets retrying" instead of hiding gaps. ```bash theme={null} curl -H "x-api-key: $YOUR_KEY" \ "https://api.polynode.dev/v2/copy-pnl/snapshot" ``` See [BYOB — Snapshot](/api-reference/backtesting/byob-snapshot) for the full response shape and examples. *** ## 2026-04-30 — `/v2/onchain/markets/{token}/volume` faster Backend optimization for the market volume endpoint. Response shape and values are unchanged — same `buys`, `sells`, `total_trades`, `buy_volume_usdc`, `sell_volume_usdc`, `volume_usdc`, `found` fields. Light and empty markets see roughly halved latency. No integration changes required. *** ## 2026-04-30 — Wallet activity & redemptions: deep pagination unlocked Heavy wallets returning more than 1000 records on `/v2/onchain/wallets/{wallet}/redemptions` and `/v2/onchain/wallets/{wallet}/activity` now return the complete dataset: * **`offset` past 1000 now works.** Previously, pagination beyond the first 1000 records returned empty results regardless of how many records existed. You can now walk a heavy redeemer's full history with `offset=1000`, `offset=2000`, etc. * **No more silent truncation.** Wallets with >1000 redemptions, splits, merges, or neg-risk conversions previously had results capped at 1000. The full record set is now returned. No SDK update required. No integration changes. Same URLs, same query parameters, same response shapes — your existing code automatically benefits. ```bash theme={null} # Walk a heavy redeemer's full history: curl "https://api.polynode.dev/v2/onchain/wallets/{wallet}/redemptions?limit=1000&offset=0" \ -H "x-api-key: $YOUR_KEY" curl "https://api.polynode.dev/v2/onchain/wallets/{wallet}/redemptions?limit=1000&offset=1000" \ -H "x-api-key: $YOUR_KEY" ``` *** ## 2026-04-30 — TypeScript SDK 0.9.7 Pluggable storage for Bun/Deno/edge runtime compatibility: * **`storage` config option** — pass `'memory'` for an in-memory backend (no native dependencies), a file path for SQLite (default), or your own `TradingStorage` implementation. * **Auto-fallback** — if `better-sqlite3` isn't available (Bun, Deno, edge runtimes), the SDK automatically falls back to in-memory storage instead of crashing. * **`BunSqliteBackend`** — persistent SQLite storage using Bun's built-in `bun:sqlite`. Zero native dependencies. Same schema, same persistence as the Node backend. * **Auto-detection** — if you don't pass a `storage` option, the SDK tries `better-sqlite3` first (Node), then `bun:sqlite` (Bun), then falls back to in-memory. Just works in both runtimes. * **Exported interface** — `TradingStorage`, `InMemoryStorage`, and `BunSqliteBackend` are all exported so you can use them directly or build custom adapters. ```typescript theme={null} // Bun — auto-detected, no config needed: const trader = new PolyNodeTrader({ /* storage auto-detects bun:sqlite */ }); // Bun — explicit: import { PolyNodeTrader, BunSqliteBackend } from 'polynode-sdk'; const trader = new PolyNodeTrader({ storage: new BunSqliteBackend('./trading.db'), }); ``` Upgrade: ```bash theme={null} npm install polynode-sdk@0.9.7 ``` *** ## 2026-04-30 — TypeScript SDK 0.9.5 Bug fix release for the trading module: * **Fixed `signer.getAddress is not a function` crash** — `ensureReady()` and `linkWallet()` could throw this error with viem WalletClient signers when Polymarket packages expect an ethers-style `getAddress()` method. The SDK now ensures `getAddress()` is always available on the normalized signer, regardless of which `@polymarket/clob-client` version you have installed. * **Fixed signer detection logic** — a duplicate guard condition was allowing incomplete signer objects through, causing crashes instead of clean error messages. * **Hardened relay signer adapter** — address extraction now handles additional wallet shapes during Safe deployment and approval flows. Upgrade: ```bash theme={null} npm install polynode-sdk@0.9.5 ``` *** ## 2026-04-30 — BYOB (Bring Your Own Backtest) — precomputed leaderboards The on-demand backtest endpoints answer "score this wallet" synchronously. **BYOB inverts that** — you hand us a private wallet pool, we precompute scores in the background across all six period presets, you query the resulting leaderboard with sub-second latency. Four new endpoints under `/v2/copy-pnl/`: ``` POST /v2/copy-pnl/wallets body: {addresses[]} add to pool (max 1000) DELETE /v2/copy-pnl/wallets body: {addresses[]} remove from pool GET /v2/copy-pnl/wallets list pool GET /v2/copy-pnl/leaderboard ?period=&sort_by=&order=&limit=&offset=&min_trade_count=&exclude_toxic= ``` Newly-added wallets are scored within \~30s of being added. The full pool refreshes daily in the background. Each result row includes `computed_at` so you can render freshness in your UI. Per-tenant isolation: each API key has its own private pool keyed on the SHA256 of the key. Your tracked wallets are never visible to other customers. References: [Backtesting Overview](/api-reference/backtesting/overview) · [Add Wallets](/api-reference/backtesting/byob-add-wallets) · [Remove Wallets](/api-reference/backtesting/byob-remove-wallets) · [List Wallets](/api-reference/backtesting/byob-list-wallets) · [Leaderboard](/api-reference/backtesting/byob-leaderboard) *** ## 2026-04-30 — On-chain wallet/market trades: deep pagination unlocked `/v2/onchain/wallets/{w}/trades` and `/v2/onchain/markets/{token}/trades` now properly paginate across the full trade history of any wallet or market, no matter how active. Previously these endpoints silently truncated heavy traders to \~2000 fills lifetime — deep `?offset=` queries returned empty. Customer-visible behavior changes: * Heavy wallets (e.g. 1M+ fills) now return correct, complete trade history * Deep `?offset=` queries return real data instead of empty arrays * No SDK or query-shape changes required — same `?limit=&offset=` parameters * Lower latency on most queries *** ## 2026-04-30 — Backtest Copy PnL: batch endpoint Score up to 100 wallets in one call: ``` POST /v2/copy-pnl/batch { "addresses": ["0x...", ...], "from": "...", "to": "..." } ``` Same math + response shape as the single-wallet endpoint. Per-wallet errors don't fail the batch — the bad slot returns `{"wallet": "...", "error": "..."}` and the rest still come back. Reference: [Batch endpoint](/api-reference/backtesting/batch) *** ## 2026-04-30 — Backtest Copy PnL endpoint New paid endpoint for scoring any wallet's copy-trade quality: ``` GET /v2/copy-pnl/{wallet}?period=30d ``` Walks every fill in the requested window, applies a realistic 2% slippage on buys and sells (capped at \$1.00 per share for buys), settles redemptions / merges / splits at face value, and returns: * `actual_pnl_usdc` — the wallet's cashflow PnL over the window * `backtest_copy_pnl_usdc` — what a copier would have earned with friction * `slippage_amount_usdc` — the dollar gap * `slippage_cost_rate_pct` — friction as a percentage of actual PnL * `toxic_for_copying` — `true` when the rate exceeds 15% (wallet's profit relies on execution speed; copier won't replicate) * `trade_count`, `applied_filters`, `sources`, optional `trades[]` drill-down **Time window options**: `?period=7d|14d|30d|60d|90d|180d` (default 30d), or `?from=&to=` with `YYYY-MM-DD` or unix seconds. **Note on PnL definition**: this returns **cashflow** PnL (real dollars moved), not Polymarket's website PnL (which marks open positions at current price). The response includes a `pnl_definition: "cashflow"` field to make this explicit. For PM-website style PnL use [Trader PnL Series](/api-reference/enriched/trader-pnl). **Limits**: paid tier required, 1 request per 5s per key, 30s server-side budget. Validated on wallets up to \~1.6M fills in the window. Full reference: [Backtest Copy PnL](/api-reference/backtesting/copy-pnl) · [Backtesting Overview](/api-reference/backtesting/overview) *** # Changelog - August 10-16, 2026 Source: https://docs.polynode.dev/changelog-august-10-16-2026 Archived polynode SDK, billing, V3, WebSocket, Chainlink, and user-owned execution changes from August 10 through August 16, 2026. [← Back to the current changelog](/changelog) [Earlier: August 3-9, 2026 →](/changelog-august-3-9-2026) ## 2026-08-15 - More reliable TypeScript V2 trading and a smaller npm install The TypeScript SDK's 0.13.x release series closed several V2 trading edge cases and reduced the public package to its intended runtime surface. What's improved: * Concurrent V2 orders now receive distinct order identities even when they are prepared during the same second. * Fill-or-kill results that become ambiguous at the HTTP boundary are reconciled conservatively instead of being reported as a definite failure. * Repeated deposit-wallet setup and relayed calls do not repeat an already completed setup step. * `polynode-sdk` 0.13.6 reduced the package to one direct runtime dependency, `viem`. Optional trading integrations remain separately installable. * Clean ESM and CommonJS consumer installs passed with zero production audit findings. These fixes are included in the current `polynode-sdk` 0.14.2 release. Docs: [TypeScript trading](/sdks/ts/trading) *** ## 2026-08-14 - User-owned execution across all three SDKs TypeScript `polynode-sdk` 0.13.0, Python `polynode` 0.13.0, and Rust `polynode` 0.16.0 introduced the first shared user-owned execution mode. What's new: * A connected wallet can authorize wallet-scoped relayer credentials without giving polynode or the integrating platform its private key or seed phrase. * User-owned orders use the wallet's own trading credentials, carry zero builder attribution, and do not consume the platform's shared builder allowance. * EOA, Safe, and default deposit-wallet account types are supported with exact wallet and funder binding. * The SDKs reject builder credentials, builder codes, and positive polynode fees when user-owned mode is selected. * The existing `https://trade.polynode.dev` service URL is used. No separate cosigner URL or additional service purchase is required. The August 18 release added the complete browser-signing, encrypted-vault, funding, exact-order identity, and Connect Wallet guide on top of this base. Docs: [User-owned execution](/sdks/user-owned-execution) *** ## 2026-08-12 - Explicit Chainlink spot subscriptions Clients can now request the Chainlink spot stream explicitly while the default `chainlink` subscription continues to follow both TWAP windows. What's new: * Set `price_source: "spot"` at the subscription top level or inside `filters` to receive only spot events. * Continue using `twap_windows: [30]`, `[60]`, or `[30, 60]` for explicit TWAP selection. * A subscription cannot combine spot and TWAP selectors. Invalid combinations fail closed with a protocol error. * Spot and TWAP events retain the same feed names and additive identity fields. Default subscriptions remain on the two TWAP windows. Docs: [Chainlink TWAP Prices](/crypto/twap) *** ## 2026-08-12 - Safer paid-access recovery and resubscription Corrected two billing-state edge cases that could leave a successfully paid or newly resubscribed account on older access state. What's improved: * A successful current payment restores the matching paid entitlement before older period records are considered. * Successive paid periods no longer overlap in a way that lets an earlier correction replace the current period. * Accounts whose recorded legacy period has ended can start a current subscription from the pricing flow without the old record blocking them. * Existing API keys remain attached to the account and adopt the restored plan limits after the successful billing event. [View current pricing](https://polynode.dev/pricing) *** ## 2026-08-11 - Faster deep wallet-position pages Improved `GET /v3/wallets/{address}/positions` for deep pages and terminal status filters that could still exceed the public timeout. Release measurements: * The exact reproduced query improved from 6.6 seconds to about 0.6 seconds. * The prior public timeout returned HTTP `200` in 657 milliseconds after the change. * A 24-case public matrix across open, closed, redeemable, and redeemed states and offsets through 4,800 returned HTTP `200` throughout, from 70 milliseconds to 1.17 seconds. Fields, values, ordering, filters, and pagination remain compatible. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-08-11 - Restart an expired legacy subscription Accounts that reached the end of an earlier recorded paid period now receive a clear current-subscription path instead of a dead-end legacy billing action. What's improved: * The Billing page directs eligible expired accounts to the current pricing flow. * A successful current subscription takes precedence over the expired record. * Existing API keys are retained and receive the selected plan's limits after activation. * Ambiguous or still-active billing records continue to fail closed instead of creating a duplicate subscription. [View current pricing](https://polynode.dev/pricing) *** ## 2026-08-10 - Complete billing self-service and invoice history The signed-in dashboard now uses a dedicated Billing page for current plan details, limits, invoices, and subscription actions. What's new: * Current plan and capacity are shown together with the correct Manage, Subscribe, or payment-recovery action. * Current and legacy invoice history appear in one timeline. * Archived invoices remain visible without presenting an invalid action for a closed billing account. * Active current subscribers are sent to the current billing portal rather than a legacy portal or duplicate Checkout. No API-key value or active plan entitlement changes merely by viewing the page. *** ## 2026-08-10 - Faster recent position pages Improved recent open-position pages that previously timed out while checking whether historical rows still needed repair. Release measurements: * The reproduced `status=open&offset=300&limit=500` request improved from HTTP `504` at about 3.04 seconds to HTTP `200` in 0.32 to 0.41 seconds. * Eight of twelve historical timeout shapes returned HTTP `200` on their first replay after the release. The response contract, ordering, and pagination are unchanged. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-08-10 - Correct V2 taker execution amounts Corrected V2 taker-fill interpretation in the Event WebSocket. What's improved: * Pending `fills` and settlement rows now preserve the wallet's actual side, execution price, and share size for direct BUY/SELL, BUY/BUY mint, SELL/SELL merge, mixed-side, standard, and negative-risk V2 fills. * A release proof matched 1,450 pending fill rows to pending settlements and matched 1,417 receipt-confirmed fills on side, price, and size with zero mismatch. * Existing event names and field types are unchanged. Docs: [Fills subscription](/websocket/subscribing#fills) and [Trade tracking](/guides/trade-tracking) *** ## 2026-08-10 - Improved confirmation-stream continuity Improved Event WebSocket confirmation timeliness and continuity during transient data interruptions. The public subscription protocol, confirmation payloads, event ordering, and API-key behavior are unchanged. Post-release acceptance retained contiguous Polygon heads and current settlement/status delivery through the reproduced failure cases, so no client change is required. # Changelog - August 3-9, 2026 Source: https://docs.polynode.dev/changelog-august-3-9-2026 Archived polynode usage, billing, V3, WebSocket, perps, Chainlink, and dashboard changes from August 3 through August 9, 2026. [← Back to the current changelog](/changelog) [Earlier: July 27-August 2, 2026 →](/changelog-july-27-august-2-2026) ## 2026-08-09 - Usage pace and capacity projections The signed-in Usage page now turns current account usage into an end-of-cycle projection for each monthly resource. What's new: * Each resource shows the account's current average per day and projected total through the end of the service period. * The page calculates the exact additional 10-million-request or 100-GB package count needed at the current pace. * When added capacity is needed, the page shows the one-time package cost and a direct guarded Checkout action. * Accounts that already fit their capacity see that explicitly. Very large projections direct the customer to the Enterprise/Institutional contact path. * Projections update as account usage changes and do not change plan capacity or enable monthly enforcement. Docs: [Monthly usage allowances and packages](/guides/rate-limits#monthly-usage-allowances) *** ## 2026-08-08 - Account usage dashboard and one-time capacity packages The signed-in polynode dashboard now shows account-level API requests, Order Book + Chainlink transfer, and On-chain event transfer for the current service period. What's new: * Included plan capacity and added packages are displayed separately with exact remaining amounts and dates. * Every active API key owned by an account contributes to the same account totals. * The monthly calculator estimates 24/7 WebSocket transfer and API-request needs, then suggests matching packages. * One-time Stripe Checkout supports 10-million-request, 100-GB Order Book + Chainlink, and 100-GB On-chain event packages. Each package costs \$20 and remains active for 90 days. * Existing per-minute, per-second, connection, and Free-session limits are unchanged. * Monthly usage enforcement is not active yet; this release adds visibility and prepaid capacity first. Docs: [Monthly usage allowances and packages](/guides/rate-limits#monthly-usage-allowances) *** ## 2026-08-07 - Faster recent wallet trades and positions Improved the default and recent-window paths for wallet trades and wallet positions without changing their response contracts. Release measurements: * An exact trade request that returned HTTP `504` in 3.05 seconds returned HTTP `200` in 82 milliseconds after release. * The next 2,000 wallet-trade requests were 2,000/2,000 HTTP `200`, with 81 milliseconds p99 and zero 5xx responses. * Four other observed timeout wallets returned in 67 to 85 milliseconds. * The subsequent recent-position window was 296/296 HTTP `200`, with 664 milliseconds p99 and 809 milliseconds maximum. Fields, values, ordering, pagination, grouping, and filters remain compatible. Docs: [Wallet Trades](/data/wallets/trades) and [Wallet Positions](/data/wallets/positions) *** ## 2026-08-07 - Chainlink TWAP default cutover completed The default `chainlink` WebSocket subscription now delivers both published TWAP windows. What's changed: * Default subscriptions receive 30-second and 60-second Chainlink TWAP events. * Clients that need one window can continue to select `twap_windows: [30]` or `[60]` explicitly. * Every event identifies its window through `is_twap` and `twap_window_seconds`. * Existing sockets, feed names, API keys, and subscription messages remain compatible. The orderbook stream is unaffected. Docs: [Chainlink TWAP Prices](/crypto/twap) *** ## 2026-08-06 - Global leaderboard rank ceiling `GET /v3/leaderboard` now serves ranks 1 through 10,000 and rejects deeper windows before running an expensive query. Client behavior: * `offset + limit` may be at most 10,000 on the global leaderboard. * A deeper request returns HTTP `400` with `error: "leaderboard_offset_too_deep"`, plus `max_rank`, `max_offset`, `limit`, and `offset`. * Normal pages and tag-scoped leaderboards retain their existing behavior. * In the release sample, over-cap requests were rejected in at most 3.86 milliseconds while a two-minute V3 window completed with zero requests at or above 2.9 seconds. Docs: [Global Leaderboard](/data/leaderboard/global) *** ## 2026-08-06 - More reliable perps WebSocket delivery The perps WebSocket no longer leaves a connected client attached to stale ticker data when a market-data session becomes silent. Release validation retained the same connected client through a reproduced silent period and then observed 6,800 current ticker events in 20 seconds. The public authenticated socket subsequently delivered 5,066 ticker events in 15 seconds with current data and no gateway error. Event schemas, subscriptions, authentication, and REST routes are unchanged. Docs: [Perps WebSocket](/perps/websocket/overview) *** ## 2026-08-06 - Explicit API-key copy failures The dashboard now reports when the browser cannot place a newly created API key on the clipboard instead of showing a false success state. The key remains visible for the existing one-time copy flow, so the user can copy it manually. API-key values, issuance, and authentication are unchanged. *** ## 2026-08-05 - Migrate a legacy subscription without losing prepaid time Eligible subscribers from the earlier billing catalog can now move through the current card Checkout while preserving their recorded paid-through date. What's improved: * The dashboard sends an eligible legacy subscriber to current Checkout instead of a closed legacy billing portal. * The new subscription begins billing at the verified end of the prepaid period, with no proration charge for time already paid. * The existing entitlement remains authoritative until Checkout succeeds, so an abandoned session does not remove access. * Repeated attempts reuse the same open same-plan Checkout and do not create a duplicate subscription. * Current-account subscribers continue to use the current billing portal. [View current pricing](https://polynode.dev/pricing) *** ## 2026-08-04 - Faster bounded historical trade pages Improved historical V3 trade pagination when a bounded time window is combined with a deeper offset. Release measurements: * The reported `after=1783768438&offset=585&order=asc&limit=1` request improved from HTTP `504` in 3.32 seconds to HTTP `200` in 186 milliseconds. * Related offset-zero and bounded `before` variants returned in 84 to 86 milliseconds. Response fields, ordering, inclusive time behavior, offsets, and filters remain compatible. Docs: [Wallet Trades](/data/wallets/trades) *** ## 2026-08-04 - Correct compact combo execution fills Reconciled `combo_execution` with the static combo API and the standard maker/taker vocabulary used by settlement events. What's improved: * Top-level fields describe the taker execution while `trades[]` describes each signed order from the maker's perspective. * `size` is shares, `amount_usdc` is dollars, and `price` is the actual fill price rather than the signed limit when price improvement occurs. * Each signed order includes its canonical exchange `order_hash` for exact correlation. * Validation covered 48 historical confirmed combo transactions and 101 receipt fills, including multi-maker, BUY, SELL, standard, and negative-risk cases. Docs: [Combo Execution](/websocket/events/combo-execution) *** ## 2026-08-03 - Recover a past-due subscription without duplicating it Accounts with a current subscription in payment recovery are now directed to that subscription's Billing Portal instead of a new Checkout. What's improved: * A customer can update the payment method and pay the existing invoice. * Paid access is restored only after a successful payment event. * Card updates alone cannot incorrectly restore a still-unpaid subscription. * Repeated recovery actions cannot create a second current subscription. * Existing API keys are preserved throughout recovery. [View current pricing](https://polynode.dev/pricing) # Changelog - July 13-19, 2026 Source: https://docs.polynode.dev/changelog-july-13-19-2026 Archived PolyNode API, identity, WebSocket, orderbook, website, pagination, performance, and reliability changes from July 13 through July 19, 2026. [← Back to the current changelog](/changelog) [Earlier: July 6-12, 2026 →](/changelog-july-6-12-2026) ## 2026-07-19 - Opt-in orderbook sequence and checksum verification Added PN1, an opt-in integrity protocol for clients that maintain a local copy of the Orderbook Stream. What's new: * Connect to `wss://ob.polynode.dev/ws?key=YOUR_KEY&integrity=1` to receive an ordered anchor for every subscribed token. * Every depth-changing frame carries a token-scoped `prev_seq`, `seq`, and deterministic post-update `checksum`. A client can detect either a missing frame or an incorrectly applied price level immediately. * Send `{"action":"resync","markets":["TOKEN_ID"]}` after a sequence or checksum failure. The stream gates that token, sends a replacement `book_snapshot` anchor, and confirms completion with `snapshots_done` and `reason: "resync"`. * If an anchor is already being prepared, `resync_in_progress` includes `retry_after_ms`. If continuity can no longer be guaranteed, `integrity_backpressure` or `integrity_internal_reset` closes the connection so the client can reconnect with fresh anchors. * PN1 subscriptions use explicit market lists and are initially capped at 500 resolved token IDs per connection. `markets: ["*"]` remains available on the normal stream but is not supported with `integrity=1`. Existing account limits still apply when lower. * `last_trade_price` and other non-depth events do not advance the depth sequence or carry a checksum. The normal stream is unchanged when `integrity` is omitted or set to `0`. PN1 verifies the continuity and resulting state of PolyNode-delivered depth; it is not a Polymarket sequence number or a cryptographic signature. Launch verification covered 368 anchors, approximately 12,800 depth updates, 543 trade messages, targeted resync, compressed and uncompressed connections, and both Node.js and Python clients. These are release-validation measurements, not throughput guarantees. Docs: [Orderbook Integrity (PN1)](/orderbook/integrity), [Orderbook Messages](/orderbook/messages), and [Orderbook Stream](/orderbook/overview) *** ## 2026-07-19 - Bounded concurrency for exact wallet P\&L Added a short, explicit concurrency bound to `GET /v3/wallets/{address}/pnl` so bursts of expensive wallet calculations fail quickly and predictably instead of building a long queue. Client behavior: * Each account can have up to two exact wallet P\&L requests running at once. * An additional request waits for capacity for up to 750 milliseconds. If the account's two requests are still running, it returns `429` with `error: "wallet_pnl_busy"`, `scope: "v3_pnl_account_concurrency"`, and `Retry-After: 1`. * A separate capacity response can return `503` with `scope: "v3_pnl_global_concurrency"`. It uses the same `wallet_pnl_busy` error and one-second retry guidance. * This concurrency guard is separate from requests-per-minute limits. Successful responses still include the normal rate-limit headers. * `GET /v3/wallets/{address}/pnl/events`, leaderboards, batch wallet reads, and trade routes are not part of this guard. Requests that proceed return the same P\&L fields and values as before. In release validation, a three-request burst against a worst-case wallet returned the excess request in 781 milliseconds instead of leaving all three calculations running. Docs: [Wallet P\&L](/data/wallets/pnl) and [Rate Limits](/guides/rate-limits) *** ## 2026-07-18 - V3 pages now have a 1,000-item ceiling Standardized the largest possible V3 response page at 1,000 rows or buckets. What's changed: * No V3 endpoint returns more than 1,000 rows or buckets in one page. Requests above an endpoint's cap are normalized to the cap instead of rejected. * `GET /v3/wallets/{address}/pnl/events` now defaults to `limit=1000` and clamps there, replacing its former 5,000 default and 10,000 maximum. * `GET /v3/markets/condition/{condition_id}/positions` keeps a 300-row Starter cap; Growth and Enterprise keys can request up to 1,000. The former Enterprise maximum was 2,000. * Stricter endpoint caps remain in place. Most V3 lists still cap at 300 rows, and leaderboards retain their 100-row cap. * Values through each endpoint's cap, cursor and offset behavior, filters, sorting, response fields, and row contents are unchanged. For a complete history, continue paging with the returned offset or cursor. For deep trade history, bounded `after` and `before` windows are usually more efficient than very large offsets. Docs: [Pagination Limits](/guides/rate-limits#pagination-limits), [Wallet P\&L Time Series](/data/wallets/pnl-events), and [Condition Holders](/data/markets/condition-positions) *** ## 2026-07-18 - Faster token-scoped wallet trade history Improved `GET /v3/wallets/{address}/trades` when a request is narrowed to one outcome token. What's improved: * Token-scoped maker, taker, and `role=both` reads now use a faster path while preserving one row per matching wallet role. * Pagination remains stable and non-overlapping, including single-side maker-only and taker-only requests. * Token, condition, market, event, time, role, amount, grouping, sorting, and ordering filters were checked together to ensure the optimization did not change composition behavior. * Request parameters, response fields, formulas, caps, and broader multi-market query behavior are unchanged. In the release concurrency check, a 16-way request set improved from 51.5 ms p95 to 17.8 ms p95, with all 64 responses successful. This is a measured release result, not a latency SLA. Docs: [Wallet Trades](/data/wallets/trades) *** ## 2026-07-18 - Faster explicit-window P\&L histories Improved `GET /v3/wallets/{address}/pnl/events` for long explicit `after`/`before` windows without changing P\&L calculations or response ordering. Release measurements: * A heavy full-history control improved from 6.466 seconds to 560 milliseconds. * A replay of 141 previously slow request shapes completed with HTTP `200` throughout: 72 ms median, 1.483 seconds p95, 2.393 seconds p99, and 6.272 seconds maximum. * Responses before and after matched on deterministic fields, values, types, and ordering. The 1,000-bucket page ceiling introduced the same day applies to these histories. Use successive windows or pages when more buckets are needed. Docs: [Wallet P\&L Time Series](/data/wallets/pnl-events) *** ## 2026-07-17 - Wallet type, deployment, and current status are separate Identity responses can now distinguish what kind of wallet an address is, whether its contract exists on Polygon, and whether it is the account's currently selected trading wallet. What's new: * `wallet_type` reports `deposit_wallet`, `safe`, or `proxy` when known. * `deployed` reports whether the wallet contract currently exists on Polygon. * `current` reports whether the address is the account's selected trading wallet. * The fields are additive on `GET /v3/identities/{address}`, `POST /v3/identities/batch`, `GET /v3/identities/search`, and identity-enriched credits responses. * `GET /v1/resolve/{query}` now includes `wallet_details`, which lists the current address and the account's other deployed wallets with `wallet_type`, `deployed`, and `current` on each item. The existing `wallets` object remains deployed-only for compatibility. This means a current deposit-wallet address can appear in `wallet_details` with `deployed: false` and `current: true` while its `wallets.deposit_wallet` value is still `null`. Legacy identities can return `null` where a status is genuinely unknown. No existing resolver or identity field was renamed or removed. Docs: [Resolve Wallet](/api-reference/wallets/resolve), [Identity Lookup](/identities/lookup), [Batch Resolve](/identities/batch-resolve), and [Username Search](/identities/search) *** ## 2026-07-17 - V3 account-level rate limits V3 REST limits now apply once per account, not once per API key. What's new: * All API keys owned by the same account share the plan's rolling standard V3 REST allowance. * Keys can be used at the same time, but creating more keys does not increase the account's throughput. * Heavy trade-history endpoints keep their separate allowance, which is also shared across the account's keys. Existing API keys, request formats, numeric plan allowances, and rate-limit response headers continue to work without client changes. Docs: [Rate Limits](/guides/rate-limits) *** ## 2026-07-15 - Lower settlement, status, and confirmed-trade latency Corrected two independent delivery stalls affecting the public event WebSocket. What's improved: * Settlement frames no longer accumulate behind periodic connection bookkeeping and then arrive in a burst. In a 210-second public check covering 3,743 settlements, measured delivery was 1 ms median, 3 ms p90, 15 ms p99, and 214 ms maximum. * Confirmed `status_update` and `trade` delivery recovered from a post-restart regression whose p90 had risen to approximately 23.7 seconds. Later windows measured status p90 at 530-842 ms and trade p90 at 491-1,066 ms. * Pending settlement notifications continue to lead confirmed status delivery. Follow-up windows measured a 2.9-3.3 second p90 lead. * A 180-second public soak delivered 4,336 settlements and 4,317 status updates across 121 blocks with no socket or parsing errors; embedded confirmation latency measured 3.096 seconds p95 and 3.794 seconds maximum. * A paired validation matched 257 of 257 observed pending transactions to their confirmed updates, with arrival latency of 3.003 seconds p95 and 3.221 seconds p99. Payloads, metadata enrichment, routing, compression, subscription behavior, and free-tier rules are unchanged. Docs: [Settlement Events](/websocket/events/settlement), [Status Update Events](/websocket/events/status-update), and [Trade Events](/websocket/events/trade) *** ## 2026-07-14 - Clearer checkout returns and support feedback Improved two customer-facing website flows. What's changed: * After a successful card checkout returns to the dashboard, the page now refreshes account status for up to 30 seconds until the selected paid plan is visible. This avoids briefly showing the old plan while activation finishes. * The support widget now shows an on-page acknowledgement only after a message is accepted. The acknowledgement disappears when a real support reply arrives; signed-in users are also told that a reply can follow by email while they are away. * New USDC checkout buttons and sign-in handoffs were temporarily removed from the website. Previously stored USDC handoffs are cleared so an old browser session cannot reopen that purchase flow. * Existing USDC-paid access and its displayed expiration date are unchanged. Card checkout remains available. No API endpoint, API key, plan name, or existing paid entitlement changed as part of this website update. [View current pricing](https://polynode.dev/pricing) *** ## 2026-07-14 - Faster recent wallet-position pages Improved `GET /v3/wallets/{address}/positions` performance for recent, not-yet-redeemed positions, especially on wallets with long histories. One previously slow release sample improved from approximately 194 ms to 24.3 ms. Public position samples remained successful, and a combined positions/trades enrichment check passed without response differences. The endpoint's 300-row page cap, lifecycle filters, fields, values, and pagination contract are unchanged. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-07-13 - V3 service incident resolved Some core V3 data requests returned `503` responses beginning at approximately 22:20 UTC, with the main service interruption lasting from approximately 23:00 to 23:51 UTC. Service was restored during the same window. Post-recovery checks returned `200` across the affected surfaces, including approximately 100 ms for a representative trades request and 36 ms for a representative positions request. Normal live-data processing also resumed. No client request, endpoint, or response-format change was required after recovery. # Changelog - July 20-26, 2026 Source: https://docs.polynode.dev/changelog-july-20-26-2026 Archived polynode combo, trade, WebSocket, account, and billing changes from July 20 through July 26, 2026. [← Back to the current changelog](/changelog) [Earlier: July 13-19, 2026 →](/changelog-july-13-19-2026) ## 2026-07-25 - Full and partial combo redemption lineage Added dedicated combo redemption endpoints without changing existing position or activity responses. What's new: * `GET /v3/combos/redemptions` returns canonical combo redemption and reduction history across wallets. * `GET /v3/wallets/{address}/combos/redemptions` returns the same history for one wallet. * Every row identifies `redemption_scope` as `full`, `partial`, or `transformation` and exposes its supporting `redemption_evidence`. * Full redemptions map automated redemption activity to the actual user and combo position. * Partial reductions expose source, destination, removed, remaining, parent, and child identifiers, with `leg_transition` values such as `5_to_1`. * When canonical market metadata exists, enriched legs include token, result, and current-price fields. Permissionless legs retain their exact position ID without guessed market fields. * Filters cover wallet, condition, position, event kind, scope, transaction hash, and time range. Docs: [Combo Redemptions](/data/combos/redemptions) and [Wallet Combo Redemptions](/data/combos/wallet-redemptions) *** ## 2026-07-24 - Clearer WebSocket and RPC capacity limits Updated the public limit contract so client connection planning is distinct from subscription planning. What's clarified: * A WebSocket physical-connection allowance is separate from the number of logical subscriptions and filters multiplexed over each connection. * Requests authenticated by a member-owned API key use that key's own plan limits rather than a shared platform key's allowance. * Eligible paid API keys can use the documented Polygon RPC allowance of 50 requests per second. * Existing endpoint, message, and authentication formats are unchanged. Docs: [Rate limits](/guides/rate-limits) *** ## 2026-07-22 - polynode is now part of Agg polynode joined Agg and continues as a standalone product for Polymarket data customers. What this means for customers: * Existing API and WebSocket domains, endpoints, API keys, SDK workflows, and documentation remain available. No client migration is required. * Current plan names and pricing remain in place, and the product stays open to all builders. * The product focus remains faster maintenance, stronger reliability, and broader data coverage. [Read the announcement](https://www.tradingview.com/news/chainwire:7f0ceb3a3094b:0-agg-market-acquires-polynode-the-fastest-polymarket-data-api/) *** ## 2026-07-21 - Query trades by order hash V3 trade feeds can now return every fill associated with one exact Polymarket order hash. What's new: * Use `order_hash` on `GET /v3/trades`, `GET /v3/wallets/{address}/trades`, `GET /v3/markets/{token_id}/trades`, and `GET /v3/markets/slug/{slug}/trades`. * Wallet queries can combine the hash with maker/taker role, token, condition, market, event, time, and amount filters. Filtering occurs before pagination. * `group_by=order_hash` and `sort_by=order_hash` work consistently across the global, wallet, market-token, and market-slug routes. * A valid hash with no matching fills returns an empty page. A malformed hash returns HTTP `400`. * Combo trades do not expose a Polymarket order hash, so combining `order_hash` with `include_combos=true` returns HTTP `400`. Docs: [Trades by Order Hash](/data/query-catalog/trades/by-order-hash) and [Wallet Trades](/data/wallets/trades) *** ## 2026-07-21 - Clearer subscription expiry and resubscription Updated how the dashboard handles an earlier paid subscription after its recorded access period ends. What's changed: * Paid access moves to the Free plan at the recorded end time rather than remaining indefinitely on an expired subscription. * Existing API keys remain active and adopt Free-plan access and limits. * A Free account sees **Subscribe** in Settings and is sent to current pricing, even when the account retains an older billing reference. * A newer active subscription or another valid paid-access method takes precedence, so an old expiry cannot overwrite current access. * Delayed billing events from an earlier subscription cannot overwrite a newer successful resubscription. [View current pricing](https://polynode.dev/pricing) *** ## 2026-07-20 - Updated card checkout and billing portal Moved new card purchases to the current polynode subscription catalog while preserving active access and in-progress checkouts during the transition. What's improved: * Starter, Growth, and Enterprise purchase buttons open the current card checkout for the published plan and price. * The Starter plan retains its three-day trial. * A checkout opened from an older browser session is translated to the corresponding current plan instead of failing on an outdated reference. * Customers with an active subscription are sent to the correct billing portal instead of creating a duplicate Checkout. * Existing paid access remains valid through its recorded paid-through period. [View current pricing](https://polynode.dev/pricing) # Changelog - July 27-August 2, 2026 Source: https://docs.polynode.dev/changelog-july-27-august-2-2026 Archived polynode SDK, combo, Chainlink, V3, order-book, and account changes from July 27 through August 2, 2026. [← Back to the current changelog](/changelog) [Earlier: July 20-26, 2026 →](/changelog-july-20-26-2026) ## 2026-08-02 - Restored combo execution and redemption delivery Restored real-time combo execution and redemption event delivery. What's improved: * Existing `combo_execution` and combo-redemption subscriptions resume without a client message or parser change. * Execution payloads retain canonical signed-order hashes and maker/taker semantics. * Combo legs are enriched with current canonical market category, tags, images, event metadata, and a nested `market` object while legacy fields remain. * Release validation covered current execution, full-redemption, and partial-reduction shapes. Docs: [Combo WebSocket events](/websocket/combos), [Combo Markets](/data/combos/markets), and [Combo Redemptions](/data/combos/redemptions) *** ## 2026-08-01 - Full core coverage in the TypeScript, Python, and Rust SDKs The three public SDKs now expose the same core V3 REST, Event WebSocket, Order Book, crypto, and perps surfaces with language-native types. What's new: * TypeScript `polynode-sdk` 0.12.0, Python `polynode` 0.12.0, and Rust `polynode` 0.15.0 cover all 120 V3 operations available at release. * Settlement subscriptions reconnect with their cursor and preserve raw unknown additive events, allowing forward-compatible consumers to inspect new event families. * PN1 Order Book helpers retain exact decimal values and expose integrity state for snapshot and delta handling. * Perps REST and WebSocket clients use the documented public perps endpoints. * The 0.12.2 TypeScript/Python and 0.15.2 Rust patch releases added optional condition IDs to event-search filters without breaking older callers. Docs: [TypeScript SDK](/sdks/ts/overview), [Python SDK](/sdks/python/overview), and [Rust SDK](/sdks/rust/overview) *** ## 2026-07-31 - Chainlink TWAP streams and August 7 cutover Affected Polymarket crypto up-or-down markets changed from a single snapshot-in-time price to a Chainlink-computed time-weighted average price. The values delivered by polynode are Chainlink prices; polynode does not calculate the TWAP. What's new: * Use `twap_windows: [30]`, `[60]`, or `[30, 60]` on the existing `chainlink` WebSocket subscription. * The published mapping uses the 30-second lookback for 5-minute markets and the 60-second lookback for 15-minute and 4-hour markets. * On August 7 at 00:00 UTC, the default `chainlink` subscription switched from spot to both TWAP windows alongside the resolution change. * Every price event includes additive `is_twap` and `twap_window_seconds` fields. Existing event fields, feed names, API keys, and subscription messages remain compatible. * Existing sockets did not need to reconnect or resubscribe at cutover. The order-book stream was unaffected. Docs: [Chainlink TWAP Prices](/crypto/twap) *** ## 2026-07-30 - Faster PolyUSD flows and P\&L leaderboards Improved high-volume V3 wallet and leaderboard requests without changing returned data, fields, ordering, filters, or pagination behavior. Release measurements: * A representative large-wallet `GET /v3/wallets/{address}/polyusd-flows` request improved from 8.29 seconds to 3.34 seconds. * A representative filtered `GET /v3/leaderboard` request improved from 10.0 seconds to 0.59 seconds. * A representative global top-100 leaderboard request improved from 7.17 seconds to 0.14 seconds. Docs: [Wallet PolyUSD Flows](/data/wallets/polyusd-flows), [Global Leaderboard](/data/leaderboard/global), and [Tag Leaderboard](/data/leaderboard/tag-leaderboard) *** ## 2026-07-29 - Faster V3 wallet-position pages Improved `GET /v3/wallets/{address}/positions` for wallets with long histories and deep result pages. Release measurements: * Representative pages improved from 18.36 seconds to 1.89 seconds, 6.24 seconds to 0.36 seconds, and 2.90 seconds to 0.54 seconds. * A representative deep request that previously timed out completed in 1.32 seconds. * In the post-release sample, the observed HTTP `504` rate fell from 2.69% to 0.23%, while successful requests had a 283-millisecond p95 response time. Fields, values, ordering, result counts, filters, and pagination remain compatible. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-07-28 - Broader wallet resolution and safer token-price responses Existing wallet and token lookup endpoints now handle two previously incomplete edge cases without changing their response contracts. What's improved: * `GET /v1/resolve/{query}` can resolve the controlling EOA for older proxy wallet addresses, including the associated username when available. * `GET /v3/tokens/{token_id}` and `GET /v3/markets/{token_id}/price` return the established numeric `0` price instead of HTTP `502` when a token exists but no current price has been established. * Existing fields, API-key behavior, and not-found responses remain compatible. Docs: [Resolve Wallet](/api-reference/wallets/resolve), [Token Info](/data/tokens/info), and [Token Price](/data/markets/price) *** ## 2026-07-28 - Clearer account onboarding The signed-in account flow now lets a customer identify the account as an individual or company, with a visible option to defer the choice. The public site also presents Enterprise/Institutional access through the contact path and includes a stability fix for the landing page on iOS Safari. Existing accounts, API keys, plans, and authentication remain unchanged. *** ## 2026-07-27 - Complete wallet redemptions with transaction hashes `GET /v3/wallets/{address}/redemptions` now returns redemptions attributed to the wallet across direct, negative-risk, and AutoRedeemer execution paths. What's new: * Direct and AutoRedeemer redemptions are merged across available history before pagination. * Every row includes `transaction_hash`, `block_number`, and `log_index` for exact onchain event identification. * `redemption_source` distinguishes direct, negative-risk, binary, and combo sources while `source_event` preserves the protocol event family. * AutoRedeemer activity is attributed to the beneficiary wallet rather than the protocol contract. * `order=asc|desc`, `next_offset`, and deterministic cross-source pagination are explicit in the response contract. Docs: [Wallet Redemptions](/data/wallets/redemptions) *** ## 2026-07-27 - New order-book markets without reconnecting Newly available markets are now added to the live Order Book service without requiring a service restart or client reconnect. Subscription messages, PN1 frames, sequence rules, API keys, and existing market behavior remain unchanged. Docs: [Order Book overview](/orderbook/overview) # Changelog - July 6-12, 2026 Source: https://docs.polynode.dev/changelog-july-6-12-2026 Archived PolyNode API, identity, credits, perps, orderbook, and data-quality changes from July 6 through July 12, 2026. [← Back to the current changelog](/changelog) [Newer: July 13-19, 2026 ←](/changelog-july-13-19-2026) · [Earlier: June 29-July 5, 2026 →](/changelog-june-29-july-5-2026) ## 2026-07-12 - Event-scoped trades and dollar-size filtering Trade feeds can now be scoped to a whole Polymarket event and filtered by dollar size. What's new: * `event_slug` and `event_id` filters on `GET /v3/trades` and `GET /v3/wallets/{address}/trades`: one call returns trades across every market in an event, with pagination. Builder trades gain `event_id` alongside the existing `event_slug`. * `min_amount_usd` on global, market, market-slug, wallet, and builder trades: a dollar floor that matches the `amount_usd` field already present in every trade row. `?min_amount_usd=100` means "show me \$100+ trades". Decimals are accepted. The raw `min_amount` filter keeps working; `min_amount_usd` is the recommended one. * Trade rows across all trades endpoints are now enriched with `event_slug` and `event_id`, so any feed can be grouped by event client-side. * `condition_id` and `market_slug` filters on global trades are now documented for market-scoped feeds across all outcomes. * An event filter that matches nothing returns an empty page rather than falling back to unfiltered results, and invalid values return `400`. Docs: [Global Trades](/data/global/trades), [Wallet Trades](/data/wallets/trades), and [Builder Trades](/data/builders/trades) *** ## 2026-07-12 - Faster wallet activity and builder statistics Improved two aggregation-heavy V3 read paths without changing their request or response contracts. Release measurements: * Representative `GET /v3/wallets/{address}/activity` requests improved from 1.013 seconds to 51 ms and from 1.607 seconds to 26 ms. * A redemption-heavy wallet request that had previously timed out returned `200` in 16 ms. * A large `GET /v3/builders/{code}` statistics request improved from 131.7 seconds to 2.72 seconds. * Before-and-after checks returned the same row sets, values, timestamp ordering, and builder aggregates. These are measured examples, not latency guarantees. Field names, event values, pagination, and endpoint limits are unchanged. Docs: [Wallet Activity](/data/wallets/activity) and [Builder Detail](/data/builders/detail) *** ## 2026-07-11 - Credits API for rewards, yield, rebates, and referrals Added a complete indexed history of the five ways Polymarket pays users: liquidity rewards, yield, maker rebates, taker rebates, and referral rewards. Wallet routes: * `GET /v3/wallets/{address}/credits/totals` returns per-program totals for all time or a `start_ts`/`end_ts` window. * `GET /v3/wallets/{address}/credits` returns individual payouts with program, time, amount, token, and transaction context. It supports time and amount filters plus time- or amount-based sorting. * `GET /v3/wallets/{address}/credits/series` returns chart-ready earnings buckets. Use `interval=hour|day|week|month` and `fill=zero` when a continuous series is needed. Global routes: * `GET /v3/credits/leaderboard` ranks recipients by one program or combined credits over `24h`, `7d`, `30d`, all time, or an explicit window. * `GET /v3/credits/stats` returns program-wide totals and time series. * `GET /v3/credits/events` is a cursor-paginated global payout feed; `min_amount` can turn it into a large-credit monitor. * `GET /v3/credits/recipients/stats` shows new earning wallets per time bucket. * `GET /v3/credits/distributors` lists the public payout addresses and their totals. * `GET /v3/credits/txs/{hash}` decodes one payout transaction into its typed recipient-and-amount breakdown. Use `reward`, `yield`, `maker_rebate`, `taker_rebate`, and `referral_reward` in `type` or `types`; `types` accepts a comma-separated set or `all`. The history begins with each program's first on-chain payout, and newly confirmed credits normally become queryable within about a minute. The dataset includes the program batches visible in Polymarket's activity feed plus direct distributor payments that the feed omits. Transfers between payout-system addresses are excluded from aggregate surfaces. All payout amounts are dollar values; the `token` field distinguishes the settlement token. For global stats, `unique_recipients` is exact on all-time requests and `null` when a custom time window is supplied. Hourly stats require a window of seven days or less. Docs: [Credits Overview](/credits/overview), [Wallet Credit Totals](/credits/wallet-totals), [Credits Leaderboard](/credits/leaderboard), [Global Credit Stats](/credits/stats), and [Global Credit Feed](/credits/feed) *** ## 2026-07-11 - Batch identity resolution, username search, and identity-enriched credits Added three V3 identity routes for turning Polymarket wallet activity into account-level context: * `POST /v3/identities/batch` resolves up to 1,000 trading wallets per call. Unknown wallets return `null` instead of failing the whole request. * `GET /v3/identities/search?q=...` searches more than five million known Polymarket usernames, supports partial matches, and ranks exact matches first. * `GET /v3/identities/{address}` works in both directions: a trading wallet returns its username, controlling EOA, wallet type, and related wallets; an EOA returns the Polymarket wallets it controls. Credits responses are enriched at the same time: events include `username`; leaderboard rows include `username`, `eoa`, and `wallet_type`; wallet totals include an `identity` block and `other_wallets`. Fields remain `null` when an identity is unknown. The batch and search routes use the identity catalog refreshed daily. For a brand-new wallet that may not be in that catalog yet, `GET /v1/resolve/{query}` remains the deeper single-identity lookup. Docs: [Batch Resolve](/identities/batch-resolve), [Username Search](/identities/search), and [Identity Lookup](/identities/lookup) *** ## 2026-07-11 - Current all-time wallet P\&L at request time Strengthened current P\&L responses so a recently sold, resolved, or repriced position cannot leave an all-time wallet result behind the latest wallet state. What's improved: * An unwindowed `GET /v3/wallets/{address}/pnl` now computes against the current wallet state, including requests with market metadata filters. * The no-window summary returned by `GET /v3/wallets/{address}/pnl/events` uses the same current accounting. * A wallet that fully sold a position before resolution is no longer credited as though it held the winning outcome through settlement. * If the exact read cannot complete for an unusually large wallet, an unfiltered all-time request can use a certified current result only when it is complete and fully valued. Otherwise the API returns an unavailable response rather than stale P\&L. * Response field names and numeric types are unchanged. Time-windowed P\&L, leaderboards, block/transaction lookups, and combo routing keep their existing behavior. Docs: [Wallet P\&L](/data/wallets/pnl) and [Wallet P\&L Time Series](/data/wallets/pnl-events) *** ## 2026-07-11 - Perps API consistency and coverage pass A hardening pass across the whole perps surface, based on an external-style audit of the docs and live API. What's new: * `perps_klines` WebSocket events now carry exactly one flat candle (`[open_time, open, high, low, close, volume, trade_count]`) and are sent only when the candle's contents change. Empty and duplicate events are gone. * `perps_statistics` events are sent per instrument only when the statistics change, substantially reducing idle bandwidth. * WebSocket authentication failures are now visible: the connection opens, delivers one error frame, and closes with code `4401` for a bad or missing key or `4429` for a connection-limit failure instead of an unexplained disconnect. * `GET /v3/perps/funding/{instrument}` now accepts `after`/`before` in seconds or milliseconds like the other series endpoints, honors `limit`, and includes `instrument_id` and `symbol`. `start_timestamp`/`end_timestamp` keep working. * Klines responses now include `instrument_id` and `symbol`; `/limit-tiers` and `/assets` return the standard `{"data": [...]}` wrapper. * Timestamp field names are unified: `timestamp` for event/sample times and `as_of` for snapshot freshness. * Derived values such as aggregates, notionals, basis, and CVD are normalized to clean decimals; exchange-reported values retain their native precision. * Unknown query parameters now return `400` with the accepted parameter names, so a misspelled filter cannot silently return unfiltered data. * Transient upstream congestion returns `503` with a `Retry-After` header instead of a misleading `429`. * Newly activated accounts now enter position coverage on the next normal collection cadence instead of waiting for a long full pass. Coverage drift also triggers a faster complete refresh. All listed instruments measured 99.6-100.0% in the post-release validation window; that measurement is not a coverage SLA. * Docs now include real response examples, automatic wallet resolution, clarified book/kline streaming semantics, and explicit sort order on every series endpoint. Docs: [Perps Overview](/perps/overview), [WebSocket Channels](/perps/websocket/channels), [Funding History](/perps/market-data/funding), and [Coverage](/perps/analytics/coverage) *** ## 2026-07-10 - Exact wallet-position accounting and fractional resolutions Corrected `GET /v3/wallets/{address}/positions` for several lifecycle cases where balance, cost accounting, resolution, and pagination could disagree. What's improved: * A position sold completely before market resolution now keeps its actual sale P\&L instead of being valued as though the wallet held the winning outcome through resolution. * Position accounting is brought current before applying cost-sensitive sorts or lifecycle pagination, so deep pages cannot mix a current balance with older cost values. * Positions present in wallet activity but temporarily absent from one response source are still returned when their current state can be established, without producing duplicate rows. * `status=open|closed|redeemable|redeemed` is classified before pagination using current market and payout state, making status pages consistent across offsets. * Resolved positions now honor the complete Conditional Tokens payout. Invalid, cancelled, or otherwise fractional resolutions use the actual payout fraction rather than assuming every result is exactly 0 or 1. * For a fractional payout, `won` is `null` while price, value, and realized P\&L use the payout fraction. Ordinary binary winners and losers retain their existing `true`/`false` values. * Wallet-position envelopes now include additive `next_offset`; the endpoint continues to cap a page at 300 rows and reports the applied `limit`. No request parameter or existing field name changed. A small displayed average-price difference can still remain when PolyNode and Polymarket use different historical cost-basis conventions; that difference does not change the terminal outcome or redeemable payout. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-07-10 - Perps wallet resolution and position-state correctness Improved account lookup and historical position behavior across the perps wallet and analytics routes. What's improved: * Every perps wallet route can now resolve email/social-login proxy wallets to their controlling account automatically, alongside plain EOAs, deposit wallets, and Gnosis Safes. * A proxy not yet known to the resolver returns a repeatable `422` with guidance to pass the signer directly; repeated lookup no longer risks a server error. * Current positions, size/P\&L leaderboards, large-position queries, and coverage now use the latest complete wallet observation. A complete empty portfolio closes prior positions instead of leaving stale rows marked open. * Position-change events use stable timestamp-and-ID ordering and a deterministic identity, preventing duplicate close/reopen transitions in historical pagination. * Liquidation and position-event feeds ignore incomplete predecessor observations rather than manufacturing a transition from partial data. Docs: [Wallet Mapping](/perps/wallet-mapping), [Wallet Overview](/perps/wallets/overview), [Position History](/perps/analytics/position-history), and [Position Events](/perps/analytics/events) *** ## 2026-07-09 - Polymarket perps API Full market and account data coverage for Polymarket perpetual futures is now available under the same `/v3` surface and API keys as the rest of PolyNode. What's new: * Live market data for every listed perps instrument: tickers, orderbooks, best bid/offer, trades, 24-hour statistics, klines, funding, and a cross-instrument screener. * PolyNode-exclusive history the exchange does not serve: trade archive with server-side filters, open interest, volume, basis, trade-flow/CVD, and cumulative funding series. * Wallet endpoints with automatic address resolution: pass a Polymarket profile address or the underlying account address, singly or in a batch. * Cross-account analytics: whale leaderboard, smart money, positioning, large positions, position history, position events, liquidations, and a coverage transparency metric. * On-chain collateral data: TVL, deposits, withdrawals, top depositors/withdrawers, and per-wallet flows. * WebSocket streaming at `wss://perps.polynode.dev/ws`: tickers, statistics, BBO, books, trades, and klines over one connection. Docs: [Perps Overview](/perps/overview), [Quickstart](/perps/quickstart), and [Perps WebSocket](/perps/websocket/overview) *** ## 2026-07-09 - Multi-wallet context in `/resolve` Expanded `GET /v1/resolve/{query}` so one lookup can return every deployed Polymarket wallet associated with the account. What's new: * The additive `wallets` object contains `deposit_wallet`, `safe`, and `proxy_wallet`, each set to its deployed address or `null`. * Queries can still start from a trading wallet, controlling EOA, or case-insensitive username. * Both standalone and upgradeable deposit-wallet variants are recognized and reported as `type: "deposit_wallet"`; callers do not need to distinguish "deposit" from "beacon" wallet naming. * If an account has a deployed deposit wallet, the legacy top-level `safe` field continues to return that preferred trading wallet. Otherwise it falls back to the existing Safe or proxy wallet. * Existing `safe`, `eoa`, `username`, and `type` fields remain backward compatible. `eoa` is populated for proxy wallets whenever the owner can be recovered and remains `null` in the rare unresolved case. Docs: [Resolve Wallet](/api-reference/wallets/resolve) *** ## 2026-07-09 - Connection-preserving Orderbook Stream releases Orderbook Stream releases can now move new traffic to an updated version without disconnecting established WebSocket clients. What's improved: * Existing connections to `wss://ob.polynode.dev/ws` can continue naturally while new connections move to the updated service. * The updated stream must be warm and return matching subscription behavior before it receives new connections. * REST fallback follows the same active target as the WebSocket stream, avoiding stale routing after a release. * A brief burst of `502` responses from the REST fallback after the first transition was corrected the same day. Later failures return a controlled unavailable response instead of an abrupt empty connection. The first complete release cycle preserved all 33 established public connections through the transition and drain. That was a rollout measurement, not a connection-count or uptime guarantee. Docs: [Orderbook Stream](/orderbook/overview) *** ## 2026-07-06 - Visible activity and resolution times on wallet positions Added the timestamps and resolution context needed to display and verify recent closed, redeemed, and redeemable positions. What's improved on `GET /v3/wallets/{address}/positions`: * `resolved_at` is populated from current market resolution metadata with a historical fallback. At release, 99.8% of closed markets had a known resolution time. * New additive field `last_activity_at` exposes the time of the position's latest on-chain balance activity, including redemption or settlement activity. It is available even when no direct wallet redemption event exists. * `last_trade_at` now exposes the most recent fill time for the position's token. * `winning_outcome_index` is populated when the market's payout is known. * `include_combos=true` rows gain `last_update_block` and `last_activity_at` for the same client-side recency workflow. `sort=recent` already ordered rows by their latest balance-activity block and was not changed. The new `last_activity_at` field makes that ordering visible to clients instead of forcing them to treat missing timestamps as zero. Open positions continue to return `resolved_at: null` until resolution. Docs: [Wallet Positions](/data/wallets/positions) *** ## 2026-07-06 - Paid-plan REST limits standardized Aligned paid-plan REST provisioning and published limits so new and existing keys receive the same documented allowance: * Starter: 1,000 requests per minute. * Growth: 2,000 requests per minute. * Enterprise: 4,000 requests per minute by default, with custom capacity by agreement. Requests above the allowance return `429 Too Many Requests` with a retry time. WebSocket connections are not counted as REST requests and keep their separate plan limits. This entry records the plan allowances introduced on July 6. They were initially enforced per API key; the July 17 release changed V3 REST sharing to one allowance per account without changing the numeric plan limits. Docs: [Rate Limits](/guides/rate-limits) # Changelog - June 1-7, 2026 Source: https://docs.polynode.dev/changelog-june-1-7-2026 Archived polynode API and WebSocket changes from June 1 through June 7, 2026. [← Back to the current changelog](/changelog) [Newer: June 8-14, 2026 ←](/changelog-june-8-14-2026) [Earlier: May 25-31, 2026 →](/changelog-may-25-31-2026) ## 2026-06-07 - Fresher short-form crypto candles and window prices Short-form crypto candles and price-to-beat responses now follow the same live Chainlink price stream used by polynode's 1-second tick history. What's improved: * `GET /v1/crypto/candles` returns approximately 30 five-minute OHLC candles, covering about 2.5 hours. * Candle responses refresh about every 5 seconds instead of every 30 seconds. * `symbol` accepts both bare asset symbols such as `BTC` and feed names such as `BTC/USD`. * `GET /v1/crypto/price` uses the live tick history for market-window opening prices and completed closing prices when that history is available. * Existing price response fields and completed/incomplete flags remain compatible. Supported assets remain `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, and `HYPE`. Docs: [Oracle Candles](/api-reference/crypto/candles) and [Price to Beat](/api-reference/crypto/price) *** ## 2026-06-06 - Outcome-enriched redemption WebSocket events Redemption events can now identify the resolved outcome directly, without requiring a separate market lookup. New additive fields, when resolution metadata is available: * `token_ids`: ordered token IDs for the market * `outcomes`: ordered outcome labels * `payouts`: ordered payout numerators * `outcome_prices`: normalized payout values, including fractional split outcomes * `winning_outcome_index`, `winning_outcome`, and `winning_token_id` when exactly one outcome has a non-zero payout Wallet attribution is also corrected for redemptions routed through Polymarket protocol contracts, so wallet-filtered subscriptions identify the actual user wallet rather than an intermediate contract. Existing redemption fields are unchanged. If resolution metadata is unavailable, the new enrichment fields are omitted rather than populated with guessed values. Docs: [Redemption Event](/websocket/events/redemption) *** ## 2026-06-04 - `/resolve` prefers deployed deposit wallets `GET /v1/resolve/{query}` keeps the same response fields: `safe`, `eoa`, `username`, and `type`. The legacy `safe` field now means the preferred Polymarket trading wallet. If the resolved EOA has a deployed deposit wallet, `safe` is that deposit wallet and `type` is `"deposit_wallet"`. If no deposit wallet is deployed, `safe` falls back to the existing Safe or proxy wallet. This applies to address, EOA, and cached username lookups. No request change is required. Docs: [Resolve Wallet](/api-reference/wallets/resolve) *** ## 2026-06-03 - Historical 1-second crypto price ticks Added `GET /v1/crypto/ticks` for chart backfill using the same crypto price events delivered by the `price_feed` WebSocket stream. Request contract: * Required `symbol`: `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, or `HYPE` * Required `from` and `to` as Unix timestamps in milliseconds * Optional `limit`, default `10,000` and maximum `100,000` * Maximum range of 24 hours per request Responses include `count`, `truncated`, and ordered `ticks`. Each tick includes a replay-safe `id`, `timestamp_ms`, and the same Chainlink feed, price, bid, ask, and timestamp values used by the live stream. If `truncated` is `true`, narrow the time range or increase the limit. Ranges before collection began return an empty `ticks` array. Docs: [Historical Price Ticks](/api-reference/crypto/ticks) *** ## 2026-06-03 - V2 onchain API service restored Restored the shared `/v2/onchain/*` serving path after requests began returning `502`, including tags, trades, and both wallet-position route forms. After recovery, the affected routes returned normal `200` responses again with their existing request and response formats. No API-key or client change was required. Large uncached V2 wallet-position histories could still take tens of seconds at this point in the release history. For bounded reads, prefer the paginated `GET /v2/onchain/positions?wallet=...` route and request only the page size needed. # Changelog - June 15-21, 2026 Source: https://docs.polynode.dev/changelog-june-15-21-2026 Archived PolyNode API, WebSocket, and documentation changes from June 15 through June 21, 2026. [← Back to the current changelog](/changelog) [Newer: June 22-28, 2026 ←](/changelog-june-22-28-2026) · [Earlier: June 8-14, 2026 →](/changelog-june-8-14-2026) ## 2026-06-19 - WebSocket fan-out capacity and settlement latency guidance Expanded public WebSocket delivery capacity for heavily subscribed event streams and clarified the best subscription shape for latency-sensitive settlement consumers. What's improved: * High-volume streams have more delivery headroom, improving resilience when many subscriptions are active at once. * No event names, payload fields, filter syntax, or subscription messages changed. * For the lowest settlement latency, use a dedicated `type: "settlements"` subscription. The broader `type: "trades"` preset intentionally multiplexes `settlement`, `trade`, and `status_update` events; preserving per-connection order can place a settlement behind other frames during a burst. * Initial `type: "snapshot"` messages contain historical state and should be excluded when measuring live `detected_at`-to-receive latency. In one post-release live-only validation window, a dedicated settlement subscription delivered 592 unique pending transactions at p50 `1ms`, p90 `4ms`, p99 `11ms`, and max `50ms`, with no samples above `100ms`. These measurements describe that validation window, not a latency SLA. Docs: [WebSocket Overview](/websocket/overview) and [Settlement Event](/websocket/events/settlement) *** ## 2026-06-17 - 62-page V3 Query Catalog Published an intent-based Query Catalog so developers can start from the result they need instead of first finding the underlying endpoint. The catalog includes category guides and granular copy-ready recipes for: * Trades: global, wallet, market-token, market-slug, builder-attributed, grouped-order, condition, and combo trade queries. * Positions: wallet, open-wallet, global, token-holder, condition-holder, market-slug, and combo position queries. * P\&L: all-time and time-window wallet P\&L, market/tag breakdowns, event history, batch reads, and leaderboards. * Markets: search, condition and slug lookup, token details, prices, tags, resolutions, and candles. * Wallet activity: unified activity, splits, merges, redemptions, negative-risk conversions, PolyUSD flows, fees, rebates, and rewards. * Builders, combos, fees, tags, and categories, including additive `include_combos=true` query shapes. The endpoint reference remains the source for complete parameter and response schemas; the Query Catalog is the shortest path to a working request for a specific product use case. Docs: [V3 Query Catalog](/data/query-catalog/overview) *** ## 2026-06-17 - Fee, rebate, and reward data guide Published a dedicated Fees section that distinguishes the API's accounting surfaces and points each question to the correct endpoint. Documented query paths: * Exact all-time trader-paid fees: `GET /v3/wallets/{address}?include_accounting_summary=true`. * Fee-bearing wallet fills: `GET /v3/wallets/{address}/fees-paid`. * Global and receiver-scoped fee events: `GET /v3/fees` and `GET /v3/fees/{receiver}`. * Builder fee ranking and underlying attributed fills: `GET /v3/builders?sort=fees` and `GET /v3/builders/{code}/trades`. * Maker rebates: `GET /v3/wallets/{address}/rebates`. * Public reward-market configuration: `GET /v3/rewards/markets` and `GET /v3/rewards/markets/{condition_id}`. Important conventions are now explicit: * `page_total_fees_paid` is scoped to the returned page; use the opt-in wallet accounting summary for the exact all-time total. * Fee-event raw amounts use six-decimal USDC units. * Builder `total_fees` means protocol fees generated by attributed fills, not an off-chain builder revenue-share payout. * Maker rebate lookups use the CLOB maker/signing address, and reward-market configuration is not a per-wallet earned-rewards ledger. Docs: [Fees Overview](/data/fees/overview) *** ## 2026-06-17 - Full V3 market-candles reference Published the complete public reference for trade-built V3 OHLCV candles across token, condition, and market-slug lookups. Documented routes: ```http theme={null} GET /v3/markets/{token_id}/candles GET /v3/markets/condition/{condition_id}/candles GET /v3/markets/slug/{slug}/candles ``` The reference covers: * Resolutions `1m`, `5m`, `15m`, `1h`, `4h`, and `1d`, with maximum request sizes of 120, 180, 240, 300, 360, and 500 candle buckets respectively. * Forward and backward windows with `direction`, `anchor_ts`, `start`, and `end`; timestamp parameters use Unix seconds. * Backward history pagination through `pagination.older_end_ts`. * Optional `gap_fill=true` carry-forward candles after a prior price exists. * Token routes returning one `candles` series, while condition and slug routes return one `series` entry per outcome token. Use `token_id` to select one outcome from a condition or slug. * OHLC, USD/share/buy/sell volume, trade count, VWAP, millisecond chart timestamps, and first/last fill timestamps. Docs: [Market Candles](/data/markets/candles) *** ## 2026-06-15 - PM2 AutoRedeemer redemptions in WebSocket streams PM2 AutoRedeemer redemptions are now surfaced in both the combo stream and the standard redemption stream. What's new: * AutoRedeemer `Redemption`, `BinaryRedemption`, and `NegRiskRedemption` logs emit customer-facing `combo_lifecycle` events with the wallet, exact raw payout, normalized payout, module name, and receipt log index. Binary and negative-risk redemptions also include the condition ID directly. * Confirmed `combo_status_update` messages can include `lifecycle_events[]` for receipt-only AutoRedeemer lifecycle activity. * The same AutoRedeemer payout is also bridged into the standard `redemption` event class, attributed to the user wallet instead of the AutoRedeemer contract. * New `type: "redemptions"` WebSocket preset subscribes directly to `redemption` events. Existing `settlements` or `wallets` subscriptions with `event_types: ["redemption"]` continue to work. No subscription change is required for existing redemption consumers. # Changelog - June 22-28, 2026 Source: https://docs.polynode.dev/changelog-june-22-28-2026 Archived PolyNode API, WebSocket, Explorer, and documentation changes from June 22 through June 28, 2026. [← Back to the current changelog](/changelog) [Newer: June 29-July 5, 2026 ←](/changelog-june-29-july-5-2026) · [Earlier: June 15-21, 2026 →](/changelog-june-15-21-2026) ## 2026-06-25 - More complete winner metadata on redemption streams Improved the availability and durability of resolution metadata used to enrich live redemption events. What's improved: * Redemption conditions missing winner context are now recovered continuously without delaying event delivery, reducing the chance that later events for the same condition arrive without `payouts` or winner fields. * Newly resolved conditions are picked up continuously, and known resolution data is retained for future redemptions, including redemptions that occur long after resolution. * The improvement targets rare enrichment misses without delaying or suppressing the underlying redemption event. * Frames that were already emitted are not rewritten; the repair benefits subsequent live events for the condition. * No subscription messages, event names, filters, or payload field names changed. In the initial live-only baseline, 249 of 250 redemption events were fully enriched and one was missing resolution context. The missing condition was resolved by the new recovery path during validation. These measurements describe that validation window, not a coverage SLA. Docs: [Redemption Event](/websocket/events/redemption) *** ## 2026-06-24 - Builder volume normalization and Explorer correction Clarified builder-volume semantics across `GET /v3/builders`, `GET /v3/builders/{code}`, and the Explorer Builder Leaderboard. What's new in the V3 builder responses: * Side-aware local volume fields: `volume_e6`, `volume_usdc`, `buy_volume_e6`, `buy_volume_usdc`, `sell_volume_e6`, and `sell_volume_usdc`. * Decimal-USDC companions for the legacy raw totals: `total_maker_volume_usdc`, `total_taker_volume_usdc`, and `total_fees_usdc`. * Public profile context: `external_rank`, `external_volume`, and `external_active_users`. * Data-state fields: `stats_refreshed_at`, `stats_checked_at`, and `stats_pending`, with source labels on the list and detail responses. Builder detail also exposes `stats_source`. Field conventions: * Prefer `volume_usdc` when displaying a builder's PolyNode-attributed volume. It selects the collateral side of each fill and normalizes six-decimal units. * `external_volume` is the separate value from Polymarket's public builder leaderboard; it is not substituted for PolyNode's local fill volume. * Legacy `total_maker_volume`, `total_taker_volume`, and `total_fees` remain available as raw six-decimal values for compatibility. * `unique_makers` and `unique_takers` were removed because they did not represent supported exact distinct-wallet counts. `sort=makers` and `sort=takers` now return `400`; supported list sorts are `fills`, `volume`, and `fees`. The Explorer Builder Leaderboard now uses `volume_usdc` and scales legacy raw amounts correctly. This fixes displays that were previously up to `1,000,000x` too large because raw six-decimal values were being labeled as whole USDC. Docs: [Builder Leaderboard](/data/builders/list) and [Builder Detail](/data/builders/detail) *** ## 2026-06-24 - V3 wallet redemptions enriched with market and winner context Expanded `GET /v3/wallets/{address}/redemptions` so a redemption row can identify the market, payout, and winning outcome without a second market lookup. New additive fields include: * Accounting-safe payout aliases: `condition_id`, `payout_e6`, and `payout_usdc`. * Market context: `market_title`, `market_slug`, `market_image`, `event_title`, `event_slug`, and `neg_risk`. * Ordered outcome context: `token_ids`, `outcomes`, `payouts`, and `outcome_prices`. * Resolution context: `winning_outcome_index`, `winning_outcome`, `winning_token_id`, and `resolved_at`. The array fields use the same outcome order. Resolution and market fields are nullable when the corresponding metadata is unavailable. Existing fields — `id`, `timestamp`, `condition`, `payout`, and `index_sets` — remain present and unchanged. Docs: [Wallet Redemptions](/data/wallets/redemptions) *** ## 2026-06-24 - Redemption WebSocket winner fields restored Restored resolution enrichment on customer-facing WebSocket redemption events. What's restored when resolution context is available: * `payouts` and `outcome_prices`. * `winning_outcome_index`, `winning_outcome`, and `winning_token_id`. * The same enrichment behavior across direct `type: "redemptions"` subscriptions, wallet-filtered redemption subscriptions, and `type: "settlements"` subscriptions using `event_types: ["redemption"]`. Delivery remains unconditional: a redemption is still sent when winner metadata is not yet available, and the enrichment fields remain best-effort rather than blocking the frame. No subscription change is required. In one warmed post-release validation window, 98 of 100 live redemption events included a payout vector, and the documented settlements-plus-redemption subscription returned 5 of 5 enriched events. These measurements describe that validation window, not a coverage SLA. Docs: [Redemption Event](/websocket/events/redemption) *** ## 2026-06-22 - V3 wallet accounting summary Added an optional all-time accounting summary to the V3 wallet summary endpoint. What's new: * `GET /v3/wallets/{address}?include_accounting_summary=true` returns `accounting_summary`. * `accounting_summary.fees_paid.amount` is the exact all-time trader-paid fee total, while `fees_paid.raw` exposes the exact six-decimal value. * `fee_fill_count` and `order_owner_fill_count` expose the fee-bearing and total order-owner fill counts covered by the summary. * `order_filled_through_block` and `projector_status` describe the summary's coverage and readiness. * Maker rebates and rewards have explicit status fields. `not_loaded` means the source is unavailable and must not be interpreted as a zero amount. Existing default responses are unchanged. The accounting object is included only when requested. Docs: [Wallet Summary](/data/wallets/summary) and [Fees Overview](/data/fees/overview) *** ## 2026-06-22 - Wallet P\&L and leaderboard filters clarified Completed the production handoff for time-windowed wallet P\&L requests using `period` or `after`, while preserving the all-time wallet P\&L response and the rest of the V3 surface. The public P\&L references now make the filtering contract explicit: * Without a time parameter, `GET /v3/wallets/{address}/pnl` returns all-time P\&L. `period`, `after`, and `before` select a realized-P\&L time window; `include_unrealized=true` adds current unrealized P\&L to a time-filtered result. * Wallet P\&L supports `category`, `tags`/`tag_slug`, `market`/`market_slug`, `event_slug`, and `condition_id` filters. * All-time `wins` and `losses` are position counts. Time-windowed `wins`, `losses`, and `events` are realized-P\&L event counts, so the two modes should not be compared as identical counters. * `GET /v3/leaderboard` supports the same primary market dimensions. Use one primary dimension per request. * For broad tags or categories such as `crypto`, `sports`, or `politics`, use `GET /v3/leaderboard?tags=...` or `?category=...`; the direct `/v3/tags/{slug}/leaderboard` route is intended for narrower tags. Docs: [Wallet P\&L](/data/wallets/pnl), [Global Leaderboard](/data/leaderboard/global), and [Tag Leaderboard](/data/leaderboard/tag-leaderboard) # Changelog - June 29-July 5, 2026 Source: https://docs.polynode.dev/changelog-june-29-july-5-2026 Archived polynode API and data-quality changes from June 29 through July 5, 2026. [← Back to the current changelog](/changelog) [Newer: July 6-12, 2026 ←](/changelog-july-6-12-2026) · [Earlier: June 22-28, 2026 →](/changelog-june-22-28-2026) ## 2026-06-30 - Corrected resolved-position accounting and redeemable status Corrected `GET /v3/wallets/{address}/positions` for resolved positions that still held a nonzero balance but had incomplete cost accounting. What's improved: * When a position has a known balance but its returned cost fields are incomplete, the response now recovers `avg_price`, `initial_value`, `total_bought`, `realized_pnl`, `unrealized_pnl`, and `total_pnl` from the available wallet history. * Resolved positions with a remaining balance now use `status: "redeemable"` for both winning and losing outcomes. A losing position remains `won: false` and correctly returns `redeemable_payout: 0`. * `status=closed` no longer captures these affected resolved-but-unredeemed balances, so `status=redeemable` returns both winning and losing resolved balances under the same lifecycle filter. * Market-holder responses use the same recovered cost basis on `GET /v3/markets/{token_id}/positions`, `GET /v3/markets/condition/{condition_id}/positions`, and `GET /v3/markets/slug/{slug}/positions`. * Positions whose accounting was already complete keep their existing values. No parameter, pagination, or field-name change is required for existing clients. The correction removes null or zero accounting caused by an incomplete position row. Small differences from Polymarket's displayed `avgPrice` can still occur when the two systems use different cost-basis conventions; those differences do not change the resolved outcome or redeemable payout. Docs: [Wallet Positions](/data/wallets/positions), [Token Holders](/data/markets/positions), [Condition Holders](/data/markets/condition-positions), and [Market Slug Lookup](/data/markets/by-slug) *** ## 2026-06-30 - More complete event and tag metadata on V3 positions Improved metadata completeness for historical and resolved position rows, especially child markets created beneath a live esports event. What's improved: * Incomplete rows can now gain `event_slug` and `tag_slugs` from their parent event when that context is available. * A missing `image` is recovered at the same time when the source provides one. * Closed and resolved child markets continue to be revisited, so historical position metadata can recover after the market leaves the current-event feed. * The correction is automatic. No new parameter or refresh workflow is required, and the response shape is unchanged. * Metadata fields remain nullable when the corresponding event context is unavailable from the source. The initial release restored complete event and tag context on the two reported examples, repaired 91 existing rows in those event families, and filled 162 additional incomplete rows in the first two broader recovery passes. Docs: [Wallet Positions](/data/wallets/positions) # Changelog - June 8-14, 2026 Source: https://docs.polynode.dev/changelog-june-8-14-2026 Archived PolyNode API, WebSocket, orderbook, and SDK changes from June 8 through June 14, 2026. [← Back to the current changelog](/changelog) [Newer: June 15-21, 2026 ←](/changelog-june-15-21-2026) · [Earlier: June 1-7, 2026 →](/changelog-june-1-7-2026) ## 2026-06-14 - V3 pagination and Orderbook Stream limits documented Expanded the public limit reference so clients can choose page sizes and WebSocket subscription shapes without relying on trial and error. The documented contract: * Most V3 list endpoints default to `limit=100` and clamp requests to a maximum of `300` rows per page. * `GET /v3/wallets/{address}/pnl/events` is the high-volume exception: it defaults to `5,000` buckets and allows up to `10,000`. * `GET /v3/markets/condition/{condition_id}/positions` allows up to `300` rows on Starter, `1,000` on Growth, and `2,000` on Enterprise. * Explicit Orderbook Stream lists are capped at `15,000` resolved token IDs per connection. Use `markets: ["*"]` for the dedicated all-market firehose path. * Plan upgrades increase concurrent Orderbook Stream connections: Free has `1`, Starter `10`, Growth `50`, and Enterprise is unlimited. The explicit-list cap remains per connection on every plan. * A `service_warming_up` Orderbook Stream error means market metadata is still loading after a restart; retry the subscription shortly. For deep trade-history walks, bounded `after` and `before` windows are preferred over very large offsets. Docs: [Rate Limits](/guides/rate-limits) and [Orderbook Stream Overview](/orderbook/overview) *** ## 2026-06-13 - Settlement WebSocket delivery and metadata hardening Pending settlement delivery no longer waits for an optional metadata refresh. This prevents a temporary metadata miss from dropping or delaying the transaction frame customers use for the pre-confirmation head start. What's improved: * Pending `settlement` events are delivered immediately after in-memory enrichment, even when an optional market field is temporarily unavailable. * Missing metadata is refreshed outside the delivery path for subsequent events, so a slow metadata provider cannot add latency to settlement fan-out. * Metadata completeness checks now cover `market_title`, `outcome`, `market_slug`, `condition_id`, `token_ids`, `outcomes`, `tokens`, and each trade's outcome label. * Confirmed `status_update` events use the same metadata checks and remain pairable to the pending event by `tx_hash`. * Subscription acknowledgements are sent before initial snapshot frames, giving raw WebSocket clients a deterministic subscribe lifecycle. No subscription format changed. Enrichment fields remain additive and may be omitted briefly during metadata warmup rather than blocking the core settlement event. Docs: [Settlement Event](/websocket/events/settlement) and [Status Update Event](/websocket/events/status-update) *** ## 2026-06-13 - Open-but-silent Orderbook Stream connections fixed Fixed a failure mode where an Orderbook Stream socket could remain open after its delivery path had ended, leaving the client connected but no longer receiving updates. What's improved: * Reconnects and resubscriptions now replace stale delivery state cleanly instead of reusing a connection that can no longer forward updates. * Large explicit subscriptions continue receiving batches after reconnect and resubscribe cycles. * Connections that cannot continue delivery are cleaned up instead of appearing healthy while silently stalled. * Existing message types, subscribe payloads, snapshots, and batch formats are unchanged. The TypeScript and Python SDKs released earlier in the week automatically replay active subscriptions after reconnect; raw clients should continue to reconnect and resubscribe when the socket actually closes. Docs: [Orderbook Stream Overview](/orderbook/overview) and [Orderbook Messages](/orderbook/messages) *** ## 2026-06-12 - Higher V3 REST limits Raised and standardized the public V3 data allowances across paid plans. New standard V3 limits: * Starter: `1,000` requests per minute * Growth: `2,000` requests per minute * Enterprise: `4,000` requests per minute by default, with custom capacity by agreement Heavy trade-history routes use a separate allowance because they scan the largest histories: * Starter: `1,000` requests per minute * Growth: `1,500` requests per minute * Enterprise: `1,500` requests per minute by default, with custom capacity by agreement The heavy group includes global, wallet, combo-wallet, market-token, market-slug, and builder trade-history routes. Requests must pass both the standard V3 allowance and the heavy-route allowance. Successful responses expose `x-ratelimit-limit`, `x-ratelimit-remaining`, and `x-ratelimit-reset`. Exceeded allowances return `429`; V3 data routes require a paid API key and return `402 Payment Required` for Free-tier keys. Event and Orderbook WebSocket limits are unchanged. Docs: [Rate Limits](/guides/rate-limits) *** ## 2026-06-12 - Combo redemption, resolution, and P\&L semantics Hardened combo position accounting after a combo resolves or is redeemed. What's improved: * Router, direct, and auto-redeemer paths are normalized into public `PositionRedeemed` activity with `side: "Redeem"`. * Redemption activity includes `payout_usdc` when available and reports the underlying module kind as `Combinatorial`, `Binary`, or `NegRisk`. * Fully redeemed winners return `RESOLVED_WIN`; fully redeemed losers return `RESOLVED_LOSS`. * Winning redemptions settle realized P\&L as payout minus weighted-average entry basis, with zero remaining open entry cost. * `entry_avg_price_usdc` remains the historical weighted-average entry price after a position closes instead of being cleared. * Resolved leg metadata can include `RESOLVED_WIN` / `RESOLVED_LOSS`, `leg_resolved_at`, and `leg_current_price`. These changes affect dedicated combo position/activity routes and the additive combo branches returned by `include_combos=true`. Docs: [Combo Overview](/data/combos/overview), [Wallet Combo Positions](/data/combos/wallet-positions), and [Wallet Combo Activity](/data/combos/wallet-activity) *** ## 2026-06-12 - Faster V3 builder trade time filters Improved reliability and latency for time-filtered builder trade lookups. What's improved: * `GET /v3/builders/{code}/trades?after=...` now returns consistently for high-volume builders instead of timing out on large builder histories. * `after` / `before` filters now work efficiently with broad `tag_slug` or `category` filters when a time bound is provided. * Time windows outside a builder's activity range return a normal empty response instead of an internal timeout. * Invalid millisecond timestamps now return a structured `400` with a hint to use Unix seconds. No response fields or pagination semantics changed. *** ## 2026-06-11 - Chainlink coverage for all seven crypto feeds Expanded the `price_feed` WebSocket and crypto history APIs to deliver fresh Chainlink prices for every supported asset. What's improved: * `BTC/USD`, `ETH/USD`, `SOL/USD`, `BNB/USD`, `XRP/USD`, `DOGE/USD`, and `HYPE/USD` now receive updates at approximately one tick per second. * Price events include real bid and ask values for all seven feeds. * An unfiltered `type: "chainlink"` subscription returns all seven feeds; use `filters.feeds` to select individual feeds. * `GET /v1/crypto/price`, `GET /v1/crypto/ticks`, and `GET /v1/crypto/candles` provide consistent Chainlink prices across the crypto API. * New five-minute and fifteen-minute windows receive their opening tick at the window boundary, avoiding the prior freshness delay. No WebSocket message shape or REST request format changed. Docs: [Price Feed Event](/websocket/events/price-feed), [Historical Price Ticks](/api-reference/crypto/ticks), [Oracle Candles](/api-reference/crypto/candles), and [Price to Beat](/api-reference/crypto/price) *** ## 2026-06-11 - Polymarket combos: V3 API and WebSocket event references Added public documentation for Polymarket combo / combinatorial position support. What's new: * New combo API group in the API Reference. * `GET /v3/combos/markets` for observed combo markets and legs. * `GET /v3/combos/activity` for combo lifecycle activity by market, condition, position, or wallet. * `GET /v3/wallets/{address}/combos/positions` for combo-only wallet positions. * `GET /v3/wallets/{address}/combos/trades` for combo-only wallet trades. * `GET /v3/wallets/{address}/combos/activity` for combo-only wallet lifecycle activity. * `GET /v3/wallets/{address}/combos/summary` for combo-only wallet P\&L summary. * `include_combos=true` on wallet summary, wallet P\&L, wallet positions, and wallet trades for additive standard + combo responses. * New WebSocket event reference pages for `combo_execution`, `combo_status_update`, `combo_lifecycle`, and `combo_approval`. Notes: * Existing wallet endpoints keep their default response behavior. Combo data is included only when explicitly requested or when using dedicated combo endpoints. * If a wallet has no combo exposure, `include_combos=true` returns a normal successful response with a zero combo contribution. *** ## 2026-06-09 - Deposit-wallet trading fixes in both SDKs Released `polynode-sdk@0.10.18` for TypeScript and `polynode==0.10.7` for Python. What's fixed: * `ensureReady()` / `ensure_ready()` now detects deployed Polymarket deposit wallets (`POLY_1271`) correctly. * V2 type-3 orders use the deposit wallet as both maker and signer, matching Polymarket's expected order payload. * Existing local credentials created with the previous wallet classification can be repaired by rerunning the SDK readiness method. Upgrade: ```bash theme={null} npm install polynode-sdk@0.10.18 ws pip install --upgrade polynode==0.10.7 ``` *** ## 2026-06-09 - Python SDK v0.10.6 WebSocket resilience Released `polynode==0.10.6` for Python WebSocket consumers. What's new: * Event-stream subscriptions preserve frames that arrive before the subscribe acknowledgement, so handlers attached immediately after `await ...send()` still receive initial snapshot/live events. * Default event WebSocket subscribe timeout is now 30s and configurable with `WsOptions(subscribe_timeout=...)`. * Orderbook `subscribe()` now resolves only after the server acknowledges the subscription, and rejects promptly on server errors, disconnects, or timeout. * Orderbook `unsubscribe(token_ids)` can remove a subset of tokens; `unsubscribe()` with no arguments remains the full unsubscribe behavior. * Added protocol regression tests for snapshot-before-ack, pending-subscribe errors, timeout handling, and partial unsubscribe behavior. Upgrade: ```bash theme={null} pip install --upgrade polynode==0.10.6 ``` *** ## 2026-06-09 - TypeScript SDK v0.10.17 WebSocket resilience Released `polynode-sdk@0.10.17` for Node/TypeScript WebSocket consumers. What's new: * Event-stream subscriptions preserve frames that arrive before the subscribe acknowledgement, so handlers attached immediately after `await subscribe(...).send()` still receive initial snapshot/live events. * Default WebSocket subscribe timeout is now 30s and configurable with `subscribeTimeoutMs`. * Orderbook `subscribe()` now resolves only after the server acknowledges the subscription. * Orderbook reconnects replay the active token list without replacing existing handlers. * Orderbook `unsubscribe(tokenIds)` can remove a subset of tokens; `unsubscribe()` with no arguments remains the full unsubscribe behavior. * Added SDK protocol tests and a live orderbook soak test for multi-token subscribe, partial unsubscribe/resubscribe, snapshots, live batches, protocol errors, unexpected unsubscribe frames, and disconnects. Upgrade: ```bash theme={null} npm install polynode-sdk@0.10.17 ws ``` *** ## 2026-06-08 - Atomic Orderbook Stream resubscriptions Orderbook resubscriptions now keep the last valid market set active until a replacement set resolves successfully. What's improved: * A transient unresolved slug, condition ID, or token list no longer clears the connection's working subscription. * An invalid replacement does not interrupt updates for the last valid token set. * Upstream reconnects and market-rotation churn are absorbed by PolyNode while the downstream WebSocket remains on one stable logical subscription. * Full-market and large watchlist traffic received broader throughput and backlog handling improvements, reducing stream stalls during bursts. * Plan connection caps are enforced consistently without changing the existing subscribe payload or event formats. Clients can continue using the existing `subscribe` and `unsubscribe` messages. For SDK consumers, the June 9 releases add acknowledgement-aware subscribe calls and automatic subscription replay after reconnect. Docs: [Orderbook Stream Overview](/orderbook/overview) # Changelog — March 15–26, 2026 Source: https://docs.polynode.dev/changelog-march-15-26-2026 Archived PolyNode API and SDK changes from March 15–26, 2026. [← Back to the current changelog](/changelog) ## 2026-03-26 ### API — Wallet Resolver New endpoint that instantly resolves any Polymarket wallet identity. Pass a proxy wallet address, EOA address, or username and get back all three. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/DTCahill" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0x0ecdd241ec1bc84a40b8142bebe65787aee97514", "eoa": "0xddd57cce99ca962fe23aa2da95b139f86a241459", "username": "DTCahill" } ``` Covers \~3 million Polymarket wallets and is updated daily. Lookups are sub-millisecond. Accepts any of the three identifiers as input: * `GET /v1/resolve/{safe_address}` — proxy wallet to EOA + username * `GET /v1/resolve/{eoa_address}` — EOA to proxy wallet + username * `GET /v1/resolve/{username}` — username to both addresses (case-insensitive) See the [full documentation](/api-reference/wallets/resolve) for details. *** ### API — `order_hash` on Settlements and Trades Every settlement trade and confirmed trade event now includes an `order_hash` field — the EIP-712 hash that uniquely identifies a limit order on Polymarket's order book. **Why this matters:** A single limit order can be partially filled across multiple transactions. The `order_hash` stays the same across all of them, letting you track order lifecycle, group partial fills, and build order-level analytics. * **Settlement events:** `order_hash` appears on each trade inside the `trades[]` array. Available on pending (pre-chain) settlements, computed from transaction calldata before block confirmation. * **Trade events:** `order_hash` appears as a top-level field, extracted directly from the on-chain `OrderFilled` event log. ```json theme={null} { "type": "trade", "data": { "order_hash": "0x916fa5c2728c93e19ea5d7c254b07234815ad01e59597573c09d852fe53ee564", "maker": "0x4b8cf80092c60b9b23d22133eb63eb4508fe4d31", "price": 0.71, "size": 3.0 } } ``` No SDK update required — the field is automatically included in the WebSocket stream. ### API — `order_hashes` on Status Updates The `status_update` event now includes an `order_hashes` field containing every EIP-712 order hash from the original pending settlement. This lets you correlate confirmed settlements back to specific limit orders without needing to store state from the initial pending event. ```json theme={null} { "type": "status_update", "data": { "tx_hash": "0xbb26c8cd...", "order_hashes": [ "0xafc3488df3505c4dbba8797b8b6c645630c8ee9decf811a0acc4d63fdecfdd36", "0x9b5a06de7196bde87b4d8baa6cb80681151338d263fac0e643a2d53c4497e27f" ], "maker_wallets": ["0xd408...", "0x9443..."], "latency_ms": 3959 } } ``` Purely additive. Existing clients are unaffected. *** ### TypeScript SDK — RedemptionWatcher Memory Management The `RedemptionWatcher` now automatically evicts resolved conditions and zero-size positions from its local watch set. This keeps memory bounded to only active, non-zero positions regardless of how long the watcher runs or how many wallets it tracks. Previously, resolved markets and fully-sold positions accumulated in memory indefinitely. For long-running services tracking thousands of wallets, this could grow to hundreds of megabytes over weeks. **What changed:** * Resolved conditions are removed from the index immediately after alerts fire * Positions that drop to zero size (full sell) are removed automatically * `refreshInterval` default changed from `0` (disabled) to `300_000` (5 minutes). This periodic REST refresh acts as a safety net, re-populating any positions missed during brief WebSocket disconnections. **No breaking changes.** Alert behavior is identical. If you were explicitly setting `refreshInterval: 0`, that still works. ```bash theme={null} npm install polynode-sdk@latest ``` See [RedemptionWatcher — Memory Management](/sdks/redemption-watcher#memory-management) for details. *** ### Trader Profile — EOA Wallet Resolution The `/v1/trader/{wallet}` endpoint now returns an `eoaWallet` field that resolves the underlying EOA (externally owned account) for Polymarket proxy wallets. This is derived onchain from the Gnosis Safe contract. ```json theme={null} { "wallet": "0xc2e7800b5af46e6093872b177b7a5e7f0563be51", "eoaWallet": "0xb49e5499562a4bc3345c1a1f2db13a5360dfddac", "name": "beachboy4", ... } ``` For older lightweight proxy wallets, `eoaWallet` returns `null`. ### Tier-Aware Rate Limits on Data-Heavy Endpoints A handful of data-heavy endpoints now have their own per-key rate limits that scale with your plan: | Tier | Limit | | - | - | | Free | 1 req/sec | | Starter | 30 req/sec | | Growth | 50 req/sec | | Enterprise | 100 req/sec | Affected endpoints: `/v1/trader/{wallet}`, `/v1/trader/{wallet}/pnl`, `/v1/leaderboard`, `/v1/trending`, `/v1/activity`, `/v1/event/{slug}`, `/v1/movers`, `/v2/markets/{category}`. All other REST endpoints use your plan's standard rate limit. See [Rate Limits](/guides/rate-limits) for full details. *** ## 2026-03-25 ### TypeScript SDK — RedemptionWatcher New high-level class that monitors wallets and fires alerts the instant any position becomes redeemable on-chain. ```bash theme={null} npm install polynode-sdk@latest ``` ```typescript theme={null} import { RedemptionWatcher } from 'polynode-sdk'; const watcher = new RedemptionWatcher({ apiKey: 'pn_live_...' }); watcher.on('alert', (alert) => { if (alert.isWinner) { console.log(`${alert.wallet} can redeem "${alert.marketTitle}" — ~$${alert.estimatedPayoutUsd}`); } }); await watcher.start(['0xabc...', '0xdef...']); ``` **What it does:** Fetches wallet positions via REST, indexes by `condition_id`, subscribes to the oracle stream for `condition_resolution` events, and cross-references in real-time. Optional live position tracking via the wallets stream keeps sizes accurate as users trade. **Key features:** * Runtime `addWallets()` / `removeWallets()` with automatic re-subscription * Callback (`.on('alert', ...)`) and async iterator (`for await`) consumption * Winner detection with payout estimates * Full market metadata on every alert (title, slug, image, outcomes) See the [full documentation](/sdks/redemption-watcher) for lifecycle, configuration, and a production example. *** ### Oracle Stream — `condition_resolution` Event The oracle WebSocket stream now includes `condition_resolution` events. This is the on-chain signal that positions are redeemable on the Conditional Tokens contract. Previously, the stream included `resolution` events (outcome decided on the UMA adapter) but not the separate on-chain step where `reportPayouts()` is called on the CTF contract. For neg-risk markets (the majority on Polymarket), there is a \~2-3 minute gap between these two events. `condition_resolution` closes that gap. **Subscribe and filter:** ```json theme={null} { "action": "subscribe", "type": "oracle", "event_types": ["condition_resolution"] } ``` **Payload includes:** `resolved_price`, `payouts`, `condition_id`, `question_id`, and full market metadata (title, outcomes, token IDs, image). **Use case:** Trigger redemption workflows the instant positions become redeemable, instead of polling or waiting for the Polymarket UI to update. **SDK support:** Available in Rust SDK `polynode 0.4` via `OracleEventType::ConditionResolution`. TypeScript SDK update coming soon. *** ### TypeScript SDK v0.4.8 — Composable Leaderboard Builder The local cache now supports composable leaderboards with multi-metric ranking, market filtering, slug pattern matching, wallet scoping, and time windows. **New:** Call `cache.leaderboard()` with no arguments to get a `LeaderboardBuilder`: ```typescript theme={null} const rows = cache.leaderboard() .metrics(['total_pnl', 'volume', 'win_rate']) .slugs(['*election*']) .since(weekAgo) .limit(10) .build(); // Each row: { wallet, label, rank, metrics: { total_pnl, volume, win_rate } } ``` **7 new metrics** (11 total): `roi`, `realized_pnl`, `volume`, `avg_trade_size`, `largest_win`, `largest_loss`, `market_count`. **Builder methods:** * `.metric()` / `.metrics()` — single or multi-metric per row * `.sortBy()` / `.sort('ASC' | 'DESC')` — control ranking * `.markets([conditionIds])` — filter by market * `.slugs([patterns])` — glob match on market slugs (`*election*`, `btc-*`) * `.category({ name, slugs })` — reusable named slug groups * `.wallets([addrs])` — rank a wallet subset instead of full watchlist * `.since(ts)` / `.until(ts)` — time window for trade metrics * `.limit(n)` — top N Backward compatible. Existing `cache.leaderboard('total_pnl')` still returns the same `LeaderboardEntry[]` format. ```bash theme={null} npm install polynode-sdk@0.4.8 ``` Full documentation: [Local Cache — Leaderboard Builder](/sdks/local-cache#leaderboard-builder) *** ### WebSocket — Application-Level Keepalive Cloud platform reverse proxies (Railway, Render, Heroku, AWS ALB, fly.io) can intercept WebSocket Ping/Pong control frames, preventing the server from detecting that your client is still alive. This caused connections to drop after 1-2 minutes with an empty error and no close frame. **What changed:** * The server now accepts any incoming message (not just Pong frames) as proof the client is alive * New `{"action": "ping"}` message returns `{"type": "pong", "ts": ...}` as an application-level keepalive * Stale connection timeout extended from 90 seconds to 5 minutes * Stale disconnects now include a close frame with a reason, instead of a silent drop **If you're running on a cloud platform**, add a periodic ping to your connection: ```python Python theme={null} async def keepalive(): while True: await asyncio.sleep(30) await ws.send(json.dumps({"action": "ping"})) ping_task = asyncio.create_task(keepalive()) ``` ```javascript Node.js theme={null} setInterval(() => ws.send(JSON.stringify({ action: "ping" })), 30000); ``` If you're running on bare metal or a VM with no reverse proxy in front of your client, this doesn't affect you. Standard WS Ping/Pong still works as before. See [WebSocket Overview](/websocket/overview#application-level-keepalive) for full connection examples. *** ### WebSocket — Reconnect Gap-Fill with `since` Subscribe messages now accept an optional `since` filter (UNIX milliseconds). When set, the initial snapshot returns all events after that timestamp instead of just the most recent N, letting you fill gaps after a disconnect or cold start without missing data. ```json theme={null} { "action": "subscribe", "type": "settlements", "filters": { "since": 1774412600000 } } ``` The response is the same `snapshot` message you already handle. Existing clients are unaffected — `since` is fully optional. **Lookback windows by tier:** | Tier | Max lookback | | - | - | | Free | 30 seconds | | Starter | 2 minutes | | Growth | 5 minutes | | Enterprise | 5 minutes | If `since` is older than your tier's window, it's automatically clamped. Within the window, there is no event count limit — you get everything that matches your filters. *** ## 2026-03-24 ### API — Onchain Redemption State on Wallet Positions The `/v1/wallets/{addr}/positions` and `/v1/wallets/positions` endpoints now include onchain redemption data for resolved markets. Three new fields are returned on positions where `redeemable` is `true`: * **`redeemed`** — `true` if the wallet has burned their tokens onchain (claimed USDC payout), `false` if tokens are still held. * **`unredeemed_balance`** — Number of tokens still held onchain. Tells you exactly how much hasn't been claimed. * **`unredeemed_usd`** — USD value of unclaimed tokens (\$1 per token on winning positions). This data is not available from Polymarket's API. polynode checks the Conditional Token Framework contract onchain in a single batched call, adding \~130ms only when redeemable positions are present. Active (unresolved) positions are unaffected. ```bash theme={null} curl "https://api.polynode.dev/v1/wallets/0x62d2.../positions" \ -H "x-api-key: pn_live_..." ``` ```json theme={null} { "title": "Lana Del Rey divorce in 2025?", "redeemable": true, "redeemed": false, "unredeemed_balance": 418.73, "unredeemed_usd": 418.73, "size": 418.73 } ``` *** ## 2026-03-23 ### API — Event Search & Token IDs Two changes to event endpoints: * **New:** `GET /v1/events/search?q=...&limit=N` — search events by text query. Returns events with all sub-markets, each including `tokenId` (YES token for CLOB price history via `/v1/candles`) and current `price`. Multi-outcome events like "How many Fed rate cuts in 2026?" return as a single result with all outcomes. * **Updated:** `GET /v1/event/{slug}` — now includes `tokenId` on every market in the response. Previously, token IDs were not available on this endpoint. ```bash theme={null} curl "https://api.polynode.dev/v1/events/search?q=recession&limit=5" \ -H "x-api-key: pn_live_..." ``` Rate limit: 1 request per second per API key (shared with other enriched data endpoints). ### TypeScript SDK v0.4.6 * **New:** `searchEvents(query, { limit })` — typed method for event search, returns `EventSearchResponse` * **New types:** `EventSearchResponse`, `EventSearchResult`, `EventSearchMarket` * **Updated:** `EventMarket` now includes optional `tokenId` field ```bash theme={null} npm install polynode-sdk@0.4.6 ``` ```typescript theme={null} const results = await pn.searchEvents('Fed rate', { limit: 5 }); for (const event of results.events) { console.log(event.title, `(${event.markets.length} outcomes)`); for (const m of event.markets) { // Use tokenId to fetch price history const candles = await pn.candles(m.tokenId, { resolution: '1h' }); } } ``` *** ## 2026-03-21 - Enriched TypeScript SDK methods ### TypeScript SDK v0.4.4 — Enriched Data Methods Eight new typed methods on the `PolyNode` client for all enriched data endpoints: * `leaderboard()` — top 20 traders by profit or volume, with period filtering * `trending()` — carousel, breaking markets, hot topics, featured events, and biggest movers * `activity()` — platform-wide trade feed (50 most recent) * `movers()` — markets with largest 24h price swings * `traderProfile(wallet)` — full trader stats: PnL, volume, trades, largest win * `traderPnl(wallet, { period })` — cumulative PnL time series * `event(slug)` — full event detail with all sub-markets * `marketsByCategory(category)` — browse markets by category All methods are fully typed with dedicated response interfaces. Install: ```bash theme={null} npm install polynode-sdk@0.4.4 ``` *** ### TypeScript SDK v0.4.3 — Cache UI Primitives Four new features for building dashboards on top of the local cache. * **View methods** — `watchlistSummary()`, `walletDashboard()`, `leaderboard()`, `marketOverview()`. Pre-shaped data for common dashboard patterns. No SQL, no aggregation. * **Reactive subscriptions** — `onChange()` and `onWalletChange()` fire callbacks when new trades or settlements land from the live WebSocket stream. Returns an `unsub()` function for cleanup. * **Export helpers** — `exportCSV()`, `exportJSON()`, `exportRows()` dump filtered data for charting libraries, spreadsheets, or custom analysis. * **Query builder** — Chainable fluent API: `.wallet()`, `.side()`, `.since()`, `.market()`, `.minPnl()`, `.limit()`, `.run()`. Complex filters without writing SQL. ```bash theme={null} npm install polynode-sdk@0.4.3 ``` Full documentation: [Local Cache](/sdks/local-cache) *** ## 2026-03-21 - Enriched data API endpoints ### API — Enriched Data Endpoints Eight new REST endpoints for trader analytics, market discovery, and platform trends. * `GET /v1/leaderboard` — Top 20 traders ranked by profit or volume (daily, weekly, monthly, all-time) * `GET /v1/trader/{wallet}` — Full trader profile: PnL, volume, trade count, largest win, portfolio value * `GET /v1/trader/{wallet}/pnl` — PnL time series at 4 resolutions (1D, 1W, 1M, ALL) * `GET /v1/trending` — Carousel highlights, breaking markets, hot topics, featured events, biggest movers * `GET /v1/activity` — Platform-wide live trade feed (last 50 trades with tx hashes) * `GET /v1/event/{slug}` — Full event data with all sub-markets, outcome prices, condition IDs * `GET /v1/movers` — Markets with the largest 24h price changes * `GET /v2/markets/{category}` — Category market listings with counts (crypto, politics, sports, etc.) Rate limit: 1 request per second per API key. Responses cached 1-3 minutes. ### TypeScript SDK v0.4.1 * **Fix:** ESM imports now work correctly. v0.4.0 crashed on `cache.start()` when using `import` syntax. * **Fix:** Eliminated `MODULE_TYPELESS_PACKAGE_JSON` Node.js warning. * **New:** `getActiveTestWallet()` / `getActiveTestWallets()` — returns known-active wallet addresses for testing and examples. ```bash theme={null} npm install polynode-sdk@0.4.1 ``` ### API — Wallet positions fix * Fixed `firstTradeAt` / `lastTradeAt` returning `null` for certain wallets on `GET /v1/markets/{id}/positions?includeTrades=true`. * Added fallback query path for wallets where the primary trade lookup returns empty. ### API — Per-endpoint rate limiting * `includeTrades=true` on market positions now has its own 20 req/min rate limit per key. * Separate bucket from standard rate limit — doesn't consume your normal quota. *** ## 2026-03-21 - TypeScript and Rust local cache SDKs ### TypeScript SDK v0.4.0 * **New:** Local Cache — SQLite-backed local storage for instant offline queries. * Backfill wallet history in seconds (1 request per wallet, up to 500 trades). * Live WebSocket stream keeps the cache up to date automatically. * Query trades, positions, and settlements locally with zero API calls. * Watchlist file with hot-reload and runtime add/remove API. * Full documentation at [Local Cache](/sdks/local-cache). ### Rust SDK v0.4.0 * **New:** Local Cache ported from TypeScript, matching its cache behavior and query methods. * Builder pattern: `PolyNodeCache::builder(client).db_path(...).build()?` * `rusqlite` (bundled) + `notify` as optional dependencies behind `cache` feature flag. *** ## 2026-03-20 ### Web Frontend * Speed comparison test redesigned with 3-second warm-up period, win % scoreboard, and visual win ratio bar. * Updated "Run this test yourself" code snippet to match new logic. *** ## 2026-03-19 ### TypeScript SDK v0.3.0 * **New:** `OrderbookEngine` — higher-level orderbook client with shared state and filtered views per component. * **New:** `LocalOrderbook` — local orderbook state management. * **New:** `ShortFormStream` — condensed event stream for bandwidth-constrained environments. ### API * Orderbook REST endpoints: `/v1/orderbook/{token}`, `/v1/midpoint/{token}`, `/v1/spread/{token}`. * Wallet trades `limit` parameter now allows up to 1,000 (was 500). *** ## 2026-03-15 ### API v1 — Initial Public Release * **WebSocket streaming:** settlements, trades, prices, blocks, wallets, markets, large trades, oracle, chainlink * **REST API:** markets, search, candles, stats, settlements, wallets * **Orderbook streaming** via `ob.polynode.dev` * **RPC endpoint** via `rpc.polynode.dev` — JSON-RPC with TX #1 delivery * **CLI** (`pn`) — stream events, query markets, manage API keys from the terminal # Changelog — March 28–31, 2026 Source: https://docs.polynode.dev/changelog-march-28-31-2026 Archived PolyNode API and SDK changes from March 28–31, 2026. [← Back to the current changelog](/changelog) ## 2026-03-31 — TypeScript SDK v0.5.6 (Cache Crash Recovery) ### TypeScript SDK v0.5.6 Fixes a crash that could occur when stopping the cache mid-backfill, and adds proper crash recovery for interrupted backfills. **Graceful shutdown**: `cache.stop()` now waits for any in-flight backfill operation to complete before closing the database. Previously, stopping during an active backfill could crash with a `Cannot read properties of null` error on the SQLite handle. **Crash recovery**: on startup, any backfills that were interrupted by a previous crash or kill are automatically detected and retried. The cache logs exactly what's happening: ``` # Restart after crash — resumes incomplete backfills only [PolyNodeCache] Reset 1 interrupted backfill(s) from previous session. [PolyNodeCache] Backfilling 2 entities (1 page of 500 each) — ETA: ~1s # Clean restart — all data persisted, no network calls needed [PolyNodeCache] All 4 entities already backfilled, skipping. ``` **Accurate logging**: the startup log now only reports entities that actually need backfilling, instead of the total watchlist count. ```bash theme={null} npm install polynode-sdk@0.5.6 ``` *** ## 2026-03-31 — Equity Curve Endpoint ### New: Trader Equity Curve Full equity curve for any Polymarket wallet. Returns a time-ordered series of cumulative profit and loss across every position the wallet has ever taken. **Endpoint:** `GET /v2/trader/{wallet}/equity?period=all&normalize=1` **Features:** * Raw P\&L curve with realized gains/losses and mark-to-market on open positions * \$1-normalized curve for copy-trade analysis: each position scaled to \$1 of risk, showing expected returns per dollar deployed * Period filtering: `7d`, `30d`, `90d`, `1y`, `all` * Accuracy within 2-3% of Polymarket's own P\&L calculations (variance from real-time price differences on open positions only) **\$1 normalization** answers the question: "If I copy every trade this wallet makes but only risk \$1 per position, what are my returns?" Useful for evaluating trader skill independent of position sizing. ```bash theme={null} curl "https://api.polynode.dev/v2/trader/0x.../equity?period=all&normalize=1" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "positions_count": 278, "open_count": 83, "raw": { "final_pnl": -395.90, "curve": [{"t": 1774555427, "pnl": 10.56}, ...] }, "normalized": { "bet_size": 1, "final_pnl": -3.19, "curve": [{"t": 1774555427, "pnl": 0.07}, ...] } } ``` See the [full documentation](/api-reference/enriched/equity-curve) for methodology details and response field reference. ### Fix: Market Price Fetching Fixed an issue where current market prices were not being fetched correctly for open positions across multiple endpoints. Price accuracy is now significantly improved for any endpoint that reports unrealized P\&L. *** ## 2026-03-29 — Rust SDK v0.5.6 (Order Placement Fix) ### Rust SDK v0.5.6 Critical fixes for order placement. The trading module now passes full end-to-end testing: wallet onboarding, order placement, cancellation, and order history. **Order signing fixes:** * Fixed EIP-712 struct hashing (domain type filtering) * Fixed signature `v` normalization for CLOB compatibility * Fixed amount rounding to match tick-size-based precision rules * Fixed salt generation range for CLOB compatibility **Authentication fixes:** * Fixed HMAC base64 decoding for URL-safe encoded secrets * Fixed wallet address checksumming (EIP-55) in all auth headers and order payloads **Privy integration fixes:** * Fixed address formatting in Privy wallet API calls * Fixed signature normalization in Privy response extraction ```toml theme={null} [dependencies] polynode = { version = "0.5.6", features = ["trading"] } ``` *** ## 2026-03-29 — Python SDK v0.6.0 ### Python SDK v0.6.0 Trading module fixes and Privy server-side wallet support. **Trading fixes:** * Fixed CLOB credential creation (endpoint, auth headers, EIP-712 message structure) * Fixed order signing (domain name, signature format, payload serialization) * Fixed HMAC authentication for URL-safe base64 secrets * Fixed `fetch_tick_size` and `fetch_neg_risk` response parsing * Full end-to-end verified: wallet generation, onboarding, order placement, cancellation, gasless flow **New: Privy signer** * `PrivySigner` for server-side trading with Privy-managed wallets * No private key needed, signing via Privy's wallet API * Works with all trading methods (`ensure_ready`, `order`, `cancel_all`, etc.) **Other fixes:** * `markets_by_category()` now correctly filters via query parameter * Fixed subscription filters code example in docs ```bash theme={null} pip install polynode==0.6.0 # With trading support: pip install "polynode[trading]==0.6.0" ``` *** ## 2026-03-29 — Rust SDK v0.5.0 (Feature Parity) ### Rust SDK v0.5.0 Major release bringing the Rust SDK to feature parity with the TypeScript SDK. **New REST endpoints (12 methods):** * Orderbook REST: `orderbook_rest()`, `midpoint()`, `spread()` * Enriched data: `leaderboard()`, `trending()`, `activity()`, `movers()` * Trader analytics: `trader_profile()`, `trader_pnl()` * Events: `event()`, `search_events()`, `markets_by_category()` **Trading module** (`--features trading`): * `PolyNodeTrader` for full order lifecycle on Polymarket * Wallet generation, onboarding (auto-detect Safe/Proxy), order placement, cancellation * Native EIP-712 signing via `TradingSigner` trait + `PrivateKeySigner` * CREATE2 address derivation for Safe and Proxy wallets * CLOB authentication with L2 HMAC headers * Builder attribution via co-signer proxy * Local SQLite storage for credentials and order history * On-chain approval and balance checks **Privy integration** (`--features privy`): * `PrivySigner` for server-side trading with Privy-managed wallets * Pure HTTP-based, no native SDK dependency **Redemption watcher:** * Monitor wallets for redeemable positions after oracle resolution * Fires alerts with winner detection and payout estimation ```toml theme={null} [dependencies] polynode = "0.5" # With trading: # polynode = { version = "0.5", features = ["trading"] } ``` Full documentation: [Rust SDK](/sdks/rust) *** ## 2026-03-29 — Trading Module v0.5.5 (TypeScript SDK) ### TypeScript SDK v0.5.5 * **EOA auto-approvals:** `ensureReady()` now automatically sends approval transactions for EOA wallets with proper nonce management. Requires ~~0.05 MATIC in the wallet (~~\$0.01). * **Fix:** `createPrivySigner`, `createPrivyClient`, and other Privy helpers are now correctly exported from the package root. In v0.5.2 these were only reachable through non-public module paths. * **Privy server-auth integration:** `createPrivySigner()` and `createPrivyClient()` for server-side trading with Privy-managed wallets. * **Unlimited gasless operations:** Paid tiers get unlimited gasless on-chain operations. Free tier gets basic gasless onboarding. > [!NOTE] > > **Current clarification:** this historical release note described the builder > plan available at that time. Current user-owned execution removes a platform's > shared builder relayer allowance by using wallet-scoped authorization with zero > builder attribution. Normal wallet, market, order API, abuse-prevention, and > rate-limit rules still apply; do not interpret “unlimited” as unbounded order > throughput. See [User-owned execution](/sdks/user-owned-execution). * **ethers v5/v6 compatibility:** Safe transaction signing works with both ethers v5 and v6. ```bash theme={null} npm install polynode-sdk@0.5.5 viem better-sqlite3 @polymarket/clob-client @polymarket/builder-relayer-client @polymarket/builder-signing-sdk ``` Full documentation: [Trading](/sdks/trading) *** ## 2026-03-29 — Trading Module (TypeScript SDK v0.5.0) ### TypeScript SDK — Order Placement on Polymarket Place and manage orders on Polymarket through the polynode SDK. One function call handles wallet setup, credential creation, approvals, and order placement. ```bash theme={null} npm install polynode-sdk@0.5.0 viem better-sqlite3 @polymarket/clob-client @polymarket/builder-relayer-client @polymarket/builder-signing-sdk ``` **One-call onboarding:** ```typescript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...' }); // Auto-detects your wallet type. Deploys Safe, sets approvals, creates credentials. const status = await trader.ensureReady('0xYOUR_PRIVATE_KEY'); const result = await trader.order({ tokenId: '...', side: 'BUY', price: 0.55, size: 100, }); await trader.cancelOrder(result.orderId); ``` **Key features:** * **Auto-detection:** Pass your private key. The SDK checks if you have a Safe, Proxy, or EOA on-chain and uses the right one. No wallet type guessing. * **Wallet generation:** `PolyNodeTrader.generateWallet()` for users starting from scratch. * **Gasless onboarding:** Safe deployment + 6 token approvals in one call, \~10 seconds, zero gas. * **Local credential custody:** CLOB credentials stored in local SQLite. Export, import, and back up freely. * **Builder attribution:** Orders route through polynode's relay for affiliate tracking. If the relay is down, orders fall back to direct CLOB submission. * **All three wallet types:** EOA (type 0), Proxy (type 1, legacy Magic Link), Safe (type 2, browser wallets). * **Dome drop-in:** Same `@polymarket/clob-client` signing under the hood. Import existing Dome credentials with `linkCredentials()`. Full documentation: [Trading](/sdks/trading) | [Dome Migration](/dome-migration#order-placement) *** ## 2026-03-28 — Onchain Data Endpoints + Market Metadata Enrichment ### Enrichment: All Onchain Endpoints Now Include Market Metadata Every onchain endpoint now returns enriched data with human-readable market context. Responses include `market` (question text), `slug`, `outcome` label, `image`, and `condition_id` alongside the raw onchain data. Powered by a full backfill of all 706K+ Polymarket markets into a local metadata store that refreshes every 5 minutes. ### New: Onchain Data Section Seven new endpoints for blockchain settlement data. These provide complete, accurate data that never times out or drops records. All onchain endpoints are under `/v2/onchain/` and documented in the new [Onchain](/api-reference/onchain/wallet-trades) section of the API reference. #### Wallet endpoints * **`GET /v2/onchain/wallets/{addr}/trades`** — Complete trade fill history for any wallet. Every fill, every counterparty, every fee. * **`GET /v2/onchain/wallets/{addr}/redemptions`** — All redemptions with payout amounts. See who cashed out, when, and how much. Not available anywhere else. * **`GET /v2/onchain/wallets/{addr}/activity`** — Splits, merges, and multi-outcome conversions. Shows how wallets interact with the CTF contract beyond simple trading. #### Market endpoints * **`GET /v2/onchain/markets/{tokenId}/trades`** — Complete trade tape for any market token. * **`GET /v2/onchain/markets/{tokenId}/volume`** — Lifetime volume stats: total trades, buys, sells, USDC volume with buy/sell breakdown. * **`GET /v2/onchain/markets/{conditionId}/oi`** — Per-market open interest in USDC. * **`GET /v2/onchain/oi`** — Global platform open interest (currently \~\$469M). All endpoints support `limit` and `offset` pagination where applicable. Responses are cached for 1-5 minutes depending on the endpoint. *** ### Wallet P\&L: Complete Position History + Accurate Realized P\&L #### What changed The existing `GET /v1/wallets/{addr}/positions` endpoint only returns **open** positions. Once a market resolves or a position is fully sold, it disappears from the response. The existing `GET /v1/wallets/{addr}/trades` endpoint silently drops trades for high-volume wallets (we verified one wallet showing 403 trades through the API vs 4,405 actual onchain trades). This made it impossible to compute accurate P\&L through our API. That's fixed now. Two new v2 endpoints return complete position history with accurate P\&L sourced from onchain settlement data. Per-position `realized_pnl` values come from the same onchain settlement data Polymarket uses and match individual position P\&L to the penny. The `total_realized_pnl` aggregate measures total realized gains, which is different from Polymarket's profile PnL (see [docs](/api-reference/wallets/onchain-positions#total_realized_pnl-vs-polymarket-profile-pnl) for a full breakdown). #### `GET /v2/wallets/{address}/positions/onchain` **One call. No pagination. All positions (open + closed).** Unlike the v1 positions endpoint which requires the SDK to paginate through trades page by page, this endpoint returns the complete picture in a single request with up to 20,000 positions. ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/positions/onchain" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "wallet": "0xbddf61af533ff524d27154e589d2d7a81510c684", "source": "onchain", "count": 873, "open_count": 334, "closed_count": 288, "total_realized_pnl": 17183579.48, "positions_with_pnl": 309, "positions": [ { "token_id": "3415885798119615...", "size": 0, "avg_price": 0.316481, "realized_pnl": 447182.95, "total_bought": 654236.31 } ] } ``` | Field | Description | | - | - | | `count` | Total positions (open + closed) | | `open_count` | Positions still held (`size > 0`) | | `closed_count` | Fully exited positions with nonzero P\&L | | `positions_with_pnl` | Number of positions with nonzero realized P\&L | | `total_realized_pnl` | Sum of all `realized_pnl` values | | `positions[].realized_pnl` | Profit or loss for this position in USDC | | `positions[].avg_price` | Volume-weighted average entry price | | `positions[].total_bought` | Total tokens acquired | Responses are cached for 5 minutes. First request takes 200ms-3s depending on position count. Cached responses return in under 50ms. #### `GET /v2/wallets/{address}/closed-positions` Closed positions with full metadata (title, outcome, slug). Paginated. ```bash theme={null} curl "https://api.polynode.dev/v2/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/closed-positions?limit=3&sortBy=REALIZEDPNL&sortDirection=DESC" \ -H "x-api-key: YOUR_KEY" ``` Parameters: `limit` (max 50), `offset`, `sortBy` (REALIZEDPNL, AVGPRICE, PRICE, TITLE, TIMESTAMP), `sortDirection` (ASC/DESC). #### SDK: Automatic onchain P\&L backfill The TypeScript (`polynode-sdk@0.4.10`) and Rust (`polynode@0.4.3`) SDKs now fetch onchain position data automatically during backfill. No code changes needed if you're already using `cache.start()`. The backfill makes one additional API call per wallet (the onchain positions endpoint above) and stores the results in your local SQLite database. ```bash theme={null} npm install polynode-sdk@0.4.10 ``` **Before:** The SDK backfilled trades page by page (up to 6 requests per wallet) and computed P\&L from incomplete trade history. Wallets with dropped trades got wrong numbers. **After:** One call per wallet returns all positions with precomputed P\&L. The SDK stores this in SQLite and uses it as the source of truth for all P\&L queries. ```typescript theme={null} const cache = new PolyNodeCache(client); await cache.start(); // P&L from local cache — no API calls const pnl = cache.computeRealizedPnl("0xbddf61af533ff524d27154e589d2d7a81510c684"); ``` ```json theme={null} { "wallet": "0xbddf61af533ff524d27154e589d2d7a81510c684", "total_realized_pnl": 17183579.48, "total_unrealized_pnl": 3030.53, "total_pnl": 17186610.01, "confidence": "full", "trades_analyzed": 403, "tokens": [ { "token_id": "3415885798119615...", "market_title": "Nuggets vs. Warriors", "outcome": "Warriors", "realized_pnl": 447182.95, "avg_cost": 0.3170, "remaining_size": 0 } ] } ``` `trades_analyzed` reflects cached trades from the REST API (403 in this case). The `total_realized_pnl` and per-token `realized_pnl` values come from onchain settlement data and are accurate regardless of cached trade count. `walletDashboard()` now includes `realized_pnl`, `pnl_confidence`, and `token_pnl` fields: ```typescript theme={null} const dash = cache.walletDashboard("0xbddf61af533ff524d27154e589d2d7a81510c684"); // dash.realized_pnl → 17183579.48 // dash.pnl_confidence → "full" // dash.token_pnl → per-token P&L breakdown // dash.total_pnl → realized + unrealized combined ``` *** ### Crypto Price Streaming (WebSocket) Real-time cryptocurrency prices are now available on the same WebSocket connection you already use for settlements and oracle events. Seven feeds, each updating roughly once per second: **BTC/USD**, **ETH/USD**, **SOL/USD**, **BNB/USD**, **XRP/USD**, **DOGE/USD**, **HYPE/USD** Subscribe with `{"action": "subscribe", "type": "chainlink"}`. Optionally filter to specific feeds: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD"] } } ``` Each price update includes bid, ask, and mid price: ```json theme={null} { "type": "price_feed", "feed": "BTC/USD", "timestamp": 1774675338, "data": { "feed": "BTC/USD", "price": 66240.86, "bid": 66234.85, "ask": 66243.30, "timestamp": 1774675338 } } ``` BTC/USD includes actual bid/ask spread. Other feeds currently report bid and ask equal to the mid price. See the [full documentation](/crypto/overview) for connection examples, feed details, and event format reference. *** ### Crypto REST Endpoints Five new REST endpoints for crypto prediction market data: * `GET /v1/crypto/markets` — All crypto prediction markets with volume, liquidity, and open interest (3 min cache) * `GET /v1/crypto/candles?symbol=BTC` — \~30 five-minute OHLC candles (30s cache) * `GET /v1/crypto/price?symbol=BTC&window={epoch}` — Open/close price for a specific market window (10s cache) * `GET /v1/crypto/active` — Currently active 5-minute up-or-down markets across all 7 coins with live odds (30s cache) * `GET /v1/crypto/series` — Recurring crypto market series across timeframes (5 min cache) ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/candles?symbol=ETH" \ -H "x-api-key: YOUR_KEY" ``` Supported symbols: `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, `HYPE`. See the [REST API reference](/crypto/rest-api) for full parameter details and response samples. *** # Changelog — May 1, 2026 Source: https://docs.polynode.dev/changelog-may-1-2026 Archived PolyNode API and SDK changes from May 1, 2026. [← Back to the current changelog](/changelog) ## 2026-05-01 — Cursor pagination on `/v2/onchain/*/trades` The two trade-history endpoints now support **cursor pagination** in addition to offset: * `GET /v2/onchain/markets/{token_id}/trades?cursor=:` * `GET /v2/onchain/wallets/{address}/trades?cursor=:` **Why it matters:** offset pagination slows down the deeper you page — page 500 means the database walks 50,000 rows of wasted work to find your starting point. Cursor pagination loads page 1000 just as fast as page 1 — typically \~1 second per page, regardless of how deep you go. **How to use:** 1. First page: pass `?cursor=` (empty value) instead of `?offset=0`. 2. Response includes a `pagination` block with `cursor` and `has_more`. 3. Subsequent pages: pass that `cursor` back as `?cursor=`. 4. Stop when `has_more` is `false`. **Available on every paid tier** — no Growth restriction. **Compatibility:** purely additive. The existing `?offset=` mode is unchanged and remains fully supported. Existing integrations don't need to change anything — switch to cursor when you next touch the integration. See the updated docs for full examples: [Trade History (Market)](/api-reference/onchain/market-trades) · [Trade History (Wallet)](/api-reference/onchain/wallet-trades). *** ## 2026-05-01 — Bulk trade-export endpoints (Growth plan and above) Two new endpoints return the **entire** trade history for a market token or wallet in a **single response** — no client-side pagination required: * `GET /v2/onchain/markets/{token_id}/trades/all` * `GET /v2/onchain/wallets/{address}/trades/all` The endpoint walks the full history for you. Optional `from` and `to` query parameters narrow the window. **Limits:** * Hard cap **250,000 trades** per call. Beyond that, response includes `"partial": true` with `"partial_reason": "hard_cap_250000"`. * Wall-clock budget **180 seconds**. First calls on busy markets or heavy wallets may take **1-3 minutes**. Repeated calls for the same scope and window typically return in **under 1 second**. * Typical payload **1-50 MB**. Worst case (capped): **100-200 MB JSON**. * Results are reused for **5 minutes** per `(scope, from, to)` combination. Partial results are **not reused**. **Tier requirement:** **Growth plan (\$200/mo) or above.** Starter and free tier requests receive `403`. The bulk endpoints are gated to paid plans because of their large query and payload sizes. **Compatibility:** purely additive. The standard paginated `/trades` endpoints are unchanged and remain available on all paid tiers. Updated the request timeout to 180 seconds so cold-cache calls complete cleanly. *** ## 2026-05-01 — Backtest Copy PnL: new `total_realized_pnl_usdc` field Added `total_realized_pnl_usdc` to `/v2/copy-pnl/{wallet}` responses. This is the **signed sum of WAVG-realized PnL across every position the matcher touched in the window** — the closest single number to "did this wallet make money trading?" and the recommended primary "PnL" field for customer-facing UI. Existing `actual_pnl_usdc` is unchanged but is now documented as a **cashflow** metric (USDC delta in/out of the wallet over the window), which is intentionally different from realized PnL — see the [endpoint docs](/api-reference/backtesting/copy-pnl#understanding-cashflow-pnl-vs-realized-pnl) for the worked example. Also fixed a long-standing bug in the cashflow accounting where neg-risk-conversion events were over-counting `settlement_in` (treating share counts as USDC). NRC-active wallets see corrected numbers across all four periods (`14d`, `30d`, `60d`, `180d`) on the next BYOB cycle refresh. *** # Changelog - May 2-24, 2026 Source: https://docs.polynode.dev/changelog-may-2-24-2026 Archived polynode API and SDK changes from May 2 through May 24, 2026. [← Back to the current changelog](/changelog) [Newer: May 25-31, 2026](/changelog-may-25-31-2026) · [Earlier: May 1, 2026 →](/changelog-may-1-2026) ## 2026-05-22 — V3 grouped trade total alias Added `total_amount_usd` to v3 `group_by=order_hash` trade responses. It is an additive alias of `total_usd` / `amount_usd`, so clients that already use the v2 grouped trade field can read the same total field on v3. Affected endpoints: * `GET /v3/wallets/{address}/trades?group_by=order_hash` * `GET /v3/trades?group_by=order_hash` Existing fields are unchanged. *** ## 2026-05-22 — Builder metadata and filtered builder trades Builder analytics now include public builder profile metadata on all builder endpoints: * `GET /v3/builders` * `GET /v3/builders/{code}` * `GET /v3/builders/{code}/trades` New additive fields: * `builder_code` * `builder_name` * `builder_logo` * `builder_verified` `/v3/builders/{code}/trades` also now supports builder-specific filters for `token_id`, `condition_id`, `market_slug`, `event_slug`, `side=buy|sell`, `min_amount`, `after`, `before`, `limit`, and `offset`. `category` and `tag_slug` filters are available with guardrails. Very broad category/tag requests return a structured `400` asking you to add `market_slug`, `condition_id`, `token_id`, or time bounds. ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15.../trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&tag_slug=sports&limit=10" ``` Existing fields and existing pagination behavior are unchanged. *** ## 2026-05-18 — PnL methodology note For users comparing our PnL numbers to what the Polymarket frontend displays: the two are computed differently and will diverge for wallets that hold a lot of settled-but-not-redeemed positions. **Polymarket's `pnl`** (leaderboard, profile chart) is a **mark-to-market equity curve delta**: `equity(end_of_window) − equity(start_of_window)`. Resolved markets are booked into the curve at settlement, regardless of whether the wallet has called `redeemPositions`. **Our `net_realized_pnl`** counts realized closes only — CLOB sells (the wallet sold their shares back) plus V2 adapter events (redemptions, merges, NRC conversions). Unrealized gains on settled-but-unredeemed positions stay in `unrealized_pnl`, not `net_realized_pnl`. **Empirically verified** against PM's `/closed-positions[].realizedPnl` on a representative wallet: per-position realized matches PM within 1%. The "lifetime pnl" headline diverges by the value of settled-not-redeemed positions in the wallet. `total_pnl` (= `net_realized_pnl + unrealized_pnl`) is the closer comparison to PM's curve delta — it includes both closed and still-open positions priced at current market. *** ## 2026-05-18 — New endpoint: wallet P\&L time series Added `GET /v3/wallets/{address}/pnl/events` — returns realized P\&L bucketed by `hour`, `day`, `week`, or `month` so you can plot a wallet's P\&L over time without pulling every trade. Each bucket includes `realized_pnl`, a running `cumulative_pnl`, gross profit/loss, win/loss counts, and event count. Supports `?period=1d|7d|30d|1y` shortcuts or explicit `after` / `before` Unix-second timestamps. Most full-history queries return sub-second. Other quality-of-life: * `?after` / `?before` outside the wallet's active window now correctly return zero buckets instead of an error. * All `/v3/*` paths now accept an optional trailing slash (`/v3/positions/` is equivalent to `/v3/positions`). * Unknown `/v3/*` paths return a structured 404 with a `hint` pointing to the docs, rather than HTML. * Invalid `sort` and `order` values now return `400` with the list of valid options instead of silently falling back to a default — typos surface immediately. ### Doc / API parity pass (later same day) Round 2 of the parity work — pure alignment between the API and the public reference, no breaking changes: * **`/v3/markets/condition/{condition_id}/positions`** — response field names now match `/v3/markets/{token_id}/positions`. Was returning abbreviated keys (`amt`, `avgp`, `bought`, `rpnl`, `tid`); now returns the long, documented names (`amount`, `avg_price`, `total_bought`, `realized_pnl`, `token_id`). Old keys are gone — update any client code using them. * **`/v3/resolutions`** — `payout_numerators` is now a JSON array of integers (e.g. `[0, 1]`), matching `/v3/conditions/{cid}`. Was returning quoted strings. `payout_denominator` is also an integer now. * **`/v3/builders`, `/v3/tags`, `/v3/tokens/{token_id}`** — response envelopes now include `offset` and `limit` like every other list endpoint. * **Param validation tightened** — invalid `?order=`, `?side=`, `?status=`, `?group_by=`, `?sort_by=` on trades / fees / resolutions / positions endpoints now return `400` with the valid-values list, instead of silently falling back to a default. Valid values still pass through unchanged. * **Token price scale** — `/v3/markets/{token_id}/price.price` and `/v3/tokens/{token_id}.data[].price` are JSON numbers in USD (range `0`–`1`), not 6-decimal strings. Reference page text updated accordingly. *** ## 2026-05-16 — V3 API goes live + performance fixes All `/v3/*` endpoints are now generally available (no longer "Coming Soon"). Several queries that timed out or ran slowly now return reliably and much faster: * `/v3/wallets/{addr}/positions` — default sort no longer times out, returns in \<100ms * `/v3/markets/slug/{slug}/trades` — fixed timeout, now \<100ms * `/v3/tags/{slug}/leaderboard` — small/medium tags are now sub-second; tags larger than 4,000 markets return a structured "too large" hint pointing to the global leaderboard * `/v3/tags/{slug}` — drops from 4.8s to \~1s * `/v3/wallets/{addr}/trades` — drops from 2.3s to \~200ms Tag slugs are now matched case-insensitively and accept URL-style hyphens: `/v3/tags/us-election/leaderboard` resolves to the stored tag `US Election`. Several doc examples that previously showed a `columns/rows` envelope have been corrected to the `data: [{...}]` shape that the API actually returns. *** ## 2026-05-14 — SDK fix: deposit wallet deploy + approve Fixed the deposit wallet (V2 / POLY\_1271) onboarding flow across all three SDKs. The relayer's `/submit` endpoint now requires builder authentication for WALLET-type submissions. All SDKs have been updated to include the required auth headers. If you previously hit `401 invalid authorization` or `API key and signer mismatch` errors when deploying a deposit wallet or setting approvals, update to the latest SDK version: ```bash theme={null} npm install polynode-sdk@0.10.7 # TypeScript cargo update -p polynode # Rust (0.13.4) pip install polynode==0.10.4 # Python ``` `ensureReady()` handles the full flow automatically — deploy, approve, create credentials. If your wallet is already deployed, it skips to approvals. If approvals are already set, it skips to credentials. *** ## 2026-05-10 — Sort and group trades by order hash `/v2/onchain/trades` now supports two new query parameters for working with limit order fills: **`sort_by=order_hash`** — reorders the response so all fills from the same limit order are adjacent, sorted by time within each order. Every fill is still returned individually. No data is collapsed. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0x...&sort_by=order_hash&limit=100" \ -H "x-api-key: YOUR_KEY" ``` **`group_by=order_hash`** — aggregates all fills from the same limit order into a single row with `total_amount_usd`, `total_shares`, `avg_price` (VWAP), `fill_count`, time range (`first_fill_at` / `last_fill_at`), and a `tx_hashes` array. ```bash theme={null} curl "https://api.polynode.dev/v2/onchain/trades?wallet=0x...&group_by=order_hash&limit=100" \ -H "x-api-key: YOUR_KEY" ``` A single limit order can be filled across hundreds of transactions over hours or days. These parameters let you view that activity at either granularity. *** ## 2026-05-05 — Magic-link wallet EOA recovery in `/resolve` `/v1/resolve` now returns the controlling EOA for Polymarket magic-link wallets — accounts created with email or social login. Previously these returned `eoa: null` because Polymarket's profile API does not expose the signer for this wallet type. ```json theme={null} { "safe": "0x16cbe223607a6513ae76d1e3751c78e4eabc2704", "eoa": "0xbe5ba588ab7173b34efc0706b881794951014293", "username": "MRF", "type": "proxy" } ``` **No code changes required.** The response shape is unchanged. The `eoa` field is now populated for the vast majority of `type: "proxy"` wallets. A small number may still return `eoa: null` where the EOA cannot be determined. Repeat queries are sub-100ms. *** ## 2026-05-02 — Deposit wallet support Polymarket is rolling out deposit wallets as a new account type for new users. This release adds full support across the API, all three SDKs, and the copy trading engine. **Existing integrations are fully backward compatible** — no code changes required unless you want to take advantage of the new features. Read the full [Deposit Wallets guide](/guides/deposit-wallets) for details, code examples, and FAQ. ### What's new **`/resolve` endpoint** — now returns a `type` field (`"safe"`, `"deposit_wallet"`, or `"proxy"`) in all responses. Resolves deposit wallets in both directions: wallet address to EOA and EOA to wallet address. Existing `safe`, `eoa`, and `username` fields unchanged. ```json theme={null} { "safe": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "eoa": "0xa60601a4d903af91855c52bfb3814f6ba342f201", "username": null, "type": "deposit_wallet" } ``` **SDK — address derivation and detection** — `deriveDepositWalletAddress(eoa)` computes the deterministic deposit wallet address for any EOA. `detectWalletType()` and `ensureReady()` automatically detect whether an EOA has a Safe, proxy, or deposit wallet. Safe is checked first, so existing users keep their existing wallet type. **SDK — order signing** — when `signatureType` is `POLY_1271` (3), the SDK wraps the EIP-712 signature using ERC-7739 TypedDataSign format automatically. `order()` / `signV2Order()` / `create_signed_order_v2()` detect the signature type from stored credentials and sign correctly. No code changes needed on your side. **SDK — onboarding** — `ensureReady()` handles the full flow for deposit wallet users: derives the wallet, deploys via `WALLET-CREATE` if needed, and sets V2 approvals via a signed `WALLET` batch. Same one-call pattern as Safe wallets. **Copy trading** — the copy trading engine generates the correct typed data for deposit wallet followers (`sig_type: 3`). Your signing code should use `signV2Order()` from the SDK. ### Install ```bash theme={null} cargo add polynode@0.13.3 # Rust npm install polynode-sdk@0.10.6 # TypeScript pip install polynode==0.10.3 # Python ``` ### Do I need to update? * **If you only read data** (positions, trades, resolve): no changes needed. The `type` field is additive. * **If you place orders via the SDK**: update to the versions above. Your code stays the same. * **If you build order signatures yourself**: you need to implement ERC-7739 wrapping for `signatureType: 3`. See the [guide](/guides/deposit-wallets#how-poly_1271-signing-works). # Changelog - May 25-31, 2026 Source: https://docs.polynode.dev/changelog-may-25-31-2026 Archived polynode API, SDK, WebSocket, webhook, and billing changes from May 25 through May 31, 2026. [← Back to the current changelog](/changelog) [Newer: June 1-7, 2026](/changelog-june-1-7-2026) · [Earlier: May 2-24, 2026 →](/changelog-may-2-24-2026) ## 2026-05-27 - More reliable sports discovery Sports and esports discovery now stays useful when Polymarket's primary event listing is incomplete or temporarily unavailable. What's improved: * `GET /v2/sports/leagues/{code}/games` resolves each public league code to its sports series, then applies `status`, `sort`, `direction`, `limit`, and `offset` consistently. * Responses include `series_id`, `source`, `fallback`, and `stale`, so clients can tell which source produced the result and whether a recent last-known-good response was used. * Known event variants such as exact-score, halftime-result, and more-markets pages are deduplicated in favor of the canonical game. * `GET /v2/sports/search` can fall back to alternate Polymarket event discovery instead of returning an upstream `502` immediately. * `GET /v2/sports/games/{slug}/history` now defaults to the full available history when no interval or timestamp range is supplied. * `GET /v2/sports/live` can supplement a partial sports summary with league-level event data instead of returning mostly empty arrays. If all live event sources are unavailable, the league-games route may return a recent response with `stale: true` for up to 12 hours. Docs: [Sports Markets](/api-reference/sports/sports-markets) *** ## 2026-05-27 - One-month USDC checkout Logged-in customers can buy one month of polynode access with USDC directly from the pricing page. What's new: * Starter, Growth, and Enterprise pricing cards offer a `Pay 1 month with USDC` option alongside normal card subscriptions. * USDC purchases are one-time 30-day access grants, not recurring subscriptions. * A later USDC purchase extends access from the end of the customer's current USDC period rather than shortening or replacing it. * Customers with an active card subscription are protected from accidental double payment. Trialing or past-due card users can switch to one-month USDC access. * Existing card checkout, account login, API keys, and plan entitlements continue to work as before. Stripe Checkout supports USDC on this path, not USDT. *** ## 2026-05-27 - V3 wallet P\&L alignment, fees, rebates, rewards, and PolyUSD flows Updated V3 wallet accounting surfaces. What's new: * Default/all-time `GET /v3/wallets/{address}/pnl/events` now returns a single all-time bucket so it agrees with `GET /v3/wallets/{address}/pnl`. * Explicit time-windowed P\&L events (`period`, `after`, or `before`) return realized P\&L buckets and ignore timestamp-0 artifacts. * Added `GET /v3/wallets/{address}/fees-paid` for fee-bearing wallet fills. * Added `GET /v3/wallets/{address}/polyusd-flows` for wallet PolyUSD deposits and withdrawals. * Added `GET /v3/wallets/{address}/rebates` for maker rebates. * Added public reward-market configuration at `GET /v3/rewards/markets` and `GET /v3/rewards/markets/{condition_id}`. Notes: * Fees paid and maker rebates are intentionally separate surfaces. LP reward market configuration is public; per-wallet earned LP rewards require authenticated Polymarket data and are not exposed as an arbitrary-wallet lookup in the public docs. * `GET /v3/wallets/{address}/activity` remains the conditional-token activity feed; PolyUSD deposits and withdrawals now live in the separate wallet PolyUSD flows endpoint. *** ## 2026-05-26 - Webhooks beta: first observed position opens Added `position_status_change` support for watched-wallet CTF position opens and exits. What's new: * `position_status_change` now detects first observed `none` to `open` transitions for watched wallets. * Existing positions are established as the wallet's baseline when it is first watched, so future transitions are emitted without replaying historical opens. * Adding another watched wallet does not replay source activity from before that wallet's own baseline. * Payloads include `previous_amount`, `new_amount`, `delta_amount`, `transfer_amount`, `source`, `source_event_id`, block and transaction fields, and market enrichment. * Filters include `wallet_addresses`, `token_ids`, `condition_ids`, `event_slugs`, `tags`, `status_from`, and `status_to`. Beta requirement: `wallet_addresses` is required. Unfiltered global position-status webhooks are not enabled. Docs: [`position_status_change`](/webhooks/events/position-status-change) *** ## 2026-05-26 - Polymarket Profiles API Added a paid-plan API for apps that want users to create or change a Polymarket username from a user-owned EOA without sharing private keys or long-lived Polymarket credentials. New endpoints: * `GET /v3/polymarket/profiles/username-available` checks a requested username. Local format is 3-32 letters, numbers, or underscores; Polymarket remains the final authority. * `POST /v3/polymarket/profiles/username/challenge` returns the Polymarket sign-in message and polynode consent typed data for the user's wallet. Challenges expire after 10 minutes. * `POST /v3/polymarket/profiles/username/complete` verifies both signatures and completes the profile or username action. * `GET /v3/polymarket/profiles/{address}` returns normalized public profile information. The challenge and completion calls belong on your backend and must use the same polynode API key. Browser clients only sign the returned payloads; they should never receive your API key or send a private key to polynode. Docs: [Polymarket Profiles](/api-reference/polymarket-profiles/overview) *** ## 2026-05-26 - TypeScript SDK v0.10.13: V3 parity, resolver, and profile helpers Released a TypeScript SDK parity update for the current REST API surface. What's new: * `pn.v3` namespace for the V3 historical data API while preserving existing top-level SDK behavior. * Typed V3 methods for wallet summaries, wallet P\&L, P\&L events, wallet trades, wallet positions, global trades, global positions, market search, market price, market trades, market positions, leaderboard, tags, builders, builder trades, fees, resolutions, conditions, and token info. * Builder trade filters in the SDK: `tokenId`, `conditionId`, `marketSlug`, `eventSlug`, `side`, `category`, `tagSlug`, `minAmount`, `after`, `before`, `limit`, and `offset`. * `pn.resolve(query)` for wallet, EOA, or username resolution, returning `{ safe, eoa, username, type }`. * Fully typed `pn.walletOnchainPositions()` responses, including market metadata, status, price, P\&L, and lifecycle timestamps. * V3 Polymarket profile helpers: `polymarketUsernameAvailable`, `createPolymarketUsernameChallenge`, `completePolymarketUsername`, and `polymarketProfile`. Existing `pn.market()`, `pn.wallet()`, `pn.leaderboard()`, and other top-level methods keep their historical paths and response shapes. Upgrade: ```bash theme={null} npm install polynode-sdk@0.10.13 ``` Docs: [TypeScript V3 Data and Profiles](/sdks/ts/v3-data) *** ## 2026-05-25 - Rust SDK v0.13.5 deposit-wallet onboarding fix Released `polynode` v0.13.5 for Rust integrations using V2 deposit wallets and `POLY_1271` signatures. What's fixed: * `ensure_ready()` recognizes an already-deployed deposit wallet from its onchain contract state instead of re-entering a failed deployment loop. * Deposit-wallet approval batches contain only the supported V2 pUSD and Conditional Tokens approvals. * Nested approval batches use the correct EIP-712 encoding and normalized wallet signature format. * After setup, the SDK refreshes the V2 CLOB balance and allowance state for both new and already-deployed deposit wallets. * Orders continue to use the deposit wallet as maker, the owner EOA as signer, and signature type `3` (`POLY_1271`). Upgrade: ```toml theme={null} polynode = { version = "0.13.5", features = ["trading"] } ``` *** ## 2026-05-25 - Sports and esports API suite Added a game-centered API for discovering Polymarket sports markets, current prices, price history, and WebSocket subscription targets. New and expanded routes include: * `GET /v2/sports/leagues`, `/v2/sports/live`, and `/v2/sports/market-types` for discovery and overview data. * `GET /v2/sports/leagues/{league}/teams` and `/v2/sports/leagues/{league}/games` for league-specific coverage. * `GET /v2/sports/games/{slug}` for normalized game and market details. * `GET /v2/sports/games/{slug}/state` for one object containing metadata, score fields, markets, current prices, and an orderbook subscription payload. * `GET /v2/sports/games/{slug}/prices` and `/history` for current CLOB price data and batch token history. * `GET /v2/sports/games/{slug}/context` for generated matchup, injury, lineup, news, social, or market queries with optional game state. * `GET /v2/sports/search?q={query}` for sports event and team search. Game-state requests price up to 200 tokens. Batch history includes up to 20 tokens per request. Live orderbook updates use the WebSocket target and token IDs returned by the response. Docs: [Sports Markets](/api-reference/sports/sports-markets) *** ## 2026-05-25 - Online Search API beta Added `GET /v2/search/online` for low-volume web context and market research. The endpoint returns normalized organic results with title, URL, domain, snippet, source engines, score, category, and optional publication time. It supports: * `max_results`, default `10` and maximum `20` * comma-separated `engines` * `language`, default `en-US` * `time_range=day|week|month|year` * `safe_search=0|1|2` * `cache_ttl_seconds`, default `600` and maximum `3600` The beta has an additional limit of 3 requests per 10 seconds per API key. Results are best-effort and may be partial or unavailable when public search providers throttle or fail. Docs: [Online Search API](/api-reference/search-online) *** ## 2026-05-25 - Public plan-limit conventions clarified Consolidated the public limits into one plan table and separated Event WebSocket limits from Orderbook WebSocket limits. At the time of this release: * REST limits were 60 requests/minute on Free, 600 on Starter, 3,000 on Growth, and custom on Enterprise. * Event WebSocket and Orderbook WebSocket connection limits were each 1 on Free, 10 on Starter, 50 on Growth, and unlimited on Enterprise. * A subscription could contain up to 10,000 filter items; paid plans had unlimited session time and unlimited orderbook market subscriptions. * API-key allowances were 1 on Free, 3 on Starter, 10 on Growth, and 25 on Enterprise. * Expensive endpoints could still carry endpoint-specific caps or plan requirements in addition to the plan's main REST allowance. These are historical limits. See [Rate Limits](/guides/rate-limits) for the current contract. *** ## 2026-05-25 - Polygon RPC endpoint restored `https://rpc.polynode.dev` returned to service for authenticated Polygon JSON-RPC requests. The endpoint again served live chain reads such as `eth_chainId` and `eth_blockNumber` using the existing request shape and API-key authentication. No client change was required. Docs: [Polygon RPC](/rpc/overview) # API Reference Source: https://docs.polynode.dev/charts/api-reference Complete API documentation for Chart, Series, TimeScale, PriceScale, and Orderbook # API Reference ## createChart ```typescript theme={null} import { createChart } from 'polynode-charts' const chart = createChart(container, options?) ``` | Parameter | Type | Description | | - | - | - | | `container` | `HTMLElement \| string` | DOM element or CSS selector | | `options` | `ChartOptions` | Optional configuration | ### ChartOptions ```typescript theme={null} interface ChartOptions { width?: number // fixed width (px) height?: number // fixed height (px) autoSize?: boolean // auto-resize to container (default: true) layout?: LayoutOptions grid?: GridOptions crosshair?: CrosshairOptions timeScale?: TimeScaleOptions rightPriceScale?: PriceScaleOptions } ``` ### LayoutOptions ```typescript theme={null} interface LayoutOptions { background?: string // default: '#080d16' textColor?: string // default: '#556' fontFamily?: string // default: '"SF Mono", "Fira Code", monospace' fontSize?: number // default: 10 } ``` ### GridOptions ```typescript theme={null} interface GridOptions { vertLines?: { color?: string; visible?: boolean } horzLines?: { color?: string; visible?: boolean } } ``` ### PriceScaleOptions ```typescript theme={null} interface PriceScaleOptions { mode?: 'normal' | 'probability' // 'probability' clamps axis to 0-100% autoScale?: boolean scaleMargins?: { top?: number; bottom?: number } } ``` *** ## Chart ### Series Methods ```typescript theme={null} chart.addCandleSeries(opts?: CandleSeriesOptions): CandleSeries chart.addLineSeries(opts?: LineSeriesOptions): LineSeries chart.addAreaSeries(opts?: AreaSeriesOptions): AreaSeries chart.addVolumeSeries(opts?: VolumeSeriesOptions): VolumeSeries chart.removeSeries(series): void ``` ### Scale Access ```typescript theme={null} chart.timeScale(): TimeScale ``` ### Events ```typescript theme={null} // Subscribe to crosshair movement — returns unsubscribe function const unsub = chart.subscribeCrosshairMove((params) => { console.log(params.time, params.point) }) unsub() // stop listening // Subscribe to chart clicks const unsub2 = chart.subscribeClick((params) => { console.log('Clicked at time:', params.time) }) ``` **CrosshairMoveParams:** ```typescript theme={null} interface CrosshairMoveParams { time: number | null point: { x: number; y: number } | null seriesData: Map } ``` **ClickParams:** ```typescript theme={null} interface ClickParams { time: number | null point: { x: number; y: number } } ``` ### Utility ```typescript theme={null} chart.getContainer(): HTMLElement // returns the chart's parent DOM element ``` ### Lifecycle ```typescript theme={null} chart.resize(width, height): void // manual resize chart.remove(): void // cleanup everything ``` *** ## Series All series share these common methods: ```typescript theme={null} series.setData(data[]): void // replace all data series.update(item): void // append or update last point series.setMaxLength(n): void // cap buffer size (drops oldest) ``` ### CandleSeries ```typescript theme={null} const series = chart.addCandleSeries({ upColor: '#22c55e', downColor: '#ef4444', wickUpColor: '#22c55e', // optional, defaults to upColor wickDownColor: '#ef4444', // optional, defaults to downColor borderVisible: true, }) ``` **Data shape:** ```typescript theme={null} interface OhlcData { time: number // epoch milliseconds open: number high: number low: number close: number volume?: number } ``` ### LineSeries ```typescript theme={null} const series = chart.addLineSeries({ color: '#f7931a', lineWidth: 2, smooth: true, // bezier curve interpolation showDot: true, // pulsing dot at last point dotColor: '#f7931a', }) ``` **Data shape:** ```typescript theme={null} interface LineData { time: number // epoch milliseconds value: number } ``` **Live mode:** ```typescript theme={null} series.setLive(true) // phantom point + smooth lerp series.isLive() // check live state ``` **Price line overlay:** ```typescript theme={null} series.setPriceLine(72822.50, { color: '#3b82f6', dash: [6, 4], label: 'PRICE TO BEAT', labelColor: '#fff', }) series.clearPriceLine() series.getPriceLine() // returns PriceLineConfig | null ``` The price line renders as a dashed horizontal line across the chart with a label on the left and a price badge on the right axis. The Y-axis auto-expands to keep the price line visible. ### AreaSeries Extends `LineSeries` with a gradient fill beneath the line. ```typescript theme={null} const series = chart.addAreaSeries({ color: '#6ea8fe', // line color topColor: '#6ea8fe33', // gradient top bottomColor: '#6ea8fe00', // gradient bottom (transparent) lineWidth: 2, smooth: true, }) ``` Uses the same `LineData` shape as LineSeries. ### VolumeSeries Automatically creates a separate pane at 22% of chart height. ```typescript theme={null} const series = chart.addVolumeSeries({ upColor: 'rgba(34, 197, 94, 0.4)', downColor: 'rgba(239, 68, 68, 0.4)', opacity: 0.4, }) ``` **Data shape:** ```typescript theme={null} interface VolumeData { time: number value: number color?: string // override per-bar color } ``` *** ## TimeScale ```typescript theme={null} const ts = chart.timeScale() ``` | Method | Description | | - | - | | `goLive()` | Enable live mode. Auto-scrolls to newest data. Snaps back after 4s idle. | | `isLive()` | Returns `true` if in live mode | | `setVisibleRange(start, end)` | Set visible time range (epoch ms) | | `animateToRange(start, end)` | Animated zoom to range | | `zoomAt(factor, mouseXFrac)` | Zoom around a point (scroll wheel) | | `getVisibleStart()` | Left edge time (epoch ms) | | `getVisibleEnd()` | Right edge time (epoch ms) | | `getVisibleWindow()` | Duration of visible range (ms) | **Live mode behavior:** When live, the chart auto-scrolls to show the latest data. If the user pans or zooms away, the chart remembers and snaps back to live after 4 seconds of idle. This gives users freedom to explore history while keeping the default view current. *** ## Orderbook ```typescript theme={null} import { createOrderbook } from 'polynode-charts' const ob = createOrderbook('#orderbook', { colorBid: '#22c55e', colorAsk: '#ef4444', depthFillOpacity: 0.08, labelCount: 8, }) ob.update({ bids: [{ price: 0.54, size: 1200 }, { price: 0.53, size: 800 }], asks: [{ price: 0.55, size: 900 }, { price: 0.56, size: 1500 }], }) ``` ### OrderbookOptions ```typescript theme={null} interface OrderbookOptions { colorBid?: string // default: '#22c55e' colorAsk?: string // default: '#ef4444' depthFillOpacity?: number // default: 0.08 labelCount?: number // price labels on axis background?: string textColor?: string } ``` ### BookData ```typescript theme={null} interface BookData { bids: PriceLevel[] asks: PriceLevel[] } interface PriceLevel { price: number size: number } ``` | Method | Description | | - | - | | `ob.update(data)` | Replace book data and re-render | | `ob.destroy()` | Remove DOM and stop rendering | *** ## createShortFormOverlay One-liner to add Polymarket short-form price-to-beat overlays to any live chart. Adds interval buttons, auto-discovers markets, draws a dashed price-to-beat line, and shows live odds with a countdown timer. ```typescript theme={null} import { createChart, createShortFormOverlay } from 'polynode-charts' const chart = createChart('#btc', { layout: { background: '#0c1220' } }) const series = chart.addLineSeries({ color: '#f7931a', showDot: true }) series.setLive(true) chart.timeScale().goLive() // One line: buttons + discovery + price line + odds + countdown const overlay = createShortFormOverlay(chart, series, { coin: 'btc' }) ``` ### ShortFormOverlayOptions ```typescript theme={null} interface ShortFormOverlayOptions { coin: ShortFormCoin // 'btc' | 'eth' | 'sol' | 'xrp' | 'doge' | 'hype' intervals?: ShortFormInterval[] // default: ['5m', '15m', '1h'] defaultInterval?: ShortFormInterval // if set, auto-starts on creation onRotation?: (event: RotationEvent) => void // callback on each poll/rotation } ``` ### ShortFormOverlay (return type) | Method | Description | | - | - | | `overlay.setInterval('15m')` | Switch to a different interval | | `overlay.stop()` | Stop polling, remove price line, clear display | | `overlay.destroy()` | Full cleanup: stop + remove DOM | | `overlay.getActiveInterval()` | Returns current interval or `null` | ### What it renders * **Interval buttons** (5m, 15m, 1h) — click to toggle on/off * **Price-to-beat line** — horizontal dashed blue line on the chart * **Odds display** — "24% up · 77% down · 1m35s" with live countdown * **Auto-rotation** — discovers the next market window when the current one expires *** ## PolynodeProvider — MarketInfo The `outcome` field tells you which side of a binary market this token represents. ```typescript theme={null} interface MarketInfo { token_id: string question: string // the market question (e.g. "US x Iran ceasefire by April 7?") slug: string image: string last_price: number volume_24h: number outcomes: string[] // e.g. ['Yes', 'No'] outcome: string // which outcome THIS token is ('Yes' or 'No') condition_id?: string neg_risk?: boolean // true for multi-outcome events (elections, championships) } ``` The `neg_risk` field indicates a multi-outcome event on Polymarket. When `provider.event()` searches for multi-outcome markets, it prioritizes `neg_risk: true` markets to find genuine events (elections, World Cup, NBA Finals) rather than binary matches. # Data Providers Source: https://docs.polynode.dev/charts/data-providers Built-in providers for polynode REST API, orderbook streaming, and short-form market discovery # Data Providers The Charts SDK includes three data providers that connect to polynode endpoints. All are optional. The chart itself works with any data source. ## PolynodeProvider Full-featured REST provider for market data, candles, search, events, and multi-outcome charts. ```typescript theme={null} import { PolynodeProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_live_...', baseUrl: 'https://api.polynode.dev', // default }) ``` ### Top Markets ```typescript theme={null} const markets = await provider.markets(10) // Returns MarketInfo[] sorted by 24h volume ``` **Response:** ```json theme={null} [ { "token_id": "82855088893985825781350...", "question": "US x Iran ceasefire by April 7?", "slug": "us-x-iran-ceasefire-by-april-7", "image": "https://polymarket-upload.s3...", "last_price": 0.999, "volume_24h": 19542289.32, "outcomes": ["Yes", "No"], "condition_id": "0x4c5701bc..." } ] ``` ### Search Markets ```typescript theme={null} const results = await provider.search('bitcoin', 5) // Returns MarketInfo[] matching query, sorted by volume ``` ### Fetch Candles ```typescript theme={null} const candles = await provider.candles(tokenId, '1h') // Returns OhlcData[] — ready for series.setData() const series = chart.addCandleSeries() series.setData(candles) ``` The first call fetches trades and caches them locally. After that, switching resolution is instant — the SDK rebuilds candles client-side from the cached trades. **Supported resolutions:** `'1m'`, `'5m'`, `'15m'`, `'1h'`, `'4h'`, `'1d'` **Options:** ```typescript theme={null} // Fetch more history (default: 30 days) const candles = await provider.candles(tokenId, '1h', { days: 90 }) ``` **Response shape (`OhlcData[]`):** ```json theme={null} [ { "time": 1775826000000, "open": 0.54, "high": 0.55, "low": 0.52, "close": 0.54, "volume": 1200 } ] ``` ### Price History (Line/Area Charts) For simple `{time, value}` points (faster than candles — one HTTP call, no pagination): ```typescript theme={null} const history = await provider.priceHistory(tokenId, '7d') // Returns LineData[] const series = chart.addAreaSeries({ color: '#22c55e' }) series.setData(history) ``` **Supported ranges:** `'1h'`, `'6h'`, `'1d'`, `'7d'`, `'30d'`, `'all'` > [!NOTE] > > `candles()` fetches trades and builds OHLCV locally. Best for candlestick charts where you need resolution switching. > > `priceHistory()` hits the CLOB prices-history endpoint directly. Best for line/area charts where you just need price points over time. ### Get Event (Multi-Outcome) ```typescript theme={null} const event = await provider.event('presidential election') ``` Returns `EventInfo | null`. The method searches your loaded markets, groups by shared question pattern, and returns all outcomes with prices and colors. **Response:** ```json theme={null} { "question": "the 2028 US Presidential Election", "slug": "presidential-election-winner-2028", "condition_id": "0x...", "image": "https://...", "volume_24h": 2847291, "outcomes": [ { "name": "Gavin Newsom", "token_id": "98250...", "price": 0.159, "color": "#4378FF" }, { "name": "Kamala Harris", "token_id": "70663...", "price": 0.032, "color": "#22c55e" }, { "name": "Ron DeSantis", "token_id": "10448...", "price": 0.021, "color": "#FDC503" } ] } ``` Colors are assigned automatically from `OUTCOME_COLORS` (a 20-color palette). ### Multi-Outcome Price History (Batch) Fetch price history for all outcomes in parallel: ```typescript theme={null} const event = await provider.event('presidential election') const priceMap = await provider.outcomePrices(event.outcomes, '7d', { maxOutcomes: 5 }) for (const outcome of event.outcomes) { const data = priceMap.get(outcome.token_id) if (!data) continue const series = chart.addLineSeries({ color: outcome.color }) series.setData(data) } ``` `outcomePrices()` is much faster than fetching candles per outcome — one HTTP call each, no trade pagination. For candlestick data per outcome, use `outcomeCandles()` instead: ```typescript theme={null} const candleMap = await provider.outcomeCandles(event.outcomes, '4h', { days: 30, maxOutcomes: 5 }) ``` ### Orderbook Snapshot ```typescript theme={null} const book = await provider.book(tokenId) // Returns { bids: PriceLevel[], asks: PriceLevel[] } ``` ### Poll for Live Updates ```typescript theme={null} const stop = provider.pollPrices(tokenId, (point) => { series.update(point) // { time, value } }, { intervalMs: 5000 }) // Stop polling stop() ``` For multi-outcome polling: ```typescript theme={null} const stop = provider.pollOutcomePrices(event.outcomes, (tokenId, point) => { seriesMap.get(tokenId)?.update(point) }, { intervalMs: 10000, maxOutcomes: 5 }) ``` ### Market Resolution All methods accept flexible market identifiers: * **token\_id** — direct lookup (fastest) * **slug** — matched against loaded markets (e.g. `'bitcoin-above-64k'`) * **condition\_id** — hex string starting with `0x` ### Clear Cache ```typescript theme={null} provider.clearCache() // clears trade cache for all markets ``` ### MarketInfo ```typescript theme={null} interface MarketInfo { token_id: string question: string slug: string image: string last_price: number // 0-1 volume_24h: number // USD outcomes: string[] // ["Yes", "No"] or ["Up", "Down"] condition_id?: string } ``` *** ## PolynodeOBProvider WebSocket-based orderbook streaming with automatic zlib decompression (uses the native `DecompressionStream` API, no dependencies). ```typescript theme={null} import { PolynodeOBProvider } from 'polynode-charts' const ob = new PolynodeOBProvider({ wsUrl: 'wss://ob.polynode.dev/ws', // default }) ob.subscribe(tokenId, (book) => { orderbook.update(book) // pass to Orderbook renderer }) ``` ### Methods | Method | Description | | - | - | | `subscribe(tokenId, callback)` | Subscribe to live book updates | | `unsubscribe(tokenId)` | Stop receiving updates for a token | | `connect()` | Manually connect (auto-connects on first subscribe) | | `disconnect()` | Close WebSocket and stop reconnecting | The provider handles reconnection automatically with exponential backoff (1s to 30s). ### Message Types The provider processes three message types from the orderbook WebSocket: * `snapshot_batch` — initial full book for all subscribed tokens * `book_snapshot` — full book replacement for a single token * `book_update` — incremental update (add/remove/change levels) All are normalized to `BookData` before calling your callback. *** ## ShortFormProvider Discovers short-form crypto markets (5-minute, 15-minute, and hourly up/down markets) and provides live odds rotation. HTTP-only, no WebSocket required. ```typescript theme={null} import { ShortFormProvider } from 'polynode-charts' const sf = new ShortFormProvider() ``` ### One-Shot Discovery ```typescript theme={null} const market = await sf.discover('btc', '15m') if (market) { console.log(market.priceToBeat) // 72822.50 console.log(market.upOdds) // 0.62 console.log(market.downOdds) // 0.38 console.log(market.windowEnd) // unix timestamp } ``` ### Auto-Rotation with Live Odds `startRotation()` discovers the current window, emits immediately, then polls for updated odds every second and re-discovers at each window boundary. ```typescript theme={null} const stop = sf.startRotation('btc', '15m', (event) => { // Called on discovery + every odds update series.setPriceLine(event.market.priceToBeat!, { color: '#3b82f6', label: 'PRICE TO BEAT', }) console.log(`${(event.market.upOdds * 100).toFixed(0)}% up`) console.log(`${event.timeRemaining}s remaining`) }, { pollMs: 1000 }) // Stop rotation and polling stop() ``` ### Supported Coins | Key | Coin | | - | - | | `'btc'` | Bitcoin | | `'eth'` | Ethereum | | `'sol'` | Solana | | `'xrp'` | XRP | | `'doge'` | Dogecoin | | `'hype'` | Hype | | `'bnb'` | BNB | ### Supported Intervals | Key | Window | | - | - | | `'5m'` | 5 minutes | | `'15m'` | 15 minutes | | `'1h'` | 1 hour | ### ShortFormMarket ```typescript theme={null} interface ShortFormMarket { coin: ShortFormCoin slug: string title: string conditionId: string windowStart: number // unix seconds windowEnd: number // unix seconds outcomes: string[] outcomePrices: number[] clobTokenIds: string[] upOdds: number // 0-1 downOdds: number // 0-1 liquidity: number volume24h: number priceToBeat: number | null } ``` ### RotationEvent ```typescript theme={null} interface RotationEvent { interval: ShortFormInterval market: ShortFormMarket windowStart: number // unix seconds windowEnd: number // unix seconds timeRemaining: number // seconds until window closes } ``` ### Options ```typescript theme={null} const sf = new ShortFormProvider({ apiBaseUrl: 'https://api.polynode.dev', // default rotationBuffer: 3, // seconds after window end before re-discovering (default: 3) }) ``` # Examples Source: https://docs.polynode.dev/charts/examples Copy-paste examples for common chart setups # Examples ## Prediction Market — Yes/No Outcome ```typescript theme={null} import { createChart, PolynodeProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) const chart = createChart('#chart', { rightPriceScale: { mode: 'probability' }, }) const series = chart.addAreaSeries({ color: '#22c55e', topColor: '#22c55e22', bottomColor: '#22c55e00', smooth: true, }) const history = await provider.priceHistory(tokenId, '7d') series.setData(history) ``` The `probability` price scale mode clamps the Y-axis to 0-100% with appropriate tick marks. ## Multi-Outcome Event (e.g., Election) ```typescript theme={null} import { createChart, PolynodeProvider, OUTCOME_COLORS } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) const event = await provider.event('presidential election') const chart = createChart('#chart', { rightPriceScale: { mode: 'probability' }, }) // Fetch all outcome price histories in one call const priceMap = await provider.outcomePrices(event.outcomes, '7d', { maxOutcomes: 8 }) for (const outcome of event.outcomes) { const data = priceMap.get(outcome.token_id) if (!data || data.length === 0) continue const series = chart.addLineSeries({ color: outcome.color, lineWidth: 2, smooth: true, }) series.setData(data) } ``` `OUTCOME_COLORS` provides a 20-color palette optimized for dark backgrounds. Colors are auto-assigned by `provider.event()`. ## Candlestick + Volume ```typescript theme={null} import { createChart, PolynodeProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) const chart = createChart('#chart') const candles = chart.addCandleSeries({ upColor: '#22c55e', downColor: '#ef4444', }) const volume = chart.addVolumeSeries({ upColor: 'rgba(34, 197, 94, 0.3)', downColor: 'rgba(239, 68, 68, 0.3)', }) const data = await provider.candles(tokenId, '1h') candles.setData(data) // Volume is included in OhlcData when built from trades volume.setData(data.map(d => ({ time: d.time, value: d.volume || 0, color: d.close >= d.open ? '#22c55e66' : '#ef444466', }))) ``` ### Instant Resolution Switching After the first `candles()` call, trades are cached locally. Switching resolution rebuilds candles client-side with zero network calls: ```typescript theme={null} // First call fetches trades (~2s) await provider.candles(tokenId, '1h') // These are instant — trades are already cached await provider.candles(tokenId, '5m') await provider.candles(tokenId, '1d') ``` ## Live Crypto with Short-Form Overlay ```typescript theme={null} import { createChart, ShortFormProvider } from 'polynode-charts' const chart = createChart('#chart', { layout: { background: '#0c1220' }, }) const series = chart.addLineSeries({ color: '#f7931a', lineWidth: 2, smooth: true, showDot: true, dotColor: '#f7931a', }) series.setLive(true) series.setMaxLength(600) chart.timeScale().goLive() // WebSocket price feed const ws = new WebSocket('wss://ws.polynode.dev/ws?key=pn_...') ws.onopen = () => ws.send(JSON.stringify({ action: 'subscribe', type: 'chainlink' })) ws.onmessage = (e) => { const msg = JSON.parse(e.data) if (msg.type === 'price_feed' && msg.feed === 'BTC/USD') { series.update({ time: Date.now(), value: msg.data.price }) } } // Short-form price-to-beat overlay const sf = new ShortFormProvider() let stopRotation = null function setInterval(interval) { if (stopRotation) stopRotation() stopRotation = sf.startRotation('btc', interval, (event) => { const m = event.market if (m.priceToBeat !== null) { series.setPriceLine(m.priceToBeat, { color: '#3b82f6', label: 'PRICE TO BEAT', }) } updateUI({ upPct: (m.upOdds * 100).toFixed(0), downPct: (m.downOdds * 100).toFixed(0), timeRemaining: event.timeRemaining, }) }, { pollMs: 1000 }) } // Start with 15m interval setInterval('15m') ``` ## Interactive Crosshair ```typescript theme={null} const chart = createChart('#chart') const series = chart.addCandleSeries() series.setData(data) chart.subscribeCrosshairMove((params) => { if (!params.time) { tooltip.style.display = 'none' return } tooltip.style.display = 'block' tooltip.style.left = params.point.x + 'px' tooltip.style.top = params.point.y + 'px' tooltip.textContent = `Time: ${new Date(params.time).toLocaleString()}` }) ``` ## Orderbook with Depth Chart ```typescript theme={null} import { createOrderbook, PolynodeOBProvider } from 'polynode-charts' const ob = createOrderbook('#orderbook', { colorBid: '#22c55e', colorAsk: '#ef4444', depthFillOpacity: 0.08, labelCount: 8, }) const provider = new PolynodeOBProvider() provider.subscribe(tokenId, (book) => { ob.update(book) // Calculate spread const bestBid = book.bids[0]?.price || 0 const bestAsk = book.asks[0]?.price || 0 const spread = bestAsk - bestBid document.getElementById('spread').textContent = `Spread: ${(spread * 100).toFixed(1)}c` }) ``` ## Poll Multiple Outcomes ```typescript theme={null} import { createChart, PolynodeProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) const event = await provider.event('presidential election') const chart = createChart('#chart', { rightPriceScale: { mode: 'probability' }, }) // Load initial history const priceMap = await provider.outcomePrices(event.outcomes, '7d') const seriesMap = new Map() for (const outcome of event.outcomes) { const data = priceMap.get(outcome.token_id) if (!data) continue const series = chart.addLineSeries({ color: outcome.color, smooth: true }) series.setData(data) seriesMap.set(outcome.token_id, series) } // Poll for live updates const stop = provider.pollOutcomePrices(event.outcomes, (tokenId, point) => { seriesMap.get(tokenId)?.update(point) }, { intervalMs: 10000 }) ``` ## Responsive Chart The chart auto-sizes to its container by default. Just give the container a CSS height: ```html theme={null}
``` ```typescript theme={null} const chart = createChart('#chart') // Chart resizes automatically on window/container resize ``` For mobile, the chart handles touch events natively: single-finger drag to pan, pinch to zoom. No configuration needed. # Getting Started Source: https://docs.polynode.dev/charts/getting-started Create your first chart in under 5 minutes # Getting Started ## Installation ```bash theme={null} npm install polynode-charts ``` The package has **zero runtime dependencies**. It ships as ESM and CJS with full TypeScript declarations. ## Create a Chart Every chart needs a container element with a defined height. ```html theme={null}
``` ```typescript theme={null} import { createChart } from 'polynode-charts' const chart = createChart('#chart') ``` You can also pass an `HTMLElement` directly: ```typescript theme={null} const el = document.getElementById('chart') const chart = createChart(el) ``` ## Add a Series ```typescript theme={null} // Candlestick chart const candles = chart.addCandleSeries({ upColor: '#22c55e', downColor: '#ef4444', }) candles.setData([ { time: 1710000000000, open: 0.52, high: 0.55, low: 0.50, close: 0.54 }, { time: 1710003600000, open: 0.54, high: 0.58, low: 0.53, close: 0.57 }, ]) ``` ```typescript theme={null} // Line chart const line = chart.addLineSeries({ color: '#f7931a', lineWidth: 2, smooth: true, }) line.setData([ { time: 1710000000000, value: 72500 }, { time: 1710000001000, value: 72510 }, ]) ``` ## Chart Options ```typescript theme={null} const chart = createChart('#chart', { layout: { background: '#0a0e17', textColor: '#556', fontFamily: '"SF Mono", monospace', fontSize: 10, }, grid: { horzLines: { color: 'rgba(100, 120, 150, 0.06)' }, vertLines: { visible: false }, }, rightPriceScale: { mode: 'probability', // clamps axis to 0-100% }, }) ``` ## Live Streaming For real-time data, use `update()` instead of `setData()`: ```typescript theme={null} const series = chart.addLineSeries({ color: '#14f195', showDot: true, dotColor: '#14f195', }) // Enable live mode — smooth phantom point between ticks series.setLive(true) // Auto-scroll to latest data chart.timeScale().goLive() // Push updates as they arrive ws.onmessage = (e) => { const { price } = JSON.parse(e.data) series.update({ time: Date.now(), value: price }) } ``` In live mode, the chart adds a phantom leading point that lerps smoothly to the latest value, giving fluid motion even with infrequent ticks. A pulsing dot marks the current price. ## Max Data Length For streaming use cases, cap the data buffer to prevent memory growth: ```typescript theme={null} series.setMaxLength(600) // keep last 600 points (~10 min at 1/sec) ``` Older points are dropped from the front as new ones arrive. ## Volume Pane Adding a volume series automatically creates a second pane at 22% height: ```typescript theme={null} const volume = chart.addVolumeSeries({ upColor: 'rgba(34, 197, 94, 0.4)', downColor: 'rgba(239, 68, 68, 0.4)', }) volume.setData([ { time: 1710000000000, value: 15000, color: '#22c55e' }, { time: 1710003600000, value: 23000, color: '#ef4444' }, ]) ``` ## Cleanup ```typescript theme={null} chart.remove() // stops animation, detaches listeners, removes DOM ``` ## Next Steps * [API Reference](/charts/api-reference) — full Chart, Series, and Scale APIs * [Data Providers](/charts/data-providers) — connect to polynode REST, WebSocket, and short-form endpoints * [Live Streaming](/charts/live-streaming) — real-time crypto prices with price-to-beat overlays # Live Streaming Source: https://docs.polynode.dev/charts/live-streaming Real-time crypto price charts with price-to-beat overlays and live odds # Live Streaming This guide covers building a real-time crypto price chart with WebSocket streaming, live mode, and short-form market overlays. ## Basic Live Chart Connect a WebSocket feed to a line series with live mode enabled: ```typescript theme={null} import { createChart } from 'polynode-charts' const chart = createChart('#chart', { layout: { background: '#0c1220', textColor: '#556' }, grid: { horzLines: { color: 'rgba(100, 120, 150, 0.06)' }, vertLines: { visible: false }, }, }) const series = chart.addLineSeries({ color: '#f7931a', lineWidth: 2, smooth: true, showDot: true, dotColor: '#f7931a', }) // Live mode: smooth phantom point + auto-scroll series.setLive(true) series.setMaxLength(600) // ~10 min at 1/sec chart.timeScale().goLive() // Connect to price feed const ws = new WebSocket('wss://ws.polynode.dev/ws?key=pn_...') ws.onopen = () => { ws.send(JSON.stringify({ action: 'subscribe', type: 'chainlink' })) } ws.onmessage = (e) => { const msg = JSON.parse(e.data) if (msg.type === 'price_feed' && msg.feed === 'BTC/USD') { series.update({ time: Date.now(), value: msg.data.price }) } } ``` ## How Live Mode Works When `setLive(true)` is called: 1. **Phantom point** — a virtual leading data point is appended at `Date.now()` that smoothly lerps toward the latest real value. This creates fluid animation even if ticks arrive only once per second. 2. **Pulsing dot** — a glowing dot marks the current price at the phantom point, pulsing with a subtle sine-wave animation. 3. **Auto-scroll** — `goLive()` on the time scale keeps the visible range pinned to the latest data. If the user pans away, the chart returns to live after 4 seconds of inactivity. 4. **Continuous redraw** — the animation frame loop redraws the data layer every frame (for lerp + pulse), but background and overlay layers only redraw when dirty. ## Price-to-Beat Overlay Overlay a horizontal dashed line showing the opening price for a short-form market window: ```typescript theme={null} import { ShortFormProvider } from 'polynode-charts' const sf = new ShortFormProvider() const stop = sf.startRotation('btc', '15m', (event) => { const m = event.market // Draw dashed price line if (m.priceToBeat !== null) { series.setPriceLine(m.priceToBeat, { color: '#3b82f6', label: 'PRICE TO BEAT', }) } // Display odds const upPct = (m.upOdds * 100).toFixed(0) const downPct = (m.downOdds * 100).toFixed(0) document.getElementById('odds').textContent = `${upPct}% up · ${downPct}% down · ${event.timeRemaining}s` }, { pollMs: 1000 }) ``` The price line automatically stays visible. The Y-axis expands to include the price-to-beat value even if it's outside the current data range. ### What Happens at Window Boundaries When a short-form window expires (e.g., the 15-minute window closes): 1. `startRotation` waits a buffer period (default 3 seconds) 2. Discovers the next window's market via the gamma proxy 3. Fetches the new price-to-beat from the crypto-price endpoint 4. Calls your `onRotation` callback with the new market 5. Resumes polling odds every `pollMs` for the new window No manual intervention needed. The rotation handles the full lifecycle. ## Multiple Coins Run independent charts for multiple coins, each with their own series and short-form rotation: ```typescript theme={null} const coins = [ { coin: 'btc', feed: 'BTC/USD', color: '#f7931a' }, { coin: 'eth', feed: 'ETH/USD', color: '#627eea' }, { coin: 'sol', feed: 'SOL/USD', color: '#14f195' }, ] for (const { coin, feed, color } of coins) { const chart = createChart(`#chart-${coin}`, { /* ... */ }) const series = chart.addLineSeries({ color, smooth: true, showDot: true, dotColor: color }) series.setLive(true) series.setMaxLength(600) chart.timeScale().goLive() // Price updates from WebSocket ws.onmessage = (e) => { const msg = JSON.parse(e.data) if (msg.type === 'price_feed' && msg.feed === feed) { series.update({ time: Date.now(), value: msg.data.price }) } } // Independent short-form rotation per coin const sf = new ShortFormProvider() sf.startRotation(coin, '15m', (event) => { if (event.market.priceToBeat !== null) { series.setPriceLine(event.market.priceToBeat, { color: '#3b82f6', label: 'PRICE TO BEAT', }) } }) } ``` ## Orderbook + Chart Side-by-Side Combine a candle chart with a live orderbook: ```typescript theme={null} import { createChart, createOrderbook, PolynodeProvider, PolynodeOBProvider } from 'polynode-charts' const provider = new PolynodeProvider({ apiKey: 'pn_...' }) // Chart const chart = createChart('#chart') const series = chart.addCandleSeries() const candles = await provider.getCandles(tokenId, '1h') series.setData(candles) // Orderbook const ob = createOrderbook('#orderbook', { colorBid: '#22c55e', colorAsk: '#ef4444', }) const obProvider = new PolynodeOBProvider() obProvider.subscribe(tokenId, (book) => ob.update(book)) ``` ## Reconnection Both the WebSocket feed and the OB provider handle reconnection automatically with exponential backoff (1s up to 30s). No special handling is needed in your code. For the `ShortFormProvider`, discovery retries 3 times with a 2-second delay between attempts before giving up on a window. The rotation timer then retries at the next buffer interval. # Charts SDK Source: https://docs.polynode.dev/charts/overview High-performance Canvas 2D charting library built for prediction markets and live crypto prices # polynode-charts A zero-dependency **browser** charting library purpose-built for prediction market data and real-time crypto price streams. Renders on Canvas 2D with a 60fps animation loop, triple-layer dirty-flag rendering, and native touch/pinch support. > [!NOTE] > > This is the **visualization** companion to `polynode-sdk`. The data SDK (`polynode-sdk`) handles REST API calls, WebSocket streaming, trading, and caching in Node.js. This package (`polynode-charts`) renders that data as interactive charts in the browser. They are separate npm packages. > > ```bash theme={null} > # Data layer (Node.js / server) > npm install polynode-sdk > > # Visualization layer (browser) > npm install polynode-charts > ``` > > `polynode-charts` also includes its own built-in data providers (REST, WebSocket, short-form discovery) so you can use it standalone without `polynode-sdk` if you only need charts. ## Features * **Candlestick, line, area, and volume** series types * **Live streaming mode** with smooth lerp animation between ticks * **Orderbook visualization** with depth chart and spread display * **Short-form market overlays** with price-to-beat lines and live odds * **Multi-outcome support** for prediction markets (up to 20+ outcomes) * **Auto-scaling** price axis with probability mode (0-100%) * **Interactive** pan, zoom, scroll, pinch-to-zoom on mobile * **Crosshair** with snap-to-candle and OHLC tooltip ## Install ```bash theme={null} npm install polynode-charts ``` ## Quick Start ```typescript theme={null} import { createChart } from 'polynode-charts' const chart = createChart('#my-chart', { layout: { background: '#0a0e17', textColor: '#556' }, }) const series = chart.addCandleSeries({ upColor: '#22c55e', downColor: '#ef4444', }) series.setData([ { time: 1710000000000, open: 0.52, high: 0.55, low: 0.50, close: 0.54 }, { time: 1710003600000, open: 0.54, high: 0.58, low: 0.53, close: 0.57 }, // ... ]) ``` ## Architecture The chart uses a triple-layer canvas stack per pane: | Layer | Z-Index | Content | | - | - | - | | Background | 1 | Grid lines, axis labels | | Data | 2 | Series (candles, lines, areas, volumes) | | Overlay | 3 | Crosshair, tooltips, interaction capture | Each layer only redraws when its dirty flag is set, keeping GPU load minimal even at 60fps. The animation loop runs continuously for live mode (smooth phantom points, pulsing dots) but skips unchanged layers. ## Series Types | Type | Method | Data Shape | Use Case | | - | - | - | - | | Candle | `addCandleSeries()` | `OhlcData` | Market price history | | Line | `addLineSeries()` | `LineData` | Live crypto prices, single-outcome tracking | | Area | `addAreaSeries()` | `LineData` | Probability trends with gradient fill | | Volume | `addVolumeSeries()` | `VolumeData` | Trading volume bars (auto-paned at 22%) | ## Data Providers The SDK includes three built-in data providers for polynode endpoints: * **PolynodeProvider** — REST + polling for market candles, search, events, multi-outcome charts * **PolynodeOBProvider** — WebSocket orderbook streaming with zlib decompression * **ShortFormProvider** — Short-form crypto market discovery with live odds rotation All providers are optional. The chart itself is provider-agnostic and works with any data source. ## Live Demo See the full interactive demo at [charts.polynode.dev](https://charts.polynode.dev). # CLI Source: https://docs.polynode.dev/cli/overview Bloomberg terminal for prediction markets. Real-time TUI dashboards and JSON output for agents. The PolyNode CLI (`pn`) gives you instant access to every PolyNode feature from the terminal. Watch live settlements scroll by, view full-depth orderbooks with bid/ask visualization, track short-form crypto markets with countdown timers, and monitor Chainlink price feeds. Every command also supports `--json` for programmatic use by agents and scripts. ## Install ```bash theme={null} # From source (requires Rust) cargo install --git https://github.com/joinQuantish/polynode-cli ``` The binary is called `pn`. ## Authentication The CLI resolves your API key in this order: 1. `--key` flag: `pn markets --key pn_live_...` 2. `POLYNODE_API_KEY` environment variable 3. `~/.config/polynode/key` file (auto-saved when you run `pn key create`) ```bash theme={null} # Generate a free API key (auto-saves to ~/.config/polynode/key) pn key create ``` ## Commands ![pn --help](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-help.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=35587fa1d263c6a64dd684cb5842d5ee) | Command | Type | Description | | - | - | - | | `pn key create [name]` | REST | Generate a new API key | | `pn status` | REST | System status and metrics | | `pn markets [--count N]` | REST | Top markets by 24h volume | | `pn search ` | REST | Full-text market search | | `pn market ` | REST | Single market detail | | `pn stream [type]` | Live TUI | Scrolling real-time event feed | | `pn orderbook ` | Live TUI | Full-screen bid/ask depth view | | `pn short-form <5m\|15m\|1h>` | Live TUI | Multi-coin crypto dashboard | | `pn chainlink` | Live TUI | Live Chainlink price feeds | Every command supports `--json` for machine-readable output. *** ## Static Commands ### Markets View the top markets by 24h trading volume. ```bash theme={null} pn markets --count 10 ``` ![pn markets](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-markets.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=3c55f696f8589a0eef010e05032fb2ed) ### Search Full-text search across all market questions. ```bash theme={null} pn search "bitcoin" ``` ![pn search bitcoin](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-search.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=cd69dd169fa26d6ebbf902f85513b66a) ### Status System health, connection count, and state metrics. ```bash theme={null} pn status ``` ![pn status](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-status.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=cd457f79f8745ff6a0b63fadd4b8e63b) ### Market Detail Look up a single market by slug or token ID. ```bash theme={null} pn market will-bitcoin-reach-150k-in-march-2026 ``` *** ## Live TUI Commands Live commands open a full-screen terminal UI that updates in real-time. Press `q` or `Esc` to exit. ### Stream Watch every settlement, trade, block, or oracle event as it happens. ```bash theme={null} # All settlements pn stream settlements # Large trades only (> $100) pn stream settlements --min-size 100 # Filter by wallet pn stream settlements --wallets 0xabc... # Other event types pn stream trades pn stream blocks pn stream oracle pn stream global ``` ![pn stream settlements](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-stream.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=01bc416c9a2859b0012768dff9f06687) Events are color-coded: yellow for pending, green for confirmed. The header shows event count and throughput rate. ### Orderbook Full-depth live orderbook with proportional bid/ask bars. Green bars show bid depth growing left, red bars show ask depth growing right. ```bash theme={null} pn orderbook btc-updown-5m-1774077000 pn orderbook will-bitcoin-reach-150k-in-march-2026 ``` ![pn orderbook](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-orderbook.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=e8eed2181802812c0f692093d03c45f4) Use arrow keys to scroll deeper into the book. The footer shows midpoint, spread, total updates, and update rate. ### Short-Form Dashboard Multi-coin dashboard for Polymarket's short-form crypto markets. Shows all 7 coins (BTC, ETH, SOL, XRP, DOGE, HYPE, BNB) with beat price, direction, odds, liquidity, volume, and a countdown timer. Auto-rotates to the next window when the current one expires. ```bash theme={null} # 5-minute windows pn short-form 5m # 15-minute, specific coins pn short-form 15m --coins btc,eth,sol # Hourly pn short-form 1h ``` ![pn short-form 5m](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-shortform.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=23caa11dfbbb9c5a824c6949aef0ad11) ### Chainlink Price Feeds Live Chainlink data stream prices with bid/ask. ```bash theme={null} pn chainlink ``` ![pn chainlink](https://mintcdn.com/polynode/GlCT3esNSi9wuwtk/images/pn-chainlink.png?fit=max\&auto=format\&n=GlCT3esNSi9wuwtk\&q=85\&s=21af81b75f5bbd57c336564f39964430) *** ## JSON Mode (for Agents) Every command supports `--json` for programmatic use. Static commands output pretty-printed JSON. Streaming commands output newline-delimited JSON (NDJSON), one object per line, with no TUI. ```bash theme={null} # Static: pretty JSON pn markets --count 5 --json # Streaming: NDJSON (one event per line, no TUI) pn stream settlements --json # Pipe to jq pn stream settlements --json | jq '.taker_size' # Orderbook snapshots as JSON pn orderbook btc-updown-5m-1774077000 --json ``` This makes `pn` composable with standard Unix tools and usable as a data source for automated trading agents. *** ## Key Bindings (TUI) | Key | Action | | - | - | | `q` / `Esc` | Quit | | `Ctrl-C` | Quit | | `Up` / `Down` | Scroll orderbook depth | | `Home` | Reset scroll to top of book | # Credit Distributors Source: https://docs.polynode.dev/credits/distributors GET /v3/credits/distributors The on-chain payout addresses behind each credit type, with lifetime totals — full transparency into where the money comes from. The on-chain addresses Polymarket pays each program from, with lifetime totals per address. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/credits/distributors" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Global Credit Feed Source: https://docs.polynode.dev/credits/feed GET /v3/credits/events Most recent credit events across ALL wallets — watch large rebates or rewards land in near real time. Cursor-paginated. Recent credits across all wallets, newest first, cursor-paginated. `min_amount` turns it into a whale-credit watch. > [!NOTE] > > Every event carries `username` — the recipient's Polymarket display name — where known (`null` otherwise). ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Examples Large rebates landing right now: ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=maker_rebate,taker_rebate&min_amount=10000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Page with the returned cursor: ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?limit=100&cursor=90017147-2043" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Credits Leaderboard Source: https://docs.polynode.dev/credits/leaderboard GET /v3/credits/leaderboard Top earners for any credit type over any window, across every wallet. Not possible with Polymarket's per-wallet activity feed. Top earners for any credit program over 24h/7d/30d/all-time or an explicit time range. > [!NOTE] > > Leaderboard entries are identity-enriched: each row carries `username` (Polymarket display name), `eoa` (controlling account) and `wallet_type` where known. Fields are `null` for wallets without a resolved identity. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## One leaderboard per program ```bash # liquidity rewards theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=reward&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash # yield theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=yield&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash # maker rebates theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=maker_rebate&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash # taker rebates theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=taker_rebate&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash # referral rewards theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=referral_reward&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Add `window=7d` (or `24h`/`30d`), or explicit `start_ts`/`end_ts`, and `min_amount` to filter small earners. `type=all` ranks by combined credits. # Maker Rebates Source: https://docs.polynode.dev/credits/maker-rebates Maker fee rebates — the largest Polymarket credit program, $135M+ paid since January 2026. Since the introduction of trading fees, Polymarket rebates makers a share of the fees their filled quotes generate. Rebates are paid out in on-chain batches, typically daily. PolyNode indexes every payout: **\$135.2M to 133,973 wallets since 2026-01-07**. > [!NOTE] > > Polymarket also exposes a per-date accounting lookup for makers; PolyNode proxies it at [Wallet Maker Rebates](/data/wallets/rebates). This section is the complete indexed history: lifetime totals, time windows, leaderboards and event-level filters. All credits endpoints take this type as `maker_rebate`. ## Lifetime total for a wallet ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=maker_rebate" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## This month's earnings for a wallet Add unix-second bounds for windowed totals: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=maker_rebate&start_ts=1783036800&end_ts=1785715200" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Maker Rebates leaderboard ```bash theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=maker_rebate&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Windows: `window=24h|7d|30d|all`, or explicit `start_ts`/`end_ts`. ## Payout history for a wallet Filterable by time and amount, sortable by `time` or `amount`: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=maker_rebate&min_amount=100&sort=amount&order=desc&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Earnings chart data ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=maker_rebate&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Watch payouts land globally ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=maker_rebate&min_amount=1000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```python theme={null} import requests BASE = "https://api.polynode.dev" HEADERS = {"x-api-key": "YOUR_KEY"} wallet = "0x204f72f35326db932158cba6adff0b9a1da95e14" totals = requests.get( f"{BASE}/v3/wallets/{wallet}/credits/totals", params={"types": "maker_rebate"}, headers=HEADERS, ).json() print(totals["totals"]["maker_rebate"]["amount"]) ``` See the [Credits API Reference](/credits/wallet-totals) for every parameter. # Credits Overview Source: https://docs.polynode.dev/credits/overview Every Polymarket payout to users — liquidity rewards, yield, maker/taker rebates and referral rewards — indexed on-chain from the first payment ever made, with totals, leaderboards and filters Polymarket's API does not offer. Polymarket pays users five kinds of credits. Each lands on Polygon as a batch token transfer, and PolyNode indexes all of them, for every wallet, from the first payout ever made: | Program | Type value | Paid out | Recipients | History starts | | - | - | - | - | - | | [Liquidity Rewards](/credits/rewards) | `reward` | \$28.1M | 174,850 | 2023-11-25 | | [Yield](/credits/yield) | `yield` | \$2.74M | 321,307 | 2025-07-17 | | [Maker Rebates](/credits/maker-rebates) | `maker_rebate` | \$135.2M | 133,973 | 2026-01-07 | | [Taker Rebates](/credits/taker-rebates) | `taker_rebate` | \$13.7M | 36,469 | 2026-06-20 | | [Referral Rewards](/credits/referral-rewards) | `referral_reward` | \$11.5M | 7,752 | 2026-03-25 | Polymarket's public API exposes these only as a per-wallet activity feed with no totals, no cross-wallet queries and no aggregation. The credits endpoints add: * **Totals in one call** — lifetime or any time window, per type ([Wallet Credit Totals](/credits/wallet-totals)) * **Leaderboards** — top earners per program per window across all wallets ([Leaderboard](/credits/leaderboard)) * **Global stats and series** — program-wide payout volumes over time ([Stats](/credits/stats)) * **A global feed** — watch credits land across every wallet, filterable by size ([Feed](/credits/feed)) * **Full filtering** — amount bounds, amount sorting, token filter, time windows on everything * **Identity enrichment** — usernames on leaderboards and event feeds, plus each wallet's controlling EOA and other deployed Polymarket wallets on the totals endpoint The index is built from on-chain distributor transfers, so it is a superset of Polymarket's own activity ledger: batch program payouts match Polymarket's feed exactly, and direct one-off payments from the distributor wallets (which Polymarket's feed omits) are included as well. Amounts are USD strings (payouts settle in USDC.e historically and pUSD today; both are dollar-pegged and carried in the `token` field). New credits appear within about a minute of on-chain confirmation. Internal treasury/plumbing transfers between payout infrastructure addresses are excluded from all aggregate surfaces. All endpoints require your regular API key. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. # Recipient Growth Source: https://docs.polynode.dev/credits/recipients GET /v3/credits/recipients/stats How many wallets earned their first credit per bucket — program growth over time. New earning wallets per bucket, per program — a clean read on each program's adoption. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Example New referral earners per month: ```bash theme={null} curl "https://api.polynode.dev/v3/credits/recipients/stats?types=referral_reward&interval=month" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Referral Rewards Source: https://docs.polynode.dev/credits/referral-rewards Referral program earnings — fee-share payouts to referrers since March 2026. Polymarket's referral program pays referrers a share of their invitees' fees (see Polymarket's referral endpoints for codes and rates). The earnings arrive as on-chain batch payouts. PolyNode indexes the full history: \*\*$11.5M to 7,752 wallets since 2026-03-25** — top referrers have earned $600K+. All credits endpoints take this type as `referral_reward`. ## Lifetime total for a wallet ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=referral_reward" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## This month's earnings for a wallet Add unix-second bounds for windowed totals: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=referral_reward&start_ts=1783036800&end_ts=1785715200" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Referral Rewards leaderboard ```bash theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=referral_reward&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Windows: `window=24h|7d|30d|all`, or explicit `start_ts`/`end_ts`. ## Payout history for a wallet Filterable by time and amount, sortable by `time` or `amount`: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=referral_reward&min_amount=100&sort=amount&order=desc&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Earnings chart data ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=referral_reward&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Watch payouts land globally ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=referral_reward&min_amount=1000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```python theme={null} import requests BASE = "https://api.polynode.dev" HEADERS = {"x-api-key": "YOUR_KEY"} wallet = "0x204f72f35326db932158cba6adff0b9a1da95e14" totals = requests.get( f"{BASE}/v3/wallets/{wallet}/credits/totals", params={"types": "referral_reward"}, headers=HEADERS, ).json() print(totals["totals"]["referral_reward"]["amount"]) ``` See the [Credits API Reference](/credits/wallet-totals) for every parameter. # Liquidity Rewards Source: https://docs.polynode.dev/credits/rewards Polymarket's liquidity rewards program — daily payouts to accounts that quote rewarded markets inside the spread. Polymarket pays daily liquidity rewards to makers who keep orders inside the max spread on rewarded markets (see Polymarket's Liquidity Rewards program docs). Each day's earnings arrive as an on-chain batch transfer. PolyNode indexes every payout ever made: **\$28.1M to 174,850 wallets since 2023-11-25**. > [!NOTE] > > Reward market configurations (which markets pay rewards, rates and spreads) are served by the [Rewards](/data/rewards/markets) endpoints; this section covers the payouts themselves. All credits endpoints take this type as `reward`. ## Lifetime total for a wallet ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=reward" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## This month's earnings for a wallet Add unix-second bounds for windowed totals: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=reward&start_ts=1783036800&end_ts=1785715200" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Liquidity Rewards leaderboard ```bash theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=reward&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Windows: `window=24h|7d|30d|all`, or explicit `start_ts`/`end_ts`. ## Payout history for a wallet Filterable by time and amount, sortable by `time` or `amount`: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=reward&min_amount=100&sort=amount&order=desc&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Earnings chart data ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=reward&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Watch payouts land globally ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=reward&min_amount=1000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```python theme={null} import requests BASE = "https://api.polynode.dev" HEADERS = {"x-api-key": "YOUR_KEY"} wallet = "0x204f72f35326db932158cba6adff0b9a1da95e14" totals = requests.get( f"{BASE}/v3/wallets/{wallet}/credits/totals", params={"types": "reward"}, headers=HEADERS, ).json() print(totals["totals"]["reward"]["amount"]) ``` See the [Credits API Reference](/credits/wallet-totals) for every parameter. # Global Credit Stats Source: https://docs.polynode.dev/credits/stats GET /v3/credits/stats Program-wide aggregates per credit type: totals, unique recipients, batch transaction counts, average credit size, plus a bucketed series. Program-wide totals and time series: how much Polymarket pays out per program, to how many wallets, at what average size. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Examples Monthly payout volumes for every program: ```bash theme={null} curl "https://api.polynode.dev/v3/credits/stats?types=all&interval=month" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Taker rebates by day since launch: ```bash theme={null} curl "https://api.polynode.dev/v3/credits/stats?types=taker_rebate&interval=day" \ -H "x-api-key: $POLYNODE_API_KEY" ``` `unique_recipients` is exact for all-time requests and `null` when you pass `start_ts`/`end_ts`. `interval=hour` requires a window of 7 days or less. # Taker Rebates Source: https://docs.polynode.dev/credits/taker-rebates Taker fee rebates — volume-based rebates to active takers, launched June 2026. Polymarket's newest rebate program returns part of taker fees to active traders. Payouts run in on-chain batches and include large one-off settlements (single credits above $1M exist). PolyNode indexes all of it: **$13.7M to 36,469 wallets since 2026-06-20\*\*. All credits endpoints take this type as `taker_rebate`. ## Lifetime total for a wallet ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=taker_rebate" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## This month's earnings for a wallet Add unix-second bounds for windowed totals: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=taker_rebate&start_ts=1783036800&end_ts=1785715200" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Taker Rebates leaderboard ```bash theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=taker_rebate&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Windows: `window=24h|7d|30d|all`, or explicit `start_ts`/`end_ts`. ## Payout history for a wallet Filterable by time and amount, sortable by `time` or `amount`: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=taker_rebate&min_amount=100&sort=amount&order=desc&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Earnings chart data ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=taker_rebate&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Watch payouts land globally ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=taker_rebate&min_amount=1000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```python theme={null} import requests BASE = "https://api.polynode.dev" HEADERS = {"x-api-key": "YOUR_KEY"} wallet = "0x204f72f35326db932158cba6adff0b9a1da95e14" totals = requests.get( f"{BASE}/v3/wallets/{wallet}/credits/totals", params={"types": "taker_rebate"}, headers=HEADERS, ).json() print(totals["totals"]["taker_rebate"]["amount"]) ``` See the [Credits API Reference](/credits/wallet-totals) for every parameter. # Decode Payout Transaction Source: https://docs.polynode.dev/credits/tx GET /v3/credits/txs/{hash} Decode one payout transaction into typed credit rows: every recipient, every amount. Turn one payout transaction hash into its full typed breakdown: every recipient and amount in the batch. ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/credits/txs/0xb3b589e87145a7a61324bca2a241c891fd488cf0615e5c2d7a3121b28698d7a6" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Credit Events Source: https://docs.polynode.dev/credits/wallet-events GET /v3/wallets/{addr}/credits Individual credit events for one wallet with filters Polymarket does not offer: amount bounds, amount sorting, token filter. Every individual credit a wallet has received, filterable by program, time and amount, sortable by time or amount. > [!NOTE] > > Every event carries `username` — the recipient's Polymarket display name — where known (`null` otherwise). > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Examples Largest maker rebates first: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=maker_rebate&sort=amount&order=desc&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Yield credits during one week: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=yield&start_ts=1783036800&end_ts=1783641600" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `events[].wallet` | string | The wallet this row belongs to | `wallet` stays the address you passed. # Wallet Credit Series Source: https://docs.polynode.dev/credits/wallet-series GET /v3/wallets/{addr}/credits/series Time-bucketed earnings series per credit type for one wallet. Bucketed earnings over time for one wallet. Use `fill=zero` for continuous buckets when charting. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Example Weekly rebate earnings, chart-ready: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=maker_rebate,taker_rebate&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Buckets are summed per bucket across the combined wallets, and `wallet` stays the address you passed. # Wallet Credit Totals Source: https://docs.polynode.dev/credits/wallet-totals GET /v3/wallets/{addr}/credits/totals Lifetime or time-windowed totals per credit type for one wallet, in one call. Polymarket's own API only exposes these as a raw activity feed you would have to page and sum yourself. Total credits received by a wallet, per program, in one call. Add `start_ts`/`end_ts` for time-windowed totals (for example, rebates earned this month). > [!NOTE] > > The response includes an `identity` block with `username`, controlling `eoa`, `wallet_type`, `deployed`, `current`, `wallet_details`, and `other_wallets`. `wallet_details` separates wallet type from deployment status and identifies the account's current trading wallet. Polymarket's own API does not expose this anywhere. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Credit types Every credits endpoint accepts these values in `type`/`types`: | Value | Program | | - | - | | `reward` | [Liquidity rewards](/credits/rewards) | | `yield` | [Yield on balances](/credits/yield) | | `maker_rebate` | [Maker rebates](/credits/maker-rebates) | | `taker_rebate` | [Taker rebates](/credits/taker-rebates) | | `referral_reward` | [Referral rewards](/credits/referral-rewards) | `types` accepts a comma-separated set (`types=maker_rebate,taker_rebate`) or `all`. ## Examples All five programs at once: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Rebates only, June 2026: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=maker_rebate,taker_rebate&start_ts=1780272000&end_ts=1782950400" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Totals are summed per program across the combined wallets. `wallet` stays the address you passed, and `identity` describes that address. # Yield Source: https://docs.polynode.dev/credits/yield Interest paid on Polymarket balances — daily on-chain distributions since July 2025. Polymarket pays yield on eligible USD balances. It lands as one daily on-chain batch (around 00:10 UTC) to every enrolled wallet. PolyNode indexes the full history: **\$2.74M to 321,307 wallets since 2025-07-17** — the largest credit type by recipient count. All credits endpoints take this type as `yield`. ## Lifetime total for a wallet ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=yield" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## This month's earnings for a wallet Add unix-second bounds for windowed totals: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/totals?types=yield&start_ts=1783036800&end_ts=1785715200" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Yield leaderboard ```bash theme={null} curl "https://api.polynode.dev/v3/credits/leaderboard?type=yield&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Windows: `window=24h|7d|30d|all`, or explicit `start_ts`/`end_ts`. ## Payout history for a wallet Filterable by time and amount, sortable by `time` or `amount`: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits?types=yield&min_amount=100&sort=amount&order=desc&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Earnings chart data ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x204f72f35326db932158cba6adff0b9a1da95e14/credits/series?types=yield&interval=week&fill=zero" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Watch payouts land globally ```bash theme={null} curl "https://api.polynode.dev/v3/credits/events?types=yield&min_amount=1000&limit=50" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```python theme={null} import requests BASE = "https://api.polynode.dev" HEADERS = {"x-api-key": "YOUR_KEY"} wallet = "0x204f72f35326db932158cba6adff0b9a1da95e14" totals = requests.get( f"{BASE}/v3/wallets/{wallet}/credits/totals", params={"types": "yield"}, headers=HEADERS, ).json() print(totals["totals"]["yield"]["amount"]) ``` See the [Credits API Reference](/credits/wallet-totals) for every parameter. # Event Format Source: https://docs.polynode.dev/crypto/event-format Price feed event schema and field reference. ## Event payload This example is an explicitly selected spot event. Default followers now receive 30-second and 60-second TWAP events with the same shape and different identity fields. See [Chainlink Spot and TWAP Prices](/crypto/twap) for the subscription filters. ```json theme={null} { "type": "price_feed", "feed": "ETH/USD", "timestamp": 1774672089, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "ETH/USD", "price": 1989.49, "bid": 1989.49, "ask": 1989.49, "timestamp": 1774672089, "is_twap": false, "twap_window_seconds": null } } ``` ## Fields **type** `string` *required* Always `"price_feed"`. **feed** `string` *required* Feed name (e.g. `"BTC/USD"`, `"ETH/USD"`). Top-level convenience field, same value as `data.feed`. **timestamp** `number` *required* Observation timestamp in Unix seconds. Top-level convenience field, same value as `data.timestamp`. **is\_twap** `boolean` *required* `true` for a Chainlink-computed TWAP and `false` for a spot price. **twap\_window\_seconds** `30 | 60 | null` *required* Chainlink TWAP lookback window. `null` on spot events. **data** `object` *required* **data fields** **feed** `string` *required* Feed name (e.g. `"BTC/USD"`). **price** `number` *required* Mid price in USD. This is the canonical price for this asset at this timestamp. **bid** `number` *required* Bid price in USD. **ask** `number` *required* Ask price in USD. **timestamp** `number` *required* Observation timestamp in Unix seconds. **is\_twap** `boolean` *required* `true` for a TWAP event and `false` for a spot event. **twap\_window\_seconds** `30 | 60 | null` *required* TWAP lookback window. `null` on spot events. ## Notes * **Update rate**: approximately 1 update per second per feed. * **No snapshot**: unlike settlement subscriptions, price feed subscriptions do not include an initial snapshot. The first event arrives with the next price observation (\~1 second after subscribing). * **TWAP windows**: when you subscribe to both windows, key state by `feed` and `twap_window_seconds`. See [Chainlink Spot and TWAP Prices](/crypto/twap). * **Deduplication**: include `feed`, `twap_window_seconds`, and `timestamp` in a TWAP deduplication key. # Available Feeds Source: https://docs.polynode.dev/crypto/feeds All crypto price feeds with live examples. ## Feed reference All feeds update at approximately one event per second. Prices are quoted in USD. The examples below show explicitly selected spot events. The same seven feed names apply to spot, 30-second TWAP, and 60-second TWAP events. See [Chainlink Spot and TWAP Prices](/crypto/twap) for the current default, explicit spot selection, and `twap_windows` filters. ### BTC/USD Bitcoin. The most liquid and widely traded crypto asset. ```json theme={null} { "type": "price_feed", "feed": "BTC/USD", "timestamp": 1774672089, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "BTC/USD", "price": 66236.61, "bid": 66236.61, "ask": 66236.61, "timestamp": 1774672089, "is_twap": false, "twap_window_seconds": null } } ``` ### ETH/USD Ethereum. ```json theme={null} { "type": "price_feed", "feed": "ETH/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "ETH/USD", "price": 1989.68, "bid": 1989.68, "ask": 1989.68, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ### SOL/USD Solana. ```json theme={null} { "type": "price_feed", "feed": "SOL/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "SOL/USD", "price": 82.57, "bid": 82.57, "ask": 82.57, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ### BNB/USD BNB (Binance). ```json theme={null} { "type": "price_feed", "feed": "BNB/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "BNB/USD", "price": 610.54, "bid": 610.54, "ask": 610.54, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ### XRP/USD XRP. ```json theme={null} { "type": "price_feed", "feed": "XRP/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "XRP/USD", "price": 1.326, "bid": 1.326, "ask": 1.326, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ### DOGE/USD Dogecoin. ```json theme={null} { "type": "price_feed", "feed": "DOGE/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "DOGE/USD", "price": 0.08991, "bid": 0.08991, "ask": 0.08991, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ### HYPE/USD Hyperliquid. ```json theme={null} { "type": "price_feed", "feed": "HYPE/USD", "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null, "data": { "feed": "HYPE/USD", "price": 38.60, "bid": 38.60, "ask": 38.60, "timestamp": 1774672588, "is_twap": false, "twap_window_seconds": null } } ``` ## Filtering Subscribe to specific feeds only: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD", "SOL/USD"] } } ``` Feed names are case-insensitive. `"btc/usd"` and `"BTC/USD"` both work. To receive spot prices for the selected feeds, add `price_source: "spot"`: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD", "SOL/USD"], "price_source": "spot" } } ``` ## Subscribing to all feeds Omit the `feeds` filter to follow the default stream for all feeds: ```json theme={null} {"action": "subscribe", "type": "chainlink"} ``` The default stream now sends both TWAP windows per feed. Add `price_source: "spot"` for every spot pair, or select `twap_windows: [30]` or `[60]` when your application needs only one TWAP lookback. # Crypto Prices Source: https://docs.polynode.dev/crypto/overview Stream Chainlink spot prices and 30-second or 60-second TWAP prices over WebSocket. Stream real-time Chainlink prices over WebSocket. Seven feeds update at approximately one event per second each. > [!NOTE] > > The default `chainlink` subscription now delivers both the 30-second and > 60-second TWAP streams. Add `price_source: "spot"` to select spot prices > explicitly. See [Chainlink Spot and TWAP Prices](/crypto/twap) for every > selection and its acknowledgement. ## Connection ``` wss://ws.polynode.dev/ws?key=YOUR_API_KEY ``` This is the same WebSocket endpoint used for settlements and orderbook. If you already have a connection open, you don't need a new one. ## Available feeds | Feed | Pair | Update rate | | - | - | - | | `BTC/USD` | Bitcoin / US Dollar | \~1/second | | `ETH/USD` | Ethereum / US Dollar | \~1/second | | `SOL/USD` | Solana / US Dollar | \~1/second | | `BNB/USD` | BNB / US Dollar | \~1/second | | `XRP/USD` | XRP / US Dollar | \~1/second | | `DOGE/USD` | Dogecoin / US Dollar | \~1/second | | `HYPE/USD` | Hyperliquid / US Dollar | \~1/second | ## Quick start Connect and follow the default stream for all seven feeds: ```javascript JavaScript theme={null} const WebSocket = require("ws"); const ws = new WebSocket( "wss://ws.polynode.dev/ws?key=YOUR_API_KEY" ); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "chainlink" })); }); ws.on("message", (data) => { const msg = JSON.parse(data); if (msg.type === "price_feed") { console.log(`${msg.data.feed}: $${msg.data.price}`); } }); ``` ```python Python theme={null} import asyncio import json import websockets async def main(): uri = "wss://ws.polynode.dev/ws?key=YOUR_API_KEY" async with websockets.connect(uri) as ws: await ws.send(json.dumps({ "action": "subscribe", "type": "chainlink" })) async for message in ws: msg = json.loads(message) if msg.get("type") == "price_feed": d = msg["data"] print(f"{d['feed']}: ${d['price']}") asyncio.run(main()) ``` ```rust Rust theme={null} use polynode::PolyNodeWS; #[tokio::main] async fn main() { let mut ws = PolyNodeWS::connect("YOUR_API_KEY").await.unwrap(); ws.subscribe_price_feeds(None).await.unwrap(); // None = all feeds while let Some(event) = ws.next_event().await { println!("{}: ${}", event.feed, event.price); } } ``` ```bash wscat theme={null} wscat -c "wss://ws.polynode.dev/ws?key=YOUR_API_KEY" # Then send: {"action": "subscribe", "type": "chainlink"} ``` ### Filter to specific feeds Only receive the feeds you care about: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD"] } } ``` Omit `feeds` to get all 7. ### Select spot explicitly Add `price_source: "spot"` to receive spot prices instead of following the default TWAP stream: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD"], "price_source": "spot" } } ``` Omit `feeds` to receive every available spot pair. Do not combine `price_source: "spot"` with `twap_windows`. ## Event format Every price update arrives as a `price_feed` event: ```json theme={null} { "type": "price_feed", "feed": "BTC/USD", "timestamp": 1774672588, "is_twap": true, "twap_window_seconds": 30, "data": { "feed": "BTC/USD", "price": 66225.49, "bid": 66225.49, "ask": 66225.49, "timestamp": 1774672588, "is_twap": true, "twap_window_seconds": 30 } } ``` See [Event Format](/crypto/event-format) for the full field reference. ## Combining with other streams Crypto prices run on the same WebSocket connection as settlements, orderbook, and oracle streams. Send multiple subscribe messages: ```javascript JavaScript theme={null} // Settlements + crypto prices on the same connection ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); ws.send(JSON.stringify({ action: "subscribe", type: "chainlink" })); }); ws.on("message", (data) => { const msg = JSON.parse(data); if (msg.type === "price_feed") { // crypto price tick console.log(`${msg.data.feed}: $${msg.data.price}`); } else if (msg.type === "settlement") { // settlement event console.log(`${msg.data.market_title}: ${msg.data.outcome}`); } }); ``` ```python Python theme={null} await ws.send(json.dumps({"action": "subscribe", "type": "settlements"})) await ws.send(json.dumps({"action": "subscribe", "type": "chainlink"})) async for message in ws: msg = json.loads(message) if msg.get("type") == "price_feed": d = msg["data"] print(f"Price: {d['feed']} ${d['price']}") elif msg.get("type") == "settlement": d = msg["data"] print(f"Settlement: {d['market_title']}: {d['outcome']}") ``` Use the `type` field (`"price_feed"` vs `"settlement"`) to route events. ## REST Endpoints In addition to the WebSocket stream, crypto data is available via REST. See the [REST API reference](/crypto/rest-api) for full details. | Endpoint | Description | | - | - | | `GET /v1/crypto/markets` | All crypto prediction markets | | `GET /v1/crypto/candles?symbol=BTC` | 5-min OHLC candles from Chainlink oracle | | `GET /v1/crypto/ticks?symbol=BTC&from={unix_ms}&to={unix_ms}` | 1-second historical price ticks for chart backfill | | `GET /v1/crypto/price?symbol=BTC&window={epoch}` | Open/close price for a market window | | `GET /v1/crypto/active` | Currently active 5-minute markets for all 7 coins | | `GET /v1/crypto/series` | Recurring crypto market series | All endpoints require an API key via `?key=` or `x-api-key` header. ## Related guides * [Chainlink Spot and TWAP Prices](/crypto/twap) * [Available Feeds](/crypto/feeds) * [Event Format](/crypto/event-format) * [Crypto REST API](/crypto/rest-api) # REST API Source: https://docs.polynode.dev/crypto/rest-api REST endpoints for crypto market discovery, oracle candles, historical ticks, price-to-beat, and active short-form markets. REST endpoints for crypto prediction market data. All endpoints require an API key. ## Authentication Pass your API key via query parameter or header: ```bash theme={null} # Query parameter curl "https://api.polynode.dev/v1/crypto/markets?key=YOUR_API_KEY" # Header curl -H "x-api-key: YOUR_API_KEY" "https://api.polynode.dev/v1/crypto/markets" ``` *** ## GET /v1/crypto/markets All crypto prediction markets with liquidity, volume, and open interest. **Cache:** 3 minutes ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/markets?key=YOUR_API_KEY" ``` **Response** ```json theme={null} { "events": [ { "id": "238474", "slug": "what-price-will-bitcoin-hit-in-march-2026", "title": "What price will Bitcoin hit in March?", "startDate": "2026-03-01T05:20:27.791222Z", "endDate": "2026-04-01T04:00:00Z", "active": true, "volume": 88886711.74, "volume24hr": 5733750.73, "liquidity": 6074250.39, "openInterest": 12827944.10, "seriesSlug": "bitcoin-hit-price-monthly", "markets": [ { "id": "1629442", "question": "$100,000?", "conditionId": "0x...", "outcomes": ["Yes", "No"], "outcomePrices": [0.045, 0.955], "volume": 24084104.74, "liquidity": 2028310.67, "active": true, "closed": false, "groupItemTitle": "↑ 150,000" } ] } ] } ``` *** ## GET /v1/crypto/candles 5-minute OHLC candles from PolyNode's live Chainlink tick archive. Returns \~2.5 hours of history (30 candles). **Cache:** \~5 seconds | Parameter | Required | Description | | - | - | - | | `symbol` | Yes | Asset symbol or feed name: `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, `HYPE`, or names like `BTC/USD` | ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/candles?symbol=BTC&key=YOUR_API_KEY" ``` > [!NOTE] > > REST candle symbols accept both bare asset symbols like `BTC` and feed names like `BTC/USD`. WebSocket Chainlink subscriptions use feed names such as `BTC/USD`. **Response** ```json theme={null} { "candles": [ { "time": 1774665300, "open": 65954.03, "high": 65992.01, "low": 65947.14, "close": 65949.69 } ] } ``` *** ## GET /v1/crypto/ticks Historical 1-second ticks for the same crypto feeds available on the `price_feed` WebSocket stream. Use this to backfill a chart window before switching to live WebSocket updates. **Range:** up to 24 hours per request | Parameter | Required | Description | | - | - | - | | `symbol` | Yes | Asset symbol: `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, `HYPE` | | `from` | Yes | Start of range as Unix milliseconds | | `to` | Yes | End of range as Unix milliseconds | | `limit` | No | Max ticks to return. Default 10000, max 100000 | ```bash theme={null} curl -H "x-api-key: YOUR_API_KEY" \ "https://api.polynode.dev/v1/crypto/ticks?symbol=BTC&from=1780458961000&to=1780459082000&limit=5" ``` **Response** ```json theme={null} { "symbol": "BTC", "feed": "BTC/USD", "from": 1780458961000, "to": 1780459082000, "limit": 5, "count": 5, "truncated": true, "ticks": [ { "id": "1780458962000-0", "type": "price_feed", "feed": "BTC/USD", "timestamp": 1780458962, "timestamp_ms": 1780458962000, "data": { "feed": "BTC/USD", "price": 65869.02124677686, "bid": 65865.65936734258, "ask": 65870.4120597498, "timestamp": 1780458962 } } ] } ``` If `truncated` is `true`, request a narrower range or increase `limit`. *** ## GET /v1/crypto/price Open and close price for a specific crypto market window. Use this to get the "price to beat" for a short-form market. **Cache:** 10 seconds | Parameter | Required | Description | | - | - | - | | `symbol` | Yes | Asset symbol: `BTC`, `ETH`, `SOL`, `BNB`, `XRP`, `DOGE`, `HYPE` | | `window` | Yes | Unix epoch timestamp of the market window start | | `interval` | No | Market interval variant (e.g. `5m`, `15m`, `1h`, `4h`) | ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/price?symbol=BTC&window=1774674000&key=YOUR_API_KEY" ``` **Response** ```json theme={null} { "openPrice": 66285.01, "closePrice": 66238.61, "timestamp": 1774674466843, "completed": false, "incomplete": true, "cached": false } ``` The `openPrice` is the oracle price at market open. `closePrice` updates in real time until the window completes. `completed: true` means the market has resolved. *** ## GET /v1/crypto/active Currently active 5-minute up-or-down markets for all 7 coins. Returns live market data with token IDs, outcomes, and current odds. **Cache:** 30 seconds ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/active?key=YOUR_API_KEY" ``` **Response** ```json theme={null} { "markets": [ { "id": "312746", "slug": "btc-updown-5m-1774674300", "title": "Bitcoin Up or Down - March 28, 1:05AM-1:10AM ET", "active": true, "closed": false, "startDate": "2026-03-27T05:16:04.211285Z", "endDate": "2026-03-28T05:10:00Z", "markets": [ { "question": "Bitcoin Up or Down - March 28, 1:05AM-1:10AM ET", "conditionId": "0x...", "outcomes": "[\"Up\", \"Down\"]", "outcomePrices": [0.465, 0.535], "tokenId": "12345...", "active": true, "closed": false } ] } ], "count": 7, "windowStart": 1774674300 } ``` The `windowStart` field is the epoch timestamp of the current 5-minute window. New markets rotate every 5 minutes. > [!TIP] > > Slug pattern is deterministic: `{coin}-updown-5m-{windowStart}`. You can compute the current window yourself with `Math.floor(Date.now() / 1000 / 300) * 300`. The SDK's `shortForm()` method handles this automatically with auto-rotation, enriched market data, and settlement streaming. See [Short-Form Markets](/sdks/short-form) for the interactive slug calculator and full reference. *** ## GET /v1/crypto/series Recurring crypto market series (5m, 15m, 1h, 4h, daily, weekly, monthly patterns). **Cache:** 5 minutes ```bash theme={null} curl "https://api.polynode.dev/v1/crypto/series?key=YOUR_API_KEY" ``` **Response** ```json theme={null} { "series": [ { "id": "10422", "slug": "xrp-up-or-down-15m", "title": "XRP Up or Down 15m", "recurrence": "15m", "active": true, "eventCount": null }, { "id": "10065", "slug": "ethereum-neg-risk-weekly", "title": "Ethereum Neg Risk Weekly", "recurrence": "weekly", "active": true, "eventCount": null } ], "count": 7 } ``` # Chainlink Spot and TWAP Prices Source: https://docs.polynode.dev/crypto/twap Choose Chainlink spot, 30-second TWAP, 60-second TWAP, or both TWAP streams. polynode offers Chainlink spot prices plus 30-second and 60-second time-weighted average prices (TWAP) through the existing `chainlink` WebSocket subscription. The current default delivers both TWAP windows. Select spot or one TWAP window explicitly when that is all your application needs. ## Choose spot Add `price_source: "spot"`: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD"], "price_source": "spot" } } ``` The acknowledgement confirms the selection: ```json theme={null} { "type": "subscribed", "subscription_type": "chainlink", "price_source": "spot", "twap_windows": null } ``` ## Choose TWAP Use `twap_windows` to select a lookback: | Price selection | Filter | Acknowledgement `price_source` | | - | - | - | | 30-second TWAP | `"twap_windows": [30]` | `twap30` | | 60-second TWAP | `"twap_windows": [60]` | `twap60` | | Both TWAPs | `"twap_windows": [30, 60]` | `both` | For example, subscribe to both windows for BTC/USD and ETH/USD: ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD"], "twap_windows": [30, 60] } } ``` `30` and `60` are lookback windows, not update rates. Read `twap_window_seconds` on each event instead of inferring the window from event timing. ## Follow the current default Omit both selectors to follow the current default: ```json theme={null} {"action": "subscribe", "type": "chainlink"} ``` The acknowledgement returns `price_source: "follow_main"` and `twap_windows: null`. The current default sends both the 30-second and 60-second TWAP streams. ## Selection rules * `price_source` accepts `"spot"`. * `twap_windows` accepts `[30]`, `[60]`, or `[30, 60]`. * Do not combine `price_source: "spot"` with `twap_windows`. * Omit `feeds` to receive every available pair. * Spot and TWAP subscriptions begin with the next update. They do not include a snapshot, history, or replay. ## Identify each event Every event keeps the existing `price_feed` shape and adds two fields that identify the price type: ```json theme={null} { "type": "price_feed", "feed": "BTC/USD", "timestamp": 1785178800, "is_twap": true, "twap_window_seconds": 30, "data": { "feed": "BTC/USD", "price": 65000.5, "bid": 65000.5, "ask": 65000.5, "timestamp": 1785178800, "is_twap": true, "twap_window_seconds": 30 } } ``` For spot events, `is_twap` is `false` and `twap_window_seconds` is `null`. For TWAP events, `is_twap` is `true` and `twap_window_seconds` is `30` or `60`. When both windows are selected, the two events for one feed are separate price observations. Key application state by `feed` and `twap_window_seconds`, and include `timestamp` when deduplicating delivery. Existing clients can keep their WebSocket URL, API key, subscription type, and existing JSON fields unchanged. Add a selector only when the application needs spot or one exact TWAP window. # Compare Builder Daily Activity Source: https://docs.polynode.dev/data/builders/activity-comparison Return aligned daily activity for up to 20 Builder codes, with an optional residual series. This endpoint returns an aligned daily rectangle for multiple Builders. Use it for comparison charts and selected-only bulk reads without issuing one request per Builder. ## Request ```http theme={null} GET /v3/builders/activity/daily ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `builders` | string | required | One to 20 comma-separated Builder codes. `builder_codes` is an accepted alias. | | `start_date` | date | 29 UTC days before today | First inclusive UTC date in `YYYY-MM-DD` format | | `end_date` | date | Today in UTC | Last inclusive UTC date in `YYYY-MM-DD` format | | `include_other` | boolean | `true` | Include one `is_other=true` series containing activity from every unselected Builder | The inclusive range may contain at most 366 days. Codes are normalized and duplicates are removed while preserving first-seen order. Use `include_other=false` when only the selected Builder series are needed. ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/activity/daily?builders=0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1,0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df&start_date=2026-08-01&end_date=2026-08-30&include_other=false" ``` The response uses the same envelope and `series[].days[]` fields as [Builder Daily Activity](/data/builders/daily-activity). Bulk responses intentionally return empty `top_markets` and `top_categories` arrays so query cost stays bounded as the selected set or date range grows. When `include_other=true`, the final series has `builder_code: null`, `builder_name: "Other"`, and `is_other: true`. Its daily active-trader count deduplicates wallets across all unselected Builders for that day. ## Errors | Status | Error | Meaning | | - | - | - | | `400` | `builders_required`, `invalid_builder`, `too_many_builders`, `invalid_date`, `invalid_date_range`, or `date_range_too_large` | A query value is invalid | | `401` | authentication error | The API key is missing or invalid | | `402` | payment required | The key's plan does not include paid V3 REST data | | `429` | rate limit exceeded | The account's shared V3 REST request limit was exceeded | | `503` | `temporarily_unavailable` | Coverage is incomplete or a required bounded query is unavailable; no partial series is returned | ## Related endpoints | Endpoint | Description | | - | - | | [`GET /v3/builders`](/data/builders/list) | Print or search the public Builder directory | | [`GET /v3/builders/{code}/activity/daily`](/data/builders/daily-activity) | Add recent top-market and category composition for one Builder | | [`GET /v3/builders/{code}/leaderboard`](/data/builders/trader-leaderboard) | Rank traders active through one Builder | # Builder Daily Activity Source: https://docs.polynode.dev/data/builders/daily-activity Return an inclusive daily time series plus recent market and category composition for one Builder. Use this endpoint for one Builder's daily attributed volume, fills, active traders, trader-paid fees, and buy/sell mix. Recent windows also include the top markets and categories by attributed volume. ## Request ```http theme={null} GET /v3/builders/{code}/activity/daily ``` ### Path parameter | Parameter | Type | Description | | - | - | - | | `code` | string | Builder code (with or without `0x`) or exact public Builder name. Hex digits, the prefix, and names are case-insensitive; names must be URL-encoded. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `start_date` | date | 29 UTC days before today | First inclusive UTC date in `YYYY-MM-DD` format | | `end_date` | date | Today in UTC | Last inclusive UTC date in `YYYY-MM-DD` format | | `top_limit` | integer | `10` | Top markets and categories to return, from 1 through 20 | The inclusive range may contain at most 366 days and may begin no earlier than `2020-01-01`. When a request reaches today but the newest completed daily bucket is one or two days behind, the service shifts both dates backward by the same amount. Always treat the returned `start_date` and `end_date` as authoritative. Top-market and top-category composition is included only for windows of 31 days or fewer. Longer history requests preserve the same response shape and return empty `top_markets` and `top_categories` arrays. ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/BetMoar/activity/daily?start_date=2026-08-01&end_date=2026-08-30&top_limit=5" ``` ## Response shape ```json theme={null} { "start_date": "2026-08-01", "end_date": "2026-08-30", "coverage_start_date": "2026-04-03", "coverage_end_date": "2026-08-30", "volume_scope": "clob_v2_onchain", "volume_semantics": "outcome_share_par_notional", "fee_semantics": "Trader-paid fees attributed to fills. These are not builder rebates.", "series": [ { "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "builder_name": "BetMoar", "builder_logo": "https://example.com/builder.png", "builder_verified": true, "is_other": false, "days": [ { "date": "2026-08-01", "volume_e6": "248501250000", "volume": "248501.25", "trades": 821, "active_traders": 194, "trader_paid_fees_e6": "184200000", "trader_paid_fees": "184.2", "buy_volume_e6": "148500000000", "buy_volume": "148500", "sell_volume_e6": "100001250000", "sell_volume": "100001.25" } ], "top_markets": [], "top_categories": [] } ] } ``` `days` contains one row for every requested UTC date, including explicit zero-valued days. Buy and sell volume use the same outcome-share par-notional basis and add to total volume. `active_traders` is the distinct attributed trader count for that Builder and day. Each `top_markets` and `top_categories` row includes `rank`, volume, fills, trader-paid fees, and buy/sell volume. Market rows also include nullable `condition_id`, title, slug, image, and category. ## Errors | Status | Error | Meaning | | - | - | - | | `400` | `invalid_builder`, `invalid_date`, `invalid_date_range`, `date_range_too_large`, or `invalid_top_limit` | A path or query value is invalid | | `401` | authentication error | The API key is missing or invalid | | `402` | payment required | The key's plan does not include paid V3 REST data | | `404` | `builder_not_found` | No Builder matches a supplied public name | | `409` | `ambiguous_builder_name` | More than one Builder uses the supplied name; use a code from the Builder directory | | `429` | rate limit exceeded | The account's shared V3 REST request limit was exceeded | | `503` | `temporarily_unavailable` | Coverage is incomplete or a required bounded query is unavailable; no partial series is returned | ## Related endpoints | Endpoint | Description | | - | - | | [`GET /v3/builders/activity/daily`](/data/builders/activity-comparison) | Compare selected Builder daily series | | [`GET /v3/builders/{code}/leaderboard`](/data/builders/trader-leaderboard) | Rank the Builder's active trader cohort | | [`GET /v3/builders/{code}/trades`](/data/builders/trades) | Paginate the underlying attributed fills | # Builder Detail Source: https://docs.polynode.dev/data/builders/detail GET /v3/builders/{code} Get stats and public profile metadata for a single Builder by code or exact public name. Returns fill count, Polymarket-compatible V2 share-notional volume, fees, buy/sell volume, raw maker/taker totals, and public profile metadata for a specific Builder. ## Request ``` GET /v3/builders/{code} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `code` | string | Builder code (with or without `0x`) or exact public Builder name. Hex digits, the prefix, and names are case-insensitive; names must be URL-encoded. | ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0xd1d9dd6983c40006b0dc8eab84a41ac9a4f27643296178479ffbebbc01ab7bde" ``` ```json theme={null} { "builder": "0xd1d9dd6983c40006b0dc8eab84a41ac9a4f27643296178479ffbebbc01ab7bde", "builder_code": "0xd1d9dd6983c40006b0dc8eab84a41ac9a4f27643296178479ffbebbc01ab7bde", "builder_logo": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-5148537-b5dbf263-8d5f-41d7-bba1-387bfa17075c.png", "builder_name": "MagicMarkets", "builder_verified": true, "buy_volume_e6": "18512535904523", "buy_volume_usdc": "18512535.904523000000", "buy_volume": "18512535.904523000000", "elapsed_ms": 3, "external_active_users": 3, "external_rank": 23, "external_volume": "18380636.129236996", "fee_semantics": "Builder-attributed trader-paid fees. This is not a builder rebate payout.", "fill_count": 23076, "first_fill": "1777382110", "last_fill": "1782307555", "sell_volume_e6": "0", "sell_volume_usdc": "0.000000000000000000000000", "sell_volume": "0.000000000000000000000000", "source": "builder_fee_stats", "stats_checked_at": "2026-06-24 13:28:05.26204+00", "stats_pending": false, "stats_refreshed_at": "2026-06-24 13:28:03.133082+00", "stats_source": "local_order_filled_event_index", "total_fees": "116885095300", "total_fees_usdc": "116885.095300000000", "total_maker_volume": "8805777867302", "total_maker_volume_usdc": "8805777.867302000000", "total_taker_volume": "18512535904523", "total_taker_volume_usdc": "18512535.904523000000", "volume_e6": "18512535904523", "volume_usdc": "18512535.904523000000", "volume": "18512535.904523000000", "volume_scope": "clob_v2_onchain", "volume_semantics": "outcome_share_par_notional" } ``` You may also use the exact public name. A shared name returns HTTP `409`; use the code from the [Builder directory](/data/builders/list) to disambiguate. ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/BetMoar" ``` ## Response fields Same fields as the [Builder Leaderboard](/data/builders/list) response, without `rank`. | Field | Type | Description | | - | - | - | | `builder` | string | Builder code (`0x`-prefixed hex, 32 bytes) | | `builder_code` | string | Same builder code, included for profile-style naming consistency | | `builder_name` | string \| null | Public builder profile name when available | | `builder_logo` | string \| null | Public builder profile image URL when available | | `builder_verified` | boolean \| null | Whether the builder profile is verified, when available | | `fill_count` | integer | Total fills attributed to this builder | | `first_fill` | string | Unix timestamp of first fill | | `last_fill` | string | Unix timestamp of most recent fill | | `source` | string | Legacy source label. `builder_fee_stats` means local builder stats are present; `polymarket_builder_metadata` means only profile metadata is present so far. | | `stats_source` | string \| null | Local stats source, currently `local_order_filled_event_index` when local stats are populated | | `total_fees` | string | Total fees generated in raw 6-decimal USDC units | | `total_fees_usdc` | string \| null | Total fees normalized to decimal USDC | | `total_maker_volume` | string | Sum of raw maker-side amount fields in 6-decimal units, kept for compatibility | | `total_maker_volume_usdc` | string \| null | Legacy decimal-scaled maker amount. Depending on the fill side, this raw leg can be collateral or outcome shares. | | `total_taker_volume` | string | Sum of raw taker-side amount fields in 6-decimal units, kept for compatibility | | `total_taker_volume_usdc` | string \| null | Legacy decimal-scaled taker amount. Depending on the fill side, this raw leg can be collateral or outcome shares. | | `volume_e6` | string \| null | Canonical total builder volume as outcome-share par notional in raw 6-decimal units | | `volume` | string \| null | Preferred decimal total builder volume; one outcome share counts as \$1 of par notional | | `volume_usdc` | string \| null | Compatibility alias for `volume`; it is par notional, not collateral cash paid | | `buy_volume_e6` | string \| null | Buy-side outcome-share par notional in raw 6-decimal units | | `buy_volume` | string \| null | Decimal buy-side outcome-share par notional | | `buy_volume_usdc` | string \| null | Compatibility alias for `buy_volume` | | `sell_volume_e6` | string \| null | Sell-side outcome-share par notional in raw 6-decimal units | | `sell_volume` | string \| null | Decimal sell-side outcome-share par notional | | `sell_volume_usdc` | string \| null | Compatibility alias for `sell_volume` | | `volume_scope` | string | `clob_v2_onchain`; legacy pre-V2 builder attribution is outside this total | | `volume_semantics` | string | `outcome_share_par_notional` | | `external_rank` | integer \| null | Polymarket's public builder leaderboard rank, when available | | `external_volume` | string \| null | Polymarket's public builder leaderboard volume, when available | | `external_active_users` | integer \| null | Polymarket's public active-user count, when available | | `stats_refreshed_at` | string \| null | Time Polynode last rewrote local stats for this builder | | `stats_checked_at` | string \| null | Time Polynode last checked this builder, including no-op refreshes | | `stats_pending` | boolean | `true` when profile metadata exists but the local stats row has not been populated yet | | `fee_semantics` | string | Reminder that builder fees are trader-paid fees attributed to builder order flow, not a builder rebate payout | | `elapsed_ms` | integer | Server-side query time in milliseconds | ## Name-resolution errors | Status | Error | Meaning | | - | - | - | | `404` | `builder_not_found` or `builder not found` | No Builder matches the supplied name or code | | `409` | `ambiguous_builder_name` | More than one Builder uses the supplied name; use a code from the Builder directory | ## Related endpoints | Endpoint | Description | | - | - | | `GET /v3/builders` | Builder leaderboard | | `GET /v3/builders/{code}/leaderboard` | Rank every eligible trader active through this builder by global wallet P\&L first, or by attributed activity | | `GET /v3/builders/{code}/activity/daily` | Daily activity and recent top-market/category composition | | `GET /v3/builders/{code}/trades` | Trades attributed to this builder | # Builder Leaderboard Source: https://docs.polynode.dev/data/builders/list GET /v3/builders Rank Polymarket builders by V2-attributed share notional, fill count, fees, and enriched builder profile metadata. Polymarket V2 trades include a `builder` field identifying which order routing service executed the trade. This endpoint is both the Builder ranking and the canonical public Builder directory. It returns each Builder's display name and code, and it can resolve an exact display name case-insensitively. Builder profile metadata is synced from Polymarket's public builder metadata. Local fill, fee, and volume stats come from Polynode's indexed `OrderFilled` events. Builders can appear with metadata before their local stats row is refreshed; in that case `stats_pending` is `true` and local volume fields are `null`. `volume` is the canonical total builder volume. It counts the outcome shares attributed to the builder, with one share represented as \$1 of par notional. This matches Polymarket's builder-volume convention over the same CLOB V2 history. Polymarket may show additional legacy volume from before onchain V2 builder attribution; Polynode does not import that historical total. ## Request ``` GET /v3/builders ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sort` | string | `fills` | Sort by: `fills`, `volume`, `fees` | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | | `name` | string | -- | Exact public Builder name, matched case-insensitively. All matches are returned when a display name is shared. | `sort` and `name` are case-insensitive. Responses retain canonical Builder names and codes. ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders?sort=volume&limit=1" ``` ```json theme={null} { "builders": [ { "builder": "0xd1d9dd6983c40006b0dc8eab84a41ac9a4f27643296178479ffbebbc01ab7bde", "builder_code": "0xd1d9dd6983c40006b0dc8eab84a41ac9a4f27643296178479ffbebbc01ab7bde", "builder_logo": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-5148537-b5dbf263-8d5f-41d7-bba1-387bfa17075c.png", "builder_name": "MagicMarkets", "builder_verified": true, "external_active_users": 3, "external_rank": 23, "external_volume": "18380636.129236996", "fill_count": 23076, "first_fill": "1777382110", "last_fill": "1782307555", "rank": 1, "source": "local_order_filled_event_index", "stats_checked_at": "2026-06-24 13:28:05.26204+00", "stats_pending": false, "stats_refreshed_at": "2026-06-24 13:28:03.133082+00", "buy_volume_e6": "18512535904523", "buy_volume_usdc": "18512535.904523000000", "buy_volume": "18512535.904523000000", "sell_volume_e6": "0", "sell_volume_usdc": "0.000000000000000000000000", "sell_volume": "0.000000000000000000000000", "total_fees": "116885095300", "total_fees_usdc": "116885.095300000000", "total_maker_volume": "8805777867302", "total_maker_volume_usdc": "8805777.867302000000", "total_taker_volume": "18512535904523", "total_taker_volume_usdc": "18512535.904523000000", "volume_e6": "18512535904523", "volume_usdc": "18512535.904523000000", "volume": "18512535.904523000000", "volume_scope": "clob_v2_onchain", "volume_semantics": "outcome_share_par_notional" } ], "elapsed_ms": 8, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `builder` | string | Builder code (`0x`-prefixed hex, 32 bytes) | | `builder_code` | string | Same builder code, included for profile-style naming consistency | | `builder_name` | string \| null | Public builder profile name when available | | `builder_logo` | string \| null | Public builder profile image URL when available | | `builder_verified` | boolean \| null | Whether the builder profile is verified, when available | | `fill_count` | integer | Total fills attributed to this builder | | `first_fill` | string | Unix timestamp of first fill | | `last_fill` | string | Unix timestamp of most recent fill | | `rank` | integer | Position in the leaderboard | | `source` | string | `local_order_filled_event_index` when local stats are present, otherwise `polymarket_builder_metadata` | | `total_fees` | string | Total fees generated in raw 6-decimal USDC units | | `total_fees_usdc` | string \| null | Total fees normalized to decimal USDC | | `total_maker_volume` | string | Sum of raw maker-side amount fields in 6-decimal units, kept for compatibility | | `total_maker_volume_usdc` | string \| null | Legacy decimal-scaled maker amount. Depending on the fill side, this raw leg can be collateral or outcome shares. | | `total_taker_volume` | string | Sum of raw taker-side amount fields in 6-decimal units, kept for compatibility | | `total_taker_volume_usdc` | string \| null | Legacy decimal-scaled taker amount. Depending on the fill side, this raw leg can be collateral or outcome shares. | | `volume_e6` | string \| null | Canonical total builder volume as outcome-share par notional in raw 6-decimal units | | `volume` | string \| null | Preferred decimal total builder volume; one outcome share counts as \$1 of par notional | | `volume_usdc` | string \| null | Compatibility alias for `volume`; it is par notional, not collateral cash paid | | `buy_volume_e6` | string \| null | Buy-side outcome-share par notional in raw 6-decimal units | | `buy_volume` | string \| null | Decimal buy-side outcome-share par notional | | `buy_volume_usdc` | string \| null | Compatibility alias for `buy_volume` | | `sell_volume_e6` | string \| null | Sell-side outcome-share par notional in raw 6-decimal units | | `sell_volume` | string \| null | Decimal sell-side outcome-share par notional | | `sell_volume_usdc` | string \| null | Compatibility alias for `sell_volume` | | `volume_scope` | string | `clob_v2_onchain`; legacy pre-V2 builder attribution is outside this total | | `volume_semantics` | string | `outcome_share_par_notional` | | `external_rank` | integer \| null | Polymarket's public builder leaderboard rank, when available | | `external_volume` | string \| null | Polymarket's public builder leaderboard volume, when available | | `external_active_users` | integer \| null | Polymarket's public active-user count, when available | | `stats_refreshed_at` | string \| null | Time Polynode last rewrote local stats for this builder | | `stats_checked_at` | string \| null | Time Polynode last checked this builder, including no-op refreshes | | `stats_pending` | boolean | `true` when profile metadata exists but the local stats row has not been populated yet | `builder_name`, `builder_logo`, `builder_verified`, and the local-volume fields are nullable. `external_volume` is separate public profile context and is never substituted into `volume`. Buy and sell volume use the same share-notional basis and add to total builder volume. Use `external_active_users` for the current public builder user-count signal. ## Find a Builder by name Names are matched exactly after trimming whitespace and without case sensitivity. Because display names are not guaranteed to be unique, retain the returned `builder_code` as the stable identifier. ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders?name=BetMoar" ``` ## Print every Builder name and code The directory supports 300 rows per request. This loop follows `has_more` and prints a tab-separated directory without assuming how many Builders currently exist. ```bash theme={null} offset=0 while :; do page=$(curl -fsS -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders?sort=volume&limit=300&offset=${offset}") jq -r '.builders[] | [(.builder_name // ""), .builder_code] | @tsv' <<<"$page" [ "$(jq -r '.has_more' <<<"$page")" = "true" ] || break offset=$((offset + 300)) done ``` ## Related endpoints | Endpoint | Description | | - | - | | `GET /v3/builders/{code}` | Stats for a single builder | | `GET /v3/builders/{code}/leaderboard` | Rank every eligible trader active through one builder by P\&L first, or by attributed activity, over 1D, 7D, 30D, or All Time | | `GET /v3/builders/{code}/activity/daily` | Daily activity and recent top-market/category composition for one Builder | | `GET /v3/builders/activity/daily` | Compare daily activity for up to 20 Builder codes | | `GET /v3/builders/{code}/trades` | Trades attributed to a builder, with market and profile enrichment | # Builder Trader P&L Leaderboard Source: https://docs.polynode.dev/data/builders/trader-leaderboard GET /v3/builders/{code}/leaderboard Rank every trader active through one builder by global wallet P&L, attributed volume, fills, trader-paid fees, active days, or recency. This endpoint answers the most common Builder leaderboard question first: **which traders active through this Builder have the highest P\&L?** It ranks the Builder's eligible trader cohort without intersecting it with a global Top-N list. Each request returns at most 100 rows, and the supported ranking window is the first 500 ranks. * `1d`, `7d`, and `30d` rank by **realized P\&L**. * `all` ranks by **total P\&L** by default and also supports realized or unrealized P\&L. * Existing builder-attributed volume, fills, trader-paid fees, active-day, and recency rankings remain available. > [!WARNING] > > P\&L is the trader wallet's global Polymarket P\&L, not P\&L attributed to the builder. The builder determines which wallets are in the cohort. Builder attribution is available for the activity columns, but order attribution alone cannot assign a wallet's eventual P\&L to one builder. ## Request ```http theme={null} GET /v3/builders/{code}/leaderboard ``` ### Path parameter | Parameter | Type | Description | | - | - | - | | `code` | string | Builder code (with or without `0x`) or exact public Builder name. Hex digits, the prefix, and names are case-insensitive; names must be URL-encoded. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `30d` | `1d`, `7d`, `30d`, or `all` | | `sort` | string | `pnl` | `pnl`, `realized_pnl`, `total_pnl`, `unrealized_pnl`, `volume`, `trades`, `fees`, `active_days`, or `recent` | | `order` | string | `desc` | `asc` or `desc` | | `limit` | integer | `100` | Rows per page, from 1 through 100 | | `offset` | integer | `0` | Rank offset. `offset + limit` must not exceed 500. Five full 100-row pages use offsets `0`, `100`, `200`, `300`, and `400`. | | `pagination` | string | `offset` | `offset` for the historical contract, or `cursor` for repeat-free All-Time P\&L traversal | | `cursor` | string | -- | Opaque `next_cursor` or `previous_cursor` from a cursor response. Pass it unchanged. | | `as_of` | RFC 3339 timestamp | -- | Builder-activity snapshot copied from the first page; required on cursor continuations | | `pnl_as_of` | RFC 3339 timestamp | -- | P\&L snapshot copied from the first page; required on cursor continuations | `sort=pnl` is the recommended stable default. It resolves to `realized_pnl` for `1d`, `7d`, and `30d`, and to `total_pnl` for `all`. The response reports the resolved sort. Dated windows reject `total_pnl` and `unrealized_pnl`; those marked values are only meaningful for All Time. The canonical wire values are `1d`, `7d`, `30d`, and `all`. Period, sort, order, and pagination values are case-insensitive, so `30D`, `ALL`, `TOTAL_PNL`, and `CURSOR` are accepted and returned in canonical lowercase where a corresponding response field exists. `all-time` is not an alias for `all`. Treat cursor values and timestamps as opaque and pass them unchanged. The builder cohort contains every wallet with attributed CLOB V2 maker-order activity in the selected builder window. Fixed builder-activity windows use inclusive UTC dates through `window.complete_through`. Dated P\&L is the canonical rolling realized-P\&L aggregate through `pnl_as_of`; All Time uses the canonical current total, realized, and unrealized wallet summary. `coverage.complete` means every UTC date in the builder cohort window has a successfully built aggregate. P\&L data fails closed when its canonical aggregate is incomplete or stale. No partial ranking is returned as authoritative data. Legacy offset pagination remains the default and its response body is unchanged. Retain every filter and add the number of returned rows to `offset`. Stop when `has_more` is `false`; it is always `false` after rank 500. Rankings use wallet address ascending as the tie-break, regardless of metric or direction. For an All-Time `total_pnl`, `realized_pnl`, or `unrealized_pnl` walk, use `pagination=cursor`. The first request uses `offset=0` without a cursor. Every continuation must keep the same Builder, resolved period, sort, order, and limit; add the number of rows already returned to `offset`; and pass the preceding response's `next_cursor`, `as_of`, and `pnl_as_of`. This pins both snapshots and prevents a wallet already returned in that traversal from appearing again. It does not change any P\&L value, ranking formula, or tie-break. See [Authentication](/authentication) for key creation and [Rate Limits](/guides/rate-limits) for plan availability and current request limits. ## P\&L-first example The example uses BetMoar's public builder code. ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/builders/0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1/leaderboard?period=30d&sort=pnl&limit=1" ``` ```json theme={null} { "builder_code": "0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1", "builder_name": "BetMoar", "builder_logo": "https://example.com/builder.png", "builder_verified": true, "period": "30d", "sort": "realized_pnl", "order": "desc", "limit": 1, "offset": 0, "has_more": true, "cohort_wallet_count": 2101, "eligible_wallet_count": 2101, "window": { "start_date": "2026-08-01", "end_date": "2026-08-30", "complete_through": "2026-08-30" }, "coverage": { "start_date": "2026-04-03", "end_date": "2026-08-30", "complete": true }, "as_of": "2026-08-30T08:12:17.000000Z", "pnl_as_of": "2026-08-30T08:00:00.000000Z", "pnl_scope": "wallet_global_polymarket_not_builder_attributed", "pnl_semantics": "Global Polymarket wallet PnL for traders active through this builder in the selected window. PnL is not attributed to the builder.", "volume_scope": "clob_v2_onchain", "volume_semantics": "outcome_share_par_notional", "fee_semantics": "Trader-paid fees on builder-attributed maker orders. These are not builder rebates.", "data": [ { "rank": 1, "wallet": "0x1111111111111111111111111111111111111111", "trader_address": "0x1111111111111111111111111111111111111111", "realized_pnl": "184250.75", "unrealized_pnl": null, "total_pnl": null, "volume_e6": "248501250000", "volume": "248501.25", "buy_volume_e6": "148500000000", "buy_volume": "148500", "sell_volume_e6": "100001250000", "sell_volume": "100001.25", "trades": 821, "trader_paid_fees_e6": "184200000", "trader_paid_fees": "184.2", "active_days": 24, "first_activity_at": 1785579462, "last_activity_at": 1788043265 } ] } ``` For a dated P\&L ranking, `realized_pnl` is always a decimal string and `total_pnl` / `unrealized_pnl` are `null`. For All Time, all three P\&L fields are decimal strings. ## Walk five All-Time pages without repeats This loop prints as many as 500 rows in pages of 100. It stops earlier when the Builder has fewer eligible traders. If the API returns HTTP `409` because either snapshot advanced, discard the traversal and restart at offset `0`. ```bash theme={null} BUILDER="BetMoar" BASE_URL="https://api.polynode.dev/v3/builders/${BUILDER}/leaderboard" offset=0 cursor="" as_of="" pnl_as_of="" while [ "$offset" -lt 500 ]; do args=( --data-urlencode "period=all" --data-urlencode "sort=total_pnl" --data-urlencode "order=desc" --data-urlencode "limit=100" --data-urlencode "offset=${offset}" --data-urlencode "pagination=cursor" ) if [ "$offset" -gt 0 ]; then args+=( --data-urlencode "cursor=${cursor}" --data-urlencode "as_of=${as_of}" --data-urlencode "pnl_as_of=${pnl_as_of}" ) fi page=$(curl -fsS -G -H "x-api-key: $POLYNODE_API_KEY" \ "${args[@]}" "$BASE_URL") || exit 1 jq -c '.data[]' <<<"$page" rows=$(jq -r '.data | length' <<<"$page") [ "$(jq -r '.has_more' <<<"$page")" = "true" ] || break cursor=$(jq -r '.next_cursor // empty' <<<"$page") [ "$rows" -gt 0 ] && [ -n "$cursor" ] || exit 1 as_of=$(jq -r '.as_of' <<<"$page") pnl_as_of=$(jq -r '.pnl_as_of' <<<"$page") offset=$((offset + rows)) done ``` ## Common queries ```bash theme={null} BUILDER_CODE="0xceebf77a833b30520287ddd9478ff51abbdffa30aa90a8d655dba0e8a79ce0c1" BASE_URL="https://api.polynode.dev/v3/builders/${BUILDER_CODE}/leaderboard" # Recommended defaults: 30-day realized P&L curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}" # 1-day realized P&L curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=1d&sort=pnl" # 7-day realized P&L curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=7d&sort=realized_pnl" # All-Time total, realized, and unrealized P&L rankings curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=all&sort=total_pnl" curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=all&sort=realized_pnl" curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=all&sort=unrealized_pnl" # Existing builder-attributed activity rankings curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=30d&sort=volume" curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=30d&sort=trades" curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=all&sort=fees" # Second 100-row page of the same ranking curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=30d&sort=pnl&limit=100&offset=100" # Fifth and final supported 100-row page curl -H "x-api-key: pn_live_YOUR_KEY" "${BASE_URL}?period=30d&sort=pnl&limit=100&offset=400" # An exact public name also resolves directly curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/builders/BetMoar/leaderboard?period=30d&sort=pnl&limit=100" ``` ## Response fields | Field | Type | Description | | - | - | - | | `builder_code` | string | Normalized builder code | | `builder_name`, `builder_logo`, `builder_verified` | string / boolean / null | Public builder identity when available | | `period` | string | Resolved cohort and P\&L window | | `sort` | string | Resolved sort; `pnl` is returned as `realized_pnl` or `total_pnl` | | `order` | string | Resolved sort direction | | `limit`, `offset`, `has_more` | integer / boolean | Bounded pagination state inside the supported first 500 ranks | | `pagination` | string | `cursor` on opt-in cursor responses; omitted from legacy offset responses | | `previous_cursor`, `next_cursor` | string \| null | Opaque traversal tokens on cursor responses. The first page has no previous cursor; the last page has no next cursor. | | `cohort_wallet_count` | integer | Distinct wallets active through this builder in the selected window; returned for P\&L sorts | | `eligible_wallet_count` | integer | Wallets eligible for the requested P\&L ranking; dated realized-P\&L cohorts include explicit zeroes, while All Time excludes wallets whose canonical current basis or mark is incomplete | | `window` | object | Inclusive UTC dates used to construct the builder-attributed wallet cohort | | `coverage` | object | Full retained builder-activity extent and selected-window completeness | | `as_of` | string | Completion timestamp of the latest builder-activity aggregate | | `pnl_as_of` | string | Canonical P\&L snapshot timestamp; returned for P\&L sorts | | `pnl_scope` | string | `wallet_global_polymarket_not_builder_attributed` for P\&L sorts; `not_applicable_builder_attributed_activity_only` for activity sorts | | `pnl_semantics` | string | Explicit reminder that P\&L is global wallet P\&L, not builder-attributed P\&L; returned for P\&L sorts | | `volume_scope` | string | Always `clob_v2_onchain` | | `volume_semantics` | string | Always `outcome_share_par_notional`; one full outcome share represents \$1 of par notional | | `fee_semantics` | string | Trader-paid fees on attributed maker orders, not builder rebates or revenue | | `data[].rank` | integer | Rank after the requested metric and ascending wallet-address tie-break | | `data[].wallet`, `data[].trader_address` | string | Same normalized trader wallet address | | `data[].realized_pnl` | string | Global wallet realized P\&L for the requested period; returned for P\&L sorts | | `data[].unrealized_pnl` | string \| null | Global wallet current unrealized P\&L for All Time; `null` for dated P\&L | | `data[].total_pnl` | string \| null | Global wallet current total P\&L for All Time; `null` for dated P\&L | | `data[].volume_e6`, `data[].volume` | string | Builder-attributed outcome-share par notional in raw 6-decimal and decimal units | | `data[].buy_volume_e6`, `data[].sell_volume_e6` | string | Raw 6-decimal signed-order-side attributed volume | | `data[].buy_volume`, `data[].sell_volume` | string | Decimal signed-order-side attributed volume | | `data[].trades` | integer | Builder-attributed maker-order fills in the cohort window | | `data[].trader_paid_fees_e6`, `data[].trader_paid_fees` | string | Trader-paid fees in raw six-decimal and decimal USDC units | | `data[].active_days` | integer | UTC dates with at least one attributed fill in the cohort window | | `data[].first_activity_at`, `data[].last_activity_at` | integer | First and last attributed fill times in Unix seconds | ## Errors | Status | Error | Meaning | | - | - | - | | `400` | `invalid_builder`, `invalid_period`, `invalid_sort`, `invalid_order`, `invalid_limit`, `invalid_offset`, `invalid_pagination`, `invalid_cursor`, `invalid_as_of`, or `invalid_pnl_as_of` | A path or query value is invalid, a cursor continuation changed its bound inputs, or the requested page extends beyond rank 500 | | `401` | authentication error | The API key is missing or invalid | | `402` | payment required | The key's plan does not include paid V3 REST data | | `404` | `builder_not_found` | The normalized builder has no metadata or indexed activity | | `409` | `ambiguous_builder_name` or `builder_trader_leaderboard_snapshot_changed` | Use a code for an ambiguous name, or restart a traversal at offset `0` when a pinned snapshot advances | | `429` | rate limit exceeded | The account's shared V3 REST request limit was exceeded | | `503` | `builder_trader_leaderboard_unavailable` | Required builder activity or P\&L data is incomplete, stale, or unavailable; no partial ranking is returned | ## Related endpoints | Endpoint | Description | | - | - | | [`GET /v3/builders`](/data/builders/list) | Rank all builders by attributed activity | | [`GET /v3/builders/{code}`](/data/builders/detail) | Inspect one builder's profile and totals | | [`GET /v3/builders/{code}/activity/daily`](/data/builders/daily-activity) | Inspect daily activity and recent composition for this Builder | | [`GET /v3/builders/{code}/trades`](/data/builders/trades) | Paginate the underlying builder-attributed fills | # Builder Trades Source: https://docs.polynode.dev/data/builders/trades GET /v3/builders/{code}/trades Get trades attributed to a specific builder, with builder profile and market enrichment. Returns fills attributed to a specific builder, enriched with builder profile metadata and market context. Use token, market, event, side, size, and time filters to narrow the trade feed. ## Request ``` GET /v3/builders/{code}/trades ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `code` | string | Builder code (with or without `0x`) or exact public Builder name. Hex digits, the prefix, and names are case-insensitive; names must be URL-encoded. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `token_id` | string | -- | Filter trades involving this outcome token | | `condition_id` | string | -- | Filter by market condition ID (resolves to token IDs) | | `market_slug` | string | -- | Filter by market slug (resolves to token IDs) | | `event_slug` | string | -- | Filter by event slug (resolves to token IDs across the event) | | `event_id` | integer | -- | Filter by numeric event ID (same scope as `event_slug`) | | `side` | string | -- | `buy` or `sell`, based on the maker order side | | `min_amount_usd` | number | -- | Minimum trade size in dollars, matching the `amount_usd` response field. Decimals allowed, e.g. `99.5` | | `min_amount` | integer | -- | Minimum `maker_amount_filled` (raw 6-decimal). Prefer `min_amount_usd` | | `category` | string | -- | Filter by market category. Broad categories may return `400` asking for a narrower filter. | | `tag_slug` | string | -- | Filter by market tag slug. Broad tags may return `400` asking for a narrower filter. | | `after` | integer | 0 | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&limit=1" ``` ```json theme={null} { "builder": "0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df", "builder_code": "0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df", "builder_logo": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-4043800-ced7ecde-0754-46a1-8a16-bb6c338fbf39.png", "builder_name": "PolyCop", "builder_verified": true, "elapsed_ms": 134, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1, "trades": [ { "amount": 34.62, "amount_usd": 34.58538, "asset": "21578184864194020862792310253337084708609281967112790860038966988826118995357", "builder": "0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df", "builder_code": "0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df", "builder_logo": "https://polymarket-upload.s3.us-east-2.amazonaws.com/profile-image-4043800-ced7ecde-0754-46a1-8a16-bb6c338fbf39.png", "builder_name": "PolyCop", "builder_verified": true, "condition_id": "0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86", "direction": "SELL", "event_id": 507638, "event_slug": "dota2-tundra-xtreme-2026-05-22", "fee": 0.00103, "id": "0x5177eefeb47113ec68797a30997eadc7bc7f1e748358ea240ca4c391f29c06d6_0x95a8da83ec734acb0324ee2af0c05551a85b55ef824e0c898ed0ab613d9eab69_1025", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/dota2-7ffacddb21.jpg", "maker": "0x952d11ebff81d6bd3185e608ed3515b94618ab8a", "maker_amount": 34.62, "maker_asset_id": "21578184864194020862792310253337084708609281967112790860038966988826118995357", "market": "Dota 2: Tundra Esports vs Xtreme Gaming - Game 1 Winner", "order_hash": "0x95a8da83ec734acb0324ee2af0c05551a85b55ef824e0c898ed0ab613d9eab69", "outcome": "Tundra Esports", "outcome_index": 0, "price": 0.999, "role": "maker", "side": 1, "size": 34.62, "slug": "dota2-tundra-xtreme-2026-05-22-game1", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "taker_amount": 34.58538, "taker_asset_id": "0", "timestamp": "1779449911", "token_id": "21578184864194020862792310253337084708609281967112790860038966988826118995357", "transaction_hash": "0x5177eefeb47113ec68797a30997eadc7bc7f1e748358ea240ca4c391f29c06d6" } ] } ``` ## Response fields ### Response envelope | Field | Type | Description | | - | - | - | | `builder` | string | Builder code requested in the path | | `builder_code` | string | Same builder code, included for profile-style naming consistency | | `builder_name` | string \| null | Public builder profile name when available | | `builder_logo` | string \| null | Public builder profile image URL when available | | `builder_verified` | boolean \| null | Whether the builder profile is verified, when available | | `trades` | array | Trade rows attributed to this builder | | `rows_returned` | integer | Number of trade rows returned | | `has_more` | boolean | Whether another page is available | | `offset` | integer | Pagination offset used | | `limit` | integer | Page size used | | `elapsed_ms` | integer | Server-side query time in milliseconds | ### Trade data Each trade contains the same enriched fields as [Wallet Trades](/data/wallets/trades), including market context, computed price/size, order hash, and direction. Builder metadata is also repeated on each row for clients that stream or store trade rows independently. | Field | Type | Description | | - | - | - | | `builder_code` | string | Builder code for this trade row | | `builder_name` | string \| null | Public builder profile name when available | | `builder_logo` | string \| null | Public builder profile image URL when available | | `builder_verified` | boolean \| null | Whether the builder profile is verified, when available | ## Filter examples ### Trades for a specific token ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?token_id=21578184864194020862792310253337084708609281967112790860038966988826118995357&limit=10" ``` ### Trades for a specific market ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&limit=10" ``` ### Maker-side buys or sells ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?side=buy&limit=10" curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?side=sell&limit=10" ``` ### Combine tag/category with a narrow market filter ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&tag_slug=sports&limit=10" curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&category=Sports&limit=10" ``` Builder categories are derived from the first market tag. Broad `category` and `tag_slug` filters can be too large to run directly; add `market_slug`, `condition_id`, or `token_id` to use the indexed intersection path. ```json theme={null} { "error": "tag_slug filter too broad for builder trades; add market_slug, condition_id, token_id, or time bounds" } ``` ## Name-resolution errors | Status | Error | Meaning | | - | - | - | | `404` | `builder_not_found` | No Builder matches a supplied public name | | `409` | `ambiguous_builder_name` | More than one Builder uses the supplied name; use a code from the Builder directory | ## Related endpoints | Endpoint | Description | | - | - | | `GET /v3/builders` | Builder leaderboard | | `GET /v3/builders/{code}` | Stats and profile metadata for this builder | | `GET /v3/builders/{code}/leaderboard` | Rank this Builder's active trader cohort | | `GET /v3/builders/{code}/activity/daily` | Daily attributed activity for this Builder | # Combo Activity Source: https://docs.polynode.dev/data/combos/activity GET /v3/combos/activity Query combo lifecycle activity by market, condition, position, or wallet. Returns combo lifecycle activity across wallets. At least one of `market_id`, `condition_id`, or `position_id` is required. Add `wallet` to narrow results to a single wallet, or to every wallet an owner EOA owns. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/combos/activity ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | Alias for `condition_id` | | `condition_id` | string | -- | Combo condition ID | | `position_id` | string | -- | Combo position ID | | `wallet` | string | -- | Wallet address or owner EOA | | `event_kind` | string | -- | Filter by event kind, for example `PositionsSplit` or `PositionRedeemed` | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/combos/activity?condition_id=0x03d98f6ac4c108c5ca66f79f34908a1d820000000000000000000000000000&limit=10" ``` ```json theme={null} { "activity": [ { "position_type": "combo", "event_kind": "PositionsSplit", "wallet_address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "combo_condition_id": "0x03d98f6ac4c108c5ca66f79f34908a1d820000000000000000000000000000", "amount_usdc": "0.050750", "tx_hash": "0xf3a8985f04bf869483ef4163a185f296c834eb827b5e5ae3db5bd44558121d51", "block_number": 88276713, "timestamp": 1781120055 } ], "rows_returned": 10, "has_more": true, "position_type": "combo", "source": "v3.combos.activity" } ``` ## Owner address fields Present only when `wallet` is an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `activity[].wallet` | string | The wallet this row belongs to | ## Notes * Use `/v3/wallets/{address}/combos/activity` when the wallet address is already known. * Use `/v3/combos/redemptions` when you need terminal-versus-partial redemption evidence or condition/position lineage. * Use this endpoint when you are exploring all lifecycle activity for a combo market or position. * The activity feed is on-chain derived and can include split, merge, redemption, and transfer-related lifecycle rows as those events are observed. * Public combo redemption rows are normalized to Polymarket's combo activity shape: router and auto-redeemer redemption paths are returned as `event_kind: "PositionRedeemed"` with `side: "Redeem"`, a module kind such as `Combinatorial`, `Binary`, or `NegRisk`, and `payout_usdc` when available. * When leg metadata is available, resolved combo activity includes leg statuses such as `RESOLVED_WIN` or `RESOLVED_LOSS` and `leg_current_price` values. # Combo Daily Activity Source: https://docs.polynode.dev/data/combos/daily-activity GET /v3/combos/activity/daily Chart complete UTC-day Combo fills, share volume, lifecycle activity, mapped transfers, and exact redemptions. `GET /v3/combos/activity/daily` returns one zero-filled row for every UTC day in a bounded window. Use it to build daily Combo charts without paging and joining four separate feeds in your application. History is complete from `2026-05-29`. The current UTC day is included but has `complete: false` because more activity can still arrive. ## Request ```text theme={null} GET /v3/combos/activity/daily ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `30d` | `1d`, `7d`, or `30d`. Do not combine it with explicit dates. | | `start_date` | date | none | Inclusive UTC date in `YYYY-MM-DD` format. Requires `end_date`. | | `end_date` | date | none | Inclusive UTC date in `YYYY-MM-DD` format. Requires `start_date`. | | `interval` | string | `day` | Only `day` is supported. | An explicit range can contain at most 30 days, including both endpoints. It cannot begin before `2026-05-29` or end after the current UTC date. ## Examples Use a rolling period: ```bash theme={null} curl "https://api.polynode.dev/v3/combos/activity/daily?period=7d" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use an inclusive date range: ```bash theme={null} curl "https://api.polynode.dev/v3/combos/activity/daily?start_date=2026-08-01&end_date=2026-08-02" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "start_date": "2026-08-01", "end_date": "2026-08-02", "interval": "day", "timezone": "UTC", "coverage_start": "2026-05-29", "complete_through": "2026-08-01", "as_of": "2026-08-02T12:04:05Z", "as_of_block": 90000000, "share_volume_unit": "shares", "share_volume_semantics": "sum of indexed combo fill share size, not USD notional", "side_semantics": "BUY and SELL are the signed ExchangeV3 OrderFilled order side, not wallet-direction or platform-net flow", "count_semantics": { "fills": "indexed combo trade rows", "lifecycle": "indexed Prepare, Split, Merge, and Redeem events", "transfers": "indexed combo position transfer rows joined to the canonical position-to-combo mapping", "exact_redemptions": "canonical redemption rows, split into full, partial, and transformation scopes" }, "days": [ { "date": "2026-08-01", "complete": true, "fill_count": 18, "signed_order_buy_fill_count": 10, "signed_order_sell_fill_count": 8, "share_volume_e6": "42500000", "share_volume": "42.5", "signed_order_buy_share_volume_e6": "25000000", "signed_order_buy_share_volume": "25", "signed_order_sell_share_volume_e6": "17500000", "signed_order_sell_share_volume": "17.5", "lifecycle_count": 9, "prepare_event_count": 2, "prepared_combo_count": 2, "split_count": 3, "merge_count": 2, "redeem_event_count": 2, "mapped_transfer_count": 21, "exact_redemption_count": 3, "full_redemption_count": 1, "partial_redemption_count": 1, "transformation_count": 1 }, { "date": "2026-08-02", "complete": false, "fill_count": 0, "signed_order_buy_fill_count": 0, "signed_order_sell_fill_count": 0, "share_volume_e6": "0", "share_volume": "0", "signed_order_buy_share_volume_e6": "0", "signed_order_buy_share_volume": "0", "signed_order_sell_share_volume_e6": "0", "signed_order_sell_share_volume": "0", "lifecycle_count": 0, "prepare_event_count": 0, "prepared_combo_count": 0, "split_count": 0, "merge_count": 0, "redeem_event_count": 0, "mapped_transfer_count": 0, "exact_redemption_count": 0, "full_redemption_count": 0, "partial_redemption_count": 0, "transformation_count": 0 } ] } ``` ## Metric semantics | Fields | Meaning | | - | - | | `fill_count`, `share_volume*` | Indexed Combo fill rows and their share size. The `_e6` values are exact integer micro-shares; display values are decimal strings. | | `signed_order_buy_*`, `signed_order_sell_*` | The signed ExchangeV3 order side on each fill. These are not a wallet's direction. | | `prepare_event_count` | Indexed `Prepare` lifecycle events. | | `prepared_combo_count` | Distinct Combo condition IDs prepared that day. | | `split_count`, `merge_count`, `redeem_event_count` | Indexed lifecycle events with those actions. | | `mapped_transfer_count` | Transfer rows whose position ID joins to the canonical position-to-Combo mapping. | | `exact_redemption_count` | Canonical redemption rows; the full, partial, and transformation counts partition this family. | `redeem_event_count` and `exact_redemption_count` come from different canonical fact families. Do not assume they are equal on every day. ## Completeness and no-go interpretations * `complete_through` is the last fully covered UTC date certified by all required checkpoints. A day after it has `complete: false`. * Zeroes are emitted only inside the documented coverage window. They mean no matching canonical facts were indexed for that day, not missing pagination. * Share volume is **not USD notional**. Do not put a dollar sign on it or add it to USD volume. * Signed BUY/SELL is **not wallet direction** and cannot establish wallet buys, wallet sells, or net platform flow. * This route does not reconstruct a historical active-Combo count or infer a state snapshot from lifecycle events. ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_period` or `invalid_interval` | Unsupported period or an interval other than `day`. | | `400` | `conflicting_date_range` | `period` was combined with explicit dates. | | `400` | `incomplete_date_range` | Only one explicit date was supplied. | | `400` | `invalid_date` or `invalid_date_range` | A date is malformed, reversed, outside coverage, or in the future. | | `400` | `date_range_too_large` | The inclusive range exceeds 30 days. | | `401` | authentication error | The API key is missing or invalid. | | `503` | `temporarily_unavailable` | A required checkpoint or bounded query is unavailable. The response fails closed instead of returning a partial series. | The `503` body is intentionally generic. Retry the complete request; do not treat it as a zero-activity window. # Combo P&L Leaderboard Source: https://docs.polynode.dev/data/combos/leaderboard GET /v3/combos/leaderboard Rank eligible Combo wallets by realized P&L over fixed or custom windows, or by marked All Time P&L. `GET /v3/combos/leaderboard` ranks wallets using the dedicated Combo cost-basis ledger. It supports realized P\&L for 1-day, 7-day, 30-day, and custom windows, plus realized, unrealized, and total P\&L for All Time. The route is intentionally global. It does **not** accept tag, category, market, or event filters. ## Request ```text theme={null} GET /v3/combos/leaderboard ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `all` | `all`, `1d`, `7d`, `30d`, or `custom` | | `after` | integer | none | Inclusive custom lower bound in Unix seconds | | `before` | integer | none | Exclusive custom upper bound in Unix seconds | | `sort_by` | string | mode-specific | `total_pnl`, `realized_pnl`, or `unrealized_pnl` | | `limit` | integer | `100` | Rows per page; maximum `300` | | `offset` | integer | `0` | Rank offset; maximum `100000` | The window rules are strict: * `period=custom` requires `after`, `before`, or both. When both are present, the realized window is half-open: `[after, before)`. * `after` and `before` are forbidden with `all`, `1d`, `7d`, or `30d`. * All Time accepts all three sort fields and defaults to `total_pnl`. * Fixed and custom windows rank `realized_pnl` only. ## Examples Rank marked All Time total P\&L: ```bash theme={null} curl "https://api.polynode.dev/v3/combos/leaderboard?period=all&sort_by=total_pnl" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Rank realized P\&L in one half-open window: ```bash theme={null} curl "https://api.polynode.dev/v3/combos/leaderboard?period=custom&after=1788134400&before=1788220800&sort_by=realized_pnl" \ -H "x-api-key: $POLYNODE_API_KEY" ``` One-sided custom windows are also valid. Omitting `after` leaves the lower side open; omitting `before` leaves the upper side open. ## Response ```json theme={null} { "data": [ { "rank": 1, "wallet_address": "0x1111111111111111111111111111111111111111", "realized_pnl": "125.5", "unrealized_pnl": "12.25", "total_pnl": "137.75", "open_combo_count": 2, "closed_combo_count": 4, "position_count": 6, "event_count": 18, "last_activity_at": "2026-08-29T16:00:00Z", "win_count": 3, "loss_count": 1, "resolved_count": 4, "win_rate": "0.7500" } ], "period": "all", "window": { "after": null, "before": null }, "pnl_scope": "all_time_marked", "coverage": { "status": "direct_cost_basis_only", "raw_wallet_transfers_included": false, "eligible_wallet_count": 40, "excluded_wallet_count": 3, "transfer_incomplete_wallet_count": 2, "unmarked_wallet_count": 1 }, "as_of": "2026-08-29T16:01:00Z", "as_of_block": 90123456, "source": "combo_state.combo_cost_basis_event" } ``` ### Window and scope | Field | Meaning | | - | - | | `period` | Normalized requested period | | `window.after` | Inclusive resolved lower bound in Unix seconds, or `null` | | `window.before` | Exclusive resolved upper bound in Unix seconds, or `null` | | `pnl_scope` | `all_time_marked` for All Time; `realized_only` for fixed and custom windows | | `as_of` | RFC3339 ledger-snapshot time | | `as_of_block` | Indexed block used by the snapshot | | `source` | Always `combo_state.combo_cost_basis_event` | All Time returns two null window bounds. Fixed `1d`, `7d`, and `30d` responses return both concrete resolved bounds. A custom response preserves an omitted side as `null`. ### Row fields All USD P\&L values are decimal strings. Do not parse them through a binary floating-point type when exact arithmetic matters. | Field | Meaning | | - | - | | `rank` | Rank in the requested ordering | | `wallet_address` | Eligible wallet address | | `realized_pnl` | Realized Combo P\&L in decimal USD | | `unrealized_pnl` | Marked unrealized Combo P\&L in decimal USD; `null` in realized-only modes | | `total_pnl` | Realized plus unrealized P\&L in decimal USD; `null` in realized-only modes | | `open_combo_count` | Current eligible open Combo positions, not window-scoped | | `closed_combo_count` | Current eligible closed Combo positions, not window-scoped | | `position_count` | Current eligible Combo position snapshot count, not window-scoped | | `event_count` | Eligible direct-basis events in the realized window; All Time counts all eligible direct-basis events | | `last_activity_at` | RFC3339 time of the wallet's latest eligible Combo activity, or `null` | | `win_count` | Resolved Combo positions the wallet won, all time, not window-scoped | | `loss_count` | Resolved Combo positions the wallet lost, all time, not window-scoped | | `resolved_count` | `win_count` + `loss_count` | | `win_rate` | `win_count` / `resolved_count` as a 4-decimal fraction string (`"0.7500"` = 75%), or `null` when the wallet has no resolved Combo | A Combo position is won or lost once its legs resolve: a YES position wins when every leg wins and loses as soon as any leg loses; a NO position is the reverse. For one wallet's win and loss counts inside a time window, call [Wallet Combo Summary](/data/combos/wallet-summary#time-windows) with `period=custom` and this response's `window.after` / `window.before`. The two place activity differently: ranged leaderboard P\&L follows realized events, and windowed win/loss counts follow when each combo settled. ## Cost basis, marks, and exclusions `coverage.status` is always `direct_cost_basis_only`. The leaderboard uses directly attributable Combo cost-basis events and does not invent basis for an arbitrary wallet-to-wallet transfer. Every ExchangeV3 `OrderFilled` row is attributed once to its signed-order maker; the event's collateral-denominated fee increases BUY cost or reduces SELL proceeds. Router and auto-redemptions are admitted only when their paired `PositionRedeemed` record proves the redeemed size and payout. ### Which fees are included? The included fee is specifically the collateral-denominated exchange fee recorded in each signed order's `OrderFilled.fee`. It increases BUY cost or reduces SELL proceeds, so do not deduct that fee again from Combo P\&L. "Maker" here identifies the signed-order owner; it does not by itself establish who supplied liquidity. This field does not provide a breakdown of fee components. Gas, separately collected application or escrow charges, and rebates or rewards outside this recorded fill fee are not included by this calculation. Do not describe Combo P\&L as including every cost or credit. Standard spot [Wallet P\&L](/data/wallets/pnl) excludes separately reported fees, rebates, and rewards. Perps uses a separate accounting model. The Combo rule must not be applied to either product's P\&L. Open Combo balances are marked with the latest Combo fill. Terminal Combo positions are marked at `1` for a winning payout or `0` for a losing payout. The endpoint does not replace a missing open mark with zero. A wallet is omitted from `data` when any position lacks complete direct cost basis, its raw-transfer basis is incomplete, or a required mark is unavailable. Omitted wallets are **never zero-filled** and therefore cannot silently fall to the bottom of the ranking. Inspect these fields before displaying results: | Coverage field | Meaning | | - | - | | `eligible_wallet_count` | Wallets eligible for this ranking snapshot | | `excluded_wallet_count` | Wallets omitted for incomplete direct/transfer basis or a missing mark | | `transfer_incomplete_wallet_count` | Wallets whose arbitrary raw transfer prevents complete direct basis | | `unmarked_wallet_count` | Wallets without every mark required by the requested ranking | | `raw_wallet_transfers_included` | Always `false`; arbitrary transferred basis is not inferred | ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_request` | Invalid period, custom bound combination, sort, limit, or offset | | `401` | authentication error | The API key is missing or invalid | | `503` | `combo_pnl_unavailable` | The Combo P\&L ledger or required mark snapshot is unavailable | An unavailable response is exact: ```json theme={null} { "error": "combo_pnl_unavailable", "message": "Combo P&L is temporarily unavailable." } ``` The endpoint fails closed instead of returning a partial ranking. # Combo Markets Source: https://docs.polynode.dev/data/combos/markets GET /v3/combos/markets List observed Polymarket combo markets with legs and activity counters. Returns observed combo markets. Each market includes its combo condition, status, activity counters, volume, and a `legs` array when leg metadata is available. ## Request ``` GET /v3/combos/markets ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | Alias for `condition_id` | | `condition_id` | string | -- | Combo condition ID | | `status` | string | -- | `observed` or `all`. Every combo market is `observed`; see [Resolution](#resolution) | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/combos/markets?limit=2" ``` ```json theme={null} { "markets": [ { "combo_condition_id": "0x03c58e66825a6501dfffbf7dd0e802c3470000000000000000000000000000", "module_name": "CombinatorialModule", "status": "observed", "observed_execution_count": 10, "observed_lifecycle_count": 16, "observed_transfer_count": 32, "volume_usdc": "427.01", "last_activity_at": "2026-06-11T02:07:18+00:00", "legs": [ { "leg_index": 0, "leg_position_id": "770259566746216134461634134886555299946416955842760322422283095048103919616", "leg_status": "OPEN", "market_slug": "fifwc-gha-pan-2026-06-17-spread-away-1pt5", "market_title": "Panama (-1.5)", "event_title": "Ghana vs. Panama - More Markets", "leg_current_price": "0.0000" } ] } ], "rows_returned": 2, "has_more": true, "position_type": "combo", "source": "v3.combos.markets", "elapsed_ms": 148 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `combo_condition_id` | string | Combo condition ID | | `module_name` | string | Combo module name, usually `CombinatorialModule` | | `status` | string | Always `observed`: the market was seen on chain. It does not change when legs resolve | | `observed_execution_count` | integer | Observed combo execution count | | `observed_lifecycle_count` | integer | Observed split/merge/lifecycle count | | `observed_redeem_count` | integer | Observed combo redemption count | | `observed_transfer_count` | integer | Observed combo position transfer count | | `volume_usdc` | string | Observed combo volume formatted in USDC | | `last_activity_at` | string | Last observed combo activity timestamp | | `legs` | array | Market legs that define the combo | ## Resolution A combo market has no resolution of its own: each leg is a normal market that resolves on its own schedule, so a combo can have some legs resolved and others still open. Read each leg's result from `legs[].leg_status` (`RESOLVED_WIN` or `RESOLVED_LOSS` once that leg resolves) with `leg_resolved_at`; the market-level `status` stays `observed`. A combo's YES side wins when every leg wins and loses as soon as any leg loses; the NO side is the reverse. Per-wallet outcomes are on [Wallet Combo Positions](/data/combos/wallet-positions) (`status=resolved_win`, `resolved_loss`, or `resolved`) and as counts on [Wallet Combo Summary](/data/combos/wallet-summary#win-and-loss-counts). Resolved leg metadata is refreshed from Polymarket combo metadata when available. Leg rows can include `leg_status` values such as `RESOLVED_WIN` or `RESOLVED_LOSS`, `leg_resolved_at`, and `leg_current_price`. # Combos Overview Source: https://docs.polynode.dev/data/combos/overview Query Polymarket combo markets, combo wallet positions, combo trades, and combo lifecycle activity. Combos are Polymarket's combinatorial positions: one position is defined by multiple market legs. PolyNode indexes those on-chain combo positions separately from standard CTF positions, then exposes them through dedicated combo endpoints and opt-in wallet aggregates. Use the dedicated combo endpoints when you want combo-only data. Use `include_combos=true` on supported wallet endpoints when you want the wallet-level response to include both standard market data and combo data. ## Base URL ``` https://api.polynode.dev/v3 ``` ## Dedicated combo endpoints | Endpoint | Description | | - | - | | `GET /v3/combos/markets` | List observed combo markets with leg metadata | | `GET /v3/combos/activity` | List combo lifecycle activity for a market, condition, position, or wallet | | `GET /v3/combos/activity/daily` | Complete UTC-day fills, share volume, lifecycle, transfer, and redemption series | | `GET /v3/combos/leaderboard` | Eligible-wallet realized P\&L windows and marked All Time P\&L with explicit exclusions | | `GET /v3/combos/redemptions` | Full redemptions, partial reductions, and exact combo lineage across wallets | | `GET /v3/wallets/{address}/combos/positions` | Combo positions for one wallet | | `GET /v3/wallets/{address}/combos/trades` | Combo trades for one wallet | | `GET /v3/wallets/{address}/combos/activity` | Combo lifecycle activity for one wallet | | `GET /v3/wallets/{address}/combos/redemptions` | Full redemptions and partial reductions for one wallet | | `GET /v3/wallets/{address}/combos/summary` | Combo-only P\&L, position counts, and win/loss counts (all time or windowed) for one wallet | ## Additive wallet support These wallet endpoints support `include_combos=true`: | Endpoint | Behavior | | - | - | | `GET /v3/wallets/{address}` | Adds combo P\&L/counts to the all-time wallet summary | | `GET /v3/wallets/{address}/pnl` | Adds combo P\&L/counts to all-time wallet P\&L | | `GET /v3/wallets/{address}/positions` | Appends combo positions to the position list | | `GET /v3/wallets/{address}/trades` | Adds a `combo_trades` branch alongside the standard trade list | If a wallet has no combo exposure, `include_combos=true` still returns `200` with the normal wallet response and a zero combo contribution or empty combo branch. Clients do not need to know ahead of time whether a wallet has traded combos. ## Identifier notes | Identifier | Description | | - | - | | `combo_condition_id` | Combo condition ID. Returned as a hex string. | | `position_id` / `combo_position_id` | ERC-1155 position ID for the combo leg or combo position. Returned as a string because it can exceed JavaScript integer precision. | | `legs` | Array of market legs that define the combo position. Legs may include market slug/title, event slug/title, outcome label, current price, and leg status when metadata is available. | | `redemption_scope` | `full`, `partial`, or `transformation` on combo redemption rows. | | `reduced_combo_condition_id` / `residual_combo_condition_id` | Exact on-chain lineage for partial combo reductions. | ## P\&L semantics Combo P\&L uses the same high-level model as standard Polymarket positions: weighted-average cost basis, realized P\&L from closes/redeems/merges, and unrealized P\&L for open balances when a current price is available. The [Combo P\&L Leaderboard](/data/combos/leaderboard) is stricter than a single-wallet summary: it ranks only wallets with complete direct cost basis and every required mark. Wallets with arbitrary transfer-basis gaps or missing marks are omitted and disclosed, never presented as zero-P\&L rows. When a combo is redeemed, Polynode settles the redeemed size against weighted-average entry basis. Fully redeemed winners return `RESOLVED_WIN` with zero open entry cost and realized P\&L from the redemption payout; fully redeemed losers return `RESOLVED_LOSS`. Combo redemption activity is normalized to Polymarket's public `PositionRedeemed` shape even when the on-chain path used the router or auto-redeemer. The dedicated redemption endpoints distinguish a terminal redemption, a post-resolution compression into a smaller combo, and a structural extraction. `Compressed` provides the old/new position transition; `Extracted` provides full/reduced/residual condition lineage without falsely claiming a payout. Both can show that a three-leg combo became a two-leg combo and return remaining/removed leg sets. See [Combo Redemptions](/data/combos/redemptions). All aggregate P\&L fields are returned as decimal USD numbers. Event-level combo amount fields use decimal strings such as `"0.050750"` for exact USDC-style display. # Combo Redemptions Source: https://docs.polynode.dev/data/combos/redemptions GET /v3/combos/redemptions Query terminal combo redemptions, partial post-resolution compression, and exact on-chain lineage. Use this endpoint to answer one question: after a user's combo (parlay) was processed, was the whole position redeemed, or were settled legs removed and a smaller combo left behind? The response preserves Polymarket's public combo activity fields and adds the explicit before-and-after transition. That includes what the combo contained before the operation, which legs were removed, what remained, and whether the resulting combo is still held. This endpoint is additive. It does not change standard positions or combo position responses. Use [`GET /v3/combos/activity`](/data/combos/activity) for ordinary combo acquisition and burn activity such as `PositionsSplit` and `PositionsMerged`. This endpoint is scoped to terminal redemptions, post-resolution compression, and the module-level transformations needed to explain redemption lineage. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## The consumer view * A **full redemption** means the complete combo was consumed. `remaining_leg_count` is `0`, and there is no remaining combo position. * A **partial redemption** means post-resolution compression removed one or more settled legs and produced a smaller combo. `remaining_combo` identifies the resulting position and, when available, whether the wallet still holds it. * A **transformation** changes combo structure but is not evidence of a redemption payout. These rows are kept separate so extraction or wrapping is not mistaken for money being redeemed. For example, `leg_transition: "5_to_1"` means a five-leg combo became a one-leg combo. Four legs were removed, one leg remained, and the user may still hold the new one-leg position. ## How this differs from Polymarket combo activity Polymarket provides a public [combo activity endpoint](https://docs.polymarket.com/api-reference/core/get-user-combo-activity) and [combo positions endpoint](https://docs.polymarket.com/api-reference/core/get-user-combo-positions). The activity response supplies the lifecycle event, reported combo identifiers, amount or payout, transaction details, and a per-leg breakdown. polynode preserves that basic record and adds the transaction-level interpretation needed to explain the redemption directly: | Question | Polymarket combo activity | polynode combo redemptions | | - | - | - | | What operation happened? | `REDEEM`, `COMPRESS`, and other lifecycle types | Preserved as `type` and `event_kind` | | Was the whole combo redeemed or did a smaller combo remain? | Inferred from the operation and surrounding position state | Explicit `redemption_scope`, `redemption_type`, and terminal/partial flags | | What did the operation start with and produce? | The activity row identifies the reported combo | Explicit source, full, reduced, and destination condition and position IDs | | How many legs were removed and left? | Not explicit in the activity row | `source_leg_count`, `removed_leg_count`, `remaining_leg_count`, and `leg_transition` | | Which exact legs changed? | One `legs` array for the reported combo | Separate `source_legs`, `removed_legs`, and `remaining_legs` arrays | | Does the user still hold the resulting combo? | Requires a combo-position lookup | Compact `remaining_combo` snapshot when the balance is available | In the public `5_to_1` transaction used below, Polymarket reports a `COMPRESS` event with the resulting one-leg combo. polynode also identifies the consumed five-leg combo, the four removed legs, the exact source-to-destination position transition, and the remaining holding. This removes the need to reconstruct the change from separate activity and position records. ## Request ``` GET /v3/combos/redemptions ``` No filter is required. Use the filters below for wallet, market, position, transaction, event, scope, or time-bounded reads. ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `wallet` | string | -- | Wallet address or owner EOA | | `market_id` | string | -- | One or more comma-separated combo condition IDs. Matches any condition in the lineage. | | `condition_id` | string | -- | Combo condition ID. Matches the source, full, parent, reduced, residual, child, or destination condition. | | `position_id` | string | -- | Decimal ERC-1155 position ID. Matches the primary, source, destination, or underlying position. | | `event_kind` | string | -- | `PositionRedeemed`, `Compressed`, `Extracted`, `Unwrapped`, or another supported combo lifecycle event | | `redemption_scope` | string | `all` | `full`, `partial`, `transformation`, or `all` | | `redemption_type` | string | `all` | `FULL_COMBO`, `PARTIAL_COMBO`, `COMBO_TRANSFORMATION`, or `all` | | `tx_hash` | string | -- | Exact Polygon transaction hash | | `after` | integer | -- | Inclusive Unix timestamp in seconds | | `before` | integer | -- | Inclusive Unix timestamp in seconds | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ### Owner address fields Present only when `wallet` is an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `redemptions[].wallet` | string | The wallet this row belongs to | ## Full redemptions ```bash theme={null} curl "https://api.polynode.dev/v3/combos/redemptions?wallet=0xf83ec0e37ac9eece71c064507270e9001a734663&redemption_scope=full&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "event_kind": "PositionRedeemed", "redemption_scope": "full", "redemption_type": "FULL_COMBO", "redemption_evidence": "terminal_position_redeemed", "is_full_combo_redemption": true, "is_partial_combo_redemption": false, "is_terminal_redemption": true, "is_partial_combo_reduction": false, "has_collateral_payout": true, "combo_condition_id": "0x03c90d5cf41198141f9d85cee33943b3750000000000000000000000000000", "combo_position_id": "1712167034491293012950849257976671163728504435933953725817269660684235309057", "payout_usdc": "0.001749", "source_leg_count": 3, "removed_leg_count": 3, "remaining_leg_count": 0, "leg_transition": "3_to_0", "legs": [ {"leg_index": 0, "leg_outcome_label": "Yes"}, {"leg_index": 1, "leg_outcome_label": "No"}, {"leg_index": 2, "leg_outcome_label": "No"} ] } ``` `PositionRedeemed` proves that the entire referenced combo position was redeemed. A terminal `Compressed` event whose destination position is `0` is also classified as `full`, with `redemption_evidence: "terminal_compression"`. Router and auto-redeemer transactions use the user-facing wallet rather than attributing the redemption to an intermediary contract. ## Partial post-resolution redemptions ```bash theme={null} curl "https://api.polynode.dev/v3/combos/redemptions?redemption_scope=partial&event_kind=Compressed&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` A non-terminal `Compressed` row proves that post-resolution processing changed an old combo position into a smaller combo position. The leg arrays below are abbreviated: ```json theme={null} { "event_kind": "Compressed", "type": "COMPRESS", "side": "Compress", "wallet_address": "0xc82f0a25aad828f59347670e63ead5ea144466a7", "redemption_scope": "partial", "redemption_type": "PARTIAL_COMBO", "redemption_evidence": "post_resolution_compression", "is_full_combo_redemption": false, "is_partial_combo_redemption": true, "is_terminal_redemption": false, "is_partial_combo_reduction": true, "has_collateral_payout": false, "combo_condition_id": "0x03f20b4d62f602343ec586eb21b1fd88320000000000000000000000000000", "combo_position_id": "1784593540973682895298448580384733359095951577285561914582372891673092947968", "full_combo_condition_id": "0x0387525b6b182939b62c8ffd3f64c703aa0000000000000000000000000000", "reduced_combo_condition_id": "0x03f20b4d62f602343ec586eb21b1fd88320000000000000000000000000000", "source_position_id": "1596031307328819069153563606934811624985504858539062944212408350305599619073", "destination_position_id": "1784593540973682895298448580384733359095951577285561914582372891673092947969", "amount_usdc": "392.295381", "position_amount_usdc": "392.295381", "collateral_out_usdc": "0.000000", "source_leg_count": 5, "removed_leg_count": 4, "remaining_leg_count": 1, "leg_transition": "5_to_1", "full_legs": [{"leg_index": 0, "leg_outcome_label": "Spain"}], "source_legs": [{"leg_index": 0, "leg_outcome_label": "Spain"}], "remaining_legs": [ { "leg_index": 0, "leg_position_id": "607054667337535653336040312390449441244232932993621750080905322313694576640", "leg_condition_id": "0x4a0aa5a56b98476ffbab967ba0eb70d35794ad0f154fbce5b976d6053bb47808", "leg_outcome_index": 0, "leg_outcome_label": "Argentina", "market_token_id": "67596909630505748192273119086224135081859582478741941473155557882450542807607", "leg_result": "won", "leg_current_price": "1.0000", "leg_price_source": "settlement", "market": { "title": "Argentina vs. Cabo Verde: Team to Advance", "slug": "fifwc-arg-cvi-2026-07-03-team-to-advance", "active": true, "closed": true, "accepting_orders": false, "resolved": true, "winning_outcome_index": 0 } } ], "removed_legs": [{"leg_index": 0, "leg_outcome_label": "Spain"}], "remaining_combo": { "combo_condition_id": "0x03f20b4d62f602343ec586eb21b1fd88320000000000000000000000000000", "combo_position_id": "1784593540973682895298448580384733359095951577285561914582372891673092947969", "shares_created": "392.295381", "current_wallet_balance": "873.364653", "still_held": true, "status": "OPEN" }, "metadata_coverage": "complete", "tx_hash": "0xe73ed3c24d1ca763984df61fad854479c45ea67b555ebaa547c994aa777add0c", "log_index": 559, "block_number": 89561963 } ``` For a combo reduced to a smaller combo—for example, three legs reduced to two: * `full_combo_condition_id` identifies the pre-transition combo consumed by this compression. * `reduced_combo_condition_id` identifies the surviving smaller combo. * `combo_condition_id`, `combo_position_id`, and `legs` retain Polymarket's basic record for the surviving combo. * `full_legs` and `source_legs` preserve that pre-transition combo context. * `remaining_legs` and `removed_legs` compare the indexed leg registries. * `source_position_id` and `destination_position_id` provide the exact ERC-1155 transition. * `source_leg_count`, `removed_leg_count`, and `remaining_leg_count` answer how many legs the operation started with, removed, and left behind. `leg_transition` is the compact form, such as `3_to_2`. * `remaining_combo` is a compact holding snapshot for the destination combo. It does not include entry price, cost basis, or P\&L and is not a replacement for the positions endpoint. `has_collateral_payout` and `collateral_out_usdc` tell you whether compression also emitted collateral. A zero collateral amount can still be a real partial resolution: the surviving value moved entirely into the reduced combo position. For a full redemption, `remaining_leg_count` is `0`, `removed_leg_count` equals the source leg count, and `remaining_combo` is omitted. If a partial redemption's current destination balance is unavailable, `remaining_combo` still includes its condition, position, and `shares_created`; balance-dependent fields are omitted rather than assumed to be zero. ## Leg identifiers, result, and price Each object in `legs`, `full_legs`, `source_legs`, `remaining_legs`, `removed_legs`, and `residual_legs` can include: | Field | Description | | - | - | | `leg_position_id` | Position ID used by the combo contract for this leg | | `leg_condition_id` | Standard market condition ID | | `leg_outcome_index` | Selected outcome index within the standard market | | `leg_outcome_label` | Selected outcome label | | `market_token_id` | Canonical Polymarket CLOB token ID for the selected outcome. Use this with price, order-book, trade, and candle endpoints. | | `leg_result` | `won`, `lost`, `resolved`, or `pending` for the selected outcome | | `leg_current_price` | Best available canonical price for the selected outcome, formatted from `0.0000` to `1.0000` | | `leg_price_source` | `settlement`, `clob_mid`, `last_fill`, or `polymarket_market` | | `market.active` | Whether Polymarket marks the market active | | `market.closed` | Whether the market is closed | | `market.accepting_orders` | Whether the market currently accepts orders | | `market.resolved` | Whether a final result is known | | `market.winning_outcome_index` | Winning outcome index when one unique winner is known | `settlement` is the terminal `0` or `1` outcome value. `clob_mid` is the current order-book midpoint. `last_fill` is the most recent trade price when a midpoint is unavailable. `polymarket_market` is Polymarket's market-level outcome price fallback. `market_token_id` is intentionally distinct from `leg_position_id`. The former is the standard market token accepted by price and order-book endpoints; the latter is the combo contract's leg identifier. Permissionless combo markets can contain an on-chain leg that has no corresponding Polymarket CLOB market or order book. In that case, the exact `leg_position_id` remains present while `market_token_id`, `leg_result`, `leg_current_price`, `leg_price_source`, and standard market metadata are omitted rather than inferred. ## Structural extraction is not a redemption `Extracted` returns `full_combo_condition_id`, `reduced_combo_condition_id`, and `residual_combo_condition_id`, which is useful for reconstructing a larger combo into smaller branches. It is classified as: ```json theme={null} { "event_kind": "Extracted", "redemption_scope": "transformation", "redemption_type": "COMBO_TRANSFORMATION", "redemption_evidence": "condition_extraction", "is_partial_combo_redemption": false, "is_partial_combo_reduction": true } ``` This distinction is intentional: `Extracted` proves exact condition lineage, but it does not prove a redemption payout. Use `Compressed` for a partial post-resolution transition and `PositionRedeemed` or terminal compression for a terminal redemption. ## Scope meanings | Scope | Meaning | | - | - | | `full` | A complete combo position was redeemed (`PositionRedeemed`) or terminally compressed to position `0`. | | `partial` | A non-terminal post-resolution `Compressed` event changed the old combo into a reduced combo. | | `transformation` | A non-redemption lifecycle transformation such as extract, inject, wrap, unwrap, convert, or condition/event split/merge. | ## Evidence and lineage fields | Field | Description | | - | - | | `redemption_evidence` | Why the row is classified as terminal, partial, extraction, injection, or another transformation | | `is_terminal_redemption` | `true` for terminal `PositionRedeemed` or terminal compression | | `is_partial_combo_reduction` | `true` for a smaller-combo compression or structural extraction | | `has_collateral_payout` | Whether `payout_usdc` or `collateral_out_usdc` is positive | | `lineage_event_id` | Stable transaction-hash/log-index identifier | | `full_combo_condition_id` | Pre-transition full/source combo condition for this event | | `parent_combo_condition_id` | Parent condition for condition/event operations | | `source_combo_condition_id` | Condition consumed by the operation | | `reduced_combo_condition_id` | Smaller combo condition produced by a reduction | | `residual_combo_condition_id` | Residual condition emitted by extract/inject | | `child_yes_combo_condition_id` / `child_no_combo_condition_id` | Child conditions emitted by condition splits/merges | | `destination_combo_condition_id` | Primary destination condition when one exists | | `source_position_id` / `destination_position_id` | Exact position transition when present | | `underlying_position_id` | Standard underlying position for wrap/unwrap operations | Condition-to-position mapping is deterministic: the combo condition occupies the high 31 bytes of the position ID and the outcome index occupies the low byte. This lets historical full redemptions map to their combo without re-indexing unrelated contracts. For a chain of multiple compressions, `full_combo_condition_id` is the immediate pre-transition combo on each row, not a guessed earliest ancestor. Follow `source_position_id` and `destination_position_id` across rows when the chain facts are available; the endpoint does not invent a root parlay identifier that the contract did not emit. ## Metadata coverage `metadata_coverage` describes the leg expansion available for that row: * `complete`: the required combo leg registries are available. * `missing_source_legs`: the source condition is known on chain, but its leg metadata is not yet available. * `missing_reduced_legs`: the reduction is known on chain, but the reduced combo's leg metadata is not yet available. The condition and position lineage remains chain-derived even when descriptive leg metadata is incomplete. # Wallet Combo Activity Source: https://docs.polynode.dev/data/combos/wallet-activity GET /v3/wallets/{address}/combos/activity List combo lifecycle activity for one wallet, including split and merge activity. Returns combo lifecycle activity for a wallet. This is the combo-only counterpart to wallet splits, merges, redemptions, and lifecycle activity. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/combos/activity ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | Alias for `condition_id` | | `condition_id` | string | -- | Combo condition ID | | `position_id` | string | -- | Combo position ID | | `event_kind` | string | -- | Filter by event kind, for example `PositionsSplit` or `PositionRedeemed` | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/activity?limit=2" ``` ```json theme={null} { "address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "activity": [ { "position_type": "combo", "event_kind": "PositionsSplit", "side": "Split", "user_address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "combo_condition_id": "0x03d98f6ac4c108c5ca66f79f34908a1d820000000000000000000000000000", "combo_position_id": "1741334187009265192213210063949860811096650382021683265628751751539647840256", "amount_usdc": "0.050750", "tx_hash": "0xf3a8985f04bf869483ef4163a185f296c834eb827b5e5ae3db5bd44558121d51", "log_index": 890, "block_number": 88276713, "timestamp": 1781120055, "legs": [ { "leg_index": 0, "leg_position_id": "547325449395903582555711510844460161809002726131102493368605951180083822592" } ] } ], "rows_returned": 2, "has_more": true, "position_type": "combo", "source": "v3.wallet_combos.activity" } ``` ## Response fields | Field | Type | Description | | - | - | - | | `event_kind` | string | Public lifecycle event kind | | `side` | string | Human-readable lifecycle side, such as `Split` or `Merge` | | `combo_condition_id` | string | Combo condition ID | | `combo_position_id` | string | Combo position ID | | `amount_usdc` | string | Amount formatted in USDC | | `payout_usdc` | string or null | Redemption payout formatted in USDC when the activity is a redeem | | `tx_hash` | string | Polygon transaction hash | | `block_number` | integer | Polygon block number | | `timestamp` | integer | Unix timestamp in seconds | | `legs` | array | Leg position IDs involved in the lifecycle event | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `activity[].wallet` | string | The wallet this row belongs to | ## Redemption semantics Combo redemptions are normalized to match Polymarket's public combo activity shape. Router and auto-redeemer paths are returned as `event_kind: "PositionRedeemed"` with `side: "Redeem"` and the underlying module kind, such as `Combinatorial`, `Binary`, or `NegRisk`. The raw router/auto-redeemer contract path is used internally for indexing but is not the public event kind. When leg metadata is available, redemption rows include resolved leg statuses and `leg_current_price` values in the `legs` array. For terminal-versus-partial redemption evidence—and the reduced/residual condition IDs needed to identify a three-leg combo becoming a two-leg combo—use [Wallet Combo Redemptions](/data/combos/wallet-redemptions). # Wallet Combo Positions Source: https://docs.polynode.dev/data/combos/wallet-positions GET /v3/wallets/{address}/combos/positions List combo positions for one wallet with legs, entry basis, balances, and P&L. Returns combo positions for a wallet. Each row includes balance, entry basis, realized/unrealized/total P\&L, status, and leg metadata when available. For a combined standard + combo position list, call `GET /v3/wallets/{address}/positions?include_combos=true`. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/combos/positions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | Alias for `condition_id` | | `condition_id` | string | -- | Combo condition ID | | `position_id` | string | -- | Combo position ID | | `status` | string | -- | `open`, `closed`, `resolved_win`, `resolved_loss`, `resolved` (won or lost), or `all` | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/positions?limit=1" ``` ```json theme={null} { "address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "positions": [ { "position_type": "combo", "wallet_address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "combo_condition_id": "0x030002fa8781d9f445d838e60524d70bf30000000000000000000000000000", "combo_position_id": "1356959103499736670017337806334234879289930581423500836189165811753797287936", "shares_balance": "0.000100", "entry_avg_price_usdc": "0.2285", "entry_cost_usdc": "0.00", "realized_pnl_usdc": "0.000000", "total_pnl_usdc": "0.000000", "status": "open", "legs_total": 3, "legs": [ { "leg_index": 0, "leg_outcome_label": "Yes", "leg_status": "OPEN", "market": { "slug": "fifwc-ger-civ-2026-06-20", "event_title": "Germany vs. Cote d'Ivoire" } } ] } ], "rows_returned": 1, "has_more": true, "position_type": "combo", "source": "v3.wallet_combos.positions" } ``` ## Response fields | Field | Type | Description | | - | - | - | | `combo_condition_id` | string | Combo condition ID | | `combo_position_id` | string | Combo ERC-1155 position ID | | `shares_balance` | string | Current combo share balance | | `entry_avg_price_usdc` | string | Weighted-average entry price | | `entry_cost_usdc` | string | Entry cost for current/lifetime accounting | | `realized_pnl_usdc` | string | Realized P\&L | | `unrealized_pnl_usdc` | string or null | Unrealized P\&L when available | | `total_pnl_usdc` | string | Realized + unrealized P\&L | | `status` | string | Current combo position status | | `legs` | array | Leg metadata for the combo | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `positions[].wallet` | string | The wallet this row belongs to | ## Resolution semantics Redeemed combo positions are settled into weighted-average cost basis as soon as PolyNode observes the on-chain combo redemption. A fully redeemed winning combo returns `status: "RESOLVED_WIN"`, `shares_balance: "0.000000"`, `entry_cost_usdc: "0.00"`, and realized/total P\&L equal to redemption payout minus entry basis. A fully redeemed losing combo returns `status: "RESOLVED_LOSS"` with zero open entry cost. `entry_avg_price_usdc` remains the historical weighted-average entry price after close. Leg metadata is refreshed from Polymarket combo metadata. Resolved legs expose `leg_status` values such as `RESOLVED_WIN` or `RESOLVED_LOSS`, `leg_resolved_at`, and `leg_current_price` when available. `legs_resolved` and `legs_pending` are derived from those leg statuses. # Wallet Combo Redemptions Source: https://docs.polynode.dev/data/combos/wallet-redemptions GET /v3/wallets/{address}/combos/redemptions List full combo redemptions and partial combo reductions for one wallet with exact leg changes. Returns the canonical combo redemption and reduction history for one wallet. This is the wallet-scoped form of [`GET /v3/combos/redemptions`](/data/combos/redemptions). In plain language, each row tells you whether the wallet redeemed its entire combo or removed settled legs and kept a smaller combo. The compact fields answer how many legs changed; the leg arrays and position IDs provide the exact market and on-chain details for follow-up queries. Unlike a basic combo activity row, the response makes the before-and-after transition explicit. See [How this differs from Polymarket combo activity](/data/combos/redemptions#how-this-differs-from-polymarket-combo-activity) for the consumer and developer comparison. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/combos/redemptions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | One or more comma-separated combo condition IDs; matches any lineage condition | | `condition_id` | string | -- | Combo condition ID; matches any lineage condition | | `position_id` | string | -- | Primary, source, destination, or underlying position ID | | `event_kind` | string | -- | Filter by canonical event kind | | `redemption_scope` | string | `all` | `full`, `partial`, `transformation`, or `all` | | `redemption_type` | string | `all` | `FULL_COMBO`, `PARTIAL_COMBO`, `COMBO_TRANSFORMATION`, or `all` | | `tx_hash` | string | -- | Exact Polygon transaction hash | | `after` | integer | -- | Inclusive Unix timestamp in seconds | | `before` | integer | -- | Inclusive Unix timestamp in seconds | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xc82f0a25aad828f59347670e63ead5ea144466a7/combos/redemptions?redemption_scope=partial&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "address": "0xc82f0a25aad828f59347670e63ead5ea144466a7", "redemptions": [ { "event_kind": "Compressed", "redemption_scope": "partial", "redemption_type": "PARTIAL_COMBO", "redemption_evidence": "post_resolution_compression", "is_full_combo_redemption": false, "is_partial_combo_redemption": true, "is_terminal_redemption": false, "is_partial_combo_reduction": true, "has_collateral_payout": false, "full_combo_condition_id": "0x0387525b6b182939b62c8ffd3f64c703aa0000000000000000000000000000", "reduced_combo_condition_id": "0x03f20b4d62f602343ec586eb21b1fd88320000000000000000000000000000", "amount_usdc": "392.295381", "source_leg_count": 5, "removed_leg_count": 4, "remaining_leg_count": 1, "leg_transition": "5_to_1", "remaining_combo": { "combo_condition_id": "0x03f20b4d62f602343ec586eb21b1fd88320000000000000000000000000000", "combo_position_id": "1784593540973682895298448580384733359095951577285561914582372891673092947969", "shares_created": "392.295381", "current_wallet_balance": "873.364653", "still_held": true, "status": "OPEN" }, "tx_hash": "0xe73ed3c24d1ca763984df61fad854479c45ea67b555ebaa547c994aa777add0c", "log_index": 559, "block_number": 89561963 } ], "rows_returned": 1, "has_more": false, "offset": 0, "limit": 25, "position_type": "combo", "source": "v3.wallet_combos.redemptions" } ``` ## Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `redemptions[].wallet` | string | The wallet this row belongs to | ## Choosing this endpoint * Use `redemption_scope=full` for terminal whole-combo redemptions. * Use `redemption_scope=partial` for post-resolution compression into a smaller combo, including a three-leg combo becoming a two-leg combo when Polymarket emits that transition. * Use `event_kind=Extracted` for structural full/reduced/residual lineage. Extraction is marked as a reduction, but not as a redemption. * Use the default `all` when reconstructing the wallet's complete combo redemption and transformation history. * Use the global endpoint when the wallet is unknown or when correlating one condition, position, or transaction across wallets. * Read `source_leg_count`, `removed_leg_count`, `remaining_leg_count`, and `leg_transition` when you only need to know what changed in that redemption. * Read `market_token_id`, `leg_result`, `leg_current_price`, and `leg_price_source` on each leg when you need an actionable standard-market identifier and outcome state. * Read `remaining_combo` to see the resulting combo position and whether the wallet still holds a positive balance. Use the combo positions endpoint for full position, cost, and P\&L context. For a consumer-facing summary, display `redemption_scope` and `leg_transition` first. For a developer workflow, use the source and destination IDs as stable joins, then use `market_token_id` from each changed leg with price, order-book, trade, or candle endpoints. Existing standard and combo position endpoints are unchanged. # Wallet Combo Summary Source: https://docs.polynode.dev/data/combos/wallet-summary GET /v3/wallets/{address}/combos/summary Get combo-only P&L, position counts, and win/loss counts for one wallet, all time or inside a time window. Returns a combo-only summary for a wallet. Use this endpoint when you want to inspect combo exposure separately from the standard wallet summary. For an all-in wallet summary, call `GET /v3/wallets/{address}?include_combos=true`. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/combos/summary ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `address` | string | Wallet address or owner EOA | ### Query parameters All optional. They scope only the win and loss counts; see [Time windows](#time-windows). | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `all` | `all`, `1d`, `7d`, `30d`, or `custom`. `1d` / `7d` / `30d` end now. | | `after` | integer | none | Window start, Unix seconds, inclusive. Requires `period=custom` (or no `period`) | | `before` | integer | none | Window end, Unix seconds, exclusive. Requires `period=custom` (or no `period`) | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x8f73711ac46f9e9c7d97196889603a52bc42bb9e/combos/summary" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "address": "0x8f73711ac46f9e9c7d97196889603a52bc42bb9e", "summary": { "position_type": "combo", "wallet_address": "0x8f73711ac46f9e9c7d97196889603a52bc42bb9e", "open_combo_count": 17, "closed_combo_count": 39, "balance_count": 56, "realized_pnl_usdc": "1849.109086", "unrealized_pnl_usdc": "-1046.697946", "total_pnl_usdc": "802.411140", "last_activity_at": "2026-10-06T22:41:31.671553+00:00", "win_count": 39, "loss_count": 17, "resolved_count": 56, "win_rate": "0.6964" }, "rows_returned": 1, "position_type": "combo", "source": "v3.wallet_combos.summary" } ``` ### Past 7 days ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x1109da04152c38666464f5adb5d7c55618810b2c/combos/summary?period=7d" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "address": "0x1109da04152c38666464f5adb5d7c55618810b2c", "summary": { "position_type": "combo", "wallet_address": "0x1109da04152c38666464f5adb5d7c55618810b2c", "open_combo_count": 10307, "closed_combo_count": 44089, "balance_count": 54396, "realized_pnl_usdc": "7725995.313053", "unrealized_pnl_usdc": "-4222707.461465", "total_pnl_usdc": "3503287.851588", "last_activity_at": "2026-10-27T07:39:59.108677+00:00", "win_count": 483, "loss_count": 0, "resolved_count": 483, "win_rate": "1.0000" }, "rows_returned": 1, "position_type": "combo", "source": "v3.wallet_combos.summary", "period": "7d", "window": { "after": 1792484127, "before": 1793088927 } } ``` ## Response fields | Field | Type | Description | | - | - | - | | `open_combo_count` | integer | Open combo positions | | `closed_combo_count` | integer | Closed combo positions | | `balance_count` | integer | Total combo balance rows tracked for the wallet | | `realized_pnl_usdc` | string | Realized combo P\&L in USD | | `unrealized_pnl_usdc` | string or null | Current unrealized combo P\&L when available | | `total_pnl_usdc` | string | Realized + unrealized combo P\&L | | `last_activity_at` | string | Last observed combo activity for this wallet | | `win_count` | integer | Resolved combo positions the wallet won | | `loss_count` | integer | Resolved combo positions the wallet lost | | `resolved_count` | integer | `win_count` + `loss_count` | | `win_rate` | string or null | `win_count` / `resolved_count` as a 4-decimal fraction (`"0.6964"` = 69.64%); `null` when the wallet has no resolved combo | With a window, the response also has these top-level fields: | Field | Type | Description | | - | - | - | | `period` | string | The requested period: `1d`, `7d`, `30d`, or `custom` | | `window` | object | `{after, before}` in Unix seconds that the counts used; `after` inclusive, `before` exclusive, `null` when open | ### Win and loss counts A combo position is won or lost once its legs resolve: a YES position wins when every leg wins and loses as soon as any leg loses; a NO position is the reverse. The counts cover every combo position the wallet has held, all time, whether or not it was redeemed, including positions it sold or transferred before the combo resolved. Open positions are not counted. To list the positions behind the all-time counts, call [Wallet Combo Positions](/data/combos/wallet-positions) with `status=resolved_win`, `status=resolved_loss`, or `status=resolved` (both). That listing is not window-scoped. ### Time windows With `period=1d`, `7d`, `30d`, or `custom`, `win_count`, `loss_count`, `resolved_count` and `win_rate` count only the combo positions that settled inside the window. P\&L, `open_combo_count`, `closed_combo_count`, `balance_count` and `last_activity_at` are always all time. * A combo settles at its first payout to any holder. Both sides of a combo share that time, so a lost position is placed when the winning side was paid. * A small share of resolved combos has no recorded payout. Their positions count in the all-time totals but in no window, until a payout is recorded. Most of them are losses, so a windowed `win_rate` can read slightly high. * The window is half-open: `after` is inclusive and `before` is exclusive, like the [Combo P\&L Leaderboard](/data/combos/leaderboard). Wallet Combo Redemptions treats `before` as inclusive. * An invalid window returns 400 `invalid_request`, for example `period=1y`, `period=custom` with no bound, `after` not less than `before`, or `window=7d` (use `period`). Windowed counts can briefly return 503 `combo_window_unavailable` when the payout data is catching up; retry, or call without a window for the all-time counts. ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Counts and P\&L are summed across the combined wallets, `win_rate` is recomputed from the summed counts, and `last_activity_at` is the latest of them. With a window, every combined wallet uses the same window. # Wallet Combo Trades Source: https://docs.polynode.dev/data/combos/wallet-trades GET /v3/wallets/{address}/combos/trades List confirmed combo fills for one wallet with side, size, price, role, counterparty, and transaction data. Returns confirmed combo fills where the requested wallet participated as maker or taker. Use this endpoint for combo-only trade history. For the same fills before confirmation, subscribe to the [`combo_execution` WebSocket event](/websocket/events/combo-execution). > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/combos/trades ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `market_id` | string | -- | Alias for `condition_id` | | `condition_id` | string | -- | Combo condition ID | | `position_id` | string | -- | Combo position ID | | `side` | string | -- | `BUY`, `SELL`, or `all` | | `limit` | integer | 100 | Results per page, max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/wallets/0x0d8b4fb38999aaf7658df758f3587d25fe7fd417/combos/trades?limit=2" ``` ```json theme={null} { "address": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "trades": [ { "position_type": "combo", "wallet_role": "maker", "wallet_address": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "counterparty_address": "0xe3333700ca9d93003f00f0f71f8515005f6c00aa", "combo_condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501376", "side": "BUY", "price": "0.5700", "size": "40.350877", "fee": "0.494500", "tx_hash": "0xf4f973bcca17c05081574c36183a5f61fae8eb5895a2d46d71aaadb3cf11e556", "log_index": 549, "block_number": 91404731, "timestamp": 1785812123 }, { "position_type": "combo", "wallet_role": "taker", "wallet_address": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "counterparty_address": "0xe2315b15280fc49bc6e60eaaeea30c0df64493a5", "combo_condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501377", "side": "BUY", "price": "0.4300", "size": "40.350877", "fee": "0.000000", "tx_hash": "0xf4f973bcca17c05081574c36183a5f61fae8eb5895a2d46d71aaadb3cf11e556", "log_index": 539, "block_number": 91404731, "timestamp": 1785812123 } ], "rows_returned": 2, "has_more": true, "position_type": "combo", "source": "v3.wallet_combos.trades" } ``` ## Response fields | Field | Type | Description | | - | - | - | | `position_type` | string | Always `combo` | | `wallet_role` | string | Requested wallet's role for this fill: `maker` or `taker` | | `wallet_address` | string | Requested wallet | | `counterparty_address` | string | Counterparty for this fill; this can be ExchangeV3 for the taker order | | `combo_condition_id` | string | Combo condition ID | | `condition_id` | string | Alias of `combo_condition_id` | | `position_id` | string | YES or NO combo position filled | | `side` | string | Signed order maker's `BUY` or `SELL` direction | | `price` | string | Actual fill price | | `size` | string | Combo shares filled | | `fee` | string | Fee in USDC | | `tx_hash` | string | Polygon transaction hash | | `log_index` | integer | Log index within the transaction | | `block_number` | integer | Polygon block number | | `timestamp` | integer | Unix timestamp in seconds | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `trades[].wallet` | string | The wallet this row belongs to | ## Maker and taker roles One combo match contains multiple signed orders, so the requested wallet can appear in more than one row for the same transaction. In the example, the wallet is the maker of the YES taker order and the taker/counterparty of the complementary NO maker order. The static API projects each receipt fill from the requested wallet's point of view. The WebSocket preserves the underlying signed-order view directly: `trades[].maker`, `trades[].taker`, and `trades[].side` describe that order, while top-level `taker_*` fields identify the transaction's taker order. The static endpoint does not currently return `order_hash` or `amount_usdc`. Both are present on pending WebSocket trade rows; correlate the two surfaces with `tx_hash`, `position_id`, `side`, `price`, and `size`. # Event Catalog Source: https://docs.polynode.dev/data/events/catalog GET /v3/events Walk the complete Polymarket event catalog with member-market counts and stable cursor pagination. `GET /v3/events` groups markets by parent event slug and returns one event row with status and member-market counts. Events are ordered by the latest update among their member markets. ## Request ```text theme={null} GET /v3/events ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | 100 | Rows per page. Values below 1 use 1; values above 300 use 300. | | `cursor` | string | none | Opaque `next_cursor` returned by the preceding page. | | `status` | string | all | `open`, `closed`, `inactive`, or `all`. Matching is case-insensitive. | | `event_slug` | string | none | Exact event slug. | | `sort` | string | `updated` | Only `updated` is available. | | `order` | string | `desc` | Only `desc` is available. | Offset pagination is not supported on this route. ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/events?event_slug=example-event&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "events": [ { "event_slug": "example-event", "title": "Example event", "status": "open", "active": true, "closed": false, "market_count": 2, "status_counts": { "open": 1, "closed": 1, "inactive": 0 }, "latest_market_updated_at": "2026-08-27T20:00:00Z", "title_variant_count": 1, "image_variant_count": 1, "icon_variant_count": 1, "image": "https://example.com/event.png", "representative_market": { "condition_id": "0x1111111111111111111111111111111111111111111111111111111111111111", "slug": "will-the-example-market-resolve-yes", "question": "Will the example market resolve Yes?", "end_date": null, "tag_slugs": ["example"] }, "volume_all_time": null, "liquidity": null } ], "rows_returned": 1, "has_more": false, "limit": 1, "next_cursor": null, "sort": "updated", "order": "desc", "filters": { "status": null, "event_slug": "example-event" } } ``` ## Event status An event is `open` while any member market is open. It is `closed` when every member market is closed. Otherwise it is `inactive`. ## Response envelope The envelope has the same cursor fields as the [market catalog](/data/markets/catalog), with the page rows in `events`. Pass `next_cursor` unchanged and keep the same filters. Stop when `has_more` is `false`. ## Event fields | Field | Type | Nullable | Description | | - | - | - | - | | `event_slug` | string | no | Event slug. | | `title` | string | yes | Representative event title. | | `status` | string | no | `open`, `closed`, or `inactive`. | | `active`, `closed` | boolean | no | Status convenience flags. | | `market_count` | integer | no | Member markets. | | `status_counts` | object | no | Open, closed, and inactive member-market counts. | | `latest_market_updated_at` | string | yes | Latest available update among member markets. | | `title_variant_count` | integer | no | Distinct non-empty event titles among member markets. | | `image_variant_count`, `icon_variant_count` | integer | no | Distinct non-empty image and icon URLs among member markets. | | `image`, `icon` | string | yes | Representative image URLs. | | `representative_market` | object | no | One member market with `condition_id`, `slug`, `question`, `end_date`, and `tag_slugs`. | | `volume_all_time`, `liquidity` | null | yes | Reserved financial fields. This catalog currently returns `null`; do not treat them as zero. | ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_request` | Invalid status, event slug, sort, order, or use of `offset`. | | `400` | `invalid_cursor` | A cursor is malformed, expired, belongs to the market route, or is used with different filters. | | `401` | authentication error | The API key is missing or invalid. | | `410` | `invalid_cursor` | The page walk referenced by the cursor is no longer available. Start again without a cursor. | | `503` | `temporarily_unavailable` | Markets and events are temporarily unavailable. | # Event Catalog Stats Source: https://docs.polynode.dev/data/events/catalog-stats GET /v3/events/stats Get complete event, member-market, and event-status counts. Returns counts for the complete [event catalog](/data/events/catalog), independent of any one page. ## Request ```bash theme={null} curl "https://api.polynode.dev/v3/events/stats" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Response ```json theme={null} { "event_count": 900634, "member_market_count": 2653204, "catalog_market_count": 2662678, "status_counts": { "open": 99115, "closed": 800390, "inactive": 1129 } } ``` Counts change as events and their member markets change. | Field | Type | Description | | - | - | - | | `event_count` | integer | Events in the complete event catalog. | | `member_market_count` | integer | Markets linked to those events. | | `catalog_market_count` | integer | Markets in the complete market catalog, including markets without an event slug. | | `status_counts.open` | integer | Open events. | | `status_counts.closed` | integer | Closed events. | | `status_counts.inactive` | integer | Events that are neither open nor closed. | ## Errors | Status | Error | When it occurs | | - | - | - | | `401` | authentication error | The API key is missing or invalid. | | `503` | `temporarily_unavailable` | Markets and events are temporarily unavailable. | # Builder Fees Source: https://docs.polynode.dev/data/fees/builder-fees Rank builders by attributed fee generation and inspect their fee-bearing fills. Builder fee data is based on the `builder` field on attributed fills. `total_fees` is protocol fee generated by attributed fills, not the builder's off-chain rev-share payout. Canonical endpoint references: * [Builder Leaderboard](/data/builders/list) * [Builder Detail](/data/builders/detail) * [Builder Trades](/data/builders/trades) ## Rank Builders by Fees ```bash theme={null} curl "https://api.polynode.dev/v3/builders?sort=fees&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Inspect Builder Trades ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Builder Trade Filters | Parameter | Purpose | | - | - | | `token_id` | One outcome token | | `condition_id` | All outcomes in a condition | | `market_slug` | Market URL slug | | `event_slug` | All markets in an event | | `side` | `buy` or `sell` | | `min_amount` | Minimum raw maker amount | | `category` | Market category | | `tag_slug` | Market tag slug | | `after`, `before` | Time range | > [!NOTE] > > Builder codes are 32-byte hex tags, not wallet addresses. # Fees by Receiver Source: https://docs.polynode.dev/data/fees/fees-by-receiver Fetch fee charged events received by one address. Use this when you know the receiver address and want only fee events paid to that receiver. Canonical endpoint reference: [Fee Events](/data/global/fees). ## Query ```bash theme={null} curl "https://api.polynode.dev/v3/fees/0x115f48dc2a731aa16251c6d6e1befc42f92accc9?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Filters | Parameter | Purpose | | - | - | | `after` | Start timestamp | | `before` | End timestamp | | `limit` | Page size, max 300 | | `offset` | Pagination offset | ## Returned Data Rows match the global fee event shape, with the receiver implied by the path. # Global Fee Events Source: https://docs.polynode.dev/data/fees/global-fees Browse fee charged events across Polymarket. Use this when you want the global stream of fee charged events rather than wallet-owned fills. Canonical endpoint reference: [Fee Events](/data/global/fees). ## Query ```bash theme={null} curl "https://api.polynode.dev/v3/fees?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Filters | Parameter | Purpose | | - | - | | `after` | Start timestamp | | `before` | End timestamp | | `limit` | Page size, max 300 | | `offset` | Pagination offset | ## Returned Data Rows include the fee receiver, raw amount, transaction hash, and timestamp. Amounts are raw 6-decimal USDC values unless a page says otherwise. # Maker Rebates Source: https://docs.polynode.dev/data/fees/maker-rebates Query Polymarket-reported maker rebate records for one maker/date. Maker rebates are Polymarket accounting credits. They are not the same thing as trader-paid fill fees. Canonical endpoint reference: [Wallet Maker Rebates](/data/wallets/rebates). ## Query ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a/rebates" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Optional Date ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a/rebates?date=2026-06-17" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Notes * Rebate lookups are keyed by CLOB maker/signing address. * Passing a Safe or proxy wallet can return an empty `rebates` array with a hint. * This endpoint can return zero rows for a valid wallet/date. # Fees Overview Source: https://docs.polynode.dev/data/fees/overview Where to query trader-paid fees, fee receiver events, builder-attributed fees, maker rebates, and reward market configuration. PolyNode exposes fee data in a few different forms. Use this section when you know you need fee or rebate data but are not sure which endpoint matches the accounting question. > [!NOTE] > > Fees, rebates, rewards, and builder payouts are separate concepts. Trader-paid fees come from executed fills. Fee events show receiver-level on-chain fee charges. Maker rebates and reward configuration are Polymarket accounting surfaces. Builder rev share is paid off-chain and is not the same as `total_fees`. ## Fee Surfaces | Need | Endpoint | Use this when | | - | - | - | | Wallet all-time fee summary | `GET /v3/wallets/{address}?include_accounting_summary=true` | You want the exact all-time trader-paid fee total without paging raw fills | | Wallet fee-bearing fills | `GET /v3/wallets/{address}/fees-paid` | You want trades where a wallet paid a nonzero fill fee | | Global fee events | `GET /v3/fees` | You want fee charged events across the platform | | Fees by receiver | `GET /v3/fees/{receiver}` | You want fee events received by one address | | Builder fee ranking | `GET /v3/builders?sort=fees` | You want builders ranked by fees generated on attributed fills | | Builder fee trades | `GET /v3/builders/{code}/trades` | You want the underlying attributed fills, including per-fill `fee` | | Maker rebates | `GET /v3/wallets/{address}/rebates` | You want Polymarket-reported maker rebates for one maker/date | | Reward configs | `GET /v3/rewards/markets` | You want public reward-market configuration, not wallet-earned rewards | ## Quick Examples ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a?include_accounting_summary=true" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a/fees-paid?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/fees?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/builders?sort=fees&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Related Pages | Page | Canonical reference | | - | - | | [Wallet Summary](/data/wallets/summary) | [Wallet Summary](/data/wallets/summary) | | [Wallet Fees Paid](/data/fees/wallet-fees-paid) | [Wallet Fees Paid](/data/wallets/fees-paid) | | [Global Fee Events](/data/fees/global-fees) | [Fee Events](/data/global/fees) | | [Fees by Receiver](/data/fees/fees-by-receiver) | [Fee Events](/data/global/fees) | | [Builder Fees](/data/fees/builder-fees) | [Builder Leaderboard](/data/builders/list) | | [Maker Rebates](/data/fees/maker-rebates) | [Wallet Maker Rebates](/data/wallets/rebates) | | [Reward Market Configs](/data/fees/reward-market-configs) | [Reward Markets](/data/rewards/markets) | # Reward Market Configs Source: https://docs.polynode.dev/data/fees/reward-market-configs Query public Polymarket reward-market configuration. Reward market configuration describes markets with reward programs. It is not a per-wallet earned rewards ledger. Canonical endpoint references: * [Reward Markets](/data/rewards/markets) * [Reward Market Detail](/data/rewards/market) ## List Reward Markets ```bash theme={null} curl "https://api.polynode.dev/v3/rewards/markets" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## One Condition ```bash theme={null} curl "https://api.polynode.dev/v3/rewards/markets/0x0001cb8c0b39aeb614ab9a43867595317f06ede9c011661513065c638fbbefda" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Filters | Parameter | Purpose | | - | - | | `sponsored` | Filter to sponsored reward markets | | `next_cursor` | Provider cursor pagination | > [!NOTE] > > Use this for public market reward configuration. Do not treat it as arbitrary-wallet earned LP rewards. # Wallet Fees Paid Source: https://docs.polynode.dev/data/fees/wallet-fees-paid Query fee-bearing executed fills for one wallet. Use this when you want the fills where a specific wallet paid a nonzero trader fee. Canonical endpoint reference: [Wallet Fees Paid](/data/wallets/fees-paid). For the exact all-time total, use [Wallet Summary](/data/wallets/summary) with `include_accounting_summary=true` and read `accounting_summary.fees_paid.amount`. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Query ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a/fees-paid?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Filters | Parameter | Purpose | | - | - | | `after` | Start timestamp, Unix seconds | | `before` | End timestamp, Unix seconds | | `order` | `asc` or `desc` | | `limit` | Page size, max 300 | | `offset` | Pagination offset | ## Returned Data The response includes a `fees` array with the same market-enriched fill fields as wallet trades, plus: | Field | Meaning | | - | - | | `fee` | Fee in USD | | `fee_paid` | Same value as `fee`, named for fee-specific summaries | | `fee_paid_raw` | Raw 6-decimal amount | | `page_total_fees_paid` | Sum for the returned page only | | `fee_semantics` | Reminder that this is trader-paid fill fees | > [!NOTE] > > `page_total_fees_paid` is page-scoped. Use `GET /v3/wallets/{address}?include_accounting_summary=true` when you need the all-time total. ## Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `fees[].wallet` | string | The wallet this row belongs to | # Condition Detail Source: https://docs.polynode.dev/data/global/conditions GET /v3/conditions/{condition_id} Get full market condition data including payouts, outcomes, metadata, and resolution status. Returns full condition data for a market, including payout structure, outcomes, and enriched market metadata. ## Request ``` GET /v3/conditions/{condition_id} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `condition_id` | string | Market condition ID (0x-prefixed) | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/conditions/0x6c4d221b3cf2c8d17467c70a8aa3c714e30299b6e57cd3e4269dc8a41d2b0cd8?key=YOUR_KEY" ``` ```json theme={null} { "id": "0x6c4d221b3cf2c8d17467c70a8aa3c714e30299b6e57cd3e4269dc8a41d2b0cd8", "position_ids": [ "30698649476690694814108493145041085718609914990967907518412053225237708492787", "43362318061877762261164265810725209343672429810065542703856317173848260953021" ], "payout_numerators": [0, 1], "payout_denominator": "1", "question": "Will Trump pardon Joe Exotic \"The Tiger King\" in 2025?", "slug": "will-trump-pardon-joe-exotic-the-tiger-king-in-2025-784-928-365", "outcomes": ["Yes", "No"], "end_date": "2025-12-31 12:00:00+00", "active": true, "closed": true, "neg_risk": false, "event_slug": "who-will-trump-pardon-in-2025", "event_title": "Who will Trump pardon in 2025?", "category": null, "liquidity": "0", "volume": "99993.937724000003072433173656463623046875", "tags": ["Politics", "Trump", "SBF", "cz", "Trump Presidency", "Ghislaine Maxwell"], "winning_outcome_index": 1, "elapsed_ms": 6 } ``` `position_ids` are **decimal strings**, not JSON numbers. Polymarket token IDs are 78-digit values that exceed IEEE 754 float precision — any JSON parser that decodes them as floats will corrupt the lower digits. Always treat them as strings. `volume` and `liquidity` are returned at full database precision (up to \~50 digits after the decimal). Round them on the client; do not store as a JS `Number`. ## Response fields | Field | Type | Nullable | Description | | - | - | - | - | | `id` | string | no | Condition ID | | `position_ids` | array\ | no | Outcome token IDs (decimal-string-encoded — see note above) | | `payout_numerators` | array\ | no | Payout numerators per outcome (non-zero after resolution) | | `payout_denominator` | string | no | Payout denominator | | `question` | string | no | Market question | | `slug` | string | no | Market URL slug | | `outcomes` | array\ | no | Outcome labels | | `end_date` | string | yes | Market end date (Postgres timestamp with offset) | | `active` | boolean | no | Currently active | | `closed` | boolean | no | No longer accepting orders | | `neg_risk` | boolean | no | Multi-outcome (neg-risk) market | | `event_slug` | string | yes | Parent event slug | | `event_title` | string | yes | Parent event title | | `category` | string | yes | Optional category label | | `liquidity` | string (decimal) | no | Current liquidity, full-precision string | | `volume` | string (decimal) | no | All-time volume, full-precision string | | `tags` | array\ | yes | Category tags in their canonical (Title Case) form | | `winning_outcome_index` | integer | yes | Winning outcome (null if unresolved) | # Fee Events Source: https://docs.polynode.dev/data/global/fees GET /v3/fees Browse fee charged events across all Polymarket trades. Returns fee events from the Polymarket exchange. Each fee event records the receiver, amount, and associated transaction. ## Request ``` GET /v3/fees ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ### By receiver ``` GET /v3/fees/{receiver} ``` Returns fees received by a specific address. ## Example ```bash theme={null} curl https://api.polynode.dev/v3/fees?limit=1 ``` ```json theme={null} { "data": [ { "id": "0x1e20bc6a2107b61fa179b3ab17047b43569031e238f2b4ac92d9fa25a2822e3d_633", "timestamp": "1778962419", "receiver": "0x115f48dc2a731aa16251c6d6e1befc42f92accc9", "amount": "318480", "transaction_hash": "0x1e20bc6a2107b61fa179b3ab17047b43569031e238f2b4ac92d9fa25a2822e3d" } ], "rows_returned": 1, "has_more": true, "offset": 0, "limit": 1, "elapsed_ms": 3 } ``` When fetching `GET /v3/fees/{receiver}`, the `receiver` field is omitted from each row (it's redundant — every row matches the path parameter). ## Response fields | Field | Type | Description | | - | - | - | | `id` | string | Unique fee event ID | | `timestamp` | string | Unix timestamp | | `receiver` | string | Fee receiver address | | `amount` | string | Fee amount (6-decimal USDC) | | `transaction_hash` | string | On-chain transaction hash | # Global Positions Source: https://docs.polynode.dev/data/global/positions GET /v3/positions Browse the latest positions across all Polymarket wallets. Filter by market, status, or size. Returns the most recent position changes across all wallets, enriched with market metadata and current prices. Defaults to most recent positions first. ## Request ``` GET /v3/positions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `status` | string | -- | Filter: `open`, `closed`, `redeemable`, `redeemed` | | `sort` | string | recent | Sort by: `pnl`, `size`, `volume`. Default is most recent first. | | `order` | string | `desc` | `asc` or `desc` | | `token_id` | string | -- | Filter by outcome token ID | | `condition_id` | string | -- | Filter by market condition ID | | `market_slug` | string | -- | Filter by market slug | | `min_size` | number | -- | Minimum position size in USD | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ### Position statuses Global positions use the same lifecycle statuses as wallet positions: | Status | Meaning | | - | - | | `open` | Wallet holds shares in an active (unresolved) market | | `closed` | Position fully sold before market resolved | | `redeemable` | Market resolved, wallet still holds shares that can be redeemed | | `redeemed` | Market resolved and shares have been redeemed | ## Examples ### Latest position changes ```bash theme={null} curl https://api.polynode.dev/v3/positions?limit=5 ``` ### Biggest open positions ```bash theme={null} curl https://api.polynode.dev/v3/positions?sort=size&status=open&limit=5 ``` ### Who holds positions in a specific market ```bash theme={null} curl "https://api.polynode.dev/v3/positions?condition_id=0xdd22472e...&sort=pnl&limit=10" ``` ### Unclaimed redeemable positions ```bash theme={null} curl "https://api.polynode.dev/v3/positions?status=redeemable&min_size=100&sort=size&limit=10" ``` ## Response fields (per row in `positions`) This endpoint returns a leaner field set than [`/v3/wallets/{addr}/positions`](/data/wallets/positions). For full enrichment (`last_trade_at`, `tag_slugs`, `event_slug`, `market_status`, `opposite_asset`, `price_source`, `redeemable_payout`, `won`, etc.), use the per-wallet endpoint. | Field | Type | Nullable | Description | | - | - | - | - | | `wallet` | string | no | Wallet address | | `token_id` | string | no | Outcome token ID (decimal-string-encoded — see [Identifiers](/data/overview#identifiers-and-large-numbers)) | | `size` | number | no | Current shares held (USD) | | `avg_price` | number | no | Weighted-average entry price (USD per outcome token) | | `realized_pnl` | number | no | Realized P\&L (USD) | | `unrealized_pnl` | number | no | Unrealized P\&L (USD) — `(current_price - avg_price) * size` | | `total_pnl` | number | no | `realized_pnl + unrealized_pnl` (USD) | | `current_price` | number | no | Latest token price (USD). Falls back to `0` if no price is known yet. | | `total_bought` | number | no | Total USD spent buying this position | | `resolved` | boolean | no | Whether the market has settled | | `status` | string | no | `open`, `closed`, `redeemable`, or `redeemed` | | `market` | string | yes | Market question (null if the token's metadata hasn't been backfilled) | | `slug` | string | yes | Market URL slug | | `outcome` | string | yes | Outcome label | | `outcome_index` | integer | yes | Outcome position (0 or 1) | | `image` | string | yes | Market image URL | | `condition_id` | string | yes | Market condition ID | | `neg_risk` | boolean | yes | Neg-risk (multi-outcome) market flag | # Market Resolutions Source: https://docs.polynode.dev/data/global/resolutions GET /v3/resolutions Browse recent market resolutions with payout data and market metadata. Returns market resolution events, sorted by most recent. Each resolution includes the payout structure and enriched market metadata. ## Request ``` GET /v3/resolutions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/resolutions?limit=1 ``` ```json theme={null} { "data": [ { "category": null, "condition_id": "0xbd7f5df4a14a1b0ec35354ed910acf8c538d5e556c8389fcb58bb6a45c32e5b6", "created_at": "2026-05-15 22:16:02.633047", "outcomes": [ "Over", "Under" ], "payout_denominator": "1", "payout_numerators": [ "0", "1" ], "question": "Chicago Cubs vs. Chicago White Sox: O/U 11.5", "resolved_at": "1778883350000", "slug": "mlb-chc-cws-2026-05-15-total-11pt5" } ], "elapsed_ms": 6, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `condition_id` | string | Market condition ID | | `payout_numerators` | array | Payout for each outcome (e.g. `["0", "1"]` means outcome 1 won) | | `payout_denominator` | string | Payout denominator (usually `"1"`) | | `resolved_at` | string | Resolution timestamp (milliseconds) | | `created_at` | string | When the resolution was recorded | | `question` | string | Market question | | `slug` | string | Market slug | | `outcomes` | array | Outcome labels (e.g. `["Yes", "No"]`) | | `category` | string | Market category | # Platform Stats Source: https://docs.polynode.dev/data/global/stats GET /v3/stats Global aggregates for the entire Polymarket database. Total fills, wallets, volume, and P&L. Returns platform-wide aggregates from the `global_stats` materialized view. Instant response. ## Request ``` GET /v3/stats ``` ## Example ```bash theme={null} curl https://api.polynode.dev/v3/stats ``` ```json theme={null} { "total_fills": 1227599616, "total_redemptions": 160535696, "total_wallets": 2676595, "total_positions": "227857354", "total_realized_pnl": "2240414321986960", "total_gross_profit": "13881389085858405", "total_gross_loss": "-11640974763871445", "total_volume": "2149019620148621138", "elapsed_ms": 0 } ``` ## Related global endpoints | Endpoint | Description | | - | - | | `GET /v3/trades` | Global trade feed. `?after=`, `?before=`, `?min_amount=`, `?order=` | | `GET /v3/fees` | Fee events. `?after=`, `?before=` | | `GET /v3/fees/{receiver}` | Fees by receiver address | | `GET /v3/resolutions` | Recent market resolutions with metadata | | `GET /v3/conditions/{id}` | Condition with payouts and market metadata | # Global Trades Source: https://docs.polynode.dev/data/global/trades GET /v3/trades Browse the full Polymarket trade history with market enrichment, computed prices, and order hashes. Returns all Polymarket fills across all wallets, enriched with market metadata. Supports time range filtering, dollar-size filtering, and scoping by token, market, or event. ## Request ``` GET /v3/trades ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range (Unix timestamp) | | `token_id` | string | -- | Filter by outcome token | | `condition_id` | string | -- | Filter by market condition ID (resolves to token IDs) | | `market_slug` | string | -- | Filter by market slug (resolves to token IDs) | | `event_slug` | string | -- | Filter by event slug (resolves to token IDs across all of the event's markets) | | `event_id` | integer | -- | Filter by numeric event ID (same scope as `event_slug`) | | `order_hash` | string | -- | Return only fills for one exact order hash (`0x` + 64 hex characters) | | `builder` | string | -- | Filter by builder code (hex) | | `min_amount_usd` | number | -- | Minimum trade size in dollars, matching the `amount_usd` response field. Decimals allowed, e.g. `99.5` | | `min_amount` | integer | -- | Minimum maker\_amount\_filled (raw 6-decimal). Prefer `min_amount_usd` | | `side` | string | -- | Maker order side: `buy`, `sell`, `0`, or `1` | | `sort_by` | string | -- | `order_hash` groups fills from the same order visually | | `group_by` | string | -- | `order_hash` aggregates the returned fills per order | | `order` | string | `desc` | `asc` or `desc` | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | Event filters cover events currently in Polymarket's catalog. A very large event can return `400` asking for a narrower filter (`condition_id` or `market_slug`). All supplied filters are intersected. `order_hash` is an exact, indexed filter applied before pagination. Hex characters are case-insensitive; malformed or empty hashes return `400`, while a valid hash with no fills returns an empty `200` page. ## Example Every fill for one order: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c" ``` See [Trades by Order Hash](/data/query-catalog/trades/by-order-hash) for global, wallet, token, slug, pagination, and grouping recipes. \$100+ trades, newest first: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v3/trades?min_amount_usd=100&limit=1" ``` ```json theme={null} { "trades": [ { "id": "0x5e5cf2c73b8d7a8d09f6397c3c32aa285b7102ab957f43a22afaf0e2a1c3476e_0x3ef6f61107628696009ccf3d343c29177a3244f5d1e92f1fd540e75f04a9f48c_1102", "maker": "0xe9076a87c5ed90ef16e6fe6529c943baeca0cff6", "taker": "0xe2222d279d744050d28e00520010520000310f59", "maker_asset_id": "14635675870982897917581198649476127837975251193150495566552970565909631535281", "taker_asset_id": "0", "maker_amount": 2028.24, "taker_amount": 585.671225, "amount_usd": 585.671225, "fee": 20.82768, "price": 0.2888, "size": 2028.24, "timestamp": "1783824661", "transaction_hash": "0x5e5cf2c73b8d7a8d09f6397c3c32aa285b7102ab957f43a22afaf0e2a1c3476e", "order_hash": "0x3ef6f61107628696009ccf3d343c29177a3244f5d1e92f1fd540e75f04a9f48c", "builder": "0x2c6624a23b16a2a69acd14c87b7fc03906870c851fa0a7b7f9d7be0fbbedea8a", "side": 1, "role": "maker", "direction": "SELL", "market": "Will Argentina win on 2026-07-11?", "slug": "fifwc-arg-che-2026-07-11-arg", "outcome": "Yes", "outcome_index": 0, "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/soccer ball-bba4025f77.png", "condition_id": "0x95f726bbb693b945f94473908298b2389989550b08a7bfd90f97ce7ba62cb719", "event_slug": "fifwc-arg-che-2026-07-11", "event_id": 679992 } ], "rows_returned": 1, "has_more": true, "offset": 0, "limit": 1, "elapsed_ms": 10 } ``` Event-scoped: every trade across all markets of one event: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v3/trades?event_slug=fifwc-arg-che-2026-07-11&limit=100" ``` ## Response fields Each trade contains the same fields as [Wallet Trades](/data/wallets/trades), including market enrichment (market, slug, outcome, image, condition\_id, event\_slug, event\_id), computed price and size in USD, order\_hash, and direction. `event_slug`/`event_id` identify the Polymarket event the market belongs to; they are null for old markets that no longer exist in Polymarket's catalog. On global trades (no wallet context), `role` is always `"maker"` and `direction` reflects the maker's action. Use the [Wallet Trades](/data/wallets/trades) endpoint for wallet-specific perspective. # Leaderboard Source: https://docs.polynode.dev/data/leaderboard/global GET /v3/leaderboard Rank Polymarket wallets globally, by category, or by one tag. Supports all-time rankings and 1-day, 7-day, and 30-day realized-P&L rankings. `GET /v3/leaderboard` supports two ranking modes: * Omit `period`, or use `period=all`, for the all-time leaderboard. All-time views can rank by total P\&L, realized P\&L, unrealized P\&L, profit, loss, volume, wins, or position count. * Use `period=1d`, `7d`, or `30d` for a rolling realized-P\&L leaderboard. Rolling views rank by `realized_pnl` in descending order and do not include historical unrealized P\&L. All monetary values are in USD. > [!NOTE] > > A rolling leaderboard measures realized-state changes recorded inside the selected window. It is not a historical snapshot of each wallet's all-time total P\&L. See [Wallet P\&L](/data/wallets/pnl) for the matching time-window semantics. ## Request ```text theme={null} GET /v3/leaderboard ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `all` | `1d`, `7d`, `30d`, or `all`. Aliases `day`, `week`, and `month` are accepted. `all_time` and `all-time` also select all-time mode. | | `sort` | string | mode-dependent | All-time: `total_pnl`, `realized_pnl`, `unrealized_pnl`, `gross_profit`, `gross_loss`, `volume`, `wins`, or `position_count`, including the aliases below. Rolling: `realized_pnl` only. | | `order` | string | `desc` | All-time: `asc` or `desc`. Rolling: `desc` only. | | `category` | string | none | Filter to one market category, case-insensitive. | | `tags` | string | none | Filter to a tag. All-time mode also accepts comma-separated tags. Rolling mode accepts exactly one tag. | | `tag_slug` | string | none | Alias for a single `tags` value. | | `market` | string | none | All-time only. Filter by condition ID or market slug. | | `market_slug` | string | none | All-time only. Filter by market slug. | | `event_slug` | string | none | All-time only. Filter by parent event slug. | | `condition_id` | string | none | All-time only. Filter by market condition ID. | | `limit` | integer | 20 | Number of rows. Values below 1 use 1; values above 100 use 100. | | `offset` | integer | 0 | Pagination offset. Negative values use 0. | All-time sort aliases include `total`, `pnl`, and `net_pnl` for `total_pnl`; `realized` and `net_realized_pnl` for `realized_pnl`; `unrealized` for `unrealized_pnl`; `profit` for `gross_profit`; `loss` for `gross_loss`; `total_volume` for `volume`; and `positions` for `position_count`. ### Rolling scope rules A rolling request can use exactly one of these scopes: | Scope | Parameters | | - | - | | Global | No `category`, `tags`, or `tag_slug` | | Category | One `category` | | Tag | One `tags` or `tag_slug` value | Leaderboard requests do not accept `after` or `before`; use `period` for a dated ranking. Rolling requests also do not accept market, event, condition, multiple-tag, or combined category-and-tag filters. ## All-time example ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?sort=total_pnl&order=desc&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "leaderboard": [ { "rank": 1, "wallet": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "net_realized_pnl": 22053845.825455, "realized_pnl": 22053845.825455, "gross_profit": 22057977.181649, "gross_loss": -4131.356194, "unrealized_pnl": 0.000689, "total_pnl": 22053845.826144, "wins": 18, "losses": 4, "position_count": 22, "open_positions": 1, "total_volume": 43013258.515682 } ], "count": 1, "limit": 1, "offset": 0, "has_more": true, "sort": "total_pnl", "order": "desc" } ``` ## Rolling examples ### Global 7-day realized P\&L ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=7d&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ### 30-day category and tag rankings ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=30d&category=sports&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" curl "https://api.polynode.dev/v3/leaderboard?period=30d&tag_slug=us-election&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ### Rolling response ```json theme={null} { "leaderboard": [ { "rank": 1, "wallet": "0x1111111111111111111111111111111111111111", "net_realized_pnl": 125000.5, "realized_pnl": 125000.5, "gross_profit": 140000.5, "gross_loss": -15000, "wins": 42, "losses": 8, "position_count": 50, "event_count": 73, "condition_count": 31 } ], "count": 1, "limit": 20, "offset": 0, "has_more": true, "period": "7d", "sort": "realized_pnl", "order": "desc", "category": null, "tags": [] } ``` ## Response envelope | Field | Mode | Description | | - | - | - | | `leaderboard` | both | Ranked rows for the requested page. | | `count` | both | Number of rows returned in this response. | | `limit` | both | Effective page size after the 100-row cap. | | `offset` | both | Effective pagination offset. | | `has_more` | both | Whether another page exists inside the selected rank cap. | | `sort` | both | Effective sort field. Rolling mode always returns `realized_pnl`. | | `order` | both | Effective sort order. Rolling mode always returns `desc`. | | `period` | rolling | Canonical period: `1d`, `7d`, or `30d`. | | `category` | rolling and filtered all-time | Selected category, or `null`. | | `tags` | rolling and filtered all-time | Selected tag values. | | `market_slug`, `event_slug`, `condition_id` | filtered all-time | Selected all-time filter values, or `null`. | ## Row fields ### All-time rows | Field | Type | Description | | - | - | - | | `rank` | integer | Position in the selected leaderboard. | | `wallet` | string | Wallet address. | | `net_realized_pnl` | number | Net realized P\&L. Equal to `realized_pnl`. | | `realized_pnl` | number | Net realized P\&L. | | `gross_profit` | number | Sum of profitable positions. | | `gross_loss` | number | Sum of losing positions, negative or zero. | | `unrealized_pnl` | number | Current P\&L from open positions. | | `total_pnl` | number | Realized plus unrealized P\&L. | | `wins` | integer | Winning position count. | | `losses` | integer | Losing position count. | | `position_count` | integer | Total position count. | | `open_positions` | integer | Current open-position count. | | `total_volume` | number | Total traded volume. | ### Rolling rows | Field | Type | Description | | - | - | - | | `rank` | integer | Position in the rolling leaderboard. | | `wallet` | string | Wallet address. | | `net_realized_pnl` | number | Net realized P\&L in the selected window. Equal to `realized_pnl`. | | `realized_pnl` | number | Net realized P\&L in the selected window. | | `gross_profit` | number | Sum of positive per-position realized changes in the window. | | `gross_loss` | number | Sum of negative per-position realized changes in the window. | | `wins` | integer | Positions with a positive realized change. | | `losses` | integer | Positions with a negative realized change. | | `position_count` | integer | Positions with a non-zero realized change in the window. | | `event_count` | integer | Realized changes included in the row. | | `condition_count` | integer | Distinct markets represented in the row. | Rolling rows do not contain `unrealized_pnl`, `total_pnl`, `open_positions`, or `total_volume`. ## Pagination and empty results * Global all-time pagination exposes ranks 1 through 10,000. If `offset + limit` exceeds 10,000, the API returns `400 leaderboard_offset_too_deep`. * Rolling pagination is capped at rank 1,000 for every scope. Shorter rankings end at their last returned row. If `offset + limit` exceeds 1,000, the API returns `400 leaderboard_offset_too_deep`. * A valid category or tag with no realized results in the selected rolling window returns HTTP `200` with an empty `leaderboard`, `count: 0`, and `has_more: false`. ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_period` | `period` is not `1d`, `7d`, `30d`, or an all-time value. | | `400` | `invalid_sort` | The selected sort is not available for the requested mode. | | `400` | `invalid_order` | Rolling mode uses an order other than `desc`, or all-time mode uses an unsupported order. | | `400` | `unsupported_leaderboard_filter` | A rolling request combines scopes or uses an unsupported filter. | | `400` | `leaderboard_offset_too_deep` | The requested rank window exceeds the mode's cap. | | `401` | authentication error | The API key is missing or invalid. | | `503` | `leaderboard_unavailable` | The rolling leaderboard is temporarily unavailable. | | `503` | `pnl_unavailable` | A filtered all-time leaderboard is temporarily unavailable. | ```json theme={null} { "error": "leaderboard_unavailable", "message": "This leaderboard is temporarily unavailable." } ``` # Leaderboard Scopes Source: https://docs.polynode.dev/data/leaderboard/scopes GET /v3/leaderboard/scopes Discover and search the categories or tags available to 1-day, 7-day, and 30-day realized-P&L leaderboards. Use this endpoint to build category and tag navigation for rolling trader leaderboards. It returns only scopes available for the selected period, ordered by qualifying wallet count descending and then by name. ## Request ```text theme={null} GET /v3/leaderboard/scopes ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | required | `1d`, `7d`, or `30d`. Aliases `day`, `week`, and `month` are accepted. | | `scope` | string | required | `category` or `tag`. Plural aliases are accepted. | | `q` | string | none | Case-insensitive literal substring search. Up to 80 visible characters. | | `limit` | integer | 100 | Number of scopes. Values below 1 use 1; values above 200 use 200. | | `offset` | integer | 0 | Pagination offset from 0 through 10,000. | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard/scopes?period=7d&scope=category&limit=3" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "scopes": [ { "value": "sports", "wallet_count": 7985, "ranked_count": 1000 }, { "value": "up-or-down", "wallet_count": 7634, "ranked_count": 1000 }, { "value": "esports", "wallet_count": 5496, "ranked_count": 1000 } ], "count": 3, "total_count": 329, "limit": 3, "offset": 0, "has_more": true, "period": "7d", "scope": "category", "query": null } ``` Counts change as new realized results enter the selected window. ## Response fields | Field | Type | Description | | - | - | - | | `scopes` | array | Categories or tags in this page. | | `count` | integer | Number of scopes returned. | | `total_count` | integer | Total scopes matching the selected period, type, and search text. | | `limit` | integer | Effective page size. | | `offset` | integer | Effective pagination offset. | | `has_more` | boolean | Whether another reachable page exists. | | `period` | string | Canonical period: `1d`, `7d`, or `30d`. | | `scope` | string | Canonical scope type: `category` or `tag`. | | `query` | string or null | Normalized search text, or `null` when no search is active. | ### Scope rows | Field | Type | Description | | - | - | - | | `value` | string | Category or tag value accepted by the leaderboard. | | `wallet_count` | integer | Wallets with qualifying realized results in the selected scope and period. | | `ranked_count` | integer | Ranks available through the corresponding rolling leaderboard, capped at 1,000. | Use a returned `value` as `category` or `tags` on [`GET /v3/leaderboard`](/data/leaderboard/global). Tag values also work as the path slug on the [tag leaderboard](/data/leaderboard/tag-leaderboard). ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_period` | `period` is missing or is not a rolling period. | | `400` | `invalid_scope` | `scope` is missing or is not `category` or `tag`. | | `400` | `invalid_query` | Search text is too long or contains a control character. | | `400` | `scope_offset_too_deep` | `offset` is outside 0 through 10,000. | | `401` | authentication error | The API key is missing or invalid. | | `503` | `leaderboard_unavailable` | Scope discovery is temporarily unavailable. | # Tag Leaderboard Source: https://docs.polynode.dev/data/leaderboard/tag-leaderboard GET /v3/tags/{slug}/leaderboard Rank wallets within one market tag using all-time metrics or 1-day, 7-day, and 30-day realized P&L. `GET /v3/tags/{slug}/leaderboard` is the path form of a single-tag leaderboard. It supports the same all-time and rolling modes as [`GET /v3/leaderboard`](/data/leaderboard/global). ## Request ```text theme={null} GET /v3/tags/{slug}/leaderboard ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `slug` | string | One lower-case tag slug such as `sports`, `ufc`, or `us-election`. Matching is case-insensitive. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `all` | `1d`, `7d`, `30d`, or `all`. Aliases `day`, `week`, and `month` are accepted. `all_time` and `all-time` also select all-time mode. | | `sort` | string | mode-dependent | All-time supports the full all-time sort set. Rolling supports `realized_pnl` only. | | `order` | string | `desc` | All-time supports `asc` and `desc`. Rolling supports `desc` only. | | `limit` | integer | 20 | Number of rows. Values below 1 use 1; values above 100 use 100. | | `offset` | integer | 0 | Pagination offset. Negative values use 0. | Do not combine the path slug with a different `tags` or `tag_slug` query value. A conflict returns `400 conflicting_tag_scope`. ## Rolling example ```bash theme={null} curl "https://api.polynode.dev/v3/tags/sports/leaderboard?period=7d&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The equivalent query form is: ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=7d&tag_slug=sports&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "leaderboard": [ { "rank": 1, "wallet": "0x1111111111111111111111111111111111111111", "net_realized_pnl": 125000.5, "realized_pnl": 125000.5, "gross_profit": 140000.5, "gross_loss": -15000, "wins": 42, "losses": 8, "position_count": 50, "event_count": 73, "condition_count": 31 } ], "count": 1, "limit": 20, "offset": 0, "has_more": true, "period": "7d", "sort": "realized_pnl", "order": "desc", "category": null, "tags": ["sports"] } ``` ## All-time example ```bash theme={null} curl "https://api.polynode.dev/v3/tags/ufc/leaderboard?sort=total_pnl&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Omitting `period` preserves the all-time response and sort behavior. See [Leaderboard response fields](/data/leaderboard/global#row-fields) for the exact all-time and rolling row shapes. ## Pagination, empty results, and errors * Rolling tag leaderboards return up to 100 rows per request and are capped at rank 1,000. Shorter rankings end at their last returned row. * All-time tag leaderboards retain their existing offset pagination and do not use the global all-time 10,000-rank cap. * A tag with no realized results in a valid rolling window returns HTTP `200` with an empty `leaderboard`. * A rolling view that is temporarily unavailable returns `503 leaderboard_unavailable`. * An invalid period, sort, order, filter combination, or rank window returns HTTP `400` with a stable error code. | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_tag` | The path does not contain one valid tag slug. | | `400` | `conflicting_tag_scope` | A query tag differs from the path tag. | | `400` | `invalid_period`, `invalid_sort`, or `invalid_order` | A value is not supported by the selected mode. | | `400` | `unsupported_leaderboard_filter` | A rolling request uses an unsupported filter combination. | | `400` | `leaderboard_offset_too_deep` | A rolling request goes beyond rank 1,000. | | `401` | authentication error | The API key is missing or invalid. | | `503` | `leaderboard_unavailable` | The rolling tag leaderboard is temporarily unavailable. | | `503` | `pnl_unavailable` | The all-time tag leaderboard is temporarily unavailable. | > [!NOTE] > > Rolling tag rows contain realized metrics, `event_count`, and `condition_count`. They do not contain historical unrealized P\&L, total P\&L, open-position counts, or volume. # Tag Markets Source: https://docs.polynode.dev/data/leaderboard/tag-markets GET /v3/tags/{slug} List markets that belong to a specific tag (category), ordered by all-time volume or other metrics. Returns every market tagged with the given slug. Useful for building category landing pages or filtering search results. ## Request ``` GET /v3/tags/{slug} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `slug` | string | Tag slug. Matched case-insensitively. URL-style hyphens are converted to spaces, so `us-election` resolves to the stored tag `US Election`. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sort` | string | `volume_all_time` | Sort by `volume_all_time`, `liquidity`, or `created_at`. | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/tags/ufc?limit=2&key=YOUR_KEY" ``` ```json theme={null} { "data": [ { "condition_id": "0x61ef853c0ecc72a583da722cf6434681f9b92d10652cded44d8f889beb923418", "question": "Dvalishvili vs. Sandhagen", "slug": "ufc-dvalishvili-vs-sandhagen-2025-10-04", "outcomes": ["Dvalishvili", "Sandhagen"], "category": null, "active": true, "closed": true, "neg_risk": false, "volume_all_time": "999731.6550259999930858612060546875", "liquidity": "0", "end_date": "2025-10-11 18:00:00+00", "event_slug": "ufc-320-ankalaev-vs-pereira-2", "event_title": "UFC 320: Ankalaev vs. Pereira 2", "winning_outcome_index": 0 } ], "rows_returned": 1, "has_more": true, "offset": 0, "limit": 1, "elapsed_ms": 42 } ``` ## Response fields (per row in `data`) | Field | Type | Description | | - | - | - | | `condition_id` | string | Market condition ID | | `question` | string | Market question text | | `slug` | string | Market URL slug | | `outcomes` | array\ | Outcome labels | | `category` | string \| null | Optional category label | | `active` | boolean | Market is currently active | | `closed` | boolean | Market is closed (no longer accepting orders) | | `neg_risk` | boolean | Neg-risk (multi-outcome) market | | `volume_all_time` | string (decimal) | All-time USD volume | | `liquidity` | string (decimal) | Current liquidity in USD | | `end_date` | string \| null | Market resolution deadline (ISO timestamp with offset) | | `event_slug` | string \| null | Parent event slug | | `event_title` | string \| null | Parent event title | | `winning_outcome_index` | integer \| null | Winning outcome (null if unresolved) | ## Errors If no tag matches the slug (case-insensitive, hyphen-converted), the endpoint returns `404` with: ```json theme={null} {"error": "tag not found", "tag": "notarealtag"} ``` For a wallet-level P\&L leaderboard scoped to a tag, see [Tag Leaderboard](/data/leaderboard/tag-leaderboard). # Tags Source: https://docs.polynode.dev/data/leaderboard/tags GET /v3/tags List all market tags with the number of markets in each category. Returns all market tag categories ranked by market count. ## Request ``` GET /v3/tags ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/tags?limit=3&key=YOUR_KEY" ``` ```json theme={null} { "tags": [ { "tag": "Sports", "market_count": 575318 }, { "tag": "Games", "market_count": 522716 }, { "tag": "Hide From New", "market_count": 447811 } ], "rows_returned": 3, "has_more": true, "elapsed_ms": 1241 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `tag` | string | Canonical tag label as stored in the database. Title Case, spaces preserved (e.g. `"US Election"`, `"Trump Presidency"`). | | `market_count` | integer | Number of markets with this tag | ## Using tag values in URLs The `tag` value above is the canonical (Title Case) form. When passing a tag in a URL path (e.g. [`/v3/tags/{slug}`](/data/leaderboard/tag-markets) or [`/v3/tags/{slug}/leaderboard`](/data/leaderboard/tag-leaderboard)), use a lowercase, hyphen-separated form — the API resolves it back to the canonical tag: | URL form | Resolves to | | - | - | | `sports` | `Sports` | | `us-election` | `US Election` | | `primary-elections` | `primary elections` | The match is case-insensitive and converts hyphens to spaces. If no tag matches, you get `404 {"error":"tag not found","tag":...}`. # Market by Condition Source: https://docs.polynode.dev/data/markets/by-condition GET /v3/markets/condition/{condition_id} Get market metadata, token IDs, and outcomes by condition ID. Returns full market metadata for a condition, including all token IDs and their outcome labels. ## Request ``` GET /v3/markets/condition/{condition_id} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `condition_id` | string | Market condition ID (0x-prefixed) | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/markets/condition/0x6c4d221b3cf2c8d17467c70a8aa3c714e30299b6e57cd3e4269dc8a41d2b0cd8?key=YOUR_KEY" ``` ```json theme={null} { "data": [ { "condition_id": "0x6c4d221b3cf2c8d17467c70a8aa3c714e30299b6e57cd3e4269dc8a41d2b0cd8", "question": "Will Trump pardon Joe Exotic \"The Tiger King\" in 2025?", "slug": "will-trump-pardon-joe-exotic-the-tiger-king-in-2025-784-928-365", "outcomes": ["Yes", "No"], "category": null, "active": true, "closed": true, "neg_risk": false, "volume_all_time": "99993.937724000003072433173656463623046875", "liquidity": "0", "end_date": "2025-12-31 12:00:00+00", "event_slug": "who-will-trump-pardon-in-2025", "event_title": "Who will Trump pardon in 2025?", "tag_slugs": ["Politics", "Trump", "SBF", "cz", "Trump Presidency", "Ghislaine Maxwell"], "token_ids": [ "30698649476690694814108493145041085718609914990967907518412053225237708492787", "43362318061877762261164265810725209343672429810065542703856317173848260953021" ], "token_outcomes": ["Yes", "No"], "winning_outcome_index": 1 } ], "rows_returned": 1, "has_more": false, "offset": 0, "limit": 1, "elapsed_ms": 3 } ``` The response is wrapped in the standard `data: [{...}]` envelope. If no condition matches, `data` is `[]` and `rows_returned` is `0`. `volume_all_time` and `liquidity` are full-precision decimal strings — round on the client. `token_ids` are decimal strings, not numbers — they are 78-digit values and lose precision if parsed as floats. ## Response fields (per row in `data`) | Field | Type | Nullable | Description | | - | - | - | - | | `condition_id` | string | no | Market condition ID | | `question` | string | no | Market question | | `slug` | string | no | URL slug | | `outcomes` | array\ | no | Outcome labels | | `token_ids` | array\ | no | Outcome token IDs (decimal-string-encoded) | | `token_outcomes` | array\ | no | Outcome label for each token, in the same order as `token_ids` | | `active` | boolean | no | Currently active | | `closed` | boolean | no | No longer accepting orders | | `neg_risk` | boolean | no | Multi-outcome (neg-risk) market | | `volume_all_time` | string (decimal) | no | Full-precision volume in USD | | `liquidity` | string (decimal) | no | Full-precision current liquidity in USD | | `end_date` | string | yes | Market end date (Postgres timestamp with offset) | | `event_slug` | string | yes | Parent event slug | | `event_title` | string | yes | Parent event title | | `category` | string | yes | Optional category label | | `tag_slugs` | array\ | yes | Category tags in their canonical (Title Case) form | | `winning_outcome_index` | integer | yes | Which outcome won (null if unresolved) | # Market by Slug Source: https://docs.polynode.dev/data/markets/by-slug GET /v3/markets/slug/{slug}/trades Get trades and positions for a market by its URL slug. Look up a market by its slug (the URL path on Polymarket) and get trades or positions across all outcomes. ## Trades by slug ``` GET /v3/markets/slug/{slug}/trades ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ### Example ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-aur1-liquid-2026-05-13/trades?limit=1" ``` Returns the same enriched trade format as [Wallet Trades](/data/wallets/trades). ## Positions by slug ``` GET /v3/markets/slug/{slug}/positions ``` Returns every wallet holding (or that has ever held) any outcome of this market, across V1 + V2, with realized P\&L computed from the V2 adapter pipeline. ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | | `sort` | string | `realized_pnl` | One of `amount`, `volume`, `realized_pnl`, `pnl` | | `status` | string | -- | `open` (current holders only) or `closed` (zeroed-out positions only). Omit to return all. | For this market-scoped endpoint, `status` is a holder-state filter on the current raw balance. `open` means `amount > 0`; `closed` means `amount = 0`. It is not the wallet/global lifecycle status split, where resolved nonzero positions are `redeemable` and resolved zero-balance positions are `redeemed`. ### Example ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-aur1-liquid-2026-05-13/positions?limit=1" ``` ```json theme={null} { "data": [ { "user": "0xca70278943df14029a0f819f9baf060f67860908", "token_id": "2241710011255999173993483096156975147842635212627942653724495466212043852479", "amount": "0", "avg_price": "500000", "total_bought": "2000000", "realized_pnl": "998000" } ], "rows_returned": 1, "has_more": true, "offset": 0, "limit": 1, "elapsed_ms": 179 } ``` ### Response fields | Field | Type | Description | | - | - | - | | `user` | string | Wallet address (lowercased) | | `token_id` | string | Outcome token ID this row is about | | `amount` | string | Current balance in raw 6-decimal USDC (`0` if fully exited) | | `avg_price` | string | Time-weighted average buy price in raw 6-decimal USDC (`500000` = \$0.50) | | `total_bought` | string | Cumulative cost-basis of all purchases in raw 6-decimal USDC | | `realized_pnl` | string | Realized P\&L on closed-out portion of the position in raw 6-decimal USDC | # Market Candles Source: https://docs.polynode.dev/data/markets/candles Trade-built OHLCV candles for V3 Polymarket outcome tokens, condition IDs, and market slugs. Build OHLCV candles from V3 Polymarket trade fills. Candles are bucketed by trade timestamp and include price, volume, VWAP, trade count, and first/last fill markers for each bucket. Use this endpoint for V3 charting when you already have an outcome token ID, condition ID, or market slug. ## Endpoints ```http theme={null} GET /v3/markets/{token_id}/candles GET /v3/markets/condition/{condition_id}/candles GET /v3/markets/slug/{slug}/candles ``` The token route returns one candle series for one outcome token. The condition and slug routes resolve the market's outcome tokens and return a `series` array, one entry per outcome token. Pass `token_id` on the condition or slug route to return only one outcome. ## Authentication ```bash theme={null} curl "https://api.polynode.dev/v3/markets/{token_id}/candles?resolution=5m&limit=120" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Query parameters | Parameter | Type | Default | Description | | - | -: | -: | - | | `resolution` | string | `1h` | Bucket size. One of `1m`, `5m`, `15m`, `1h`, `4h`, `1d`. | | `limit` | integer | `120` | Maximum number of candle buckets in the requested window. Clamped by resolution. | | `direction` | string | `before` | `before` returns the window ending at `anchor_ts` or now. `after` returns the window starting at `anchor_ts`. | | `anchor_ts` | integer | now | Unix timestamp in seconds. Required when `direction=after`. | | `start` | integer | -- | Explicit window start timestamp in seconds. Alias: `start_time`, `after`. | | `end` | integer | -- | Explicit window end timestamp in seconds. Alias: `end_time`, `before`. | | `order` | string | `asc` | Candle order. Use `desc` to return newest bucket first. | | `gap_fill` | boolean | `false` | When true, empty buckets are filled with flat carry-forward candles after a prior price exists. | | `token_id` | string | -- | Condition/slug routes only. Filters the resolved market to one outcome token. | Timestamp parameters are Unix seconds, not milliseconds. If you pass an explicit range, the range must fit inside the resolution's bucket limit. ## Bucket limits `limit` is a candle-bucket count, not a trade count. | Resolution | Max candles per request | | - | -: | | `1m` | 120 | | `5m` | 180 | | `15m` | 240 | | `1h` | 300 | | `4h` | 360 | | `1d` | 500 | For more history, walk backward with `pagination.older_end_ts`: ```bash theme={null} # First page: latest 120 one-minute buckets curl "https://api.polynode.dev/v3/markets/$TOKEN_ID/candles?resolution=1m&limit=120" \ -H "x-api-key: $POLYNODE_API_KEY" # Older page: use pagination.older_end_ts from the previous response curl "https://api.polynode.dev/v3/markets/$TOKEN_ID/candles?resolution=1m&limit=120&anchor_ts=$OLDER_END_TS" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Token route response ```json theme={null} { "token_id": "7936379438884929999943146941289093559746194477224187754527972073168717543990", "resolution": "1m", "count": 1, "candles": [ { "time": 1781659920, "time_unix": 1781659920, "time_ms": 1781659920000, "open": 0.525, "high": 0.535, "low": 0.515, "close": 0.53, "volume": 233.135659, "volume_usd": 233.135659, "volume_shares": 444.019955, "volume_buy": 121.504, "volume_sell": 111.631659, "trades": 13, "vwap": 0.52504954, "first_trade_ts": 1781659922, "last_trade_ts": 1781659978, "first_block": 88620000, "last_block": 88620030, "first_log_index": 320, "last_log_index": 881, "gap_filled": false } ], "question": "Spread: Argentina (-1.5)", "slug": "fifwc-arg-alg-2026-06-16-spread-home-1pt5", "outcome": "Argentina", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/soccer ball-bba4025f77.png", "condition_id": "0x1eb724a708f3720c2b7ef63d7ffc7483ecc14deed6df2e7e9dc1dfa724a98bd6", "outcome_index": 0, "window": { "start_ts": 1781652840, "end_ts": 1781659981, "first_bucket": 1781652840, "last_bucket": 1781659980, "duration_seconds": 7142, "bucket_count": 120, "resolution_seconds": 60, "older_end_ts": 1781652839, "newer_start_ts": 1781660040, "has_older": true, "has_newer": true }, "pagination": { "limit": 120, "max_limit": 120, "direction": "before", "order": "asc", "older_end_ts": 1781652839, "newer_start_ts": 1781660040, "has_more": true, "has_older": true, "has_newer": true }, "gap_fill": false, "elapsed_ms": 27 } ``` Sparse markets can return `count: 0` and `candles: []` for a window with no trades. That is a valid empty chart window, not a missing market. ## Condition and slug responses ```bash theme={null} curl "https://api.polynode.dev/v3/markets/condition/$CONDITION_ID/candles?resolution=5m&limit=2" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "condition_id": "0x1eb724a708f3720c2b7ef63d7ffc7483ecc14deed6df2e7e9dc1dfa724a98bd6", "resolution": "5m", "series_count": 2, "series": [ { "token_id": "7936379438884929999943146941289093559746194477224187754527972073168717543990", "resolution": "5m", "count": 0, "candles": [], "question": "Spread: Argentina (-1.5)", "slug": "fifwc-arg-alg-2026-06-16-spread-home-1pt5", "outcome": "Argentina", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/soccer ball-bba4025f77.png", "condition_id": "0x1eb724a708f3720c2b7ef63d7ffc7483ecc14deed6df2e7e9dc1dfa724a98bd6", "outcome_index": 0 } ], "window": { "start_ts": 1781668800, "end_ts": 1781669399, "first_bucket": 1781668800, "last_bucket": 1781669100, "duration_seconds": 600, "bucket_count": 2, "resolution_seconds": 300, "older_end_ts": 1781668799, "newer_start_ts": 1781669400, "has_older": true, "has_newer": true }, "pagination": { "limit": 2, "max_limit": 180, "direction": "before", "order": "asc", "older_end_ts": 1781668799, "newer_start_ts": 1781669400, "has_more": true, "has_older": true, "has_newer": true }, "gap_fill": false, "elapsed_ms": 205 } ``` For a single outcome from a condition or slug: ```bash theme={null} curl "https://api.polynode.dev/v3/markets/condition/$CONDITION_ID/candles?token_id=$TOKEN_ID&resolution=15m&limit=96" \ -H "x-api-key: $POLYNODE_API_KEY" ``` If a condition or slug resolves to more than 50 outcome tokens, pass `token_id` to request one outcome series. ## Candle fields | Field | Type | Description | | - | - | - | | `time` | integer | Candle bucket start time in Unix seconds. | | `time_unix` | integer | Same as `time`. | | `time_ms` | integer | Candle bucket start time in Unix milliseconds for charting libraries. | | `open` | number | First trade price in the bucket. | | `high` | number | Highest trade price in the bucket. | | `low` | number | Lowest trade price in the bucket. | | `close` | number | Last trade price in the bucket. | | `volume` | number | Total USD volume in the bucket. Alias of `volume_usd`. | | `volume_usd` | number | Total USD volume in the bucket. | | `volume_shares` | number | Total outcome-share volume in the bucket. | | `volume_buy` | number | USD volume where the fill bought this outcome token. | | `volume_sell` | number | USD volume where the fill sold this outcome token. | | `trades` | integer | Number of fills in the bucket. | | `vwap` | number | Volume-weighted average price. | | `first_trade_ts` | integer or null | Timestamp of the first fill in the bucket. | | `last_trade_ts` | integer or null | Timestamp of the last fill in the bucket. | | `first_block` | integer or null | Polygon block of the first fill in the bucket. | | `last_block` | integer or null | Polygon block of the last fill in the bucket. | | `first_log_index` | integer or null | Log index of the first fill in the bucket. | | `last_log_index` | integer or null | Log index of the last fill in the bucket. | | `gap_filled` | boolean | `true` only for carry-forward buckets created by `gap_fill=true`. | ## Errors and guards | Status | Condition | | -: | - | | `400` | Invalid `resolution`, invalid `direction`, invalid `order`, millisecond timestamp, range larger than the resolution limit, or `token_id` that does not belong to a condition/slug route. | | `404` | Unknown token, condition, or slug. | Unknown token IDs return: ```json theme={null} { "error": "market token not found", "token_id": "0", "hint": "candles are available for Polymarket outcome token IDs, not collateral or arbitrary asset IDs" } ``` # Market Catalog Source: https://docs.polynode.dev/data/markets/catalog GET /v3/markets Walk the complete Polymarket market catalog with stable cursor pagination and optional status or event filters. `GET /v3/markets` is the exhaustive market-listing route. Use it when every market matters. Use [Search Markets](/data/markets/search) when relevance search is more useful than a complete cursor walk. Rows are ordered by `updated_at` descending, with rows that have no update timestamp placed last. ## Request ```text theme={null} GET /v3/markets ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `limit` | integer | 100 | Rows per page. Values below 1 use 1; values above 300 use 300. | | `cursor` | string | none | Opaque `next_cursor` returned by the preceding page. | | `status` | string | all | `open`, `closed`, `inactive`, or `all`. Matching is case-insensitive. | | `event_slug` | string | none | Exact parent event slug. | | `sort` | string | `updated` | Only `updated` is available. | | `order` | string | `desc` | Only `desc` is available. | Offset pagination is not supported on this route. ## First page ```bash theme={null} curl "https://api.polynode.dev/v3/markets?status=open&limit=2" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "markets": [ { "condition_id": "0x1111111111111111111111111111111111111111111111111111111111111111", "question": "Will the example market resolve Yes?", "slug": "will-the-example-market-resolve-yes", "outcomes": ["Yes", "No"], "active": true, "closed": false, "status": "open", "event_slug": "example-event", "event_title": "Example event", "tag_slugs": ["example"], "category": "examples", "image": "https://example.com/market.png", "updated_at": "2026-08-27T20:00:00Z", "volume_all_time": null, "liquidity": null, "outcome_prices": null } ], "rows_returned": 1, "has_more": true, "limit": 2, "next_cursor": "mec1.example-cursor", "sort": "updated", "order": "desc", "filters": { "status": "open", "event_slug": null } } ``` The example cursor is shortened for display. Treat a real cursor as opaque. ## Continue pagination Pass `next_cursor` unchanged and keep the same `status` and `event_slug` filters: ```bash theme={null} curl "https://api.polynode.dev/v3/markets?status=open&limit=2&cursor=$NEXT_CURSOR" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Stop when `has_more` is `false`. The last page returns `next_cursor: null`. Cursors expire, so complete a page walk promptly rather than storing a cursor as a permanent market ID. ## Response envelope | Field | Type | Description | | - | - | - | | `markets` | array | Market rows in this page. | | `rows_returned` | integer | Number of rows returned. | | `has_more` | boolean | Whether another page exists. | | `limit` | integer | Effective page size. | | `next_cursor` | string or null | Cursor for the next page, or `null` on the last page. | | `sort` | string | Always `updated`. | | `order` | string | Always `desc`. | | `filters.status` | string or null | Canonical status filter, or `null` for all statuses. | | `filters.event_slug` | string or null | Event filter, or `null`. | ## Market fields | Field | Type | Nullable | Description | | - | - | - | - | | `condition_id` | string | no | Market condition ID. | | `question` | string | yes | Market question. | | `slug` | string | yes | Market slug. | | `outcomes` | array\ | yes | Outcome labels. | | `status` | string | no | `open`, `closed`, or `inactive`. | | `active`, `closed`, `archived` | boolean | yes | Market state flags when available. | | `enable_order_book` | boolean | yes | Whether orderbook trading is enabled. | | `end_date`, `closed_time` | string | yes | Market timestamps when available. | | `neg_risk` | boolean | yes | Whether the market uses neg-risk settlement. | | `neg_risk_market_id` | string | yes | Neg-risk market ID when available. | | `event_slug`, `event_title` | string | yes | Parent event identity. | | `group_item_title` | string | yes | Group label for a market inside an event. | | `image`, `icon` | string | yes | Image URLs when available. | | `tag_slugs` | array\ | no | Market tags. An untagged market returns an empty array. | | `category` | string | yes | Market category when available. | | `winning_outcome_index` | integer | yes | Winning outcome index after resolution. | | `updated_at`, `pm_created_at`, `pm_updated_at` | string | yes | Market timestamps when available. | | `volume_all_time`, `liquidity`, `outcome_prices` | null | yes | Reserved financial fields. This catalog currently returns `null`; do not treat them as zero. | ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | `invalid_request` | Invalid status, event slug, sort, order, or use of `offset`. | | `400` | `invalid_cursor` | A cursor is malformed, expired, or used with different filters. | | `401` | authentication error | The API key is missing or invalid. | | `410` | `invalid_cursor` | The page walk referenced by the cursor is no longer available. Start again without a cursor. | | `503` | `temporarily_unavailable` | Markets and events are temporarily unavailable. | # Market Catalog Stats Source: https://docs.polynode.dev/data/markets/catalog-stats GET /v3/markets/stats Get complete market counts and open, closed, and inactive status totals. Returns counts for the complete [market catalog](/data/markets/catalog), independent of any one page. ## Request ```bash theme={null} curl "https://api.polynode.dev/v3/markets/stats" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Response ```json theme={null} { "market_count": 2662678, "event_linked_market_count": 2653204, "event_count": 900634, "status_counts": { "open": 544652, "closed": 2071666, "inactive": 46360 } } ``` Counts change as markets are added or their status changes. | Field | Type | Description | | - | - | - | | `market_count` | integer | Markets in the complete catalog. | | `event_linked_market_count` | integer | Markets with a parent event slug. | | `event_count` | integer | Distinct parent events represented by linked markets. | | `status_counts.open` | integer | Open markets. | | `status_counts.closed` | integer | Closed markets. | | `status_counts.inactive` | integer | Markets that are neither open nor closed. | ## Errors | Status | Error | When it occurs | | - | - | - | | `401` | authentication error | The API key is missing or invalid. | | `503` | `temporarily_unavailable` | Markets and events are temporarily unavailable. | # Market Positions (Condition) Source: https://docs.polynode.dev/data/markets/condition-positions GET /v3/markets/condition/{condition_id}/positions Get wallet positions across every outcome token in a market condition. Returns wallet-position rows for every outcome token in a market condition. Use `sort=amount` to fetch the largest current holders first across all outcomes in the condition. ## Request ``` GET /v3/markets/condition/{condition_id}/positions ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `condition_id` | string | Market condition ID (`0x` + 64 hex characters). The response includes positions for every outcome token in this condition. | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sort` | string | `pnl` | Sort order. One of `pnl` (realized P\&L), `amount` (current shares held), or `volume` (total bought). | | `limit` | integer | 100 | Rows per page. Requests are capped by API key tier: Starter `300`, Growth `1000`, Enterprise `1000`. | | `offset` | integer | 0 | Number of rows to skip for pagination. | If `limit` is above your tier cap, PolyNode normalizes it to the maximum allowed value instead of rejecting the request. Every response includes the applied `limit`, plus `rows_returned`, `offset`, and `has_more`. ## Sorting Use `sort=amount` when you need the largest current holders for a condition. The sort is descending, so the first rows are the wallets with the highest current `amount` across the condition's outcome tokens. ## Example ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/markets/condition/0x713641f745d71f6ec61f906237ffca3c8583f251e49384429a63ceb0ccdb2d37/positions?sort=amount&limit=1&offset=0" ``` ### Example response ```json theme={null} { "data": [ { "amount": "6660546928621", "avg_price": null, "realized_pnl": "0", "token_id": "1770840559776249239623005379825945674336282130390798724203946923853499387834", "total_bought": "0", "user": "0xa5ef39c3d3e10d0b270233af41cac69796b12966" } ], "elapsed_ms": 3, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response columns | Column | Type | Description | | - | - | - | | `user` | string | Wallet address (lowercased) | | `token_id` | string | Outcome token this row covers (each condition has multiple outcomes; a wallet can appear once per outcome it has touched) | | `amount` | string | Current shares held in 6-decimal token units (`0` if the wallet has exited this outcome) | | `avg_price` | string \| null | Average entry price in 6-decimal USDC units (`500000` = \$0.50). May be `null` when cost basis is not available. | | `realized_pnl` | string | Realized P\&L on the closed portion of the position in 6-decimal USDC units | | `total_bought` | string | Cumulative purchase cost basis in 6-decimal USDC units | # Market Positions (Token) Source: https://docs.polynode.dev/data/markets/positions GET /v3/markets/{token_id}/positions Get all wallets holding positions in a specific outcome token, sorted by P&L or size. Returns all wallets that hold or have held positions in a specific outcome token. ## Request ``` GET /v3/markets/{token_id}/positions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sort` | string | `pnl` | Sort by: `pnl`, `amount`, `volume` | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/markets/75783394880030392863380883800697645018418815910449662777195626260206142035810/positions?limit=1 ``` ```json theme={null} { "data": [ { "amount": "0", "avg_price": "490000", "realized_pnl": "9999999", "total_bought": "19607842", "user": "0xa435d9eb84bf50f5d72d88023a77e8c7fd1d572d" } ], "elapsed_ms": 204, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response columns | Column | Type | Description | | - | - | - | | `user` | string | Wallet address | | `amount` | string | Current shares held (6-decimal) | | `avg_price` | string | Weighted-average entry price (6-decimal) | | `realized_pnl` | string | Realized P\&L (6-decimal USDC) | | `total_bought` | string | Total volume bought (6-decimal USDC) | # Token Price Source: https://docs.polynode.dev/data/markets/price GET /v3/markets/{token_id}/price Get the current price, resolution status, and price source for any outcome token. Returns the latest price for an outcome token, including where the price was sourced from and whether the market has resolved. ## Request ``` GET /v3/markets/{token_id}/price ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `token_id` | string | Outcome token ID | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/markets/75783394880030392863380883800697645018418815910449662777195626260206142035810/price ``` ```json theme={null} { "token_id": "75783394880030392863380883800697645018418815910449662777195626260206142035810", "price": 1.0, "resolved": true, "source": "settlement", "updated_at": "2026-05-13 12:27:28.558218", "elapsed_ms": 1 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `token_id` | string | Outcome token ID | | `price` | number | Token price in USD. Range `0`–`1` for unresolved markets, exactly `0` or `1` for resolved. | | `resolved` | boolean | Whether the market has settled | | `source` | string | Price source: `settlement` (final payout), `clob_mid` (CLOB orderbook midpoint), `v1_condition` (V1 condition payout), `last_fill` (most recent trade price) | | `updated_at` | string | When the price was last updated | ### Price priority Prices follow this priority chain (higher sources are never overwritten by lower ones): 1. `settlement` -- final payout after market resolution (`0` or `1`) 2. `clob_mid` -- live CLOB orderbook midpoint (updated every 5 minutes) 3. `v1_condition` -- V1 condition payout data 4. `last_fill` -- price from the most recent trade # Search Markets Source: https://docs.polynode.dev/data/markets/search GET /v3/markets/search Full-text search across all Polymarket markets. Returns matching markets with metadata. Search market questions by keyword. Returns matching markets with metadata, volume, and resolution status. ## Request ``` GET /v3/markets/search ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `q` | string | required | Search query. Case-insensitive substring match against the `question`, `slug`, and `event_title` fields. Multiple words are AND-matched. | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ### How matching works * `?q=bitcoin` matches any market whose question, slug, or event title contains the substring `bitcoin` (any case). * `?q=trump pardon` matches questions containing both substrings, in any order. * Punctuation in the query is preserved (`?q=$72,000` matches the literal characters). * Results are ordered by `volume_all_time DESC` so higher-traded markets surface first. ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/markets/search?q=bitcoin&limit=1" ``` ```json theme={null} { "data": [ { "active": true, "category": null, "closed": true, "condition_id": "0x58c931c00e31fd20d02aade0c1e287e46a15b6da514c3ac3624e956e41bc45d0", "question": "Will the price of Bitcoin be above $72,000 on February 13?", "slug": "bitcoin-above-72k-on-february-13", "tag_slugs": [ "Crypto", "Bitcoin", "Crypto Prices", "Recurring", "Hide From New", "Weekly", "Multi Strikes" ], "volume_all_time": "999989.65550899994559586048126220703125", "winning_outcome_index": 1 } ], "elapsed_ms": 668, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response fields (per row in `data`) | Field | Type | Nullable | Description | | - | - | - | - | | `condition_id` | string | no | Market condition ID | | `question` | string | no | Market question text | | `slug` | string | no | URL slug | | `category` | string | yes | Optional category label | | `volume_all_time` | string (decimal) | no | Total volume in USD at full precision | | `active` | boolean | no | Currently active | | `closed` | boolean | no | No longer accepting orders | | `winning_outcome_index` | integer | yes | Which outcome won (null if unresolved) | | `tag_slugs` | array\ | yes | Tags in canonical (Title Case) form | # Market Trades Source: https://docs.polynode.dev/data/markets/trades GET /v3/markets/{token_id}/trades Get all trades for a specific outcome token or market slug, with full enrichment. Returns fills involving a specific outcome token, enriched with market metadata, computed prices, and order hashes. Can look up by token ID or market slug. ## By token ID ``` GET /v3/markets/{token_id}/trades ``` ## By market slug ``` GET /v3/markets/slug/{slug}/trades ``` Resolves the slug to all token IDs for that market and returns trades across all outcomes. ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `order_hash` | string | -- | Return only fills for one exact order hash (`0x` + 64 hex characters) | | `min_amount_usd` | number | -- | Minimum trade size in dollars, matching the `amount_usd` response field. Decimals allowed, e.g. `99.5` | | `order` | string | `desc` | `asc` or `desc` | | `sort_by` | string | -- | `order_hash` groups fills from the same order visually | | `group_by` | string | -- | `order_hash` aggregates the returned fills per order | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | Both the token-ID and market-slug forms accept `order_hash` and `min_amount_usd`. Filters are intersected and applied before pagination. For example, `?order_hash=0x...&min_amount_usd=100` returns only \$100+ fills from that order in the selected token or market. A valid hash with no scoped fills returns an empty `200` page; an empty or malformed hash returns `400`. ## Example (by token ID) ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v3/markets/75783394880030392863380883800697645018418815910449662777195626260206142035810/trades?limit=1" ``` ```json theme={null} { "elapsed_ms": 1, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1, "token_id": "75783394880030392863380883800697645018418815910449662777195626260206142035810", "trades": [ { "amount": 5000.0, "amount_usd": 5.0, "asset": "75783394880030392863380883800697645018418815910449662777195626260206142035810", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "condition_id": "0x4f05dbc6273b89aed46bb79a961c1d8771c01925d92d439e9a81fa6241900661", "direction": "BUY", "event_id": 475423, "event_slug": "dota2-aur1-liquid-2026-05-13", "fee": 0.14985, "id": "0x01d8b23249b1327d103d033ae9c4cff7303ff87a2cf1bcca7d53bbfb98aec6ed_0xfdc90661e12491b7b4244496eaec409d45a4df55d734244e297eb761bec220b9_1378", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/dota2-7ffacddb21.jpg", "maker": "0xcf19ba47a99eee6be9925211c4f0c6cfd1c344b5", "maker_amount": 5.0, "maker_asset_id": "0", "market": "Dota 2: Aurora vs Team Liquid (BO3) - DreamLeague Group A", "order_hash": "0xfdc90661e12491b7b4244496eaec409d45a4df55d734244e297eb761bec220b9", "outcome": "Aurora", "outcome_index": 0, "price": 0.001, "role": "maker", "side": 0, "size": 5000.0, "slug": "dota2-aur1-liquid-2026-05-13", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "taker_amount": 5000.0, "taker_asset_id": "75783394880030392863380883800697645018418815910449662777195626260206142035810", "timestamp": "1778692047", "token_id": "75783394880030392863380883800697645018418815910449662777195626260206142035810", "transaction_hash": "0x01d8b23249b1327d103d033ae9c4cff7303ff87a2cf1bcca7d53bbfb98aec6ed" } ] } ``` ## Example (by slug) ```bash theme={null} curl https://api.polynode.dev/v3/markets/slug/dota2-aur1-liquid-2026-05-13/trades?limit=5 ``` ## Filter a market by order hash ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/markets/slug/nba-det-cle-2026-05-15/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c" ``` ## Response fields Each trade contains the same fields as [Wallet Trades](/data/wallets/trades), including all market enrichment fields. # API Overview Source: https://docs.polynode.dev/data/overview polynode API reference. Real-time streaming, historical data, P&L analytics, market data, and more. The polynode API provides two main surfaces: 1. **V3 Historical Data** — query the complete Polymarket V1 + V2 historical dataset. 1.2 billion fills, 228 million positions, 2.7 million wallets. Dual P\&L (realized + unrealized), position tracking with settlement status, builder analytics, market search, and leaderboards. 2. **Real-time Streaming** — live WebSocket feeds for settlements, trades, price updates, position changes, and more. See the [WebSocket tab](/websocket/overview). The V3 endpoints are **live** and provide the most comprehensive Polymarket dataset available. ## V3 Data API — Base URL ``` https://api.polynode.dev/v3 ``` ## Authentication Every `/v3/*` endpoint requires an API key. Pass it either as a `key` query parameter or as a bearer token in the `Authorization` header: ```bash theme={null} # Query string curl "https://api.polynode.dev/v3/stats?key=pn_live_..." # Bearer header curl -H "Authorization: Bearer pn_live_..." https://api.polynode.dev/v3/stats ``` Get a key from the [dashboard](https://polynode.dev/dashboard). All examples in this section assume `?key=YOUR_KEY` is appended (omitted only for brevity in the code blocks). ## Dataset Scale Query `GET /v3/stats` for live counts. Current scale: | Metric | Count | | - | - | | Fills (trades) | 1+ billion | | Positions | 200+ million | | Unique wallets | 2.5+ million | | Redemptions | 160+ million | | Splits | 30+ million | | Merges | 14+ million | | Markets tracked | 1.07 million | | Token prices | 2 million | ## Key features * **Dual P\&L** — realized and unrealized profit/loss for every wallet, computed from the full event history using weighted-average cost basis math * **Position status** — every position is tagged as `open`, `closed`, `redeemable`, or `redeemed` based on live settlement data * **Redeemable payouts** — see exactly how much USDC a wallet can claim from resolved markets * **Builder attribution** — 77 million fills attributed to 1,502 unique builders * **Batch queries** — query up to 100 wallets in a single call * **Time-range filters** — filter trades, redemptions, and activity by Unix timestamp * **Market search** — full-text search across 1 million+ market questions ## Amounts and precision Monetary fields come in two conventions depending on the endpoint: **Decimal USD (JSON number).** Used by aggregated P\&L responses (wallet summary, batch, pnl, positions) and by token-price responses (`/v3/markets/{token_id}/price`, `/v3/tokens/{token_id}`): ```json theme={null} { "net_realized_pnl": 22053845.825455, "total_volume": 43013258.515682 } { "price": 0.42 } ``` `net_realized_pnl: 22053845.825455` means **$22,053,845.83 USD**. `price: 0.42` means **$0.42 per share** (Polymarket outcome prices are always in the range 0–1). **Raw 6-decimal USDC (JSON string).** Used by event-level rows — fees, splits, merges, redemptions, NRC, activity, tag-leaderboard rollups, market-positions rows: ```json theme={null} { "amount": "120469388830" } ``` Divide by `1_000_000` to get USD. `"120469388830"` is **120,469.38883 USDC**. **Full-precision decimal (JSON string).** Used by raw subgraph fields like `volume_all_time`, `liquidity`, `price`: ```json theme={null} { "volume_all_time": "99993.937724000003072433173656463623046875" } ``` These are stored at full Postgres `numeric` precision (up to \~50 digits). Round on the client; do not parse as a JS `Number`. Each endpoint's response-fields table explicitly notes which convention applies. ## Identifiers and large numbers Polymarket `token_id` and `position_id` values are 78-digit decimal integers (uint256). They are returned as **JSON strings** so they survive standard JSON parsers — IEEE 754 doubles cannot represent them. Treat them as opaque strings; do not parse them as numbers. ## Polymarket Protocol V2 markets Markets on Polymarket Protocol V2, Polymarket's new market system, appear in the same endpoints with the same fields and units. Their rows add `protocol_version: "v2"`, `module`, `structural_condition_id`, on multi-outcome markets `neg_risk_event_id`, and on resolved markets the exact result as `payouts_ppm`. Endpoints that take a condition id accept the 66-character form and Polymarket's 31-byte form. Elsewhere on this page, "V1" and "V2" refer to Polymarket's exchange before and after the April 2026 exchange upgrade. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ## Nullable fields Many fields can be `null` in real responses even when the example shows a populated value — typically when a row was created before the metadata pipeline backfilled it, or when a market hasn't resolved yet. Each endpoint's response-fields table has a **Nullable** column. Defensive clients should accept `null` for any field marked nullable, plus for any field whose row predates indexing. ## Response envelopes Endpoints fall into three envelope shapes: | Shape | Endpoints | Top-level data key | | - | - | - | | Single-object | `GET /v3/wallets/{addr}`, `GET /v3/wallets/{addr}/pnl`, `GET /v3/markets/{token_id}/price`, `GET /v3/conditions/{cid}`, `GET /v3/builders/{code}`, `GET /v3/stats` | Fields at top level (no wrapper) | | Named list | `/v3/trades`, `/v3/wallets/{addr}/trades`, `/v3/markets/{token_id}/trades`, `/v3/markets/slug/{slug}/trades`, `/v3/builders/{code}/trades` | `"trades": [...]` | | Named list | `/v3/positions`, `/v3/wallets/{addr}/positions` | `"positions": [...]` | | Named list | `/v3/leaderboard` | `"leaderboard": [...]` | | Named list | `/v3/tags`, `/v3/builders` | `"tags": [...]`, `"builders": [...]` | | Named list | `POST /v3/wallets/batch` | `"wallets": [...]` | | Generic list | Everything else (fees, resolutions, splits, merges, NRC, activity, redemptions, tag-leaderboard, tag-markets, market-positions, condition-positions, market-by-condition, market-search, tokens/info) | `"data": [...]` | Standard ungrouped list responses also include `rows_returned`, `has_more`, `offset`, `limit`, and `elapsed_ms`. Grouped trade responses are the exception: with `group_by=order_hash`, the response includes `trades`, `rows_returned`, `grouped_by`, and `elapsed_ms`, but omits `has_more`, `offset`, and `limit`. ## Owner addresses Pass an owner EOA to a wallet endpoint below and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for that endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xb365112c16570fd249e972e1ce91f621b090495a/pnl" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The response keeps its usual fields, sums them across the combined wallets, and lists those wallets in `wallets`. Here the Safe has -292.08 over 479 positions and the deposit wallet -65.65 over 9 (excerpt, values from 2026-10-21): ```json theme={null} { "address": "0xb365112c16570fd249e972e1ce91f621b090495a", "realized_pnl": -357.729130, "gross_profit": 5471.188973, "gross_loss": -3277.639933, "unrealized_pnl": 0.0, "total_pnl": -357.729130, "wins": 202, "losses": 271, "position_count": 488, "open_positions": 0, "total_volume": 69142.870196, "wallets": [ { "wallet": "0xab08afea55b32ef017970556bb578d081c9937fa", "type": "safe" }, { "wallet": "0xe415429c78a6d39557c4549e5af109502c373fb8", "type": "deposit_wallet" } ] } ``` Endpoints that accept an owner EOA: | Area | Endpoints | | - | - | | Summary and P\&L | `GET /v3/wallets/{address}`, `POST /v3/wallets/batch`, `/pnl`, `/pnl/events` | | Wallet history | `/positions`, `/trades`, `/activity`, `/splits`, `/merges`, `/redemptions`, `/fees-paid`, `/nrc` | | Combos | `/combos/positions`, `/combos/activity`, `/combos/redemptions`, `/combos/trades`, `/combos/summary`, and the `wallet` filter on `/v3/combos/activity` and `/v3/combos/redemptions` | | Credits | `/credits`, `/credits/totals`, `/credits/series` | Combined responses: | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets. Present only on combined responses. In `POST /v3/wallets/batch` it is inside each combined element. | | `wallets[].wallet` | string | Wallet address, lowercased | | `wallets[].type` | string | `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `wallet` (on each list row) | string | The wallet the row belongs to | * `address` (`wallet` on credits routes) is still the address you passed. * `wallets` lists the EOA first when it has its own history, then its Safe, proxy and deposit wallets. Only wallets with data for that endpoint are listed, so `wallets` can differ between endpoints. * Totals and counts are summed across the combined wallets, and time-series buckets are summed per bucket. A field that cannot be summed, such as a status, is `null` when the combined wallets disagree. * Lists keep the endpoint's sort order, and `limit`, `offset`, `has_more`, and `next_offset` page through the combined list. Combining covers the first 10,000 rows (`offset + limit` up to 10,000). A deeper page returns only the address you passed, with no `wallets`. * Rows are never merged across wallets: two wallets holding the same token return two rows, and a fill between two of the owner's wallets appears once for each wallet. Include `wallet` when you key rows by `token_id` or `id`. * In `POST /v3/wallets/batch`, each owner EOA is combined on its own. The response keeps one element per requested address, in request order. * If any combined wallet returns an error, the request returns that error instead of a partial result. If combining does not finish in time, the request returns `503`. Nothing changes when: * You pass a Safe, proxy, or deposit wallet, or an EOA that owns no wallets with data. The response is the same as before, with no `wallets` field. * You call rebates, rewards, Copy PnL, webhooks, or WebSocket wallet filters. These still match only the exact address you pass. V1 and V2 wallet endpoints are also unchanged. ## Timestamps All Unix timestamps in responses are in **seconds** (e.g., `"1778674056"`). The `resolved_at` field in resolutions uses **milliseconds** (e.g., `"1778674836000"`). Datetime strings like `updated_at` are in UTC. ## Rate limits V3 REST data endpoints require a paid API key. Limits are shared across all API keys owned by the same account, so keys can be used at the same time without multiplying the account's throughput. | Plan | Standard V3 REST | Heavy V3 trade endpoints | | - | - | - | | Starter | 1,000 req/min | 1,000 req/min | | Growth | 2,000 req/min | 1,500 req/min | | Enterprise | 4,000 req/min default; custom by agreement | 1,500 req/min default; custom by agreement | See [Rate Limits](/guides/rate-limits) for the full tier table and heavy-endpoint details. ## Pagination Most list endpoints support: * `?limit=N` — results per page (usually default 100 and max 300) * `?offset=N` — skip N results The Builder trader leaderboard is an explicit exception: it returns at most 100 rows per request and supports the first 500 ranks. Ungrouped responses include the actual `limit` used, plus `has_more: true/false` to indicate if more pages exist. Grouped trade requests still accept `limit` and `offset`, but their responses omit those fields and `has_more`; track the requested values and stop after an empty `trades` array. For deep trade-history walks, prefer `after` and `before` time windows instead of very large offsets. ## Response format Every response includes `elapsed_ms` showing server-side query time in milliseconds. ```json theme={null} { "data": [...], "rows_returned": 100, "has_more": true, "offset": 0, "limit": 100, "elapsed_ms": 12 } ``` ## Endpoint categories | Category | Endpoints | What you can do | | - | - | - | | [Wallet P\&L](/data/wallets/summary) | 4 | Wallet summary, dual P\&L breakdown, batch queries, enriched positions | | [Wallet Activity](/data/wallets/trades) | 6 | Trades, redemptions, splits, merges, NRC, combined activity | | [Combos](/data/combos/overview) | 8 | Combo markets, P\&L rankings, wallet combo positions, combo trades, lifecycle activity, and additive wallet summaries | | [Markets](/data/markets/search) | 8 | Search, lookup by condition/token/slug, trades, positions, prices, candles | | [Leaderboard](/data/leaderboard/global) | 3 | Global P\&L rankings, tag discovery, tag leaderboards | | [Builders](/data/builders/list) | 6 | Directory and name lookup, profile stats, daily activity and comparison, trader leaderboard, attributed trades | | [Global](/data/global/stats) | 5 | Platform stats, trade feed, fees, resolutions, conditions | | [Tokens](/data/tokens/info) | 1 | Token price and market metadata | ## Explorer Browse the data interactively with pre-built SQL recipes at [explorer.polynode.dev](https://explorer.polynode.dev). # Builders Query Catalog Source: https://docs.polynode.dev/data/query-catalog/builders Builder recipes for rankings, profiles, fee sorting, attributed trades, and filtered builder feeds. Use these recipes when building builder dashboards, attribution analytics, or builder-specific trade feeds. > [card] [Builder Leaderboard](/data/query-catalog/builders/leaderboard) > > Rank Builders by fills, volume, or fees. > [card] [Builder Detail](/data/query-catalog/builders/detail) > > Stats and public profile metadata for one builder. > [card] [Builder Trader Leaderboard](/data/query-catalog/builders/trader-leaderboard) > > Rank one Builder's active traders by P\&L or attributed activity. > [card] [Builder Daily Activity](/data/query-catalog/builders/daily-activity) > > Chart daily volume, fills, traders, fees, and buy/sell mix. > [card] [Compare Builder Activity](/data/query-catalog/builders/activity-comparison) > > Fetch aligned daily series for up to 20 Builder codes. > [card] [Builder Trades](/data/query-catalog/builders/trades) > > Trades attributed to one builder code. > [card] [Builder Trades by Market](/data/query-catalog/builders/trades-by-market) > > Builder-attributed trades inside one market. > [card] [Builder Trades by Tag or Category](/data/query-catalog/builders/trades-by-tag-category) > > Indexed builder tag/category filters paired with market, condition, or token filters. > [card] [Builder Trades by Side and Size](/data/query-catalog/builders/trades-by-side-size) > > Buy/sell and amount filters for builder trades. # Compare Builder Daily Activity Source: https://docs.polynode.dev/data/query-catalog/builders/activity-comparison Fetch aligned daily series for up to 20 selected Builder codes in one request. Canonical reference: [Compare Builder Daily Activity](/data/builders/activity-comparison) ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/activity/daily?builders=$BUILDER_CODES&start_date=2026-08-01&end_date=2026-08-30&include_other=false" ``` Set `BUILDER_CODES` to a comma-separated list of one to 20 canonical codes. Use `include_other=true` to append one residual series for all unselected Builders. # Builder Daily Activity Source: https://docs.polynode.dev/data/query-catalog/builders/daily-activity Chart one Builder's daily volume, fills, traders, fees, and buy/sell mix. Canonical reference: [Builder Daily Activity](/data/builders/daily-activity) ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/BetMoar/activity/daily?start_date=2026-08-01&end_date=2026-08-30&top_limit=5" ``` Windows of 31 days or fewer include recent top-market and category composition. Longer windows keep the daily series and return empty composition arrays. # Builder Detail Source: https://docs.polynode.dev/data/query-catalog/builders/detail Get stats and public profile metadata for one builder. Canonical reference: [Builder Detail](/data/builders/detail) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Builder Leaderboard Source: https://docs.polynode.dev/data/query-catalog/builders/leaderboard Rank builders by V2-attributed share-notional volume, fills, or fees. Canonical reference: [Builder Leaderboard](/data/builders/list) ```bash theme={null} curl "https://api.polynode.dev/v3/builders?sort=volume&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` `sort=volume` uses locally indexed outcome-share par notional, matching Polymarket's builder-volume convention for CLOB V2 history. Supported sorts are `fills`, `volume`, and `fees`. # Builder Trader Leaderboard Source: https://docs.polynode.dev/data/query-catalog/builders/trader-leaderboard Rank one Builder's active trader cohort across rolling and All Time P&L or attributed activity. Canonical reference: [Builder Trader P\&L Leaderboard](/data/builders/trader-leaderboard) ```bash theme={null} curl -H "x-api-key: $POLYNODE_API_KEY" \ "https://api.polynode.dev/v3/builders/BetMoar/leaderboard?period=30d&sort=pnl&limit=100&offset=0" ``` Use `period=1d`, `7d`, `30d`, or `all`. Period, sort, and order values are case-insensitive and responses return canonical lowercase values. Each request returns at most 100 rows; the supported rank window ends at 500. For a repeat-free All-Time P\&L walk, start with `pagination=cursor&offset=0`, then pass each response's `next_cursor`, `as_of`, and `pnl_as_of` with the next offset. Keep the same Builder, period, sort, order, and limit. Stop at `has_more=false`; restart at offset `0` after a snapshot-change HTTP `409`. P\&L is global Polymarket wallet P\&L for the Builder-active cohort, not P\&L attributed exclusively to that Builder. Volume, fills, fees, active days, and recency are Builder-attributed. # Builder Trades Source: https://docs.polynode.dev/data/query-catalog/builders/trades Get trades attributed to one builder code. Canonical reference: [Builder Trades](/data/builders/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Builder Trades by Market Source: https://docs.polynode.dev/data/query-catalog/builders/trades-by-market Filter builder-attributed trades to one market slug. Canonical reference: [Builder Trades](/data/builders/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` You can also use `condition_id` or `token_id` when you already have those identifiers. # Builder Trades by Side and Size Source: https://docs.polynode.dev/data/query-catalog/builders/trades-by-side-size Filter builder-attributed trades by side and minimum amount. Canonical reference: [Builder Trades](/data/builders/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?side=buy&min_amount=1000000&limit=10" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `side=buy` or `side=sell`. `min_amount` is useful for large-trade filters. # Builder Trades by Tag or Category Source: https://docs.polynode.dev/data/query-catalog/builders/trades-by-tag-category Filter builder trades by tag or category on a narrow market, condition, or token scope. Canonical reference: [Builder Trades](/data/builders/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&tag_slug=sports&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?market_slug=dota2-tundra-xtreme-2026-05-22-game1&category=Sports&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Pair broad tag or category filters with `market_slug`, `condition_id`, or `token_id` for the indexed query path. # Combos Query Catalog Source: https://docs.polynode.dev/data/query-catalog/combos Combo recipes for markets, activity, wallet summaries, combo positions, combo trades, and combined wallet views. Use these recipes when building combo market explorers, combo wallet dashboards, or lifecycle activity feeds. > [card] [Combo Markets](/data/query-catalog/combos/markets) > > List observed combo markets with leg metadata. > [card] [Combo Activity](/data/query-catalog/combos/activity) > > Lifecycle activity by combo market, condition, position, or wallet. > [card] [Combo P\&L Leaderboard](/data/combos/leaderboard) > > Global realized-P\&L windows and marked All Time rankings with explicit coverage. > [card] [Combo Redemptions](/data/query-catalog/combos/redemptions) > > Full redemptions, partial reductions, and exact combo lineage. > [card] [Wallet Combo Summary](/data/query-catalog/combos/wallet-summary) > > Combo-only P\&L, position counts, and win/loss counts (all time or windowed) for one wallet. > [card] [Wallet Combo Positions](/data/query-catalog/combos/wallet-positions) > > Combo positions for one wallet. > [card] [Wallet Combo Trades](/data/query-catalog/combos/wallet-trades) > > Combo trades for one wallet. > [card] [Wallet Combo Activity](/data/query-catalog/combos/wallet-activity) > > Combo lifecycle activity for one wallet. > [card] [Wallet Combo Redemptions](/data/query-catalog/combos/wallet-redemptions) > > Full and partial combo redemption history for one wallet. > [card] [Include Combos in Wallet Views](/data/query-catalog/combos/include-combos) > > Add combo branches to standard wallet P\&L, positions, and trades. # Combo Activity Source: https://docs.polynode.dev/data/query-catalog/combos/activity Query combo lifecycle activity by market, condition, position, or wallet. Canonical reference: [Combo Activity](/data/combos/activity) ```bash theme={null} curl "https://api.polynode.dev/v3/combos/activity?condition_id=0x03d98f6ac4c108c5ca66f79f34908a1d820000000000000000000000000000&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Include Combos in Wallet Views Source: https://docs.polynode.dev/data/query-catalog/combos/include-combos Add combo branches to standard wallet P&L, positions, and trades. Canonical reference: [Combos Overview](/data/combos/overview) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/pnl?include_combos=true" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/positions?include_combos=true&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/trades?include_combos=true&limit=10" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Combo Markets Source: https://docs.polynode.dev/data/query-catalog/combos/markets List observed combo markets with leg metadata. Canonical reference: [Combo Markets](/data/combos/markets) ```bash theme={null} curl "https://api.polynode.dev/v3/combos/markets?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Combo Redemptions Source: https://docs.polynode.dev/data/query-catalog/combos/redemptions Query terminal redemptions, post-resolution compression, and combo lineage across wallets. Canonical reference: [Combo Redemptions](/data/combos/redemptions) This recipe turns a combo lifecycle record into a direct before-and-after answer. Polymarket's public combo activity API identifies a `REDEEM` or `COMPRESS` operation and the legs on the reported combo. polynode additionally returns the source combo, removed legs, remaining legs, exact leg counts, and destination holding in the same row. ```bash theme={null} curl "https://api.polynode.dev/v3/combos/redemptions?redemption_scope=partial&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` To locate a post-resolution two-out-of-three transition from either side of its lineage, pass the original or reduced combo condition as `condition_id`. Use `event_kind=Extracted` separately for structural reduction without redemption evidence. ## What happened in the redemption? Use the count fields for the compact answer, then inspect the removed and remaining legs only when you need market details: ```bash theme={null} curl "https://api.polynode.dev/v3/combos/redemptions?tx_hash=0xe73ed3c24d1ca763984df61fad854479c45ea67b555ebaa547c994aa777add0c" \ -H "x-api-key: $POLYNODE_API_KEY" \ | jq '.redemptions[] | { tx_hash, redemption_scope, leg_transition, source_leg_count, removed_leg_count, remaining_leg_count, removed_legs: [.removed_legs[] | { leg_outcome_label, market_token_id, leg_result, leg_current_price, leg_price_source }], remaining_legs: [.remaining_legs[] | { leg_outcome_label, market_token_id, leg_result, leg_current_price, leg_price_source }], remaining_combo }' ``` * `3_to_0` with `redemption_scope=full` means the whole three-leg combo was redeemed. * `3_to_2` with `redemption_scope=partial` means one leg was removed and a two-leg combo remained. * `remaining_combo.still_held` tells you whether the wallet currently has a positive destination-combo balance when that balance is available. * `market_token_id` is the standard token to pass to [`GET /v3/markets/{token_id}/price`](/data/markets/price) or [`GET /v1/orderbook/{token_id}`](/api-reference/orderbook/order-book). For a UI, `redemption_scope` plus `leg_transition` is usually enough to display "full 3-leg redemption" or "5 legs became 1." For analytics or automation, use `source_position_id`, `destination_position_id`, and the changed-leg arrays so no transition has to be inferred from titles or current position state. To reconstruct multiple steps, fetch the wallet's rows and follow each row's `source_position_id` into a later row's `destination_position_id`. This keeps each API item scoped to one redemption while still supporting lifecycle analysis across calls. # Wallet Combo Activity Source: https://docs.polynode.dev/data/query-catalog/combos/wallet-activity List combo lifecycle activity for one wallet. Canonical reference: [Wallet Combo Activity](/data/combos/wallet-activity) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/activity?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Combo Positions Source: https://docs.polynode.dev/data/query-catalog/combos/wallet-positions List combo positions for one wallet. Canonical reference: [Wallet Combo Positions](/data/combos/wallet-positions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/positions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Combo Redemptions Source: https://docs.polynode.dev/data/query-catalog/combos/wallet-redemptions List terminal combo redemptions, partial compression, and structural lineage for one wallet. Canonical reference: [Wallet Combo Redemptions](/data/combos/wallet-redemptions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xf83ec0e37ac9eece71c064507270e9001a734663/combos/redemptions?redemption_scope=full&limit=25" \ -H "x-api-key: $POLYNODE_API_KEY" ``` For a one-row explanation of each wallet redemption, select the counts, transition, and compact destination holding: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xc82f0a25aad828f59347670e63ead5ea144466a7/combos/redemptions?limit=100" \ -H "x-api-key: $POLYNODE_API_KEY" \ | jq '.redemptions[] | { tx_hash, redemption_scope, leg_transition, source_leg_count, removed_leg_count, remaining_leg_count, remaining_combo }' ``` Use the canonical [combo redemptions recipe](/data/query-catalog/combos/redemptions) when you also need per-leg token IDs, result, price, and follow-up market queries. # Wallet Combo Summary Source: https://docs.polynode.dev/data/query-catalog/combos/wallet-summary Get combo-only P&L, position counts, and win/loss counts (all time or windowed) for one wallet. Canonical reference: [Wallet Combo Summary](/data/combos/wallet-summary) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/summary" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Win and loss counts for the past 7 days: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/summary?period=7d" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Combo Trades Source: https://docs.polynode.dev/data/query-catalog/combos/wallet-trades List combo trades for one wallet. Canonical reference: [Wallet Combo Trades](/data/combos/wallet-trades) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Markets Query Catalog Source: https://docs.polynode.dev/data/query-catalog/markets Market recipes for complete catalog walks, search, condition lookup, slug lookup, token info, prices, tags, and resolutions. Use these recipes when building market search, market detail pages, token pages, tag pages, or resolution feeds. > [card] [Complete Market Catalog](/data/markets/catalog) > > Walk every market with stable cursor pagination. > [card] [Complete Event Catalog](/data/events/catalog) > > Walk every parent event with member-market counts. > [card] [Catalog Statistics](/data/markets/catalog-stats) > > Read complete market and status counts independent of a page. > [card] [Search Markets](/data/query-catalog/markets/search-markets) > > Full-text market search. > [card] [Market by Condition](/data/query-catalog/markets/by-condition) > > Market metadata, outcomes, and token IDs from a condition ID. > [card] [Condition Detail](/data/query-catalog/markets/condition-detail) > > Resolution and payout data for one condition. > [card] [Trades and Positions by Slug](/data/query-catalog/markets/by-slug) > > Use a Polymarket slug to retrieve market trades or holders. > [card] [Token Info](/data/query-catalog/markets/token-info) > > Outcome-token metadata, price, category, tags, and resolution status. > [card] [Token Price](/data/query-catalog/markets/token-price) > > Current price and resolution status for one outcome token. > [card] [Market Candles](/data/query-catalog/markets/candles) > > OHLCV candles from V3 trade fills. > [card] [Tags](/data/query-catalog/markets/tags) > > List tags and find markets by tag. > [card] [Market Resolutions](/data/query-catalog/markets/resolutions) > > Recent market resolution feed. # Market by Condition Source: https://docs.polynode.dev/data/query-catalog/markets/by-condition Get market metadata and outcome tokens from a condition ID. Canonical reference: [Market by Condition](/data/markets/by-condition) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/condition/0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when your app stores market condition IDs. # Trades and Positions by Slug Source: https://docs.polynode.dev/data/query-catalog/markets/by-slug Use a market slug to fetch trades or positions. Canonical reference: [Market by Slug](/data/markets/by-slug) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-tundra-xtreme-2026-05-22-game1/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-tundra-xtreme-2026-05-22-game1/positions?sort=amount&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Market Candles Source: https://docs.polynode.dev/data/query-catalog/markets/candles Build OHLCV candles for a V3 market token, condition ID, or slug. Canonical reference: [Market Candles](/data/markets/candles) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/{token_id}/candles?resolution=5m&limit=120" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for V3 charting. Candles are built from trade fills and support `1m`, `5m`, `15m`, `1h`, `4h`, and `1d` buckets. # Condition Detail Source: https://docs.polynode.dev/data/query-catalog/markets/condition-detail Get resolution and payout data for a condition. Canonical reference: [Condition Detail](/data/global/conditions) ```bash theme={null} curl "https://api.polynode.dev/v3/conditions/0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for settlement, payout, and resolution status views. # Market Resolutions Source: https://docs.polynode.dev/data/query-catalog/markets/resolutions Browse recent resolved markets with payout data. Canonical reference: [Market Resolutions](/data/global/resolutions) ```bash theme={null} curl "https://api.polynode.dev/v3/resolutions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for settlement feeds and post-resolution workflows. # Search Markets Source: https://docs.polynode.dev/data/query-catalog/markets/search-markets Search Polymarket markets by text. Canonical reference: [Search Markets](/data/markets/search) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/search?q=dota&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use market search when a user enters free text or when you need to discover slugs and condition IDs. # Tags and Markets by Tag Source: https://docs.polynode.dev/data/query-catalog/markets/tags List tags and discover markets under a tag. Canonical references: [Tags](/data/leaderboard/tags), [Tag Markets](/data/leaderboard/tag-markets) ```bash theme={null} curl "https://api.polynode.dev/v3/tags?limit=3" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/tags/ufc?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Tag values are case-insensitive. URL hyphens are treated like spaces. # Token Info Source: https://docs.polynode.dev/data/query-catalog/markets/token-info Get metadata, price, category, tags, and resolution status for one outcome token. Canonical reference: [Token Info](/data/tokens/info) ```bash theme={null} curl "https://api.polynode.dev/v3/tokens/21578184864194020862792310253337084708609281967112790860038966988826118995357" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when you have an outcome token ID and need the market context around it. # Token Price Source: https://docs.polynode.dev/data/query-catalog/markets/token-price Get the current price and resolution status for one outcome token. Canonical reference: [Token Price](/data/markets/price) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/21578184864194020862792310253337084708609281967112790860038966988826118995357/price" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use token price for lightweight price checks when you do not need full market metadata. # Query Catalog Source: https://docs.polynode.dev/data/query-catalog/overview Intent-based catalog of the most useful PolyNode V3 query shapes. The API reference is organized by endpoint. The query catalog is organized by what you are trying to build: trade feeds, wallet dashboards, P\&L screens, market pages, fee accounting, builder analytics, and combo views. > [!NOTE] > > All examples use the public V3 API and an API key. Set `POLYNODE_API_KEY` once, then copy any example. ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." ``` > [card] [Trades](/data/query-catalog/trades) > > Global trades, wallet trades, market trades, builder-attributed trades, grouped orders, and combo trades. > [card] [Positions](/data/query-catalog/positions) > > Wallet positions, open positions, global holders, token holders, condition holders, slug holders, and combo positions. > [card] [P\&L](/data/query-catalog/pnl) > > Wallet P\&L, time-windowed P\&L, tag/market P\&L, P\&L events, batch reads, and leaderboards. > [card] [Markets](/data/query-catalog/markets) > > Search, condition lookup, condition detail, token info, price, tags, tag markets, and resolutions. > [card] [Wallet Activity](/data/query-catalog/wallet-activity) > > Unified activity, splits, merges, redemptions, neg-risk conversions, PolyUSD flows, fees, rebates, and rewards. > [card] [Fees](/data/fees/overview) > > Wallet-paid fees, global fee events, receiver fees, builder fee ranking, rebates, and reward configs. > [card] [Builders](/data/query-catalog/builders) > > Builder leaderboard, builder profiles, builder trades, market filters, side/size filters, tag filters, and category filters. > [card] [Combos](/data/query-catalog/combos) > > Combo markets, combo activity, combo wallet summary, combo positions, combo trades, and additive wallet views. ## Granular Recipes The left navigation includes both category pages and individual query recipes. Use the category pages for orientation, then jump to the exact query shape you need. # P&L Query Catalog Source: https://docs.polynode.dev/data/query-catalog/pnl P&L recipes for wallet totals, time windows, tag and market filters, events, batches, and leaderboards. Use these recipes when building wallet performance pages, time-series charts, filtered rankings, and leaderboard views. > [card] [Wallet All-Time P\&L](/data/query-catalog/pnl/wallet-all-time) > > Recovered all-time wallet P\&L with realized, unrealized, total, wins, losses, and volume. > [card] [Wallet Time-Windowed P\&L](/data/query-catalog/pnl/wallet-time-window) > > Realized P\&L for periods like 1d, 7d, 30d, and 1y. > [card] [Wallet P\&L by Tag](/data/query-catalog/pnl/wallet-by-tag) > > Wallet P\&L filtered to a tag or category. > [card] [Wallet P\&L by Market](/data/query-catalog/pnl/wallet-by-market) > > Wallet P\&L filtered to one condition or market slug. > [card] [Wallet P\&L Events](/data/query-catalog/pnl/wallet-events) > > Bucketed P\&L events for charts. > [card] [Batch Wallet P\&L](/data/query-catalog/pnl/batch-wallet-pnl) > > Read P\&L for multiple wallets in one request. > [card] [Global P\&L Leaderboard](/data/query-catalog/pnl/global-leaderboard) > > Rank wallets all-time or by 1-day, 7-day, and 30-day realized P\&L, globally or within one category or tag. > [card] [Tag P\&L Leaderboard](/data/query-catalog/pnl/tag-leaderboard) > > Rank wallets inside one tag using all-time metrics or rolling realized P\&L. # Batch Wallet P&L Source: https://docs.polynode.dev/data/query-catalog/pnl/batch-wallet-pnl Query P&L for multiple wallets in one request. Canonical reference: [Batch Wallet P\&L](/data/wallets/batch) ```bash theme={null} curl -X POST "https://api.polynode.dev/v3/wallets/batch" \ -H "content-type: application/json" \ -H "x-api-key: $POLYNODE_API_KEY" \ -d '{"wallets":["0x56687bf447db6ffa42ffe2204a05edaa20f55839","0x952d11ebff81d6bd3185e608ed3515b94618ab8a"]}' ``` Use this when a dashboard needs several wallet summaries at once. # Global P&L Leaderboard Source: https://docs.polynode.dev/data/query-catalog/pnl/global-leaderboard Rank wallets all-time or by 1-day, 7-day, and 30-day realized P&L. Canonical reference: [Leaderboard](/data/leaderboard/global) ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?sort=total&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Omitting `period` selects the all-time leaderboard. Use `sort=total`, `realized`, `unrealized`, `volume`, `profit`, `loss`, `wins`, or `positions` depending on the view. Use `period=1d`, `7d`, or `30d` for a rolling realized-P\&L leaderboard: ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=7d&limit=100" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Rolling views always use `sort=realized_pnl&order=desc`. They return realized metrics plus position, event, and market counts. Historical unrealized P\&L and volume are not part of rolling rows. Scope a rolling leaderboard to one category or one tag: ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=30d&category=sports&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" curl "https://api.polynode.dev/v3/leaderboard?period=30d&tag_slug=us-election&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Rolling pages contain up to 100 rows and are capped at rank 1,000. All-time global pages also contain up to 100 rows and are capped at rank 10,000. A shorter ranking ends at its last returned row. Market, event, condition, multiple-tag, and combined category-and-tag filters are not supported in rolling mode. Market, event, and condition filters remain available where documented for all-time queries. Leaderboards do not accept `after` or `before`; use `period` for a dated ranking. # Tag P&L Leaderboard Source: https://docs.polynode.dev/data/query-catalog/pnl/tag-leaderboard Rank wallets inside one tag using all-time metrics or rolling realized P&L. Canonical reference: [Tag Leaderboard](/data/leaderboard/tag-leaderboard) ```bash theme={null} curl "https://api.polynode.dev/v3/tags/ufc/leaderboard?period=7d&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The equivalent query form is: ```bash theme={null} curl "https://api.polynode.dev/v3/leaderboard?period=7d&tag_slug=ufc&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Omit `period` for the all-time tag leaderboard: ```bash theme={null} curl "https://api.polynode.dev/v3/tags/ufc/leaderboard?sort=total_pnl&limit=20" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Rolling tag leaderboards support `1d`, `7d`, and `30d`, rank by `realized_pnl` descending, and are capped at rank 1,000. A shorter ranking ends at its last returned row. A tag with no realized results in the selected window returns HTTP `200` with an empty `leaderboard`. # Wallet All-Time P&L Source: https://docs.polynode.dev/data/query-catalog/pnl/wallet-all-time Get recovered all-time wallet P&L. Canonical reference: [Wallet P\&L](/data/wallets/pnl) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/pnl" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The response includes realized P\&L, unrealized P\&L, total P\&L, gross profit, gross loss, wins, losses, open positions, and volume. # Wallet P&L by Market Source: https://docs.polynode.dev/data/query-catalog/pnl/wallet-by-market Filter wallet P&L to one condition ID or market slug. Canonical reference: [Wallet P\&L](/data/wallets/pnl) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?market=0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `market` for a condition ID, or `market_slug` for a Polymarket slug. `event_slug` and `condition_id` are also accepted for focused market/event P\&L views. # Wallet P&L by Tag Source: https://docs.polynode.dev/data/query-catalog/pnl/wallet-by-tag Filter wallet P&L to a tag or category. Canonical reference: [Wallet P\&L](/data/wallets/pnl) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?tags=sports" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use comma-separated `tags` for multiple tags where supported. `category` filters the first market tag, and `tag_slug` is accepted as an alias for single-tag filters. # Wallet P&L Events Source: https://docs.polynode.dev/data/query-catalog/pnl/wallet-events Get bucketed wallet P&L events for charts. Canonical reference: [Wallet P\&L Time Series](/data/wallets/pnl-events) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl/events?period=7d&group=day&limit=10" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `group=hour`, `day`, `week`, or `month` depending on the chart resolution. # Wallet Time-Windowed P&L Source: https://docs.polynode.dev/data/query-catalog/pnl/wallet-time-window Get wallet P&L for a period such as 30 days. Canonical reference: [Wallet P\&L](/data/wallets/pnl) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?period=30d&include_unrealized=true" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Supported period shortcuts are `1d`, `7d`, `30d`, and `1y`. You can also use `after` and `before` Unix timestamps. This query returns the change in **weighted-average-cost realized state** from immediately before the inclusive start through the inclusive end. It is not a historical snapshot of the all-time leaderboard. A position held through resolution can contribute to current all-time P\&L without changing realized state inside a time window. `include_unrealized=true` adds current unrealized P\&L; it does not reconstruct historical unrealized P\&L. See [Wallet P\&L](/data/wallets/pnl) for the complete reconciliation and timeout behavior. # Positions Query Catalog Source: https://docs.polynode.dev/data/query-catalog/positions Position recipes for wallet positions, open positions, holders, market positions, and combo positions. Use these recipes when building wallet dashboards, holder tables, market pages, or position discovery views. > [card] [Positions by Wallet](/data/query-catalog/positions/by-wallet) > > All standard positions for one wallet. > [card] [Open Wallet Positions](/data/query-catalog/positions/open-wallet-positions) > > Current open positions for one wallet. > [card] [Global Positions](/data/query-catalog/positions/global-positions) > > Platform-wide open-position discovery. > [card] [Positions by Market Token](/data/query-catalog/positions/by-market-token) > > Holders for one outcome token. > [card] [Positions by Condition](/data/query-catalog/positions/by-condition) > > Holders across all outcomes in one market condition. > [card] [Positions by Market Slug](/data/query-catalog/positions/by-market-slug) > > Holders for a market URL slug. > [card] [Combo Positions](/data/query-catalog/positions/combo-positions) > > Combo-only and combined wallet position views. # Positions by Condition Source: https://docs.polynode.dev/data/query-catalog/positions/by-condition Get holders across all outcomes in one market condition. Canonical reference: [Market Positions by Condition](/data/markets/condition-positions) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/condition/0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86/positions?sort=amount&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use condition-level positions when a market has multiple outcome tokens and you want the full holder table. # Positions by Market Slug Source: https://docs.polynode.dev/data/query-catalog/positions/by-market-slug Get holders for a market URL slug. Canonical reference: [Market by Slug](/data/markets/by-slug) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-tundra-xtreme-2026-05-22-game1/positions?sort=amount&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when your app stores or receives Polymarket slugs. # Positions by Market Token Source: https://docs.polynode.dev/data/query-catalog/positions/by-market-token Get holders for one outcome token. Canonical reference: [Market Positions](/data/markets/positions) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/21578184864194020862792310253337084708609281967112790860038966988826118995357/positions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when you already know the outcome token ID. # Positions by Wallet Source: https://docs.polynode.dev/data/query-catalog/positions/by-wallet Get all standard positions for one wallet. Canonical reference: [Wallet Positions](/data/wallets/positions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/positions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for wallet position tables with market context, current prices, unrealized P\&L, and settlement status. # Combo Positions Source: https://docs.polynode.dev/data/query-catalog/positions/combo-positions Get combo-only wallet positions or include combos in the standard wallet position view. Canonical references: [Wallet Combo Positions](/data/combos/wallet-positions), [Wallet Positions](/data/wallets/positions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/positions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/positions?include_combos=true&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Global Positions Source: https://docs.polynode.dev/data/query-catalog/positions/global-positions Browse platform-wide open positions. Canonical reference: [Global Positions](/data/global/positions) ```bash theme={null} curl "https://api.polynode.dev/v3/positions?status=open&sort=size&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for holder discovery across the platform. Add `condition_id`, `token_id`, `status`, `min_size`, and `sort` to narrow the result. # Open Wallet Positions Source: https://docs.polynode.dev/data/query-catalog/positions/open-wallet-positions Get current open positions for one wallet. Canonical reference: [Wallet Positions](/data/wallets/positions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/positions?status=open&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `status=open` when you only want active exposure. # Tags and Categories Query Catalog Source: https://docs.polynode.dev/data/query-catalog/tags-categories Tag and category recipes for discovery, market lists, P&L filters, leaderboards, and builder filters. Tags are market labels. In V3 market and token responses, the first tag is also the category used by category-style query filters. > [card] [Rolling Leaderboard Scopes](/data/leaderboard/scopes) > > Search and paginate categories or tags that have 1-day, 7-day, or 30-day rankings. > [card] [List Tags](/data/query-catalog/markets/tags) > > Discover available tag values. > [card] [Markets by Tag](/data/query-catalog/markets/tags) > > List markets under a tag. > [card] [Leaderboard by Tag](/data/query-catalog/pnl/tag-leaderboard) > > Rank wallets inside one tag using all-time metrics or 1-day, 7-day, and 30-day realized P\&L. > [card] [Wallet P\&L by Tag](/data/query-catalog/pnl/wallet-by-tag) > > Filter wallet P\&L to a tag/category. > [card] [Builder Trades by Tag or Category](/data/query-catalog/builders/trades-by-tag-category) > > Filter builder-attributed trades by tag/category on an indexed market, condition, or token scope. # Trades Query Catalog Source: https://docs.polynode.dev/data/query-catalog/trades Trade feed recipes for global, wallet, order-hash, market, builder, grouped-order, and combo trade queries. Use these recipes when building trade feeds, market tapes, wallet histories, builder analytics, or order-level views. > [card] [All Trades](/data/query-catalog/trades/all-trades) > > Global trade feed with pagination and time filters. > [card] [Trades by Wallet](/data/query-catalog/trades/by-wallet) > > Trades where one wallet was maker or taker. > [card] [Trades by Order Hash](/data/query-catalog/trades/by-order-hash) > > Exact order fills globally or scoped to a wallet or market. > [card] [Trades by Market Token](/data/query-catalog/trades/by-market-token) > > Trades for one outcome token. > [card] [Trades by Market Slug](/data/query-catalog/trades/by-market-slug) > > Trades for all outcomes in one market slug. > [card] [Wallet Trades by Condition](/data/query-catalog/trades/wallet-by-condition) > > One wallet's trades inside one market condition. > [card] [Wallet Trades Grouped by Order](/data/query-catalog/trades/wallet-grouped-by-order) > > Order-level grouping for wallet trades. > [card] [Builder Trades](/data/query-catalog/trades/by-builder) > > Trades attributed to a builder code. > [card] [Combo Wallet Trades](/data/query-catalog/trades/combo-wallet-trades) > > Combo-only and combined wallet trade views. # All Trades Source: https://docs.polynode.dev/data/query-catalog/trades/all-trades Browse the global Polymarket trade feed. Canonical reference: [Global Trades](/data/global/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `after`, `before`, `limit`, `offset`, `order`, and `min_amount` to page and filter the feed. # Builder Trades Source: https://docs.polynode.dev/data/query-catalog/trades/by-builder Get trades attributed to a builder code. Canonical reference: [Builder Trades](/data/builders/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/builders/0x4898df15ec6590495dc6c0fedf951ade3e64001d47f9caf44a64e86fc11959df/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Builder trades can be narrowed by `market_slug`, `condition_id`, `token_id`, `side`, `min_amount`, `tag_slug`, and `category`. # Trades by Market Slug Source: https://docs.polynode.dev/data/query-catalog/trades/by-market-slug Get trades for all outcome tokens in one market slug. Canonical reference: [Market by Slug](/data/markets/by-slug) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/dota2-tundra-xtreme-2026-05-22-game1/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when your application works from Polymarket URLs or slugs instead of token IDs. # Trades by Market Token Source: https://docs.polynode.dev/data/query-catalog/trades/by-market-token Get trades for one outcome token. Canonical reference: [Market Trades](/data/markets/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/markets/21578184864194020862792310253337084708609281967112790860038966988826118995357/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this when you already know the ERC-1155 outcome token ID. # Trades by Order Hash Source: https://docs.polynode.dev/data/query-catalog/trades/by-order-hash Return every fill for an exact Polymarket order, globally or inside a wallet or market scope. Canonical references: [Global Trades](/data/global/trades), [Wallet Trades](/data/wallets/trades), and [Market Trades](/data/markets/trades) An order can fill more than once. `order_hash` returns the raw fill rows for the exact order by default, so paginate the result just like any other trade feed. The value must be `0x` followed by 64 hexadecimal characters. Hex character case is accepted and normalized to lowercase. ## Global order fills ```bash theme={null} curl "https://api.polynode.dev/v3/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c&limit=100" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## One wallet's fills for the order ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c&limit=100" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The wallet predicate and order hash are both applied before pagination. The response includes fills where that wallet was maker or taker, with `role` and wallet-perspective `direction` preserved. ## Compose wallet filters Every additional parameter is an intersection. This example returns only maker fills for the order, in one market, after a timestamp, worth at least \$100: ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c&side=maker&market_slug=nba-det-cle-2026-05-15&after=1778000000&min_amount_usd=100&order=asc" \ -H "x-api-key: $POLYNODE_API_KEY" ``` You can also combine `order_hash` with `token_id`, `condition_id`, `event_slug`, `event_id`, `before`, `min_amount`, `sort_by=order_hash`, or `group_by=order_hash`. ## Scope by token or market slug ```bash theme={null} curl "https://api.polynode.dev/v3/markets/31336121594291014914271611062289284423554618020629759821503694496084098706290/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/markets/slug/nba-det-cle-2026-05-15/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ## Empty and invalid results * A well-formed order hash with no matching fills returns `200`, `trades: []`, and `has_more: false`. * An empty, short, or non-hex hash returns `400`. * `order_hash` with `include_combos=true` returns `400` because combo trades do not expose a Polymarket order hash. # Trades by Wallet Source: https://docs.polynode.dev/data/query-catalog/trades/by-wallet Get trades where a wallet participated as maker or taker. Canonical reference: [Wallet Trades](/data/wallets/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Useful filters include `order_hash`, `after`, `before`, `side`, `condition_id`, `token_id`, `market_slug`, and `group_by=order_hash`. Filters compose with AND semantics. `include_combos=true` is available only when `order_hash` is absent. # Combo Wallet Trades Source: https://docs.polynode.dev/data/query-catalog/trades/combo-wallet-trades Get combo-only wallet trades or include combo trades in the standard wallet trade view. Canonical references: [Wallet Combo Trades](/data/combos/wallet-trades), [Wallet Trades](/data/wallets/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/combos/trades?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/trades?include_combos=true&limit=10" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Trades by Condition Source: https://docs.polynode.dev/data/query-catalog/trades/wallet-by-condition Filter one wallet's trades to a specific market condition. Canonical reference: [Wallet Trades](/data/wallets/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/trades?condition_id=0x97269cbb95bd572b3dde34cdd619be278c8f13ba5e43e2e6c2d8639411128a86&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use `condition_id` when you want both outcomes for one market. Use `token_id` when you want one specific outcome. # Wallet Trades Grouped by Order Source: https://docs.polynode.dev/data/query-catalog/trades/wallet-grouped-by-order Group wallet fills by order hash. Canonical reference: [Wallet Trades](/data/wallets/trades) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/trades?group_by=order_hash&limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Use this for order-level analytics where multiple fills share the same order hash. # Wallet Activity Query Catalog Source: https://docs.polynode.dev/data/query-catalog/wallet-activity Wallet activity recipes for lifecycle events, PolyUSD flows, fees, rebates, and rewards. Use these recipes when building wallet timelines, cash movement views, settlement history, or fee accounting pages. > [card] [Unified Wallet Activity](/data/query-catalog/wallets/unified-activity) > > Splits, merges, redemptions, and neg-risk conversions in one feed. > [card] [Wallet Splits](/data/query-catalog/wallets/splits) > > USDC converted into outcome tokens. > [card] [Wallet Merges](/data/query-catalog/wallets/merges) > > Outcome tokens converted back into USDC. > [card] [Wallet Redemptions](/data/query-catalog/wallets/redemptions) > > Claimed payouts from resolved markets. > [card] [Neg-Risk Conversions](/data/query-catalog/wallets/neg-risk-conversions) > > Neg-risk conversion events for a wallet. > [card] [PolyUSD Flows](/data/query-catalog/wallets/polyusd-flows) > > PolyUSD deposits and withdrawals. > [card] [Wallet Fees Paid](/data/query-catalog/wallets/fees-paid) > > Fee-bearing fills for one wallet. > [card] [Wallet Rebates and Rewards](/data/query-catalog/wallets/rebates-rewards) > > Polymarket-reported maker rebates and reward surfaces. # Wallet Fees Paid Source: https://docs.polynode.dev/data/query-catalog/wallets/fees-paid Get fee-bearing fills for one wallet. Canonical reference: [Wallet Fees Paid](/data/wallets/fees-paid) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63ce342161250d705dc0b16df89036c8e5f9ba9a/fees-paid?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` This is trader-paid fill fee data. It is separate from maker rebates and reward configuration. # Wallet Merges Source: https://docs.polynode.dev/data/query-catalog/wallets/merges Get merge events where outcome tokens were converted back into USDC. Canonical reference: [Wallet Merges](/data/wallets/merges) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x01a23b7408650ba910b11740a814071e57fbfbe3/merges?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Neg-Risk Conversions Source: https://docs.polynode.dev/data/query-catalog/wallets/neg-risk-conversions Get neg-risk conversion activity for one wallet. Canonical reference: [Wallet NRC](/data/wallets/nrc) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x4ce73141dbfce41e65db3723e31059a730f0abad/nrc?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # PolyUSD Flows Source: https://docs.polynode.dev/data/query-catalog/wallets/polyusd-flows Get PolyUSD deposits and withdrawals for one wallet. Canonical reference: [Wallet PolyUSD Flows](/data/wallets/polyusd-flows) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x2a1f579283C87c4574102bbF6E4B39F7A12fe77E/polyusd-flows?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Wallet Rebates and Rewards Source: https://docs.polynode.dev/data/query-catalog/wallets/rebates-rewards Query maker rebates and wallet reward surfaces. Canonical references: [Wallet Maker Rebates](/data/wallets/rebates), [Reward Markets](/data/rewards/markets) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x8ecb4b228e07b6ddc58a32997093032a6907b8f6/rebates" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```bash theme={null} curl "https://api.polynode.dev/v3/rewards/markets" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Reward-market list rows include nullable title, slug, image, event, category, and tag context. Rebates, rewards, and fill fees are distinct accounting surfaces. # Wallet Redemptions Source: https://docs.polynode.dev/data/query-catalog/wallets/redemptions Get direct and AutoRedeemer-attributed wallet payout redemptions with exact transaction hashes. Canonical reference: [Wallet Redemptions](/data/wallets/redemptions) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/redemptions?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` The all-time result merges direct, negative-risk, and AutoRedeemer execution paths before pagination. Each row includes `transaction_hash`, `block_number`, `log_index`, `redemption_source`, and `source_event`. # Wallet Splits Source: https://docs.polynode.dev/data/query-catalog/wallets/splits Get split events where USDC was converted into outcome tokens. Canonical reference: [Wallet Splits](/data/wallets/splits) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x0f35109cc3ceaf729609c3109310791bd616c84a/splits?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Unified Wallet Activity Source: https://docs.polynode.dev/data/query-catalog/wallets/unified-activity Get non-trade wallet activity in one feed. Canonical reference: [Wallet Activity](/data/wallets/activity) ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/activity?limit=1" \ -H "x-api-key: $POLYNODE_API_KEY" ``` This feed includes split, merge, redemption, and neg-risk conversion activity. # Reward Market Detail Source: https://docs.polynode.dev/data/rewards/market GET /v3/rewards/markets/{condition_id} Get public Polymarket reward configuration for one condition ID. Returns Polymarket's public reward-market configuration for a single condition ID. This describes market reward settings; it is not per-wallet earned LP rewards. ## Request ``` GET /v3/rewards/markets/{condition_id} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `condition_id` | string | `0x` + 64 hex condition ID | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sponsored` | boolean | `false` | Filter to sponsored reward markets | | `next_cursor` | string | -- | Pagination cursor | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/rewards/markets/0x0000c7fe300953933808d82cd4aa35dbc9f291f0b78ca9da43b0604883906c6c" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "reward_semantics": "public Polymarket reward market configuration; this is not per-wallet earned LP rewards", "data": { "count": 1, "limit": 100, "data": [ { "condition_id": "0x0000c7fe300953933808d82cd4aa35dbc9f291f0b78ca9da43b0604883906c6c", "event_slug": "ia-02-house-margin-of-victory-2026", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-the-republican-party-win-the-popular-vote-in-the-2026-us-house-of-representatives-midterm-elections-by-6-or-more-KZdstWMJdb8e.png", "market_competitiveness": 0, "market_slug": "will-the-republican-party-candidate-win-the-2026-ia-02-house-election-by-6-9", "question": "Will the Republican Party candidate win the 2026 IA-02 House election by 6%-9%?", "rewards_config": [ { "asset_address": "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174", "end_date": "2500-12-31", "id": 1490227, "rate_per_day": 5, "start_date": "2026-08-27", "total_days": 173252, "total_rewards": 0 } ], "rewards_max_spread": 5.5, "rewards_min_size": 20, "tokens": [ { "outcome": "Yes", "price": 0.29, "token_id": "24473378447612899353575382165317011629536764151843413452585009431556652189881" }, { "outcome": "No", "price": 0.71, "token_id": "54647080501201331455477326147811376064824100171608827092711080601004925467479" } ] } ], "next_cursor": "LTE=" } } ``` ## Response fields | Field | Type | Description | | - | - | - | | `reward_semantics` | string | Meaning note | | `data` | object | Reward-market configuration response | Each detail row includes the condition, event and market slugs, question, image, competitiveness, reward settings, and outcome token prices. The seven nullable market-context fields on the [reward-market list](/data/rewards/markets) are a list-route enrichment. This detail route returns the reward configuration without that additional market context. ## Errors | HTTP | When | | - | - | | `400` | Invalid condition ID format | | `401` | Missing or invalid polynode API key | | `502` | Temporary rewards data provider failure | # Reward Markets Source: https://docs.polynode.dev/data/rewards/markets GET /v3/rewards/markets List public Polymarket reward market configurations. Returns Polymarket's public reward-market configuration feed with nullable market and event context. This describes markets with active reward programs; it is not per-wallet earned LP rewards. ## Request ``` GET /v3/rewards/markets ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `sponsored` | boolean | `false` | Filter to sponsored reward markets | | `next_cursor` | string | -- | Pagination cursor | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/rewards/markets" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "reward_semantics": "public Polymarket reward market configuration; this is not per-wallet earned LP rewards", "data": { "count": 1, "limit": 500, "data": [ { "condition_id": "0x0001cb8c0b39aeb614ab9a43867595317f06ede9c011661513065c638fbbefda", "title": "Will the example market resolve Yes?", "slug": "will-the-example-market-resolve-yes", "image": "https://example.com/market.png", "event_slug": "example-event", "event_title": "Example event", "category": "examples", "tag_slugs": ["example"], "native_daily_rate": 1, "rewards_config": [ { "asset_address": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", "end_date": "2500-12-31", "id": 0, "rate_per_day": 1, "start_date": "2026-02-17", "total_rewards": 0 } ], "rewards_max_spread": 4.5, "rewards_min_size": 50, "total_daily_rate": 1 } ], "next_cursor": null } } ``` ## Response fields | Field | Type | Description | | - | - | - | | `reward_semantics` | string | Meaning note | | `data` | object | Reward-market configuration response | `data.count` is the number of rows in this page, `data.limit` is the page size, and `data.next_cursor` continues pagination when it is not `null`. ### Market context fields Every row in `data.data` includes these additive fields: | Field | Type | Description | | - | - | - | | `title` | string or null | Market title, or `null` when unavailable. | | `slug` | string or null | Market slug, or `null`. | | `image` | string or null | Market image URL, or `null`. | | `event_slug` | string or null | Parent event slug, or `null`. | | `event_title` | string or null | Parent event title, or `null`. | | `category` | string or null | Market category, or `null`. | | `tag_slugs` | array\ or null | Market tags, or `null` when unavailable. | These fields are nullable. Reward configuration fields such as `native_daily_rate`, `total_daily_rate`, `rewards_max_spread`, `rewards_min_size`, and `rewards_config` remain unchanged. ## Errors | HTTP | When | | - | - | | `401` | Missing or invalid polynode API key | | `502` | Temporary rewards data provider failure | | `503` | Reward-market metadata is temporarily unavailable | # Token Info Source: https://docs.polynode.dev/data/tokens/info GET /v3/tokens/{token_id} Get full details for an outcome token: price, resolution status, market metadata, and tags. Returns price, resolution status, and market context for a specific outcome token. ## Request ``` GET /v3/tokens/{token_id} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `token_id` | string | Outcome token ID | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/tokens/75783394880030392863380883800697645018418815910449662777195626260206142035810 ``` ```json theme={null} { "data": [ { "category": null, "condition_id": "0xaa08b43f2e39a28c52278738d456dfce516fcd966d43f157aab3727457cd4b6c", "outcome": "Down", "outcome_index": 1, "price": 1.0, "question": "Bitcoin Up or Down - March 29, 1:10AM-1:15AM ET", "resolved": true, "slug": "btc-updown-5m-1774761000", "source": "v1_condition", "tag_slugs": [ "Crypto", "Bitcoin", "Crypto Prices", "Recurring", "Up or Down", "Hide From New", "5M" ], "token_id": "40671034664065625078050343379339320067070367341089437265715901074008336896448", "updated_at": "2026-05-16 11:42:10.666489" } ], "elapsed_ms": 3, "has_more": false, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response columns | Column | Type | Description | | - | - | - | | `token_id` | string | Outcome token ID | | `price` | number | Current price in USD (`0`–`1` for unresolved, exactly `0` or `1` for resolved) | | `resolved` | boolean | Whether the market has settled | | `source` | string | Price source: `settlement`, `clob_mid`, `v1_condition`, `last_fill` | | `updated_at` | string | When the price was last updated | | `condition_id` | string | Market condition ID | | `outcome` | string | Outcome label (e.g. "Aurora", "Yes") | | `outcome_index` | integer | Outcome position (0 or 1) | | `question` | string | Market question | | `slug` | string | Market URL slug | | `category` | string | Market category | | `tag_slugs` | array | Category tags | # Wallet Activity Source: https://docs.polynode.dev/data/wallets/activity GET /v3/wallets/{address}/activity Get all non-trade activity for a wallet: splits, merges, neg-risk conversions, and redemptions. Returns a unified feed of all non-trade events for a wallet, sorted by timestamp. Includes splits, merges, neg-risk conversions, and redemptions. > [!NOTE] > > This endpoint is the conditional-token activity feed for splits, merges, neg-risk conversions, and redemptions. PolyUSD deposits and withdrawals are available separately through [Wallet PolyUSD Flows](/data/wallets/polyusd-flows). > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/activity ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/activity?limit=1 ``` ```json theme={null} { "data": [ { "amount": "706561610", "event_type": "redemption", "extra": "{1,2}", "id": "0x7a7494699af0d7bf9734db8c803fc9ecad0330df97ebc7893bb05a81bc3c93bf_0x353", "ref_id": "0xfbf0af69aa98b4662b95ff5ffb6dde560ec2e3da723a1980a6ef3f919cbeddea", "timestamp": "1777356700" } ], "elapsed_ms": 8, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `event_type` | string | `split`, `merge`, `nrc` (neg-risk conversion), or `redemption` | | `id` | string | Event ID | | `timestamp` | string | Unix timestamp | | `ref_id` | string | Condition ID or neg-risk market ID | | `amount` | string | Amount (6-decimal USDC) | | `extra` | string | Additional data (index\_sets for redemptions, question\_count for NRC) | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `data[].wallet` | string | The wallet this row belongs to | # Batch Wallet P&L Source: https://docs.polynode.dev/data/wallets/batch POST /v3/wallets/batch Query P&L for up to 100 wallets in a single request. All amounts in USD. Query multiple wallets at once. Returns the same summary data as the single wallet endpoint, but for up to 100 wallets in one call. All monetary values are in USD. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` POST /v3/wallets/batch ``` ### Request body ```json theme={null} { "wallets": [ "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "0xa9857c7bcb9bcfafd2c132ab053f34f678610058" ] } ``` | Field | Type | Description | | - | - | - | | `wallets` | array | Up to 100 wallet addresses or owner EOAs | ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/wallets/batch \ -H 'Content-Type: application/json' \ -d '{"wallets":["0x56687bf447db6ffa42ffe2204a05edaa20f55839"]}' ``` ```json theme={null} { "count": 1, "elapsed_ms": 1, "wallets": [ { "wallet": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "net_realized_pnl": 22053845.825455, "gross_profit": 22057977.181649, "gross_loss": -4131.356194, "unrealized_pnl": 0.000688755, "total_pnl": 22053845.826143753, "wins": 18, "losses": 4, "position_count": 22, "open_positions": 1, "total_volume": 43013258.515682 } ] } ``` ## Response fields Same fields as [Wallet Summary](/data/wallets/summary), with `wallet` instead of `address`. All amounts in USD. ### Owner address fields Each owner EOA in the request is combined on its own. The response keeps one element per requested address, in request order, and each element's `wallet` stays the address you passed. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets[].wallets` | array | Present only on elements for an owner EOA. The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Totals and counts in a combined element are summed across its wallets. # Copy PnL Source: https://docs.polynode.dev/data/wallets/copy-pnl GET /v3/wallets/{address}/copy-pnl Estimate copying slippage with date filters, optional full history, and lifetime realized-PnL context. Calculate a wallet's gross trading cash flow and the cash flow of a simulated copier using Polynode's indexed fills and settlement events. This replaces the deprecated [V2 on-demand endpoint](/api-reference/backtesting/copy-pnl). ## Request ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/wallets/0xab03f377164c3726d498e56f7a9398cd8eb74494/copy-pnl" ``` | Parameter | Location | Default | Description | | - | - | - | - | | `address` | Path | Required | `0x` followed by 40 hexadecimal characters. Normalized to lowercase. | | `max_trades` | Query | `50000` | Integer from `1` to `50000`. Maximum number of recent wallet-owned order fills to include. | | `history` | Query | `recent` | `recent`, `auto`, or `full`. In `auto`, `max_trades` is the fallback cap; in `full`, it is the initial scan size, not a limit on the returned fill count. | | `period` | Query | None | `7d`, `14d`, `30d`, `60d`, `90d`, or `180d`, ending at `to` or the calculation snapshot. | | `from` | Query | None | Inclusive start, as Unix seconds or `YYYY-MM-DD` at UTC midnight. Overrides `period`. | | `to` | Query | Snapshot | Exclusive end, in the same formats. `from` must be earlier than `to`. | The cap counts **fills**, not positions, tokens, transactions, or distinct orders. The calculation selects the wallet's own signed-order fill records, including its taker-order execution record. It avoids counting that wallet again as the counterparty to other matched orders. This attribution is different from requesting both address roles on the raw trades endpoint. There is no default date window. With `history=recent`, active wallets can reach 50,000 fills quickly; quieter wallets can cover years. Date filters apply before the fill cap, including to settlement events. A wallet with fewer matching fills returns all matching indexed fills. `coverage.history_truncated` tells you whether older fills **inside the requested date window** were excluded by the fill selection. ## History modes * `recent`: return up to `max_trades` recent fills. This preserves the original V3 default. * `auto`: first complete the recent calculation, then spend up to two additional seconds extending toward all matching history, within the overall calculation deadline. Return full history if it completes; otherwise return the original completed recent calculation with an explicit fallback reason. * `full`: require all matching indexed history. If the work or time limit is reached, return an error instead of a recent-window fallback. Full-history work is bounded at 500,000 fills and 100,000 settlement events per wallet. Both `auto` and `full` can return more than 50,000 fills. `max_trades` remains limited to 50,000 and controls the initial recent calculation. A successful `full` result contains all matching history, never the first 500,000 fills of a larger history. For example, request a complete historical month with `?history=full&from=2026-08-01&to=2026-09-01`, or use `?history=auto&period=90d` to allow an explicit recent-window fallback. Read `coverage.requested_history`, `served_history` (`full` or `recent`), and `fallback_reason` on every result. `served_history=full` means the requested date window is complete; `lifetime_history_included` is true only when no date filters or fill truncation restrict the indexed history. Automatic fallback reasons are `query_timeout`, `query_work_limit`, `activity_limit_exceeded`, or `history_limit_exceeded`. If the initial recent calculation fails, there is no valid fallback and the request returns an error. ## Calculation * Buy: the copier pays `min(price × 1.02, 1.00) × shares`. * Sell: the copier receives `price × 0.98 × shares`. * Splits consume collateral; merges and redemptions release collateral. Neg-risk conversions include released collateral according to their selected outcomes. These settlement flows receive no simulated slippage. ```text theme={null} actual_pnl_usdc = sells - buys + settlement_in - settlement_out backtest_copy_pnl_usdc = actual_pnl_usdc - slippage_amount_usdc slippage_cost_rate_pct = slippage_amount_usdc / abs(actual_pnl_usdc) × 100 toxic_for_copying = slippage_cost_rate_pct > 15 ``` The 2% assumption is relative to each execution price. It is a fixed screening model, not a measured execution cost or a forecast. When the absolute gross cash flow is below 1 USDC, both the percentage and `toxic_for_copying` are `null`. > [!WARNING] > > `pnl_definition` is `cashflow`. Fees are excluded, opening inventory is not valued, and open positions are not marked to market. Sales or redemptions of inventory acquired before the selected window can therefore make this differ substantially from realized or total portfolio PnL. Deposits, withdrawals, and token transfers are outside this calculation. It covers spot order fills, not combo or perpetual trading. If older matching fills are excluded, settlement inclusion begins at the exact block and log of the first included fill, inclusive. Otherwise, all indexed settlement history within the requested dates is eligible, including events before the first fill. A wallet with settlement activity and no fills can still return a cash-flow result. Explicit timestamps are checked exactly; the database snapshot bounds which events are visible. ## Realized-PnL context `realized_pnl_context` provides the wallet's stored lifetime realized profit and position counts alongside the cash-flow simulation. Its `total_realized_pnl_usdc` is actual realized profit from the wallet summary; it is not the copier's simulated realized profit and is not used in the slippage or copying flag formulas. This context always has `scope: "lifetime_wallet"` and `date_filters_applied: false`. It is **not rewound by `from` or `to`** and is not a realized-profit result for a historical backtest window. Read `updated_at`, `updated_block`, and `refresh_age_seconds` to see the summary's last update. `latest_indexed_fill_block` supports the `freshness` indicator: `behind_indexed_fills`, `no_newer_indexed_fills`, `unknown`, or `unavailable`. No newer fills does not prove all settlement or valuation inputs are current. If no summary is available, `available` is false and its profit/count/update fields are null, rather than zero. `position_count` and `open_positions` describe the stored lifetime summary. They do not reproduce V2's count of positions with nonzero realized PnL. ## Response The following is an illustrative two-fill calculation: a buy costing 5 USDC followed by a sale returning 8 USDC, with no settlement flows. ```json theme={null} { "data": { "wallet": "0x1111111111111111111111111111111111111111", "actual_pnl_usdc": "3.000000", "backtest_copy_pnl_usdc": "2.740000", "slippage_amount_usdc": "0.260000", "slippage_cost_rate_pct": "8.666667", "toxic_for_copying": false, "trade_count": 2, "pnl_definition": "cashflow", "fees_included": false, "opening_inventory_valued": false, "open_positions_marked_to_market": false, "slippage_bps": {"buy": 200, "sell": 200, "buy_price_capped_at": "1.000000"}, "cashflows": { "buy_cost_usdc": "5.000000", "sell_revenue_usdc": "8.000000", "settlement_in_usdc": "0.000000", "settlement_out_usdc": "0.000000" }, "event_counts": {"buys": 1, "sells": 1, "splits": 0, "merges": 0, "redemptions": 0, "neg_risk_conversions": 0}, "coverage": { "selection": "latest_wallet_order_fills", "max_trades": 50000, "history_truncated": false, "requested_history": "recent", "served_history": "full", "fallback_reason": null, "lifetime_history_included": true, "window_start": {"type": "beginning_of_indexed_history"}, "window_end": {"type": "database_snapshot", "snapshot_at": "2026-09-07T01:00:00.000Z"}, "first_included_event_timestamp": 1788652800, "last_included_event_timestamp": 1788739200, "snapshot_at": "2026-09-07T01:00:00.000Z" }, "applied_filters": {"period": null, "from": null, "to": 1788742800}, "realized_pnl_context": { "available": true, "scope": "lifetime_wallet", "date_filters_applied": false, "source": "api.wallet_pnl_current", "pnl_definition": "realized", "total_realized_pnl_usdc": "3.000000", "position_count": 1, "open_positions": 0, "updated_block": "93350000", "updated_at": "2026-09-07T00:59:00Z", "refresh_age_seconds": 60, "latest_indexed_fill_block": "93350000", "freshness": "no_newer_indexed_fills" }, "query_ms": 800 }, "cache": {"status": "miss", "age_ms": 800}, "elapsed_ms": 805 } ``` Money and percentages are decimal strings with six fractional digits. Event timestamps are Unix seconds. `snapshot_at` is a UTC timestamp. For a truncated history, `window_start` contains `type: "inclusive_trade_cursor"`, `block_number` and `log_index` as strings, and `timestamp` in Unix seconds. A complete window with a start date uses `type: "inclusive_timestamp"` and `timestamp`. `window_end` is either an `exclusive_timestamp` or a `database_snapshot`. `applied_filters` reports the resolved date bounds; without explicit dates, its `to` records the snapshot time in whole seconds. An empty wallet has zero cash-flow amounts and `null` first/last event timestamps. Results may be cached for 30 seconds after calculation, separately for each wallet and set of options. `cache.status` is `miss`, `hit`, or `coalesced` (shared in-progress work). `cache.age_ms` measures time since the calculation's snapshot; `data.query_ms` describes that calculation, including any attempted history expansion, while `elapsed_ms` describes the current request. Each wallet has its own snapshot, including in a batch. Relative periods are anchored to that calculation; supply explicit `from` and `to` to fix the same date window across wallets. ## Access and errors Available on paid V3 plans under the account's normal [REST limits](/guides/rate-limits) and monthly usage policy. The V2-specific one-request-per-five-seconds limit does **not** apply. Each HTTP request counts as one API request, including a batch. Cache hits still count as requests. Database capacity is bounded; account request limits are not a guarantee of uncached calculation throughput. | HTTP status | Error code | Meaning | | - | - | - | | `400` | `invalid_wallet`, `invalid_max_trades`, `invalid_history`, `invalid_period`, `invalid_timestamp`, `invalid_window`, `duplicate_parameter`, `unknown_parameter` | Invalid input. Trade-detail flags remain unsupported. | | `422` | `activity_limit_exceeded` | More than 100,000 settlement events fall in the selected window. No partial financial total is returned. | | `422` | `unsupported_accounting_data`, `query_work_limit` | Unsupported accounting inputs or calculation work limit reached. No partial total is returned. | | `422` | `history_limit_exceeded` | More than 500,000 fills are required for full history. No partial total is returned. | | `503` | `server_busy`, `database_unavailable` | Capacity or data access is temporarily unavailable. | | `504` | `query_timeout` | The calculation or queue deadline was exceeded. | Authentication, plan access, monthly usage, and account rate-limit failures use the normal V3 edge responses. Do not treat an error as zero PnL. ## Migrating from V2 Use `GET /v3/wallets/{address}/copy-pnl` or [V3 Copy PnL Batch](/data/wallets/copy-pnl-batch). Read the summary from `data`; batch input uses `wallets` instead of `addresses`. `period`, `from`, and `to` are supported. V2 defaulted to 30 days; send `period=30d` explicitly to request that window in V3. Use `history=full` when the whole requested window is required, or `auto` when an explicit recent-window fallback is acceptable. Read actual lifetime realized PnL from `realized_pnl_context.total_realized_pnl_usdc`, with the scope and freshness limitations above. This does not restore V2's window-specific weighted-average position metrics. `include_trades`, individual trade arrays, weighted entry/holding metrics, and V2's BYOB tracked-wallet pool, snapshot, and leaderboard remain outside these endpoints. # Copy PnL Batch Source: https://docs.polynode.dev/data/wallets/copy-pnl-batch POST /v3/copy-pnl/batch Calculate copying-slippage cash flow for up to 100 wallets in one request. Uses the same [Copy PnL calculation, coverage, and response fields](/data/wallets/copy-pnl) for each wallet. This replaces the deprecated [V2 on-demand batch](/api-reference/backtesting/batch). ## Request ```bash theme={null} curl -X POST "https://api.polynode.dev/v3/copy-pnl/batch" \ -H "x-api-key: pn_live_YOUR_KEY" \ -H "Content-Type: application/json" \ --data '{"wallets":["0xab03f377164c3726d498e56f7a9398cd8eb74494","0x3708cef9f92678df15a0473e36c45d68a16cdaf9"],"max_trades":50000}' ``` | Body field | Required | Description | | - | - | - | | `wallets` | Yes | Array of 1–100 wallet addresses. | | `max_trades` | No | Integer from 1 to 50,000, applied **per wallet**. Default 50,000. Recent/fallback cap; initial scan size in full mode. | | `history` | No | `recent` (default), `auto`, or `full`, applied independently to each wallet. | | `period` | No | `7d`, `14d`, `30d`, `60d`, `90d`, or `180d`. No default date window. | | `from`, `to` | No | Inclusive start and exclusive end. Unix seconds or UTC `YYYY-MM-DD` dates. `from` overrides `period`. | Send parameters in a JSON object, with a body no larger than 16 KiB. Unknown fields, invalid options, and invalid batch sizes return `400`. An invalid wallet within an otherwise valid batch produces an error for that row. Results preserve input order and duplicate entries. Duplicate normalized wallets with the same options share calculation work. Wallets use different snapshots; relative periods are anchored to each calculation, so use explicit `from` and `to` to fix the same dates across the batch. The whole HTTP batch counts as one API request under normal V3 account limits; the old V2 five-second throttle does not apply. Every successful row includes separately scoped lifetime `realized_pnl_context`. Date filters apply to the copying simulation, not to that stored lifetime context. In `auto`, some wallets may return full history and others the completed recent-window fallback. Inspect `data.coverage.served_history`, `history_truncated`, and `fallback_reason` for every row. In `full`, incomplete histories become individual errors. See [history modes and work limits](/data/wallets/copy-pnl#history-modes). ## Response and partial failures The envelope contains `results`, `requested`, `succeeded`, `failed`, `max_trades`, and `elapsed_ms`. | Result field | Successful row | Failed row | | - | - | - | | `wallet` | Normalized wallet address | Original input | | `status` | `ok` | `error` | | `data` | Full single-wallet summary | Absent | | `cache` | `status` and `age_ms` | Absent | | `error` | Absent | Object with `code` and `message` | | `status_code` | Absent | Per-wallet HTTP-equivalent status, such as `400`, `422`, `503`, or `504` | A valid batch returns HTTP `200` even if some or all wallets fail. Always inspect `status` on every result. For example, an invalid wallet row is: ```json theme={null} { "wallet": "invalid-address", "status": "error", "error": { "code": "invalid_wallet", "message": "Wallet must be a 0x-prefixed, 40-digit hexadecimal address." }, "status_code": 400 } ``` Work is scheduled with bounded concurrency. Each calculation has a ten-second database budget, and the batch has a 25-second queue/result deadline inside the public request timeout. A maximum-size batch is accepted, but 100 uncached heavy wallets are not guaranteed to finish in that deadline. Start with batches of 5–10 for interactive use. Keep successful results and retry only transient failures in smaller batches; changing `max_trades` changes the analysis window. Automatic expansion has up to two additional seconds per wallet within the existing ten-second calculation budget. It never silently lowers the requested fallback cap or returns a partly calculated financial total. The endpoint does not create a background job or update V2 BYOB wallets. # Wallet Fees Paid Source: https://docs.polynode.dev/data/wallets/fees-paid GET /v3/wallets/{address}/fees-paid Get fee-bearing order fills for a wallet. Returns fills where the wallet was the order owner and `OrderFilled.fee` was greater than zero. Each row is enriched with the same market context used by wallet trade history. This is fees paid by the trader on executed order fills. It is not the same as maker rebates, LP rewards, or builder payouts. > [!NOTE] > > `page_total_fees_paid` is the sum for the returned page only. For the exact all-time fee total, use `GET /v3/wallets/{address}?include_accounting_summary=true` and read `accounting_summary.fees_paid.amount`. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/fees-paid ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | `0` | Start of time range (Unix seconds, inclusive) | | `before` | integer | `9999999999` | End of time range (Unix seconds, inclusive) | | `order` | string | `desc` | `asc` or `desc` | | `limit` | integer | `100` | Max 300 | | `offset` | integer | `0` | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/fees-paid?limit=1&after=1779700000" ``` ```json theme={null} { "address": "0xbddf61af533ff524d27154e589d2d7a81510c684", "fees": [ { "id": "0x4f8447fda6ed5b200d876ffc677fedd853d524c9a2751d055d7578c1575124dc_847", "maker": "0xbddf61af533ff524d27154e589d2d7a81510c684", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "fee": 352.774, "fee_paid": 352.774, "fee_paid_raw": "352774000", "price": 0.45, "size": 47511.65, "direction": "BUY", "market": "Spread: Thunder (-2.5)", "slug": "nba-sas-okc-2026-05-26-spread-home-2pt5", "condition_id": "0x7bcc428d368834c6dfbb4925f699079f65925fef69ad259274b88c5671aaa29e", "timestamp": "1779839786", "source": "wallet_fees_paid" } ], "rows_returned": 1, "has_more": true, "page_total_fees_paid": 352.774, "fee_semantics": "Trader-paid fees on executed order fills where this wallet was the order owner. Includes supported Polymarket exchange versions.", "elapsed_ms": 14 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `address` | string | Wallet address, lowercased | | `fees` | array | Fee-bearing fill rows | | `fees[].fee` | number | Fee in USD | | `fees[].fee_paid` | number | Same value as `fee`, included for category-breakdown clarity | | `fees[].fee_paid_raw` | string | Raw 6-decimal fee amount | | `fees[].source` | string | Dataset label | | `rows_returned` | integer | Number of rows returned | | `has_more` | boolean | Whether another page exists | | `offset` | integer | Offset used for this page | | `limit` | integer | Limit used for this page | | `page_total_fees_paid` | number | Sum of `fee_paid` for this page only. Use wallet summary `include_accounting_summary=true` for the all-time total. | | `page_total_fees_paid_raw_note` | string | Reminder that the total is page-scoped | | `fee_semantics` | string | Attribution note | | `after` | string | Applied start timestamp | | `before` | string | Applied end timestamp | | `elapsed_ms` | integer | Server-side query time in milliseconds | The fill objects also include standard trade fields such as `maker_asset_id`, `taker_asset_id`, `maker_amount`, `taker_amount`, `token_id`, `asset`, `amount`, `amount_usd`, `transaction_hash`, `order_hash`, `builder`, `side`, `role`, `outcome`, `outcome_index`, and `image` when available. ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `fees[].wallet` | string | The wallet this row belongs to | `page_total_fees_paid` covers the combined page. ## Errors | HTTP | When | | - | - | | `400` | Invalid wallet address | | `400` | Invalid `order` value | | `401` | Missing or invalid PolyNode API key | # Wallet Merges Source: https://docs.polynode.dev/data/wallets/merges GET /v3/wallets/{address}/merges Get all merge events for a wallet. Merges occur when outcome tokens are converted back into USDC. Returns merge events where outcome tokens were converted back into USDC for a market condition. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/merges ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xada100874d00e3331d00f2007a9c336a65009718/merges?limit=1 ``` ```json theme={null} { "data": [ { "id": "0x56e84b69492dff41fae8aa932695eec8b90931aa286ce09d9565932d72e4a1f4_0x612", "timestamp": "1778482999", "condition": "0x649340b2a3e39f7d0de414d6891a14b6e1969293f8fec3ccb481572fd2375e34", "amount": "20000000" } ], "rows_returned": 1, "has_more": true, "elapsed_ms": 2 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `id` | string | Merge event ID | | `timestamp` | string | Unix timestamp | | `condition` | string | Market condition ID | | `amount` | string | USDC amount received (6-decimal) | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `data[].wallet` | string | The wallet this row belongs to | # Wallet NRC Source: https://docs.polynode.dev/data/wallets/nrc GET /v3/wallets/{address}/nrc Get neg-risk conversion events for a wallet. NRC events convert between multi-outcome market positions. Returns neg-risk conversion events for a wallet. These occur when positions in multi-outcome (neg-risk) markets are converted between outcome tokens. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/nrc ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x4ce73141dbfce41e65db3723e31059a730f0abad/nrc?limit=1 ``` ```json theme={null} { "data": [], "elapsed_ms": 2, "has_more": false, "limit": 1, "offset": 0, "rows_returned": 0 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `id` | string | NRC event ID | | `timestamp` | string | Unix timestamp | | `neg_risk_market_id` | string | Parent neg-risk market ID | | `amount` | string | Amount converted (6-decimal USDC) | | `index_set` | string | Bit-packed index indicating which outcomes were involved | | `question_count` | integer | Total number of outcomes in the neg-risk market | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `data[].wallet` | string | The wallet this row belongs to | # Wallet P&L Source: https://docs.polynode.dev/data/wallets/pnl GET /v3/wallets/{address}/pnl Get profit and loss for a wallet in USD. Supports time-windowed P&L with ?period=1d|7d|30d|1y plus tag, category, market, event, and condition filters. Returns P\&L data for a wallet in USD. Without a time parameter, it returns the wallet's current all-time P\&L. With `period`, `after`, or `before`, it returns this boundary calculation across all matching positions: ```text theme={null} time-window realized P&L = realized state at or before `before` - realized state immediately before `after` ``` Both boundaries are inclusive. A state change timestamped exactly at `after` or `before` is included. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Fees and accounting scope For **standard spot market positions**, realized and unrealized P\&L exclude separately reported trader-paid fees, rebates, and rewards. `net_realized_pnl` means the combined realized gains and losses, not an after-fee return. Use [Fees Paid](/data/wallets/fees-paid), [Rebates](/data/wallets/rebates), and the optional [Wallet Summary accounting fields](/data/wallets/summary) when you need those separate amounts. `include_combos=true` adds a component with different fee treatment: [Combo P\&L](/data/combos/leaderboard) includes each signed order's recorded exchange fill fee in its cost basis or sale proceeds. That does not make the standard spot component fee-inclusive. Perps has its own endpoint accounting model; do not infer its fee or funding treatment from either component. ## Time-window behavior The two modes have different counting semantics: all-time `wins` and `losses` are current position counts; time-windowed `wins`, `losses`, and the legacy `events` field count positions whose realized state changed. Time-windowed responses declare `count_type: "positions_changed"`. Do not compare the counts directly. > [!WARNING] > > Time-windowed P\&L is a **realized-state change**, not a historical snapshot of the all-time leaderboard. It captures realized changes reflected by sells, merges, redemptions, and timestamped corrections. A buy-and-hold position can therefore contribute `0` to a window even if terminal treatment makes the resolved position profitable in current all-time P\&L. For the same reason, an `after=1&before=now` result is not expected to equal the all-time response or leaderboard total. The boundary calculation uses Polynode's recovered Polymarket weighted-average-cost state. The difference is scope and timing, not a simpler cost-basis formula: all-time P\&L uses the current recovered portfolio state, including terminal treatment for resolved holdings and current unrealized P\&L, while a time window reports only the change in realized state across its boundaries. > [!NOTE] > > Wallet P\&L supports focused market filters such as `category`, `tags`/`tag_slug`, `market`/`market_slug`, `event_slug`, and `condition_id`. For leaderboard views, use one primary filter dimension per request. ## Request ``` GET /v3/wallets/{address}/pnl ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | -- | Time window: `1d`, `7d`, `30d`, `1y` | | `after` | integer | -- | Start timestamp (Unix seconds). Time-windowed queries clamp values below `1` to `1`. | | `before` | integer | -- | End timestamp (Unix seconds) | | `category` | string | -- | Filter to one market category, case-insensitive | | `tags` | string | -- | Comma-separated tag slugs to filter by, case-insensitive (e.g. `politics,crypto`, `nfl`, `Iran`) | | `tag_slug` | string | -- | Alias for a single `tags` value | | `market` | string | -- | Filter by condition ID or market slug | | `market_slug` | string | -- | Filter by market slug | | `event_slug` | string | -- | Filter by parent event slug | | `condition_id` | string | -- | Filter by market condition ID | | `include_unrealized` | string | `false` | Set to `true` to add current unrealized P\&L to the realized event-window result. This is the current value, not the change between the two requested boundaries. Only applies to time-filtered queries. | | `include_combos` | boolean | `false` | Add combo position P\&L to all-time wallet P\&L. If the wallet has no combo exposure, the response remains 200 with a zero combo contribution. | ## Examples ### All-time P\&L ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/pnl ``` ### All-time P\&L including combos ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/pnl?include_combos=true" ``` ```json theme={null} { "address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "net_realized_pnl": 113.510513, "realized_pnl": 113.510513, "gross_profit": 184.901354, "gross_loss": -71.390841, "unrealized_pnl": 0.0, "total_pnl": 113.510513, "position_count": 21496, "open_positions": 1495, "total_volume": 129.837476, "include_combos": true, "included_position_types": ["market", "combo"], "combo_pnl": { "position_type": "combo", "included": true, "realized_pnl": 113.510513, "unrealized_pnl": 0.0, "total_pnl": 113.510513, "position_count": 21492, "open_positions": 1495 } } ``` For time-windowed or tag-filtered P\&L, the response stays successful. If combo P\&L cannot be safely added to that filtered view, `combo_pnl.included` is `false` and the standard market P\&L fields remain unchanged. ```json theme={null} { "address": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "net_realized_pnl": 22053845.825455, "gross_profit": 22057977.181649, "gross_loss": -4131.356194, "unrealized_pnl": 0.000688755, "total_pnl": 22053845.826143753, "position_count": 22, "open_positions": 1, "total_volume": 43013258.515682, "wins": 18, "losses": 4, "elapsed_ms": 41 } ``` ### 30-day P\&L ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/pnl?period=30d ``` ```json theme={null} { "address": "0xbddf61af533ff524d27154e589d2d7a81510c684", "realized_pnl": 1815261.28, "gross_profit": 1918402.27, "gross_loss": -103140.98, "wins": 33039, "losses": 58867, "events": 91906, "count_type": "positions_changed", "source": "recovered_realized_boundaries", "period": "30d", "after": 1776134996, "before": 1778726996, "elapsed_ms": 5902 } ``` ### Filtered P\&L ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?category=crypto" curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?tag_slug=us-election&period=30d" curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?market_slug=will-donald-trump-win-the-popular-vote-in-the-2024-presidential-election" curl "https://api.polynode.dev/v3/wallets/0x952d11ebff81d6bd3185e608ed3515b94618ab8a/pnl?event_slug=presidential-election-popular-vote-winner-2024" ``` ### 30-day P\&L with unrealized Pass `include_unrealized=true` to add current unrealized P\&L to the realized-state change. This does not turn the response into a historical portfolio-value change between `after` and `before`. ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/pnl?period=30d&include_unrealized=true ``` ```json theme={null} { "address": "0xbddf61af533ff524d27154e589d2d7a81510c684", "realized_pnl": 1815261.28, "gross_profit": 1918402.27, "gross_loss": -103140.98, "unrealized_pnl": 14714.71, "total_pnl": 1829975.99, "open_positions_at_date": 363, "wins": 33039, "losses": 58867, "events": 91906, "count_type": "positions_changed", "source": "recovered_realized_boundaries", "period": "30d", "after": 1776135002, "before": 1778727002, "elapsed_ms": 3803 } ``` ## Response fields (all-time) | Field | Type | Description | | - | - | - | | `net_realized_pnl` | number | Net realized P\&L (USD) | | `gross_profit` | number | Sum of winning positions (USD) | | `gross_loss` | number | Sum of losing positions (USD, negative) | | `unrealized_pnl` | number | Paper P\&L from open positions (USD) | | `total_pnl` | number | `net_realized_pnl + unrealized_pnl` (USD) | | `wins` | integer | Winning position count | | `losses` | integer | Losing position count | | `position_count` | integer | Total positions | | `open_positions` | integer | Currently held positions | | `total_volume` | number | Total volume traded (USD) | | `include_combos` | boolean | Present when `include_combos=true` was requested | | `included_position_types` | array | Position families included in aggregate totals | | `combo_pnl` | object | Combo-only contribution to the aggregate response | ## Response fields (with period) | Field | Type | Description | | - | - | - | | `realized_pnl` | number | Weighted-average-cost realized state at `before` minus the state immediately before `after` (USD) | | `gross_profit` | number | Sum of positive changed-position deltas in the window (USD) | | `gross_loss` | number | Sum of negative changed-position deltas in the window (USD, negative) | | `wins` | integer | Positions with a positive realized-state delta | | `losses` | integer | Positions with a negative realized-state delta | | `events` | integer | Legacy field name; total positions with a nonzero realized-state delta | | `count_type` | string | `positions_changed` for time-windowed queries | | `period` | string | The requested period | | `after` | integer | Start timestamp (Unix seconds) | | `before` | integer | End timestamp (Unix seconds) | | `source` | string | Dataset label for time-windowed queries; currently `recovered_realized_boundaries` | ### Additional fields (with `include_unrealized=true`) | Field | Type | Description | | - | - | - | | `unrealized_pnl` | number | Current unrealized P\&L for open positions (USD), not the change in unrealized P\&L between the requested boundaries. | | `total_pnl` | number | `realized_pnl + unrealized_pnl` (USD) | | `open_positions_at_date` | integer | Current open position count returned with the unrealized P\&L estimate | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Totals and counts are summed across the combined wallets. With `period`, `after`, or `before`, every wallet uses the same window, and `address` stays the address you passed. With `include_combos=true`, `combo_pnl` is included only when it is available for every combined wallet; otherwise the response covers market positions only. A wallet whose P\&L is not loaded yet is left out of the combination and of `wallets`. ## Errors | HTTP | Error | When | | - | - | - | | `400` | Invalid request | The wallet address, period, filter, or boundary is invalid | | `503` | `time_filtered_pnl_unavailable` | The selected wallet and window exceed the serving deadline. Retry with a narrower window. The response includes `reason: "query_timeout"`. | # Wallet P&L Time Series Source: https://docs.polynode.dev/data/wallets/pnl-events GET /v3/wallets/{address}/pnl/events Realized P&L bucketed by hour, day, week, or month — chart-ready time series for a wallet. Returns wallet P\&L buckets for charting. With `period`, `after`, or `before`, each row is a fixed time window (hour, day, week, or month). A running `cumulative_pnl` is included so the response can be plotted directly. These standard spot P\&L buckets exclude separately reported trader-paid fees, rebates, and rewards. `cumulative_pnl` accumulates the returned P\&L; it is not an after-fee account return. See [Wallet P\&L accounting scope](/data/wallets/pnl) and [Fees Paid](/data/wallets/fees-paid) for the separate fee data. Event-series mode is separate from the boundary-state calculation used by time-filtered [`GET /v3/wallets/{address}/pnl`](/data/wallets/pnl). Each bucket sums recorded weighted-average-cost realized-P\&L event deltas. It is not a historical all-time-portfolio snapshot: holdings that are only bought and held can contribute `0`, even when a resolved holding contributes profit to the current all-time P\&L. Baseline corrections without an event timestamp are not placed into a bucket. Without an explicit time filter, the endpoint returns a single all-time summary bucket that matches [`GET /v3/wallets/{address}/pnl`](/data/wallets/pnl). In event-series mode, `wins`, `losses`, and `events` count realized P\&L events in the selected window. In default summary mode, counts are position counts and the response includes `count_type: "positions"` and `summary_bucket: true`. Rows at timestamp `0` or earlier are ignored in event-series mode, so explicit event windows start at Unix second `1`. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/pnl/events ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `group` | string | `day` | Bucket size: `hour`, `day`, `week`, `month` | | `period` | string | -- | Shortcut for `after`: `1d`, `7d`, `30d`, `1y` | | `after` | integer | `1` | Start timestamp (Unix seconds, inclusive). Values below `1` are treated as `1`. | | `before` | integer | now | End timestamp (Unix seconds, inclusive) | | `limit` | integer | `1000` | Max buckets returned, clamped to 1-1000 | If `after` and `period` are both set, `after` wins. ## Examples ### All-time summary bucket ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0xbddf61af533ff524d27154e589d2d7a81510c684/pnl/events" ``` ```json theme={null} { "address": "0xbddf61af533ff524d27154e589d2d7a81510c684", "granularity": "day", "bucket_count": 1, "buckets": [ { "bucket": 1779908613, "realized_pnl": 29035964.931344, "cumulative_pnl": 29035964.931344, "gross_profit": 29818047.886063, "gross_loss": -782082.954719, "wins": 482, "losses": 33, "events": 1016, "position_count": 1016, "open_positions": 511, "unrealized_pnl": -26917534.501466, "total_pnl": 2118430.429878, "total_volume": 177203290.120101 } ], "total_realized_pnl": 29035964.931344, "total_events": 1016, "total_wins": 482, "total_losses": 33, "total_positions": 1016, "open_positions": 511, "unrealized_pnl": -26917534.501466, "total_pnl": 2118430.429878, "source": "wallet_summary", "count_type": "positions", "summary_bucket": true, "elapsed_ms": 3 } ``` ### Daily P\&L for the last 7 days ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x44c1dfe43260c94ed4f1d00de2e1f80fb113ebc1/pnl/events?period=7d&group=day" ``` ```json theme={null} { "address": "0x44c1dfe43260c94ed4f1d00de2e1f80fb113ebc1", "granularity": "day", "after": 1778478745, "before": 1779083545, "bucket_count": 3, "buckets": [ { "bucket": 1778889600, "realized_pnl": 0.000525, "cumulative_pnl": 0.000525, "gross_profit": 0.000525, "gross_loss": 0, "wins": 1, "losses": 0, "events": 1 }, { "bucket": 1778976000, "realized_pnl": 611.069702, "cumulative_pnl": 611.070227, "gross_profit": 618.41811, "gross_loss": -7.348408, "wins": 23, "losses": 3, "events": 26 }, { "bucket": 1779062400, "realized_pnl": 11.774724, "cumulative_pnl": 622.844951, "gross_profit": 11.774724, "gross_loss": 0, "wins": 2, "losses": 0, "events": 2 } ], "total_realized_pnl": 622.844951, "total_events": 29, "total_wins": 26, "total_losses": 3, "elapsed_ms": 4 } ``` ### Hourly P\&L for an explicit window ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x44c1dfe43260c94ed4f1d00de2e1f80fb113ebc1/pnl/events?after=1778976000&before=1779062400&group=hour" ``` ### Weekly P\&L for the last year ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x44c1dfe43260c94ed4f1d00de2e1f80fb113ebc1/pnl/events?period=1y&group=week" ``` ## Response fields | Field | Type | Description | | - | - | - | | `address` | string | The wallet address (lowercased) | | `granularity` | string | Resolved bucket size (`hour`, `day`, `week`, `month`) | | `after` | integer | Start of the window (Unix seconds, inclusive) | | `before` | integer | End of the window (Unix seconds, inclusive) | | `bucket_count` | integer | Number of buckets returned | | `buckets` | array | Time-series rows, ordered oldest → newest | | `buckets[].bucket` | integer | Bucket start timestamp (Unix seconds, UTC, truncated to bucket boundary) | | `buckets[].realized_pnl` | number | Weighted-average-cost realized P\&L changes from indexed events in that bucket (USD) | | `buckets[].cumulative_pnl` | number | Running sum of `realized_pnl` over the returned series (USD) | | `buckets[].gross_profit` | number | Sum of winning events in that bucket (USD) | | `buckets[].gross_loss` | number | Sum of losing events in that bucket (USD, negative) | | `buckets[].wins` | integer | Count of winning events in that bucket | | `buckets[].losses` | integer | Count of losing events in that bucket | | `buckets[].events` | integer | Total P\&L events in event-series mode; position count in default summary mode | | `buckets[].position_count` | integer | Position count. Present in default summary mode. | | `buckets[].open_positions` | integer | Open position count. Present in default summary mode. | | `buckets[].unrealized_pnl` | number | Current unrealized P\&L. Present in default summary mode. | | `buckets[].total_pnl` | number | `realized_pnl + unrealized_pnl`. Present in default summary mode. | | `buckets[].total_volume` | number | Wallet volume from the summary source. Present in default summary mode. | | `total_realized_pnl` | number | Sum of event-realized `realized_pnl` across all returned buckets (USD); it is not expected to equal the current all-time P\&L | | `total_events` | integer | Sum of `events` across all returned buckets | | `total_wins` | integer | Sum of `wins` across all returned buckets | | `total_losses` | integer | Sum of `losses` across all returned buckets | | `source` | string | Dataset label. Present in default summary mode. | | `count_type` | string | `positions` in default summary mode | | `summary_bucket` | boolean | `true` in default summary mode | | `elapsed_ms` | integer | Server-side query time in milliseconds | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Buckets are summed per bucket across the combined wallets, and `cumulative_pnl` and the `total_*` fields cover the combined series. With `period`, `after`, or `before`, every wallet uses the same window, and `address` stays the address you passed. A wallet whose P\&L is not loaded yet is left out of the combination and of `wallets`. ## Errors | HTTP | When | | - | - | | `400` | Invalid wallet address (must be `0x` + 40 hex) | | `400` | Invalid `group` value (must be `hour`, `day`, `week`, or `month`) | | `400` | `after` greater than `before` | # Wallet PolyUSD Flows Source: https://docs.polynode.dev/data/wallets/polyusd-flows GET /v3/wallets/{address}/polyusd-flows Get PolyUSD deposits and withdrawals for a wallet. Returns PolyUSD deposit and withdrawal history for one wallet. Deposits are incoming PolyUSD mints to the wallet. Withdrawals are outgoing PolyUSD movements that redeem back to USDC or USDC.e. > [!NOTE] > > This endpoint is focused on user cash movement. It excludes split, merge, and trading settlement mechanics, which are available through the wallet activity and trade endpoints. ## Request ``` GET /v3/wallets/{address}/polyusd-flows ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `kind` | string | `all` | `all`, `deposit`, or `withdrawal` | | `after` | integer | `0` | Start of time range (Unix seconds, inclusive) | | `before` | integer | unlimited | End of time range (Unix seconds, inclusive) | | `order` | string | `desc` | `asc` or `desc` | | `limit` | integer | `100` | Max 300 | | `offset` | integer | `0` | Pagination offset | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x2a1f579283C87c4574102bbF6E4B39F7A12fe77E/polyusd-flows?limit=2" ``` ```json theme={null} { "address": "0x2a1f579283c87c4574102bbf6e4b39f7a12fe77e", "flows": [ { "event_type": "withdrawal", "direction": "out", "amount": 2690.200068, "amount_usdc": 2690.200068, "amount_raw": "2690200068", "asset": "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", "asset_symbol": "USDC.e", "ramp": "CollateralOfframp", "source_event": "Transfer+Unwrapped", "transaction_hash": "0xed54095cbf5c5f434cd3c12d7d226e8922bb40d597d0c61a623412567b5f0e45" }, { "event_type": "deposit", "direction": "in", "amount": 1500, "amount_usdc": 1500, "amount_raw": "1500000000", "asset": "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", "asset_symbol": "USDC.e", "ramp": "CollateralOnramp", "source_event": "Wrapped", "transaction_hash": "0x1d516fa44c127232be3f8aad9dc974fca73e2f1e1c8716914a8ef6c8222cbf25" } ], "rows_returned": 2, "total_matching_rows": 21, "has_more": true, "total_deposited": 12854.05392, "total_withdrawn": 5930.200068, "net_deposited": 6923.853852, "source": "polyusd_flows" } ``` ## Response fields | Field | Type | Description | | - | - | - | | `address` | string | Wallet address, lowercased | | `flows` | array | Deposit and withdrawal rows for the requested page | | `flows[].event_type` | string | `deposit` or `withdrawal` | | `flows[].direction` | string | `in` for deposits, `out` for withdrawals | | `flows[].amount` | number | 6-decimal normalized USD amount | | `flows[].amount_raw` | string | Raw PolyUSD amount | | `flows[].asset` | string | Underlying asset address | | `flows[].asset_symbol` | string | `USDC.e`, `USDC`, or `unknown` | | `flows[].ramp` | string | Ramp contract used | | `flows[].recipient` | string | Recipient of minted PolyUSD or unwrapped USDC/USDC.e | | `flows[].transaction_hash` | string | Polygon transaction hash | | `flows[].block_number` | integer | Polygon block number | | `flows[].block_timestamp` | integer | Polygon block timestamp | | `rows_returned` | integer | Number of rows returned | | `total_matching_rows` | integer | Total rows after filters before pagination | | `has_more` | boolean | Whether another page exists | | `total_deposited` | number | Sum of matching deposit rows | | `total_withdrawn` | number | Sum of matching withdrawal rows | | `net_deposited` | number | Deposits minus withdrawals | | `source` | string | Dataset label | ## Errors | HTTP | When | | - | - | | `400` | Invalid wallet address, `kind`, or `order` | | `401` | Missing or invalid PolyNode API key | | `502` | Temporary data provider failure | # Wallet Positions Source: https://docs.polynode.dev/data/wallets/positions GET /v3/wallets/{address}/positions Get all positions for a wallet with market context, current prices, unrealized P&L, and settlement status. Returns every position a wallet has ever held, enriched with market metadata, live token prices, computed unrealized P\&L, settlement status, and redemption data. All amounts are in USD. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/positions ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `address` | string | Wallet address or owner EOA (0x-prefixed, case-insensitive) | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `status` | string | all | Filter: `open`, `closed`, `redeemable`, `redeemed` | | `sort` | string | `realized_pnl` | Sort by: `realized_pnl` (default), `amount` (current shares), `volume` / `total_bought`, `avg_price`, `recent` (last trade time) | | `order` | string | `desc` | Sort direction: `asc` or `desc` | | `condition_id` | string | -- | Filter by market condition ID | | `market_slug` | string | -- | Filter by market slug | | `min_size` | number | -- | Minimum position size in USD (e.g. `min_size=10.0`) | | `include_combos` | boolean | `false` | Append combo positions to the response. Combo rows have `position_type: "combo"` and include `legs` metadata. | | `limit` | integer | 100 | Results per page (max 300) | | `offset` | integer | 0 | Pagination offset | ### Position statuses Wallet and global position endpoints use lifecycle statuses: | Status | Meaning | | - | - | | `open` | Wallet holds shares in an active (unresolved) market | | `closed` | Position fully sold before market resolved | | `redeemable` | Market resolved, wallet still holds shares that can be redeemed | | `redeemed` | Market resolved and shares have been redeemed | Market-scoped holder endpoints may use `open`/`closed` differently when explicitly documented as holder-state filters: `open` means the current balance is nonzero, and `closed` means the current balance is zero. ## Examples ### All positions ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/positions?limit=1 ``` ```json theme={null} { "address": "0xa9857c7bcb9bcfafd2c132ab053f34f678610058", "positions": [ { "token_id": "56311531524793560667677947517355066819344622894461317832902534277368408457717", "size": 0.003332, "avg_price": 0.479999, "realized_pnl": 0.083202, "unrealized_pnl": 0.0, "total_pnl": 0.083202, "current_price": 0.0, "total_bought": 2.083332, "initial_value": 0.001599, "redeemable_payout": 0.0, "resolved": true, "price_source": "settlement", "status": "redeemable", "market": "Bitcoin Up or Down - May 13, 6:55AM-7:00AM ET", "slug": "btc-updown-5m-1778669700", "outcome": "Down", "outcome_index": 1, "opposite_asset": "75458928898922591833639657019011228747535375591777673334858165385124723756977", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "condition_id": "0xa1118bf183058190b9b47529d94eed53d0210c65531990019c09b893cb64b73b", "event_slug": "btc-updown-5m-1778669700", "neg_risk": false, "market_status": "live", "tag_slugs": ["Hide From New", "Recurring", "Up or Down", "Crypto Prices", "Crypto", "Bitcoin", "5M"], "last_trade_at": "1778670064", "resolved_at": "0", "winning_outcome_index": null, "won": null } ], "rows_returned": 1, "has_more": true, "offset": 0, "limit": 1, "elapsed_ms": 45 } ``` ### Only open positions ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x.../positions?status=open ``` ### Only redeemable (resolved but not yet claimed) ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x.../positions?status=redeemable ``` The `redeemable_payout` field shows the exact USD amount the wallet can claim. ### Sort by most recent trade ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x.../positions?sort=recent" ``` ### Sort by current position size ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x.../positions?sort=amount" ``` ### Include combo positions ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/positions?include_combos=true&limit=2" ``` When combo rows are present, they are appended with `position_type: "combo"` and a combo-specific field set: ```json theme={null} { "position_type": "combo", "combo_condition_id": "0x030002fa8781d9f445d838e60524d70bf30000000000000000000000000000", "combo_position_id": "1356959103499736670017337806334234879289930581423500836189165811753797287936", "shares_balance": "0.000100", "entry_avg_price_usdc": "0.2285", "entry_cost_usdc": "0.00", "realized_pnl_usdc": "0.000000", "total_pnl_usdc": "0.000000", "status": "open", "legs": [ { "leg_index": 0, "leg_position_id": "943244391856361009754982642766252708422485833075867696330382296106234020352", "leg_outcome_label": "Yes", "leg_status": "OPEN" } ] } ``` ## Response fields ### Top-level combo fields | Field | Type | Description | | - | - | - | | `include_combos` | boolean | Present when `include_combos=true` was requested | | `included_position_types` | array | Includes `market` and `combo` when combo inclusion was requested | | `combo_position_count` | integer | Number of combo position rows returned in this page | ### Position data | Field | Type | Description | | - | - | - | | `token_id` | string | Outcome token ID | | `size` | number | Current shares held in USD (0 if closed/redeemed) | | `avg_price` | number | Weighted-average entry price in USD | | `realized_pnl` | number | Realized P\&L from closed trades (USD) | | `unrealized_pnl` | number | Paper P\&L: `(current_price - avg_price) * size` | | `total_pnl` | number | `realized_pnl + unrealized_pnl` | | `current_price` | number | Latest token price (USD, from settlement, CLOB mid, or last fill) | | `total_bought` | number | Total USD spent buying this position | | `initial_value` | number | `avg_price * size` at current holdings | | `redeemable_payout` | number | USD claimable if redeemed now (0 for losing outcomes) | | `resolved` | boolean | Whether the market has settled | | `price_source` | string | Price source: `settlement`, `clob_mid`, `v1_condition`, `last_fill` | | `status` | string | `open`, `closed`, `redeemable`, or `redeemed` | ### Market context | Field | Type | Description | | - | - | - | | `market` | string | Market question text | | `slug` | string | Market URL slug | | `outcome` | string | Outcome label (e.g. "Yes", "No", "Trump") | | `outcome_index` | integer | Outcome position (0 or 1) | | `opposite_asset` | string | Token ID of the other outcome in this market | | `image` | string | Market image URL | | `condition_id` | string | Market condition ID | | `event_slug` | string | Parent event slug | | `neg_risk` | boolean | Whether this is a neg-risk (multi-outcome) market | | `market_status` | string | `live`, `closed`, `resolved-win`, or `resolved-loss` | | `tag_slugs` | array | Category tags for this market | ### Timestamps and resolution | Field | Type | Description | | - | - | - | | `last_trade_at` | string | Unix timestamp of the most recent fill for this token | | `resolved_at` | string | Unix timestamp when the market was resolved | | `winning_outcome_index` | integer | Which outcome won (0 or 1), null if unresolved | | `won` | boolean | Whether this position's outcome won, null if unresolved | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `positions[].wallet` | string | The wallet this row belongs to | Positions are never merged across wallets. When two of the owner's wallets hold the same token, each has its own row, so key rows by `wallet` and `token_id`. Combo rows from `include_combos=true` also carry `wallet`. ## Use cases * **Portfolio dashboard** — show a trader's open positions with live P\&L and market context * **Redemption alerts** — find wallets with unclaimed payouts using `?status=redeemable` * **Performance analysis** — sort by P\&L to see best and worst positions * **Copy trading** — see what a wallet is currently holding with `?status=open&sort=amount` # Wallet Maker Rebates Source: https://docs.polynode.dev/data/wallets/rebates GET /v3/wallets/{address}/rebates Get Polymarket-reported maker rebates for a wallet and date. Returns maker rebate records reported by Polymarket for one maker address and one date. Maker rebates are Polymarket accounting credits. They are not the same value as trader fees paid. > [!NOTE] > > Polymarket rebate lookups are keyed by CLOB maker/signing address. If you pass a Safe or proxy wallet that Polymarket does not accept as a maker address, PolyNode returns an empty `rebates` array with an explanatory `hint`. ## Request ``` GET /v3/wallets/{address}/rebates ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `date` | string | current UTC date | Date in `YYYY-MM-DD` format | ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x8ecb4b228e07b6ddc58a32997093032a6907b8f6/rebates" ``` ```json theme={null} { "address": "0x8ecb4b228e07b6ddc58a32997093032a6907b8f6", "date": "2026-05-27", "rebates": [], "rows_returned": 0, "total_rebated_fees_usdc": 0, "source": "polymarket_rebates", "rebate_semantics": "Maker rebates reported for one maker/date. Separate from trader-paid fees.", "elapsed_ms": 271 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `address` | string | Wallet or maker address, lowercased | | `date` | string | Date used for the rebate lookup | | `rebates` | array | Polymarket rebate records | | `rows_returned` | integer | Number of rebate records returned | | `total_rebated_fees_usdc` | number | Sum of `rebated_fees_usdc` across returned records when present | | `source` | string | Dataset label | | `rebate_semantics` | string | Accounting note | | `provider_status` | integer | Present when the rebate data provider returned an invalid maker-address response that PolyNode converted to an empty result | | `provider_warning` | object | Present with the provider warning body for invalid maker-address responses | | `hint` | string | Present when a Safe/proxy address may need to be resolved to a maker EOA | | `elapsed_ms` | integer | Server-side request time in milliseconds | The objects inside `rebates` follow Polymarket's rebate record format. When a record includes `rebated_fees_usdc`, PolyNode includes it in `total_rebated_fees_usdc`. ## Errors | HTTP | When | | - | - | | `400` | Invalid wallet address | | `400` | Invalid `date` format | | `401` | Missing or invalid PolyNode API key | | `502` | Temporary rebate data provider failure | # Wallet Redemptions Source: https://docs.polynode.dev/data/wallets/redemptions GET /v3/wallets/{address}/redemptions Get all direct and AutoRedeemer-attributed payout redemptions for a wallet. Returns all indexed redemption events attributed to the wallet across direct Conditional Tokens, negative-risk, and AutoRedeemer execution paths. AutoRedeemer rows use the beneficiary wallet rather than the protocol contract address, so the result remains complete when the protocol submits the underlying claim. Direct and AutoRedeemer rows are merged across all time before sorting and pagination. Every row includes `transaction_hash`, `block_number`, `log_index`, `redemption_source`, and `source_event`. Rows are enriched with market and resolution metadata when available so clients can identify the winning outcome without a second market lookup. Existing response fields remain present and unchanged. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/redemptions ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | | `order` | string | `desc` | Sort order: `asc` or `desc` | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839/redemptions?limit=1 ``` ```json theme={null} { "data": [ { "id": "0x6173027f191670852e049df6ded0b353069a531f5ea647220bdcb64ab634348e_cac", "timestamp": "1776731610", "condition": "0x19be7c46e28b61455ec766679ee1122fba39eb0d5c85d0878e4b203ab8b18406", "payout": "4078910900", "index_sets": ["1", "2"], "condition_id": "0x19be7c46e28b61455ec766679ee1122fba39eb0d5c85d0878e4b203ab8b18406", "payout_e6": "4078910900", "payout_usdc": 4078.9109, "market_title": "Will John Ternus be the next CEO of Apple?", "market_slug": "will-john-ternus-be-the-next-ceo-of-apple", "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/next-ceo-of-apple-leUfWn-_USCO.jpg", "event_title": "Next CEO of Apple?", "event_slug": "next-ceo-of-apple", "neg_risk": true, "token_ids": [ "92311850691119989700494243314039291208974625045063458908184129720108035114164", "14954786464025422340381119759227166561985048022429770302259194276382916274663" ], "outcomes": ["Yes", "No"], "payouts": [1.0, 0.0], "outcome_prices": [1.0, 0.0], "winning_outcome_index": 0, "winning_outcome": "Yes", "winning_token_id": "92311850691119989700494243314039291208974625045063458908184129720108035114164", "resolved_at": "2026-05-28T04:49:07.589252+00:00", "transaction_hash": "0x6173027f191670852e049df6ded0b353069a531f5ea647220bdcb64ab634348e", "redemption_source": "direct_neg_risk", "source_event": "NegRiskAdapter.PayoutRedemption", "block_number": 85805783, "log_index": 3244 } ], "rows_returned": 1, "has_more": true, "next_offset": 1, "offset": 0, "limit": 1, "order": "desc", "source": "v3.wallet_redemptions_unified", "elapsed_ms": 3 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `id` | string | Redemption event ID | | `timestamp` | string | Unix timestamp | | `condition` | string | Market condition ID that was redeemed | | `payout` | string | Exact raw payout amount in six-decimal integer units. Preserved for backwards compatibility. | | `index_sets` | array \| null | Which outcome index sets were redeemed. AutoRedeemer lifecycle rows may not expose this value. | | `condition_id` | string | Alias of `condition`, matching the WebSocket redemption payload naming. | | `payout_e6` | string | Alias of `payout`; exact six-decimal payout amount for accounting-safe comparisons. | | `payout_usdc` | number | Human-readable payout amount in USDC. | | `market_title` | string \| null | Human-readable market question. | | `market_slug` | string \| null | Market slug. | | `market_image` | string \| null | Market image URL. | | `event_title` | string \| null | Parent event title, when available. | | `event_slug` | string \| null | Parent event slug, when available. | | `neg_risk` | boolean \| null | Whether the market uses Polymarket negative-risk settlement. | | `token_ids` | string\[] \| null | Ordered market token IDs. Same order as `outcomes`, `payouts`, and `outcome_prices`. | | `outcomes` | string\[] \| null | Ordered outcome labels for the market. | | `payouts` | number\[] \| null | Resolved payout numerators for each outcome, when resolution metadata is available. | | `outcome_prices` | number\[] \| null | Payouts normalized by the payout denominator. Winners are usually `1.0`; losers are usually `0.0`. | | `winning_outcome_index` | number \| null | Index of the winning outcome when exactly one outcome has a non-zero payout, or when metadata already provides the winner. | | `winning_outcome` | string \| null | Label of the winning outcome. | | `winning_token_id` | string \| null | Token ID of the winning outcome. | | `resolved_at` | string \| null | ISO timestamp for when the market resolution metadata indicates the condition became resolved. | | `transaction_hash` | string | Polygon transaction hash containing the redemption event. | | `redemption_source` | string | Normalized execution path: `direct_ctf`, `direct_neg_risk`, `direct_other`, `auto_binary`, `auto_neg_risk`, or `auto_combo`. | | `source_event` | string | Exact protocol event family used to attribute the redemption. | | `block_number` | integer | Polygon block containing the source event. | | `log_index` | integer | Source event log index. Combine with `transaction_hash` for an exact event identity. | AutoRedeemer binary and negative-risk rows carry the market condition directly. Generic combo redemptions resolve their condition through the canonical combo redemption mapping. A transaction can contain multiple legitimate redemption events, so clients should identify rows by `transaction_hash` plus `log_index`, not by payout amount. ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `data[].wallet` | string | The wallet this row belongs to | # Wallet Splits Source: https://docs.polynode.dev/data/wallets/splits GET /v3/wallets/{address}/splits Get all split events for a wallet. Splits occur when USDC is converted into outcome tokens. Returns split events where USDC was converted into outcome tokens for a market condition. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/splits ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xada100874d00e3331d00f2007a9c336a65009718/splits?limit=1 ``` ```json theme={null} { "data": [ { "id": "0x48a4ffe402ea660ccb9dea5f802ca4ea5d22ed395ae07d249fca0ec94b79d325_0x566", "timestamp": "1778492385", "condition": "0xd863a481323564b64f431d4c8fa8f0237f56075b2bb4b6f3ec9be8986ec292f0", "amount": "33927075" } ], "rows_returned": 1, "has_more": true, "elapsed_ms": 3 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `id` | string | Split event ID | | `timestamp` | string | Unix timestamp | | `condition` | string | Market condition ID | | `amount` | string | USDC amount split (6-decimal) | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `data[].wallet` | string | The wallet this row belongs to | # Wallet Summary Source: https://docs.polynode.dev/data/wallets/summary GET /v3/wallets/{address} Get a complete P&L summary for any Polymarket wallet in USD. Realized and unrealized profit/loss, win rate, position count, and total volume. Returns a full profile for a single wallet in USD. Includes realized P\&L, unrealized P\&L from open positions, gross profit and loss, win/loss record, and total trading volume. > [!NOTE] > > For standard spot market positions, P\&L excludes separately reported > trader-paid fees, rebates, and rewards. `net_realized_pnl` combines realized > gains and losses; "net" does not mean after fees. Setting > `include_accounting_summary=true` adds separate accounting fields without > deducting them from P\&L. With `include_combos=true`, the added > [Combo component](/data/combos/leaderboard) already includes its recorded > exchange fill fee. Keep component and time scopes aligned when combining > accounting amounts, and do not deduct that Combo fee twice. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address} ``` ### Path parameters | Parameter | Type | Description | | - | - | - | | `address` | string | Wallet address or owner EOA (0x-prefixed, case-insensitive) | ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `include_combos` | boolean | `false` | Add combo P\&L and combo position counts to the all-time wallet summary. | | `include_accounting_summary` | boolean | `false` | Add the all-time wallet accounting summary, including exact trader-paid fees from indexed onchain fills. | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x56687bf447db6ffa42ffe2204a05edaa20f55839 ``` ### Summary including combos ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907?include_combos=true" ``` ```json theme={null} { "address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "net_realized_pnl": 113.510513, "realized_pnl": 113.510513, "total_pnl": 113.510513, "position_count": 21496, "open_positions": 1495, "include_combos": true, "included_position_types": ["market", "combo"], "combo_pnl": { "position_type": "combo", "included": true, "realized_pnl": 113.510513, "total_pnl": 113.510513, "position_count": 21492, "open_positions": 1495 } } ``` ### Summary including accounting Use this when you need the exact all-time fee summary without paging through raw fill rows. ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x7553e42ce1b37727b819dfe4bac495b3968f65ca?include_accounting_summary=true" ``` ```json theme={null} { "address": "0x7553e42ce1b37727b819dfe4bac495b3968f65ca", "net_realized_pnl": -138570.0369464795, "gross_profit": 524921.0508558493, "gross_loss": -671088.850081543, "unrealized_pnl": -7597.762279214215, "total_pnl": -146167.79922569369, "position_count": 915, "open_positions": 0, "total_volume": 2718779.615141, "accounting_summary": { "available": true, "loaded": true, "has_order_filled_rows": true, "source": "api.wallet_accounting_summary_current", "fees_paid": { "available": true, "loaded": true, "amount": 99973.115598, "raw": "99973115598", "fee_fill_count": 2984, "order_owner_fill_count": 5122, "first_fee_block": "84892414", "last_fee_block": "88904629" }, "maker_rebates": { "available": false, "loaded": false, "status": "not_loaded", "amount": null, "raw": null }, "rewards": { "available": false, "loaded": false, "status": "not_loaded", "amount": null, "raw": null }, "order_filled_through_block": "88978163", "projector_status": "ready" }, "elapsed_ms": 2 } ``` ```json theme={null} { "address": "0x56687bf447db6ffa42ffe2204a05edaa20f55839", "net_realized_pnl": 22053845.825455, "gross_profit": 22057977.181649, "gross_loss": -4131.356194, "unrealized_pnl": 0.000688755, "total_pnl": 22053845.826143753, "wins": 18, "losses": 4, "position_count": 22, "open_positions": 1, "total_volume": 43013258.515682, "elapsed_ms": 1 } ``` ## Response fields | Field | Type | Description | | - | - | - | | `net_realized_pnl` | number | Net realized P\&L in USD | | `gross_profit` | number | Sum of all winning position P\&L (USD) | | `gross_loss` | number | Sum of all losing position P\&L (USD, negative) | | `unrealized_pnl` | number | Unrealized P\&L from open positions based on current prices (USD) | | `total_pnl` | number | `net_realized_pnl + unrealized_pnl` (USD) | | `wins` | integer | Number of positions closed with positive P\&L | | `losses` | integer | Number of positions closed with negative P\&L | | `position_count` | integer | Total positions (open + closed) | | `open_positions` | integer | Positions with shares > 0 | | `total_volume` | number | Total volume traded (USD) | | `combo_pnl` | object | Present when `include_combos=true`; combo-only contribution to the wallet summary | | `accounting_summary` | object | Present when `include_accounting_summary=true`; all-time compact wallet accounting summary | | `accounting_summary.fees_paid.amount` | number | Exact all-time trader-paid fees in USD | | `accounting_summary.fees_paid.raw` | string | Exact all-time trader-paid fees in 6-decimal raw units | | `accounting_summary.fees_paid.fee_fill_count` | integer | Number of order-owner fills with a positive fee | | `accounting_summary.fees_paid.order_owner_fill_count` | integer | Number of indexed order-owner fills for the wallet | | `accounting_summary.maker_rebates.status` | string | Maker rebate projection status. `not_loaded` means do not treat the amount as zero. | | `accounting_summary.rewards.status` | string | Reward projection status. `not_loaded` means do not treat the amount as zero. | | `accounting_summary.order_filled_through_block` | string | Latest block covered by the order-filled accounting projector | | `accounting_summary.projector_status` | string | Current projector status | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | Totals and counts are summed across the combined wallets. `address` stays the address you passed. # Wallet Trades Source: https://docs.polynode.dev/data/wallets/trades GET /v3/wallets/{address}/trades Get all trades for a wallet with market context, computed price, direction, and order hash. Returns fills where the wallet participated as maker, taker, or both. Each trade is enriched with market metadata, computed price/size in USD, buy/sell direction, and the order hash. > [!NOTE] > > **Owner addresses.** Pass an owner EOA as the wallet address and the response combines the EOA's Polymarket wallets (Safe, proxy, deposit wallets) that have data for this endpoint. Passing a Safe, proxy or deposit wallet returns just that wallet, as before. Combined responses list the combined wallets in `wallets`. See [Owner addresses](/data/overview#owner-addresses). ## Request ``` GET /v3/wallets/{address}/trades ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `side` | string | `both` | `maker`, `taker`, or `both` | | `token_id` | string | -- | Filter trades involving this token | | `condition_id` | string | -- | Filter by market condition ID (resolves to token IDs) | | `market_slug` | string | -- | Filter by market slug (resolves to token IDs) | | `event_slug` | string | -- | Filter by event slug (resolves to token IDs across all of the event's markets) | | `event_id` | integer | -- | Filter by numeric event ID (same scope as `event_slug`) | | `order_hash` | string | -- | Return only fills for one exact order hash (`0x` + 64 hex characters) | | `min_amount_usd` | number | -- | Minimum trade size in dollars, matching the `amount_usd` response field. Decimals allowed, e.g. `99.5` | | `min_amount` | integer | -- | Minimum `maker_amount_filled` (raw 6-decimal). Prefer `min_amount_usd` | | `sort_by` | string | -- | `order_hash` groups fills by limit order visually (individual fill rows, sorted by most recent order) | | `group_by` | string | -- | `user_trade` returns Polymarket-style user-visible trade rows; `transaction_hash` is an alias; `order_hash` aggregates wallet-visible fills per order | | `after` | integer | -- | Start of time range (Unix timestamp) | | `before` | integer | -- | End of time range (Unix timestamp) | | `include_combos` | boolean | `false` | Add combo trades in a separate `combo_trades` branch. If the wallet has no combo trades, the response remains 200 with an empty combo branch. | | `order` | string | `desc` | `asc` or `desc` | | `limit` | integer | 100 | Max 300 | | `offset` | integer | 0 | Pagination offset | `order_hash` is applied in the database before pagination. Combine it with any other wallet-trade filter; all supplied filters are intersected. Hex characters are case-insensitive and the response uses the normalized lowercase hash. A well-formed hash with no matching fills returns `200` with an empty `trades` array. An empty or malformed hash returns `400`. Combo trades do not expose a Polymarket order hash, so `order_hash` cannot be combined with `include_combos=true`; that combination returns `400`. ## Example List every fill where one wallet participated in a specific order: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c" ``` Add filters normally—for example, maker fills for that order inside one market and time window: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/trades?order_hash=0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c&side=maker&market_slug=nba-det-cle-2026-05-15&after=1778000000&order=asc" ``` The unfiltered wallet feed has the same response shape: ```bash theme={null} curl -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v3/wallets/0xa9857c7bcb9bcfafd2c132ab053f34f678610058/trades?limit=1" ``` ```json theme={null} { "address": "0xa9857c7bcb9bcfafd2c132ab053f34f678610058", "elapsed_ms": 3, "has_more": true, "limit": 1, "offset": 0, "rows_returned": 1, "trades": [ { "amount": 8.19, "amount_usd": 4.914, "asset": "31336121594291014914271611062289284423554618020629759821503694496084098706290", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "condition_id": "0x7b461ba0d582c03577966cfdf0da2a5cb9696a26b954b5ed1890f82d6f2a3c88", "direction": "SELL", "event_id": 465162, "event_slug": "nba-det-cle-2026-05-15", "fee": 0.05896, "id": "0xedcfd55321a267c7a200cac4069e4134d85d538e4c245fe3bf1e59ad3188acd8_0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c_1168", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/super+cool+basketball+in+red+and+blue+wow.png", "maker": "0xa9857c7bcb9bcfafd2c132ab053f34f678610058", "maker_amount": 8.19, "maker_asset_id": "31336121594291014914271611062289284423554618020629759821503694496084098706290", "market": "Pistons vs. Cavaliers", "order_hash": "0x9ed363e9c05368fba5c717b8bee355d60a579f599cb7c007d90974203896a95c", "outcome": "Cavaliers", "outcome_index": 1, "price": 0.6, "role": "maker", "side": 1, "size": 8.19, "slug": "nba-det-cle-2026-05-15", "taker": "0xe111180000d2663c0091e4f400237545b87b996b", "taker_amount": 4.914, "taker_asset_id": "0", "timestamp": "1778754419", "token_id": "31336121594291014914271611062289284423554618020629759821503694496084098706290", "transaction_hash": "0xedcfd55321a267c7a200cac4069e4134d85d538e4c245fe3bf1e59ad3188acd8" } ] } ``` ### Maker-only trades ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x.../trades?side=maker&limit=10 ``` ### Trades for a specific token ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x.../trades?token_id=75783394...&limit=10 ``` ### Trades in a time window ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x.../trades?after=1778000000&before=1778604000 ``` ### Include combo trades ```bash theme={null} curl "https://api.polynode.dev/v3/wallets/0x63613e3b96f418332d43cd2af8dc321014d15907/trades?include_combos=true&limit=5" ``` Combo trades are returned in `combo_trades` so existing consumers of the standard `trades` array do not need to change parsing logic. ```json theme={null} { "address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "trades": [], "rows_returned": 0, "include_combos": true, "included_position_types": ["market", "combo"], "combo_trade_count": 5, "combo_has_more": true, "combo_source": "v3.wallet_combos.trades", "combo_trades": [ { "position_type": "combo", "wallet_role": "maker", "wallet_address": "0x63613e3b96f418332d43cd2af8dc321014d15907", "counterparty_address": "0xe3333700ca9d93003f00f0f71f8515005f6c00aa", "combo_condition_id": "0x0310c8c1e924b0ddffd987430c42fc26e10000000000000000000000000000", "position_id": "1741334187009265192213210063949860811096650382021683265628751751539647840256", "side": "BUY", "price": "0.0197", "size": "0.050750", "fee": "0.000020", "tx_hash": "0xf3a8985f04bf869483ef4163a185f296c834eb827b5e5ae3db5bd44558121d51", "block_number": 88276713, "timestamp": 1781120055, "source": "v3.wallet_combos.trades" } ] } ``` ## Response fields ### Top-level combo fields | Field | Type | Description | | - | - | - | | `include_combos` | boolean | Present when `include_combos=true` was requested | | `included_position_types` | array | Includes `market` and `combo` when combo inclusion was requested | | `combo_trades` | array | Combo trade rows for the wallet | | `combo_trade_count` | integer | Number of combo trade rows returned in this page | | `combo_has_more` | boolean | Whether more combo trade rows are available | | `combo_source` | string | Source label for the combo trade branch | ### Trade data | Field | Type | Description | | - | - | - | | `id` | string | Unique fill ID (transaction\_hash + log index) | | `maker` | string | Maker wallet address | | `taker` | string | Taker wallet address | | `maker_asset_id` | string | Asset the maker provided (`0` = USDC) | | `taker_asset_id` | string | Asset the taker provided (`0` = USDC) | | `maker_amount` | number | Amount the maker provided, normalized: outcome tokens, or USD when `maker_asset_id` is `0` | | `taker_amount` | number | Amount the taker provided, normalized: outcome tokens, or USD when `taker_asset_id` is `0` | | `amount_usd` | number | USD value of the fill (the USDC side of the trade). This is the value the `min_amount_usd` filter compares against | | `fee` | number | Fee charged (USD) | | `token_id` | string | Outcome token ID for the visible trade leg | | `asset` | string | Alias for `token_id`, included for Polymarket compatibility | | `amount` | number | Alias for `size`, included for Polymarket compatibility | | `price` | number | Computed price per outcome token (maker\_amount / taker\_amount or inverse) | | `size` | number | Number of outcome tokens traded | | `timestamp` | string | Unix timestamp | | `transaction_hash` | string | On-chain transaction hash | | `order_hash` | string | Unique order hash for this fill | | `builder` | string | Builder attribution code (hex) | | `side` | integer | Maker's limit order direction: `0` = maker was buying tokens, `1` = maker was selling tokens, `null` for V1 trades. This is the maker's side, not the queried wallet's action. Use `direction` instead for the wallet's perspective. | | `role` | string | `maker` or `taker` -- which side the queried wallet was on in this fill | | `direction` | string | `BUY` or `SELL` -- whether the queried wallet bought or sold outcome tokens. This is the field you want for understanding what the wallet did. | ### Market context | Field | Type | Description | | - | - | - | | `market` | string | Market question text | | `slug` | string | Market URL slug | | `outcome` | string | Outcome label (e.g. "Yes", "Aurora") | | `outcome_index` | integer | Outcome position (0 or 1) | | `image` | string | Market image URL | | `condition_id` | string | Market condition ID | | `event_slug` | string \| null | Slug of the Polymarket event this market belongs to | | `event_id` | integer \| null | Numeric ID of that event. Both are null for old markets no longer in Polymarket's catalog | ### Owner address fields Present only when you pass an owner EOA. See [Owner addresses](/data/overview#owner-addresses). | Field | Type | Description | | - | - | - | | `wallets` | array | The combined wallets, in a fixed order, each `{wallet, type}` with `type` one of `eoa`, `safe`, `proxy`, or `deposit_wallet` | | `trades[].wallet` | string | The wallet this row belongs to | | `combo_trades[].wallet` | string | The wallet this row belongs to | `role` and `direction` are relative to the row's `wallet`. A fill between two of the owner's wallets appears once for each wallet, with the same `id`. With `group_by`, fills are grouped within each wallet, never across wallets, and each grouped row carries `wallet`. ### Sort fills by order hash ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xa9857c.../trades?sort_by=order_hash&limit=10 ``` Groups all fills belonging to the same limit order together visually, sorted by most recent order first. Returns individual fill rows. ### User-visible trades ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xa9857c.../trades?market_slug=dota2-aur1-liquid-2026-05-13&group_by=user_trade ``` Returns one row per user-visible trade, matching the Polymarket-style wallet trade feed. This removes complementary order-side rows that can appear in raw CTF fills and merges fills that represent the same user action. Use this grouping for UI trade history and user-facing volume math. `group_by=transaction_hash` is accepted as an alias for this behavior. ### Aggregate fills by order hash ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0x61b0ea32aff59e9893e867a2ab196476ab22dd96/trades?group_by=order_hash ``` Returns one row per wallet-visible order with aggregated totals. Complementary order-side rows are collapsed from the queried wallet's perspective before order aggregation, so UI volume and share counts do not double-count both sides of the same user action. Use `group_by=user_trade` when you want one row per user-visible fill without order-level rollup. ```json theme={null} { "trades": [ { "order_hash": "0xea91f0d67086be...", "fill_count": 5, "avg_price": 0.57, "total_amount_usd": 669.11, "total_usd": 669.11, "total_shares": 1173.88, "total_fee": 0.0, "total_maker_amount": 669.11, "total_taker_amount": 1173.88, "first_fill_at": 1778100000, "last_fill_at": 1778200000, "tx_hashes": ["0xabc...", "0xdef..."], "market": "MegaETH market cap (FDV) >$1.5B one day after TGE?", "slug": "megaeth-fdv-1-5b-one-day-after-tge", "outcome": "Yes", "direction": "BUY" } ], "rows_returned": 6, "grouped_by": "order_hash" } ``` #### Grouped response fields | Field | Type | Description | | - | - | - | | `order_hash` | string | The limit order hash | | `fill_count` | integer | Number of fills in this order | | `avg_price` | number | Volume-weighted average price (`total_amount_usd / total_shares`) | | `total_amount_usd` | number | Total USD value across all fills. Alias of `total_usd`, included for compatibility with grouped onchain trade responses. | | `total_usd` | number | Total USD value across all fills | | `total_shares` | number | Total outcome tokens across all fills | | `total_fee` | number | Total fees (USD) | | `total_maker_amount` | number | Raw sum of maker amounts (side-dependent) | | `total_taker_amount` | number | Raw sum of taker amounts (side-dependent) | | `first_fill_at` | integer | Earliest fill timestamp (Unix seconds) | | `last_fill_at` | integer | Latest fill timestamp (Unix seconds) | | `timestamp` | string | Same as `last_fill_at` but as a string. Present for consistency with ungrouped trade rows. | | `tx_hashes` | array\ | Unique transaction hashes contributing to this order | | `market` | string \| null | Market question | | `slug` | string \| null | Market slug | | `outcome` | string \| null | Outcome label | | `outcome_index` | integer \| null | Outcome position (0 or 1) | | `image` | string \| null | Market image URL | | `condition_id` | string \| null | Market condition ID | | `direction` | string | `BUY` or `SELL` (queried wallet's perspective) | | `role` | string | `maker` or `taker` (which side the queried wallet was on) | | `side` | integer \| null | Maker's limit-order direction (raw on-chain value). Use `direction` instead. | | `maker` | string | Maker wallet address | | `taker` | string | Taker wallet address | ### Filter by market condition ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xa9857c.../trades?condition_id=0x4f05dbc6... ``` ### Filter by market slug ```bash theme={null} curl https://api.polynode.dev/v3/wallets/0xa9857c.../trades?market_slug=dota2-aur1-liquid-2026-05-13 ``` # Best Practices Source: https://docs.polynode.dev/guides/best-practices Patterns for correctly handling the pending-to-confirmed lifecycle, snapshots, and reconnection. ## The pending-to-confirmed lifecycle PolyNode detects Polymarket settlements **before** they confirm on-chain. This means every settlement goes through two stages, delivered as **two separate WebSocket events**: 1. **`settlement`** — the trade is detected pre-chain (`status: "pending"`) 2. **`status_update`** — the trade confirms in a Polygon block (typically 2–4 seconds later) Link them together by `tx_hash`: ```javascript theme={null} const pending = new Map(); // tx_hash → settlement data ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, { ...msg.data, received_at: Date.now(), }); console.log(`PENDING: ${msg.data.taker_side} $${msg.data.taker_size}`); } if (msg.type === "status_update") { const original = pending.get(msg.data.tx_hash); if (original) { const leadMs = msg.data.confirmed_at - original.received_at; console.log(`CONFIRMED: ${msg.data.latency_ms}ms server lead, ${leadMs}ms client lead`); pending.delete(msg.data.tx_hash); } } }; ``` > [!WARNING] > > These are **two separate events**, not an update to the original event. If you only listen for `settlement` events, you'll see pending trades but never know when they confirm. ## Handle the snapshot correctly When you subscribe, PolyNode sends a **snapshot** of recent events before streaming live data. The snapshot contains both `settlement` and `status_update` events mixed together. **The gotcha**: Settlement events in the snapshot always have their **original** status (`pending`), even if they were confirmed seconds ago. The corresponding `status_update` is a separate entry in the same snapshot. If you only process `settlement` events from the snapshot, you'll load stale "pending" settlements that are actually already confirmed — and their confirmation event will never arrive as a live message because it was already sent in the snapshot you ignored. ### Correct snapshot handling ```javascript theme={null} ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "snapshot") { // Step 1: Collect all status updates from the snapshot const confirmations = new Map(); for (const ev of msg.events) { if (ev.type === "status_update" && ev.data) { confirmations.set(ev.data.tx_hash, ev.data); } } // Step 2: Process settlements, checking for matching confirmations for (const ev of msg.events) { if (ev.type === "settlement" && ev.data) { const confirmation = confirmations.get(ev.data.tx_hash); if (confirmation) { // This settlement is already confirmed — use the confirmation data handleConfirmedSettlement(ev.data, confirmation); } else if (ev.data.status === "pending") { // Genuinely pending — will receive a live status_update soon handlePendingSettlement(ev.data); } } } return; } // Live events — standard handling if (msg.type === "settlement") handlePendingSettlement(msg.data); if (msg.type === "status_update") handleStatusUpdate(msg.data); }; ``` ## Add a stuck-pending timeout In rare cases, a `status_update` might be missed (e.g., network interruption, reconnection timing). Add a timeout so stale pending items don't get stuck forever: ```javascript theme={null} const PENDING_TIMEOUT_MS = 15_000; // 15 seconds setInterval(() => { const now = Date.now(); for (const [hash, data] of pending) { if (now - data.received_at > PENDING_TIMEOUT_MS) { console.log(`Timeout: ${hash} — no confirmation after 15s`); pending.delete(hash); } } }, 5_000); ``` Under normal conditions, confirmations arrive within 2–5 seconds. A 15-second timeout is generous enough to never fire in normal operation but catches edge cases. ## Reconnection with state recovery When reconnecting, use `snapshot_count` to recover recent state. The snapshot fills in events you missed during the disconnection: ```javascript theme={null} function connect() { const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); let delay = 1000; ws.onopen = () => { delay = 1000; ws.send(JSON.stringify({ action: "subscribe", type: "settlements", filters: { snapshot_count: 100 }, // Catch up on missed events })); }; ws.onclose = () => { setTimeout(connect, Math.min(delay *= 2, 30000)); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "heartbeat") return; // Handle snapshot + live events as above }; } ``` > [!TIP] > > The snapshot includes both `settlement` and `status_update` events from the recent buffer. Processing both event types from the snapshot (as shown above) ensures you have accurate state immediately after reconnection. ## Connection health The server sends a WebSocket Ping frame and a text heartbeat (`{"type": "heartbeat"}`) every 30 seconds. If the server receives no activity from the client within 5 minutes, the connection is closed. Activity that resets the server's liveness timer: * **Pong frames** (automatic response to server Ping, handled by most WS libraries) * **Any text message** you send: subscribe, unsubscribe, or `{"action": "ping"}` For most clients, this works automatically. All standard WebSocket libraries respond to Ping with Pong: * **Browser `WebSocket`** — handled by the browser * **Node.js `ws`** — automatic by default * **Python `websockets`** — automatic by default * **Go `gorilla/websocket`** — automatic with `SetPongHandler` (default) > [!WARNING] > > **Cloud-hosted clients (Railway, Render, Heroku, fly.io, AWS ALB):** Many cloud platforms run a reverse proxy in front of your container that intercepts WebSocket Ping/Pong frames at the proxy layer. Your application never sees the server's Ping, so it never sends a Pong, and the server eventually drops the connection for inactivity. > > **Symptoms:** Connection works on subscribe, receives a snapshot, then drops after 1-5 minutes with an empty error or no close frame. Reconnects immediately but the cycle repeats. > > **Fix:** Send `{"action": "ping"}` every 30 seconds from your application code. This is a regular JSON text frame that passes through any proxy. See the [WebSocket Overview](/websocket/overview#application-level-keepalive) for full code examples. > [!WARNING] > > If your read loop is blocked (e.g. doing heavy synchronous work before reading the next message), the client cannot send Pong frames and the server will eventually drop the connection. Keep your read loop running — offload heavy processing to a separate thread or task. ## Summary | Pattern | Why | | - | - | | Process **both** `settlement` and `status_update` events | Settlements and confirmations are separate events linked by `tx_hash` | | Process **both event types from the snapshot** | Snapshot settlements keep their original `pending` status — confirmations are separate entries | | Add a **stuck-pending timeout** (15s) | Safety net for missed confirmations during reconnection | | Use **`snapshot_count`** on reconnect | Recovers events missed during disconnection | | Keep read loop running | Server drops connections with no activity after 5 minutes | | Send `{"action": "ping"}` every 30s **if cloud-hosted** | Keeps connection alive through reverse proxies that strip Ping/Pong frames | # Deposit Wallets Source: https://docs.polynode.dev/guides/deposit-wallets Everything you need to know about Polymarket's new deposit wallet system and how it affects your integration. Polymarket is rolling out **deposit wallets** as a new account type alongside the existing Gnosis Safe proxy wallets. This guide explains what changed, whether you need to do anything, and how to handle both wallet types in your integration. ## What are deposit wallets? Deposit wallets are Polymarket's new smart contract wallet type for new accounts. They replace the Gnosis Safe proxy that existing accounts use. **Heard the term "beacon wallet"?** It's the same thing. Newer deposit wallets are built so Polymarket can upgrade all of them at once — that upgradeable variant is what gets called a beacon wallet. There's also an earlier standalone variant from before that change. Both behave identically, and everything on this page (and the [/resolve endpoint](/api-reference/wallets/resolve)) handles both — you never need to tell them apart. From your perspective as a builder, the key differences are: | | Safe proxy (existing) | Deposit wallet (new) | | - | - | - | | **Signature type** | `2` (POLY\_GNOSIS\_SAFE) | `3` (POLY\_1271) | | **How addresses are derived** | CREATE2 from Safe factory | CREATE2 from deposit wallet factory | | **Order signing** | Standard EIP-712 | EIP-712 with ERC-7739 TypedDataSign wrapper | | **Approvals** | Gasless via Safe multisend | Gasless via WALLET batch | | **V1 support** | Yes | No (V2 only) | **The good news:** if you use the polynode SDK, all of this is handled automatically. `ensureReady()` detects the wallet type, `order()` signs correctly, and the `/resolve` endpoint resolves both wallet types. ## Do I need to change anything? **If you use the polynode SDK for trading:** update to the latest version. Everything else is automatic. ```bash theme={null} # Current beacon-aware wallet resolution and onboarding cargo add polynode@0.18.0 --features trading npm install polynode-sdk@^0.15.0 python -m pip install "polynode[trading]>=0.15.0,<0.16" ``` **If you only read data (positions, trades, /resolve):** existing fields are unchanged. `/resolve` still returns `safe`, `eoa`, `username`, and `type` exactly as before. It also returns the deployed-only `wallets` object and a `wallet_details` list with plain `wallet_type`, `deployed`, and `current` status for each relevant address. V3 wallet endpoints also accept the owner EOA directly and combine its Safe, proxy, and deposit wallets in one response; see [Owner addresses](/data/overview#owner-addresses). **If you call the Polymarket CLOB directly (without our SDK):** you need to implement ERC-7739 TypedDataSign wrapping for `signatureType: 3` orders. See the [signing details](#how-poly_1271-signing-works) below. ## How to detect wallet type For trading, the SDK auto-detects wallet type when you call `ensureReady()` or `detectWalletType()`. Detection checks on-chain in this order: 1. Safe deployed? -> `POLY_GNOSIS_SAFE` (type 2) 2. Proxy deployed? -> `POLY_PROXY` (type 1) 3. Deposit wallet deployed? -> `POLY_1271` (type 3) 4. Nothing deployed -> defaults to `POLY_GNOSIS_SAFE` (new Safe will be created) This controls how the SDK signs orders. The `/resolve` identity endpoint uses a different rule for compatibility with Polymarket's deposit-wallet migration: if a resolved EOA has a deployed deposit wallet, `/resolve` returns that deposit wallet in `safe`. That list describes the general server-signer trader. The dedicated `BrowserUserOwnedSession` used by [Connect Wallet to order](/sdks/user-owned-web-app) defaults a new injected-wallet session to type 3, supports an explicit type 0 EOA, and preserves an existing type 2 Safe through the backend-vault model. ```typescript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...' }); const status = await trader.ensureReady(privateKey); console.log(status.signatureType); // 2 = Safe (existing user) // 3 = Deposit wallet (new user) // Either way, order() works the same: await trader.order({ tokenId: '...', side: 'BUY', price: 0.55, size: 100 }); ``` ## How to handle mixed user bases If your platform has existing Safe users and new deposit wallet users, no special handling is needed. The SDK stores each user's wallet type in the local database and uses the correct signing method automatically. ```typescript theme={null} // User A: existing Safe wallet await trader.ensureReady(userA_privateKey); // status.signatureType === 2, uses standard EIP-712 await trader.order({ tokenId: '...', side: 'BUY', price: 0.5, size: 50 }); // User B: new deposit wallet await trader.ensureReady(userB_privateKey); // status.signatureType === 3, uses ERC-7739 TypedDataSign wrapper await trader.order({ tokenId: '...', side: 'BUY', price: 0.5, size: 50 }); // Same API, different signing under the hood ``` ## Wallet address resolution Current deposit wallets can use either the earlier standalone UUPS deployment or the active factory beacon. Resolve the current address against Polygon before funding it. The older synchronous `deriveDepositWalletAddress()` / `derive_deposit_wallet_address()` helpers derive only the legacy UUPS address and are deprecated for live wallet selection. ```typescript TypeScript theme={null} import { deriveSafeAddress, resolveDepositWalletAddress } from 'polynode-sdk'; import { createPublicClient, http } from 'viem'; import { polygon } from 'viem/chains'; const eoa = '0xA60601A4d903af91855C52BFB3814f6bA342f201'; const provider = createPublicClient({ chain: polygon, transport: http(process.env.POLYGON_RPC_URL), }); const depositWallet = await resolveDepositWalletAddress(provider, eoa); const safe = await deriveSafeAddress(eoa); ``` ```python Python theme={null} import os from polynode.trading import resolve_deposit_wallet_address, derive_safe_address eoa = "0xA60601A4d903af91855C52BFB3814f6bA342f201" deposit_wallet = await resolve_deposit_wallet_address( eoa, rpc_url=os.environ["POLYGON_RPC_URL"], ) safe = derive_safe_address(eoa) ``` ```rust Rust theme={null} use polynode::trading::{ derive_safe_address, resolve_deposit_wallet_address, Address, }; let eoa: Address = "0xA60601A4d903af91855C52BFB3814f6bA342f201".parse()?; let rpc_url = std::env::var("POLYGON_RPC_URL")?; let deposit_wallet = resolve_deposit_wallet_address(eoa, &rpc_url).await?; let safe = derive_safe_address(eoa); ``` Both possible deposit addresses are deterministic for an EOA, but the factory's current beacon state determines which address is active. A deployed legacy UUPS wallet remains authoritative. ## The /resolve endpoint The [Resolve Wallet](/api-reference/wallets/resolve) endpoint keeps the same fields and prioritizes deposit wallets in the existing `safe` field. The field name remains `safe` for backward compatibility. ```bash theme={null} curl "https://api.polynode.dev/v1/resolve/0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40" \ -H "x-api-key: YOUR_KEY" ``` ```json theme={null} { "safe": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "eoa": "0xa60601a4d903af91855c52bfb3814f6ba342f201", "username": null, "type": "deposit_wallet", "wallets": { "deposit_wallet": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "safe": null, "proxy_wallet": null }, "wallet_details": [ { "address": "0x8b60bf0f650bf7a0d93f10d72375b37de18f8c40", "wallet_type": "deposit_wallet", "deployed": true, "current": true } ] } ``` The `safe` field contains the preferred trading wallet address. If the controlling EOA has a deployed deposit wallet, `safe` is the deposit wallet. Otherwise it is the existing Safe/proxy wallet. The `type` field tells you which kind of wallet was returned. `deployed` and `current` are separate booleans in `wallet_details`, so an address can still be identified as a deposit wallet before its contract is deployed. | `type` value | Description | | - | - | | `"safe"` | Gnosis Safe proxy (most existing accounts) | | `"deposit_wallet"` | Deposit wallet (newer accounts) | | `"proxy"` | Legacy proxy wallet | Both forward resolution (EOA -> wallet) and reverse resolution (wallet -> EOA) work for all wallet types. When both a Safe and deposit wallet exist, deposit wallet wins. ## How POLY\_1271 signing works > [!NOTE] > > You only need this section if you're implementing signing without the polynode SDK. If you use `signV2Order()` or `trader.order()`, this is handled automatically. For deposit wallet users, V2 orders use `signatureType: 3` (POLY\_1271). The signing process wraps the standard Order EIP-712 hash in a Solady TypedDataSign struct: 1. Build the standard V2 Order struct (same fields as type 0/1/2) 2. Set `maker` and `signer` to the **deposit wallet address** (not the EOA) 3. Sign using `TypedDataSign` as the EIP-712 primary type under the exchange domain, with the deposit wallet parameters as struct fields 4. Wrap the resulting signature: `innerSig (65 bytes) + appDomainSeparator (32 bytes) + contentsHash (32 bytes) + orderTypeString (186 bytes) + typeStringLength (2 bytes)` The final wrapped signature is 317 bytes (634 hex chars + "0x" prefix = 636 total). Orders on [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2) use the same `signatureType: 3` wrapping. Only the exchange domain differs: version `"3"` with ExchangeV3 (`0xe3333700cA9d93003F00f0F71f8515005F6c00Aa`) as the verifying contract, so `appDomainSeparator` is ExchangeV3's. The SDK handles this from TypeScript 0.15.0, Python 0.15.0 and Rust 0.18.0. The `TypedDataSign` struct includes the deposit wallet's identity: * `name`: `"DepositWallet"` * `version`: `"1"` * `verifyingContract`: the deposit wallet address * `salt`: `bytes32(0)` ## FAQ > [accordion] Do existing Safe wallet users need to change anything? > > No. Safe wallets continue to work exactly as before. The SDK detects your wallet type automatically. All existing integrations are backward compatible. > [accordion] Will my /resolve API responses break? > > No. No existing field was renamed or removed. The endpoint still returns `safe`, `eoa`, `username`, `type`, and `wallets`; `wallet_details` is additive. > [accordion] Can I still create new Safe wallets? > > Yes. The general server-signer trader defaults to a Safe when no wallet is > detected on-chain. The specialized injected-wallet user-owned session instead > defaults to an order-capable deposit wallet and completes its readiness flow > through the connected wallet. Choose the documented entry point deliberately; > neither silently changes an existing account type. > [accordion] What SDK version do I need? > > For current beacon-aware resolution, wallet-owned authorization, and full > onboarding, use TypeScript `polynode-sdk >= 0.14.1`, Python > `polynode >= 0.14.0`, or Rust `polynode >= 0.17.0` with the `trading` > feature. These releases also include the complete browser-signing flow in > [Connect Wallet to order](/sdks/user-owned-web-app). > [accordion] What if a user has both a Safe and a deposit wallet? > > For `/resolve`, the deposit wallet is returned in `safe` when it is deployed. The field name stays `safe` so existing clients do not need to parse a new field. `wallet_details` lists both addresses and shows which one is current and whether each is deployed. > [accordion] Do deposit wallets work with V1 orders? > > No. POLY\_1271 (signature type 3) is V2 only. V1 orders only support types 0 (EOA), 1 (POLY\_PROXY), and 2 (POLY\_GNOSIS\_SAFE). Since Polymarket's V2 exchange is now live, all new activity uses V2. > [accordion] How do I know which wallet type to use for copy trading? > > Register followers with their actual `sig_type` (2 for Safe, 3 for deposit wallet). The copy trading engine automatically generates the correct typed data for each follower's wallet type. Your signing code should use `signV2Order()` from the SDK, which handles both types transparently. > [accordion] Is there a performance difference? > > Deposit wallet signatures are larger (317 bytes vs 65 bytes) due to the ERC-7739 wrapping, but this has no meaningful impact on order submission speed or gas costs. The CLOB processes both types identically. # Errors Source: https://docs.polynode.dev/guides/errors Error format, status codes, and troubleshooting. All errors return a JSON object with an `error` field. ## Error format ```json theme={null} { "error": "Human-readable error message." } ``` ## Status codes | Code | Meaning | When | | - | - | - | | 200 | OK | Successful request | | 201 | Created | API key generated successfully | | 400 | Bad Request | Invalid parameters (e.g. bad candle resolution, missing `q` param) | | 401 | Unauthorized | Missing or malformed API key | | 403 | Forbidden | API key is invalid or inactive | | 404 | Not Found | Market, wallet, or token not found | | 429 | Too Many Requests | Rate limit exceeded | | 500 | Internal Server Error | Server-side error | | 503 | Service Unavailable | Service temporarily unavailable | ## Common errors ### Missing API key ```json 401 theme={null} { "error": "Missing or invalid API key. Use x-api-key header or ?key= param." } ``` **Fix**: Include your API key as a header (`x-api-key: pn_live_...`) or query parameter (`?key=pn_live_...`). ### Invalid API key ```json 403 theme={null} { "error": "Invalid or inactive API key." } ``` **Fix**: Verify your key is correct. Keys cannot be retrieved after creation — generate a new one if lost. ### Rate limited ```json 429 theme={null} { "error": "Rate limit exceeded. Retry after 1772500060." } ``` **Fix**: Wait until the timestamp, or reduce request frequency. Default limit is 120 requests per minute. ### Market not found ```json 404 theme={null} { "error": "Market 0x123... not found" } ``` **Fix**: Verify the token ID. Use `/v1/search` to find the correct token. ### Invalid resolution ```json 400 theme={null} { "error": "Invalid resolution. Use: 1m, 5m, 15m, 1h, 4h, 1d" } ``` ### Missing search query ```json 400 theme={null} { "error": "Missing required query parameter 'q'" } ``` ### Key generation rate limit ```json 429 theme={null} { "error": "Too many key generation requests. Max 3 per hour." } ``` ## WebSocket disconnections The server may close your WebSocket connection for any of these reasons: | Reason | Trigger | What to do | | - | - | - | | **Pong timeout** | No Pong response for 90 seconds (3 missed Ping frames) | Ensure your read loop is not blocked — standard WS libraries handle Pong automatically | | **Send buffer full** | Client is consuming messages too slowly | Increase processing speed or reduce subscription scope with filters | | **Invalid API key** | Key rejected during connection upgrade | Verify your `pn_live_` key is correct and active | | **Server restart** | API binary redeployed or service restarted | Reconnect with exponential backoff (see [best practices](/guides/best-practices)) | In all cases, the server closes the connection without a close frame. Implement reconnection with exponential backoff as described in the [WebSocket overview](/websocket/overview#reconnection). # Fee Escrow Source: https://docs.polynode.dev/guides/fee-escrow Optional per-order fee collection with on-chain escrow, refund on cancel, and affiliate revenue sharing. ## Overview The Fee Escrow lets platforms charge a fee on trades placed through the polynode SDK. Fees are optional, per-order, and fully on-chain. The system uses an escrow model: fees are pulled before order placement and either distributed on fill or refunded on cancel. Users never lose fees on unfilled orders. **Key properties:** * Fees are opt-in. Set `feeBps: 0` to skip the escrow entirely. * Each order gets its own escrow entry with an independent affiliate and split. * If the operator doesn't settle within 72 hours, the user can self-refund on-chain. * All escrow operations are gasless via Polymarket's relayer. > [!NOTE] > > **This is your platform's fee — separate from anything Polymarket charges.** > > A user trading through your SDK may pay three distinct fees, each collected by a different system: > > | Fee | Who charges it | Where it's set | How it's collected | > | - | - | - | - | > | **Polymarket protocol fee** | Polymarket | V1 Order struct `feeRateBps` field. V2 has no per-order fee slot. | Taken by the CLOB at settlement, goes to Polymarket's treasury | > | **Polymarket builder rev share** (V2 only) | Polymarket | V2 Order struct `builder` bytes32 field | Polymarket reads the field from the `OrderFilled` event and pays the builder rev share off-chain | > | **Your platform fee** (this guide) | Your platform | `feeConfig.feeBps` in the polynode SDK | Pulled from the user's collateral into our FeeEscrow contract before the order reaches the CLOB | > > All three are independent. `feeBps: 0` turns off **your** platform fee only — it does not waive Polymarket's protocol fee or builder rev share. Setting your `feeBps` does not change anything inside the signed CLOB Order struct. ## Frequently Asked Questions > [accordion] How does the contract know how much to distribute? > > It doesn't know anything about the Polymarket order. The amount is locked at deposit time. When `pullFee` is called, the contract stores `escrows[orderId].amount = feeAmount`. That number is immutable. `distribute` sends from that stored amount. `refund` sends back whatever's left. The contract just moves money between three fixed addresses: the escrow pool, the affiliate wallet, and the treasury. > [accordion] What stops someone else from taking my fee out of the contract? > > Three access controls, each with a single hardcoded destination: > > * **`distribute()`** requires `onlyAuthorized` (our operator wallet or contract owner). Sends funds only to the `affiliate` and `treasury` addresses stored at deposit time. Anyone else calling it gets `Unauthorized`. > * **`refund()`** also requires `onlyAuthorized`. Sends funds only back to the original `payer`. > * **`claimRefund()`** can be called by anyone, but the contract checks `msg.sender == escrow.payer` and `block.timestamp > pulledAt + 72 hours`. Only the original payer can claim, and only after 72h. Funds go exclusively to `escrow.payer`. > > The affiliate address and share split are signed by the user in the EIP-712 FeeAuth message and stored on-chain at deposit time. Nobody can change them after deposit. The user signed it, the contract stored it, and that's where the money goes. > [accordion] Where exactly does the money go when distributed? > > The contract splits every distribution into two transfers: > > * `affiliateShareBps / 10000` of the amount goes to the `affiliate` address (your wallet). > * The remainder goes to the `treasury` address (set by the contract owner). > > If `affiliateShareBps` is `10000` (the default), you keep 100% and nothing goes to the treasury. Both addresses are immutable for each escrow entry. > [accordion] What if the order never fills? How does the fee get returned? > > Three independent paths back to the user, any one of which is sufficient: > > 1. **Inline refund on cancel.** When you call `cancelOrder()` or `cancelAll()`, our cosigner automatically calls `refund()` in the same request. The collateral returns to the user's wallet immediately. > 2. **Lifecycle refund.** Our background service checks pending escrow orders every 30 seconds using on-chain verification. If an order has no fills after 72 hours, it calls `refund()` automatically. > 3. **User self-refund.** After 72 hours, the user (or anyone on their behalf) can call `claimRefund(orderId)` directly on the contract. No involvement from us needed. Funds go to the original payer, always. > > These three paths are completely independent. If our backend is down, path 3 still works. If the user is offline, paths 1 and 2 still work. > [accordion] Can money get permanently stuck in the contract? > > No. Every escrowed fee has exactly two possible exits, and at least one is always available: > > * **Distribute** sends it to the affiliate and treasury. > * **Refund / claimRefund** sends it back to the payer. > > There is no expiration that burns funds. There is no third destination. If all automated paths fail, the contract owner has `emergencyWithdraw` as a last resort. And `claimRefund` is always available to the payer after 72 hours with zero dependencies on our infrastructure. > [accordion] Is there any edge case where a cancelled order doesn't get refunded? > > The only scenario where a refund doesn't happen automatically: our cosigner is down at the moment of cancellation AND the lifecycle service is also down AND the user doesn't call `claimRefund` themselves after 72 hours. In that case the funds sit in the contract, untouched, until someone acts. They don't disappear, they don't move, and no one else can take them. The moment any one of those three systems comes back online, the refund happens. > [accordion] How does partial fill distribution work? > > Our lifecycle service checks on-chain `OrderFilled` events every 30 seconds. Each partial fill emits an event with the exact amount filled. The service sums all fills, computes the fill fraction against the original order size, and distributes only the new portion since the last check. The contract tracks cumulative distributed amounts and caps at the total, so there's no risk of over-distribution even if our math has a rounding error. Undistributed remainder is refunded after the 72-hour timeout. > [accordion] How does the system verify that an order actually filled? > > Pure on-chain verification. The CLOB order ID is the EIP-712 hash of the signed order, and that same hash appears in every matching on-chain `OrderFilled` event. Our lifecycle queries `eth_getLogs` with that hash across all Polymarket V2 exchange contracts. If the event exists on the blockchain, the fill happened. If it doesn't exist, it didn't. No API calls, no authentication, no trust assumptions. Immutable blockchain state is the source of truth. ## V1 and V2 — which one do I use? Two contracts are live. Both are fully supported; neither is being deprecated. | You're trading on… | Use | Collateral token | | - | - | - | | **V1 CLOB** (`clob.polymarket.com`) | **FeeEscrow V1** `0xa11D28433B79D0A88F3119b16A090075752258EA` | USDC.e | | **V2 CLOB** (`clob-v2.polymarket.com`) | **FeeEscrow V2** `0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F` | pUSD | The two contracts have byte-identical calldata, identical function signatures, and identical behavior. The only differences are the collateral token (USDC.e vs pUSD) and the EIP-712 domain name / version. If you're writing a new V2 integration you do not need to support V1 — just point at the V2 contract and sign against the V2 domain. Existing V1 integrations keep working unchanged — no migration required. Orders on [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2), a separate and newer change from the V2 CLOB above, use FeeEscrow V2 and pUSD as well. Nothing changes in your fee setup. ## How It Works ``` 1. User signs EIP-712 fee authorization (off-chain, free) 2. Operator calls pullFee → collateral moves from user's Safe to escrow 3. Order goes to Polymarket CLOB (unchanged, builder creds preserved) 4. On fill → operator calls distribute → fee splits to treasury + affiliate On cancel → operator calls refund → collateral returns to user's Safe On timeout (72h) → user calls claimRefund → collateral returns automatically ``` The fee escrow is completely independent from the Polymarket order flow. Builder credentials, order signing, and CLOB submission are unchanged. The fee is a separate ERC-20 transfer (USDC.e on V1, pUSD on V2) that happens before the order. ## Contract addresses Both contracts are on Polygon mainnet (chain ID 137), both use the same 72-hour self-refund window, and both have the same `FEE_AUTH_TYPEHASH`. ### V1 — USDC.e collateral (V1 CLOB) | Field | Value | | - | - | | **Address** | `0xa11D28433B79D0A88F3119b16A090075752258EA` | | **Collateral** | USDC.e `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` (6 decimals) | | **EIP-712 domain** | `name="PolyNodeFeeEscrow"`, `version="1"`, chainId 137 | ### V2 — pUSD collateral (V2 CLOB, live 2026-04-24) | Field | Value | | - | - | | **Address** | `0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F` | | **Collateral** | pUSD `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` (6 decimals) | | **EIP-712 domain** | `name="PolyNodeFeeEscrowV2"`, `version="2"`, chainId 137 | ## Setup Users need one additional ERC-20 approval for the escrow contract — USDC.e for V1, pUSD for V2. This is added to the existing approval batch during wallet setup (7th approval, gasless, batched with the 6 Polymarket approvals). ```typescript theme={null} // V1: ensureReady() approves USDC.e for the V1 FeeEscrow alongside // the six Polymarket approvals. No manual setup needed. const status = await trader.ensureReady(privateKey); ``` For V2, set `exchangeVersion: "v2"` in your `TraderConfig` (TypeScript), `exchange_version=ExchangeVersion.V2` (Python), or `exchange_version: ExchangeVersion::V2` (Rust). `ensureReady()` then approves pUSD for the V2 FeeEscrow contract as part of the same gasless Safe approval batch as V1 does for USDC.e. Supported from SDK versions: `polynode-sdk@0.9.2` (TypeScript), `polynode==0.9.2` (Python), `polynode = "0.12.2"` (Rust). ## Fee Authorization (EIP-712) The user signs a typed message authorizing a specific fee amount for a specific order. This prevents anyone from pulling more than the user agreed to. The `FeeAuth` struct is identical across V1 and V2 — only the domain changes. ```typescript theme={null} // V1 domain (USDC.e collateral) { name: "PolyNodeFeeEscrow", version: "1", chainId: 137, verifyingContract: "0xa11D28433B79D0A88F3119b16A090075752258EA" } // V2 domain (pUSD collateral) { name: "PolyNodeFeeEscrowV2", version: "2", chainId: 137, verifyingContract: "0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F" } // FeeAuth struct — same for V1 and V2 { orderId: bytes32, // unique order identifier payer: address, // user's Safe wallet (where collateral is pulled from) signer: address, // user's EOA (signs this message) feeAmount: uint256, // fee amount (6 decimals — USDC.e on V1, pUSD on V2) deadline: uint256, // unix timestamp — authorization expires after this nonce: uint256 // signer's current nonce (prevents replay) } ``` ### Selecting V2 at submit time The polynode cosigner routes every fee request to V1 by default. To use V2, include the contract address in the `fee_auth` body of your `/submit` call: ```jsonc theme={null} // POST /submit to trade.polynode.dev { "method": "POST", "path": "/order", "body": "...", // V2 CLOB order body "headers": { ... }, // CLOB L2 HMAC headers "fee_auth": { "escrow_contract": "0x3A43D88ef8Aae4dF5a50B3abf67122CAAeEF7c9F", // ← routes to V2 "escrow_order_id": "0x...", "payer": "0xSafe...", "signer": "0xEOA...", "fee_amount": "27500", "deadline": 1777000000, "nonce": 0, "signature": "0x...", // signed against the V2 domain above "affiliate": "0xPartnerWallet...", "affiliate_share_bps": 10000 } } ``` Omit `escrow_contract` (or set it to the V1 address) to use V1. Any other value falls through to V1, where the signature check will fail because the V2 domain separator won't match — you'll get an `InvalidSignature` revert rather than funds going to the wrong place. ## Order Types Every order type works with the escrow. The fee is pulled before submission and settled based on the order outcome. ### Limit Buy (GTC, resting) Order rests on the book. Fills at any point in the future distribute the fee normally. If cancelled before fill, the fee is refunded. Orders resting past 72 hours are covered explicitly in the [72-Hour Safety Net](#72-hour-safety-net) section below. ``` pullFee($0.005) → order BUY 5 @ $0.20 → cancel → refund($0.005) ↳ user gets fee back ``` Verified on Polygon — order `0x39cb2d...` placed at 20c, cancelled, fee refunded. Safe net change: \$0.00. ### Market Buy (fills immediately) Order fills instantly. Fee is distributed to treasury. ``` pullFee($0.005) → order BUY 5 @ $0.36 → fills → distribute($0.005) ↳ 5 shares for $1.80 ↳ treasury receives fee ``` Verified on Polygon — matched, making=\$1.80 taking=5 shares. Fee distributed to treasury. ### Limit Sell (GTC, resting) Same flow as limit buy. Rests on book, refunded on cancel. ``` pullFee($0.005) → order SELL 5 @ $0.45 → cancel → refund($0.005) ``` Verified on Polygon — order `0x71f943...` placed at 45c, cancelled, fee refunded. ### Market Sell (fills immediately) ``` pullFee($0.005) → order SELL 5 @ $0.35 → fills → distribute($0.005) ``` Verified on Polygon — matched, fee distributed. ### Batch Cancel Multiple resting orders can be cancelled at once. Each gets its own refund. ``` pullFee(order_a) → place order A pullFee(order_b) → place order B cancelAll() refund(order_a) refund(order_b) ``` Verified on Polygon — 2 orders cancelled via `cancelAll()`, both fees refunded. ### No Fee (Opt-Out) If `feeBps` is 0, the SDK skips the escrow entirely. The order goes straight to the CLOB with no fee interaction. Existing behavior is completely unchanged. ## Affiliate Revenue Sharing Each order can specify an affiliate address and their share of the fee. The split is set per-order, so different partners can have different rates. ```typescript theme={null} // Example: partner keeps 90% of a $0.10 fee pullFee({ orderId: "0x...", feeAmount: 100000, // $0.10 affiliate: "0xPartnerWallet...", affShareBps: 9000, // 90% to partner }) // On distribute: // Partner receives: $0.090 // Treasury receives: $0.010 ``` | Split | Treasury | Affiliate | | - | - | - | | `affiliateShareBps: 10000` (default — you keep 100%) | \$0.00 | \$0.10 | | `affiliateShareBps: 7000` (share 30% with polynode) | \$0.03 | \$0.07 | | `affiliateShareBps: 5000` (50/50 split) | \$0.05 | \$0.05 | All splits verified on Polygon mainnet with real USDC transfers. ## Partial Fills If an order partially fills, the fee is proportionally distributed. The remainder stays in escrow until the order fully fills or is cancelled. ``` pullFee($0.20) → distribute(30%) → $0.06 to treasury → distribute(40%) → $0.08 to treasury → refund(rest) → $0.06 back to user ``` Verified on Polygon — partial fills distribute proportionally, refund returns the exact remainder. ## 72-Hour Safety Net The escrow contract has a 72-hour timeout. After that window, the user can always get their undistributed fee back. ```solidity theme={null} // After 72 hours, anyone can call this escrow.claimRefund(orderId); // → undistributed USDC returns to the payer's Safe, always ``` Three things to know: 1. **The transfer target is hardcoded.** `claimRefund` always sends funds back to the original payer, no matter who calls it. Nobody can steal anyone else's fee. The reason anyone can trigger it (not just the payer) is purely so a bot or a friend can help a user recover funds if the user is offline. 2. **This is a fail-safe, not the expected path.** It exists so that if our backend goes down, gets paused, or disappears entirely, users are guaranteed to get their escrowed money back without needing us. Most users will never know the function exists, and most will never call it. 3. **It does not fire automatically.** The timeout doesn't trigger anything on its own — it just unlocks the *option* for the user (or anyone acting on their behalf) to reclaim the fee. If nobody calls `claimRefund`, the escrow sits untouched and `distribute` / `refund` continue to work normally, forever. ### What this means for limit orders resting on the book This is the scenario to understand clearly. A limit order can rest on the CLOB for as long as needed. The 72-hour timeout starts when the fee is pulled, not when the order fills. Here is exactly what happens at each boundary: | Situation | Behavior | | - | - | | Order fills within 72h | Operator calls `distribute` — funds flow to treasury and affiliate normally. Nothing unusual. | | Order cancelled within 72h | Operator calls `refund` — full fee returns to the user. Nothing unusual. | | Order still resting at hour 72, user does nothing | Escrow sits untouched. When the order eventually fills — minute 73, day 5, month 2 — operator calls `distribute` and funds flow normally. Everyone is paid. | | Order still resting at hour 72, user calls `claimRefund` | User gets their fee back. If the order then fills later, the fill is effectively fee-free. The builder gives up the fee on that one order; nothing else breaks. | In practice, virtually no user will invoke `claimRefund` while their own order is still trying to fill. They'd have no reason to — they placed the order because they wanted the trade. The timeout exists as a safety valve for the case where the operator is *unable* to settle (outage, pause, shutdown), not as a routine workflow step. ### Practical guidance for builders * If you charge fees on orders expected to fill quickly (aggressive limits near midprice), the 72h window is a non-issue. * If you charge fees on long-dated limits that commonly rest for days, you can either accept that a fully-informed user has an escape hatch, or skip the fee on those specific orders by passing `feeBps: 0`. * If you really want to keep fee coverage alive on a long-resting order, the operator can proactively `refund` before hour 72 and re-pull a fresh signature from the user with a new nonce. This is a manual flow and most builders won't need it. Funds are never permanently locked, never routed to a third party, and never surprised away from either the user or the builder during the normal fill path. ## Security **V1** has been through three independent security audits and 57 Foundry tests covering unit, fuzz, and adversarial scenarios. **V2** is a strict two-change diff from V1 (collateral token address + EIP-712 domain strings). Every other line of the contract is byte-identical to the audited V1 source. Verification against the deployed V2 contract on Polygon mainnet: 8/8 fork tests pass (pullFee, distribute 30/70 split, refund, 72h claimRefund, and every revert path — expired deadline, wrong nonce, tampered signature). Tests impersonate a real on-chain pUSD holder to fund the payer. Both versions enforce the same invariants: * **Signature malleability** — rejected (secp256k1 s-value upper bound check) * **Replay attacks** — prevented by per-signer sequential nonces * **Affiliate share overflow** — capped at 10000 bps (100%) * **Self-referential payer** — blocked (payer cannot be the escrow contract) * **ecrecover(0)** — rejected explicitly * **Operator compromise** — operator can be revoked by Safe owner instantly * **Stuck funds** — 72-hour user self-refund + owner emergency withdraw ## SDK Integration Enable fee collection with a single config option. Everything else is automatic. ### Basic Setup ```typescript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...', feeConfig: { feeBps: 50, // 0.5% fee on every order affiliate: '0xYourWallet...', // REQUIRED: your wallet that receives the fee }, }); ``` The `affiliate` field is **required** when `feeBps > 0`. This is the wallet where your fees are sent. By default, you keep 100% of the fee. If you want to share a portion with the polynode treasury, set `affiliateShareBps` to less than 10000: ```typescript theme={null} feeConfig: { feeBps: 50, affiliate: '0xYourWallet...', affiliateShareBps: 7000, // optional: keep 70%, share 30% with polynode } ``` When `feeConfig` is set with `feeBps > 0`, every order automatically: 1. Calculates the fee from the order's price and size 2. Signs an EIP-712 authorization (free, off-chain) 3. Pulls the fee into escrow before the order reaches the CLOB 4. Refunds the fee automatically if the order is cancelled ### Fee Calculation The fee is calculated as: ``` feeAmount = floor(price × size × 1e6 × feeBps / 10000) ``` For example, BUY 10 shares at \$0.55 with `feeBps: 50`: ``` floor(0.55 × 10 × 1e6 × 50 / 10000) = 27500 raw USDC = $0.0275 ``` ### Placing an Order with Fees ```typescript theme={null} // Initialize wallet (one-time setup — handles Safe deploy + all 7 approvals including escrow) const status = await trader.ensureReady(privateKey); console.log('Wallet ready:', status.funderAddress); // Send USDC.e to status.funderAddress before placing orders // Find a market const results = await fetch('https://api.polynode.dev/v1/search?q=hungary', { headers: { 'x-api-key': 'pn_live_...' }, }).then(r => r.json()); const market = results.results[0]; console.log(market.question, '→ token:', market.token_ids[0]); // Check the orderbook const book = await fetch(`https://api.polynode.dev/v1/orderbook/${market.token_ids[0]}`, { headers: { 'x-api-key': 'pn_live_...' }, }).then(r => r.json()); console.log('Best bid:', book.bids[0]?.price, 'Best ask:', book.asks[0]?.price); // Place order — fee escrow happens automatically const result = await trader.order({ tokenId: market.token_ids[0], side: 'BUY', price: 0.02, // well below best ask, will rest on book size: 10, }); console.log('Order ID:', result.orderId); console.log('Fee TX:', result.feeEscrowTxHash); // on-chain pullFee transaction console.log('Fee:', result.feeAmount, 'USDC'); // fee amount charged ``` The response includes `feeEscrowTxHash` (the on-chain transaction that moved USDC into escrow) and `feeAmount` (how much was charged). ### Cancelling (Auto-Refund) ```typescript theme={null} if (result.orderId) { const cancel = await trader.cancelOrder(result.orderId); console.log('Cancelled:', cancel.canceled); } // Fee is automatically refunded on-chain — no extra call needed ``` When you cancel an order that had a fee, the refund happens inline during the cancel. The USDC returns to your Safe wallet in the same request. No polling, no background jobs needed. `cancelAll()` also triggers refunds for every cancelled order that had a fee. ### Per-Order Fee Override Override the global `feeConfig` on individual orders: ```typescript theme={null} // This order uses a different fee rate and affiliate const result = await trader.order({ tokenId: '...', side: 'BUY', price: 0.55, size: 100, feeConfig: { feeBps: 100, // 1% for this order affiliate: '0xSpecialPartner...', affiliateShareBps: 5000, // 50/50 split }, }); ``` ### Opting Out Set `feeBps: 0` or omit `feeConfig` entirely. The SDK skips the escrow and the order goes straight to the CLOB with zero overhead. Existing behavior is completely unchanged. ```typescript theme={null} // No fee — identical to pre-escrow behavior const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...' }); ``` ### What the SDK Does Under the Hood When you call `trader.order()` with `feeBps > 0`: ``` SDK Cosigner FeeEscrow CLOB │ │ │ │ │ 1. Calculate fee │ │ │ │ 2. Generate escrowOrderId │ │ │ │ 3. Sign EIP-712 FeeAuth │ │ │ │ │ │ │ │── POST /submit (w/ fee) ───>│ │ │ │ │── pullFee(feeAuth) ──────>│ │ │ │<── tx confirmed ──────────│ │ │ │── forward order ─────────────────────────>│ │ │<── orderId ──────────────────────────────│ │<── { orderId, feeTxHash } ──│ │ │ │ │ │ │ │── DELETE /submit (cancel) ─>│ │ │ │ │── forward cancel ────────────────────────>│ │ │<── canceled ─────────────────────────────│ │ │── refund() ──────────────>│ │ │ │<── tx confirmed ──────────│ │ │<── { canceled } ────────────│ │ │ ``` ### Approvals The escrow contract requires one USDC approval. This is automatically included in the approval batch during `ensureReady()` — the 7th approval alongside the 6 Polymarket approvals. For Safe wallets, it's batched into the same multicall transaction (no extra gas). For EOA wallets, it's one additional approval TX (\~\$0.001 MATIC). # Nonce Exploit Research Source: https://docs.polynode.dev/guides/nonce-exploit Live research on the Polymarket settlement exploit — methodology, on-chain evidence, attacker identification, and detection. polynode monitors every Polymarket settlement in real time, including ones that fail. This page documents our ongoing research into settlement failures caused by the `incrementNonce()` exploit on Polymarket's V1 CTF Exchange. All data on this page is from Polygon mainnet. Every transaction hash is real and verifiable. > [!NOTE] > > **Update — 2026-04-17: Fixed in V2.** The V2 CTF Exchange Order struct removes the `nonce` field entirely (along with `taker`, `expiration`, and `feeRateBps`). With no on-chain nonce to manipulate, `incrementNonce()` no longer exists as an attack surface. V2 cutover is scheduled for April 29, 2026 — at that point, Variant 1 of this exploit becomes structurally impossible. See the [V2 Migration Guide](/guides/v2-migration) for the full Order struct changes. ## Background Polymarket uses a hybrid architecture: orders are matched off-chain by the CLOB (Central Limit Order Book), then settled on-chain by an operator calling `matchOrders` on the CTF Exchange contract. There is a 2-3 second window between when the operator builds the settlement transaction and when it lands in a block. This window is the attack surface. ## The exploit The CTF Exchange contract has a public function called `incrementNonce()` (selector `0x627cdcb9`). Anyone can call it on their own address for less than \$0.10 in gas. When called, it increments the caller's on-chain nonce, which instantly invalidates every outstanding order they have on the exchange. The attack: 1. The attacker places orders on **both sides** of a market (YES and NO) 2. One side gets matched by the CLOB 3. Before the operator's `matchOrders` transaction lands on-chain, the attacker calls `incrementNonce()` on the CTF Exchange 4. The `matchOrders` transaction reverts because the attacker's order nonce no longer matches their on-chain nonce 5. Since `matchOrders` is **atomic** (no try/catch per order), one invalid order kills the entire batch — every other order in that transaction also fails 6. The counterparties who were matched against the attacker get nothing. Their trades evaporate. 7. Polymarket's off-chain system removes all affected orders from the book The attacker keeps their winning side and loses nothing on their losing side. The cost is \~\$0.10 per cycle. ## Two attack variants Our research identified two distinct methods that cause settlement failures: ### Variant 1: Nonce flip The attacker calls `incrementNonce()` directly on the CTF Exchange contract. This is the canonical exploit described in public disclosures. The on-chain call is permanent and auditable — every instance can be traced to a specific wallet and block. ### Variant 2: Balance drain The attacker transfers their USDC out of their wallet between order matching and on-chain settlement. When the operator's `matchOrders` transaction executes, the token transfer fails with `"ERC20: transfer amount exceeds balance"`. The effect is identical — the entire atomic batch reverts, killing all orders in the transaction. This variant does not leave an `incrementNonce()` trace. It manifests as a standard ERC-20 balance error. Polymarket's CLOB validates balances at order placement time, so a balance error at settlement time indicates the funds were moved deliberately in the \~2 second window between matching and settlement. Both variants produce the same outcome: ghost fills. A trade appears to match off-chain but never settles on-chain. ## Live audit: April 9, 2026 ### Settlement failure rate We ran 10 consecutive 30-second monitoring sessions collecting every `matchOrders` transaction from polynode's settlement stream and checking each receipt for revert status. | Metric | Value | | - | - | | **Timestamp** | 2026-04-09 \~06:15 UTC | | **Collection** | 10 rounds x 30 seconds | | **Total matchOrders TXs** | 9,294 | | **Succeeded** | 9,263 | | **Reverted** | 31 | | **Overall failure rate** | 0.334% | A separate scan of 1,000 consecutive blocks (\~33 minutes, blocks 85296314–85297314) found 66,638 total `matchOrders` transactions with 100 reverts (0.150% failure rate). The rate fluctuates between 0% and 1% depending on whether short-term crypto markets are actively resolving. ### Per-round breakdown | Round | TXs | Reverted | Rate | | - | - | - | - | | 1 | 1,091 | 2 | 0.183% | | 2 | 792 | 2 | 0.253% | | 3 | 1,313 | 2 | 0.152% | | 4 | 1,684 | 7 | 0.416% | | 5 | 683 | 7 | 1.025% | | 6 | 557 | 4 | 0.718% | | 7 | 513 | 2 | 0.390% | | 8 | 541 | 3 | 0.555% | | 9 | 1,252 | 2 | 0.160% | | 10 | 868 | 0 | 0.000% | ### Market category breakdown | Category | Reverts | Percentage | | - | - | - | | Short-term crypto (BTC/ETH 5–15 min) | 29 | 93.5% | | Other crypto | 1 | 3.2% | | Other (politics) | 1 | 3.2% | 93.5% of all settlement failures occur in short-term crypto markets. These are the 5-minute and 15-minute BTC/ETH "up or down" markets where the outcome becomes clear in the final seconds, giving the attacker a window to invalidate their losing orders before settlement. ### Revert cause analysis We traced every reverted transaction using `trace_transaction` to decode the exact revert reason. | Revert reason | Count | Variant | | - | - | - | | `ERC20: transfer amount exceeds balance` | 20 | Balance drain | | `SafeMath: subtraction overflow` | 11 | Balance drain | | Total | 31 | | All 31 reverts in this sample produced balance-related errors at the ERC-20 transfer level, consistent with both the nonce flip (which cascades into balance errors when the atomic batch unwinds) and the balance drain variant. ### Attacker identification We scanned 1,800 consecutive blocks (\~1 hour) for all calls to `incrementNonce()` (selector `0x627cdcb9`) on the CTF Exchange contract (`0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E`). **21 `incrementNonce()` calls found in 1 hour. Two wallets responsible for all of them.** #### Attacker 1: `0xe5f5f9bf130f4e0947ab9e79b2ee0ab3f33885f5` * **12 calls** in 1 hour * Calls `incrementNonce()` **directly** on the CTF Exchange (no proxy) * Regular \~150 block cadence (\~5 minutes), matching BTC/ETH short-term market resolution cycles * No Polymarket profile found for this address * **Directly caused 7 of 31 reverted settlements** in our audit (confirmed via same-block correlation) Nonce flip blocks: 85296283, 85296433, 85296583, 85296733, 85296883, 85297033, 85297183, 85297333, 85297483, 85297633, 85297783, 85297933 At block **85297633**, this wallet called `incrementNonce()` in the same block as 3 reverted BTC Up/Down settlements, and 4 more reverted in the next 1–3 blocks as the operator's queued transactions hit the invalidated nonce. #### Attacker 2: `0xfd29d745edaf724bae8ade4f7b3a3465eed3b905` * **7 calls** in 1 hour * Calls `incrementNonce()` through a **Safe proxy wallet** at `0xfc64b6660ed1...` * Similar \~5 minute cadence * Has a Polymarket account and profile page * Attribution to specific reverts pending (proxy routing makes block-level correlation less precise) Nonce flip blocks (via proxy): 85296604, 85296825, 85297016, 85297484, 85297770, 85297921, 85297985 #### Additional callers Two wallets (`0x2df3626c...`, `0xa2b2a759...`) made single `incrementNonce()` calls during the scan period. These may be legitimate order cancellations rather than exploit activity. ### Attribution: nonce flip to settlement failure For the 31 reverted settlements in our audit, we cross-referenced each revert block against the `incrementNonce()` call log: | Attribution | Count | Notes | | - | - | - | | **Confirmed nonce flip** | 7 | `incrementNonce()` call in same block or 1–3 blocks before revert. All from Attacker 1. | | **Unattributed** | 24 | No nearby `incrementNonce()` call. Likely balance drain variant or nonce flip from undetected proxy call. | The 7 confirmed nonce-flip reverts all occurred in BTC Up/Down 2:10–2:15AM ET markets within blocks 85297633–85297636. The 24 unattributed reverts are concentrated in ETH Up/Down markets and revert with balance errors, consistent with the balance drain variant. ### Sample reverted transactions ``` BTC Up/Down 2:10-2:15AM — Nonce flip confirmed (Attacker 1, block 85297633): 0x6694bb41b21ec924d29e8126659db6be34bfa057a9a32f7abbc2fc773855a031 0x727488a9527e0b140e2907e51385d3ef3c1df07bdfa54e2de5bda867b8daeb8a 0x5e20b0d3d6bb59dfa981c75b2e0900c1a9474d5127f4859c88b9a0cd5469ddda ETH Up/Down 2:15-2:30AM — Balance drain (unattributed): 0x1ba2ed39c77e767ae2b000f521e14e618187746520c4385092f083d4871d158d 0x56aec1b48fc1c6e0d7c87e7533d66b4d00537979ab9fb0ce0c87e9a6f6b6f5e4 0xf595c73f55dd2008f5a83855fd44b277ca4cf3468f8e19e155d1cdec584445c6 ``` ## How polynode detects ghost fills polynode detects settlements from the mempool 3–5 seconds before on-chain confirmation. When a `matchOrders` transaction is detected, a pending `settlement` event is emitted. When the block confirms: * If the receipt shows `status: 0x1` (success): a `status_update` event is emitted with `confirmed_fills` containing exact on-chain execution data * If the receipt shows `status: 0x0` (reverted): no `status_update` is emitted. The pending settlement was a ghost fill. To detect ghost fills, track pending settlements that never receive a `status_update`: ```javascript theme={null} const pending = new Map(); ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, { ...msg.data, detected_at: Date.now(), }); } if (msg.type === "status_update") { // Confirmed on-chain — not a ghost fill pending.delete(msg.data.tx_hash); } }; // Check for ghost fills every 5 seconds setInterval(() => { const now = Date.now(); for (const [txHash, data] of pending) { if (now - data.detected_at > 15000) { console.log("Ghost fill:", txHash, data.market_title); pending.delete(txHash); } } }, 5000); ``` For verified trade data, use the `confirmed_fills` field on `status_update` events. See the [Trade Tracking Guide](/guides/trade-tracking) for details on using pending settlements vs confirmed fills. ## Methodology All data was collected using polynode's live settlement stream and Polygon RPC. **Settlement failure rate:** Subscribe to settlements via WebSocket, collect unique `tx_hash` values for a fixed period, wait for block confirmations, batch-query receipts, check `receipt.status`. **Revert cause analysis:** Use `trace_transaction` on reverted TXs to decode the revert reason string from the deepest failing call. **Attacker identification:** Scan all transactions in the block range for calls to `incrementNonce()` (selector `0x627cdcb9`) targeting the CTF Exchange contract (`0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E`) or the NegRisk CTF Exchange. Both direct calls and proxy calls (where the selector appears inside `execTransaction` calldata) are detected. **Attribution:** Cross-reference `incrementNonce()` call blocks against reverted settlement blocks. A revert is "confirmed" if a nonce flip occurred in the same block or 1–3 blocks prior. No mock data is used. All transaction hashes, block numbers, and wallet addresses are from Polygon mainnet. # Polymarket Profile Setup Source: https://docs.polynode.dev/guides/polymarket-profile-setup Let your users create or change their Polymarket username from an EOA wallet without handling private keys. The Polymarket Profile API lets your app set a user's Polymarket username from their EOA wallet. The flow is built for platforms that already have a wallet-connected frontend and a backend that can call PolyNode with an API key. The user signs two payloads in their wallet. Your backend sends the signatures to PolyNode. PolyNode handles the Polymarket profile create or username update. > [!WARNING] > > Never send user private keys to PolyNode. Never expose your PolyNode API key in a browser app. Your backend calls PolyNode. Your frontend only asks the user wallet to sign the returned messages. ## What this does This API can: * check whether a username is available * create a profile for a new EOA-backed Polymarket user * change the username for an existing EOA-backed Polymarket profile * return public profile state for an address This API does not: * upload profile images * link X accounts * enable trading * bypass Polymarket compliance, eligibility, captcha, geoblock, or terms flows * accept private keys or long-lived Polymarket session credentials ## Endpoints | Method | Endpoint | Purpose | | - | - | - | | `GET` | `/v3/polymarket/profiles/username-available` | Check whether Polymarket will accept a username | | `POST` | `/v3/polymarket/profiles/username/challenge` | Create the wallet-signing challenge | | `POST` | `/v3/polymarket/profiles/username/complete` | Submit signatures and create or update the username | | `GET` | `/v3/polymarket/profiles/{address}` | Read public profile state | All endpoints require a paid PolyNode API key. ```bash theme={null} curl "https://api.polynode.dev/v3/polymarket/profiles/username-available?username=alice123" \ -H "x-api-key: pn_live_..." ``` ## The integration flow 1. Your frontend collects the user's EOA address and desired username. 2. Your backend calls `POST /v3/polymarket/profiles/username/challenge`. 3. Your frontend asks the user wallet to sign `challenge.polymarket.message` with `personal_sign`. 4. Your frontend asks the user wallet to sign `challenge.consent` with `eth_signTypedData_v4`. 5. Your backend calls `POST /v3/polymarket/profiles/username/complete` with both signatures. 6. PolyNode logs in to Polymarket with the user-signed SIWE message, creates the profile if needed, and sets the username. The two signatures are intentional: * The Polymarket SIWE signature authorizes sign-in to Polymarket. * The PolyNode consent signature authorizes this specific profile action: address, username, action, challenge id, chain id, and expiration. That prevents a generic login signature from being reused later to mutate a username. ## Backend: create a challenge Your backend owns the PolyNode API key. With the TypeScript SDK: ```ts theme={null} import { PolyNode } from "polynode-sdk"; const pn = new PolyNode({ apiKey: process.env.POLYNODE_KEY || "pn_live_YOUR_KEY" }); // POST /api/polymarket-profile/challenge in your own backend async function createPolymarketProfileChallenge(input) { return pn.v3.createPolymarketUsernameChallenge({ address: input.address, username: input.username, action: "set_username", }); } ``` With raw HTTP: ```ts theme={null} // POST /api/polymarket-profile/challenge in your own backend export async function createPolymarketProfileChallenge(input: { address: string; username: string; }) { const resp = await fetch( "https://api.polynode.dev/v3/polymarket/profiles/username/challenge", { method: "POST", headers: { "content-type": "application/json", "x-api-key": process.env.POLYNODE_KEY || "pn_live_YOUR_KEY", }, body: JSON.stringify({ address: input.address, username: input.username, action: "set_username", }), } ); const body = await resp.json(); if (!resp.ok) { throw new Error(`${body.error}: ${body.message}`); } return body; } ``` Challenge response shape: ```json theme={null} { "challenge_id": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "username": "alice123", "action": "set_username", "expires_at": "2026-05-26T13:03:06Z", "polymarket": { "signature_type": "personal_sign", "message": "polymarket.com wants you to sign in with your Ethereum account:\n0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0\n\nWelcome to Polymarket! Sign to connect.\n\nURI: https://polymarket.com\nVersion: 1\nChain ID: 137\nNonce: 4b7d...\nIssued At: 2026-05-26T12:53:06.000Z\nExpiration Time: 2026-06-02T12:53:06.000Z", "fields": { "domain": "polymarket.com", "address": "0xC3579b0C908F43d50C63951A30C6f72fCEA4F6A0", "statement": "Welcome to Polymarket! Sign to connect.", "uri": "https://polymarket.com", "version": "1", "chainId": 137, "nonce": "4b7d...", "issuedAt": "2026-05-26T12:53:06.000Z", "expirationTime": "2026-06-02T12:53:06.000Z" } }, "consent": { "signature_type": "typed_data_v4", "domain": { "name": "Polynode", "version": "1", "chainId": 137 }, "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" } ], "PolymarketProfileAction": [ { "name": "action", "type": "string" }, { "name": "address", "type": "address" }, { "name": "username", "type": "string" }, { "name": "challengeId", "type": "string" }, { "name": "expiresAt", "type": "uint256" } ] }, "primaryType": "PolymarketProfileAction", "message": { "action": "set_username", "address": "0xc3579b0c908f43d50c63951a30c6f72fcea4f6a0", "username": "alice123", "challengeId": "pmprof_652e85a9839fe3e97348a72ff5018ef5", "expiresAt": 1779800586 } }, "derived": { "deposit_wallet": "0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31", "safe_address": "0xba2ef45d0fe68cee6351420b60fb554bbe91bf02", "safe_deployed": false } } ``` > [!NOTE] > > `expires_at` is an ISO string for display. `consent.message.expiresAt` is a Unix timestamp because it is signed as `uint256` in EIP-712. ## Frontend: ask the wallet to sign With an EIP-1193 wallet provider: ```ts theme={null} type EthereumProvider = { request(args: { method: string; params?: unknown[] }): Promise; }; declare const ethereum: EthereumProvider; const challenge = await fetch("/api/polymarket-profile/challenge", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ address, username }), }).then((r) => r.json()); const polymarketSignature = await ethereum.request({ method: "personal_sign", params: [challenge.polymarket.message, address], }); const consentSignature = await ethereum.request({ method: "eth_signTypedData_v4", params: [ address, JSON.stringify({ domain: challenge.consent.domain, types: challenge.consent.types, primaryType: challenge.consent.primaryType, message: challenge.consent.message, }), ], }); ``` With viem: ```ts theme={null} const challenge = await fetch("/api/polymarket-profile/challenge", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ address, username }), }).then((r) => r.json()); const polymarketSignature = await walletClient.signMessage({ account: address, message: challenge.polymarket.message, }); const { EIP712Domain: _EIP712Domain, ...types } = challenge.consent.types; const consentSignature = await walletClient.signTypedData({ account: address, domain: challenge.consent.domain, types, primaryType: challenge.consent.primaryType, message: challenge.consent.message, }); ``` With ethers v6: ```ts theme={null} import { BrowserProvider } from "ethers"; const browserProvider = new BrowserProvider(window.ethereum); const signer = await browserProvider.getSigner(); const address = await signer.getAddress(); const polymarketSignature = await signer.signMessage( challenge.polymarket.message ); const { EIP712Domain, ...types } = challenge.consent.types; const consentSignature = await signer.signTypedData( challenge.consent.domain, types, challenge.consent.message ); ``` ## Backend: complete the action The complete request must be sent from your backend with the same PolyNode API key that created the challenge. With the TypeScript SDK: ```ts theme={null} export async function completePolymarketProfile(input: { challenge_id: string; address: string; username: string; polymarket_signature: string; consent_signature: string; }) { return pn.v3.completePolymarketUsername(input); } ``` With raw HTTP: ```ts theme={null} // POST /api/polymarket-profile/complete in your own backend export async function completePolymarketProfile(input: { challenge_id: string; address: string; username: string; polymarket_signature: string; consent_signature: string; }) { const resp = await fetch( "https://api.polynode.dev/v3/polymarket/profiles/username/complete", { method: "POST", headers: { "content-type": "application/json", "x-api-key": process.env.POLYNODE_KEY || "pn_live_YOUR_KEY", }, body: JSON.stringify(input), } ); const body = await resp.json(); if (!resp.ok) { throw new Error(`${body.error}: ${body.message}`); } return body; } ``` Complete response: ```json theme={null} { "status": "success", "action": "set_username", "username": "alice123", "address": "0xc3579b0c908f43d50c63951a30c6f72fcea4f6a0", "deposit_wallet": "0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31", "safe_address": "0xba2ef45d0fe68cee6351420b60fb554bbe91bf02", "gamma_user_id": "8313180", "gamma_profile_id": "8391726", "created_profile": true, "changed_username": true, "profile_url": "https://polymarket.com/profile/0xf6d30d58add6c6814d1b086ec543a16ab6cc9a31" } ``` ## Username rules PolyNode validates the username before calling Polymarket: ```text theme={null} ^[A-Za-z0-9_]{3,32}$ ``` Polymarket is still the final authority. A username can pass local validation and still return `available: false`. Recommended UX: 1. Call `username-available` as the user types, with debounce. 2. Disable submit until it returns `available: true`. 3. Re-check availability when creating the challenge. 4. Handle `username_taken` on complete, because another user can claim the username between challenge and completion. ## Security checklist * Keep `POLYNODE_KEY` only on your backend. * Never ask the user for a private key. * Treat `challenge_id` as one-time use. * Submit complete within 10 minutes. * Send complete with the same API key that created the challenge. * Verify on your side that the connected wallet address matches the address in the challenge before asking the wallet to sign. * Do not cache or log raw signatures, SIWE tokens, cookies, or Authorization headers. ## Error codes | Code | Meaning | | - | - | | `invalid_address` | Address is not a valid EVM address | | `invalid_username` | Username failed local validation | | `username_taken` | Polymarket says the username is unavailable | | `challenge_not_found` | Challenge expired, was consumed, or never existed | | `challenge_expired` | Challenge is older than 10 minutes | | `challenge_mismatch` | API key, address, username, action, or challenge id does not match | | `signature_invalid` | One of the wallet signatures cannot be recovered to the challenge EOA | | `safe_already_deployed` | The derived Safe is already deployed but Gamma did not return a user for the session | | `polymarket_login_failed` | Polymarket login rejected the SIWE token | | `polymarket_profile_create_failed` | Profile creation failed upstream | | `polymarket_profile_update_failed` | Username or preference update failed upstream | | `polymarket_compliance_blocked` | Polymarket returned a compliance, auth, or eligibility block | | `upstream_unavailable` | Polymarket, Gamma, or Polygon RPC could not be reached | | `rate_limited` | Profile-specific rate limit exceeded | Error responses use: ```json theme={null} { "error": "username_taken", "message": "Username is not available" } ``` ## Rate limits Profile endpoints have stricter limits than normal data endpoints: | Endpoint | Limit | | - | - | | `username-available` | 5 req/sec per API key, 1 req/sec per username | | `challenge` | 1 req/sec per API key, 5 req/min per EOA | | `complete` | 1 req/sec per API key, 3 req/min per EOA | Responses include the standard PolyNode rate-limit headers: ```text theme={null} x-ratelimit-limit x-ratelimit-remaining x-ratelimit-reset ``` # Polymarket Protocol V2 Markets Source: https://docs.polynode.dev/guides/polymarket-protocol-v2 What Polymarket Protocol V2 is, when new markets move to it, and what it means for your polynode integration. For most integrations, nothing changes. > [!NOTE] > > **Two different "V2"s.** Polymarket has used the name "V2" for two separate upgrades. This page is about the second one. > > | | April 2026 exchange upgrade | Polymarket Protocol V2 | > | - | - | - | > | What changed | The exchange contracts, the order format and the collateral (pUSD) | Where positions live, the exchange every market type trades on, and the ids of new markets | > | Which markets | All markets | Newly created markets | > | When | Live since April 28, 2026 | Test markets since October 5, 2026. New markets from around November 2, 2026 (tentative, per Polymarket) | > | How polynode marks it | `exchange_version: "v2"` on WebSocket trades | `protocol_version: "v2"` on REST rows and WebSocket events | > | Guide | [V2 Migration](/guides/v2-migration) | This page | > > In these docs, Polymarket Protocol V2 is always written out in full. ## What it is Polymarket Protocol V2 is Polymarket's new on-chain system for markets. Polymarket introduced it to run every market type (yes/no, multi-outcome and combos) on one position system and one exchange: * positions live in a new position ledger, **PositionManager**, instead of Conditional Tokens; * every market type trades on one exchange, **ExchangeV3**; * split, merge and redeem go through Polymarket's **Router**; * each market and outcome gets a new id, and results are reported as shares of 1,000,000. Polymarket's combos already run on these contracts, and polynode's [combo stream](/websocket/combos) and combo routes keep working as documented. **Why the name repeats.** Polymarket's market data labels markets on the original position system (Conditional Tokens) as version `v1` and markets on the new system as version `v2`, hence Protocol V2. The April 2026 upgrade was also called "V2" because it replaced the original exchange contracts. They are different layers: April changed the exchange and kept every market and token id, while Protocol V2 changes the position system for new markets. **What does not change.** Markets that exist today stay on the current system and keep their ids. Existing holdings are not converted. Collateral is still pUSD. Polymarket's own description is in its guide [Migrate to Polymarket Protocol V2](https://docs.polymarket.com/migrate/polymarket-v2/overview). This page covers what it means for polynode. ## Dates These are Polymarket's dates. | Date | What happens | | - | - | | October 5, 2026 | Polymarket's Protocol V2 test markets start trading | | October 30, 2026 | The test market period ends | | Around November 2, 2026 (tentative) | Newly created markets move to Polymarket Protocol V2 | polynode handles Protocol V2 markets whenever they appear, so if Polymarket moves a date, there is nothing extra for you to do. ## Do I need to do anything? | You use | What to do | | - | - | | REST API | Nothing. Same endpoints, same response shapes. | | WebSocket | Nothing. Same subscriptions, same event types. | | SDK, reading REST or WebSocket data only | Nothing. Upgrading is optional. | | SDK short-form market discovery or redemption watcher | Upgrade before November 2, 2026, so these helpers handle Protocol V2 markets. | | SDK trading: orders, split, merge or redeem | Upgrade before November 2, 2026. | | Browser or user-owned trading | Upgrade the SDK in both your browser and your server code. | | Your own database | Store outcome ids as strings (up to 78 digits). | SDK versions with Polymarket Protocol V2 support: | SDK | Version | | - | - | | TypeScript | `polynode-sdk` 0.15.0 (npm) | | Rust | `polynode` 0.18.0 (crates.io) | | Python | `polynode` 0.15.1 (PyPI) | ## How to recognise a Protocol V2 market REST rows and WebSocket events for a Protocol V2 market carry two extra fields. They are absent on every other market. | Field | Value | | - | - | | `protocol_version` | `"v2"` | | `module` | `"binary"` for yes/no markets, `"neg_risk"` for multi-outcome markets | Use these fields, not the shape or length of an id, to tell markets apart. The SDKs also provide `getMarketProtocol(id)` (TypeScript) and `get_market_protocol(id)` (Python, Rust), which return `"v1"` or `"v2"`. ### Ids * **Outcome ids** (`token_id` and similar fields) are decimal strings, as today. Protocol V2 ids are usually larger numbers, up to 78 digits. Never parse them as JavaScript numbers or floats. * **Condition ids** are 66 characters (`0x` plus 64 hex characters), as today. Polymarket's contracts and some Polymarket APIs show a Protocol V2 condition id in a shorter 31-byte form (`0x` plus 62 hex characters); the 66-character form is the same value followed by `00`. polynode routes and WebSocket filters that take a condition id accept either form. * The combo stream and combo routes keep their existing 31-byte combo condition ids. ## REST API Protocol V2 markets appear in the same routes as every other market, with the same fields and units. Rows for a Protocol V2 market add: | Field | Value | | - | - | | `protocol_version` | `"v2"` | | `module` | `"binary"` or `"neg_risk"` | | `structural_condition_id` | The market's Protocol V2 condition id (66 characters) | | `neg_risk_event_id` | Multi-outcome markets only: the Protocol V2 event id (60 characters, so it cannot be mistaken for a condition id) | | `payouts_ppm` | Resolved markets only: the exact result as shares of 1,000,000, for example `[1000000, 0]` | `condition_id` equals `structural_condition_id`, with one exception. Polymarket lets a holder move a position from a current market into Protocol V2. Such a position keeps the current market's `condition_id`, so its old and new rows group under one market, and `structural_condition_id` shows its Protocol V2 id. Results keep today's form in `payout_numerators` and `payout_denominator`. For example, `[1, 0]` with `1` means the first outcome won, and `[1, 1]` with `2` is a 50/50 result. `payouts_ppm` carries the same result exactly. While Polymarket's test markets run, they appear in wallet, trade and market-id routes, but not in market listings or search. Their slugs start with `polyv2`. ## WebSocket Protocol V2 markets arrive on the same streams as the same event types. Events for a Protocol V2 market add: | Field | On | Value | | - | - | - | | `protocol_version` | Every event for a Protocol V2 market | `"v2"` | | `module` | Every event for a Protocol V2 market | `"binary"` or `"neg_risk"` | | `exchange_version` | [`trade`](/websocket/events/trade) events and [`settlement`](/websocket/events/settlement) `trades[]` | `"v3"`: settled on ExchangeV3. `"v2"` keeps meaning the April 2026 exchange. | | `payouts_ppm` | [`oracle`](/websocket/events/oracle) results | The exact result as shares of 1,000,000, for example `[1000000, 0]` | | `derived` | [`oracle`](/websocket/events/oracle) results | `true` when a multi-outcome result follows from the rest of its event, not from its own report | `exchange` keeps its two existing values (`ctf_exchange` for yes/no markets and `neg_risk_ctf_exchange` for multi-outcome markets), so typed decoders, including older SDK versions, keep working. Protocol V2 results arrive as `oracle` events with `oracle_type: "condition_resolution"`. `payouts` uses today's form (`[1, 0]`, `[0, 1]`, or `[1, 1]` for a 50/50 result). On these events `question_id` carries the condition id and `adapter_address` the market's Polymarket module contract. The order book stream keeps its message format and adds Protocol V2 markets as Polymarket lists them. ## Trading with the SDK After upgrading, place orders with the same calls as before. The SDK checks each market's protocol (once, then cached) and signs Protocol V2 orders for ExchangeV3 with EIP-712 domain version `"3"`. The order fields are unchanged. If the SDK cannot tell which protocol a market uses, it refuses to sign and returns a retryable error, so no order is sent. Older SDK versions keep working on current markets. Polymarket rejects their orders on Protocol V2 markets, and no funds move. ### Approvals Protocol V2 markets use new approval targets. The first order on a Protocol V2 market sets up what it needs, once. This is gasless for Safe and deposit wallets; an EOA pays a small amount of POL gas. To set them up ahead of time, call `trader.ensureReady(signer, { protocolV2: true })` (TypeScript), `trader.ensure_ready(signer, protocol_v2=True)` (Python) or `trader.ensure_protocol_v2_ready()` (Rust). Existing approvals are not changed or revoked. | Approval | What it allows | | - | - | | pUSD allowance for ExchangeV3 | Buying: the exchange takes pUSD when your order fills | | PositionManager approval for ExchangeV3 | Selling: the exchange moves your shares when your order fills | | pUSD allowance and PositionManager approval for the Router | Split, merge and redeem | | PositionManager approval for AutoRedeemer | Automatic redemption by Polymarket. Only granted if you turn it on with `enableAutoRedeem()` (`enable_auto_redeem()` in Python and Rust) | ### Split, merge and redeem On Protocol V2 markets, split, merge and redeem go through Polymarket's Router; the SDK picks the right path for each market. For redeem, outcome index `0` is the first outcome (Yes, or Up) and `1` is the second. Converting negative-risk positions is not available for Protocol V2 markets; the SDK returns a clear error instead. See [Position management](/guides/position-management). ### Contract addresses (Polygon) | Contract | Address | | - | - | | ExchangeV3 | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | | AutoRedeemer | `0xa1200000d0002264C9a1698e001292D00E1b00af` | | pUSD (unchanged) | `0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB` | ## FAQ > [accordion] Is this the same as the V2 migration in April? > > No. April's upgrade replaced the exchange and moved collateral to pUSD for every market. Polymarket Protocol V2 replaces the position system for newly created markets. See the table at the top of this page. > [accordion] Do my existing positions change? > > No. Current markets keep their ids and stay on the current system. If a holder chooses to move a position into Protocol V2, polynode shows it as a Protocol V2 row for the same market (see the REST API section above). > [accordion] My order on a new market fails with an older SDK > > Upgrade to the versions above. Older versions sign for the April exchange, which Protocol V2 markets do not use. Polymarket rejects those orders and no funds move. > [accordion] Why does a condition id sometimes have 64 characters? > > That is the 31-byte form Polymarket's contracts use. polynode returns the 66-character form and accepts both. Combo condition ids keep their existing 31-byte form. # PolyUSD Guide Source: https://docs.polynode.dev/guides/polyusd How to wrap and unwrap PolyUSD — the collateral token for Polymarket V2. > [!NOTE] > > **This is not Polymarket Protocol V2.** "V2" on this page means Polymarket's April 2026 exchange upgrade (CTF Exchange V2 with pUSD collateral), live since April 28, 2026. Polymarket Protocol V2 is a separate, newer change to how markets are built: test markets since October 5, 2026, and newly created markets from around November 2, 2026 (tentative, per Polymarket). REST and WebSocket users need to do nothing; SDK traders upgrade. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). PolyUSD (pUSD) is the collateral token for Polymarket's V2 exchange system. It is backed 1:1 by USDC and replaces USDC.e as the exchange collateral. To trade on V2, you need PolyUSD. PolyUSD is also the collateral for Polymarket Protocol V2 markets, so nothing on this page changes for them. **Token info:** Name: Polymarket USD | Symbol: pUSD | Decimals: 6 | [View on Polygonscan](https://polygonscan.com/token/0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb) ## How PolyUSD Works According to Polymarket's announcement, PolyUSD is backed 1:1 by USDC. Power users and API traders can wrap either **USDC or USDC.e** into PolyUSD. For most frontend users, the transition is seamless — the Polymarket UI handles wrapping automatically with a one-time approval. There are two wrapping paths: | Path | Contract | Input Token | Status | | - | - | - | - | | **Collateral Onramp** | `0x93070a847efef7f70739046a929d47a521f5b8ee` | USDC.e (bridged) | **Active** — working today | | **PermissionedRamp** | `0xebc2459ec962869ca4c0bd1e06368272732bcb08` | Native USDC (Circle) | **Not active yet** — deployed but zero transactions | Both paths produce the same PolyUSD token. The V2 exchange doesn't care how you obtained your PolyUSD. > [!NOTE] > > The **USDC.e → Onramp** path is what's working right now. We've tested it on mainnet and verified the full flow. The native USDC path via the PermissionedRamp exists on-chain but has not processed any transactions yet. When Polymarket activates it, wrapping native USDC will also be supported. ## Quick Reference | | Address | | - | - | | PolyUSD Token | `0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb` | | Collateral Onramp (USDC.e → PolyUSD) | `0x93070a847efef7f70739046a929d47a521f5b8ee` | | Collateral Offramp (PolyUSD → USDC.e) | `0x2957922eb93258b93368531d39facca3b4dc5854` | | PermissionedRamp (native USDC, not yet active) | `0xebc2459ec962869ca4c0bd1e06368272732bcb08` | | USDC.e (bridged USDC) | `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | | Backing Vault | `0xC417fD8E9661c0d2120B64a04Bb3278C17E99DB1` | ## Wrapping: USDC.e → PolyUSD (Active Path) To get PolyUSD today, wrap your USDC.e through the Collateral Onramp contract. ### Steps 1. **Approve** the Onramp to spend your USDC.e 2. **Call** `wrap(underlyingToken, recipient, amount)` on the Onramp ```javascript Node.js theme={null} import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("YOUR_RPC_URL"); const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const USDC_E = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174"; const ONRAMP = "0x93070a847efef7f70739046a929d47a521f5b8ee"; // 1. Approve Onramp for USDC.e const usdc = new ethers.Contract(USDC_E, [ "function approve(address,uint256) returns (bool)", "function balanceOf(address) view returns (uint256)" ], wallet); await (await usdc.approve(ONRAMP, ethers.MaxUint256)).wait(); // 2. Wrap USDC.e → PolyUSD const amount = await usdc.balanceOf(wallet.address); const wrapData = new ethers.Interface(["function wrap(address,address,uint256)"]) .encodeFunctionData("wrap", [USDC_E, wallet.address, amount]); const tx = await wallet.sendTransaction({ to: ONRAMP, data: wrapData, gasLimit: 300000 }); await tx.wait(); console.log("Wrapped", (Number(amount) / 1e6).toFixed(2), "USDC.e → PolyUSD"); ``` ```python Python theme={null} from web3 import Web3 w3 = Web3(Web3.HTTPProvider("YOUR_RPC_URL")) account = w3.eth.account.from_key("YOUR_PRIVATE_KEY") USDC_E = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174" ONRAMP = "0x93070a847efef7f70739046a929d47a521f5b8ee" # 1. Approve usdc = w3.eth.contract(address=USDC_E, abi=[{ "name": "approve", "type": "function", "inputs": [{"name": "spender", "type": "address"}, {"name": "amount", "type": "uint256"}], "outputs": [{"name": "", "type": "bool"}] }]) tx = usdc.functions.approve(ONRAMP, 2**256 - 1).build_transaction({ "from": account.address, "nonce": w3.eth.get_transaction_count(account.address) }) w3.eth.send_raw_transaction(account.sign_transaction(tx).raw_transaction) # 2. Wrap USDC.e → PolyUSD amount = w3.eth.call({"to": USDC_E, "data": usdc.functions.balanceOf(account.address)._encode_transaction_data()}) amount = int.from_bytes(amount, "big") wrap_data = Web3.keccak(text="wrap(address,address,uint256)")[:4] wrap_data += bytes.fromhex(USDC_E[2:].zfill(64)) wrap_data += bytes.fromhex(account.address[2:].zfill(64)) wrap_data += amount.to_bytes(32, "big") tx = { "from": account.address, "to": ONRAMP, "data": "0x" + wrap_data.hex(), "gas": 300000, "nonce": w3.eth.get_transaction_count(account.address), "gasPrice": w3.eth.gas_price, "chainId": 137, } signed = account.sign_transaction(tx) w3.eth.send_raw_transaction(signed.raw_transaction) print(f"Wrapped {amount / 1e6:.2f} USDC.e → PolyUSD") ``` ### Using the polynode SDK The SDK handles wrapping automatically: ```rust Rust theme={null} // Wrap 1 USDC.e → PolyUSD let tx_hash = trader.wrap_to_polyusd(1_000_000).await?; // Check balance let balance = trader.get_polyusd_balance().await?; ``` ```typescript TypeScript (SDK) theme={null} // Wrap 1 USDC.e → PolyUSD const txHash = await trader.wrapToPolyUsd(1_000_000n); // Check balance const balance = await trader.getPolyUsdBalance(); ``` ```python Python theme={null} # Wrap 1 USDC.e → PolyUSD (wrap_to_polyusd is async) tx_hash = await trader.wrap_to_polyusd(1_000_000) # Balance getter is synchronous (returns raw int) balance_raw = trader.get_polyusd_balance() ``` ### Wrap Function Signature ``` function wrap(address underlyingToken, address recipient, uint256 amount) ``` * `underlyingToken` — the USDC.e contract address (`0x2791Bca1...`) * `recipient` — who receives the PolyUSD (usually yourself) * `amount` — raw amount in 6-decimal units (1 USDC = 1,000,000) ## Unwrapping: PolyUSD → USDC.e Unwrapping is designed to be **permissionless** — any EOA can call `CollateralOfframp.unwrap(asset, to, amount)` and burn their pUSD in exchange for USDC.e. The function signature mirrors wrap: ``` function unwrap(address underlyingToken, address recipient, uint256 amount) ``` > [!NOTE] > > **Unwrap is live today.** The Collateral Offramp holds `WRAPPER_ROLE` on the pUSD token and processes user unwraps directly. Verified 2026-04-21 via tx [`0x154a906c5790e272cb209146e6716ff255d92791519f642f5c43a4997a47e030`](https://polygonscan.com/tx/0x154a906c5790e272cb209146e6716ff255d92791519f642f5c43a4997a47e030) (0.1 pUSD → 0.1 USDC.e from a Safe wallet via the Polymarket relayer). > > Alternative paths that also still work: > > * **Polymarket's withdraw UI** at `bridge.polymarket.com/withdraw` — routes through a Uniswap v3 pool or off-chain witness flow. > * **Settlement through the V2 exchange** — `CTFCollateralAdapter` handles unwrapping during `matchOrders`. > * **Redeeming resolved positions** — ConditionalTokens pays out USDC.e directly. ### Steps 1. **Approve** the Offramp to spend your pUSD 2. **Call** `unwrap(USDC.e, recipient, amount)` on the Offramp Both steps are EOA-callable. For **Safe wallets**, route both through the Polymarket relayer (gasless) — the polynode SDK does this automatically, see below. ### Via the polynode SDK (recommended for Safe wallets) The SDK's `wrapToPolyUsd()` / `unwrapFromPolyUsd()` automatically detect your wallet type. If you onboarded with `ensureReady(privateKey)` (Safe wallet, the default), both calls route through the Polymarket relayer and execute as gasless Safe transactions signed by your EOA. Amounts are raw 6-decimal integers (`1_000_000` = \$1). ```typescript TypeScript theme={null} // polynode-sdk >= 0.9.1 import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...', exchangeVersion: 'v2', builderCredentials: { key: '...', secret: '...', passphrase: '...' }, }); await trader.ensureReady('0xYOUR_EOA_PRIVATE_KEY'); // Wrap 10 USDC.e → pUSD (gasless via Safe+relayer) const wrapTx = await trader.wrapToPolyUsd(10_000_000n); // Unwrap 5 pUSD → USDC.e (gasless via Safe+relayer) const unwrapTx = await trader.unwrapFromPolyUsd(5_000_000n); ``` ```python Python theme={null} # polynode >= 0.9.1 from polynode.trading import PolyNodeTrader, TraderConfig, ExchangeVersion, BuilderCredentials trader = PolyNodeTrader(TraderConfig( polynode_key="pn_live_...", exchange_version=ExchangeVersion.V2, builder_credentials=BuilderCredentials(key="...", secret="...", passphrase="..."), )) await trader.ensure_ready("0xYOUR_EOA_PRIVATE_KEY") # Wrap 10 USDC.e → pUSD wrap_tx = await trader.wrap_to_polyusd(10_000_000) # Unwrap 5 pUSD → USDC.e unwrap_tx = await trader.unwrap_from_polyusd(5_000_000) ``` ```rust Rust theme={null} // polynode >= 0.12.1 use polynode::trading::{ PolyNodeTrader, TraderConfig, ExchangeVersion, BuilderCredentials, PrivateKeySigner, }; let mut trader = PolyNodeTrader::new(TraderConfig { polynode_key: "pn_live_...".into(), exchange_version: ExchangeVersion::V2, builder_credentials: Some(BuilderCredentials { key: "...".into(), secret: "...".into(), passphrase: "...".into(), }), ..Default::default() })?; let signer = PrivateKeySigner::from_hex("0xYOUR_EOA_PRIVATE_KEY")?; trader.ensure_ready(Box::new(signer), None).await?; // Wrap 10 USDC.e → pUSD let wrap_tx = trader.wrap_to_polyusd(10_000_000).await?; // Unwrap 5 pUSD → USDC.e let unwrap_tx = trader.unwrap_from_polyusd(5_000_000).await?; ``` **Which wallet type am I using?** `ensureReady(privateKey)` defaults to `POLY_GNOSIS_SAFE` — your EOA controls a Safe at the derived funder address, and SDK methods route through the Polymarket relayer (gasless). If you pass `{ type: SignatureType.EOA }` explicitly, the SDK signs directly from the EOA and you pay MATIC for gas. For Safe mode, `builderCredentials` is required because the SDK uses your Polymarket builder HMAC to authenticate relayer requests — mint one at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder). > [!WARNING] > > **Placing an order right after a wrap?** Call `await trader.refreshBalanceAllowance()` in between. The V2 CLOB caches its view of your balance + allowances per API key; for a few seconds after wrap, that view is stale. If you submit an order before the cache refreshes, the CLOB can return a cryptic `"error parsing fee rate bps"` instead of the real "balance not yet visible" message. A single `refreshBalanceAllowance()` call fixes it. `ensureReady` already does this for you on first setup — `wrapToPolyUsd` does not, because not every wrap is followed by an immediate order. ### Related contracts | Contract | Address | Role on pUSD (today) | | - | - | - | | Collateral Onramp (wrap) | `0x93070a847efef7f70739046a929d47a521f5b8ee` | WRAPPER\_ROLE ✓ | | Collateral Offramp (unwrap) | `0x2957922eb93258b93368531d39facca3b4dc5854` | WRAPPER\_ROLE ✓ | | PermissionedRamp (witness-signed) | `0xebc2459ec962869ca4c0bd1e06368272732bcb08` | WRAPPER\_ROLE ✓ | | CtfCollateralAdapter | `0xAdA100Db00Ca00073811820692005400218FcE1f` | WRAPPER\_ROLE ✓ | | NegRiskCtfCollateralAdapter | `0xadA2005600Dec949baf300f4C6120000bDB6eAab` | WRAPPER\_ROLE ✓ | ## How It Works Under the Hood PolyUSD is backed 1:1 by collateral held in a vault contract (`0xC417fD8E...`). When you wrap: 1. Your USDC.e transfers to the vault 2. PolyUSD is minted to your wallet When you unwrap: 1. Your PolyUSD is burned 2. USDC.e is released from the vault to your wallet During V2 trade settlements, the exchange automatically handles PolyUSD ↔ USDC.e conversion through the CTFCollateralAdapter. The ConditionalTokens contract underneath still uses USDC.e for position splitting — PolyUSD is the user-facing layer that sits on top. > [!NOTE] > > The vault currently holds USDC.e as the backing collateral. Polymarket has stated that PolyUSD is backed 1:1 by USDC. A PermissionedRamp contract exists for native USDC wrapping but is not yet active. When it activates, the vault may hold a mix of USDC.e and native USDC, but PolyUSD remains 1:1 redeemable regardless of the backing composition. ## Tracking PolyUSD Events polynode detects PolyUSD wrapping and unwrapping through the settlement stream. These appear as `deposit` events: * **Wrap** (deposit): `direction: "deposit"`, `from` is the Onramp contract * **Unwrap** (withdrawal): `direction: "withdrawal"`, `to` is the user wallet Subscribe to `deposits` on the WebSocket to receive these events. Internal settlement wraps/unwraps (between exchange and adapter contracts) are filtered out automatically. ## Key Facts * **Decimals:** 6 (same as USDC) * **Backing:** 1:1 by USDC (currently held as USDC.e in the vault) * **Wrapping:** USDC.e via Onramp (active) or native USDC via PermissionedRamp (not yet active) * **Proxy:** ERC-1967 upgradeable proxy * **Chain:** Polygon mainnet (chain ID 137) * **Minimum wrap:** No minimum (tested with amounts as low as \$0.007) # Position Management Source: https://docs.polynode.dev/guides/position-management Split, merge, and convert positions on Polymarket, with gasless Safe and deposit-wallet execution. ## What are split, merge, and convert? Polymarket positions are ERC-1155 tokens representing outcomes. Three on-chain operations let you manage them directly: **Split** — Turn collateral into YES + NO tokens for a market. Current V2 trading uses pUSD; explicit legacy V1 uses USDC.e. You put in $100 and get 100 YES shares + 100 NO shares. One side will be worth $1 at resolution, the other \$0. **Merge** — The reverse. Put YES + NO tokens back together and receive the matching collateral. In current V2, 100 YES + 100 NO returns 100 pUSD. **Convert** — Rebalance positions across outcomes in a multi-outcome market (neg-risk only). The legacy neg-risk adapter converts selected NO tokens into USDC.e plus YES tokens on the remaining outcomes. ## When to use each | Operation | Use case | | - | - | | **Split** | Mint new outcome tokens without going through the orderbook. Useful for market making or taking positions on illiquid markets. | | **Merge** | Exit positions without selling on the orderbook. Merge paired YES+NO tokens back into the active collateral. | | **Convert** | Rebalance across outcomes in multi-outcome markets (e.g. "Who will win the World Cup?"). Swap your NO exposure on some outcomes into YES exposure on others. | ## TypeScript (gasless) The TypeScript SDK executes these operations gaslessly through the Polymarket relayer. No MATIC/POL needed. ```bash theme={null} npm install polynode-sdk@latest ``` ### Split ```typescript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: 'pn_live_...' }); await trader.ensureReady('0xYOUR_PRIVATE_KEY'); // Split 100 pUSD into YES + NO tokens on current V2 const result = await trader.split({ conditionId: '0x895e01db...', // from market data amount: 100, }); console.log(result.txHash); // on-chain transaction hash ``` ### Merge ```typescript theme={null} // Merge YES + NO tokens back into 50 pUSD on current V2 const result = await trader.merge({ conditionId: '0x895e01db...', amount: 50, }); ``` ### Convert Convert is only available on neg-risk multi-outcome markets (e.g. "Republican Presidential Nominee" with 36 outcomes). ```typescript theme={null} // Convert NO positions on outcomes 0 and 1 ($100 each) const result = await trader.convert({ marketId: '0xc7d902c4...', // negRiskMarketID from market data outcomeIndices: [0, 1], // which outcomes to convert amount: 100, // $100 per outcome }); ``` **What happens:** * Your NO tokens on outcomes 0 and 1 are burned * You receive **(number of outcomes - 1) x amount** in USDC.e (here: \$100) * You receive YES tokens on all other outcomes (here: outcomes 2 through 35) The `outcomeIndices` correspond to the position of each outcome in the market. Index 0 is the first outcome, index 1 is the second, etc. You can find these by looking at the `questionID` field in market data — the last byte of each questionID is the outcome index. ## Rust The existing Rust helpers remain build-only for integrations that submit their own transactions: ```rust theme={null} use polynode::trading::position_management::*; // Build a split transaction let tx = build_split_txn( "0x895e01db...", // conditionId 100.0, // $100 true, // neg_risk ); // tx.to = contract address // tx.data = ABI-encoded calldata // Submit via your provider or the Polymarket relayer ``` ```rust theme={null} // Build a convert transaction let tx = build_convert_txn( "0xc7d902c4...", // marketId &[0, 1], // outcome indices 100.0, // $100 per outcome ); ``` For an EOA-controlled Safe or deposit wallet in [`user_owned` mode](/sdks/user-owned-execution), `execute_split()` and `execute_merge()` submit gaslessly with wallet-owned authorization: ```rust,no_run theme={null} use polynode::trading::{ ExecutionMode, MergeParams, PolyNodeTrader, PrivateKeySigner, SignatureType, SplitParams, TraderConfig, }; let signer = PrivateKeySigner::from_hex( &std::env::var("POLYGON_PRIVATE_KEY")?, )?; let mut trader = PolyNodeTrader::new(TraderConfig { polynode_key: std::env::var("POLYNODE_API_KEY")?, execution_mode: ExecutionMode::UserOwned, ..Default::default() })?; let ready = trader.ensure_ready(Box::new(signer), None).await?; assert!(matches!( ready.signature_type, SignatureType::PolyGnosisSafe | SignatureType::Poly1271 )); trader.execute_split(SplitParams { condition_id: "0x895e01db...".into(), amount: 1.0, }, false).await?; trader.execute_merge(MergeParams { condition_id: "0x895e01db...".into(), amount: 1.0, }, false).await?; ``` ## Python The synchronous Python helpers also remain build-only: ```python theme={null} from polynode.trading.position_management import build_split_txn, build_convert_txn # Build a split transaction tx = build_split_txn("0x895e01db...", 100.0, neg_risk=True) # tx.to, tx.data, tx.value — submit via your provider # Build a convert transaction tx = build_convert_txn("0xc7d902c4...", [0, 1], 100.0) ``` For an EOA-controlled Safe or deposit wallet in [`user_owned` mode](/sdks/user-owned-execution), use the explicit async execution methods: ```python theme={null} import os from polynode.trading import ( ExecutionMode, MergeParams, PolyNodeTrader, SignatureType, SplitParams, TraderConfig, ) trader = PolyNodeTrader(TraderConfig( polynode_key=os.environ["POLYNODE_API_KEY"], execution_mode=ExecutionMode.USER_OWNED, )) ready = await trader.ensure_ready(os.environ["POLYGON_PRIVATE_KEY"]) assert ready.signature_type in ( SignatureType.POLY_GNOSIS_SAFE, SignatureType.POLY_1271, ) await trader.execute_split(SplitParams( condition_id="0x895e01db...", amount=1, neg_risk=False, )) await trader.execute_merge(MergeParams( condition_id="0x895e01db...", amount=1, neg_risk=False, )) ``` ## Finding market IDs To use these operations, you need the right identifiers from market data: | Field | Where to find it | Used by | | - | - | - | | `conditionId` | Market data from `/v1/events/search` or Gamma API | `split()`, `merge()` | | `negRiskMarketID` | Market data (only on neg-risk markets) | `convert()` | | Outcome index | Last byte of each outcome's `questionID` | `convert()` outcomeIndices | ```typescript theme={null} // Example: finding IDs for a market import { PolyNode } from 'polynode-sdk'; const pn = new PolyNode({ apiKey: 'pn_live_...' }); const results = await pn.searchEvents('Republican nominee', { limit: 1 }); const market = results.events[0].markets[0]; console.log(market.conditionId); // for split/merge console.log(market.negRiskMarketID); // for convert ``` ## Polymarket Protocol V2 markets Polymarket Protocol V2 is Polymarket's new market system for newly created markets, separate from the V2 exchange upgrade mentioned above. On Protocol V2 markets, split, merge and redeem go through Polymarket's Router (`0x12121212006e4CD160D18e3f00711DA5c3372600`), and TypeScript `polynode-sdk` 0.15.0, Python `polynode` 0.15.0 and Rust `polynode` 0.18.0 or newer pick the right path for each market. Collateral is still pUSD. Redeem takes an outcome index: `0` for the first outcome (Yes, or Up) and `1` for the second. Converting negative-risk positions is not available for Protocol V2 markets; the SDK returns a clear error instead. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ## Neg-risk vs standard markets | | Standard markets | Neg-risk markets | | - | - | - | | **Outcomes** | 2 (binary YES/NO) | Many (e.g. 36 candidates) | | **Split/Merge** | Via CTF contract | Via NegRiskAdapter | | **Convert** | Not available | Available | | **Auto-detection** | TypeScript SDK handles this | TypeScript SDK handles this | The TypeScript SDK auto-detects the market type and routes to the correct contract. Rust and Python default to neg-risk (most multi-outcome markets). Pass `neg_risk=False` for standard binary markets. > [!NOTE] > > Rust and Python keep their synchronous build-only helpers for compatibility and > also provide gasless user-owned `execute_split` / `execute_merge` methods. > Convert remains gasless through TypeScript; Rust and Python expose a build-only > convert transaction. # Rate Limits Source: https://docs.polynode.dev/guides/rate-limits Rate limiting details and best practices. V3 REST limits are shared across all API keys owned by the same account. Limits scale with your plan and with the endpoint class. > [!NOTE] > > **Two independent controls:** the per-minute, per-second, connection, and Free-session limits on this page remain in force. Polynode now also shows monthly API-request and WebSocket-transfer usage in the [usage dashboard](https://polynode.dev/dashboard/usage), but monthly usage enforcement is not active yet. ## Tier limits > [!NOTE] > > **Firehose** = a WebSocket subscription with no filters applied. It receives every event (all settlements, trades, blocks, etc.) at full throughput. Filtered subscriptions — where you specify wallets, tokens, slugs, or size thresholds — use far less bandwidth and don't count toward your firehose limit. | | Free | Starter (\$50/mo) | Growth (\$200/mo) | Enterprise (\$750/mo) | | - | - | - | - | - | | **Standard V3 REST data** | Not available | 1,000 req/min (\~16 QPS) | 2,000 req/min (\~33 QPS) | 4,000 req/min default; custom by agreement | | **Heavy V3 trade-history endpoints** | Not available | 1,000 req/min | 1,500 req/min | 1,500 req/min default; custom by agreement | | **Event WebSocket connections** | 1 | 10 | 50 | Unlimited | | **Orderbook WebSocket connections** | 1 | 10 | 50 | Unlimited | | **Filter items per subscription** | 10,000 | 10,000 | 10,000 | Custom | | **Orderbook market subs** | Unlimited | Unlimited | Unlimited | Unlimited | | **WebSocket session** | 1 hour/day | Unlimited | Unlimited | Unlimited | | **API keys** | 1 | 3 | 10 | 25 | | **Snapshot size** (`snapshot_count`) | 20 | 100 | 200 | 500 | | **Snapshot lookback** (`since`) | 30 seconds | 2 minutes | 5 minutes | 5 minutes | | **Key generation** | 1 per IP per day | Via dashboard | Via dashboard | Via dashboard | | **Support** | Community | Email | Priority | Dedicated + Slack | > [!NOTE] > > **Snapshot size vs snapshot lookback** — these are two separate snapshot modes controlled by different parameters. `snapshot_count` returns the last N events (capped by your tier). `since` returns all events after a UNIX-ms timestamp within your tier's lookback window. If you pass both, `since` takes priority and `snapshot_count` is ignored. See [subscribing](/websocket/subscribing#param-since) for details. > [!NOTE] > > **Enterprise** includes dedicated server infrastructure. Contact [josh@quantish.live](mailto:josh@quantish.live) before activation. > [!NOTE] > > V3 REST data endpoints require a paid plan. Heavy trade-history endpoints have a separate shared account bucket in addition to your standard V3 REST data limit. See [V3 REST data limits](#v3-rest-data-limits) below. ## How it works * V3 REST limits are tracked per account using a sliding window. You can use multiple keys at the same time, but every request draws from the same account allowance. * V3 REST data endpoints require a paid API key. Free-tier keys receive `402 Payment Required`. * Heavy V3 trade-history endpoints check both your account's standard V3 REST data limit and its heavy endpoint bucket. The stricter remaining limit applies. * When you exceed the limit, you'll receive a `429 Too Many Requests` response. * The error message includes a Unix timestamp for when you can retry. * Successful REST responses include `x-ratelimit-limit`, `x-ratelimit-remaining`, and `x-ratelimit-reset` headers. ## Monthly usage allowances Monthly usage is account-level and separate from the instantaneous limits above. Every active API key owned by the same account contributes to the same totals. Creating another key, reconnecting a WebSocket, or rotating a key does not create another allowance or reset usage. The [usage dashboard](https://polynode.dev/dashboard/usage) shows three meters: | Meter | What it counts | | - | - | | **API requests** | Completed authenticated requests on metered API routes. Requests rejected by authentication, existing rate limits, or a Polynode 5xx are not billable usage. | | **Order Book + Chainlink** | Successfully delivered Order Book and Chainlink WebSocket payload bytes. | | **On-chain events** | Successfully delivered settlements, status updates, trades, redemptions, oracle events, and other classified on-chain WebSocket payload bytes. | | Plan | API requests | Order Book + Chainlink | On-chain events | | - | -: | -: | -: | | Free | 100,000 | 5 GB | 5 GB | | Starter | 10 million | 250 GB | 250 GB | | Growth | 50 million | 1 TB | 1 TB | | Enterprise / Institutional | Unlimited | Unlimited | Unlimited | Plan allowances reset at the beginning of the account's next service period. The dashboard shows the exact start and end dates. Transfer uses decimal units: `1 GB = 1,000,000,000 bytes` and `1 TB = 1,000 GB`. Enterprise/Institutional usage is still measured and visible in the dashboard, but it has no monthly API-request or WebSocket-transfer ceiling. The instantaneous request and connection limits in the tier table remain separate. > [!NOTE] > > Monthly usage enforcement is not active yet. The dashboard and package purchases are live so you can observe real usage and prepare before monthly limits are enabled. Existing per-minute, per-second, connection, and Free-session limits still apply. ### What transferred means WebSocket transfer is the encoded application payload successfully submitted to your connection. Text messages count their UTF-8 payload length, while compressed binary messages count the smaller compressed payload length. The same payload delivered to two connections counts twice. Failed sends, acknowledgements, heartbeats, ping/pong frames, warnings, quota notices, close frames, WebSocket framing, TLS, TCP, IP, and retransmission overhead do not count. This is data transfer, not storage or a bandwidth-speed measurement. The dashboard may show API response transfer for transparency. It is informational and does not consume a version-one package or allowance. ### How capacity is consumed For each meter, Polynode consumes the allowance included with your plan first, then active purchased packages, then active courtesy capacity. Packages and courtesy grants with the earliest expiration are used first. Included capacity and added packages remain visually separate in the dashboard. ### Usage packages Signed-in Free and paid accounts can use a package to add capacity to one meter without changing the subscription plan: | Package | Added capacity | One-time price | | - | -: | -: | | **API requests** | 10 million requests | \$20 | | **Order Book + Chainlink** | 100 GB | \$20 | | **On-chain events** | 100 GB | \$20 | > [!NOTE] > > A package adds only monthly capacity for its selected meter. It does not unlock paid-only endpoints or change per-minute, connection, or Free-session limits. Select from 1 to 100 of one package in a Checkout. For example, 10 API-request packages add 100 million requests for a one-time \$200 payment. Packages are resource-specific and do not raise the request-per-minute or connection limits in the tier table. Capacity is added only after Stripe confirms a successful payment. Reopening, refreshing, or replaying the same Checkout cannot add a package twice. Each package remains active for 90 days, does not reset with the monthly service period, and expires after 90 days if unused. The dashboard shows remaining capacity and expiration. A refund or payment dispute removes the unused portion of its package. Usage already delivered is not erased. If more capacity has been consumed than can be reversed safely, Polynode preserves the usage history for review instead of abruptly disconnecting a customer. The usage calculator assumes connections remain open 24 hours per day and can recommend package quantities. Its estimate is directional because activity, filters, reconnects, message shape, and compression affect actual transfer. It never purchases automatically; the dashboard remains the source of truth. ## Best practices ### Use WebSocket for real-time data Instead of polling REST endpoints, connect via WebSocket for live updates: ```javascript theme={null} // Instead of polling /v3/trades every 5 seconds (12 req/min)... // Use WebSocket (1 connection, unlimited events) const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.send(JSON.stringify({ action: "subscribe", type: "settlements", })); ``` ### Cache metadata locally Market metadata (question, slug, outcomes) changes infrequently. Cache it and only refresh periodically: ```javascript theme={null} // Fetch full market list once const markets = await fetch("/v3/markets/search?q=bitcoin&limit=100", { headers }) .then((r) => r.json()); // Cache by token_id const cache = new Map(markets.data.map((m) => [m.condition_id, m])); // Use cache for lookups, refresh every 5 minutes ``` ### Batch where possible Use `POST /v3/wallets/batch` instead of many individual wallet summary requests when you need P\&L for multiple wallets. ### Use filtered subscriptions WebSocket subscriptions with filters reduce message volume and processing overhead: ```json theme={null} { "action": "subscribe", "type": "settlements", "filters": { "tokens": ["specific-token-id"], "min_size": 100 } } ``` ## Expected WebSocket throughput WebSocket subscriptions are not rate-limited by requests/min, but message volume varies significantly by subscription type: | Subscription | Typical messages/sec | Notes | | - | - | - | | Firehose (no filters) | 50–150 | \~0.5–1.5 Mbps uncompressed | | Filtered (1 market) | 1–20 | Depends on market activity | | Filtered (1 wallet) | 0–5 | Most wallets trade infrequently | | Blocks only | \~0.5 | One per Polygon block (\~2s) | > [!TIP] > > `status_update` events arrive in bursts (30–80 per block). If you don't need confirmation tracking, exclude them from your `event_types` filter to reduce volume. ## V3 REST data limits Standard V3 REST reads count against your plan's V3 REST data limit. | Plan | Standard V3 REST data | Heavy V3 trade-history endpoints | | - | -: | -: | | Free | Not available | Not available | | Starter | 1,000 req/min | 1,000 req/min | | Growth | 2,000 req/min | 1,500 req/min | | Enterprise | 4,000 req/min default; custom by agreement | 1,500 req/min default; custom by agreement | Heavy V3 trade endpoints have a separate shared account bucket because trade-history scans are the highest-throughput REST surface: * `/v3/trades` * `/v3/wallets/{address}/trades` * `/v3/wallets/{address}/combos/trades` * `/v3/markets/{token_id}/trades` * `/v3/markets/slug/{slug}/trades` * `/v3/builders/{code}/trades` When the heavy bucket is exceeded, you'll receive a `429` response with: ```json theme={null} { "error": "rate limit exceeded", "scope": "v3_heavy", "reset_at": 1774108000 } ``` > [!TIP] > > For real-time trades, use the [WebSocket stream](/websocket/overview) instead of polling trade-history endpoints. ## Pagination limits Most V3 list endpoints default to `limit=100` and clamp `limit` to a maximum of `300` rows per page. If you request more than the page cap, Polynode normalizes `limit` to the maximum allowed value. Responses include the actual `limit`, `offset`, `rows_returned`, and `has_more` values. `GET /v3/builders/{code}/leaderboard` is stricter: `limit` must be from 1 through 100, and `offset + limit` must stay within the first 500 ranks. Five full pages therefore use offsets `0`, `100`, `200`, `300`, and `400`. No V3 endpoint returns more than `1000` rows or buckets in one page. Cursors and offsets select where the next page starts; they do not increase its size. `/v3/markets/condition/{condition_id}/positions` supports tiered page sizes for holder lists: Starter keys can request up to `300` rows, while Growth and Enterprise keys can request up to `1000`. `/v3/wallets/{address}/pnl/events` defaults to and clamps at `limit=1000` buckets. For deep trade-history walks, prefer `after` and `before` time windows instead of very large offsets. ## Higher limits Upgrade your plan at [polynode.dev/pricing](https://polynode.dev/pricing) for higher rate limits and more WebSocket connections. Contact [josh@quantish.live](mailto:josh@quantish.live) for Enterprise capacity above the default V3 REST limits. # Serving ~1 Billion On-Chain Events at Sub-10ms Source: https://docs.polynode.dev/guides/trade-index How polynode replaced third-party subgraph infrastructure with a purpose-built trade index covering every Polymarket trade, position, and settlement since November 2022. # Serving \~1 Billion On-Chain Events at Sub-10ms Every Polymarket trade. Every position split. Every merge. Every redemption. Every conversion. From November 2022 to right now, updated in real-time, queryable in under 10 milliseconds. We replaced our entire third-party subgraph dependency with our own on-chain trade index. The result: 10-100x faster responses across every query type, zero external data dependencies, and complete coverage of Polymarket's on-chain history. ## Why We Built This Subgraph-based indexing served us well early on, but as Polymarket's volume grew, the cracks showed. Daily candle queries took over 10 seconds. Position P\&L calculations stalled during peak traffic. Data freshness lagged behind the chain. We had no control over uptime or performance, and our users felt it. We needed something that could handle the scale of Polymarket today, nearly a billion on-chain events and growing, while delivering the kind of response times that make real-time trading tools actually feel real-time. ## The Results | Query | Response Time | | - | :-: | | Wallet trade history | 9-30ms | | Market trades by token | 9ms | | Portfolio positions with P\&L | 25ms | | Hourly OHLCV candles | 14ms | | Daily OHLCV candles | 98ms | | Market volume stats | 17ms | | Wallet activity (splits, merges, redeems) | 8ms | **\~1 billion rows. Real-time chain tip. Every query under 100ms.** For context, here's what the same queries looked like before: | Query | Before | After | Improvement | | - | :-: | :-: | :-: | | Wallet trades | 340ms | 30ms | **11x** | | Market trades | 500ms | 9ms | **55x** | | Positions | 1,330ms | 25ms | **53x** | | Daily candles | 10,300ms | 98ms | **105x** | Daily candles went from 10 seconds to under 100 milliseconds. That's the difference between a chart that feels broken and one that feels instant. ## Subgraph Indexers Can't Keep Up As of April 2026, the most widely used Polymarket subgraph has its positions index nearly a week behind the chain: | Data Source | Block | Lag | | - | :-: | :-: | | **polynode trade index** | 85,634,892 | **0 blocks** | | Subgraph orderbook | 85,634,889 | 2 blocks | | Subgraph positions | 85,344,742 | **290,149 blocks (6.7 days)** | If you're querying positions from a subgraph, you're getting portfolio data that's almost a week old. Any trade, any entry, any exit that happened in the last 6.7 days simply doesn't exist in those results. This isn't a one-time outage. Positions require computing VWAP across every trade a wallet has ever made, and generic subgraph-style systems struggle with that at scale. The heaviest Polymarket wallets have millions of trades, and raw-event position rebuilds fall further behind every day as volume grows. polynode's trade index pre-computes positions for all 2.5 million wallets and maintains them in real-time as new trades confirm. There is no lag. When a trade confirms on-chain, positions update within seconds. ## Complete On-Chain Coverage The index covers every event type that matters for trade history and position reconstruction on Polymarket: * **OrderFilled** events across all exchange contracts (V1 and V2) * **PositionSplit**, collateral minted into outcome tokens * **PositionsMerge**, outcome tokens burned back to collateral * **PayoutRedemption**, winning positions claimed after resolution * **PositionsConverted**, multi-outcome NegRisk swaps Everything is decoded directly from on-chain logs. The blockchain is the source of truth. We don't rely on any third-party data pipeline, hosted subgraph, or external API to serve this data. ## Real-Time, Not Cached New trades and position events stream into the index via WebSocket as they confirm on-chain. There's no batch delay, no hourly refresh, no stale cache sitting between users and the latest data. When a trade confirms, it's queryable. Position P\&L, average entry prices, and realized gains are computed live from the raw event history. No pre-aggregated snapshots that drift out of sync. Every query reflects the actual current state of the chain. ## What This Means for Developers If you're building on Polymarket data, this changes what's possible: * **Portfolio dashboards** that load instantly, even for the heaviest wallets * **OHLCV candles at any resolution**, 1m, 5m, 15m, 1h, 4h, 1d, computed from real trade data, not sampled price feeds * **Complete trade history** for any wallet or market in a single API call * **Live P\&L tracking** that updates as trades confirm, not on a polling interval * **Settlement and redemption history** for compliance, accounting, or analytics Every polynode on-chain endpoint is powered by this system. ## Try It ```bash theme={null} # Wallet trades curl "https://api.polynode.dev/v2/onchain/trades?wallet=0x...&key=YOUR_KEY" # Positions with P&L curl "https://api.polynode.dev/v2/onchain/positions?wallet=0x...&key=YOUR_KEY" # OHLCV candles at any resolution curl "https://api.polynode.dev/v2/onchain/candles/{token_id}?resolution=1h&key=YOUR_KEY" # Market volume curl "https://api.polynode.dev/v2/onchain/markets/{token_id}/volume?key=YOUR_KEY" # Wallet redemptions curl "https://api.polynode.dev/v2/onchain/wallets/{wallet}/redemptions?key=YOUR_KEY" ``` Full endpoint documentation is available in the [API Reference](/api-reference). # Trade Tracking Guide Source: https://docs.polynode.dev/guides/trade-tracking How to track Polymarket trades for copy trading, analytics, and bookkeeping. polynode gives you two layers of trade data. Which one you use depends on what you're building. ## Two data layers, one subscription When you subscribe to `settlements`, you get two events per trade: 1. **`settlement`** (pending) — arrives 3–5 seconds before the block. Decoded from the transaction's calldata while it's still in the mempool. 2. **`status_update`** (confirmed) — arrives when the block confirms. Includes `confirmed_fills` with exact execution data from on-chain `OrderFilled` receipt logs. Both come through the same subscription. No extra configuration needed. ## How they differ The pending settlement and confirmed fills come from different data sources inside the same transaction: | | Pending settlement | Confirmed fills | | - | - | - | | **Source** | Transaction calldata (input) | OrderFilled receipt logs (output) | | **Speed** | 3–5 seconds before the block | At block confirmation | | **Price accuracy** | Exact for single-maker fills. Off by 0.01–0.04 on \~5% of multi-maker fills. | Exact. Always. This is the on-chain canonical record. | | **Size** | Gross token amount | Gross token amount (separate `fee` field) | | **Per-fill detail** | Per-maker breakdown from calldata | Per-maker breakdown from receipt logs | **Why the difference exists:** When a taker order sweeps multiple makers in one transaction, the calldata contains each maker's order and the total amounts being exchanged. But the total USDC is an aggregate across all makers. polynode estimates each maker's share proportionally. The contract computes and emits the exact per-maker amounts in the `OrderFilled` logs. For most fills, the estimate and the result are identical. For multi-maker sweeps, the contract's integer rounding can produce slightly different per-maker splits. **Size vs Polymarket:** Polymarket's activity API reports sizes net of fees. polynode's confirmed fills report the gross size from the OrderFilled event plus the fee as a separate field. To get the Polymarket-equivalent size: `net_size = size - (fee / price)`. ## Use case 1: Copy trading For copy trading, use the **pending settlement**. Speed matters more than the 0.01 price difference on the occasional multi-maker fill. To find the wallet's actual trade in a settlement event, iterate `data.trades[]` and match by `maker`: ```javascript theme={null} ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type !== "settlement" || msg.data.status !== "pending") return; for (const fill of msg.data.trades) { if (fill.maker.toLowerCase() === WALLET_IM_COPYING.toLowerCase()) { // This is the wallet's actual trade — same side, same token, same price placeTrade(fill.token_id, fill.side, fill.price); } } }; ``` > [!WARNING] > > Always match by `fill.maker`, never by `fill.taker`. The `taker` field on each fill is the counterparty, not the wallet you're tracking. Matching by `taker` returns the wrong wallet's perspective with the **opposite token** and the **complement price** — copy trading from that data would mirror the inverse of every trade. The pending settlement tells you what the wallet is trading, which direction, and at what price. That's all you need to mirror the trade before the block confirms. ## Use case 2: Analytics and bookkeeping For trade logs, P\&L tracking, portfolio analytics, or any scenario where you need exact prices, use `confirmed_fills` from the `status_update`. ```javascript theme={null} const tradeLog = []; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type !== "status_update" || !msg.data.confirmed_fills) return; for (const fill of msg.data.confirmed_fills) { if (fill.maker === WALLET_IM_TRACKING) { tradeLog.push({ tx_hash: msg.data.tx_hash, block: msg.data.block_number, timestamp: msg.data.confirmed_at, market: msg.data.market_title, token_id: fill.token_id, side: fill.side, price: fill.price, size: fill.size, fee: fill.fee, order_hash: fill.order_hash, }); } } }; ``` This is the same data Polymarket reads from the blockchain. Prices will match Polymarket's activity data exactly. ## Use case 3: Full lifecycle tracking Track both layers to get the complete picture — early detection plus exact execution. Match by `maker` in both the pending `trades[]` array and the confirmed `confirmed_fills[]` array: ```javascript theme={null} const pending = new Map(); ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { // Find the wallet's actual leg in the pending trades array const myLeg = msg.data.trades.find( t => t.maker.toLowerCase() === WALLET_IM_TRACKING.toLowerCase() ); if (myLeg) { pending.set(msg.data.tx_hash, { detected_at: Date.now(), pending_price: myLeg.price, pending_side: myLeg.side, }); } } if (msg.type === "status_update" && msg.data.confirmed_fills) { const original = pending.get(msg.data.tx_hash); const lead_time = original ? msg.data.confirmed_at - original.detected_at : null; // Match by maker in confirmed_fills too — same rule for (const fill of msg.data.confirmed_fills) { if (fill.maker.toLowerCase() === WALLET_IM_TRACKING.toLowerCase()) { console.log({ market: msg.data.market_title, side: fill.side, pending_price: original?.pending_price, confirmed_price: fill.price, lead_time_ms: lead_time, block: msg.data.block_number, }); } } pending.delete(msg.data.tx_hash); } }; ``` ## Confirmed fills field reference Each object in the `confirmed_fills` array: | Field | Type | Description | | - | - | - | | `order_hash` | string | EIP-712 order hash for this fill | | `maker` | string | Maker wallet address | | `taker` | string | Taker wallet or exchange contract | | `token_id` | string | Conditional token ID for this fill | | `side` | string | `"BUY"` or `"SELL"` (maker's perspective) | | `price` | number | Exact execution price | | `size` | number | Gross token amount (before fees) | | `maker_amount` | string | Raw maker amount (integer, 6 decimals for USDC) | | `taker_amount` | string | Raw taker amount (integer) | | `fee` | number | Fee in USDC, or `null` | ## Ghost fills and the nonce exploit A small percentage of Polymarket settlements (\~0.15–0.35%) fail on-chain. These are "ghost fills" — trades that appear to match off-chain but revert during on-chain settlement. The most common cause is the `incrementNonce()` exploit on Polymarket's V1 CTF Exchange, which allows users to invalidate their own orders after matching but before settlement. This is another reason to use `confirmed_fills` for any application where trade accuracy matters. A pending `settlement` event tells you a trade was matched. Only a `status_update` with `confirmed_fills` tells you it actually settled on-chain. To detect ghost fills, track pending settlements that never receive a `status_update`: ```javascript theme={null} const pending = new Map(); ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, { ...msg.data, detected_at: Date.now(), }); } if (msg.type === "status_update") { // Trade confirmed on-chain — not a ghost fill pending.delete(msg.data.tx_hash); } }; // Pending settlements older than 15 seconds without a status_update are ghost fills setInterval(() => { const now = Date.now(); for (const [txHash, data] of pending) { if (now - data.detected_at > 15000) { console.log("Ghost fill detected:", txHash); pending.delete(txHash); } } }, 5000); ``` For detailed research on the exploit, affected markets, and attacker identification, see the [Nonce Exploit Research](/guides/nonce-exploit) page. # V2 Technical Details Source: https://docs.polynode.dev/guides/v2-details Detailed V2 contract information for polynode subscribers. > [!NOTE] > > **This is not Polymarket Protocol V2.** "V2" on this page means Polymarket's April 2026 exchange upgrade (CTF Exchange V2 with pUSD collateral), live since April 28, 2026. Polymarket Protocol V2 is a separate, newer change to how markets are built: test markets since October 5, 2026, and newly created markets from around November 2, 2026 (tentative, per Polymarket). REST and WebSocket users need to do nothing; SDK traders upgrade. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). > [!NOTE] > > **Last updated: April 7, 2026.** This page contains detailed V2 technical information for polynode subscribers. Enter your API key below to unlock. [V2 Technical Details](https://v2-gate.bosh-jerns.workers.dev/) # Polymarket V2 Migration Source: https://docs.polynode.dev/guides/v2-migration polynode is ready for the Polymarket V2 exchange upgrade. Here's what you need to know. > [!NOTE] > > **This is not Polymarket Protocol V2.** "V2" on this page means Polymarket's April 2026 exchange upgrade (CTF Exchange V2 with pUSD collateral), live since April 28, 2026. Polymarket Protocol V2 is a separate, newer change to how markets are built: test markets since October 5, 2026, and newly created markets from around November 2, 2026 (tentative, per Polymarket). REST and WebSocket users need to do nothing; SDK traders upgrade. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). > [!NOTE] > > **V2 cutover: April 28, 2026 at \~11am UTC.** Polymarket announced the cutover date on April 18, 2026 (pushed from April 22 for extra builder testing time). The V2 test environment is open to all now at `clob-v2.polymarket.com`. V2 mainnet contracts have been processing real trades since April 3, 2026. polynode is V2-ready today — set `exchange_version: V2` in your SDK config to start placing V2 orders now, or keep V1 until cutover. After April 28, V1 orders will be rejected with `order_version_mismatch`. Polymarket is deploying a V2 exchange system on Polygon mainnet. polynode has identified, decoded, and tested against the V2 contracts deployed today. Our settlement stream and trading SDK are built to handle V2 alongside V1. **No action is required from existing settlement stream users.** When V2 settlements begin on-chain, they will flow through the same WebSocket feed automatically. ## Before Cutover: Your Checklist If you place orders on Polymarket, here's exactly what to do before April 28: 1. **Upgrade your SDK to the V2-ready version.** Older versions won't generate the correct V2 payload. * Rust: `polynode >= 0.12.0`. Install with `cargo add polynode@0.12.0`. * TypeScript: `polynode-sdk >= 0.9.0`. Install with `npm install polynode-sdk@^0.9.0`. * Python: `polynode >= 0.9.0`. Install with `pip install "polynode>=0.9.0"`. 2. **Flip the exchange version flag** in your `TraderConfig`. See [The Switch](#the-switch) below. This is the only code change required. 3. **Mint a V2 builder code** at [polymarket.com/settings?tab=builder](https://polymarket.com/settings?tab=builder) if you want attribution on your orders. Optional, orders still work without one. 4. **Cancel V1 resting orders** you don't want cleared at cutover. Open V1 orders get wiped when Polymarket flips the switch. 5. **Fund PolyUSD.** V2 orders settle in PolyUSD (pUSD), not USDC.e. If your Safe holds USDC.e, call `trader.wrap_to_polyusd(amount)` (Python) / `trader.wrapToPolyUsd(amount)` (TS) / `trader.wrap_to_polyusd(amount)` (Rust) to convert it via the Collateral Onramp. **`amount` is in raw 6-decimal units** (`1_000_000` = \$1; TS takes a `bigint` — use `1_000_000n`). Existing V1 pUSD balance carries over. 6. **Test against V2 now.** Point your SDK at V2 (step 2) and place a small order against `clob-v2.polymarket.com`. `ensure_ready` / `ensureReady` sets the V2 approvals and refreshes the CLOB's cached balance/allowance view for you. 7. **Verify V2 confirmation.** Your settlement stream tags V2 trades with `"exchange_version": "v2"` on every event. ## The Switch V2 activation is **one line in your SDK config.** Flip it before April 28 and orders route through the V2 exchange automatically. Leave it as V1 and you keep working against V1 until cutover. After that, V1 orders will be rejected. ```rust Rust theme={null} let config = TraderConfig { exchange_version: ExchangeVersion::V2, // ← this line ..Default::default() }; ``` ```typescript TypeScript theme={null} const trader = new PolyNodeTrader({ exchangeVersion: "v2", // ← this line }); ``` ```python Python theme={null} config = TraderConfig( exchange_version=ExchangeVersion.V2, # ← this line ) ``` That's it. No other code changes required. The SDK handles: * New contract addresses (V2 CTF Exchange + NegRisk A/B) * New EIP-712 domain (version `"2"`, new `verifyingContract`) * New Order struct (adds `builder`, `metadata`, `timestamp`; drops `nonce`, `feeRateBps` from the signed hash) * CLOB host swap to `clob-v2.polymarket.com` * PolyUSD collateral wrapping via the Onramp contract ## What We've Verified Tested against live V2 contracts on Polygon mainnet: * V2 settlement decoding verified against real on-chain transactions * V2 trade events (OrderFilled, OrdersMatched) decoded from block receipts * PolyUSD wrapping and unwrapping tested and detected in real time * V2 order placement tested live on the V2 CLOB * Full order lifecycle verified: place, check status, cancel, re-place * All existing market data, token IDs, and enrichment confirmed identical between V1 and V2 * **Order hash verification:** our EIP-712 order hash computation produces byte-for-byte identical results to the live V2 exchange contract's `hashOrder()` function on Polygon mainnet — cryptographic proof that our implementation is correct ## V2 Contract Addresses | Contract | Address | | - | - | | PolyUSD | `0xc011a7e12a19f7b1f670d46f03b03f3342e82dfb` | | Collateral Onramp | `0x93070a847efef7f70739046a929d47a521f5b8ee` | | Collateral Offramp | `0x2957922eb93258b93368531d39facca3b4dc5854` | | CTFCollateralAdapter | `0xAdA100Db00Ca00073811820692005400218FcE1f` | | NegRiskCTFCollateralAdapter | `0xadA2005600Dec949baf300f4C6120000bDB6eAab` | | V2 CTF Exchange | `0xe111180000d2663c0091e4f400237545b87b996b` | | V2 NegRisk Exchange A | `0xe2222d279d744050d28e00520010520000310f59` | | V2 NegRisk Exchange B | `0xe2222d002000ba0053cef3375333610f64600036` | | ConditionalTokens (unchanged) | `0x4D97DCd97eC945f40cF65F87097ACe5EA0476045` | > [!WARNING] > > All V2 contracts listed above are deployed and live on Polygon mainnet. On April 30 2026, Polymarket updated the collateral adapter contracts. The new adapters are effective May 1 2026 at 15:00 UTC — the relayer stops accepting transactions through the old adapters after that cutoff. ## How V2 Fits Together The key architectural insight: V2 only changes the **exchange layer** (how orders are matched and settled). The **token layer** (ConditionalTokens) is completely unchanged and cannot be replaced. ### Why Token IDs Don't Change This section applies to the April 2026 exchange upgrade only. Polymarket Protocol V2 markets use a new position system with new ids; see [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). All prediction market positions live inside the [ConditionalTokens](https://polygonscan.com/address/0x4D97DCd97eC945f40cF65F87097ACe5EA0476045) contract. This is a Gnosis protocol contract that has been on Polygon since Polymarket launched. Every token ID is derived from a condition ID and outcome index inside this contract. V2 does not replace ConditionalTokens. It can't. Doing so would invalidate every open position on the platform. Instead, V2 introduces an **adapter layer** between the new exchange contracts and the existing ConditionalTokens contract: ``` V1 (current): USDC.e → V1 Exchange → ConditionalTokens (mints/burns tokens directly) V2 (new): PolyUSD → V2 Exchange → CollateralAdapter → ConditionalTokens | Unwraps PolyUSD → USDC.e Deposits USDC.e into ConditionalTokens Same tokens minted as V1 ``` The CollateralAdapter translates between PolyUSD (V2's collateral) and USDC.e (what ConditionalTokens expects). ConditionalTokens never sees PolyUSD. From its perspective, nothing changed. This means: * Same token IDs across V1 and V2 * Same condition IDs * Same market metadata (Gamma API, enrichment) * Positions opened on V1 are fully compatible with V2 and vice versa ### New V2 Contracts Five new contracts support the V2 architecture. These are all live on Polygon mainnet: | Contract | Role | Status | | - | - | - | | **PolyUSD** | Wrapped USDC.e (1:1, 6 decimals) | Deployed | | **Collateral Onramp** | Wraps USDC.e → PolyUSD | Deployed | | **Collateral Offramp** | Unwraps PolyUSD → USDC.e | Deployed | | **CTFCollateralAdapter** | Bridges PolyUSD ↔ USDC.e for standard market settlements | Deployed | | **NegRiskCTFCollateralAdapter** | Bridges PolyUSD ↔ USDC.e for multi-outcome market settlements | Deployed | | **V2 CTF Exchange** | New order matching for standard markets | Deployed | | **V2 NegRisk Exchange A** | New order matching for multi-outcome markets | Deployed | | **V2 NegRisk Exchange B** | Additional multi-outcome capacity | Deployed | All V2 contracts are deployed on Polygon mainnet. V2 trading volume is currently minimal as Polymarket has not yet migrated users to V2. ### What's New in V2 **PolyUSD Collateral** — V2 uses PolyUSD instead of USDC.e as the exchange collateral. PolyUSD is a 1:1 wrapper around USDC.e with 6 decimals. See the [PolyUSD Guide](/guides/polyusd) for details on wrapping and unwrapping. **Updated Order Struct** — The EIP-712 signed hash drops two fields (`nonce`, `feeRateBps`) and adds three (`timestamp`, `metadata`, `builder`). The HTTP POST body still carries `expiration` (defaulted to `"0"` for no expiration). The polynode SDK handles all of this automatically. The dropped `feeRateBps` field was Polymarket's protocol fee slot inside the V1 order. V2 doesn't have a per-order protocol fee slot — Polymarket's fee model moves to a CLOB-level config plus the `builder` bytes32 rev share. **The polynode Fee Escrow is unaffected** by this change: it was never connected to the `feeRateBps` field. Our fee is pulled via a separate signed authorization (`FeeAuth` under our own EIP-712 domain) and only moves collateral. See the [Fee Escrow Guide](/guides/fee-escrow) for the V2-native FeeEscrow contract address and the three-fee breakdown. **EIP-712 Domain** — The signing domain version changed from `"1"` to `"2"`. The SDK handles this based on your exchange version config. **No More Settlement Routers** — V1 used FeeModule router contracts between operators and the exchange. V2 eliminates routers. Operators call the exchange contracts directly. **exchange\_version Field** — V2 trades include `"exchange_version": "v2"` on each trade object in settlement and trade events. V1 trades omit this field. Use it to distinguish which exchange system processed a settlement. Trades on Polymarket Protocol V2 markets carry `"exchange_version": "v3"` (ExchangeV3). ### What Didn't Change * **ConditionalTokens contract** — same address, same position system, same token IDs * **Market data** — same condition IDs, same Gamma metadata, same enrichment pipeline * **Authentication** — same API key derivation, same HMAC headers * **WebSocket subscriptions** — same event types, same format * **Position splits/merges/conversions** — same ConditionalTokens events * **Oracle system** — unchanged UMA adapters and resolution flow * **Orderbook streaming** — same WebSocket protocol and message format ## Impact on polynode Users ### Settlement Stream No changes required. V2 settlements produce the same event types you already receive: * `settlement` — early detection (3-5 seconds pre-confirmation) * `status_update` — block confirmation with latency measurement * `trade` — confirmed trade from OrderFilled event * `deposit` — now includes PolyUSD wrapping/unwrapping alongside USDC.e polynode detects V2 transactions automatically alongside V1. Both versions are supported simultaneously. ### Trading SDK The polynode SDK supports V2 with a single config change: ```rust Rust theme={null} use polynode::trading::{PolyNodeTrader, TraderConfig, OrderParams, OrderSide, ExchangeVersion}; let mut config = TraderConfig { polynode_key: "pn_live_...".into(), exchange_version: ExchangeVersion::V2, // ← only change needed ..Default::default() }; let mut trader = PolyNodeTrader::new(config)?; let signer = PrivateKeySigner::from_hex("0x...")?; let status = trader.ensure_ready(Box::new(signer), None).await?; // Order placement is identical to V1 let result = trader.order(OrderParams { token_id: "10293...".into(), side: OrderSide::Buy, price: 0.05, size: 10.0, ..Default::default() }).await?; ``` ```typescript TypeScript (SDK) theme={null} // npm install polynode-sdk import { PolyNodeTrader } from "polynode-sdk"; const trader = new PolyNodeTrader({ polynodeKey: "pn_live_...", exchangeVersion: "v2", // ← only change needed }); await trader.ensureReady("0xprivatekey..."); // Order placement is identical to V1 const result = await trader.order({ tokenId: "10293...", side: "BUY", price: 0.05, size: 10, }); ``` ```python Python theme={null} # pip install polynode[trading] from polynode.trading import PolyNodeTrader, TraderConfig, ExchangeVersion, OrderParams config = TraderConfig( polynode_key="pn_live_...", exchange_version=ExchangeVersion.V2, # ← only change needed ) trader = PolyNodeTrader(config) await trader.ensure_ready("0xprivatekey...") # Order placement is identical to V1 — pass OrderParams, add builder for V2 attribution result = await trader.order(OrderParams( token_id="10293...", side="BUY", price=0.05, size=10, builder="0x5472fdd7...", # optional; your V2 builder code )) ``` > [!NOTE] > > The SDK handles V2 order structs, EIP-712 signing, CLOB endpoint routing, and PolyUSD collateral automatically. You don't need to change how you construct orders or manage positions. ## Builder Attribution in V2 V2 moves builder attribution from HTTP headers into the signed order struct itself as a `bytes32` field. To attribute trades to your own builder profile, mint a builder code in Polymarket's settings and pass it to the SDK on each order. **Step 1: Mint your V2 builder code.** Visit `polymarket.com/settings?tab=builder` with your connected wallet, create a builder profile, and copy the generated bytes32 code. **Step 2: Pass it on each order.** All three polynode SDKs accept a `builder` field on the order params. If you don't pass one, orders sign with `0x0000...0000` (no attribution). ```rust Rust theme={null} let result = trader.order(OrderParams { token_id: "10293...".into(), side: OrderSide::Buy, price: 0.05, size: 10.0, builder: Some("0x0000000000000000000000000000000000000000000000000000000000000001".into()), ..Default::default() }).await?; ``` ```typescript TypeScript theme={null} const result = await trader.order({ tokenId: "10293...", side: "BUY", price: 0.05, size: 10, builder: "0x0000000000000000000000000000000000000000000000000000000000000001", }); ``` ```python Python theme={null} result = await trader.order(OrderParams( token_id="10293...", side="BUY", price=0.05, size=10, builder="0x0000000000000000000000000000000000000000000000000000000000000001", )) ``` Your existing V1 `builder_credentials` (HMAC key/secret/passphrase) are unrelated to the V2 `builder` bytes32. The HMAC credentials are still used to query builder trade history at `/builder/trades`. The V2 bytes32 is what attributes newly-placed orders on-chain. ## Pre-Migration V1 Orders Open V1 orders resting at cutover get cleared from V1 orderbooks. Polymarket exposes `GET /data/pre-migration-orders` on the V2 CLOB for fetching your pre-cutover V1 order history. Cancel V1 resting orders before April 28 if you need the capital free for V2 trading. ## Common V2 Errors If something goes wrong during migration, these are the ones you'll hit. **`order_version_mismatch`** Your SDK sent a V1-formatted order but the V2 CLOB expected V2. Flip `exchange_version: V2` in your config. **`not enough balance / allowance`** Most common causes, in order: 1. **Your wallet has USDC.e but not PolyUSD.** V2 uses PolyUSD as the collateral token. Call `trader.wrap_to_polyusd(amount_raw)` (Python/Rust) or `trader.wrapToPolyUsd(amount_raw)` (TS) to convert. Amounts are raw 6-decimal integers. 2. **Approvals not yet visible to the CLOB.** The V2 CLOB caches per-API-key balance + allowance state. `ensureReady` / `ensure_ready` refreshes this cache after setting approvals; if you changed approvals outside that flow, call `trader.refreshBalanceAllowance()` / `trader.refresh_balance_allowance()` manually. 3. **Order notional + fee exceeds balance.** V2 markets charge a fee (\~2–5% of notional depending on `base_fee`). For a BUY, `balance >= makerAmount + platformFee` must hold or the CLOB rejects. **`error parsing fee rate bps () to int64`** Your SDK is too old and isn't sending the V2 payload correctly. Upgrade to the V2-ready version listed in [the checklist above](#before-cutover-your-checklist). **Rust-specific: `not enough balance / allowance` even though you have PolyUSD** If you call `link_wallet(signer, None)` with an EOA wallet, the SDK silently uses the config's default signature type (POLY\_GNOSIS\_SAFE) and derives a Safe address as the maker. That Safe has zero balance, so the CLOB rejects the order. For EOA wallets, pass explicit opts: ```rust theme={null} use polynode::trading::{LinkOpts, SignatureType}; trader.link_wallet(Box::new(signer), Some(LinkOpts { signature_type: Some(SignatureType::Eoa), })).await?; ``` ## Timeline * **Now:** V2 test environment live at `clob-v2.polymarket.com`. V2 contracts live on Polygon mainnet processing real trades. polynode settlement stream tags V2 trades with `exchange_version: "v2"`. * **Before April 28:** Flip your SDK config to `exchange_version: V2` (or keep V1 until cutover). Mint a builder code if you want attribution. Cancel V1 resting orders you don't want cleared. * **April 28, \~11am UTC:** Polymarket cutover. V2 becomes the primary exchange. V1 orderbooks cleared. * **After cutover:** Any integration still on V1 will fail with `order_version_mismatch`. Flip your config. polynode supports both V1 and V2 simultaneously throughout the transition — no downtime, no disruption. # Batch Resolve Source: https://docs.polynode.dev/identities/batch-resolve POST /v3/identities/batch Resolve up to 1,000 Polymarket trading wallets to usernames, controlling EOAs, wallet types, deployment status, and current status in one call. Resolve up to 1,000 trading wallets per call against PolyNode's identity index (refreshed daily). Each found identity includes `wallet_type`, `deployed`, and `current`. Answers come from a single indexed query — typical response time is tens of milliseconds regardless of batch size. Wallets without a known identity come back as `null`, so the response always covers every requested wallet. For richer single-wallet resolution (live on-chain fallback for brand-new wallets), the [Resolve Wallet](/api-reference/wallets/resolve) endpoint remains the deepest option. ```bash theme={null} curl -X POST "https://api.polynode.dev/v3/identities/batch" \ -H "x-api-key: $POLYNODE_API_KEY" \ -H "Content-Type: application/json" \ -d '{"wallets": ["0x204f72f35326db932158cba6adff0b9a1da95e14"]}' ``` # Identity Lookup Source: https://docs.polynode.dev/identities/lookup GET /v3/identities/{addr} Resolve one address: by trading wallet (returns username, EOA, wallet type, deployment/current status, and related wallets) or, if not a known trading wallet, by controlling EOA (returns every wallet that account controls with status). One call, either direction: pass a trading wallet to get its username, controlling EOA, wallet type, deployment status, current status, and related wallets — or pass an EOA to list every Polymarket wallet that account controls. `wallet_type` tells you what kind of wallet an address is. `deployed` tells you whether its contract exists on Polygon. `current` tells you whether it is the account's selected trading-wallet address. When matched by wallet, `wallet_details` includes that address, the current address, and other deployed wallet types associated with the same EOA. ```bash theme={null} curl "https://api.polynode.dev/v3/identities/0x204f72f35326db932158cba6adff0b9a1da95e14" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Username Search Source: https://docs.polynode.dev/identities/search GET /v3/identities/search Search 5M+ Polymarket usernames by substring, returning wallet type, deployment status, and current status with exact matches ranked first. Find Polymarket accounts by (partial) username across 5M+ named wallets. Results include `wallet_type`, `deployed`, and `current`, and are ranked by similarity with exact matches first. Not available anywhere in Polymarket's public API. ```bash theme={null} curl "https://api.polynode.dev/v3/identities/search?q=swiss&limit=10" \ -H "x-api-key: $POLYNODE_API_KEY" ``` # Introduction Source: https://docs.polynode.dev/introduction Real-time Polymarket data API — settlements detected up to 5 seconds before on-chain confirmation. > [!NOTE] > > **Polymarket Protocol V2.** Polymarket is moving newly created markets to Polymarket Protocol V2 from around November 2, 2026 (tentative, per Polymarket; test markets since October 5, 2026). REST and WebSocket integrations need no changes. If you trade with our SDK, upgrade to `polynode-sdk` 0.15.0 (TypeScript), `polynode` 0.18.0 (Rust) or `polynode` 0.15.0 (Python). This is separate from Polymarket's April 2026 exchange upgrade ([V2 Migration](/guides/v2-migration)). See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). # PolyNode API PolyNode delivers Polymarket settlement data **2–5 seconds before on-chain confirmation** (1–2 Polygon blocks). Connect via WebSocket for real-time streaming, or query the REST API for markets, candles, and orderbook data. > [card] [WebSocket streaming](/websocket/overview) > > Real-time settlements with filtered subscriptions. The core product. > [card] [Markets & pricing](/api-reference/markets/top-markets) > > Enriched market metadata, OHLCV candles, and volume analytics. ## Quick start ### 1. Get an API key ```bash theme={null} curl -s -X POST https://api.polynode.dev/v1/keys \ -H "Content-Type: application/json" \ -d '{"name": "my-app"}' ``` ### 2. Query the REST API ```bash cURL theme={null} curl -s -H "x-api-key: pn_live_YOUR_KEY" \ "https://api.polynode.dev/v1/markets?count=5" ``` ```typescript TypeScript theme={null} const resp = await fetch("https://api.polynode.dev/v1/markets?count=5", { headers: { "x-api-key": "pn_live_YOUR_KEY" }, }); const data = await resp.json(); console.log(data.markets[0].question, data.markets[0].last_price); ``` ```python Python theme={null} import requests resp = requests.get( "https://api.polynode.dev/v1/markets", params={"count": 5}, headers={"x-api-key": "pn_live_YOUR_KEY"}, ) for m in resp.json()["markets"]: print(f"{m['question']} — {m['last_price']}") ``` ### 3. Stream live settlements via WebSocket ```javascript Node.js theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement") { const d = msg.data; console.log(`${d.taker_side} ${d.taker_size} @ ${d.taker_price} | ${d.market_title}`); } }; ``` ```python Python theme={null} import asyncio, json, websockets async def stream(): async with websockets.connect("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY") as ws: await ws.send(json.dumps({"action": "subscribe", "type": "settlements"})) async for message in ws: msg = json.loads(message) if msg["type"] == "settlement": d = msg["data"] print(f"{d['taker_side']} {d['taker_size']} @ {d['taker_price']} | {d.get('market_title')}") asyncio.run(stream()) ``` ```bash CLI theme={null} npx wscat -c "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY" # then send: {"action":"subscribe","type":"settlements"} ``` ### 4. Stream a live orderbook ```javascript Node.js theme={null} const ws = new WebSocket("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { // Subscribe by condition ID (from the REST API) or token ID ws.send(JSON.stringify({ action: "subscribe", markets: ["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"] })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "snapshot_batch") { for (const snap of msg.snapshots) { console.log(`${snap.question} [${snap.outcome}]: ${snap.bids.length} bids, ${snap.asks.length} asks`); } } else if (msg.type === "batch") { for (const update of msg.updates) { if (update.type === "price_change") { for (const asset of update.assets) { console.log(`${update.slug} [${asset.outcome}]: ${asset.price}`); } } } } }; ``` ```python Python theme={null} import asyncio, json, websockets async def stream_orderbook(): async with websockets.connect("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY") as ws: await ws.send(json.dumps({ "action": "subscribe", "markets": ["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"] })) async for message in ws: data = json.loads(message) if data["type"] == "snapshot_batch": for snap in data["snapshots"]: print(f"{snap['question']} [{snap['outcome']}]: {len(snap['bids'])} bids, {len(snap['asks'])} asks") elif data["type"] == "batch": for update in data["updates"]: if update["type"] == "price_change": for asset in update["assets"]: print(f"{update['slug']} [{asset['outcome']}]: {asset['price']}") asyncio.run(stream_orderbook()) ``` ```bash CLI theme={null} npx wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" # then send: {"action":"subscribe","markets":["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"]} ``` ## What makes PolyNode different | Feature | PolyNode | Other providers | | - | - | - | | Pending settlements (pre-chain) | 2–5 seconds early (1–2 blocks) | Not available | | Decoded Polymarket data | Enriched with market titles, outcomes, slugs | Raw logs only | | WebSocket filtering | By wallet, token, slug, side, size | Generic log filters | | Orderbook, candles, stats | CLOB proxying + enriched analytics | Separate service | ## Base URL ``` REST: https://api.polynode.dev WebSocket: wss://ws.polynode.dev/ws?key=YOUR_KEY ``` All endpoints require an API key via `x-api-key` header (REST) or `?key=` query param (WebSocket). # Examples Source: https://docs.polynode.dev/orderbook/examples Code examples for connecting to the Orderbook Stream in JavaScript, Python, and from the command line. ## Command line (wscat) ```bash theme={null} # Subscribe to the full firehose (all active markets) wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" \ -x '{"action":"subscribe","markets":["*"]}' # Subscribe by slug (easiest for specific markets) wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" \ -x '{"action":"subscribe","markets":["what-price-will-bitcoin-hit-in-march-2026"]}' # Subscribe by condition ID wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" \ -x '{"action":"subscribe","markets":["0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2"]}' # Subscribe by token ID wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" \ -x '{"action":"subscribe","markets":["73624432805780182150964443951045800666977811185963019133914618974858599458273"]}' # Subscribe with PN1 sequence/checksum integrity wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY&integrity=1" \ -x '{"action":"subscribe","markets":["73624432805780182150964443951045800666977811185963019133914618974858599458273"]}' ``` > [!TIP] > > [Orderbook Integrity (PN1)](/orderbook/integrity) provides copyable checksum code for Node.js, Python, Go, and Rust, plus the complete anchor, sequence, and targeted `resync` workflow. No PolyNode SDK is required. ## Finding markets Use the PolyNode REST API to search for markets: ```bash theme={null} # Search by keyword curl -s "https://api.polynode.dev/v1/search?q=bitcoin" | python3 -m json.tool # Look up by slug (from any Polymarket URL: polymarket.com/event/{slug}) curl -s "https://api.polynode.dev/v1/markets/slug/what-price-will-bitcoin-hit-in-march-2026" # Look up by condition ID curl -s "https://api.polynode.dev/v1/markets/condition/0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2" ``` The easiest approach: copy the slug from a Polymarket event URL and pass it directly in your subscribe message. ## JavaScript (firehose) ```javascript theme={null} const ws = new WebSocket("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { ws.send(JSON.stringify({ action: "subscribe", markets: ["*"] })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "subscribed") { console.log(`Firehose active: ${msg.markets} tokens`); } else if (msg.type === "batch") { console.log(`${msg.count} updates at ${msg.ts}`); for (const update of msg.updates) { if (update.type === "price_change") { for (const asset of update.assets) { // size="0" removes the level; otherwise it's the new absolute size at that level. console.log(` ${update.slug} [${asset.outcome}] ${asset.side} ${asset.price} -> ${asset.size} (bbo ${asset.best_bid}/${asset.best_ask})`); } } } } }; ``` ## JavaScript (specific markets) ```javascript theme={null} const ws = new WebSocket("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { // Subscribe by slug — both sides (Yes + No) are included automatically ws.send(JSON.stringify({ action: "subscribe", markets: [ "what-price-will-bitcoin-hit-in-march-2026", "netanyahu-out-before-2027" ] })); }; // Maintain local orderbook state const books = {}; ws.onmessage = (event) => { const msg = JSON.parse(event.data); switch (msg.type) { case "subscribed": console.log(`Subscribed to ${msg.markets} tokens`); console.log(`Resolved from: ${JSON.stringify(msg.resolved_from)}`); break; case "snapshot_batch": for (const snap of msg.snapshots) { books[snap.asset_id] = { bids: snap.bids, asks: snap.asks }; console.log(`Snapshot: ${snap.event_title} [${snap.outcome}] - ${snap.bids.length}b/${snap.asks.length}a`); } break; case "batch": for (const update of msg.updates) { if (update.type === "price_change") { for (const asset of update.assets) { // Apply directly to local books — price_change carries size + side so you // can maintain a tick-accurate book without polling REST. const book = books[asset.asset_id]; if (book) { const levels = asset.side === "BUY" ? book.bids : book.asks; applyDelta(levels, [{ price: asset.price, size: asset.size }]); } } } else if (update.type === "book_update") { const book = books[update.asset_id]; if (book) { applyDelta(book.bids, update.bids); applyDelta(book.asks, update.asks); } } } break; } }; // Apply incremental orderbook updates function applyDelta(existing, deltas) { for (const delta of deltas) { const idx = existing.findIndex(l => l.price === delta.price); if (delta.size === "0") { if (idx >= 0) existing.splice(idx, 1); } else if (idx >= 0) { existing[idx].size = delta.size; } else { existing.push(delta); } } } ws.onclose = () => setTimeout(() => location.reload(), 3000); ``` ## Python (firehose) ```python theme={null} import asyncio import json import websockets async def stream_firehose(): url = "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" async with websockets.connect(url, max_size=10_000_000) as ws: await ws.send(json.dumps({ "action": "subscribe", "markets": ["*"] })) async for message in ws: data = json.loads(message) if data["type"] == "subscribed": print(f"Firehose active: {data['markets']} tokens") elif data["type"] == "batch": for update in data["updates"]: if update["type"] == "price_change": for asset in update["assets"]: # size="0" removes the level; otherwise it's the new absolute size. print(f" {update['slug']} [{asset['outcome']}] {asset['side']} {asset['price']} -> {asset['size']} (bbo {asset['best_bid']}/{asset['best_ask']})") asyncio.run(stream_firehose()) ``` > [!TIP] > > Set `max_size` to at least 10 MB when connecting to the firehose (full data stream). Batch messages can be large when many markets update in the same 100ms window. ## Python (specific markets) ```python theme={null} import asyncio import json import websockets async def stream_orderbook(): url = "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" async with websockets.connect(url) as ws: # Subscribe by slug — resolves to all token IDs for those events await ws.send(json.dumps({ "action": "subscribe", "markets": [ "what-price-will-bitcoin-hit-in-march-2026", "netanyahu-out-before-2027", ] })) async for message in ws: data = json.loads(message) if data["type"] == "subscribed": print(f"Subscribed to {data['markets']} tokens") print(f"Resolved from: {data['resolved_from']}") elif data["type"] == "snapshot_batch": for snap in data["snapshots"]: print(f"Snapshot: {snap['event_title']} [{snap['outcome']}]") print(f" Bids: {len(snap['bids'])} levels") print(f" Asks: {len(snap['asks'])} levels") elif data["type"] == "batch": for update in data["updates"]: if update["type"] == "price_change": for asset in update["assets"]: print(f" {update['slug']} [{asset['outcome']}] {asset['side']} {asset['price']} -> {asset['size']} (bbo {asset['best_bid']}/{asset['best_ask']})") elif update["type"] == "book_update": bids = len(update.get("bids", [])) asks = len(update.get("asks", [])) print(f" Book delta: {update['slug']} [{update['outcome']}] +{bids}b/+{asks}a") asyncio.run(stream_orderbook()) ``` ## Python with compression ```python theme={null} import asyncio import json import zlib import websockets async def stream_compressed(): url = "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib" async with websockets.connect(url) as ws: await ws.send(json.dumps({ "action": "subscribe", "markets": ["what-price-will-bitcoin-hit-in-march-2026"] })) async for message in ws: if isinstance(message, bytes): text = zlib.decompress(message, -zlib.MAX_WBITS).decode("utf-8") data = json.loads(text) else: data = json.loads(message) print(f"[{data.get('type')}] {json.dumps(data)[:200]}") asyncio.run(stream_compressed()) ``` ## Mixed identifier subscribe You can mix slugs, condition IDs, and token IDs in a single subscribe: ```python theme={null} await ws.send(json.dumps({ "action": "subscribe", "markets": [ "what-price-will-bitcoin-hit-in-march-2026", # slug "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", # condition ID "73624432805780182150964443951045800666977811185963019133914618974858599458273" # token ID ] })) ``` # Orderbook Integrity (PN1) Source: https://docs.polynode.dev/orderbook/integrity Opt-in sequence numbers and deterministic checksums for detecting gaps or divergence in a local Orderbook Stream mirror. PN1 lets a client verify that its local bid/ask depth matches the depth delivered by PolyNode. It adds a per-token sequence number and checksum to the existing Orderbook Stream without changing the default stream. Enable it with one flag: ```text theme={null} wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY&integrity=1 ``` `pn1` means **PolyNode orderbook integrity protocol, version 1**. You only send `integrity=1`; the protocol name appears in server messages so the checksum bytes are unambiguous. > [!NOTE] > > PN1 verifies the continuity and resulting state of **PolyNode-delivered depth**. It is not a Polymarket sequence number, does not call Polymarket while processing a frame, and is not a cryptographic signature. PolyNode's separate upstream accuracy monitoring remains out of band and adds no stream latency. ## The client rule For each token: 1. Accept a message with `anchor: true` as a new baseline. Replace the entire local book, compute PN1, compare the checksum, and store `seq`. 2. For the next depth update, require `prev_seq` to equal the stored sequence. 3. Apply every changed level. A size of `"0"` removes that price; every other size is the new absolute size. 4. Recompute PN1 and require it to equal the message checksum. 5. Store `seq` only after both checks pass. 6. On any failure, stop using that token and request a new anchor. ```json theme={null} {"action":"resync","markets":["TOKEN_ID"]} ``` The server gates that token while it creates the ordered replacement anchor. It replies with `resyncing`, a `book_snapshot` anchor, then `snapshots_done` with `"reason":"resync"`. If one is already in flight, `resync_in_progress` tells you to keep the token gated and retry after `retry_after_ms`. If an acknowledged anchor cannot complete, the server fails closed with `integrity_backpressure` or `integrity_internal_reset` and closes the socket; reconnect for fresh anchors. ## Wire format The subscribe acknowledgement is queued before any anchors: ```json theme={null} { "type": "subscribed", "markets": 2, "integrity": { "enabled": true, "protocol": "pn1" } } ``` Every subscribed token receives a standalone snapshot, including an empty book: ```json theme={null} { "type": "book_snapshot", "asset_id": "TOKEN_ID", "bids": [], "asks": [], "integrity": { "protocol": "pn1", "anchor": true, "seq": 812, "checksum": "64-lowercase-hex-characters" } } ``` Depth mutations carry the post-update checksum and consecutive sequence: ```json theme={null} { "type": "book_update", "asset_id": "TOKEN_ID", "bids": [{"price":"0.51","size":"25"}], "asks": [], "integrity": { "protocol": "pn1", "prev_seq": 812, "seq": 813, "checksum": "64-lowercase-hex-characters" } } ``` In integrity mode, each depth-mutating `price_change` is token-scoped: it has a top-level `asset_id` and exactly one row in `assets`. This keeps verification identical for every depth frame. A non-depth `price_change` has no `integrity` object. `last_trade_price` never changes depth, never advances `seq`, and has no checksum. The normal stream (`integrity` omitted or `integrity=0`) keeps its existing payloads. Integrity mode does not support `markets:["*"]`; pass an explicit list of up to 500 resolved token IDs. Existing account limits still apply if they are lower. The process-wide launch limit is 5,000 unique PN1 tokens. ## PN1 checksum PN1 stores one canonical size for each `(side, price)` level. `B` means bid and `A` means ask. Canonical decimal rules: * Accept only a non-negative base-10 string with ASCII digits and at most one decimal point. * Add a missing integer zero, remove leading integer zeroes, and remove trailing fractional zeroes. * Remove an empty fraction and decimal point. Every representation of zero becomes `0`. * A canonical size of `0` removes the level. Examples: `.50`, `0.500`, and `000.5000` are all `0.5`; `01.000` is `1`. For every active level: ```text theme={null} level_hash = SHA256( UTF8("pn1:level\0") || side || UTF8("\0") || UTF8(canonical_price) || UTF8("\0") || UTF8(canonical_size) ) ``` XOR all 32-byte level hashes together. The published checksum is: ```text theme={null} SHA256( UTF8("pn1:book\0") || ASCII(bid_count) || UTF8("\0") || ASCII(ask_count) || UTF8("\0") || xor_accumulator_32_bytes ) ``` Rust is not part of the client contract. These bytes can be produced in any language with SHA-256, UTF-8/ASCII byte encoding, and byte-array XOR. The fixed vectors below let a Go, Java, C#, C++, or other implementation confirm that it produces the same result before connecting. The simplest client can recompute from its complete local book after every update in O(total depth). The incremental accumulator shown below produces the identical checksum in O(changed levels). The full-recompute functions accept the same `[{"price":"...","size":"..."}]` bid and ask arrays as a snapshot. If your local book uses maps, convert each map to those rows before calling the function. | Complete book | Expected PN1 checksum | | - | - | | no bids or asks | `f9990dc511a3f5eabf06565ee7f52801621e28d7f2d3509d6fbda91e561edecf` | | bid `0.50` / `10.000`; ask `0.6000` / `20` | `a1ec7486bc53e14c4294f08e9298362fe7b5c6495c474e8c447e27ea976eb93a` | | bids `0.5` / `12.500` and `00.4900` / `3.0`; no asks | `7829126b80f3eccac2ab4ecc0e999b90f061df3214db0d2717165834a57d66be` | On a live frame, compute the checksum after applying that frame and compare it to `integrity.checksum`. No REST request, Rust process, SDK, or server-side helper is involved on the client. ## Copyable checksum implementations Choose the language your orderbook client already uses. Node.js and Python include both full-recompute and incremental forms; Go and Rust show the shortest full-recompute form. Every block is executable and contains the same fixed PN1 vectors. > [accordion] Node.js checksum reference > > This implementation uses only the Node.js standard library. > > ```javascript theme={null} > import { createHash } from "node:crypto"; > > const sha256 = (bytes) => createHash("sha256").update(bytes).digest(); > > function canonicalDecimal(value) { > if (typeof value !== "string" || !/^(?=.*\d)\d*\.?\d*$/.test(value)) { > throw new Error(`invalid PN1 decimal: ${JSON.stringify(value)}`); > } > let [integer = "", fraction = ""] = value.split("."); > integer = integer.replace(/^0+/, "") || "0"; > fraction = fraction.replace(/0+$/, ""); > return fraction ? `${integer}.${fraction}` : integer; > } > > function levelHash(side, price, size) { > return sha256(Buffer.concat([ > Buffer.from("pn1:level\0"), Buffer.from(side), Buffer.from("\0"), > Buffer.from(price), Buffer.from("\0"), Buffer.from(size), > ])); > } > > function xorInto(accumulator, digest) { > for (let i = 0; i < 32; i++) accumulator[i] ^= digest[i]; > } > > function finishChecksum(bidCount, askCount, accumulator) { > return sha256(Buffer.concat([ > Buffer.from("pn1:book\0"), Buffer.from(String(bidCount)), Buffer.from("\0"), > Buffer.from(String(askCount)), Buffer.from("\0"), accumulator, > ])).toString("hex"); > } > > // Simplest option: call this after each update using your complete local book. > // It is O(total depth), but has no retained checksum state. > function checksumFromScratch(bids, asks) { > const accumulator = Buffer.alloc(32); > let bidCount = 0, askCount = 0; > for (const [side, rows] of [["B", bids], ["A", asks]]) { > const seen = new Set(); > for (const { price: rawPrice, size: rawSize } of rows) { > const price = canonicalDecimal(rawPrice); > const size = canonicalDecimal(rawSize); > if (size === "0") continue; > if (seen.has(price)) throw new Error(`duplicate PN1 ${side} level: ${price}`); > seen.add(price); > xorInto(accumulator, levelHash(side, price, size)); > if (side === "B") bidCount++; else askCount++; > } > } > return finishChecksum(bidCount, askCount, accumulator); > } > > class PN1Book { > constructor() { > this.bids = new Map(); > this.asks = new Map(); > this.xor = Buffer.alloc(32); > } > > apply(side, rawPrice, rawSize) { > if (side !== "B" && side !== "A") throw new Error(`invalid PN1 side: ${side}`); > const price = canonicalDecimal(rawPrice); > const size = canonicalDecimal(rawSize); > const levels = side === "B" ? this.bids : this.asks; > const oldSize = levels.get(price); > if (oldSize !== undefined) xorInto(this.xor, levelHash(side, price, oldSize)); > levels.delete(price); > if (size !== "0") { > xorInto(this.xor, levelHash(side, price, size)); > levels.set(price, size); > } > } > > replace(bids, asks) { > this.bids.clear(); this.asks.clear(); this.xor.fill(0); > for (const [side, rows] of [["B", bids], ["A", asks]]) { > const seen = new Set(); > for (const { price: rawPrice, size: rawSize } of rows) { > const price = canonicalDecimal(rawPrice); > const size = canonicalDecimal(rawSize); > if (size === "0") continue; > if (seen.has(price)) throw new Error(`duplicate PN1 ${side} level: ${price}`); > seen.add(price); > this.apply(side, price, size); > } > } > } > > checksum() { > return finishChecksum(this.bids.size, this.asks.size, this.xor); > } > } > > const vectors = [ > [[], [], "f9990dc511a3f5eabf06565ee7f52801621e28d7f2d3509d6fbda91e561edecf"], > [[{price:"0.50",size:"10.000"}], [{price:"0.6000",size:"20"}], "a1ec7486bc53e14c4294f08e9298362fe7b5c6495c474e8c447e27ea976eb93a"], > [[{price:"0.5",size:"12.500"},{price:"00.4900",size:"3.0"}], [], "7829126b80f3eccac2ab4ecc0e999b90f061df3214db0d2717165834a57d66be"], > ]; > > for (const [bids, asks, expected] of vectors) { > if (checksumFromScratch(bids, asks) !== expected) { > throw new Error("PN1 full-recompute vector mismatch"); > } > const book = new PN1Book(); > book.replace(bids, asks); > if (book.checksum() !== expected) throw new Error("PN1 incremental vector mismatch"); > } > console.log("PN1 fixed vectors: OK"); > ``` > [accordion] Python checksum reference > > This implementation uses only the Python standard library. > > ```python theme={null} > import hashlib > > def canonical_decimal(value: str) -> str: > if not isinstance(value, str) or not value or not value.isascii(): > raise ValueError(f"invalid PN1 decimal: {value!r}") > if value.count(".") > 1 or any(c != "." and not c.isdigit() for c in value): > raise ValueError(f"invalid PN1 decimal: {value!r}") > integer, dot, fraction = value.partition(".") > if not any(c.isdigit() for c in value): > raise ValueError(f"invalid PN1 decimal: {value!r}") > integer = integer.lstrip("0") or "0" > fraction = fraction.rstrip("0") > return f"{integer}.{fraction}" if fraction else integer > > def level_hash(side: bytes, price: str, size: str) -> bytes: > return hashlib.sha256( > b"pn1:level\0" + side + b"\0" + price.encode() + b"\0" + size.encode() > ).digest() > > def xor_into(accumulator: bytearray, digest: bytes): > for i, value in enumerate(digest): > accumulator[i] ^= value > > def finish_checksum(bid_count: int, ask_count: int, accumulator: bytes) -> str: > body = (b"pn1:book\0" + str(bid_count).encode() + b"\0" + > str(ask_count).encode() + b"\0" + bytes(accumulator)) > return hashlib.sha256(body).hexdigest() > > # Simplest option: call this after each update using your complete local book. > # It is O(total depth), but has no retained checksum state. > def checksum_from_scratch(bids, asks) -> str: > accumulator = bytearray(32) > bid_count = ask_count = 0 > for side, rows in ((b"B", bids), (b"A", asks)): > seen = set() > for row in rows: > price = canonical_decimal(row["price"]) > size = canonical_decimal(row["size"]) > if size == "0": > continue > if price in seen: > raise ValueError(f"duplicate PN1 level: {price}") > seen.add(price) > xor_into(accumulator, level_hash(side, price, size)) > if side == b"B": > bid_count += 1 > else: > ask_count += 1 > return finish_checksum(bid_count, ask_count, accumulator) > > class PN1Book: > def __init__(self): > self.bids, self.asks = {}, {} > self.xor = bytearray(32) > > def apply(self, side: bytes, raw_price: str, raw_size: str): > if side not in (b"B", b"A"): > raise ValueError(f"invalid PN1 side: {side!r}") > price, size = canonical_decimal(raw_price), canonical_decimal(raw_size) > levels = self.bids if side == b"B" else self.asks > old_size = levels.pop(price, None) > if old_size is not None: > self._xor(level_hash(side, price, old_size)) > if size != "0": > self._xor(level_hash(side, price, size)) > levels[price] = size > > def replace(self, bids, asks): > self.bids, self.asks, self.xor = {}, {}, bytearray(32) > for side, rows in ((b"B", bids), (b"A", asks)): > seen = set() > for row in rows: > price = canonical_decimal(row["price"]) > size = canonical_decimal(row["size"]) > if size == "0": > continue > if price in seen: > raise ValueError(f"duplicate PN1 level: {price}") > seen.add(price) > self.apply(side, price, size) > > def checksum(self) -> str: > return finish_checksum(len(self.bids), len(self.asks), self.xor) > > def _xor(self, digest: bytes): > xor_into(self.xor, digest) > > vectors = ( > ([], [], "f9990dc511a3f5eabf06565ee7f52801621e28d7f2d3509d6fbda91e561edecf"), > ([{"price":"0.50","size":"10.000"}], [{"price":"0.6000","size":"20"}], > "a1ec7486bc53e14c4294f08e9298362fe7b5c6495c474e8c447e27ea976eb93a"), > ([{"price":"0.5","size":"12.500"},{"price":"00.4900","size":"3.0"}], [], > "7829126b80f3eccac2ab4ecc0e999b90f061df3214db0d2717165834a57d66be"), > ) > for bids, asks, expected in vectors: > assert checksum_from_scratch(bids, asks) == expected > book = PN1Book() > book.replace(bids, asks) > assert book.checksum() == expected > print("PN1 fixed vectors: OK") > ``` > [accordion] Go full-recompute reference > > Go's standard library supplies SHA-256. This version favors clarity and recomputes from the complete local book. > > ```go theme={null} > package main > > import ( > "crypto/sha256" > "encoding/hex" > "fmt" > "strconv" > "strings" > ) > > type Level struct{ Price, Size string } > > func canonicalDecimal(value string) (string, error) { > if value == "" { > return "", fmt.Errorf("invalid PN1 decimal: %q", value) > } > dot, digits := -1, 0 > for i := 0; i < len(value); i++ { > switch b := value[i]; { > case b == '.': > if dot >= 0 { > return "", fmt.Errorf("invalid PN1 decimal: %q", value) > } > dot = i > case b >= '0' && b <= '9': > digits++ > default: > return "", fmt.Errorf("invalid PN1 decimal: %q", value) > } > } > if digits == 0 { > return "", fmt.Errorf("invalid PN1 decimal: %q", value) > } > integer, fraction := value, "" > if dot >= 0 { > integer, fraction = value[:dot], value[dot+1:] > } > integer = strings.TrimLeft(integer, "0") > if integer == "" { > integer = "0" > } > fraction = strings.TrimRight(fraction, "0") > if fraction == "" { > return integer, nil > } > return integer + "." + fraction, nil > } > > func levelHash(side byte, price, size string) [32]byte { > h := sha256.New() > h.Write([]byte("pn1:level\x00")) > h.Write([]byte{side, 0}) > h.Write([]byte(price)) > h.Write([]byte{0}) > h.Write([]byte(size)) > var digest [32]byte > copy(digest[:], h.Sum(nil)) > return digest > } > > func finishChecksum(bids, asks int, accumulator [32]byte) string { > h := sha256.New() > h.Write([]byte("pn1:book\x00")) > h.Write([]byte(strconv.Itoa(bids))) > h.Write([]byte{0}) > h.Write([]byte(strconv.Itoa(asks))) > h.Write([]byte{0}) > h.Write(accumulator[:]) > return hex.EncodeToString(h.Sum(nil)) > } > > func checksumFromScratch(bids, asks []Level) (string, error) { > var accumulator [32]byte > counts := [2]int{} > sides := []struct { > tag byte > rows []Level > }{{'B', bids}, {'A', asks}} > for sideIndex, side := range sides { > seen := map[string]bool{} > for _, row := range side.rows { > price, err := canonicalDecimal(row.Price) > if err != nil { > return "", err > } > size, err := canonicalDecimal(row.Size) > if err != nil { > return "", err > } > if size == "0" { > continue > } > if seen[price] { > return "", fmt.Errorf("duplicate PN1 level: %s", price) > } > seen[price] = true > digest := levelHash(side.tag, price, size) > for i := range accumulator { > accumulator[i] ^= digest[i] > } > counts[sideIndex]++ > } > } > return finishChecksum(counts[0], counts[1], accumulator), nil > } > > func main() { > vectors := []struct { > bids, asks []Level > expected string > }{ > {nil, nil, "f9990dc511a3f5eabf06565ee7f52801621e28d7f2d3509d6fbda91e561edecf"}, > {[]Level{{"0.50", "10.000"}}, []Level{{"0.6000", "20"}}, > "a1ec7486bc53e14c4294f08e9298362fe7b5c6495c474e8c447e27ea976eb93a"}, > {[]Level{{"0.5", "12.500"}, {"00.4900", "3.0"}}, nil, > "7829126b80f3eccac2ab4ecc0e999b90f061df3214db0d2717165834a57d66be"}, > } > for _, vector := range vectors { > got, err := checksumFromScratch(vector.bids, vector.asks) > if err != nil || got != vector.expected { > panic("PN1 vector mismatch") > } > } > fmt.Println("PN1 fixed vectors: OK") > } > ``` > [accordion] Rust full-recompute reference > > Rust's standard library does not include SHA-256, so add `sha2 = "0.10"` to `Cargo.toml`. No PolyNode SDK is required. > > ```rust theme={null} > use sha2::{Digest, Sha256}; > use std::collections::HashSet; > > #[derive(Clone, Copy)] > struct Level<'a> { > price: &'a str, > size: &'a str, > } > > fn canonical_decimal(value: &str) -> Result { > if value.is_empty() || !value.is_ascii() { > return Err(format!("invalid PN1 decimal: {value:?}")); > } > let mut dot = None; > let mut digits = 0; > for (index, byte) in value.bytes().enumerate() { > if byte == b'.' { > if dot.replace(index).is_some() { > return Err(format!("invalid PN1 decimal: {value:?}")); > } > } else if byte.is_ascii_digit() { > digits += 1; > } else { > return Err(format!("invalid PN1 decimal: {value:?}")); > } > } > if digits == 0 { > return Err(format!("invalid PN1 decimal: {value:?}")); > } > let (integer, fraction) = match dot { > Some(index) => (&value[..index], &value[index + 1..]), > None => (value, ""), > }; > let integer = integer.trim_start_matches('0'); > let integer = if integer.is_empty() { "0" } else { integer }; > let fraction = fraction.trim_end_matches('0'); > Ok(if fraction.is_empty() { > integer.to_string() > } else { > format!("{integer}.{fraction}") > }) > } > > fn level_hash(side: u8, price: &str, size: &str) -> [u8; 32] { > let mut hasher = Sha256::new(); > hasher.update(b"pn1:level\0"); > hasher.update([side]); > hasher.update(b"\0"); > hasher.update(price.as_bytes()); > hasher.update(b"\0"); > hasher.update(size.as_bytes()); > hasher.finalize().into() > } > > fn finish_checksum(bids: usize, asks: usize, accumulator: [u8; 32]) -> String { > let mut hasher = Sha256::new(); > hasher.update(b"pn1:book\0"); > hasher.update(bids.to_string().as_bytes()); > hasher.update(b"\0"); > hasher.update(asks.to_string().as_bytes()); > hasher.update(b"\0"); > hasher.update(accumulator); > hasher > .finalize() > .iter() > .map(|byte| format!("{byte:02x}")) > .collect() > } > > fn checksum_from_scratch(bids: &[Level<'_>], asks: &[Level<'_>]) -> Result { > let mut accumulator = [0_u8; 32]; > let mut counts = [0_usize; 2]; > for (side_index, (side, rows)) in [(b'B', bids), (b'A', asks)].into_iter().enumerate() { > let mut seen = HashSet::new(); > for row in rows { > let price = canonical_decimal(row.price)?; > let size = canonical_decimal(row.size)?; > if size == "0" { > continue; > } > if !seen.insert(price.clone()) { > return Err(format!("duplicate PN1 level: {price}")); > } > let digest = level_hash(side, &price, &size); > for (current, value) in accumulator.iter_mut().zip(digest) { > *current ^= value; > } > counts[side_index] += 1; > } > } > Ok(finish_checksum(counts[0], counts[1], accumulator)) > } > > fn main() { > let vectors = vec![ > ( > vec![], > vec![], > "f9990dc511a3f5eabf06565ee7f52801621e28d7f2d3509d6fbda91e561edecf", > ), > ( > vec![Level { > price: "0.50", > size: "10.000", > }], > vec![Level { > price: "0.6000", > size: "20", > }], > "a1ec7486bc53e14c4294f08e9298362fe7b5c6495c474e8c447e27ea976eb93a", > ), > ( > vec![ > Level { > price: "0.5", > size: "12.500", > }, > Level { > price: "00.4900", > size: "3.0", > }, > ], > vec![], > "7829126b80f3eccac2ab4ecc0e999b90f061df3214db0d2717165834a57d66be", > ), > ]; > for (bids, asks, expected) in vectors { > assert_eq!(checksum_from_scratch(&bids, &asks).unwrap(), expected); > } > println!("PN1 fixed vectors: OK"); > } > ``` ## Applying frames Use one `PN1Book` and stored sequence per token, per connection. This block uses the Node.js `PN1Book` above and handles standalone anchors, batched updates, targeted resync, terminal errors, and optional `compress=zlib` frames: ```js theme={null} import { inflateRawSync } from "node:zlib"; function tokenHint(update) { const token = update?.asset_id ?? update?.assets?.[0]?.asset_id; return typeof token === "string" && token ? token : null; } function acceptDepthFrame(states, update) { const proof = update.integrity; const hint = tokenHint(update); if (update.type === "last_trade_price") { if (proof) throw new Error(`last_trade_price carried PN1: ${hint}`); return; } if (!proof) { if (update.type === "price_change" && Array.isArray(update.assets) && !update.assets.some(row => row.size !== undefined || row.side !== undefined)) { return; // a non-depth price_change } throw new Error(`missing PN1 proof: ${hint}`); } const token = update.asset_id; if (typeof token !== "string" || !token) { throw new Error("PN1 frame missing top-level asset_id"); } if (proof.protocol !== "pn1" || !Number.isSafeInteger(proof.seq) || proof.seq < 0 || !/^[0-9a-f]{64}$/.test(proof.checksum ?? "")) { throw new Error(`invalid PN1 proof: ${token}`); } if (proof.anchor === true) { if (update.type !== "book_snapshot" || !Array.isArray(update.bids) || !Array.isArray(update.asks)) throw new Error(`invalid anchor: ${token}`); const book = new PN1Book(); book.replace(update.bids, update.asks); if (book.checksum() !== proof.checksum) throw new Error(`bad anchor: ${token}`); states.set(token, { book, seq: proof.seq, checksum: proof.checksum }); return; } const state = states.get(token); if (!state) throw new Error(`missing anchor: ${token}`); if (proof.seq === state.seq && proof.checksum === state.checksum) return; if (!Number.isSafeInteger(proof.prev_seq) || proof.prev_seq < 0 || proof.prev_seq !== state.seq) throw new Error(`sequence gap: ${token}`); if (proof.seq !== proof.prev_seq + 1) throw new Error(`bad sequence: ${token}`); if (update.type === "book_update") { if (!Array.isArray(update.bids) || !Array.isArray(update.asks)) { throw new Error(`invalid book_update: ${token}`); } for (const row of update.bids) state.book.apply("B", row.price, row.size); for (const row of update.asks) state.book.apply("A", row.price, row.size); } else if (update.type === "price_change") { if (!Array.isArray(update.assets) || update.assets.length !== 1 || update.assets[0].asset_id !== token) { throw new Error(`invalid price_change: ${token}`); } const row = update.assets[0]; const side = row.side === "BUY" ? "B" : row.side === "SELL" ? "A" : null; if (!side) throw new Error(`invalid side: ${token}`); state.book.apply(side, row.price, row.size); } else throw new Error(`unknown depth frame: ${token}`); const checksum = state.book.checksum(); if (checksum !== proof.checksum) throw new Error(`checksum mismatch: ${token}`); Object.assign(state, { seq: proof.seq, checksum }); } function parsePn1Message(data) { if (typeof data === "string") return JSON.parse(data); let bytes; if (data instanceof ArrayBuffer) bytes = Buffer.from(data); else if (ArrayBuffer.isView(data)) { bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } else throw new Error("unsupported WebSocket frame type"); return JSON.parse(inflateRawSync(bytes).toString("utf8")); } function installPn1Verification(ws, { onTokenInvalid = (token, error) => console.error(`PN1 gated ${token}:`, error), onReconnectRequired = error => console.error("PN1 reconnect required:", error), } = {}) { const states = new Map(); const pendingResync = new Set(); let terminal = false; ws.binaryType = "arraybuffer"; const requestResync = token => { if (typeof token !== "string" || !token) throw new Error("cannot resync unknown token"); states.delete(token); // gate before sending; queued deltas are now unusable if (pendingResync.has(token)) return; pendingResync.add(token); ws.send(JSON.stringify({ action: "resync", markets: [token] })); }; const failConnection = error => { if (terminal) return; terminal = true; states.clear(); pendingResync.clear(); try { ws.close(); } finally { onReconnectRequired(error); } }; const verify = update => { const token = tokenHint(update); try { acceptDepthFrame(states, update); if (update.integrity?.anchor === true) pendingResync.delete(token); } catch (error) { if (!token) throw error; states.delete(token); // A bad replacement anchor needs a new request; queued deltas do not. if (update.integrity?.anchor === true) pendingResync.delete(token); onTokenInvalid(token, error); requestResync(token); } }; ws.addEventListener("message", ({ data }) => { try { const message = parsePn1Message(data); if (message.error === "resync_in_progress") { const delay = Number.isSafeInteger(message.retry_after_ms) && message.retry_after_ms >= 0 ? message.retry_after_ms : 250; setTimeout(() => { if (terminal) return; for (const token of pendingResync) { ws.send(JSON.stringify({ action: "resync", markets: [token] })); } }, delay); } else if (message.error) { failConnection(new Error(`${message.error}: ${message.message ?? ""}`)); } else if (message.type === "batch") { if (!Array.isArray(message.updates)) throw new Error("invalid PN1 batch"); message.updates.forEach(verify); } else if (message.type === "book_snapshot") { verify(message); } } catch (error) { failConnection(error); } }); return { states, requestResync }; } // After opening the WebSocket: // const pn1 = installPn1Verification(ws, { // onReconnectRequired: error => reconnectWithACompletelyNewSocket(error), // }); ``` Keep your normal WebSocket `close` handler as the final reconnect trigger. A new connection and subscription establish new anchors; never reuse sequence state across sockets. > [!WARNING] > > Never keep applying a token after a sequence or checksum failure. Gate it immediately and wait for a valid replacement anchor. If the server reports `integrity_backpressure` or `integrity_internal_reset`, reconnect; the new connection will establish fresh anchors. # Message Reference Source: https://docs.polynode.dev/orderbook/messages Complete reference for all message types sent and received on the Orderbook Stream. ## Client messages ### Subscribe Subscribe to orderbook updates. You can subscribe to specific markets by **slug**, **condition ID**, or **token ID**, or subscribe to the full firehose (full data stream) with `"*"`. > [tab] Firehose (all markets) > > ```json theme={null} > { > "action": "subscribe", > "markets": ["*"] > } > ``` > > Subscribes to every active Polymarket market (100,000+ tokens). Live updates start flowing immediately while snapshots stream in the background. > [tab] By slug > > ```json theme={null} > { > "action": "subscribe", > "markets": ["what-price-will-bitcoin-hit-in-march-2026"] > } > ``` > [tab] By condition ID > > ```json theme={null} > { > "action": "subscribe", > "markets": ["0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2"] > } > ``` > [tab] By token ID > > ```json theme={null} > { > "action": "subscribe", > "markets": [ > "73624432805780182150964443951045800666977811185963019133914618974858599458273", > "1666184515532238710431784265702709312060757077236443477960106115591255115343" > ] > } > ``` | Field | Type | Description | | - | - | - | | `action` | string | Must be `"subscribe"` | | `markets` | string\[] | Array of market identifiers. Use `["*"]` for the full firehose, or pass specific identifiers: slugs (e.g. `"bitcoin-100k"`), condition IDs (e.g. `"0x561ff..."`), or CLOB token IDs (numeric string). Slugs and condition IDs are resolved to their corresponding token IDs automatically. | **How identifiers are detected:** * `"*"` → firehose (all active markets) * Starts with `0x` → condition ID * All digits and longer than 10 characters → CLOB token ID * Everything else → slug Subscribing again replaces your current subscription. To add markets, send a new subscribe with the full list. ### Unsubscribe Remove all subscriptions on this connection. ```json theme={null} { "action": "unsubscribe" } ``` Pass `markets` to remove only a subset. Identifiers use the same slug, condition ID, and token ID resolver as subscribe. ### Resync (PN1) Request a new ordered integrity anchor without reconnecting: ```json theme={null} { "action": "resync", "markets": ["73624432805780182150964443951045800666977811185963019133914618974858599458273"] } ``` This action is available on connections opened with `integrity=1`. Every requested market must already be subscribed. Omit `markets` or pass an empty array to resync the full current subscription. After `resyncing`, expect a new ordered anchor and a matching completion marker. If that cannot complete, the socket fails closed with a terminal integrity error. If an anchor for any requested token is already in flight, the server returns `resync_in_progress`; keep that token gated and retry after the supplied delay. ### Ping Client-initiated keepalive. ```json theme={null} { "action": "ping" } ``` Response: `{"type": "pong"}` *** ## Server messages ### `subscribed` Acknowledgment after a successful subscribe. The response format differs slightly depending on whether you subscribed to specific markets or the firehose. > [tab] Firehose > > ```json theme={null} > { > "type": "subscribed", > "firehose": true, > "markets": 104972 > } > ``` > > | Field | Type | Description | > | - | - | - | > | `firehose` | boolean | `true` when subscribed to the full firehose | > | `markets` | number | Total number of active tokens you're now receiving updates for | > [tab] Specific markets > > ```json theme={null} > { > "type": "subscribed", > "markets": 4, > "resolved_from": { > "token_ids": 0, > "slugs": 1, > "condition_ids": 0 > } > } > ``` > > | Field | Type | Description | > | - | - | - | > | `markets` | number | Total number of token IDs now subscribed (after resolution) | > | `resolved_from` | object | Breakdown of how many input entries were detected as each type | > | `resolved_from.token_ids` | number | Entries passed through as raw token IDs | > | `resolved_from.slugs` | number | Entries resolved from slugs | > | `resolved_from.condition_ids` | number | Entries resolved from condition IDs | > [tab] PN1 integrity > > ```json theme={null} > { > "type": "subscribed", > "markets": 2, > "integrity": { > "enabled": true, > "protocol": "pn1" > } > } > ``` > > The acknowledgement is queued before the standalone PN1 anchor snapshots. See [Orderbook Integrity](/orderbook/integrity). > [!TIP] > > If you subscribe with a slug and `markets` comes back as 0, the slug didn't match any known event. Use the [search API](https://api.polynode.dev/v1/search?q=bitcoin) to find the correct slug. ### `snapshot_batch` Orderbook snapshots delivered in batches after subscribing. For small subscriptions (under 100 tokens), snapshots arrive in a single batch almost instantly. For large subscriptions (firehose), snapshots are streamed in batches of 50 every 200ms to avoid flooding your connection. PN1 integrity connections instead receive one standalone `book_snapshot` anchor for every subscribed token, including empty books. ```json theme={null} { "type": "snapshot_batch", "count": 2, "total_sent": 2, "snapshots": [ { "type": "book_snapshot", "asset_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "market": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "condition_id": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "event_title": "Netanyahu out by...?", "question": "Netanyahu out by end of 2026?", "outcome": "Yes", "slug": "netanyahu-out-before-2027", "bids": [ { "price": "0.01", "size": "1130070" }, { "price": "0.02", "size": "71015.52" } ], "asks": [ { "price": "0.99", "size": "17615.05" }, { "price": "0.98", "size": "5000" } ] } ] } ``` | Field | Type | Description | | - | - | - | | `count` | number | Number of snapshots in this batch | | `total_sent` | number | Running total of snapshots sent so far | | `snapshots` | object\[] | Array of `book_snapshot` objects (see below) | Once all snapshots have been delivered, you'll receive a completion marker: ```json theme={null} { "type": "snapshots_done", "total": 12239 } ``` > [!TIP] > > Only tokens with active orderbook data are included in snapshots. Empty books are skipped. You'll still receive live `price_change` and `book_update` events for all subscribed tokens via batched updates. ### `book_snapshot` Full orderbook state for a token. Sent inside `snapshot_batch` messages after subscribing, and occasionally in `batch` updates when the upstream source sends a full refresh. ```json theme={null} { "type": "book_snapshot", "asset_id": "73624432805780182150964443951045800666977811185963019133914618974858599458273", "market": "0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2", "condition_id": "0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2", "event_title": "What price will Bitcoin hit in March?", "question": "Will Bitcoin reach $150,000 in March?", "outcome": "Yes", "slug": "what-price-will-bitcoin-hit-in-march-2026", "bids": [ { "price": "0.001", "size": "8604930.58" }, { "price": "0.002", "size": "4851192.42" } ], "asks": [ { "price": "0.999", "size": "6152045.08" }, { "price": "0.998", "size": "55007.54" }, { "price": "0.997", "size": "5000" } ] } ``` | Field | Type | Description | | - | - | - | | `asset_id` | string | Polymarket CLOB token ID | | `market` | string | Condition ID (hex) | | `condition_id` | string | Condition ID (hex), same as `market` | | `event_title` | string | Parent event title (e.g. "What price will Bitcoin hit in March?") | | `question` | string | Specific market question (e.g. "Will Bitcoin reach \$150,000 in March?") | | `outcome` | string | Which outcome this token represents ("Yes" or "No") | | `slug` | string | URL-friendly slug for the event page on Polymarket | | `bids` | PriceLevel\[] | Buy orders, sorted by price descending | | `asks` | PriceLevel\[] | Sell orders, sorted by price ascending | | `integrity` | object | Present in PN1 mode. A full snapshot has `protocol`, `anchor: true`, `seq`, and the post-snapshot `checksum`. | Each `PriceLevel` is `{"price": "0.55", "size": "1000.00"}` where price is the probability (0 to 1) and size is the number of shares. > [!TIP] > > If `bids` and `asks` are both empty, the market exists but has no active orders. You'll still receive `price_change` updates in batches when the price moves. ### `batch` Batched updates delivered every 250ms. Contains all changes for your subscribed tokens since the last batch. Multiple updates to the same price level within a batch window are coalesced into a single net change, reducing bandwidth without losing accuracy. With PN1, integrity metadata belongs to each depth update—not to this outer batch—because sequence continuity is per token. ```json theme={null} { "type": "batch", "ts": 1773794605604, "count": 4, "updates": [ { "type": "price_change", "market": "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "slug": "netanyahu-out-before-2027", "assets": [ { "asset_id": "66255671088804707681511323064315150986307471908131081808279119719218775249892", "outcome": "No", "price": "0.55", "size": "2500", "side": "BUY", "best_bid": "0.55", "best_ask": "0.56" }, { "asset_id": "114694726451307654528948558967898493662917070661203465131156925998487819889437", "outcome": "Yes", "price": "0.45", "size": "0", "side": "SELL", "best_bid": "0.44", "best_ask": "0.46" } ] }, { "type": "book_update", "asset_id": "73624432805780182150964443951045800666977811185963019133914618974858599458273", "market": "0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2", "outcome": "Yes", "slug": "what-price-will-bitcoin-hit-in-march-2026", "bids": [ { "price": "0.45", "size": "12000" } ], "asks": [] } ] } ``` | Field | Type | Description | | - | - | - | | `ts` | number | Batch timestamp (Unix milliseconds) | | `count` | number | Number of updates in this batch | | `updates` | object\[] | Array of update objects (see below) | Each update in the `updates` array is one of: #### `price_change` A market's price level changed due to an order placement, cancellation, or fill. Each entry in `assets` describes a single level change. `size` is the absolute new size at that level — `"0"` means the level was removed. You can apply `price_change` events directly to your local book to maintain tick-accurate state without polling. | Field | Type | Description | | - | - | - | | `type` | string | `"price_change"` | | `market` | string | Condition ID | | `slug` | string | Event slug | | `assets` | object\[] | Array of per-level changes (see below) | | `asset_id` | string | PN1 only: repeats the token ID at the event level | | `integrity` | object | PN1 depth frames: `protocol`, `prev_seq`, `seq`, and post-update `checksum` | Each entry in `assets`: | Field | Type | Description | | - | - | - | | `asset_id` | string | Token ID | | `outcome` | string | Outcome label (`"Yes"`, `"No"`, etc.) | | `price` | string | The level that changed | | `size` | string | Absolute size at that level after the change. `"0"` means removed. | | `side` | string | `"BUY"` (affects bids) or `"SELL"` (affects asks) | | `best_bid` | string | Best bid on this asset after the change | | `best_ask` | string | Best ask on this asset after the change | > [!TIP] > > Multiple levels on the same `asset_id` may appear in one batch — each represents a distinct level change. The 250ms coalescer merges repeat hits on the same `(asset_id, price, side)` to last-write-wins, so you always get the most recent size for each level. > [!NOTE] > > In PN1 mode, a depth-mutating `price_change` is split into token-scoped messages with exactly one `assets` row so each row has one unambiguous sequence and checksum. The default stream keeps the existing multi-row shape. #### `book_update` Incremental change to the orderbook. Apply these to the last snapshot. | Field | Type | Description | | - | - | - | | `type` | string | `"book_update"` | | `asset_id` | string | Token ID | | `market` | string | Condition ID | | `outcome` | string | Outcome label | | `slug` | string | Event slug | | `bids` | PriceLevel\[] | Changed bid levels (size `"0"` means remove) | | `asks` | PriceLevel\[] | Changed ask levels (size `"0"` means remove) | | `integrity` | object | PN1 only: `protocol`, `prev_seq`, `seq`, and the post-update `checksum` | > [!WARNING] > > `book_update` messages are **incremental deltas**, not full replacements. To maintain an accurate orderbook: > > * If a level's `size` is `"0"`, remove that price level > * Otherwise, upsert the level (add or update) #### `book_snapshot` Occasional full orderbook replacement (sent when the upstream source resets). Same schema as the initial `book_snapshot` message above. #### `last_trade_price` A trade executed on Polymarket. Delivered for every fill, not coalesced — each trade in a batch window is its own event. `last_trade_price` does not mutate bid/ask depth, so it never advances PN1 sequence and never carries an integrity checksum. ```json theme={null} { "type": "last_trade_price", "asset_id": "196889930626949471000189353840...", "market": "0x8f3a...", "price": "0.76", "size": "5", "side": "BUY", "fee_rate_bps": "0", "timestamp": "1773991152458", "outcome": "Up", "slug": "btc-updown-15m-1773990900" } ``` | Field | Type | Description | | - | - | - | | `type` | string | `"last_trade_price"` | | `asset_id` | string | Token ID that was traded | | `market` | string | Condition ID | | `price` | string | Execution price (0-1 probability) | | `size` | string | Number of shares traded | | `side` | string | `"BUY"` or `"SELL"` | | `fee_rate_bps` | string | Fee rate in basis points | | `timestamp` | string | Unix milliseconds of the trade | | `outcome` | string | Outcome label (e.g. "Yes", "Up") | | `slug` | string | Event slug | > [!TIP] > > Use `last_trade_price` events to build trade tapes, calculate VWAP, detect large fills, or trigger alerts on execution activity. Unlike `price_change` events which fire on order placement/cancellation, these fire only when an order is actually filled. > [!NOTE] > > **Need sub-millisecond granularity?** Enterprise plans can be configured with a dedicated stream that delivers every individual orderbook event without batching, including per-event timestamps. [Contact us](mailto:josh@quantish.live) if your strategy requires tick-by-tick data. ### `unsubscribed` Acknowledgment after unsubscribe. ```json theme={null} { "type": "unsubscribed" } ``` ### `pong` Response to a client ping. ```json theme={null} { "type": "pong" } ``` ### Error messages ```json theme={null} { "error": "input_too_large", "message": "Too many markets in one request. Use markets: [\"*\"] for the full firehose, or split very large explicit lists across requests." } ``` ```json theme={null} { "error": "session_limit", "message": "Free tier 1-hour daily limit reached." } ``` | Error | Cause | | - | - | | `token_limit` | Explicit subscription resolved above 15,000 token IDs on one connection. Use `markets: ["*"]` for the full firehose, or split large explicit lists across connections. | | `input_too_large` | Request contains an unusually large explicit identifier list. Use `markets: ["*"]` for the full firehose, or split very large explicit lists across connections. | | `service_warming_up` | The Orderbook Stream accepted the connection but is still loading market metadata after a restart. Retry the subscribe shortly. | | `session_limit` | Free tier 1-hour daily session expired (resets at midnight UTC) | | `invalid_integrity_option` | The `integrity` URL parameter was present but was not `0` or `1`. | | `integrity_unavailable` | PN1 is temporarily disabled by the service operator. Retry later or reconnect without `integrity=1`. | | `integrity_firehose_unsupported` | PN1 was requested with `markets:["*"]`; use an explicit list of up to 500 resolved tokens. | | `integrity_capacity` | The process-wide 5,000-unique-token PN1 mirror limit is full. The previous valid subscription is preserved. | | `resync_resolved_empty` | A non-empty PN1 resync request did not resolve to any subscribed token. The current subscription is unchanged. | | `resync_not_subscribed` | A PN1 resync requested a token outside the current subscription. | | `resync_in_progress` | An anchor is already in flight for at least one requested PN1 token. Keep the token gated and retry after `retry_after_ms`. | | `integrity_backpressure` | Gapless delivery can no longer be guaranteed. The socket closes; reconnect for fresh anchors. | | `integrity_internal_reset` | PN1 state was reset or an invariant failed. The socket closes; reconnect for fresh anchors. | # Orderbook Stream Source: https://docs.polynode.dev/orderbook/overview Real-time orderbook data for every Polymarket market, delivered through a single WebSocket connection. PolyNode's Orderbook Stream delivers live orderbook snapshots, depth updates, and price changes for every active Polymarket market. Subscribe to the markets you care about and get enriched, human-readable data pushed to your connection in real time. > [card] 108,000+ markets > > Every active Polymarket market is tracked. Subscribe to specific markets or get everything at once. > [card] Enriched data > > Snapshots include the event title, market question, outcome label, slug, and condition ID. Streaming updates include the slug and outcome for lightweight routing. > [card] 250ms batching > > Updates are batched into 250ms windows for efficient delivery. One message per tick with all changes for your subscribed markets. > [card] Compression included > > Add `&compress=zlib` to your connection URL for \~50% bandwidth savings. Recommended for production. > [card] Optional integrity > > Add one connection flag for per-token sequences and deterministic PN1 checksums. The default stream stays unchanged. > [!TIP] > > Maintaining a local book? Enable [`integrity=1`](/orderbook/integrity) to detect a missing frame or incorrect local application immediately, then request a fresh ordered anchor on the same connection. > [!NOTE] > > Successfully delivered Order Book payloads and Chainlink price payloads share the **Order Book + Chainlink** transfer meter in your [usage dashboard](https://polynode.dev/dashboard/usage). Compression reduces counted transfer because the meter uses the encoded payload delivered to the connection. Heartbeats, acknowledgements, control frames, and failed sends do not count. See [Monthly usage allowances](/guides/rate-limits#monthly-usage-allowances). ## Quick start **1. Get an API key** ```bash theme={null} curl -s -X POST https://api.polynode.dev/v1/keys \ -H "Content-Type: application/json" \ -d '{"name": "my-app"}' ``` Save the `pn_live_...` key from the response. **2. Connect and subscribe** Subscribe using a **condition ID** or **token ID** from the REST API. Both sides of the market (Yes + No) are included automatically. ```javascript Node.js theme={null} const ws = new WebSocket("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { // Subscribe by condition ID — resolves to both Yes + No tokens ws.send(JSON.stringify({ action: "subscribe", markets: ["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"] })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "snapshot_batch") { for (const snap of msg.snapshots) { console.log(`${snap.question} [${snap.outcome}]: ${snap.bids.length} bids, ${snap.asks.length} asks`); } } else if (msg.type === "batch") { for (const update of msg.updates) { if (update.type === "price_change") { for (const asset of update.assets) { // size="0" means the level was removed; otherwise it's the new absolute size at that level. console.log(`${update.slug} [${asset.outcome}] ${asset.side} @ ${asset.price} -> size ${asset.size} (bbo: ${asset.best_bid}/${asset.best_ask})`); } } } } }; ``` ```python Python theme={null} import asyncio, json, websockets async def stream_orderbook(): async with websockets.connect("wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY") as ws: await ws.send(json.dumps({ "action": "subscribe", "markets": ["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"] })) async for message in ws: data = json.loads(message) if data["type"] == "snapshot_batch": for snap in data["snapshots"]: print(f"{snap['question']} [{snap['outcome']}]: {len(snap['bids'])} bids, {len(snap['asks'])} asks") elif data["type"] == "batch": for update in data["updates"]: if update["type"] == "price_change": for asset in update["assets"]: # size="0" removes the level; otherwise it's the new absolute size. print(f"{update['slug']} [{asset['outcome']}] {asset['side']} @ {asset['price']} -> size {asset['size']} (bbo: {asset['best_bid']}/{asset['best_ask']})") asyncio.run(stream_orderbook()) ``` ```bash CLI theme={null} npx wscat -c "wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY" # once connected, send: {"action":"subscribe","markets":["0x7cb525e831729325d651017f81cbcb6f1adde5011c7b2283babea00b4ae93ae7"]} ``` > [!TIP] > > Use the REST API to find condition IDs: `curl -s -H "x-api-key: pn_live_YOUR_KEY" "https://api.polynode.dev/v1/search?q=bitcoin"` — each result includes the `condition_id` you can pass directly to the orderbook subscribe. **3. Receive data** You'll immediately receive an orderbook snapshot for each subscribed token, then live batched updates: ```json theme={null} { "type": "book_snapshot", "asset_id": "73624432805780182150964443951045800666977811185963019133914618974858599458273", "market": "0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2", "condition_id": "0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2", "event_title": "What price will Bitcoin hit in March?", "question": "Will Bitcoin reach $150,000 in March?", "outcome": "Yes", "slug": "what-price-will-bitcoin-hit-in-march-2026", "bids": [ { "price": "0.001", "size": "8604930.58" }, { "price": "0.002", "size": "4851192.42" } ], "asks": [ { "price": "0.999", "size": "6152045.08" }, { "price": "0.998", "size": "55007.54" }, { "price": "0.997", "size": "5000" } ] } ``` ## Ways to subscribe You can identify markets using any of these formats: > [tab] Firehose (all markets) > > Subscribe to every active market with a single message. Pass `"*"` as the market identifier to get the full firehose (full data stream) of all 100,000+ tokens. > > ```json theme={null} > { > "action": "subscribe", > "markets": ["*"] > } > ``` > > The server responds with `"firehose": true` and the total number of active tokens. Live updates start flowing immediately while snapshots stream in the background. > [tab] Slug (recommended) > > The simplest way to subscribe to specific markets. Use the slug from the Polymarket event URL. The server resolves it to all token IDs for that event (typically 2 per market, one for each outcome). > > ```json theme={null} > { > "action": "subscribe", > "markets": ["what-price-will-bitcoin-hit-in-march-2026"] > } > ``` > [tab] Condition ID > > Use the hex condition ID for a specific market within an event. Resolves to the Yes + No token IDs for that market. > > ```json theme={null} > { > "action": "subscribe", > "markets": ["0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2"] > } > ``` > [tab] Token ID > > Use the raw CLOB token ID if you already have it. This matches Polymarket's market identifier. > > ```json theme={null} > { > "action": "subscribe", > "markets": [ > "73624432805780182150964443951045800666977811185963019133914618974858599458273", > "1666184515532238710431784265702709312060757077236443477960106115591255115343" > ] > } > ``` You can mix formats in a single subscribe: ```json theme={null} { "action": "subscribe", "markets": [ "what-price-will-bitcoin-hit-in-march-2026", "0xd1796c09d0d6f876f8580086ae9808ec991784e3a74b25a1830a25de71a78c96", "73624432805780182150964443951045800666977811185963019133914618974858599458273" ] } ``` ## Finding markets Use the PolyNode REST API to search for markets and find their slugs, condition IDs, or token IDs: ```bash theme={null} # Search by keyword curl -s "https://api.polynode.dev/v1/search?q=bitcoin" | python3 -m json.tool # Look up by slug curl -s "https://api.polynode.dev/v1/markets/slug/what-price-will-bitcoin-hit-in-march-2026" # Look up by condition ID curl -s "https://api.polynode.dev/v1/markets/condition/0x561ffbf7de21ef3781c441f30536b026d2b301d7a4a0145a8f526f98db049ba2" ``` Or just grab the slug from any Polymarket event URL: `polymarket.com/event/{slug}`. ## Connection URL ``` wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY ``` With compression (\~50% bandwidth savings): ``` wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib ``` With opt-in local-book integrity: ``` wss://ob.polynode.dev/ws?key=pn_live_YOUR_KEY&integrity=1 ``` Compression and integrity can be combined. See [Orderbook Integrity (PN1)](/orderbook/integrity) for the checksum algorithm and copyable Node.js, Python, Go, and Rust references. ## Subscription limits Use `markets: ["*"]` for the full all-market firehose. Explicit market lists are capped at **15,000 resolved token IDs per connection** to protect low-latency fan-out; split large explicit watchlists across connections or use the firehose path when you truly need every market. | Tier | Connections | Explicit list cap | Firehose | Session limit | | - | - | - | - | - | | **Free** | 1 | 15,000 tokens / connection | Included | 1 hour/day | | **Starter** (\$50/mo) | 10 | 15,000 tokens / connection | Included | Unlimited | | **Growth** (\$200/mo) | 50 | 15,000 tokens / connection | Included | Unlimited | | **Enterprise** (\$750/mo) | Unlimited | 15,000 tokens / connection | Included | Unlimited | Each Polymarket market has two tokens (one per outcome). Subscribing to both tokens of a market gives you the full two-sided orderbook. Plan upgrades increase the number of concurrent Orderbook Stream connections. The explicit-list token cap is a per-connection safety limit and is not removed by upgrading. PN1 integrity connections use explicit market lists only and are initially capped at **500 resolved token IDs per connection**. The all-market firehose remains available on the normal stream. > [!TIP] > > **Free tier includes the full firehose.** Subscribe to every market and see the full data flow. The only limit is a 1-hour daily session so you can properly evaluate the product before upgrading. > [!NOTE] > > **Orderbook connections are separate from event WebSocket connections.** Your plan's Event WebSocket limit applies to `ws.polynode.dev`; the limits above apply to the Orderbook Stream at `ob.polynode.dev`. Session time resets at midnight UTC. ## Connection lifecycle > [tab] Firehose > > ``` > Connect -> wss://ob.polynode.dev/ws?key=pn_live_... > <- (connection established) > > Send -> {"action": "subscribe", "markets": ["*"]} > <- {"type": "subscribed", "firehose": true, "markets": 104972} > <- {"type": "batch", "ts": ..., "updates": [...]} (live data starts immediately) > <- {"type": "snapshot_batch", "count": 50, "snapshots": [...]} (snapshots stream in parallel) > <- {"type": "batch", ...} (every 100ms) > <- {"type": "snapshot_batch", ...} (every 200ms) > <- {"type": "snapshots_done", "total": 67} > <- Ping frame (every 30s) > -> Pong frame (automatic) > ``` > > Live updates start flowing immediately. You don't have to wait for snapshots to finish. Snapshots are delivered in batches of 50 every 200ms for tokens that have active book data. > [tab] Specific markets > > ``` > Connect -> wss://ob.polynode.dev/ws?key=pn_live_... > <- (connection established) > > Send -> {"action": "subscribe", "markets": ["bitcoin-slug"]} > <- {"type": "subscribed", "markets": 4, "resolved_from": {"token_ids": 0, "slugs": 1, "condition_ids": 0}} > <- {"type": "snapshot_batch", "count": 2, "snapshots": [...]} > <- {"type": "snapshots_done", "total": 2} > > <- {"type": "batch", "ts": ..., "updates": [...]} > <- {"type": "batch", ...} (every 250ms when there are changes) > <- Ping frame (every 30s) > -> Pong frame (automatic) > > Send -> {"action": "unsubscribe"} > <- {"type": "unsubscribed"} > ``` ## Separate from the main WebSocket The Orderbook Stream runs on a **separate endpoint** (`ob.polynode.dev`) from the main PolyNode WebSocket (`ws.polynode.dev`). They are independent services: | | Main WebSocket | Orderbook Stream | | - | - | - | | **Endpoint** | `wss://ws.polynode.dev/ws` | `wss://ob.polynode.dev/ws` | | **Data** | On-chain events (settlements, trades, blocks) | Off-chain orderbook (bids, asks, prices) | | **Timing** | Pre-confirmation (pending + confirmed) | Real-time (live order placement/cancellation) | | **Use case** | Trade detection, copy trading, alerts | Market making, pricing, depth analysis | You can connect to both simultaneously with the same API key. # Coverage Source: https://docs.polynode.dev/perps/analytics/coverage GET /v3/perps/coverage Transparency metric: for each instrument, our tracked long/short open interest (from the latest position snapshots) vs the exchange's live reported OI. A transparency metric. For every instrument it reports our tracked long/short open interest (from the latest position snapshots) against the exchange's live reported OI, so you can see exactly how complete our position capture is. On the majors it runs near 100%. # Position Events Source: https://docs.polynode.dev/perps/analytics/events GET /v3/perps/events Position activity feed: opened / closed / increased / reduced / flipped. Filter by type, instrument, min_notional, address, liquidation, and after. Continue newest first through a fixed traversal with `next_cursor`. A position-activity feed of **opened**, **closed**, **increased**, **reduced**, and **flipped** events. Filter by `type`, `instrument`, `min_notional`, `address`, `liquidation`, and `after`. Responses are newest first and include `has_more` plus an opaque `next_cursor`. Send that value as `cursor` with the same filters to continue through the fixed traversal: ```text theme={null} GET /v3/perps/events?address=0xabc&limit=100 GET /v3/perps/events?address=0xabc&limit=100&cursor= ``` Cursors expire after 24 hours and cannot be reused on the liquidations route. A malformed cursor returns HTTP `400` with `{"error":"invalid cursor"}`. An expired cursor returns `{"error":"cursor has expired"}`. Changing a filter returns HTTP `400` with a clean cursor-mismatch message. Start again without the cursor in each case. # Large Positions Source: https://docs.polynode.dev/perps/analytics/large-positions GET /v3/perps/positions/large Current large open positions across all tracked accounts, notional-sorted — a live whale-position feed. Filter by `min_notional` and `instrument`. A live feed of the biggest open perps positions across every tracked account, sorted by notional. Set the floor with `?min_notional=` (USD, default 10,000), narrow to one market with `?instrument=`, and cap the count with `?limit=`. Each row is that account's current position for an instrument — address, side, size, notional, and unrealized PnL — drawn from its latest snapshot (`as_of`). Use it to watch where the size is concentrated right now. # Whale Leaderboard Source: https://docs.polynode.dev/perps/analytics/leaderboard GET /v3/perps/leaderboard Top perps accounts, ranked. `metric=equity` ranks by account equity; `metric=size` by total open notional; `metric=pnl` by total unrealized PnL. Optional `instrument` filter. **Polymarket has no perps leaderboard** — perps trades carry no account attribution, so this only exists because we snapshot every account's portfolio over time. Rank perps accounts three ways: * **`metric=equity`** (default) — by account equity. The biggest accounts by capital. * **`metric=size`** — by total open notional across all their positions. The biggest active risk-takers. * **`metric=pnl`** — by total unrealized profit/loss across their open positions. Add `?instrument=BTC-USD` to rank within a single market, and `?limit=` to control how many rows. Polymarket has no perps leaderboard, and can't easily build one: its public trade feed carries no account attribution, so there's no way to rank accounts from it. This works because we snapshot every account's portfolio continuously. Each row is drawn from that account's most recent snapshot, with an `as_of` timestamp. # Liquidations Source: https://docs.polynode.dev/perps/analytics/liquidations GET /v3/perps/liquidations Likely liquidations detected from position closes at a large loss. Returns the same stable cursor response shape as position events, with route-specific cursors. Likely liquidations are position closes detected at a large loss. Filter by `type`, `instrument`, `min_notional`, `address`, and `after`. Responses are newest first and include `has_more` plus an opaque `next_cursor`. Send that value as `cursor` with the same filters to continue through the fixed traversal: ```text theme={null} GET /v3/perps/liquidations?min_notional=10000&limit=100 GET /v3/perps/liquidations?min_notional=10000&limit=100&cursor= ``` Cursors expire after 24 hours and cannot be reused on the general position events route. A malformed cursor returns HTTP `400` with `{"error":"invalid cursor"}`. An expired cursor returns `{"error":"cursor has expired"}`. Changing a filter returns HTTP `400` with a clean cursor-mismatch message. Start again without the cursor in each case. # Perps Analytics Source: https://docs.polynode.dev/perps/analytics/overview Historical and cross-account perps data that Polymarket does not offer — whale leaderboards, positioning over time, position history, and a live large-position feed. Everything else in the Perps API is live market data. This section is different: it answers questions that **need accumulated history and a view across every account** — which Polymarket's API cannot give you, because its perps trades carry no account attribution and it only ever returns a wallet's *current* portfolio. We capture every perps account's portfolio continuously, so we can serve: | Endpoint | Question it answers | | - | - | | [Whale Leaderboard](/perps/analytics/leaderboard) | Who are the biggest perps accounts — by equity, exposure, or PnL? | | [Positioning](/perps/analytics/positioning) | Is the crowd net long or short on an instrument, and how is that shifting? | | [Large Positions](/perps/analytics/large-positions) | Which accounts are holding the biggest positions right now? | | [Position History](/perps/analytics/position-history) | How has one wallet's position changed over time? | ## Freshness and honesty These read from an archive we've been building continuously. Every row carries an `as_of` timestamp so you always know how fresh it is. Position history reaches back only as far as we've been capturing (it began July 9, 2026 and grows from there) — we never present a gap as if it were complete data. For the current, exact state of any single wallet, the live [portfolio endpoint](/perps/wallets/portfolio) is always available as a pass-through. ## A note on wallets All of these accept either address form — a Polymarket profile address or the underlying signer — and resolve it automatically ([how that works](/perps/wallet-mapping)). # Position History Source: https://docs.polynode.dev/perps/analytics/position-history GET /v3/perps/wallets/{address}/positions/history A wallet's perps positions over time — how each position changed, opened, or closed, with equity and PnL trajectory. Polymarket only returns a wallet's *current* portfolio; this is the accumulated history. Filter by `instrument` and time window (`after`/`before`). A read also captures a fresh snapshot when the latest is stale, so the current state is always included. Follow one wallet's perps positions through time — how each position grew, shrank, opened, or closed, with the mark, notional, and unrealized PnL captured at each point. Filter to a single `instrument` and bound the window with `after` / `before`. Polymarket returns only a wallet's *current* portfolio. This is the accumulated history of it, which exists nowhere else. Coverage begins when we started capturing (July 9, 2026) and grows continuously; each row carries its `as_of` timestamp. When you query, we also capture a fresh snapshot if the latest one is stale, so the current state is always part of what you get back. Accepts either address form — profile address or signer — resolved automatically. # Positioning Source: https://docs.polynode.dev/perps/analytics/positioning GET /v3/perps/positioning/{instrument} Aggregate positioning for one instrument across all tracked accounts, over time: total long size, total short size, and the net. Answers 'is the crowd long or short, and how is that shifting' — impossible from Polymarket's per-account API. How the whole market is positioned on one instrument, over time. Each row is a point in time with the total **long** size, total **short** size, and the **net** across every tracked account. Watch the net flip, or watch one side build up ahead of a move. Add `after` / `before` (Unix seconds or milliseconds) to bound the window, and `limit` for the number of points. This is a cross-account aggregate. Polymarket's API only exposes one account at a time and keeps no history, so this view doesn't exist there at all. # Smart Money Source: https://docs.polynode.dev/perps/analytics/traders GET /v3/perps/traders Rank wallets by real TRADING P&L over a window: equity change minus net deposits. Possible only because we hold both equity snapshots and on-chain collateral flows. Rank wallets by real **trading** P\&L over a window — equity change minus net deposits in that window, so growth from funding the account is stripped out. This is only possible because we hold both the equity snapshots and the on-chain collateral flows. Pick the `window` (1h, 6h, 1d, 7d, 30d). Coverage deepens as history accrues. # Basis History Source: https://docs.polynode.dev/perps/market-data/basis GET /v3/perps/basis/{instrument} The perp's premium/discount to spot over time: mark - index (absolute and in bps), from the ticker snapshots. The perp's premium or discount to spot over time — mark minus index, as an absolute number and in basis points — from the ticker snapshots (minute resolution, **newest first**). Complements the live [screener](/perps/market-data/screener). Bound with `after` / `before`, cap with `limit`. # Best Bid/Offer Source: https://docs.polynode.dev/perps/market-data/bbo GET /v3/perps/bbo/{instrument} Top-of-book best bid/offer for one instrument. Lighter than fetching the full [book](/perps/market-data/book) when you only need the touch. Streams as [`perps_bbo:`](/perps/websocket/channels). # Orderbook Source: https://docs.polynode.dev/perps/market-data/book GET /v3/perps/book/{instrument} Full order book (price/quantity levels, best-first). Use `?depth=` to limit levels per side. Levels are `[price, quantity]` pairs, best-first on both sides (bids descending, asks ascending). ## Query parameters | Parameter | Description | | - | - | | `depth` | Levels per side (default: full book) | For streaming updates subscribe to [`perps_book:`](/perps/websocket/channels) — every message there is a complete snapshot (including the immediate one on subscribe), so you replace your local book each time rather than merging deltas. # Perps Daily Activity Source: https://docs.polynode.dev/perps/market-data/daily-activity GET /v3/perps/activity/daily Chart complete UTC-day perps notional and taker flow for the platform and selected instruments. `GET /v3/perps/activity/daily` returns one UTC-day row for the complete perps trade archive, plus matching rows for any instruments you select. One request can therefore power a platform-total chart and up to 20 instrument series. Trade coverage begins on `2026-07-08`. The current UTC day has `complete: false` because more trades can still arrive. ## Request ```text theme={null} GET /v3/perps/activity/daily ``` ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `period` | string | `30d` | `1d`, `7d`, or `30d`. Do not combine it with explicit dates. | | `start_date` | date | none | Inclusive UTC date in `YYYY-MM-DD` format. Requires `end_date`. | | `end_date` | date | none | Inclusive UTC date in `YYYY-MM-DD` format. Requires `start_date`. | | `interval` | string | `day` | Only `day` is supported. | | `instruments` | CSV | none | Up to 20 instrument IDs, full symbols, or bare assets, for example `6,ETH-USD,sol`. | An explicit range can contain at most 30 days, including both endpoints. It cannot begin before `2026-07-08` or end after the current UTC date. ## Examples Get the platform total for the last seven UTC days: ```bash theme={null} curl "https://api.polynode.dev/v3/perps/activity/daily?period=7d" \ -H "x-api-key: $POLYNODE_API_KEY" ``` Add selected instrument series: ```bash theme={null} curl "https://api.polynode.dev/v3/perps/activity/daily?period=7d&instruments=BTC-USD,ETH-USD" \ -H "x-api-key: $POLYNODE_API_KEY" ``` ```json theme={null} { "interval": "day", "timezone": "UTC", "period": "7d", "start_date": "2026-08-23", "end_date": "2026-08-29", "coverage_start": "2026-07-08", "complete_through": "2026-08-28", "first_returned_date": "2026-08-23", "last_returned_date": "2026-08-29", "latest_trade_at": 1788000000, "notional_unit": "pUSD", "side_semantics": "taker direction; long is taker buy and short is taker sell", "total": { "label": "All perps", "days": [ { "date": "2026-08-23", "complete": true, "trade_count": 3812, "taker_buy_trade_count": 2010, "taker_sell_trade_count": 1802, "notional_volume_pusd": "12845000.25", "taker_buy_notional_pusd": "6740000.25", "taker_sell_notional_pusd": "6105000", "net_taker_notional_pusd": "635000.25" } ] }, "instruments": [ { "instrument_id": 6, "symbol": "BTC-USD", "days": [ { "date": "2026-08-23", "complete": true, "trade_count": 1250, "taker_buy_trade_count": 700, "taker_sell_trade_count": 550, "notional_volume_pusd": "5100000.25", "taker_buy_notional_pusd": "2900000.25", "taker_sell_notional_pusd": "2200000", "net_taker_notional_pusd": "700000.25", "base_quantity": "79.25", "taker_buy_base_quantity": "45.75", "taker_sell_base_quantity": "33.5" } ] } ] } ``` With explicit dates, `period` is returned as `custom`. Every requested day is present even when its counts and decimal strings are zero. ## Metric semantics | Fields | Meaning | | - | - | | `trade_count` | Archived executions across all instruments or within the selected instrument. | | `notional_volume_pusd` | Sum of price × base quantity, returned as an exact decimal pUSD string. | | `taker_buy_*` | Trades where the taker side is `long`. | | `taker_sell_*` | Trades where the taker side is `short`. | | `net_taker_notional_pusd` | Taker-buy notional minus taker-sell notional. It can be negative. | | `base_quantity` and side splits | Base-asset units for one selected instrument only. | The platform `total` deliberately has no base-quantity fields. BTC, ETH, gold, and other base units are not additive, while pUSD notional is. ## Completeness and freshness * `complete_through` is yesterday in UTC. The current UTC day has `complete: false`. * `first_returned_date` and `last_returned_date` describe days with archived trades; they are `null` for an entirely empty range. The `days` arrays still contain the requested zero-filled rectangle. * `latest_trade_at` is Unix seconds for the newest archived trade in the response, or `null` for an empty range. * When a requested window includes today, the whole request returns `503` if the market trade archive tip is more than 15 minutes old. A stale current window is never presented as complete or as zero activity. ## No-go interpretations * Taker BUY/SELL is market-side direction, not maker direction and not a wallet-attributed action. * The trade archive does not attribute these rows to wallets. Do not derive a trader leaderboard, wallet flow, or wallet P\&L from this route. * Notional is pUSD, not base quantity. Base quantities can be compared only within the same instrument. * This route is trade activity, not open interest, funding, positions, or liquidations. ## Errors | Status | Error | When it occurs | | - | - | - | | `400` | descriptive request error | Unsupported period/interval, conflicting or incomplete dates, a future/reversed/over-30-day range, a date before coverage, empty instrument values, or more than 20 instruments. | | `400` | unknown parameter | A query parameter is not in this route's allowlist. | | `401` | authentication error | The API key is missing or invalid. | | `404` | `unknown instrument` | An instrument ID, symbol, or asset cannot be resolved. | | `503` | `warming up` with `missing: "daily activity"` | A current window cannot pass the 15-minute archive-freshness gate, or the archive is unavailable. | Retry a `503`; do not render it as a zero-activity window. # Trade Flow / CVD Source: https://docs.polynode.dev/perps/market-data/flow GET /v3/perps/flow/{instrument} Per time bucket: taker buy versus sell notional, net quantity, and running cumulative volume delta (CVD). This is a bounded single-page series and does not accept a cursor. Order-flow analytics per time bucket: taker buy versus sell notional, net quantity, and running **cumulative volume delta** (CVD). `side` is the taker's direction (`long` means bought). Choose a `bucket` from 1m to 1d and bound the response with `after` and `before`. Buckets are **oldest first** because CVD is a running sum from the start of the window. A plain call starts at the beginning of the archive on July 9, 2026. For recent flow, pass `after` so CVD accumulates over exactly the requested window. CVD remains a bounded single-page series. This route does not accept a cursor. # Funding Rates Source: https://docs.polynode.dev/perps/market-data/funding GET /v3/perps/funding/{instrument} Hourly funding-rate history, newest first. Window with `start_timestamp`/`end_timestamp` (Unix ms). Newest first, one entry per hourly funding event, with `instrument_id`/`symbol` alongside the data. ## Query parameters | Parameter | Description | | - | - | | `after` / `before` | Time window (Unix seconds or ms, detected automatically) | | `limit` | Max rows (default 500, up to 5000) | | `start_timestamp` / `end_timestamp` | Legacy aliases of `after` / `before` (Unix ms) | Responses carry a `more` flag; page older history by moving `before` to the oldest `timestamp` you've received. The current live rate and the next funding time are on the [ticker](/perps/market-data/tickers). Rates are per funding interval (hourly) — multiply by 24×365 for an annualized figure. # Cumulative Funding Source: https://docs.polynode.dev/perps/market-data/funding-pnl GET /v3/perps/funding-pnl/{instrument} The funding-rate series plus a running sum - what a 1-unit long has paid (positive) or earned (negative) over the window. The funding-rate series plus a running sum — what a one-unit long has paid (positive) or earned (negative) over the window. Useful for funding-carry and basis analysis. Entries are **oldest first** (the cumulative sum runs forward from the start of the window). Bound with `after` / `before` to accumulate over exactly the window you want; a plain call starts at the beginning of our archive. # Instruments Source: https://docs.polynode.dev/perps/market-data/instruments GET /v3/perps/instruments Every listed perps instrument with full contract config (leverage, risk tiers, precision, funding interval), plus `first_seen`. Filter with `?category=` (crypto, index, commodity, equity). Returns the complete exchange configuration for each instrument — symbol, category, leverage and risk tiers, precision, order size limits, funding interval — plus `first_seen`, the timestamp we first observed the listing. ## Query parameters | Parameter | Description | | - | - | | `category` | Filter to one category: `crypto`, `index`, `commodity`, `equity` | New instruments appear automatically as Polymarket lists them — poll this endpoint (or watch `perps_tickers` on the WebSocket for unfamiliar ids) to pick up new listings. # Klines (OHLCV) Source: https://docs.polynode.dev/perps/market-data/klines GET /v3/perps/klines/{instrument} Candlestick data. `interval` = 1m,5m,15m,30m,1h,4h,6h,12h,1d,1w. `start` is optional (defaults to a sane window). Candles are `[open_time, open, high, low, close, volume, trade_count]`, oldest first, wrapped as `{"instrument_id", "symbol", "data", "more"}`. ## Query parameters | Parameter | Description | | - | - | | `interval` | `1m`, `5m`, `15m`, `30m`, `1h`, `4h`, `6h`, `12h`, `1d`, `1w` (default `1h`) | | `start` | Window start (Unix ms). **Optional** — defaults to `limit` candles ending now | | `end` | Window end (Unix ms) | | `limit` | Number of candles (default 100) | 1m and 1h candles stream live on [`perps_klines::`](/perps/websocket/channels) — the current candle is pushed whenever it changes, and a candle is final once one with a later `open_time` arrives. # Fees & Exchange Meta Source: https://docs.polynode.dev/perps/market-data/meta Fee schedule, exchange rate-limit tiers, contract info, collateral assets, and index composition. Five small reference endpoints round out the surface: ## Fee schedule ```bash theme={null} curl "https://api.polynode.dev/v3/perps/fees?key=$POLYNODE_API_KEY" ``` Tiered maker/taker rates by 30-day volume, per instrument category (equity instruments carry different rates than crypto/index/commodity). Base tier is 4 bps taker / 1.25 bps maker. ```json theme={null} { "fee_schedule": [ { "category": "equity", "instrument_type": "perpetual", "maker_fee_rate": "0.000125", "taker_fee_rate": "0.0004", "tiers": [ { "min_volume_30d": "0", "maker_fee_rate": "0.000125", "taker_fee_rate": "0.0004" }, { "min_volume_30d": "1000000", "maker_fee_rate": "0.0001", "taker_fee_rate": "0.00037" } ] } ] } ``` ## Exchange rate-limit tiers ```bash theme={null} curl "https://api.polynode.dev/v3/perps/limit-tiers?key=$POLYNODE_API_KEY" ``` Polymarket's exchange-level trading limits by 14-day volume. Informational — your polynode rate limits are documented [here](/perps/rate-limits). ```json theme={null} { "data": [ { "min_volume_14d": "0", "actions_per_minute_limit": 2000, "actions_burst_limit": 500, "messages_per_minute": 2000, "open_orders_limit": 1000, "rate_per_minute_limit": 750, "rate_burst_limit": 500 } ] } ``` ## Exchange info ```bash theme={null} curl "https://api.polynode.dev/v3/perps/exchange?key=$POLYNODE_API_KEY" ``` EIP-712 domain and custody contract details for the perps exchange on Polygon. ```json theme={null} { "name": "Polymarket", "version": "1", "chain_id": 137, "contract": "0xDCa4af75705dbB50f62437045afF9921947917d2" } ``` ## Collateral assets ```bash theme={null} curl "https://api.polynode.dev/v3/perps/assets?key=$POLYNODE_API_KEY" ``` Collateral token config (pUSD address, decimals, withdrawal fee). ```json theme={null} { "data": [ { "asset": "pUSD", "address": "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", "decimals": 6, "collateral_ratio": "1.00", "withdrawal_fee": "0.000000" } ] } ``` ## Index composition ```bash theme={null} curl "https://api.polynode.dev/v3/perps/index/BTC?key=$POLYNODE_API_KEY" ``` The index price for an underlying asset, plus its constituent sources when the exchange publishes them (otherwise an empty `constituents` list). ```json theme={null} { "asset": "BTC", "index_price": "64174", "constituents": [], "timestamp": 1783739743072 } ``` # Open Interest History Source: https://docs.polynode.dev/perps/market-data/open-interest GET /v3/perps/oi/{instrument} Open-interest time series (with mark price and funding at each sample) — history the exchange does not offer. Open interest is normally only visible as a live number on the [ticker](/perps/market-data/tickers). This endpoint gives you its history: Each sample carries the mark price and funding rate at that moment, so OI-vs-price studies need no joins. Samples are minute-resolution, newest first. | Parameter | Description | | - | - | | `after` / `before` | Time window (Unix seconds or ms) | | `limit` | Max samples (default 500, up to 5000) | The series accrues from July 9, 2026 onward. `/v3/perps/open-interest/{instrument}` is an alias of `/v3/perps/oi/{instrument}` — both forms work. # Screener Source: https://docs.polynode.dev/perps/market-data/screener GET /v3/perps/screener Live cross-instrument screen: per-instrument funding rate, open interest, and the **basis** (mark minus index, in bps). Sort by `funding`, `oi`, or `basis`, and filter by `min_funding`. Computed on demand — Polymarket has no cross-instrument screen. A cross-instrument screen computed live from current prices. For every instrument it returns the funding rate, open interest, and the **basis** — the mark price minus the index price, both as an absolute number and in basis points (the perp's premium or discount to spot). Sort by `funding`, `oi`, or `basis` (widest first), and filter with `min_funding` to surface only instruments paying above a threshold. Polymarket returns tickers but offers no way to sort or screen across them — this does it in one call, always on current data. # 24h Statistics Source: https://docs.polynode.dev/perps/market-data/statistics GET /v3/perps/statistics/{instrument} Rolling 24h volume, open price and hourly candles for one instrument. `volume` is 24h notional volume in USD. `klines` are the trailing hourly candles as `[open_time, open, high, low, close, volume, trade_count]`. For custom intervals and longer ranges use [klines](/perps/market-data/klines); for a volume time series with your own bucketing use [volume](/perps/market-data/volume). # Tickers Source: https://docs.polynode.dev/perps/market-data/tickers GET /v3/perps/tickers/{instrument} Live prices, open interest and funding for one instrument. `index_price` is the real underlying asset price. | Field | Meaning | | - | - | | `index_price` | External reference price of the underlying | | `mark_price` | Exchange mark used for margining and liquidations | | `last_price` | Price of the most recent trade | | `mid_price` | Orderbook midpoint | | `open_interest` | Open contracts (base-asset units) | | `funding_rate` | Current hourly funding rate | | `next_funding` | When the next funding payment occurs (ms) | Tickers update continuously; for sub-second consumption use the [`perps_tickers` WebSocket channel](/perps/websocket/channels). Omit the instrument — `GET /v3/perps/tickers` — to get every instrument's ticker in one call, wrapped as `{"data": [...]}`. # Trades Source: https://docs.polynode.dev/perps/market-data/trades GET /v3/perps/trades/{instrument} Recent executions (price, quantity, side, time). Add `after`/`before` for archived history. Archived pages are newest first and return `has_more`, `next_cursor`, and the existing `more` field. Reuse the same filters with each cursor. ## Live filters Narrow the live tape with `side` (`long` or `short`), `min_qty`, `max_qty`, and `min_notional`. For example, set `min_notional=25000` to keep only trades worth at least \$25,000. Unknown parameters return HTTP `400`. ## Historical windows Add `after` and/or `before` (Unix seconds or milliseconds) to query historical trades. History covers every execution from July 9, 2026 onward and keeps growing. The same `side`, quantity, and notional filters apply to the archive. ```text theme={null} GET /v3/perps/trades/BTC-USD?after=1787875200&before=1787961600&limit=100 ``` Archived responses preserve the existing `more` flag and also return `has_more` and an opaque `next_cursor`. When `has_more` is true, send the returned cursor with the same instrument and filters: ```text theme={null} GET /v3/perps/trades/BTC-USD?after=1787875200&before=1787961600&limit=100&cursor= ``` | Parameter | Description | | - | - | | `limit` | Max rows (default 100, up to 1000) | | `after` | Only trades after this time | | `before` | Only trades before this time | | `cursor` | Opaque `next_cursor` from the preceding archived page | Trades are **newest first** in both live and archived responses. Cursor pages belong to one fixed traversal, so new trades do not overlap or displace its later pages. Cursors expire after 24 hours. A malformed cursor returns HTTP `400` with `{"error":"invalid cursor"}`. An expired cursor returns `{"error":"cursor has expired"}`. Reusing a cursor with a different instrument or filter returns HTTP `400` and a clean mismatch message. Start again without the cursor in each case. `side` is the taker's direction: `long` means the taker bought, and `short` means the taker sold. Trades carry no account attribution. For position-level tracking, use [wallet portfolios](/perps/wallets/portfolio). # Volume History Source: https://docs.polynode.dev/perps/market-data/volume GET /v3/perps/volume/{instrument} Bucketed notional volume and trade counts. `bucket` = 1m,5m,15m,1h,4h,1d. | Parameter | Description | | - | - | | `bucket` | `1m`, `5m`, `15m`, `1h`, `4h`, `1d` (default `1h`) | | `after` / `before` | Time window (Unix seconds or ms) | | `limit` | Max buckets (default 200, up to 2000) | `notional_volume` is price × quantity summed in USD; `quantity` is base-asset units. Buckets are **newest first**. Rolled up from every archived execution, accruing from July 9, 2026 onward. # Top Depositors Source: https://docs.polynode.dev/perps/onchain/depositors GET /v3/perps/depositors Biggest depositors ranked by total pUSD deposited, keyed by the real beneficiary account (not the router). The biggest depositors, ranked by total pUSD deposited — keyed by the real **beneficiary** account, not the router most deposits flow through. `min_usd` floors the total, `limit` caps rows. From on-chain deposit events; Polymarket exposes none of this. # Deposits Feed Source: https://docs.polynode.dev/perps/onchain/deposits GET /v3/perps/deposits Recent deposits, filterable by size and time. Each row carries the depositor (often a router) and the beneficiary (real account). The live deposit feed, filterable by size (`min_usd`) and time (`after` / `before`). Each row carries the `depositor` (usually a router contract) and the `account` (the real beneficiary being funded). # Wallet Flows Source: https://docs.polynode.dev/perps/onchain/flows GET /v3/perps/wallets/{address}/flows One wallet's collateral flow: total deposited, withdrawn, net, and stable pages of deposit or withdrawal events. Resolved to the signer. Totals and counts remain fixed across pages in one traversal. One wallet's collateral history: total deposited, total withdrawn, net, and pages of deposit and withdrawal events. Any supported address form resolves to the signer automatically. Responses include `has_more` and an opaque `next_cursor`. Send that value as `cursor` for the same wallet to continue through the fixed traversal: ```text theme={null} GET /v3/perps/wallets/0xabc/flows?limit=100 GET /v3/perps/wallets/0xabc/flows?limit=100&cursor= ``` The deposit and withdrawal totals and counts stay identical on every page in one traversal. Cursors expire after 24 hours. A malformed cursor returns HTTP `400` with `{"error":"invalid cursor"}`. An expired cursor returns `{"error":"cursor has expired"}`. Reusing a cursor for another wallet returns HTTP `400` with a clean mismatch message. Start again without the cursor in each case. # TVL & Collateral Source: https://docs.polynode.dev/perps/onchain/tvl GET /v3/perps/tvl Protocol collateral: current net (deposited - withdrawn) plus a daily net-flow series. Protocol collateral: current net (deposited minus withdrawn), which approximates pUSD held by the exchange, plus a daily net-flow series. # Withdrawals Feed Source: https://docs.polynode.dev/perps/onchain/withdrawals GET /v3/perps/withdrawals Recent withdrawals, filterable by size and time. The live withdrawal feed, filterable by size and time. # Top Withdrawers Source: https://docs.polynode.dev/perps/onchain/withdrawers GET /v3/perps/withdrawers Biggest withdrawers ranked by total pUSD withdrawn. The biggest withdrawers, ranked by total pUSD withdrawn. Pairs with [depositors](/perps/onchain/depositors) and [flows](/perps/onchain/flows) to follow the money. # Perps Overview Source: https://docs.polynode.dev/perps/overview Polymarket perpetual futures data through the polynode API: live market data, orderbooks, trades, funding, klines, wallet portfolios, and WebSocket streaming. Polymarket launched perpetual futures as a separate product next to its prediction markets: BTC, ETH, SOL, gold, silver, oil, S\&P 500, Nasdaq and more, with up to 20x leverage and hourly funding. It is a whole new side of Polymarket, with its own instruments, its own account model, and its own market data. The polynode Perps API covers all of it with the integration you already have: one API key, one base URL, one WebSocket subscription model — plus historical trade, funding, open-interest and volume series, and automatic mapping between prediction-market wallets and perps accounts. ## Base URL ``` https://api.polynode.dev/v3/perps ``` Authentication works exactly like every other `/v3` endpoint — pass your key as a query parameter or header: ```bash theme={null} # Query string curl "https://api.polynode.dev/v3/perps/tickers?key=pn_live_..." # Header curl -H "x-api-key: pn_live_..." https://api.polynode.dev/v3/perps/tickers ``` Get a key from the [dashboard](https://polynode.dev/dashboard). ## What you can build * **Perps trading dashboards** — live tickers, orderbooks, best bid/offer, recent trades, and candles for every listed instrument, over REST or a single WebSocket connection * **Portfolio trackers** — look up any wallet's perps positions and equity. Pass either the Polymarket profile address or the underlying account address; resolution is automatic ([how it works](/perps/wallet-mapping)) * **Funding and analytics tools** — hourly funding-rate history, 24h statistics, OHLCV candles, plus polynode-exclusive open-interest and volume time series * **Cross-product platforms** — perps data lives under the same `/v3` surface as prediction-market trades, positions, and P\&L, so one integration covers both sides of Polymarket ## Instruments Instruments span four categories — `crypto`, `index`, `commodity`, and `equity` (11 live as of mid-July 2026, and Polymarket has dozens more defined for future launch). The API discovers new instruments automatically as they list; nothing is hardcoded, so [`/instruments`](/perps/market-data/instruments) is always the current list. Everywhere an endpoint takes an instrument you can pass the numeric id (`6`), the full symbol (`BTC-USD`), or the bare asset (`btc`). ## Data conventions * **Prices and quantities are strings.** The exchange uses high-precision decimals; we pass them through untouched so you never lose precision to floating point. Exchange-reported values (prices, sizes, equity, unrealized PnL) keep their full native precision; values we derive (aggregates, notionals, basis, CVD) are normalized to a clean decimal form. * **Timestamps are Unix milliseconds** in responses, always in a field named `timestamp` (snapshot-based rows additionally carry `as_of` — when we last observed that account). Time-range filters (`after`, `before`) accept seconds or milliseconds — values are detected automatically. * **Lists come wrapped** as `{"data": [...]}`, with a `more` flag on paginated endpoints. * **`instrument_id` and `symbol` appear together** in every response, so you never need a separate lookup call. * **Unknown query parameters are rejected with a `400`** naming what the endpoint accepts, so a typo'd filter can never silently return unfiltered data. ## Live vs. historical Live market data (tickers, books, bbo, trades, statistics) reflects the current state of the market at request time. Historical series — trade history, funding, klines, open interest, volume — accrue from July 9, 2026 onward and keep growing. ## Endpoint map | Area | Endpoints | | - | - | | Market data | [instruments](/perps/market-data/instruments), [tickers](/perps/market-data/tickers), [bbo](/perps/market-data/bbo), [book](/perps/market-data/book), [trades](/perps/market-data/trades), [statistics](/perps/market-data/statistics), [klines](/perps/market-data/klines), [funding](/perps/market-data/funding), [screener](/perps/market-data/screener) | | polynode-exclusive series | [open interest](/perps/market-data/open-interest), [volume](/perps/market-data/volume), [daily activity](/perps/market-data/daily-activity), [basis](/perps/market-data/basis), [trade flow / CVD](/perps/market-data/flow), [cumulative funding](/perps/market-data/funding-pnl) | | Analytics (not on Polymarket) | [whale leaderboard](/perps/analytics/leaderboard), [smart money](/perps/analytics/traders), [positioning](/perps/analytics/positioning), [large positions](/perps/analytics/large-positions), [position history](/perps/analytics/position-history), [position events](/perps/analytics/events), [liquidations](/perps/analytics/liquidations), [coverage](/perps/analytics/coverage) | | On-chain collateral | [TVL](/perps/onchain/tvl), [depositors](/perps/onchain/depositors), [withdrawers](/perps/onchain/withdrawers), [deposits](/perps/onchain/deposits), [withdrawals](/perps/onchain/withdrawals), [wallet flows](/perps/onchain/flows) | | Exchange meta | [fees, limit tiers, exchange info, assets, index prices](/perps/market-data/meta) | | Wallets | [wallet overview](/perps/wallets/overview), [portfolio](/perps/wallets/portfolio), [registered](/perps/wallets/registered), [batch registered](/perps/wallets/batch-registered), [batch portfolios](/perps/wallets/batch-portfolios) | | Streaming | [WebSocket](/perps/websocket/overview) | ## Trading This release covers market and account **data**. Order placement and account management for perps are a separate, upcoming track — if you need them early, [talk to us](mailto:team@polynode.dev). # Quickstart Source: https://docs.polynode.dev/perps/quickstart From zero to live perps data in three requests. All you need is a polynode API key from the [dashboard](https://polynode.dev/dashboard). ## 1. List the instruments ```bash theme={null} curl "https://api.polynode.dev/v3/perps/instruments?key=$POLYNODE_API_KEY" ``` ```json theme={null} { "data": [ { "instrument_id": 6, "symbol": "BTC-USD", "category": "crypto", "max_leverage": 20, "funding_interval": "1h", "risk_tiers": [{ "lower_bound": "0", "max_leverage": 20 }], "first_seen": 1783569304465 } ] } ``` ## 2. Get live prices ```bash theme={null} curl "https://api.polynode.dev/v3/perps/tickers/btc?key=$POLYNODE_API_KEY" ``` ```json theme={null} { "instrument_id": 6, "symbol": "BTC-USD", "index_price": "62022", "mark_price": "62010", "last_price": "61989", "mid_price": "62010", "open_interest": "67.44542", "funding_rate": "0.0000125", "next_funding": 1783573200000, "timestamp": 1783571023159 } ``` ## 3. Check a wallet's perps account Pass any Polymarket address — profile address or account address, we resolve it: ```bash theme={null} curl "https://api.polynode.dev/v3/perps/wallets/0xd4983f729636aacb733171edc1fa8618a21ab84d?key=$POLYNODE_API_KEY" ``` ```json theme={null} { "input": "0xd4983f729636aacb733171edc1fa8618a21ab84d", "pm_address": null, "wallet_type": "eoa", "signer": "0xd4983f729636aacb733171edc1fa8618a21ab84d", "registered": true, "equity": "125.42", "positions": [], "timestamp": 1783569406173 } ``` ## 4. Stream it One WebSocket connection carries every perps channel: ```javascript theme={null} const ws = new WebSocket("wss://perps.polynode.dev/ws?key=pn_live_..."); ws.onopen = () => { ws.send(JSON.stringify({ action: "subscribe", channels: ["perps_tickers", "perps_trades:BTC-USD", "perps_book:ETH-USD"], })); }; ws.onmessage = (msg) => { const event = JSON.parse(msg.data); console.log(event.channel, event.data); }; ``` See [WebSocket](/perps/websocket/overview) for the full channel list and protocol. # Rate Limits Source: https://docs.polynode.dev/perps/rate-limits Request and WebSocket limits for the perps endpoints, by plan. Perps REST endpoints share your key's standard `/v3` rate limit — there is no separate perps quota to think about. | Plan | Requests / minute | | - | - | | Free | 120 | | Starter | 1,000 | | Growth | 2,000 | | Enterprise | 4,000 (custom by agreement) | Every response carries `x-ratelimit-limit`, `x-ratelimit-remaining`, and `x-ratelimit-reset` headers. ## WebSocket limits Concurrent connections to `wss://perps.polynode.dev/ws` per key: | Plan | Connections | Channel subscriptions per key | | - | - | - | | Free | 1 | 1 | | Starter | 10 | 500 | | Growth | 50 | 3,000 | | Enterprise | unlimited | 50,000 | One connection can carry all your channels — the subscription cap is what matters, and a single subscription like `perps_tickers` covers every instrument at once. These are the plan defaults; individual keys can carry a custom allowance. The hello frame you receive on connect reports **your key's exact `max_subscriptions`** — treat that as authoritative. ## Practical notes * If you find yourself polling market data faster than about once a second, the [WebSocket](/perps/websocket/overview) will serve you better — it pushes every update as it happens. * Wallet portfolio data refreshes every few seconds; querying the same wallet faster than that returns the same snapshot. * Historical endpoints (`/oi`, `/volume`, time-windowed `/trades`) paginate with `limit` + `more`; prefer larger pages over many small ones. # Wallet Mapping Source: https://docs.polynode.dev/perps/wallet-mapping Why Polymarket perps accounts use a different address than the profile you see, and how polynode resolves it for you automatically. If you take a wallet address from a Polymarket profile, a leaderboard, or from polynode's prediction-market endpoints and ask the perps exchange about it, you will usually get nothing back. This page explains why, and what polynode does about it. ## Two addresses per user Most Polymarket users trade prediction markets through a **proxy wallet** — a small smart contract deployed for them on Polygon. That contract address is their public identity: it is what appears on their profile page, on leaderboards, and in every prediction-market dataset (including polynode's `/v3` wallet endpoints). The perps exchange identifies users differently: by the **signer** — the private-key account that controls the proxy. The signer is not shown on the Polymarket frontend, and there is no public endpoint that translates one into the other. So a user's prediction-market history lives under one address, and their perps account lives under another. Without the mapping, you cannot connect them. ## What polynode does Every perps wallet endpoint accepts **either address form** and resolves it server-side: ```bash theme={null} # Polymarket profile (proxy) address — resolved to the perps account automatically curl "https://api.polynode.dev/v3/perps/wallets/0x09b428f7c2b469786286214aa5c90dd9015f7320?key=$KEY" ``` The response always tells you what was resolved: ```json theme={null} { "input": "0x09b428f7c2b469786286214aa5c90dd9015f7320", "wallet_type": "deposit", "signer": "0x509e390373f5bde0bb02c1019ee39cf0ef23a1a4", "registered": false } ``` The relationship between a proxy and its signer never changes, so once an address has been seen, repeat lookups are instant. ## Wallet types Polymarket has used a few different wallet types over the years, depending on how an account signed up. `wallet_type` tells you which one you're looking at, using Polymarket's own names: | `wallet_type` | Who has one | Resolution | | - | - | - | | `eoa` | Users trading with a plain wallet, no Polymarket contract at all. | The address is its own perps account. | | `deposit` | **Every new Polymarket account** — the deposit wallet is the current standard. | Resolved automatically. | | `safe` | Older accounts that signed up by connecting a browser wallet (MetaMask etc.) — these got a Gnosis Safe. | Resolved automatically. | | `proxy` | Older accounts that signed up with an email login — these got a Polymarket Proxy. | Resolved automatically — see below. | ### "Deposit wallet" vs "beacon wallet" If you've seen both terms: they're the same thing. The deposit wallet is Polymarket's current wallet type, and the newer ones are built so Polymarket can upgrade all of them at once — that upgradeable variant is what gets called a "beacon wallet". There's also an earlier, standalone variant from before that change. Both behave identically, both resolve automatically, and this API reports both simply as `deposit` — you never need to tell them apart. ## Proxy wallets Email-login accounts use a Polymarket Proxy wallet. These resolve automatically too — we maintain our own proxy-to-owner index covering these accounts from the beginning of Polymarket to the current block: ```json theme={null} { "input": "0xf0318c32136c2db7fec88b84869aee6a1106c80c", "wallet_type": "proxy", "signer": "0x14dd4e61e9559e47277ffd19528ce8403ad9e861", "registered": false } ``` In the rare case a proxy isn't in the index yet (the index tails the chain continuously, so this window is small), the API returns a `422` instead of guessing: ```json theme={null} { "error": "polymarket proxy wallet", "detail": "this is a Polymarket Proxy wallet (email-login accounts); its owner isn't in the owner index yet — pass the account's signer address directly", "address": "0x..." } ``` If you have the account's signer address from another source, pass it directly — everything works from there. A `422` address upgrades to full resolution automatically once the index covers it — just retry later. ## Registration Having a signer does not mean the user trades perps. Most Polymarket users have never activated a perps account. Check cheaply with: ```bash theme={null} curl "https://api.polynode.dev/v3/perps/wallets/0x.../registered?key=$KEY" ``` Once an account shows `registered: true` it stays that way; accounts that were `false` are picked up within minutes of activating, so newly onboarded perps users appear quickly. # Portfolios (batch) Source: https://docs.polynode.dev/perps/wallets/batch-portfolios GET /v3/perps/wallets/portfolios Fetch the enriched live portfolio for many wallets in one call (max 20). Each address is resolved and reported inline; a failure on one address does not fail the batch. Fetch the enriched live portfolio for a list of wallets in one request (up to 20) — positions, equity, explicit side, live mark and derived notional, exactly as the single-wallet [portfolio](/perps/wallets/portfolio) endpoint returns them, one entry per address. Pass a comma-separated `addresses` list. Each address is resolved automatically; a malformed or unresolvable address returns an `error` field inline rather than failing the whole batch. Because every entry is a live per-wallet fetch, this endpoint is capped tighter than the registration check. ```bash theme={null} curl "https://api.polynode.dev/v3/perps/wallets/portfolios?addresses=0xABC...,0xDEF...&key=$POLYNODE_API_KEY" ``` # Registered (batch) Source: https://docs.polynode.dev/perps/wallets/batch-registered GET /v3/perps/wallets/registered Check perps registration for many wallets in one call (max 50). Each address is resolved and reported inline; a failure on one address does not fail the batch. Check perps registration for a whole list of wallets in one request — the cheapest way to narrow a set of addresses down to actual perps users before pulling portfolios. Pass a comma-separated `addresses` list (up to 50). Each address is resolved automatically (proxy or signer) and returned inline with its `wallet_type`, `signer`, and `registered` flag. If one address is malformed or unresolvable, it comes back with an `error` field instead — the rest of the batch still succeeds. ```bash theme={null} curl "https://api.polynode.dev/v3/perps/wallets/registered?addresses=0xABC...,0xDEF...&key=$POLYNODE_API_KEY" ``` For a single wallet, use the per-address [registered check](/perps/wallets/registered). # Wallet Overview Source: https://docs.polynode.dev/perps/wallets/overview GET /v3/perps/wallets/{address} One call: resolve any Polymarket address, report the wallet type + signer, perps registration, and (if registered) the live enriched portfolio. Accepts a Polymarket profile (proxy) address **or** the underlying account address — [resolution is automatic](/perps/wallet-mapping). The response combines the mapping, registration status, and (for registered accounts) the live portfolio: | Field | Meaning | | - | - | | `input` | The address you passed, normalized | | `pm_address` | The Polymarket proxy address (null for plain-EOA users) | | `signer` | The perps account address | | `wallet_type` | `eoa`, `deposit`, `safe`, or `proxy` — see [wallet mapping](/perps/wallet-mapping) | | `registered` | Whether this account has activated perps | | `positions` | `[]` for accounts with nothing open | Unregistered wallets return `registered: false` with `equity: null`, `positions: []`, and `timestamp: null` — a 200, not an error, so bulk scans stay simple. # Portfolio Source: https://docs.polynode.dev/perps/wallets/portfolio GET /v3/perps/wallets/{address}/portfolio Live perps positions and equity for a wallet, enriched per position with symbol, side, mark price and notional. ## Fields | Field | Meaning | | - | - | | `symbol` | Instrument symbol, so no lookup table is needed | | `side` | `long` / `short`, made explicit (raw `size` stays signed: negative = short) | | `mark_price` | Live mark at response time | | `notional` | Absolute position value at mark (derived, 2dp) | `equity`, `size`, `entry_price`, and `unrealized_pnl` keep their exact string precision. ## Filters Narrow the position list server-side (Polymarket returns the full list only): `side`, `instrument`, `min_notional`, `min_roe`, and `sort` (`notional` or `pnl`). Unknown values return a `400`. To pull many wallets at once, use the [batch portfolios](/perps/wallets/batch-portfolios) endpoint. Portfolio data refreshes every few seconds per wallet. Works with either address form — proxy or signer ([details](/perps/wallet-mapping)). # Registered Source: https://docs.polynode.dev/perps/wallets/registered GET /v3/perps/wallets/{address}/registered Whether a wallet has activated a perps account. Cheapest way to filter a wallet list before requesting portfolios. The cheapest way to filter a wallet list down to actual perps users before requesting portfolios. Accounts that activate perps show up as `registered: true` within minutes. Accepts either address form — proxy or signer ([details](/perps/wallet-mapping)). # Channels Source: https://docs.polynode.dev/perps/websocket/channels Every perps WebSocket channel and its payload. | Channel | Scope | Payload | | - | - | - | | `perps_tickers` | all instruments | Ticker updates: index/mark/last/mid price, open interest, funding rate, next funding | | `perps_statistics` | all instruments | Rolling 24h stats per instrument, sent when they change | | `perps_bbo:` | one instrument | Best bid/offer changes | | `perps_book:` | one instrument | Complete top-20 snapshot whenever published — replace your local book, never merge | | `perps_trades:` | one instrument | Executions as they print | | `perps_klines::` | one instrument | The current candle, sent whenever it changes; intervals `1m` and `1h` | ## Example events `perps_tickers`: ```json theme={null} { "channel": "perps_tickers", "data": { "instrument_id": 6, "symbol": "BTC-USD", "index_price": "62022", "mark_price": "62010", "last_price": "61989", "mid_price": "62010", "open_interest": "67.44542", "funding_rate": "0.0000125", "next_funding": 1783573200000, "timestamp": 1783571023159 } } ``` `perps_trades:`: ```json theme={null} { "channel": "perps_trades", "data": { "instrument_id": 6, "symbol": "BTC-USD", "data": [ { "trade_id": 7504966405671651, "instrument_id": 6, "symbol": "BTC-USD", "side": "short", "price": "62009", "quantity": "0.00842", "timestamp": 1783571031288 } ] } } ``` `perps_book:` — **every delivered message is a complete snapshot** of the top 20 levels per side. A successful subscription acknowledgement does not guarantee that the first snapshot has arrived. Replace your local book with each message; merging messages as if they were deltas will accumulate stale levels and cross the book. Fetch the [REST book](/perps/market-data/book) if startup requires immediate state: ```json theme={null} { "channel": "perps_book", "data": { "instrument_id": 6, "symbol": "BTC-USD", "bids": [["62009", "0.03999"]], "asks": [["62010", "0.05098"]], "timestamp": 1783571023159 } } ``` `perps_klines::`: ```json theme={null} { "channel": "perps_klines", "data": { "instrument_id": 6, "symbol": "BTC-USD", "interval": "1m", "candle": [1783571040000, "62010", "62015", "62001", "62009", "1.2043", 18], "timestamp": 1783571100000 } } ``` Candles are `[open_time, open, high, low, close, volume, trade_count]` — the same layout as [REST klines](/perps/market-data/klines). Each event carries the **current** candle for the interval, sent only when its contents change (a trade prints, or a new period opens). A candle is final once you see an event with a later `open_time` for the same instrument and interval. Quiet markets send nothing — silence means no change, not a dropped connection (the 30-second server pings cover liveness). # Perps WebSocket Source: https://docs.polynode.dev/perps/websocket/overview One connection streams every perps channel: tickers, books, best bid/offer, trades, statistics, and candles. ``` wss://perps.polynode.dev/ws?key=pn_live_... ``` Authenticate with your normal polynode API key as the `key` query parameter. On connect you receive a hello frame listing the available channels and your subscription allowance, then you subscribe: ```javascript theme={null} const ws = new WebSocket("wss://perps.polynode.dev/ws?key=pn_live_..."); ws.onopen = () => { ws.send(JSON.stringify({ action: "subscribe", channels: ["perps_tickers", "perps_book:BTC-USD", "perps_trades:BTC-USD"], })); }; ws.onmessage = (msg) => { const event = JSON.parse(msg.data); if (event.action === "subscribed") { console.log("subscribed:", event.channels, "rejected:", event.rejected); return; } console.log(event.channel, event.data); }; ``` ## Protocol | Message | Direction | Shape | | - | - | - | | Hello | server → you | `{"status": "connected", "max_subscriptions": ..., "channels": [...]}` | | Subscribe | you → server | `{"action": "subscribe", "channels": [...]}` | | Unsubscribe | you → server | `{"action": "unsubscribe", "channels": [...]}` | | Ack | server → you | `{"action": "subscribed", "channels": [...], "rejected": [...], "active_subscriptions": n}` | | Event | server → you | `{"channel": "perps_tickers", "data": {...}}` | | Ping | you → server | `{"action": "ping"}` → `{"action": "pong"}` | Invalid channels come back in `rejected` with a reason — the rest of the batch still subscribes. Instruments can be referenced by id (`6`), symbol (`BTC-USD`), or bare asset (`btc`). ## Authentication failures A missing or invalid key does not silently drop the connection: the socket opens, you receive one error frame naming the problem, and the connection closes with an application close code — `4401` for a bad or missing key, `4429` when your plan's connection limit is reached. If you see close code `4401`, check the `key` query parameter first. Event payloads use the same field names as the REST endpoints — a `perps_tickers` event carries the exact shape of [`/v3/perps/tickers/:instrument`](/perps/market-data/tickers), so REST and WS code paths share models. ## Connection limits Per-key concurrent connections and channel subscriptions follow your plan — see [rate limits](/perps/rate-limits). A single connection is enough for most platforms: `perps_tickers` alone covers every instrument. ## Keep-alive and recovery The server pings every 30 seconds; standard pong replies (automatic in browsers and most WS libraries) keep the connection alive. If your consumer falls behind, you receive `{"warning": "lagged", "dropped_events": n}` instead of silently missing data — resubscribe or refetch REST state for the affected instruments. Every delivered `perps_book` message is a complete snapshot — replace, don't merge. A subscription acknowledgement confirms channel acceptance, not that a snapshot has already arrived; fetch the [REST book](/perps/market-data/book) when startup needs immediate state ([channel details](/perps/websocket/channels)). # Quickstart Source: https://docs.polynode.dev/quickstart Generate an API key and make your first request in 30 seconds. > [!NOTE] > > **Polymarket Protocol V2.** Polymarket is moving newly created markets to Polymarket Protocol V2 from around November 2, 2026 (tentative, per Polymarket; test markets since October 5, 2026). REST and WebSocket integrations need no changes. If you trade with our SDK, upgrade to `polynode-sdk` 0.15.0 (TypeScript), `polynode` 0.18.0 (Rust) or `polynode` 0.15.0 (Python). This is separate from Polymarket's April 2026 exchange upgrade ([V2 Migration](/guides/v2-migration)). See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ## 1. Generate an API key ```bash cURL theme={null} curl -s -X POST https://api.polynode.dev/v1/keys \ -H "Content-Type: application/json" \ -d '{"name": "my-bot"}' ``` ```python Python theme={null} import requests resp = requests.post("https://api.polynode.dev/v1/keys", json={"name": "my-bot"}) key = resp.json()["api_key"] print(key) # pn_live_a1b2c3d4e5f6... ``` ```typescript TypeScript theme={null} const resp = await fetch("https://api.polynode.dev/v1/keys", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "my-bot" }), }); const { api_key } = await resp.json(); ``` ```json Response theme={null} { "api_key": "pn_live_a1b2c3d4e5f6...", "name": "my-bot", "rate_limit_per_minute": 120, "message": "Store this key securely — it cannot be retrieved again." } ``` > [!WARNING] > > Save the `api_key` immediately. It cannot be retrieved after creation. ## 2. Make your first request Fetch the top 5 markets by 24h volume: ```bash cURL theme={null} curl -s "https://api.polynode.dev/v1/markets?count=5" \ -H "x-api-key: pn_live_YOUR_KEY" | jq ``` ```python Python theme={null} import requests resp = requests.get( "https://api.polynode.dev/v1/markets", params={"count": 5}, headers={"x-api-key": "pn_live_YOUR_KEY"}, ) print(resp.json()) ``` ```typescript TypeScript theme={null} const resp = await fetch("https://api.polynode.dev/v1/markets?count=5", { headers: { "x-api-key": "pn_live_YOUR_KEY" }, }); const data = await resp.json(); ``` ```json Response theme={null} { "count": 5, "total": 69482, "markets": [ { "token_id": "247024838963513327646981976118812247380", "question": "Will Bitcoin reach $100k?", "last_price": 0.72, "volume_24h": 48293.50, "trade_count_24h": 677, "last_trade_at": 1772512467000, "slug": "bitcoin-100k", "outcomes": ["Yes", "No"] } ] } ``` ## 3. Stream live settlements Connect via WebSocket to receive real-time settlements: ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { ws.send(JSON.stringify({ action: "subscribe", type: "settlements", })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement") { console.log(`${msg.data.taker_side} $${msg.data.taker_size} @ ${msg.data.taker_price}`); } }; ``` You'll receive a snapshot of recent events, then live updates as new settlements are detected. ## Next steps > [card] [Authentication](/authentication) > > API key management and auth methods > [card] [WebSocket](/guides/websocket) > > Real-time streaming with filtered subscriptions > [card] [API Reference](/api-reference) > > Full endpoint reference with playground > [card] [Rate Limits](/guides/rate-limits) > > Usage limits and best practices # Gas Oracle Source: https://docs.polynode.dev/rpc/gas-oracle Real-time gas price intelligence for optimal transaction positioning ## Overview PolyNode's Gas Oracle scans every block on Polygon to determine the exact gas price needed to achieve top-of-block positioning. Unlike standard `eth_gasPrice` which returns a network average, our oracle tells you what the **competitive floor** is — what the top-of-block bots are actually paying. ## Endpoint ``` GET https://rpc.polynode.dev/v1/gas ``` ## Response ```json theme={null} { "recommendation": { "recommended_gas_wei": 1986123386877, "recommended_gas_gwei": 1986.1, "avg_top_gas_gwei": 1547.4, "max_top_gas_gwei": 1805.6, "blocks_scanned": 20, "safety_multiplier": 1.1, "base_gas_gwei": 111.4, "effective_multiplier": 17.8 }, "recent_blocks": [ { "block_number": 84210810, "top_gas_gwei": 1804.6, "second_gas_gwei": 1804.6, "median_gas_gwei": 168.5, "tx_count": 252 } ] } ``` ## Fields | Field | Description | | - | - | | `recommended_gas_wei` | Gas price in wei to beat current top-of-block competition | | `recommended_gas_gwei` | Same value in gwei for readability | | `avg_top_gas_gwei` | Average highest gas price across scanned blocks | | `max_top_gas_gwei` | Maximum top-of-block gas price observed | | `blocks_scanned` | Number of recent blocks analyzed | | `safety_multiplier` | Multiplier applied above max observed (default 1.1x) | | `base_gas_gwei` | Current network base gas price | | `effective_multiplier` | How many times above base gas the recommendation is | ## Per-Block Data The `recent_blocks` array provides gas data for each scanned block: | Field | Description | | - | - | | `top_gas_gwei` | Highest gas price in the block (TX #1) | | `second_gas_gwei` | Second highest gas price | | `median_gas_gwei` | Median gas price across all transactions | | `tx_count` | Total transactions in the block | ## Usage Use the gas oracle to set your transaction's gas price for optimal block positioning: ```python theme={null} import requests # Get current recommendation resp = requests.get('https://rpc.polynode.dev/v1/gas') data = resp.json() # Use recommended gas price for TX #1 gas_price = data['recommendation']['recommended_gas_wei'] # Build your transaction with this gas price tx = { 'gasPrice': gas_price, # ... rest of your transaction } ``` ## Refresh Rate The gas oracle updates every **30 seconds**, scanning the most recent 20 blocks. Data reflects real-time market conditions on Polygon. # Integration Guide Source: https://docs.polynode.dev/rpc/integration Connect to polynode RPC from any Ethereum library or wallet ## Endpoint ``` https://rpc.polynode.dev ``` All requests require a valid API key via `x-api-key` header or `Authorization: Bearer` header. ## Integration Examples > [tab] viem > > ```typescript theme={null} > import { createPublicClient, createWalletClient, http } from 'viem' > import { polygon } from 'viem/chains' > import { privateKeyToAccount } from 'viem/accounts' > > const transport = http('https://rpc.polynode.dev', { > fetchOptions: { > headers: { 'x-api-key': 'YOUR_API_KEY' } > } > }) > > // Read contract state > const publicClient = createPublicClient({ > chain: polygon, > transport > }) > > const blockNumber = await publicClient.getBlockNumber() > const balance = await publicClient.getBalance({ > address: '0xYOUR_ADDRESS' > }) > > // Send transactions with priority routing > const account = privateKeyToAccount('0xYOUR_PRIVATE_KEY') > const walletClient = createWalletClient({ > account, > chain: polygon, > transport > }) > > const hash = await walletClient.sendTransaction({ > to: '0xRECIPIENT', > value: parseEther('1.0') > }) > ``` > [tab] ethers.js > > ```javascript theme={null} > import { ethers } from 'ethers' > > const provider = new ethers.JsonRpcProvider( > 'https://rpc.polynode.dev', > 137, > { staticNetwork: true } > ) > > // Add auth to every request > const originalSend = provider.send.bind(provider) > provider.send = async (method, params) => { > const resp = await fetch('https://rpc.polynode.dev', { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > 'x-api-key': 'YOUR_API_KEY' > }, > body: JSON.stringify({ jsonrpc: '2.0', method, params, id: 1 }) > }) > const { result, error } = await resp.json() > if (error) throw new Error(error.message) > return result > } > > const blockNumber = await provider.getBlockNumber() > const balance = await provider.getBalance('0xYOUR_ADDRESS') > > // Send a transaction > const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider) > const tx = await wallet.sendTransaction({ > to: '0xRECIPIENT', > value: ethers.parseEther('1.0') > }) > ``` > [tab] web3.py > > ```python theme={null} > from web3 import Web3 > > w3 = Web3(Web3.HTTPProvider( > 'https://rpc.polynode.dev', > request_kwargs={ > 'headers': {'x-api-key': 'YOUR_API_KEY'} > } > )) > > # Read state > block = w3.eth.block_number > balance = w3.eth.get_balance('0xYOUR_ADDRESS') > > # Check token balance (USDC) > usdc = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' > data = '0x70a08231' + '0xYOUR_ADDRESS'[2:].lower().zfill(64) > result = w3.eth.call({'to': usdc, 'data': data}) > usdc_balance = int(result.hex(), 16) / 1e6 > > # Send a transaction > account = w3.eth.account.from_key('YOUR_PRIVATE_KEY') > tx = { > 'nonce': w3.eth.get_transaction_count(account.address), > 'to': '0xRECIPIENT', > 'value': w3.to_wei(1, 'ether'), > 'gas': 21000, > 'gasPrice': w3.eth.gas_price, > 'chainId': 137, > } > signed = account.sign_transaction(tx) > tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction) > ``` > [tab] curl > > ```bash theme={null} > # Check block number > curl -X POST https://rpc.polynode.dev \ > -H "Content-Type: application/json" \ > -H "x-api-key: YOUR_API_KEY" \ > -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' > > # Check MATIC balance > curl -X POST https://rpc.polynode.dev \ > -H "Content-Type: application/json" \ > -H "x-api-key: YOUR_API_KEY" \ > -d '{ > "jsonrpc":"2.0", > "method":"eth_getBalance", > "params":["0xYOUR_ADDRESS","latest"], > "id":1 > }' > > # Send a signed transaction > curl -X POST https://rpc.polynode.dev \ > -H "Content-Type: application/json" \ > -H "x-api-key: YOUR_API_KEY" \ > -d '{ > "jsonrpc":"2.0", > "method":"eth_sendRawTransaction", > "params":["0xSIGNED_TX_HEX"], > "id":1 > }' > ``` ## Hardhat / Foundry > [tab] Hardhat > > ```javascript theme={null} > // hardhat.config.js > module.exports = { > networks: { > polygon: { > url: 'https://rpc.polynode.dev', > accounts: [process.env.PRIVATE_KEY], > chainId: 137, > httpHeaders: { > 'x-api-key': process.env.POLYNODE_API_KEY > } > } > } > } > ``` > [tab] Foundry > > ```bash theme={null} > # Set auth via header > export ETH_RPC_URL=https://rpc.polynode.dev > > # Deploy > forge script script/Deploy.s.sol \ > --rpc-url $ETH_RPC_URL \ > --broadcast \ > --private-key $PRIVATE_KEY > > # Read state > cast call 0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359 \ > "totalSupply()" \ > --rpc-url $ETH_RPC_URL > ``` ## Response Format Standard Ethereum JSON-RPC responses: ```json theme={null} // Success {"jsonrpc": "2.0", "id": 1, "result": "0x..."} // Error {"jsonrpc": "2.0", "id": 1, "error": {"code": -32000, "message": "..."}} ``` # Polygon RPC Source: https://docs.polynode.dev/rpc/overview Authenticated Polygon RPC with priority transaction routing ## Endpoint ``` https://rpc.polynode.dev ``` Standard Ethereum JSON-RPC over HTTPS for Polygon reads and priority transaction submission. Change your HTTP RPC URL and add your API key. WebSocket subscriptions and privileged node methods are intentionally outside this endpoint's current scope. ## Authentication Every request requires a valid polynode API key. Pass it as a header: ``` x-api-key: YOUR_API_KEY ``` Or as a Bearer token: ``` Authorization: Bearer YOUR_API_KEY ``` Requests without a valid key receive a `-32000` error. ## Rate Limit Active Growth and Enterprise accounts are rate-limited to **50 requests per second** per account. Exceeding this returns a `-32005` error. Batch requests count as one HTTP request and may contain up to **1,000 JSON-RPC calls**. Calls within a batch are processed sequentially. ## Transport The production endpoint is HTTP/HTTPS only. It does not currently accept WebSocket upgrades, so `eth_subscribe`, `eth_unsubscribe`, and `newHeads` are not available at `rpc.polynode.dev` yet. ## Supported Methods | Method | Source | Description | | - | - | - | | `eth_sendRawTransaction` | **Priority routing** | P2P delivery to block-producing validator | | `eth_chainId` | Local | Returns `0x89` (137) | | `eth_blockNumber` | Local cache | Latest cached reference/P2P chain tip | | `eth_gasPrice` | Local | Calibrated for optimal block positioning | | `net_version` | Local | Returns `137` | | `net_peerCount` | Local | Connected P2P peer count | | `web3_clientVersion` | Local | Returns `PolyNode/1.0.0` | | `eth_call` | Polygon upstream | Contract read calls | | `eth_getBalance` | Polygon upstream | Account balance queries | | `eth_getTransactionCount` | Polygon upstream | Nonce queries | | `eth_estimateGas` | Polygon upstream | Gas estimation | | `eth_getBlockByNumber` | Polygon upstream | Block data | | `eth_getTransactionReceipt` | Polygon upstream | Transaction receipts | | `eth_getLogs` | Polygon upstream | Log queries | > [!WARNING] > > **Historical availability follows the configured Polygon upstream.** Current production can answer historical block and state queries, but PolyNode does not operate an independent archive behind this endpoint and does not guarantee every historical height. Use `latest` or recent blocks when archival completeness matters. ## Common Queries ### Check a wallet's MATIC balance ```bash theme={null} curl -X POST https://rpc.polynode.dev \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": ["0xYOUR_WALLET_ADDRESS", "latest"], "id": 1 }' ``` The result is the balance in wei (hex). Divide by 10^18 for MATIC. ### Check a wallet's USDC balance Use `eth_call` with the ERC-20 `balanceOf(address)` function: ```bash theme={null} curl -X POST https://rpc.polynode.dev \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", "data": "0x70a08231000000000000000000000000YOUR_WALLET_ADDRESS_WITHOUT_0x" }, "latest"], "id": 1 }' ``` Replace `YOUR_WALLET_ADDRESS_WITHOUT_0x` with the 40-character address (no `0x` prefix), zero-padded to 64 characters. The result is the balance in the token's smallest unit (hex). USDC has 6 decimals. **Common Polygon token contracts:** | Token | Address | | - | - | | USDC | `0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359` | | USDC.e (bridged) | `0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174` | | USDT | `0xc2132D05D31c914a87C6611C10748AEb04B58e8F` | | WMATIC | `0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270` | | WETH | `0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619` | ### Read any contract function The `data` field for `eth_call` is the function selector (first 4 bytes of the keccak256 hash) followed by ABI-encoded arguments. Common selectors: | Function | Selector | Arguments | | - | - | - | | `balanceOf(address)` | `0x70a08231` | address (32 bytes, left-padded) | | `totalSupply()` | `0x18160ddd` | none | | `decimals()` | `0x313ce567` | none | | `symbol()` | `0x95d89b41` | none | | `name()` | `0x06fdde03` | none | | `allowance(address,address)` | `0xdd62ed3e` | owner (32 bytes) + spender (32 bytes) | ### Get the current block number ```bash theme={null} curl -X POST https://rpc.polynode.dev \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### Get a transaction receipt ```bash theme={null} curl -X POST https://rpc.polynode.dev \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xYOUR_TX_HASH"], "id": 1 }' ``` ## Batch Requests Send multiple calls in a single HTTP request: ```bash theme={null} curl -X POST https://rpc.polynode.dev \ -H "Content-Type: application/json" \ -H "x-api-key: YOUR_API_KEY" \ -d '[ {"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}, {"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":2}, {"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":3} ]' ``` Batch requests count as a single HTTP request against the rate limit and are capped at 1,000 calls. ## Error Codes | Code | Meaning | | - | - | | `-32000` | Missing or invalid API key | | `-32005` | Rate limit exceeded (max 50 requests/second) | | `-32600` | Invalid request, including an oversized batch | | `-32601` | Method not available | | `-32602` | Invalid parameters | | `-32603` | Upstream error | # Transaction Tracking Source: https://docs.polynode.dev/rpc/tx-tracking Track your transaction's block position and confirmation status ## Overview Every transaction submitted through PolyNode RPC is tracked from submission to block inclusion. You can query the exact block position and confirmation latency. ## Submit a Transaction **raw\_tx** `string` *required* Hex-encoded signed transaction (with or without `0x` prefix) ```bash theme={null} POST https://rpc.polynode.dev/v1/tx/submit Content-Type: application/json { "raw_tx": "0x02f87083..." } ``` ### Response ```json theme={null} { "tx_hash": "0xabc123...", "submitted_at": 1710524000, "status": "pending" } ``` | Field | Description | | - | - | | `tx_hash` | Transaction hash | | `status` | `pending` — waiting for block inclusion | ## Check Transaction Status ```bash theme={null} GET https://rpc.polynode.dev/v1/tx/{tx_hash} ``` ### Pending ```json theme={null} { "status": "pending", "submitted_at": 1710524000, "elapsed_ms": 1500 } ``` ### Confirmed ```json theme={null} { "status": "confirmed", "submitted_at": 1710524000, "confirmed_at": 1710524002, "block_number": 84210500, "block_hash": "0xdef456...", "tx_index": 0, "total_txs_in_block": 186, "is_first": true, "latency_ms": 2450 } ``` | Field | Description | | - | - | | `block_number` | Block the transaction was included in | | `tx_index` | Position within the block (0 = first transaction) | | `total_txs_in_block` | Total transactions in the block | | `is_first` | Whether this was the first transaction in the block | | `latency_ms` | Time from submission to block confirmation | ### Expired If a transaction isn't included within \~128 seconds (64 blocks), it's marked as expired: ```json theme={null} { "status": "expired", "submitted_at": 1710524000, "reason": "not included within 64 blocks" } ``` ## Aggregate Stats ```bash theme={null} GET https://rpc.polynode.dev/v1/stats ``` ```json theme={null} { "total_submitted": 1000, "total_confirmed": 998, "total_first_position": 895, "first_position_rate": 0.897, "total_expired": 2, "pending": 0, "avg_latency_ms": 2450, "peers": 13, "mapped_validators": 4, "unique_mapped_peers": 2, "latest_block": 90801900, "p2p_latest_block": 90801898, "reference_latest_block": 90801900, "p2p_head_lag_blocks": 2, "p2p_head_age_seconds": 4, "reference_head_age_seconds": 1, "uptime_seconds": 272500 } ``` `latest_block` is the serving tip. The separate P2P and reference fields make sparse P2P full-block observations visible without allowing `eth_blockNumber` or validator targeting to remain stale. `mapped_validators` counts validator labels; `unique_mapped_peers` counts distinct peer connections behind those mappings, because one gossip or sentry peer can relay blocks from several authors. # Local Cache Source: https://docs.polynode.dev/sdks/local-cache Persist selected wallet, trade, position, and settlement data in local SQLite from TypeScript or Rust. The optional local cache is available in TypeScript and Rust. It is useful when an application repeatedly reads the same tracked wallets or markets and wants a durable local SQLite view between restarts. > [!NOTE] > > The cache is a focused helper, not a local mirror of the complete V3 API. It does not replace V3 for every combo, credit, identity, webhook, or perps resource. Python does not currently expose this helper. ## Install ```bash TypeScript theme={null} npm install polynode-sdk@^0.15.0 better-sqlite3 ``` ```toml Rust theme={null} [dependencies] polynode = { version = "0.18.0", features = ["cache"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` ## Watchlist Create a `polynode.watch.json` file: ```json theme={null} { "version": 1, "wallets": [ { "address": "0xabc...", "label": "strategy-a", "backfill": true } ], "settings": { "ttl_days": 30 } } ``` Do not put API keys or private keys in the watchlist. ## Start and query ```typescript TypeScript theme={null} import { PolyNode, PolyNodeCache } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); const cache = new PolyNodeCache(pn, { dbPath: './polynode-cache.db', watchlistPath: './polynode.watch.json', }); await cache.start(); const trades = cache.walletTrades('0xabc...', { limit: 50 }); const positions = cache.walletPositions('0xabc...'); console.log({ trades, positions, stats: cache.stats() }); await cache.stop(); ``` ```rust Rust theme={null} use polynode::{cache::{PolyNodeCache, QueryOptions}, PolyNodeClient}; use std::sync::Arc; #[tokio::main] async fn main() -> polynode::Result<()> { let client = Arc::new(PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?); let mut cache = PolyNodeCache::builder(client) .db_path("./polynode-cache.db") .watchlist_path("./polynode.watch.json") .build()?; cache.start().await?; let trades = cache.wallet_trades( "0xabc...", &QueryOptions { limit: Some(50), ..Default::default() }, )?; let positions = cache.wallet_positions("0xabc...")?; println!("{} {} {:?}", trades.len(), positions.len(), cache.stats()?); cache.stop().await?; Ok(()) } ``` ## Operational guidance * Put the SQLite file on persistent storage and back it up according to your application's needs. * Keep one writer per database file unless your own storage design guarantees otherwise. * Observe backfill progress and rate-limit errors instead of starting many simultaneous backfills. * Stop the cache cleanly so its live subscription and database handles are released. * Use V3 as the source of truth for data outside the documented cache model. For current V3 reads, see [Complete V3 API](/sdks/v3-api). # Orderbook Streaming and PN1 Source: https://docs.polynode.dev/sdks/orderbook Stream prediction-market depth, maintain local books, and optionally fail closed on PN1 sequence or checksum errors. The orderbook WebSocket is separate from the settlement stream. It emits full snapshots, absolute depth updates, price changes, and last-trade metadata for selected outcome token IDs. Use one of three levels: | Level | Best for | | - | - | | Raw orderbook stream | applications that already manage book state | | `LocalOrderbook` | applying messages to an in-memory book yourself | | `OrderbookEngine` | managed connection, local state, filtered views, reconnect recovery, and optional PN1 integrity | For most applications, start with `OrderbookEngine`. ## Managed local book Set `TOKEN_ID` to a Polymarket outcome token ID. You can obtain token IDs from V3 market data or the `clobTokenIds` / `clob_token_ids` field on a [short-form rotation](/sdks/short-form). > [tab] TypeScript > > ```typescript theme={null} > import { > OrderbookEngine, > type BookSnapshot, > type BookUpdate, > } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > const tokenId = process.env.TOKEN_ID; > if (!apiKey || !tokenId) throw new Error('Set POLYNODE_API_KEY and TOKEN_ID'); > > const engine = new OrderbookEngine({ apiKey }); > engine.on('ready', () => { > console.log('best bid', engine.bestBid(tokenId)); > console.log('best ask', engine.bestAsk(tokenId)); > console.log('midpoint', engine.midpoint(tokenId)); > }); > engine.on('update', (update: BookSnapshot | BookUpdate) => { > console.log(update.type, update.asset_id); > }); > > await engine.subscribe([tokenId]); > process.once('SIGINT', () => engine.close()); > ``` > [tab] Python > > ```python theme={null} > import asyncio > import os > from polynode import OrderbookEngine > > async def main() -> None: > token_id = os.environ["TOKEN_ID"] > engine = OrderbookEngine(api_key=os.environ["POLYNODE_API_KEY"]) > engine.on( > "ready", > lambda: print( > "touch", > engine.best_bid(token_id), > engine.best_ask(token_id), > engine.midpoint(token_id), > ), > ) > engine.on("update", lambda update: print(update.type, update.asset_id)) > try: > await engine.subscribe([token_id]) > await asyncio.Event().wait() > finally: > engine.close() > > asyncio.run(main()) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{EngineOptions, OrderbookEngine}; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let api_key = std::env::var("POLYNODE_API_KEY") > .expect("Set POLYNODE_API_KEY"); > let token_id = std::env::var("TOKEN_ID").expect("Set TOKEN_ID"); > let engine = OrderbookEngine::connect(&api_key, EngineOptions::default()).await?; > engine.subscribe(vec![token_id.clone()]).await?; > > loop { > if let Some(book) = engine.book(&token_id).await { > println!("{} bids, {} asks", book.0.len(), book.1.len()); > println!("midpoint {:?}", engine.midpoint(&token_id).await); > break; > } > tokio::task::yield_now().await; > } > > engine.close().await?; > Ok(()) > } > ``` `subscribe()` resolves after the server acknowledges the requested identifiers. The local book becomes readable after its initial snapshot arrives. TypeScript and Python emit `ready` when every acknowledged token has a valid baseline. ## Book update rules Apply raw messages with these rules: | Message | Effect on depth | | - | - | | `book_snapshot` | replace the complete book for that token | | `book_update` | upsert each absolute price level; size `"0"` removes it | | `price_change` | upsert the absolute level on `BUY` bids or `SELL` asks; size `"0"` removes it | | `last_trade_price` | update trade metadata only; never mutate depth | Prices and sizes are decimal strings. Keep them as strings or use a decimal library for exact calculations. Converting them to binary floating point can change level identity and is incompatible with PN1 checksum verification. ## Enable PN1 integrity PN1 lets the SDK detect a missing or out-of-order depth message instead of continuing with a book that merely looks plausible. It validates: * a trusted anchor snapshot for each token * sequence continuity across depth changes * the checksum after every verified mutation > [tab] TypeScript > > ```typescript theme={null} > const engine = new OrderbookEngine({ > apiKey, > integrity: true, > allowStaleReads: false, > }); > > engine.on('integrity_error', (error) => { > console.error(error.token, error.code, error.message); > }); > await engine.subscribe([tokenId]); > ``` > [tab] Python > > ```python theme={null} > engine = OrderbookEngine( > api_key=os.environ["POLYNODE_API_KEY"], > integrity=True, > allow_stale_reads=False, > ) > engine.on( > "integrity_error", > lambda error: print(error.token, error.code, error), > ) > await engine.subscribe([token_id]) > ``` > [tab] Rust > > ```rust theme={null} > let engine = OrderbookEngine::connect( > &api_key, > EngineOptions { > integrity: true, > allow_stale_reads: false, > ..Default::default() > }, > ).await?; > > let mut errors = engine.integrity_errors(); > tokio::spawn(async move { > while let Ok(error) = errors.recv().await { > eprintln!("{} {:?}: {}", error.token, error.code, error.message); > } > }); > engine.subscribe(vec![token_id]).await?; > ``` PN1 mode requires explicit market identifiers. A wildcard/firehose orderbook subscription is not available with integrity enabled. ## Fail-closed lifecycle With `allowStaleReads` / `allow_stale_reads` left at its default `false`, the local book moves through these states: | State | Readable? | Meaning | | - | - | - | | `initializing` | No | waiting for a valid anchor | | `ready` | Yes | current sequence and checksum are valid | | `stale` | No | connection was lost | | `resyncing` | No | a replacement anchor was requested | | `failed` | No | integrity could not be recovered on the current stream | On a sequence or checksum failure, the engine gates only the affected token and requests a fresh anchor. It does not serve the last book as verified state. Set stale reads to `true` only when your application deliberately prefers availability over verified depth. Surface that choice to downstream consumers; a stale book should not be mistaken for current market state. ## Reconnects Orderbook reconnect is automatic by default. The SDK replays the active token set and waits for fresh snapshots. Sequence state from the old connection is never reused as if it belonged to the replacement connection. Application handlers remain attached across reconnects. You do not need to register them again. ## Filtered views Views share the engine's connection and state but receive updates only for their token set. > [tab] TypeScript > > ```typescript theme={null} > const view = engine.view([tokenId]); > view.on('update', (update) => console.log(update.asset_id)); > console.log(view.midpoint(tokenId)); > > view.setTokens([anotherTokenId]); > view.destroy(); > ``` > [tab] Python > > ```python theme={null} > view = engine.view([token_id]) > view.on("update", lambda update: print(update.asset_id)) > print(view.midpoint(token_id)) > > view.set_tokens([another_token_id]) > view.destroy() > ``` > [tab] Rust > > ```rust theme={null} > let mut view = engine.view(vec![token_id.clone()]); > if let Some(update) = view.next().await { > println!("{update:?}"); > } > view.set_tokens(vec![another_token_id]).await; > ``` Use views when several application components need different slices of one shared book connection. ## Raw stream Choose the raw client when you need protocol messages or maintain state elsewhere: * TypeScript: `pn.orderbook.subscribe(tokenIds)` and `pn.orderbook.on(...)` * Python: `await pn.orderbook.subscribe(token_ids)` and `pn.orderbook.on(...)` * Rust: `client.orderbook_stream(ObStreamOptions::default()).await?` In raw mode, your code is responsible for applying snapshots and deltas correctly. `LocalOrderbook` provides the same deterministic update logic without the higher-level engine. ## Cleanup > [tab] TypeScript > > ```typescript theme={null} > engine.close(); > ``` > [tab] Python > > ```python theme={null} > engine.close() > ``` > [tab] Rust > > ```rust theme={null} > engine.close().await?; > ``` See the [orderbook protocol](/orderbook/overview), [message reference](/orderbook/messages), and [PN1 integrity reference](/orderbook/integrity) for wire-level details. # Polynode SDKs Source: https://docs.polynode.dev/sdks/overview Install an official Polynode SDK and use V3 data, settlement streams, Chainlink TWAP markets, PN1 orderbooks, and perps. Polynode has official SDKs for TypeScript, Python, and Rust. Each SDK covers the same core product surfaces: * the complete V3 API, including combos and perps data * the real-time settlement stream * the managed orderbook stream, including optional PN1 integrity checks * the V3 perps WebSocket * short-form crypto markets with the correct Chainlink price window The examples in this section are tested against these published versions: | Language | Package | Current version | Runtime | | - | - | -: | - | | TypeScript / Node.js | [`polynode-sdk`](https://www.npmjs.com/package/polynode-sdk) | `0.15.0` | Node.js 18+ | | Python | [`polynode`](https://pypi.org/project/polynode/) | `0.15.1` | Python 3.10+ | | Rust | [`polynode`](https://crates.io/crates/polynode) | `0.18.0` | Tokio async runtime | > [!NOTE] > > Use these versions or newer. Older releases do not contain the complete V3 registry, the managed perps stream, reconnect-aware settlement delivery, and PN1 orderbook integrity described here. ## Install > [tab] TypeScript > > ```bash theme={null} > npm install polynode-sdk ws > ``` > > Both ESM `import` and CommonJS `require` are supported. > [tab] Python > > ```bash theme={null} > python -m pip install --upgrade "polynode>=0.15.0" > ``` > [tab] Rust > > ```toml theme={null} > [dependencies] > polynode = "0.18.0" > tokio = { version = "1", features = ["macros", "rt-multi-thread"] } > ``` Create an API key at [polynode.dev](https://polynode.dev), then keep it in a server-side environment variable: ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." ``` > [!WARNING] > > Do not embed a Polynode API key or wallet private key in browser code, mobile bundles, source control, screenshots, or logs. ## First request This reads V3 platform statistics and does not change any data. > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > > const pn = new PolyNode({ apiKey }); > const stats = await pn.v3.stats(); > console.log(stats); > ``` > [tab] Python > > ```python theme={null} > import os > from polynode import PolyNode > > with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > stats = pn.v3.execute("GET /v3/stats") > print(stats) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{PolyNodeClient, V3RequestOptions}; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let api_key = std::env::var("POLYNODE_API_KEY") > .expect("Set POLYNODE_API_KEY"); > let client = PolyNodeClient::new(api_key)?; > let stats = client > .v3() > .execute_named("GET /v3/stats", V3RequestOptions::default()) > .await?; > println!("{stats:#}"); > Ok(()) > } > ``` ## Choose a surface > [card] [V3 API](/sdks/v3-api) > > Query wallets, trades, positions, combos, fees, builders, webhooks, and perps through the complete 120-operation registry. > [card] [Settlement stream](/sdks/websocket-streaming) > > Receive pending settlements and confirmation updates with typed events, filters, reconnect replay, and observable overflow. > [card] [Short-form and TWAP](/sdks/short-form) > > Follow 5-minute, 15-minute, 1-hour, and 4-hour crypto markets as their slugs and Chainlink windows rotate. > [card] [Orderbook stream](/sdks/orderbook) > > Consume raw books or maintain verified local state with PN1 sequence and checksum validation. > [card] [Perps stream](/sdks/perps) > > Stream tickers, best bid/offer, complete books, trades, statistics, and 1-minute or 1-hour candles. > [card] [Trading and fees](/sdks/trading) > > Place current V2 orders, configure builder attribution, and understand which fee fields belong on the wire. > [card] [Connect Wallet to order](/sdks/user-owned-web-app) > > Add a secure user-owned flow with browser signing, an encrypted vault, and zero builder attribution. ## Core parity | Capability | TypeScript | Python | Rust | | - | - | - | - | | Complete V3 registry | `pn.v3.operations` | `pn.v3.operations` | `client.v3().operations()` | | Execute any registered V3 route | `pn.v3.execute()` | `pn.v3.execute()` | `execute_named()` | | Settlement reconnect cursor and overlap dedupe | Yes | Yes | Yes | | Unknown additive events remain available | Yes | Yes | Yes | | 5m / 15m / 1h / 4h managed market rotation | Yes | Yes | Yes | | Explicit Chainlink 30s / 60s TWAP filters | Yes | Yes | Yes | | PN1 orderbook integrity | Yes | Yes | Yes | | Managed V3 perps WebSocket | Yes | Yes | Yes | | Current V2 trading default | Yes | Yes | Yes, `trading` feature | Some optional helpers are intentionally language-specific. The SQLite local cache is currently available in TypeScript and Rust; trading dependencies are optional in Python and Rust. Those differences do not affect the core surfaces above. ## Three different WebSockets The SDKs expose separate clients because the streams have different protocols and state: | Stream | Use it for | SDK entry point | | - | - | - | | Events | settlements, confirmations, wallet activity, combos, Chainlink prices | `pn.ws` / `client.stream(...)` | | Orderbook | prediction-market depth and trades | `pn.orderbook`, `OrderbookEngine`, or `client.orderbook_stream(...)` | | Perps | perps tickers, BBO, books, trades, statistics, klines | `pn.perps` / `client.perps_stream()` | Do not send an event-stream subscription to the orderbook or perps socket. Each guide starts from the correct client and includes shutdown code. ## Next steps > [card] [TypeScript](/sdks/ts/overview) > > Node.js setup and complete examples. > [card] [Python](/sdks/python/overview) > > Synchronous REST and asynchronous streams. > [card] [Rust](/sdks/rust/overview) > > Tokio clients, typed events, and feature flags. If you prefer HTTP or raw WebSockets, use the [API overview](/api-reference/overview), [event WebSocket guide](/websocket/overview), [orderbook protocol](/orderbook/overview), and [perps API](/perps/overview). # Perps WebSocket Source: https://docs.polynode.dev/sdks/perps Stream Polymarket perps tickers, BBO, complete books, trades, statistics, and klines with managed resubscription. The V3 perps WebSocket is a separate stream for perps market data. The SDK client handles authentication, waits for control-message acknowledgements, preserves unknown additive messages, reconnects, and resubscribes to the channels you accepted. ## Channels | Channel | Scope | Data | | - | - | - | | `perps_tickers` | all instruments | index, mark, last, and mid prices; open interest and funding | | `perps_statistics` | all instruments | rolling statistics | | `perps_bbo:` | one instrument | best bid and offer | | `perps_book:` | one instrument | complete top-of-book depth snapshot when published | | `perps_trades:` | one instrument | executions | | `perps_klines::1m` | one instrument | current 1-minute candle | | `perps_klines::1h` | one instrument | current 1-hour candle | Use the SDK channel helpers to avoid formatting mistakes. ## Connect and subscribe > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode, perpsChannels } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > const pn = new PolyNode({ apiKey }); > const perps = pn.configurePerps({ queueCapacity: 4096 }); > > const hello = await perps.connect(); > console.log('channel limit', hello.max_subscriptions); > > const ack = await perps.subscribe([ > perpsChannels.tickers, > perpsChannels.bbo('BTC-USD'), > perpsChannels.book('BTC-USD'), > perpsChannels.trades('BTC-USD'), > perpsChannels.klines('BTC-USD', '1m'), > ]); > console.log('accepted', ack.channels, 'rejected', ack.rejected); > > perps.onMessage((message) => { > if (message.type === 'event') { > console.log(message.channel, message.data); > } else if (message.type === 'reconnect') { > console.warn(message.message, message.channels); > } else if (message.type === 'lag_warning') { > console.warn('upstream events dropped', message.dropped_events); > } > }); > > process.once('SIGINT', () => perps.disconnect()); > ``` > [tab] Python > > ```python theme={null} > import asyncio > import os > from polynode import AsyncPolyNode, PerpsEvent, perps_channels > > async def main() -> None: > async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > perps = pn.perps > hello = await perps.connect() > print("channel limit", hello.max_subscriptions) > > ack = await perps.subscribe([ > perps_channels.tickers, > perps_channels.bbo("BTC-USD"), > perps_channels.book("BTC-USD"), > perps_channels.trades("BTC-USD"), > perps_channels.klines("BTC-USD", "1m"), > ]) > print("accepted", ack.channels, "rejected", ack.rejected) > > try: > async for message in perps: > if isinstance(message, PerpsEvent): > print(message.channel, message.data) > elif message.type in ("reconnect", "lag_warning"): > print(message) > finally: > await perps.disconnect() > > asyncio.run(main()) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{ > bbo_channel, book_channel, klines_channel, trades_channel, > PerpsEvent, PerpsMessage, PolyNodeClient, > }; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let client = PolyNodeClient::new( > std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") > )?; > let mut perps = client.perps_stream().await?; > let ack = perps.subscribe(vec![ > "perps_tickers".into(), > bbo_channel("BTC-USD")?, > book_channel("BTC-USD")?, > trades_channel("BTC-USD")?, > klines_channel("BTC-USD", "1m")?, > ]).await?; > println!("accepted {:?}, rejected {:?}", ack.channels, ack.rejected); > > while let Some(message) = perps.next().await { > match message? { > PerpsMessage::Event(PerpsEvent::Ticker(ticker)) => { > println!("{:?} {}", ticker.symbol, ticker.mark_price); > } > PerpsMessage::Event(PerpsEvent::Trades(trades)) => { > println!("{} trades", trades.data.len()); > } > PerpsMessage::Reconnected(notice) => eprintln!("{}", notice.message), > PerpsMessage::LagWarning(warning) => { > eprintln!("upstream events dropped: {}", warning.dropped_events); > } > _ => {} > } > } > perps.close().await?; > Ok(()) > } > ``` The initial connection returns a hello message with the server's channel limit and currently active channels. `subscribe()` returns only after the server responds. ## Partial acceptance A subscription acknowledgement can accept some channels and reject others. Always inspect both lists: * `channels` contains the accepted channels that the SDK will restore after reconnect * `rejected` contains `{ channel, reason }` entries * `active_subscriptions` is the resulting server-side count Do not treat a resolved subscribe call as proof that every requested channel was accepted. ## Book events replace state Every received `perps_book` event is a complete replacement snapshot. Replace the prior bids and asks; do not merge it as a delta. A successful subscription acknowledgement confirms that the channel is active; it does not mean a book snapshot has already arrived. The managed cache returns no book until the first `perps_book` event. If startup requires state within a fixed readiness deadline, read the [V3 perps orderbook](/perps/market-data/book) and replace it with subsequent WebSocket snapshots. The managed clients retain the latest complete book: > [tab] TypeScript > > ```typescript theme={null} > const latest = perps.book('BTC-USD'); > console.log(latest?.bids[0], latest?.asks[0]); > ``` > [tab] Python > > ```python theme={null} > latest = perps.book("BTC-USD") > if latest: > print(latest["bids"][0], latest["asks"][0]) > ``` > [tab] Rust > > ```rust theme={null} > if let Some(latest) = perps.book("BTC-USD").await { > println!("{:?} {:?}", latest.bids.first(), latest.asks.first()); > } > ``` Perps prices and quantities are decimal strings. Preserve them as exact values for trading, accounting, and comparisons. ## Reconnect and gaps Automatic reconnect is enabled by default. After reconnect, the SDK resubscribes only the previously accepted channels and emits an explicit reconnect notice. The perps WebSocket does not replay messages missed while disconnected. Every reconnect notice sets `gap_possible` to `true`. Recover state as follows: * ticker, BBO, statistics, and book consumers can wait for a fresh event or refetch the matching REST endpoint * book consumers should discard the old book and wait for a new complete snapshot * trades and klines consumers should use the V3 REST routes to fill the time interval if continuity matters See [Perps market data](/perps/overview) for REST endpoints. ## Backpressure and lag Two different warnings can occur: | Signal | Meaning | Response | | - | - | - | | `lag_warning` | the server reports that upstream events were dropped for this connection | refetch affected state and reduce work in the read loop | | local queue overflow callback | TypeScript or Python evicted an old buffered message because the application did not consume fast enough | refetch affected state and move work to a bounded worker queue | > [tab] TypeScript > > ```typescript theme={null} > perps.onOverflow((notice) => { > console.error('local messages dropped', notice.droppedMessages); > }); > ``` > [tab] Python > > ```python theme={null} > perps.on_overflow( > lambda notice: print("local messages dropped", notice.dropped_messages) > ) > ``` > [tab] Rust > > Rust uses a bounded, backpressured receiver and does not silently evict local messages. Keep the `next()` loop responsive. ## Terminal closes Authentication close code `4401` and connection-cap close code `4429` are terminal. The SDK does not loop forever on credentials or account limits that require user action. Correct the API key or close another connection before starting a new client. ## Unknown messages Additive protocol messages remain observable: * TypeScript: `message.type === 'unknown'` * Python: `PerpsUnknownMessage` * Rust: `PerpsMessage::Unknown` Upgrade the SDK when you see one. Avoid logging credentials or an unbounded raw payload. ## Unsubscribe and close > [tab] TypeScript > > ```typescript theme={null} > await perps.unsubscribe([perpsChannels.book('BTC-USD')]); > perps.disconnect(); > ``` > [tab] Python > > ```python theme={null} > await perps.unsubscribe([perps_channels.book("BTC-USD")]) > await perps.disconnect() > ``` > [tab] Rust > > ```rust theme={null} > perps.unsubscribe(vec![book_channel("BTC-USD")?]).await?; > perps.close().await?; > ``` For channel payloads and instrument identifiers, see [Perps WebSocket channels](/perps/websocket/channels). # Python Configuration Source: https://docs.polynode.dev/sdks/python/config Configure Python endpoints, HTTP timeouts, reconnects, replay buffers, and orderbook integrity. The public endpoints are defaults. Override them only when PolyNode gives you another endpoint. ```python theme={null} import os from polynode import PolyNode pn = PolyNode( api_key=os.environ["POLYNODE_API_KEY"], base_url="https://api.polynode.dev", ws_url="wss://ws.polynode.dev/ws", ob_url="wss://ob.polynode.dev/ws", rpc_url="https://rpc.polynode.dev", timeout=10.0, ) ``` Use context managers to close HTTP clients. Streams have their own explicit lifecycle. ```python theme={null} from polynode import PolyNodeWS from polynode.types.ws import WsOptions events = PolyNodeWS( os.environ["POLYNODE_API_KEY"], "wss://ws.polynode.dev/ws", WsOptions( compress=True, auto_reconnect=True, max_reconnect_attempts=0, # 0 means unlimited reconnect_base_delay=1.0, reconnect_max_delay=30.0, subscribe_timeout=30.0, subscription_queue_capacity=4096, dedupe_capacity=4096, replay_overlap_ms=1, ), ) ``` Configure PN1 through `OrderbookEngine(..., integrity=True, allow_stale_reads=False)`. Configure perps capacity and reconnect behavior through `PerpsWS(...)` constructor arguments. Event and perps queues are bounded. Observe overflow callbacks and keep slow work out of message handlers. API keys belong in environment variables or a secret manager, never source code or logs. # Python Errors Source: https://docs.polynode.dev/sdks/python/errors Handle HTTP, WebSocket, reconnect, overflow, and orderbook-integrity failures in Python. ```python theme={null} from polynode import ApiError, PolyNodeError, WsError from polynode.orderbook_integrity import OrderbookIntegrityError try: result = pn.v3.execute("GET /v3/stats") except ApiError as error: print({ "status": error.status, "code": error.code, "hint": error.hint, "request_id": error.request_id, "retry_after": error.retry_after, "rate_limit": error.rate_limit, "safe_method": error.safe_method, "safe_url": error.safe_url, }) raise except WsError as error: print(error.code, error.message) raise except OrderbookIntegrityError as error: print(error.code, error.token, str(error)) raise except PolyNodeError as error: print(error.message) raise ``` Safe V3 reads retry transient failures and retryable statuses. State-changing calls are never retried automatically. After a mutation timeout, verify current state before submitting it again. Also observe non-exception delivery signals: * `pn.ws.on_replay(...)` for best-effort settlement replay; * `sub.on_overflow(...)` for local event loss; * `perps.on_reconnect(...)` for a possible perps gap; * `perps.on_overflow(...)` for local perps loss; * `integrity_error` for PN1 books that are gated until a fresh anchor succeeds. Log request IDs and redacted safe URLs, never API keys, private keys, CLOB secrets, builder credentials, or signed payloads. # Python Models Source: https://docs.polynode.dev/sdks/python/models Work with Python event models, unknown additive messages, Decimal V3 values, and exact orderbook strings. WebSocket events are Pydantic models selected by `event_type`: ```python theme={null} from polynode.types.events import PolyNodeEvent def handle_event(event: PolyNodeEvent) -> None: match event.event_type: case "settlement": print(event.tx_hash, event.taker_size) case "status_update": print(event.tx_hash, event.block_number) case "price_feed": print(event.feed, event.price, event.twap_window_seconds) case "unknown": print(event.wire_event_type, event.raw) case other: print(other) ``` The model union covers fills, settlements, trades, confirmation updates, blocks, position changes, deposits, splits, merges, conversions, redemptions, combo execution/status/lifecycle/approval events, oracle events, Chainlink price feeds, and an `UnknownEvent` fallback. Unknown additive messages preserve the raw payload. Observe them without treating every compatible server addition as fatal. V3 decimal fractions decode as `Decimal`. Orderbook prices and sizes remain exact strings. Perps prices and quantities are also wire strings. Keep these exact representations for accounting and convert only for display. See the [event reference](/websocket/events/settlement), [orderbook protocol](/orderbook/overview), and [perps channels](/perps/websocket/channels). # Python PN1 Orderbook Source: https://docs.polynode.dev/sdks/python/orderbook Maintain exact Python orderbooks with PN1 sequence and checksum verification. Use `OrderbookEngine` for a managed local book. Enable PN1 integrity for price-sensitive decisions. ```python theme={null} import asyncio import os from polynode import OrderbookEngine async def main() -> None: token_id = os.environ["POLYMARKET_TOKEN_ID"] engine = OrderbookEngine( os.environ["POLYNODE_API_KEY"], integrity=True, allow_stale_reads=False, ) engine.on("integrity_error", lambda error: print( error.code, error.token, error )) engine.on("ready", lambda: print({ "best_bid": engine.best_bid(token_id), "best_ask": engine.best_ask(token_id), "midpoint": engine.midpoint(token_id), "spread": engine.spread(token_id), })) try: await engine.subscribe([token_id]) await asyncio.Event().wait() finally: engine.close() asyncio.run(main()) ``` PN1 keeps price and size values as exact decimal strings. It validates the full-snapshot anchor, then validates sequence continuity and a deterministic checksum on each applicable update. Managed state moves through `initializing`, `ready`, `stale`, `resyncing`, and `failed`. With stale reads disabled, queries are unavailable until a verified anchor is ready and become unavailable after a disconnect or integrity failure. The engine requests a fresh anchor before returning to `ready`. > [!WARNING] > > Wildcard `"*"` subscriptions are unavailable in integrity mode. Use explicit token IDs, slugs, or condition IDs. For raw messages, construct `OrderbookWS(..., integrity=True)`, register `snapshot`, `resyncing`, `error`, and `unknown` handlers, then `await subscribe(...)`. Close it with `disconnect()`. See the [shared orderbook guide](/sdks/orderbook) and [PN1 protocol reference](/orderbook/integrity). # Python SDK Source: https://docs.polynode.dev/sdks/python/overview Install polynode 0.14 and make a first V3 request from Python. `polynode` provides synchronous and asynchronous V3 clients plus async event, orderbook, short-form, and perps streams. ## Install ```bash theme={null} python -m pip install --upgrade "polynode>=0.15.0,<0.16" ``` Python 3.10 or newer is required. Keep your API key outside source control: ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." ``` ## First request ```python theme={null} import os from polynode import PolyNode with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: stats = pn.v3.execute("GET /v3/stats") print(stats) ``` Use `AsyncPolyNode` in an async application: ```python theme={null} import asyncio import os from polynode import AsyncPolyNode async def main() -> None: async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: stats = await pn.v3.execute("GET /v3/stats") print(stats) asyncio.run(main()) ``` ## Client surfaces | Entry point | Use it for | | - | - | | `pn.v3` | Complete V3 API registry | | `pn.ws` | Settlements, confirmations, Chainlink prices, combos, and other events | | `pn.orderbook` | Raw orderbook messages | | `OrderbookEngine(...)` | Managed local books and PN1 integrity | | `pn.perps` | Managed V3 perps WebSocket | | `pn.ws.short_form(...)` | Rotating 5m, 15m, 1h, and 4h crypto markets | | `PolyNodeTrader(...)` | Current V2 order and position operations | > [card] [V3 API](/sdks/python/v3-api) > > Call any registered V3 operation. > [card] [Settlement stream](/sdks/python/websocket) > > Subscribe with replay and overflow visibility. > [card] [Short-form and TWAP](/sdks/python/short-form) > > Rotate with the correct Chainlink window. > [card] [PN1 orderbook](/sdks/python/orderbook) > > Maintain fail-closed local state. > [card] [Perps stream](/sdks/python/perps) > > Subscribe to tickers, books, trades, and klines. > [card] [Trading and fees](/sdks/python/trading) > > Use the current V2 defaults safely. > [card] [Connect Wallet to order](/sdks/user-owned-web-app) > > Use Python behind a browser-signing flow. # Python Perps Stream Source: https://docs.polynode.dev/sdks/python/perps Subscribe to managed Python perps tickers, BBO, full books, trades, statistics, and klines. The V3 perps WebSocket is separate from the event and prediction-market orderbook sockets. ```python theme={null} import asyncio import os from polynode import AsyncPolyNode, perps_channels async def main() -> None: async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: perps = pn.perps perps.on_reconnect(lambda notice: print("gap possible", notice)) perps.on_overflow(lambda notice: print("local overflow", notice)) ack = await perps.subscribe([ perps_channels.tickers, perps_channels.bbo("BTC-USD"), perps_channels.book("BTC-USD"), perps_channels.trades("BTC-USD"), perps_channels.klines("BTC-USD", "1m"), ]) if ack.rejected: print("rejected channels", ack.rejected) try: async for message in perps: if message.type == "event": print(message.channel, message.data) finally: await perps.disconnect() asyncio.run(main()) ``` One subscribe request can be partially accepted. Inspect `ack.channels` and `ack.rejected`. Each `perps_book` event is a complete replacement, not an incremental patch. `perps.book("BTC-USD")` returns the latest managed copy, or `None` until the first book event arrives. A successful acknowledgement confirms the channel, not book readiness; use the [V3 perps orderbook](/perps/market-data/book) when startup needs immediate state. The client reconnects and resubscribes after non-terminal disconnects, but replay is not guaranteed. Reconnect notices set `gap_possible=True`; use V3 REST to backfill when completeness matters. Authentication (`4401`) and connection-limit (`4429`) closes are terminal until the failing condition changes. See the [shared perps guide](/sdks/perps) for channel definitions, lag behavior, and lifecycle details. # Python REST Compatibility Source: https://docs.polynode.dev/sdks/python/rest-api Use the current Python V3 client and understand retained top-level V1/V2 helpers. Use `pn.v3` for new data integrations. The top-level sync and async methods remain available for existing V1/V2 integrations and focused helpers such as health, legacy market search, and RPC. ```python theme={null} import os from polynode import PolyNode with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: stats = pn.v3.execute("GET /v3/stats") health = pn.healthz() results = pn.search_events("bitcoin", limit=5) first_market = results.events[0].markets[0] if results.events else None condition_id = first_market.conditionId if first_market else None print(stats, health, len(results.events), condition_id) ``` Nested compatibility-search markets can omit `conditionId`, so the model exposes it as `str | None`. Use a token ID or slug when your workflow requires an identifier. Do not interpret the compatibility method list as the complete product API. Use [Python V3](/sdks/python/v3-api) for wallets, grouped trades, positions, combos, builders, credits, identities, profiles, webhooks, and perps. Both clients retain `rpc(method, params)`. It is an HTTP JSON-RPC helper and does not implement `eth_subscribe`; see the [RPC guide](/sdks/rpc). # Python Short-Form and TWAP Source: https://docs.polynode.dev/sdks/python/short-form Rotate Python subscriptions across short-form crypto markets with the correct Chainlink TWAP window. > [!WARNING] > > Starting **August 7, 2026 at 00:00 UTC**, use a 30-second TWAP for 5-minute markets and a 60-second TWAP for 15-minute and 4-hour markets. One-hour markets continue to use the default spot feed. | Market interval | Chainlink selection | | - | - | | `5m` | `30` seconds | | `15m` | `60` seconds | | `1h` | default spot feed | | `4h` | `60` seconds | ```python theme={null} import asyncio import os from polynode import AsyncPolyNode async def main() -> None: async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: stream = pn.ws.short_form( "5m", coins=["btc", "eth", "sol"], ) def on_rotation(rotation) -> None: for market in rotation.markets: print({ "coin": market.coin, "slug": market.slug, "feed": market.chainlink_feed, "twap_window_seconds": market.twap_window_seconds, "price_to_beat": market.price_to_beat, }) stream.on("rotation", on_rotation) stream.on("settlement", print) stream.on("error", print) try: await asyncio.Event().wait() finally: stream.stop() pn.ws.disconnect() asyncio.run(main()) ``` At every boundary the helper closes its dedicated socket, opens a new one, and subscribes to the new market identifiers and Chainlink selection. Consumers do not calculate the next slug manually, but should handle a normal connection transition around rotation. Supported assets are BTC, ETH, SOL, XRP, DOGE, HYPE, and BNB. ## Explicit Chainlink selection ```python theme={null} prices = await ( pn.ws.subscribe("chainlink") .feeds(["BTC/USD", "ETH/USD"]) .twap_windows([30, 60]) .send() ) print(prices.price_source, prices.twap_windows) prices.on("price_feed", lambda event: print( event.feed, event.price, event.is_twap, event.twap_window_seconds )) ``` Use one Chainlink selection per event socket. Combine feeds and windows, or create a separate `PolyNodeWS` when selections must be isolated. Read the [shared short-form guide](/sdks/short-form) for market fields, manual mode, and orderbook integration. # Python Trading and Fees Source: https://docs.polynode.dev/sdks/python/trading Use Python's V2 trading defaults and keep protocol fees, builder attribution, and application fees distinct. Install the optional trading dependencies. Quote the extra so shells such as zsh do not treat brackets as a filename pattern: For optional zero-builder attribution backed by the signing wallet, see [User-owned execution](/sdks/user-owned-execution). For an injected-wallet application, follow [Connect Wallet to order](/sdks/user-owned-web-app). ```bash theme={null} python -m pip install "polynode[trading]>=0.15.0,<0.16" ``` > [!NOTE] > > This version also trades Polymarket Protocol V2 markets, a separate and newer change from the V2 exchange default below, with the same calls and no config change. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). Polymarket V2 is the default: ```python theme={null} import os from polynode.trading import ExchangeVersion, PolyNodeTrader, TraderConfig trader = PolyNodeTrader(TraderConfig( polynode_key=os.environ["POLYNODE_API_KEY"], exchange_version=ExchangeVersion.V2, # Optional: already the default )) ready = await trader.ensure_ready(os.environ["POLYGON_PRIVATE_KEY"]) print("funder address", ready.funder_address) ``` `ensure_ready()` can deploy or approve wallet contracts and is state-changing for a new wallet. After the returned funder address is funded, `order(...)` places a real order: ```python theme={null} import os from polynode.trading import OrderParams try: result = await trader.order(OrderParams( token_id=os.environ["POLYMARKET_TOKEN_ID"], side="BUY", price=0.55, size=10, type="GTC", post_only=True, )) if not result.success: raise RuntimeError(result.error or "Order rejected") print(result.order_id) finally: trader.close() ``` V2 protocol fees are applied by Polymarket at match time. Do not add legacy `fee_rate_bps`, `nonce`, or `taker` fields to a V2 signed order. `builder_code` attributes eligible volume; it does not itself charge an application fee. `fee_config` is separate and disabled unless you configure it. Read [Trading and fees](/sdks/trading) before running state-changing examples. It covers funding, cancellation, builder overrides, V2 fee behavior, position operations, and cleanup. # Python V3 API Source: https://docs.polynode.dev/sdks/python/v3-api Use synchronous or asynchronous Python clients for all 120 registered V3 operations. Python 0.14.1 exposes the complete shared V3 operation registry through both `PolyNode` and `AsyncPolyNode`. V3 JSON decimal fractions are decoded as `Decimal` so money and prices are not silently rounded through binary floating point. ## Discover operations ```python theme={null} from polynode import V3_OPERATION_COUNT, V3_OPERATIONS print(V3_OPERATION_COUNT) # 120 in 0.14.1 for operation in V3_OPERATIONS: print(operation.method, operation.path, operation.domain) ``` ## Synchronous requests ```python theme={null} import os from polynode import PolyNode address = "0xa9857c7bcb9bcfafd2c132ab053f34f678610058" with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: combo_summary = pn.v3.execute( "GET /v3/wallets/{address}/combos/summary", path_params={"address": address}, ) trades = pn.v3.execute( "GET /v3/trades", query={ "limit": 50, "sort_by": "order_hash", "group_by": "order_hash", }, ) print(combo_summary, trades) ``` ## Asynchronous requests ```python theme={null} import asyncio import os from polynode import AsyncPolyNode async def main() -> None: async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: ticker = await pn.v3.execute( "GET /v3/perps/tickers/{instrument}", path_params={"instrument": "BTC-USD"}, ) print(ticker) asyncio.run(main()) ``` Use the exact `METHOD /v3/path` name from `V3_OPERATIONS`. Path and query values are encoded separately. ## Retry and precision behavior Safe reads retry transient failures and respect `Retry-After` within the configured ceiling. State-changing calls are never retried automatically. After a mutation timeout, inspect the resource before trying again. ```python theme={null} from polynode import ApiError try: stats = pn.v3.execute("GET /v3/stats") except ApiError as error: print({ "status": error.status, "code": error.code, "request_id": error.request_id, "retry_after": error.retry_after, "safe_url": error.safe_url, }) raise ``` See the [complete V3 guide](/sdks/v3-api) and [V3 endpoint reference](/data/overview). # Python Settlement Stream Source: https://docs.polynode.dev/sdks/python/websocket Consume acknowledged Python settlement subscriptions with reconnect replay, deduplication, and overflow visibility. The event client is asynchronous. `send()` returns only after the server acknowledges the subscription. ```python theme={null} import asyncio import os from polynode import AsyncPolyNode async def main() -> None: async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: sub = await ( pn.ws.subscribe("settlements") .status("all") .min_size(100) .send() ) print({"subscription_id": sub.id, "warnings": sub.warnings}) sub.on("settlement", lambda event: print( "pending", event.tx_hash, event.taker_size )) sub.on("status_update", lambda event: print( "confirmed", event.tx_hash, event.block_number )) sub.on_overflow(lambda notice: print("consumer fell behind", notice)) pn.ws.on_replay(lambda notice: print("reconnect replay", notice)) try: async for event in sub: if event.event_type == "unknown": print("new event type", event.wire_event_type, event.raw) finally: sub.unsubscribe() pn.ws.disconnect() asyncio.run(main()) ``` Current presets are `settlements`, `trades`, `prices`, `dome`, `fills`, `combos`, `redemptions`, `redemption`, `deposits`, `blocks`, `wallets`, `markets`, `large_trades`, `global`, `oracle`, and `chainlink`. Builder filters include wallets, tokens, market IDs, slugs, condition IDs, side, direction, status, size bounds, event types, initial snapshot count, reconnect `since`, Chainlink feeds and TWAP windows, combo and leg IDs, event IDs, module IDs, and action. ```python theme={null} import time fills = await ( pn.ws.subscribe("fills") .wallets(["0x..."]) .condition_ids(["0x..."]) .since(int(time.time() * 1000) - 30_000) .send() ) ``` On reconnect, the SDK replays from the latest accepted timestamp with a small overlap and deduplicates that overlap. Replay is best effort within retained server history, not an unlimited delivery guarantee. Backfill through V3 if durable completeness matters. The iterator queue is bounded. `on_overflow` makes local loss observable. Short-form rotation has a separate lifecycle: it closes and reconnects its dedicated socket at each market boundary. See [Python short-form](/sdks/python/short-form). Read the [shared settlement guide](/sdks/websocket-streaming) for the complete delivery contract. # Redemption Watcher Source: https://docs.polynode.dev/sdks/redemption-watcher Track wallet positions and receive an alert when an oracle resolution makes them redeemable. `RedemptionWatcher` loads positions for selected wallets, watches oracle resolutions, and emits a `RedeemableAlert` for matching positions. It can also follow live position changes and periodically refresh positions. Use the direct `redemptions` event preset when you need the raw redemption stream. Use this helper when you want wallet-aware position matching and an estimated payout in one object. To receive alerts for [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2), use TypeScript `polynode-sdk` 0.15.0, Python `polynode` 0.15.1, or Rust `polynode` 0.18.0 or newer. ## Start ```typescript TypeScript theme={null} import { RedemptionWatcher } from 'polynode-sdk'; const watcher = new RedemptionWatcher({ apiKey: process.env.POLYNODE_API_KEY!, }); watcher.on('alert', (alert) => { console.log(alert.wallet, alert.marketTitle, alert.isWinner, alert.estimatedPayoutUsd); }); watcher.on('error', console.error); await watcher.start(['0xabc...']); ``` ```python Python theme={null} import asyncio import os from polynode import RedemptionWatcher async def main() -> None: watcher = RedemptionWatcher(os.environ["POLYNODE_API_KEY"]) watcher.on("alert", lambda alert: print( alert.wallet, alert.market_title, alert.is_winner, alert.estimated_payout_usd, )) await watcher.start(["0xabc..."]) try: async for alert in watcher: print(alert.condition_id, alert.token_id) finally: watcher.close() asyncio.run(main()) ``` ```rust Rust theme={null} use polynode::{PolyNodeClient, RedemptionWatcher, RedemptionWatcherConfig}; use std::sync::Arc; #[tokio::main] async fn main() -> polynode::Result<()> { let client = Arc::new(PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?); let mut watcher = RedemptionWatcher::new( client, RedemptionWatcherConfig::default(), ); watcher.start(&["0xabc..."]).await?; while let Some(alert) = watcher.next_alert().await { println!("{} {} {}", alert.wallet, alert.market_title, alert.estimated_payout_usd); } watcher.close(); Ok(()) } ``` ## Alert fields An alert identifies the wallet, condition and token, held and winning outcomes, whether the position won, size, estimated payout, market title and slug, resolution price and payouts, block number, and timestamp. An alert is a notification to inspect a position. Your application should verify current position state before submitting a redemption transaction. ## Lifecycle Register handlers before `start` so early alerts are not missed. The TypeScript and Python helpers support adding and removing wallets at runtime. All languages expose the tracked wallet/position state and a close method. Close the watcher during shutdown to stop refresh work and release its subscriptions. Reconnect delivery is best effort; the periodic refresh is useful as a reconciliation layer, not a promise of exactly-once alerts. See [Oracle events](/websocket/events/oracle) and [Redemption events](/websocket/events/redemption) for the underlying payloads. # REST Clients Source: https://docs.polynode.dev/sdks/rest-api Use the complete V3 API or the SDKs' compatibility methods for older V1 and V2 endpoints. Use the V3 client for current PolyNode data. It contains a shared registry for every supported V3 route, including wallets, positions, trades, combos, fees, builders, webhooks, credits, identities, profiles, and perps. The main client also keeps top-level convenience methods for older V1 and V2 endpoints. Those methods are useful for existing integrations, but they are not the complete current product surface. > [card] [Complete V3 SDK guide](/sdks/v3-api) > > Learn how to discover and call all 120 registered V3 operations from TypeScript, Python, or Rust. ## Compatibility methods > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > const pn = new PolyNode({ apiKey }); > > const markets = await pn.markets({ count: 10 }); > const results = await pn.search('bitcoin', { limit: 10 }); > console.log(markets.count, results.results.length); > ``` > [tab] Python > > ```python theme={null} > import os > from polynode import PolyNode > > with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > markets = pn.markets(count=10) > results = pn.search("bitcoin", limit=10) > print(markets.count, len(results.results)) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::PolyNodeClient; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let client = PolyNodeClient::new( > std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") > )?; > let markets = client.markets(Some(10)).await?; > println!("{} markets", markets.count); > Ok(()) > } > ``` ## Which client should I use? | Need | Use | | - | - | | New wallet, trade, position, combo, fee, builder, webhook, credit, identity, profile, or perps integration | [V3 client](/sdks/v3-api) | | Existing code already using `market()`, `search()`, or the equivalent language method | Keep the top-level method | | Exact endpoint request and response fields | [V3 Data API reference](/data/overview) or [Perps reference](/perps/overview) | Top-level and V3 methods can be used from the same client. Migrating one request at a time does not change the behavior of the remaining compatibility calls. # RPC Helper Source: https://docs.polynode.dev/sdks/rpc Make authenticated Polygon JSON-RPC requests from TypeScript, Python, or Rust. Every SDK includes an HTTP JSON-RPC helper for `rpc.polynode.dev`. It is useful for Polygon reads that complement market data. ```typescript TypeScript theme={null} const blockNumber = await pn.rpc('eth_blockNumber'); const balance = await pn.rpc('eth_getBalance', ['0xabc...', 'latest']); console.log({ blockNumber, balance }); ``` ```python Python theme={null} block_number = pn.rpc("eth_blockNumber") balance = pn.rpc("eth_getBalance", ["0xabc...", "latest"]) print(block_number, balance) ``` ```rust Rust theme={null} let block_number = client .rpc_call("eth_blockNumber", serde_json::json!([])) .await?; let balance = client .rpc_call("eth_getBalance", serde_json::json!(["0xabc...", "latest"])) .await?; println!("{block_number} {balance}"); ``` The SDK helper uses HTTP. It does not provide WebSocket `eth_subscribe`. Never log raw signed transactions or private keys, and confirm chain ID, nonce, fees, and destination before using any state-changing RPC method. See the [RPC documentation](/rpc/overview) for supported methods, limits, and transaction guidance. # Rust Configuration Source: https://docs.polynode.dev/sdks/rust/config Configure Rust endpoints, timeouts, reconnects, bounded buffers, and PN1 integrity. The public endpoints are defaults. Override them only when PolyNode gives you another endpoint. ```rust theme={null} use polynode::PolyNodeClient; use std::time::Duration; let client = PolyNodeClient::builder(std::env::var("POLYNODE_API_KEY")?) .base_url("https://api.polynode.dev") .ws_url("wss://ws.polynode.dev/ws") .ob_url("wss://ob.polynode.dev/ws") .rpc_url("https://rpc.polynode.dev") .timeout(Duration::from_secs(10)) .build()?; ``` Configure each stream before connecting: ```rust theme={null} use polynode::{EngineOptions, PerpsStreamOptions, StreamOptions}; let event_options = StreamOptions { compress: true, auto_reconnect: true, max_reconnect_attempts: None, message_buffer_capacity: 4096, dedupe_capacity: 4096, replay_overlap: Duration::from_millis(1), ..Default::default() }; let orderbook_options = EngineOptions { integrity: true, allow_stale_reads: false, ..Default::default() }; let perps_options = PerpsStreamOptions { auto_reconnect: true, message_buffer_capacity: 4096, ..Default::default() }; ``` Rust's bounded channels apply backpressure. Poll stream `next()` methods continuously and move expensive work to a bounded worker pipeline. API keys belong in environment variables or a secret manager, never source code, panic messages, or logs. # Rust Errors Source: https://docs.polynode.dev/sdks/rust/errors Handle structured V3, WebSocket, trading, reconnect, and PN1 integrity failures in Rust. ```rust theme={null} use polynode::Error; match client.v3() .execute_named("GET /v3/stats", Default::default()) .await { Ok(value) => println!("{value:#}"), Err(Error::V3Api(error)) => { eprintln!("status={} code={:?}", error.status, error.code); eprintln!("request_id={:?} retry_after={:?}", error.request_id, error.retry_after); eprintln!("{} {}", error.safe_method, error.safe_url); } Err(error) => return Err(error), } ``` Safe V3 reads retry transient failures and retryable statuses. State-changing calls are never retried automatically. After a mutation timeout, verify current state before submitting it again. WebSocket delivery signals arrive as typed messages: * `WsMessage::Replay` reports best-effort settlement replay; * `PerpsMessage::Reconnected` reports a possible perps gap; * `PerpsMessage::LagWarning` reports upstream lag; * the event and perps receive channels are bounded and apply backpressure; * `engine.integrity_errors()` reports PN1 failures and the affected token remains gated until a fresh anchor succeeds. Log request IDs and redacted safe URLs, never API keys, private keys, CLOB secrets, builder credentials, or signed payloads. # Rust PN1 Orderbook Source: https://docs.polynode.dev/sdks/rust/orderbook Maintain exact Rust orderbooks with PN1 sequence and checksum verification. ```rust theme={null} use polynode::{EngineOptions, OrderbookEngine}; #[tokio::main] async fn main() -> polynode::Result<()> { let api_key = std::env::var("POLYNODE_API_KEY") .expect("Set POLYNODE_API_KEY"); let token_id = std::env::var("POLYMARKET_TOKEN_ID") .expect("Set POLYMARKET_TOKEN_ID"); let engine = OrderbookEngine::connect(&api_key, EngineOptions { integrity: true, allow_stale_reads: false, ..Default::default() }).await?; let mut integrity_errors = engine.integrity_errors(); tokio::spawn(async move { while let Ok(error) = integrity_errors.recv().await { eprintln!("{:?} {} {}", error.code, error.token, error.message); } }); engine.subscribe(vec![token_id.clone()]).await?; while engine.book(&token_id).await.is_none() { tokio::time::sleep(std::time::Duration::from_millis(10)).await; } println!("best bid: {:?}", engine.best_bid(&token_id).await); println!("best ask: {:?}", engine.best_ask(&token_id).await); println!("midpoint: {:?}", engine.midpoint(&token_id).await); println!("spread: {:?}", engine.spread(&token_id).await); engine.close().await?; Ok(()) } ``` PN1 keeps price and size values as exact decimal strings. It validates the full-snapshot anchor, then validates sequence continuity and a deterministic checksum on each applicable update. Managed state moves through `Initializing`, `Ready`, `Stale`, `Resyncing`, and `Failed`. With stale reads disabled, queries are unavailable until a verified anchor is ready and become unavailable after a disconnect or integrity failure. The engine requests a fresh anchor before returning to ready. > [!WARNING] > > Wildcard `"*"` subscriptions are unavailable in integrity mode. Use explicit token IDs, slugs, or condition IDs. Use `client.orderbook_stream(ObStreamOptions { integrity: true, ..Default::default() })` when you want raw `ObMessage` values instead of managed state. See the [shared orderbook guide](/sdks/orderbook) and [PN1 protocol reference](/orderbook/integrity). # Rust SDK Source: https://docs.polynode.dev/sdks/rust/overview Install polynode 0.17 and make a first V3 request with Tokio. The Rust crate provides Tokio clients for the complete V3 registry, event streaming, PN1 orderbooks, perps, short-form markets, and optional trading and cache features. ## Install ```toml Cargo.toml theme={null} [dependencies] polynode = "0.18.0" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` Keep the key outside source control: ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." ``` ## First request ```rust theme={null} use polynode::{PolyNodeClient, V3RequestOptions}; #[tokio::main] async fn main() -> polynode::Result<()> { let api_key = std::env::var("POLYNODE_API_KEY") .expect("Set POLYNODE_API_KEY"); let client = PolyNodeClient::new(api_key)?; let stats = client .v3() .execute_named("GET /v3/stats", V3RequestOptions::default()) .await?; println!("{stats:#}"); Ok(()) } ``` ## Client surfaces | Entry point | Use it for | | - | - | | `client.v3()` | Complete V3 API registry | | `client.stream(...)` | Settlements, confirmations, Chainlink prices, combos, and other events | | `client.orderbook_stream(...)` | Raw orderbook messages | | `OrderbookEngine::connect(...)` | Managed local books and PN1 integrity | | `client.perps_stream()` | Managed V3 perps WebSocket | | `client.short_form(...)` | Rotating 5m, 15m, 1h, and 4h crypto markets | | `PolyNodeTrader` | Current V2 trading with the `trading` feature | > [card] [V3 API](/sdks/rust/v3-api) > > Call any registered V3 operation. > [card] [Settlement stream](/sdks/rust/websocket) > > Subscribe with replay and backpressure. > [card] [Short-form and TWAP](/sdks/rust/short-form) > > Rotate with the correct Chainlink window. > [card] [PN1 orderbook](/sdks/rust/orderbook) > > Maintain fail-closed local state. > [card] [Perps stream](/sdks/rust/perps) > > Subscribe to tickers, books, trades, and klines. > [card] [Trading and fees](/sdks/rust/trading) > > Enable the trading feature and use V2 defaults. > [card] [Connect Wallet to order](/sdks/user-owned-web-app) > > Use Rust behind a browser-signing flow. # Rust Perps Stream Source: https://docs.polynode.dev/sdks/rust/perps Subscribe to managed Rust perps tickers, BBO, full books, trades, statistics, and klines. ```rust theme={null} use polynode::{ bbo_channel, book_channel, klines_channel, ticker_channel, trades_channel, PerpsMessage, PolyNodeClient, }; #[tokio::main] async fn main() -> polynode::Result<()> { let client = PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?; let mut perps = client.perps_stream().await?; let ack = perps.subscribe(vec![ ticker_channel(), bbo_channel("BTC-USD")?, book_channel("BTC-USD")?, trades_channel("BTC-USD")?, klines_channel("BTC-USD", "1m")?, ]).await?; if !ack.rejected.is_empty() { eprintln!("rejected channels: {:?}", ack.rejected); } while let Some(message) = perps.next().await { match message? { PerpsMessage::Event(event) => println!("{event:?}"), PerpsMessage::Reconnected(notice) => { eprintln!("gap possible: {}", notice.gap_possible); } PerpsMessage::LagWarning(warning) => eprintln!("{warning:?}"), PerpsMessage::Unknown { raw, decode_error } => { println!("unknown: {raw} {decode_error:?}"); } _ => {} } } perps.close().await?; Ok(()) } ``` One subscribe request can be partially accepted. Inspect `ack.channels` and `ack.rejected`. Each `PerpsEvent::Book` is a complete replacement, not an incremental patch. `perps.book("BTC-USD").await` returns the latest managed copy, or `None` until the first book event arrives. A successful acknowledgement confirms the channel, not book readiness; use the [V3 perps orderbook](/perps/market-data/book) when startup needs immediate state. The client reconnects and resubscribes after non-terminal disconnects, but replay is not guaranteed. `PerpsReconnectNotice.gap_possible` is true; use V3 REST to backfill if completeness matters. Authentication (`4401`) and connection-limit (`4429`) closes are terminal until the failing condition changes. The bounded receive channel applies backpressure. Poll `next()` continuously and move slow work to a bounded worker pipeline. See the [shared perps guide](/sdks/perps) for channel definitions and lifecycle details. # Rust REST Compatibility Source: https://docs.polynode.dev/sdks/rust/rest-api Use the current Rust V3 client and understand retained V1/V2 helper methods. Use `client.v3()` for new data integrations. Existing typed methods remain for V1/V2 compatibility and focused helpers such as health, legacy market search, and RPC. ```rust theme={null} use polynode::{PolyNodeClient, V3RequestOptions}; #[tokio::main] async fn main() -> polynode::Result<()> { let client = PolyNodeClient::new(std::env::var("POLYNODE_API_KEY").unwrap())?; let stats = client.v3() .execute_named("GET /v3/stats", V3RequestOptions::default()) .await?; let health = client.healthz().await?; let results = client.search_events("bitcoin", Some(5)).await?; let typed_markets = match results.events.first() { Some(event) => event.typed_markets()?, None => Vec::new(), }; let condition_id = typed_markets.first().and_then(|market| market.condition_id.as_deref()); println!("{stats:#} {health} {} {condition_id:?}", results.events.len()); Ok(()) } ``` `typed_markets()` preserves the existing raw search payload while parsing it into `EventSearchMarket`. Its `condition_id` is optional because nested compatibility-search markets can omit that field. Do not interpret the compatibility method list as the complete product API. Use [Rust V3](/sdks/rust/v3-api) for wallets, grouped trades, positions, combos, builders, credits, identities, profiles, webhooks, and perps. `client.rpc_call(method, params)` is an HTTP JSON-RPC helper and does not implement `eth_subscribe`; see the [RPC guide](/sdks/rpc). # Rust Short-Form and TWAP Source: https://docs.polynode.dev/sdks/rust/short-form Rotate Rust subscriptions across short-form crypto markets with the correct Chainlink TWAP window. > [!WARNING] > > Starting **August 7, 2026 at 00:00 UTC**, use a 30-second TWAP for 5-minute markets and a 60-second TWAP for 15-minute and 4-hour markets. One-hour markets continue to use the default spot feed. | Market interval | Rust variant | Chainlink selection | | - | - | - | | `5m` | `FiveMin` | `30` seconds | | `15m` | `FifteenMin` | `60` seconds | | `1h` | `Hourly` | default spot feed | | `4h` | `FourHour` | `60` seconds | ```rust theme={null} use polynode::{ Coin, PolyNodeClient, ShortFormInterval, ShortFormMessage, }; #[tokio::main] async fn main() -> polynode::Result<()> { let client = PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?; let mut stream = client .short_form(ShortFormInterval::FiveMin) .coins(&[Coin::Btc, Coin::Eth, Coin::Sol]) .start() .await?; while let Some(message) = stream.next().await { match message { ShortFormMessage::Rotation(rotation) => { println!("TWAP: {:?}", rotation.twap_window_seconds); for market in rotation.markets { println!( "{} {} {:?} {:?}", market.coin.id(), market.slug, market.chainlink_feed, market.price_to_beat, ); } } ShortFormMessage::PriceFeed(price) => println!("{price:?}"), ShortFormMessage::Event(event) => println!("{event:?}"), ShortFormMessage::Error(error) => eprintln!("{error}"), } } stream.stop().await; Ok(()) } ``` At every boundary the helper closes its dedicated socket, opens a new one, and subscribes to the new identifiers and Chainlink selection. Consumers do not calculate the next slug manually, but should handle a normal connection transition around rotation. Supported assets are BTC, ETH, SOL, XRP, DOGE, HYPE, and BNB. For a manual Chainlink stream, combine feeds and `twap_windows(vec![30, 60])` in one `SubscriptionType::Chainlink` subscription. One event socket can own one Chainlink selection; open another `WsStream` when selections must be isolated. Read the [shared short-form guide](/sdks/short-form) for market fields, manual mode, and orderbook integration. # Rust Trading and Fees Source: https://docs.polynode.dev/sdks/rust/trading Enable Rust trading, use the V2 default, and distinguish protocol fees, builder attribution, and application fees. ```toml Cargo.toml theme={null} [dependencies] polynode = { version = "0.18.0", features = ["trading"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` For optional zero-builder attribution backed by the signing wallet, see [User-owned execution](/sdks/user-owned-execution). For an injected-wallet application, follow [Connect Wallet to order](/sdks/user-owned-web-app). > [!NOTE] > > This version also trades Polymarket Protocol V2 markets, a separate and newer change from the V2 exchange default below, with the same calls and no config change. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). Polymarket V2 is the default: ```rust theme={null} use polynode::trading::{ ExchangeVersion, PolyNodeTrader, PrivateKeySigner, TraderConfig, }; let mut trader = PolyNodeTrader::new(TraderConfig { polynode_key: std::env::var("POLYNODE_API_KEY")?, exchange_version: ExchangeVersion::V2, // Optional: already the default ..Default::default() })?; let signer = PrivateKeySigner::from_hex(&std::env::var("POLYGON_PRIVATE_KEY")?)?; let ready = trader.ensure_ready(Box::new(signer), None).await?; println!("funder address: {}", ready.funder_address); ``` `ensure_ready()` can deploy or approve wallet contracts and is state-changing for a new wallet. After the returned funder address is funded, `order(...)` places a real order: ```rust theme={null} use polynode::trading::{OrderParams, OrderSide, OrderType}; let result = trader.order(OrderParams { token_id: std::env::var("POLYMARKET_TOKEN_ID")?, side: OrderSide::Buy, price: 0.55, size: 10.0, order_type: OrderType::GTC, expiration: None, post_only: true, fee_config: None, builder: None, }).await?; if !result.success { return Err(polynode::Error::Trading( result.error.unwrap_or_else(|| "order rejected".into()), )); } println!("{:?}", result.order_id); trader.close(); ``` V2 protocol fees are applied by Polymarket at match time. Do not add legacy `fee_rate_bps`, `nonce`, or `taker` fields to a V2 signed order. `builder_code` attributes eligible volume; it does not itself charge an application fee. `fee_config` is separate and disabled unless configured. Read [Trading and fees](/sdks/trading) before running state-changing examples. It covers funding, cancellation, builder overrides, V2 fee behavior, position operations, and cleanup. # Rust V3 API Source: https://docs.polynode.dev/sdks/rust/v3-api Execute all 120 registered V3 operations with precision-preserving serde_json values. Rust 0.17.1 exposes the complete shared V3 registry through `client.v3()`. Generic responses use `serde_json::Value`, preserving decimal strings and large integer wire values. ## Discover operations ```rust theme={null} use polynode::{V3_OPERATIONS, V3_OPERATION_COUNT}; fn main() { println!("{V3_OPERATION_COUNT}"); // 120 in 0.17.1 for operation in V3_OPERATIONS { println!("{} {} {}", operation.method, operation.path, operation.domain); } } ``` ## Execute a registered route ```rust theme={null} use polynode::{PolyNodeClient, V3RequestOptions}; #[tokio::main] async fn main() -> polynode::Result<()> { let client = PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?; let address = "0xa9857c7bcb9bcfafd2c132ab053f34f678610058"; let summary = client.v3().execute_named( "GET /v3/wallets/{address}/combos/summary", V3RequestOptions::default().path_param("address", address), ).await?; let trades = client.v3().execute_named( "GET /v3/trades", V3RequestOptions::default() .query_param("limit", 50_u64) .query_param("sort_by", "order_hash") .query_param("group_by", "order_hash"), ).await?; println!("{summary:#}\n{trades:#}"); Ok(()) } ``` Use the exact `METHOD /v3/path` name from `V3_OPERATIONS`. Path and query values are encoded separately. ## Perps REST data ```rust theme={null} let ticker = client.v3().execute_named( "GET /v3/perps/tickers/{instrument}", V3RequestOptions::default().path_param("instrument", "BTC-USD"), ).await?; println!("{ticker:#}"); ``` Safe reads retry transient failures and respect `Retry-After` within the configured ceiling. State-changing calls are never retried automatically. `Error::V3Api` exposes status, code, request ID, retry metadata, and a redacted safe URL. See the [complete V3 guide](/sdks/v3-api) and [V3 endpoint reference](/data/overview). # Rust Settlement Stream Source: https://docs.polynode.dev/sdks/rust/websocket Consume acknowledged Rust settlement subscriptions with reconnect replay, deduplication, and bounded backpressure. ```rust theme={null} use polynode::{PolyNodeClient, PolyNodeEvent, WsMessage}; use polynode::ws::{StreamOptions, Subscription, SubscriptionType}; #[tokio::main] async fn main() -> polynode::Result<()> { let client = PolyNodeClient::new( std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") )?; let mut stream = client.stream(StreamOptions::default()).await?; let ack = stream.subscribe_with_ack( Subscription::new(SubscriptionType::Settlements) .status("all") .min_size(100.0), ).await?; println!("{} {:?}", ack.subscription_id, ack.warnings); while let Some(message) = stream.next().await { match message? { WsMessage::Event(PolyNodeEvent::Settlement(event)) => { println!("pending {} {}", event.tx_hash, event.taker_size); } WsMessage::Event(PolyNodeEvent::StatusUpdate(event)) => { println!("confirmed {} {}", event.tx_hash, event.block_number); } WsMessage::Replay(notice) => { eprintln!("reconnect replay, guaranteed={}", notice.guaranteed); } WsMessage::UnknownEvent(event) => { println!("new event type {}: {}", event.wire_event_type, event.raw); } _ => {} } } stream.close().await?; Ok(()) } ``` Current presets are `Settlements`, `Trades`, `Prices`, `Dome`, `Fills`, `Combos`, `Redemptions`, `Redemption`, `Deposits`, `Blocks`, `Wallets`, `Markets`, `LargeTrades`, `Global`, `Oracle`, and `Chainlink`. Subscription filters cover wallets, tokens, market IDs, slugs, condition IDs, side, direction, status, size bounds, event types, snapshots, reconnect `since`, Chainlink feeds and TWAP windows, combo and leg IDs, event IDs, module IDs, and action. On reconnect, the stream resubscribes from the latest accepted timestamp with a small overlap and deduplicates the overlap. Replay is best effort within retained server history, not an unlimited delivery guarantee. `ReplayNotice.guaranteed` is always false. The receive channel is bounded and applies backpressure rather than silently evicting messages. Poll `next()` continuously and move slow work to a bounded worker pipeline. Short-form rotation deliberately closes and replaces its dedicated socket at every market boundary. See [Rust short-form](/sdks/rust/short-form). Read the [shared settlement guide](/sdks/websocket-streaming) for the complete delivery contract. # Short-Form Markets and Chainlink TWAP Source: https://docs.polynode.dev/sdks/short-form Follow rotating 5-minute, 15-minute, 1-hour, and 4-hour crypto markets with the matching Chainlink price window. The managed short-form stream discovers the active Polymarket crypto market, subscribes to its settlements, follows the matching Chainlink price source, and rotates to the next market window. Starting **August 7, 2026 at 00:00 UTC**, affected Polymarket short-form markets resolve against Chainlink-computed time-weighted average prices. Current SDKs select the required lookback automatically: | Market duration | Chainlink price selection | | - | - | | 5 minutes | 30-second TWAP | | 15 minutes | 60-second TWAP | | 1 hour | spot / default stream | | 4 hours | 60-second TWAP | `30` and `60` are lookback windows, not publication intervals. Read [Polymarket's August 7 announcement](https://x.com/polymarketdevs/status/2082813706996772881), the [PolyNode transition guide](/crypto/twap), and [Polymarket's Chainlink TWAP guide](https://docs.polymarket.com/market-data/chainlink-twap) for the schedule and underlying price semantics. > [!NOTE] > > Use TypeScript `0.12.0+`, Python `0.12.0+`, or Rust `0.15.0+`. Earlier versions do not implement the complete interval-to-TWAP mapping and rotation behavior documented here. Markets that open on [Polymarket Protocol V2](/guides/polymarket-protocol-v2) need TypeScript `0.15.0+`, Python `0.15.0+`, or Rust `0.18.0+`, which select the right outcome ids for them. ## Managed stream Choose an interval and, optionally, a subset of supported assets. The default is all seven: BTC, ETH, SOL, XRP, DOGE, HYPE, and BNB. > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > const pn = new PolyNode({ apiKey }); > > const stream = pn.ws.shortForm('5m', { coins: ['btc', 'eth'] }); > > stream.on('rotation', (rotation) => { > console.log('window', rotation.windowStart, rotation.windowEnd); > for (const market of rotation.markets) { > console.log({ > coin: market.coin, > slug: market.slug, > priceToBeat: market.priceToBeat, > twapWindowSeconds: market.twapWindowSeconds, > upOdds: market.upOdds, > timeRemaining: rotation.timeRemaining, > }); > } > }); > > stream.on('price_feed', (price) => { > console.log(price.feed, price.price, price.twap_window_seconds); > }); > stream.on('settlement', (event) => console.log(event.status, event.tx_hash)); > stream.on('error', (error) => console.error(error.message)); > > process.once('SIGINT', () => stream.stop()); > ``` > [tab] Python > > ```python theme={null} > import asyncio > import os > from polynode import AsyncPolyNode > > async def main() -> None: > async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > stream = pn.ws.short_form("5m", coins=["btc", "eth"]) > > def on_rotation(rotation) -> None: > for market in rotation.markets: > print( > market.coin, > market.slug, > market.price_to_beat, > market.twap_window_seconds, > rotation.time_remaining, > ) > > stream.on("rotation", on_rotation) > stream.on( > "price_feed", > lambda price: print( > price.feed, price.price, price.twap_window_seconds > ), > ) > stream.on("settlement", lambda event: print(event.status, event.tx_hash)) > stream.on("error", lambda error: print(error)) > > try: > await asyncio.Event().wait() > finally: > stream.stop() > > asyncio.run(main()) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{ > Coin, PolyNodeClient, PolyNodeEvent, ShortFormInterval, ShortFormMessage, > }; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let client = PolyNodeClient::new( > std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") > )?; > let mut stream = client > .short_form(ShortFormInterval::FiveMin) > .coins(&[Coin::Btc, Coin::Eth]) > .start() > .await?; > > while let Some(message) = stream.next().await { > match message { > ShortFormMessage::Rotation(rotation) => { > for market in rotation.markets { > println!( > "{} {} {:?} {:?}", > market.coin.id(), > market.slug, > market.price_to_beat, > market.twap_window_seconds, > ); > } > } > ShortFormMessage::PriceFeed(price) => { > println!("{} {} {:?}", price.feed, price.price, price.twap_window_seconds); > } > ShortFormMessage::Event(PolyNodeEvent::Settlement(event)) => { > println!("{:?} {}", event.status, event.tx_hash); > } > ShortFormMessage::Error(error) => eprintln!("{error}"), > _ => {} > } > } > Ok(()) > } > ``` ## What rotation means Market slugs and outcome-token IDs change at every boundary. Chainlink selection is also scoped to the WebSocket connection. The managed helper therefore owns a dedicated socket and performs this sequence at each boundary: 1. close the old dedicated socket 2. discover the new market slugs and token IDs 3. connect a replacement socket 4. subscribe to `settlements` for the exact new slugs 5. subscribe to the interval's exact Chainlink TWAP window, when applicable 6. emit `rotation` with the new market metadata This reconnect is expected and necessary. Do not place unrelated subscriptions on the managed stream's dedicated connection; the helper isolates it for you. If discovery or subscription fails, the helper emits an error. Keep the error handler visible in production and restart the stream if it stops. ## Rotation payload Each discovered market includes the fields needed to connect other user-facing components: | Field | Meaning | | - | - | | `slug` / `conditionId` | current Polymarket market identifiers | | `clobTokenIds` | outcome token IDs for orderbook or trading calls | | `chainlinkFeed` | canonical feed, such as `BTC/USD` | | `twapWindowSeconds` | `30`, `60`, or `null` for the 1-hour spot/default stream | | `priceToBeat` | opening Chainlink reference when available | | `upOdds` / `downOdds` | current outcome probabilities | | `liquidity` / `volume24h` | current market metadata | | `feesEnabled` / `takerBaseFee` | fee metadata returned for the market | Python and Rust expose the same fields in `snake_case`. Rust's `RotationInfo` also exposes `twap_window_seconds` for the selected interval. ## Choose another interval > [tab] TypeScript > > ```typescript theme={null} > const fiveMinute = pn.ws.shortForm('5m'); > const fifteenMinute = pn.ws.shortForm('15m'); > const hourly = pn.ws.shortForm('1h'); > const fourHour = pn.ws.shortForm('4h'); > ``` > [tab] Python > > ```python theme={null} > five_minute = pn.ws.short_form("5m") > fifteen_minute = pn.ws.short_form("15m") > hourly = pn.ws.short_form("1h") > four_hour = pn.ws.short_form("4h") > ``` > [tab] Rust > > ```rust theme={null} > let five_minute = client.short_form(ShortFormInterval::FiveMin); > let fifteen_minute = client.short_form(ShortFormInterval::FifteenMin); > let hourly = client.short_form(ShortFormInterval::Hourly); > let four_hour = client.short_form(ShortFormInterval::FourHour); > ``` Each managed stream owns its own connection. If you need several intervals, monitor connection usage and stop streams you no longer need. ## Subscribe to TWAP prices manually Use a manual Chainlink subscription when you want price events without managed market discovery. Combine every feed and lookback needed on that socket into one subscription. > [tab] TypeScript > > ```typescript theme={null} > const prices = await pn.ws.subscribe('chainlink') > .feeds(['BTC/USD', 'ETH/USD']) > .twapWindows([30, 60]) > .send(); > > console.log(prices.priceSource, prices.twapWindows, prices.warnings); > prices.on('price_feed', (event) => { > const key = `${event.feed}:${event.twap_window_seconds}:${event.timestamp}`; > console.log(key, event.price); > }); > ``` > [tab] Python > > ```python theme={null} > prices = await ( > pn.ws.subscribe("chainlink") > .feeds(["BTC/USD", "ETH/USD"]) > .twap_windows([30, 60]) > .send() > ) > print(prices.price_source, prices.twap_windows, prices.warnings) > prices.on( > "price_feed", > lambda event: print( > event.feed, event.twap_window_seconds, event.timestamp, event.price > ), > ) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::ws::{Subscription, SubscriptionType}; > > let ack = stream.subscribe_with_ack( > Subscription::new(SubscriptionType::Chainlink) > .feeds(vec!["BTC/USD".into(), "ETH/USD".into()]) > .twap_windows(vec![30, 60]), > ).await?; > println!("{:?} {:?} {:?}", ack.price_source, ack.twap_windows, ack.warnings); > ``` On every price event, inspect `is_twap` and `twap_window_seconds`; do not infer the price type from arrival frequency. If both windows are selected, key state by feed, window, and timestamp. ## Connect the current market to the orderbook Use the rotation payload's outcome token IDs. Replace the previous token set whenever `rotation` fires: ```typescript theme={null} import { OrderbookEngine } from 'polynode-sdk'; const engine = new OrderbookEngine({ apiKey, integrity: true }); stream.on('rotation', async ({ markets }) => { const tokenIds = markets.flatMap((market) => market.clobTokenIds); await engine.subscribe(tokenIds); }); ``` See [Orderbook streaming and PN1](/sdks/orderbook) for readiness, integrity errors, and cleanup. ## Shutdown Stop every managed stream you create. This cancels its rotation timer, removes subscriptions, and closes its dedicated connection. > [tab] TypeScript > > ```typescript theme={null} > stream.stop(); > ``` > [tab] Python > > ```python theme={null} > stream.stop() > ``` > [tab] Rust > > ```rust theme={null} > stream.stop().await; > ``` # Trading and Fees Source: https://docs.polynode.dev/sdks/trading Set up a wallet, place and manage Polymarket V2 orders, and understand protocol fees, builder attribution, and optional application fees. The SDK trading modules provide a common workflow for wallet setup, CLOB credentials, approvals, order placement, cancellation, and position operations. Polymarket V2 is the default in every current Polynode SDK. For optional zero-builder attribution backed by the signing wallet, see [User-owned execution](/sdks/user-owned-execution). A platform with injected wallets should use the complete [Connect Wallet to order guide](/sdks/user-owned-web-app). Existing integrations stay on builder mode unless they opt in. > [!WARNING] > > Trading methods sign messages and can place orders or submit on-chain transactions. Start with a dedicated test wallet, confirm the token ID, price, size, and funder address, and never commit private keys or CLOB credentials. ## Install ```bash TypeScript theme={null} npm install polynode-sdk@^0.15.0 viem ``` ```bash Python theme={null} python -m pip install "polynode[trading]>=0.15.0,<0.16" ``` ```toml Rust theme={null} [dependencies] polynode = { version = "0.18.0", features = ["trading"] } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` That TypeScript command is complete for the injected-wallet user-owned flow. The private-key server-trader examples below additionally need `@polymarket/clob-client@^5.8.1`. Add `better-sqlite3` only for persistent local storage. Add `@polymarket/builder-relayer-client@0.0.10` and `@polymarket/builder-signing-sdk@^1.0.0` only for a separate shared-builder relayer integration; those optional packages are not part of the browser entry's dependency graph. > [!WARNING] > > The optional builder-relayer client currently brings legacy Axios/ethers audit > advisories into a full install. The Polynode SDK does not bundle that tree. > Keep the safer minimal user-owned install unless you intentionally operate the > separate builder flow, then pin and audit the optional peers independently. Store credentials outside source control: ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." export POLYGON_PRIVATE_KEY="0x..." ``` ## Current V2 behavior You do not need to opt into V2. These are the defaults: | SDK | Default | | - | - | | TypeScript | `exchangeVersion: 'v2'` | | Python | `ExchangeVersion.V2` | | Rust | `ExchangeVersion::V2` | V2 uses PolyUSD collateral and applies Polymarket protocol fees when an eligible taker order matches. V2 signed orders do **not** include the legacy `feeRateBps`, `nonce`, or `taker` fields. The SDK omits those fields from the V2 signature and wire payload. The explicit V1 compatibility mode is different: its signed order includes the market fee rate. When V1 is selected, the SDK fetches the current fee and refuses to sign if fee, tick-size, or negative-risk metadata cannot be resolved safely. > [!NOTE] > > Do not copy V1 fields into a V2 order. If you do not have a deliberate legacy requirement, keep the V2 default. ## Polymarket Protocol V2 markets Polymarket Protocol V2 is a separate, newer change from the V2 exchange default above: it is Polymarket's new market system for newly created markets. The versions on this page trade Protocol V2 markets with the same calls and no config change. The SDK checks each market's protocol and signs Protocol V2 orders for ExchangeV3 automatically, and the first order on a Protocol V2 market sets up the approvals it needs. Older versions keep working on current markets, but Polymarket rejects their orders on Protocol V2 markets. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2) for dates, approvals and contract addresses. ## Set up a wallet `ensureReady` / `ensure_ready` is idempotent. It discovers the wallet type, creates or loads CLOB credentials, and completes required setup. For a new wallet it can deploy contracts or submit approvals, so treat it as a state-changing operation. ```typescript TypeScript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const trader = new PolyNodeTrader({ polynodeKey: process.env.POLYNODE_API_KEY!, exchangeVersion: 'v2', // Optional: V2 is already the default }); const ready = await trader.ensureReady(process.env.POLYGON_PRIVATE_KEY!); console.log({ wallet: ready.wallet, funderAddress: ready.funderAddress, approvalsSet: ready.approvalsSet, }); ``` ```python Python theme={null} import os from polynode.trading import ExchangeVersion, PolyNodeTrader, TraderConfig trader = PolyNodeTrader(TraderConfig( polynode_key=os.environ["POLYNODE_API_KEY"], exchange_version=ExchangeVersion.V2, # Optional: already the default )) ready = await trader.ensure_ready(os.environ["POLYGON_PRIVATE_KEY"]) print({ "wallet": ready.wallet, "funder_address": ready.funder_address, "approvals_set": ready.approvals_set, }) ``` ```rust Rust theme={null} use polynode::trading::{ ExchangeVersion, PolyNodeTrader, PrivateKeySigner, TraderConfig, }; let mut trader = PolyNodeTrader::new(TraderConfig { polynode_key: std::env::var("POLYNODE_API_KEY")?, exchange_version: ExchangeVersion::V2, // Optional: already the default ..Default::default() })?; let signer = PrivateKeySigner::from_hex(&std::env::var("POLYGON_PRIVATE_KEY")?)?; let ready = trader.ensure_ready(Box::new(signer), None).await?; println!("fund this address: {}", ready.funder_address); ``` Fund the returned `funderAddress` / `funder_address`, not an address guessed from the signing key. The correct funding flow depends on the wallet type. See [Deposit wallets](/guides/deposit-wallets), [V2 details](/guides/v2-details), and [PolyUSD](/guides/polyusd). ## Place an order The following snippets place a real order when run. Replace every placeholder and validate the market first. ```typescript TypeScript theme={null} const result = await trader.order({ tokenId: process.env.POLYMARKET_TOKEN_ID!, side: 'BUY', price: 0.55, size: 10, type: 'GTC', postOnly: true, }); if (!result.success) throw new Error(result.error ?? 'Order rejected'); console.log(result.orderId); ``` ```python Python theme={null} import os from polynode.trading import OrderParams result = await trader.order(OrderParams( token_id=os.environ["POLYMARKET_TOKEN_ID"], side="BUY", price=0.55, size=10, type="GTC", post_only=True, )) if not result.success: raise RuntimeError(result.error or "Order rejected") print(result.order_id) ``` ```rust Rust theme={null} use polynode::trading::{OrderParams, OrderSide, OrderType}; let result = trader.order(OrderParams { token_id: std::env::var("POLYMARKET_TOKEN_ID")?, side: OrderSide::Buy, price: 0.55, size: 10.0, order_type: OrderType::GTC, expiration: None, post_only: true, fee_config: None, builder: None, }).await?; if !result.success { return Err(polynode::Error::Trading( result.error.unwrap_or_else(|| "order rejected".into()), )); } println!("{:?}", result.order_id); ``` Supported time-in-force values are `GTC`, `GTD`, `FOK`, and `FAK`. A V2 `GTD` expiration must include the required safety buffer; the SDK rejects an invalid value before submission. ## Cancel and inspect orders Each SDK supports: * canceling one order; * canceling all active orders; * canceling active orders for a market; * listing open orders; * checking balances and approvals; * reading the local order-attempt history. ```typescript TypeScript theme={null} const open = await trader.getOpenOrders(); if (open[0]) await trader.cancelOrder(open[0].id); ``` ```python Python theme={null} open_orders = await trader.get_open_orders() if open_orders: await trader.cancel_order(open_orders[0].id) ``` ```rust Rust theme={null} let open_orders = trader.get_open_orders(None).await?; if let Some(order) = open_orders.first() { trader.cancel_order(&order.id).await?; } ``` ## Three different fee concepts Keep these separate in your product and accounting: | Concept | What it means | How it is configured | | - | - | - | | Polymarket protocol fee | A market fee applied by Polymarket when eligible V2 liquidity matches | Not a signed V2 order field; inspect market metadata for display and budgeting | | Builder attribution | Associates eligible volume with a public builder code | `builderCode` / `builder_code`, or the per-order `builder` override | | Optional application fee | A fee your application deliberately charges through the SDK fee configuration | `feeConfig` / `fee_config`; disabled unless configured | Builder attribution does not by itself charge the user an application fee. An application fee is enabled only when you explicitly configure it. See [Fee escrow](/guides/fee-escrow) before enabling application fees. ## Builder attribution Current V2 orders use a public `bytes32` builder code. The SDK supplies Polynode's public code by default. You can provide your own code at trader level, override it for one order, or disable the default attribution. ```typescript TypeScript theme={null} const trader = new PolyNodeTrader({ polynodeKey: process.env.POLYNODE_API_KEY!, builderCode: process.env.POLYMARKET_BUILDER_CODE!, }); // Per-order override: await trader.order({ ...order, builder: anotherBuilderCode }); ``` ```python Python theme={null} trader = PolyNodeTrader(TraderConfig( polynode_key=os.environ["POLYNODE_API_KEY"], builder_code=os.environ["POLYMARKET_BUILDER_CODE"], )) # Per-order override: await trader.order(OrderParams(**order_values, builder=another_builder_code)) ``` ```rust Rust theme={null} let mut trader = PolyNodeTrader::new(TraderConfig { polynode_key: std::env::var("POLYNODE_API_KEY")?, builder_code: Some(std::env::var("POLYMARKET_BUILDER_CODE")?), ..Default::default() })?; // `OrderParams.builder` overrides the config for one order. ``` Generate and manage builder credentials in your Polymarket builder settings. Builder credentials are secrets; the public builder code is not. ## Position operations The trading modules also expose split, merge, and negative-risk conversion builders or helpers. These are on-chain operations and are distinct from placing a CLOB order. Review [Position management](/guides/position-management) before signing or submitting one. ## Cleanup Close the trader to flush and release its local storage: ```typescript TypeScript theme={null} trader.close(); ``` ```python Python theme={null} trader.close() ``` ```rust Rust theme={null} trader.close(); ``` ## Next steps > [card] [Find a token with V3](/sdks/v3-api) > > Discover markets and token IDs before constructing an order. > [card] [Stream a verified book](/sdks/orderbook) > > Use PN1 integrity before making price-sensitive decisions. > [card] [V2 migration details](/guides/v2-migration) > > Understand the current exchange and payload differences. > [card] [Trading errors](/sdks/ts/errors) > > Handle rejected orders and transport failures explicitly. # TypeScript Configuration Source: https://docs.polynode.dev/sdks/ts/config Configure PolyNode TypeScript endpoints, timeouts, reconnects, replay buffers, and integrity behavior. The default public endpoints are already configured. Override them only when PolyNode gives you a different endpoint. ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey, baseUrl: 'https://api.polynode.dev', v3BaseUrl: 'https://api.polynode.dev', wsUrl: 'wss://ws.polynode.dev/ws', obUrl: 'wss://ob.polynode.dev/ws', rpcUrl: 'https://rpc.polynode.dev', timeout: 10_000, }); ``` Configure a stream before its first connection: ```typescript theme={null} const events = pn.configureWs({ compress: true, autoReconnect: true, maxReconnectAttempts: Infinity, reconnectBaseDelay: 1_000, reconnectMaxDelay: 30_000, subscribeTimeoutMs: 30_000, subscriptionQueueCapacity: 4_096, dedupeCapacity: 4_096, replayOverlapMs: 1, }); const orderbook = pn.configureOrderbook({ compress: true, autoReconnect: true, integrity: true, allowStaleReads: false, }); const perps = pn.configurePerps({ autoReconnect: true, operationTimeoutMs: 30_000, queueCapacity: 4_096, }); ``` Event and perps queues are bounded. Choose capacities for your processing rate, observe overflow callbacks, and move slow work away from message handlers. A larger buffer delays loss but is not a substitute for sustained consumer throughput. API keys belong in server-side environment variables or a secret manager, never a browser bundle. # TypeScript Errors Source: https://docs.polynode.dev/sdks/ts/errors Handle HTTP, WebSocket, reconnect, overflow, and orderbook-integrity failures in TypeScript. ```typescript theme={null} import { ApiError, OrderbookIntegrityError, PolyNodeError, WsError, } from 'polynode-sdk'; try { await pn.v3.stats(); } catch (error) { if (error instanceof ApiError) { console.error({ status: error.status, code: error.code, hint: error.hint, requestId: error.requestId, retryAfter: error.retryAfter, rateLimit: error.rateLimit, method: error.safeMethod, url: error.safeUrl, }); } else if (error instanceof WsError) { console.error(error.code, error.message); } else if (error instanceof OrderbookIntegrityError) { console.error(error.code, error.token, error.message); } else if (error instanceof PolyNodeError) { console.error(error.code, error.message); } throw error; } ``` Safe V3 reads retry transient transport failures and retryable statuses. State-changing V3 calls are never retried automatically. After a mutation timeout, check whether the resource changed before submitting it again. WebSocket reconnect and data-quality signals are separate from thrown errors: * `pn.ws.onReplay(...)` reports best-effort settlement replay; * `sub.onOverflow(...)` reports local event loss; * `perps.onReconnect(...)` reports a possible perps gap; * `perps.onOverflow(...)` reports local perps loss; * `integrity_error` moves an affected PN1 book away from `ready` until a fresh anchor succeeds. Log request IDs and redacted safe URLs, but never log API keys, private keys, builder credentials, CLOB secrets, or signed payloads. # TypeScript PN1 Orderbook Source: https://docs.polynode.dev/sdks/ts/orderbook Maintain exact local orderbooks with optional PN1 sequence and checksum verification. Use `OrderbookEngine` when your application needs a current local book. Enable PN1 integrity for price-sensitive decisions so gaps and checksum mismatches fail closed. ```typescript theme={null} import { OrderbookEngine } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; const tokenId = process.env.POLYMARKET_TOKEN_ID; if (!apiKey || !tokenId) throw new Error('Set POLYNODE_API_KEY and POLYMARKET_TOKEN_ID'); const engine = new OrderbookEngine({ apiKey, integrity: true, allowStaleReads: false, }); engine.on('integrity_error', (error) => { console.error(error.code, error.token, error.message); }); engine.on('ready', () => { console.log({ bestBid: engine.bestBid(tokenId), bestAsk: engine.bestAsk(tokenId), midpoint: engine.midpoint(tokenId), spread: engine.spread(tokenId), }); }); await engine.subscribe([tokenId]); ``` PN1 keeps orderbook prices and sizes as exact decimal strings. It validates the full-snapshot anchor, then validates sequence continuity and a deterministic checksum on each applicable update. The managed state moves through `initializing`, `ready`, `stale`, `resyncing`, and `failed`. With `allowStaleReads: false`, reads are unavailable until a verified anchor is ready and become unavailable again after a disconnect or integrity failure. The client requests a fresh anchor before returning to `ready`. > [!WARNING] > > Wildcard `"*"` subscriptions are intentionally unavailable in integrity mode. Subscribe with explicit token IDs, slugs, or condition IDs so every verified book has a bounded identity and anchor. ## Filtered views ```typescript theme={null} const view = engine.view([tokenId]); view.on('update', (update) => console.log(update.asset_id)); view.on('trade', (trade) => console.log(trade.price, trade.size)); console.log(view.book(tokenId)); view.destroy(); ``` ## Raw messages Use `pn.configureOrderbook({ integrity: true })` when you want protocol messages without managed local state: ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const pn = new PolyNode({ apiKey }); const ob = pn.configureOrderbook({ integrity: true }); ob.on('snapshot', (snapshot) => console.log(snapshot.integrity)); ob.on('resyncing', (message) => console.warn(message.markets)); ob.on('unknown', (message) => console.log(message.raw)); await ob.subscribe([tokenId]); ``` ## Cleanup ```typescript theme={null} engine.close(); // Or, for the raw client: ob.disconnect(); ``` See the [shared orderbook guide](/sdks/orderbook) and [PN1 protocol reference](/orderbook/integrity). # TypeScript SDK Source: https://docs.polynode.dev/sdks/ts/overview Install polynode-sdk 0.14 and make a first V3 request from Node.js. `polynode-sdk` is the Node.js client for Polynode's V3 API, event stream, PN1 orderbook, perps stream, short-form markets, and trading helpers. ## Install ```bash theme={null} npm install polynode-sdk@^0.15.0 ws ``` Node.js 18 or newer is required. The package supports ESM imports and CommonJS runtime loading. The examples use ESM. ```json package.json theme={null} { "type": "module" } ``` Keep your key server-side: ```bash theme={null} export POLYNODE_API_KEY="pn_live_..." ``` ## First request ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); const stats = await pn.v3.stats(); console.log(stats); ``` ## Client surfaces | Entry point | Use it for | | - | - | | `pn.v3` | Complete V3 API registry and typed convenience methods | | `pn.ws` | Settlements, confirmations, Chainlink prices, combos, and other events | | `pn.orderbook` | Raw orderbook messages | | `new OrderbookEngine(...)` | Managed local books and PN1 integrity | | `pn.perps` | Managed V3 perps WebSocket | | `pn.ws.shortForm(...)` | Rotating 5m, 15m, 1h, and 4h crypto markets | | `new PolyNodeTrader(...)` | Current V2 order and position operations | Each WebSocket is independent. Close the subscription or client you opened when your process shuts down. > [card] [V3 API](/sdks/ts/v3-data) > > Call any registered V3 operation. > [card] [Settlement stream](/sdks/ts/websocket) > > Subscribe with replay and overflow visibility. > [card] [Short-form and TWAP](/sdks/ts/short-form) > > Rotate with the correct Chainlink window. > [card] [PN1 orderbook](/sdks/ts/orderbook) > > Maintain fail-closed local state. > [card] [Perps stream](/sdks/ts/perps) > > Subscribe to tickers, books, trades, and klines. > [card] [Trading and fees](/sdks/ts/trading) > > Use the current V2 defaults safely. > [card] [Connect Wallet to order](/sdks/user-owned-web-app) > > Build the complete user-owned browser flow. # TypeScript Perps Stream Source: https://docs.polynode.dev/sdks/ts/perps Subscribe to managed perps tickers, BBO, full books, trades, statistics, and klines. The V3 perps WebSocket is separate from the event and prediction-market orderbook sockets. ```typescript theme={null} import { PolyNode, perpsChannels } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); const perps = pn.configurePerps({ queueCapacity: 4096 }); perps.onReconnect((notice) => console.warn('gap possible', notice)); perps.onOverflow((notice) => console.error('local overflow', notice)); const ack = await perps.subscribe([ perpsChannels.tickers, perpsChannels.bbo('BTC-USD'), perpsChannels.book('BTC-USD'), perpsChannels.trades('BTC-USD'), perpsChannels.klines('BTC-USD', '1m'), ]); if (ack.rejected.length) console.warn('rejected channels', ack.rejected); perps.onMessage((message) => { if (message.type === 'event') { console.log(message.channel, message.data); } }); ``` One subscribe request can be partially accepted. Always inspect `ack.channels` and `ack.rejected` rather than assuming every requested channel is active. Every `perps_book` event is a complete replacement for that instrument's cached book, not an incremental patch. `perps.book('BTC-USD')` returns the latest managed copy, or `null` until the first book event arrives. A successful acknowledgement confirms the channel, not book readiness; use the [V3 perps orderbook](/perps/market-data/book) when startup needs immediate state. The client reconnects and resubscribes after non-terminal disconnects, but the stream does not promise replay. A `reconnect` notice has `gap_possible: true`; backfill through V3 REST if completeness matters. Authentication (`4401`) and connection-limit (`4429`) closes are terminal until the caller changes the failing condition. ```typescript theme={null} perps.disconnect(); ``` See the [shared perps guide](/sdks/perps) for channel definitions, lag behavior, and lifecycle details. # TypeScript REST Compatibility Source: https://docs.polynode.dev/sdks/ts/rest-api Use the current V3 client and understand the retained top-level V1/V2 methods. Use `pn.v3` for new data integrations. It has the complete current route registry. The top-level `PolyNode` methods remain available for existing V1/V2 integrations and focused helpers such as health, legacy market search, and RPC. ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); // Current data surface const stats = await pn.v3.stats(); // Retained compatibility helpers const health = await pn.healthz(); const results = await pn.searchEvents('bitcoin', { limit: 5 }); const firstConditionId = results.events[0]?.markets[0]?.conditionId ?? null; console.log({ stats, health, resultCount: results.events.length, firstConditionId }); ``` Nested compatibility-search markets can omit `conditionId`. Treat it as optional and use a token ID or slug when your workflow requires an identifier. Do not interpret the compatibility method list as the complete product API. For wallets, positions, grouped trades, combos, builders, credits, identities, profiles, webhooks, and perps, use [TypeScript V3](/sdks/ts/v3-data). The generic JSON-RPC helper remains available as `pn.rpc(method, params)`. It is an HTTP request helper and does not implement `eth_subscribe`; use the [RPC guide](/sdks/rpc) for examples. # TypeScript Short-Form and TWAP Source: https://docs.polynode.dev/sdks/ts/short-form Rotate TypeScript subscriptions across short-form crypto markets with the correct Chainlink TWAP window. Polymarket's short-form crypto markets change identifiers at fixed boundaries. The managed stream discovers the active market, chooses the correct Chainlink selection, and replaces the subscription when the boundary arrives. > [!WARNING] > > Starting **August 7, 2026 at 00:00 UTC**, use a 30-second TWAP for 5-minute markets and a 60-second TWAP for 15-minute and 4-hour markets. One-hour markets continue to use the default spot feed. | Market interval | Chainlink selection | | - | - | | `5m` | `30` seconds | | `15m` | `60` seconds | | `1h` | default spot feed | | `4h` | `60` seconds | ## Managed rotation ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); const stream = pn.ws.shortForm('5m', { coins: ['btc', 'eth', 'sol'], }); stream.on('rotation', (rotation) => { console.log({ windowStart: rotation.windowStart, windowEnd: rotation.windowEnd, markets: rotation.markets.map((market) => ({ coin: market.coin, slug: market.slug, feed: market.chainlinkFeed, twapWindowSeconds: market.twapWindowSeconds, priceToBeat: market.priceToBeat, })), }); }); stream.on('settlement', (event) => console.log(event)); stream.on('error', (error) => console.error(error)); ``` At every boundary the helper closes its dedicated socket, opens a new one, and subscribes to the new market identifiers and price selection. Consumers do not manually calculate the next slug, but they should handle a normal connection transition around rotation. Supported assets are BTC, ETH, SOL, XRP, DOGE, HYPE, and BNB. ## Explicit Chainlink selection Use one Chainlink subscription per event socket. Combine feeds and windows in the same subscription when you need several: ```typescript theme={null} const prices = await pn.ws .subscribe('chainlink') .feeds(['BTC/USD', 'ETH/USD']) .twapWindows([30, 60]) .send(); console.log({ source: prices.priceSource, windows: prices.twapWindows }); prices.on('price_feed', (event) => { console.log(event.feed, event.price, event.is_twap, event.twap_window_seconds); }); ``` Do not create two competing Chainlink selections on one `PolyNodeWS`. Use another client connection if the selections must be isolated. ## Cleanup ```typescript theme={null} stream.stop(); pn.ws.disconnect(); ``` Read the [shared short-form guide](/sdks/short-form) for market fields, manual mode, and orderbook integration. # TypeScript Trading and Fees Source: https://docs.polynode.dev/sdks/ts/trading Use the TypeScript V2 trading defaults and keep protocol fees, builder attribution, and application fees distinct. Install only the dependencies for the execution model you use. The injected wallet/user-owned flow needs only: For optional zero-builder attribution backed by the signing wallet, see [User-owned execution](/sdks/user-owned-execution). For an injected-wallet application, follow [Connect Wallet to order](/sdks/user-owned-web-app). ```bash theme={null} npm install polynode-sdk@^0.15.0 viem ``` For a server-signer trader, add the CLOB client and SQLite only when that process uses them: ```bash theme={null} npm install @polymarket/clob-client@^5.8.1 better-sqlite3 ``` Only a separate shared-builder relayer integration needs these peers: ```bash theme={null} npm install @polymarket/builder-relayer-client@0.0.10 \ @polymarket/builder-signing-sdk@^1.0.0 ``` > [!WARNING] > > The optional official Polymarket relayer client currently brings legacy > Axios/ethers audit advisories into a full trading install. Polynode SDK 0.14.2 > does not bundle that dependency tree: its only direct runtime dependency is > `viem`. Pin the relayer client to the SDK's declared peer version, keep relayer > destinations fixed, and review upstream updates before changing that pin. > [!NOTE] > > This version also trades Polymarket Protocol V2 markets, a separate and newer change from the V2 exchange default below, with the same calls and no config change. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). Polymarket V2 is the default. You do not need to set `exchangeVersion`, but setting it explicitly can make a migration easier to review: ```typescript theme={null} import { PolyNodeTrader } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; const privateKey = process.env.POLYGON_PRIVATE_KEY; if (!apiKey || !privateKey) throw new Error('Set the required environment variables'); const trader = new PolyNodeTrader({ polynodeKey: apiKey, exchangeVersion: 'v2', builderCode: process.env.POLYMARKET_BUILDER_CODE, }); const ready = await trader.ensureReady(privateKey); console.log('funder address', ready.funderAddress); ``` `ensureReady()` can deploy or approve wallet contracts and is state-changing for a new wallet. After the returned funder address is funded, `trader.order(...)` places a real order. V2 fees are applied by Polymarket at match time. Do not add legacy `feeRateBps`, `nonce`, or `taker` fields to a V2 signed order. A builder code attributes eligible volume; it does not itself charge an application fee. `feeConfig` is a separate, optional application-fee feature and remains disabled unless you configure it. ```typescript theme={null} try { const result = await trader.order({ tokenId: process.env.POLYMARKET_TOKEN_ID!, side: 'BUY', price: 0.55, size: 10, type: 'GTC', postOnly: true, }); if (!result.success) throw new Error(result.error ?? 'Order rejected'); console.log(result.orderId); } finally { trader.close(); } ``` Read [Trading and fees](/sdks/trading) before running state-changing examples. It covers funding, cancellations, builder overrides, current V2 fee behavior, position operations, and cleanup. # TypeScript Types Source: https://docs.polynode.dev/sdks/ts/types Narrow event unions, preserve unknown additive messages, and keep exact numeric wire values. Event messages use a discriminated `event_type` union: ```typescript theme={null} import type { PolyNodeEvent } from 'polynode-sdk'; function handleEvent(event: PolyNodeEvent): void { switch (event.event_type) { case 'settlement': console.log(event.tx_hash, event.taker_size); break; case 'status_update': console.log(event.tx_hash, event.block_number); break; case 'price_feed': console.log(event.feed, event.price, event.twap_window_seconds); break; case 'unknown': console.log(event.wire_event_type, event.raw); break; default: console.log(event.event_type); } } ``` The union includes fills, settlements, trades, status updates, blocks, position changes, deposits, splits, merges, conversions, redemptions, combo execution/status/lifecycle/approval events, oracle events, Chainlink price feeds, and an `unknown` variant. Unknown additive events and fields are preserved so a compatible server addition does not require dropping the payload. Treat `unknown` as observable data, not as a fatal protocol error. Orderbook `price` and `size` values and perps prices/quantities are exact decimal strings. Keep them as strings or convert with a decimal library; do not use JavaScript `number` for exact accounting. V3 generic calls return wire JSON. Supply a type argument only when your application owns and validates the corresponding schema: ```typescript theme={null} type Stats = { trades: string; wallets: string }; const stats = await pn.v3.execute('GET /v3/stats'); ``` See [event reference](/websocket/events/settlement), [orderbook protocol](/orderbook/overview), and [perps channels](/perps/websocket/channels) for wire fields. # TypeScript V3 API Source: https://docs.polynode.dev/sdks/ts/v3-data Use typed TypeScript helpers or execute any of the 120 registered V3 operations. TypeScript 0.14.2 exposes the complete shared V3 operation registry at `pn.v3.operations`. Typed helpers cover common reads; `execute()` covers every registered route, including combos, credits, webhooks, and perps. ## Discover the registry ```typescript theme={null} import { PolyNode, V3_OPERATION_COUNT } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); console.log(V3_OPERATION_COUNT); // 120 in 0.14.2 for (const operation of pn.v3.operations) { console.log(operation.method, operation.path, operation.domain); } ``` ## Typed reads ```typescript theme={null} const address = '0xa9857c7bcb9bcfafd2c132ab053f34f678610058'; const summary = await pn.v3.wallet(address); const positions = await pn.v3.walletPositions(address, { status: 'open', limit: 25, }); const trades = await pn.v3.walletTrades(address, { groupBy: 'order_hash', sortBy: 'order_hash', limit: 50, }); console.log({ summary, positions, trades }); ``` ## Any registered route Use the exact operation name from the registry. Path parameters and query parameters are encoded separately: ```typescript theme={null} const comboSummary = await pn.v3.execute( 'GET /v3/wallets/{address}/combos/summary', { pathParams: { address } }, ); const globalTrades = await pn.v3.execute('GET /v3/trades', { query: { limit: 50, sort_by: 'order_hash', group_by: 'order_hash', }, }); ``` ## Newer Builder analytics routes The Builder trader leaderboard and daily-activity routes postdate the 120-operation registry in TypeScript 0.14.2. Use the same API key with a direct authenticated `fetch` until a later SDK release explicitly registers them. ```typescript theme={null} const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const builder = 'BetMoar'; const url = new URL( `https://api.polynode.dev/v3/builders/${encodeURIComponent(builder)}/leaderboard`, ); url.search = new URLSearchParams({ period: '30D', // query enums are case-insensitive sort: 'PNL', order: 'DESC', limit: '100', offset: '0', }).toString(); const response = await fetch(url, { headers: { 'x-api-key': apiKey }, }); if (!response.ok) throw new Error(`Builder leaderboard failed: ${response.status}`); const leaderboard = await response.json(); console.log(leaderboard.period, leaderboard.sort, leaderboard.data.length); ``` For All-Time P\&L, use the [documented signed-cursor loop](/data/builders/trader-leaderboard#walk-five-all-time-pages-without-repeats): start with `pagination=cursor`, then carry `next_cursor`, `as_of`, and `pnl_as_of` while incrementing `offset` by the returned row count. The page cap is 100 and the supported traversal ends at rank 500. ## Perps REST data ```typescript theme={null} const ticker = await pn.v3.execute( 'GET /v3/perps/tickers/{instrument}', { pathParams: { instrument: 'BTC-USD' } }, ); console.log(ticker); ``` ## Retry and error behavior Safe reads retry transient failures and respect `Retry-After` within the configured ceiling. Mutations are never retried automatically. A mutation timeout can have an ambiguous result, so inspect the resource before retrying it. ```typescript theme={null} import { ApiError } from 'polynode-sdk'; try { await pn.v3.stats(); } catch (error) { if (error instanceof ApiError) { console.error({ status: error.status, code: error.code, requestId: error.requestId, retryAfter: error.retryAfter, url: error.safeUrl, }); } throw error; } ``` Keep exact decimals and large integers in their wire representation. See the [complete V3 guide](/sdks/v3-api) and [V3 endpoint reference](/data/overview). # TypeScript Settlement Stream Source: https://docs.polynode.dev/sdks/ts/websocket Consume acknowledged settlement subscriptions with reconnect replay, deduplication, and overflow visibility. The event WebSocket carries pending settlements, confirmation updates, Chainlink prices, combo lifecycle events, wallet activity, and other product events. `send()` resolves only after the server acknowledges the subscription. ## Subscribe ```typescript theme={null} import { PolyNode } from 'polynode-sdk'; const apiKey = process.env.POLYNODE_API_KEY; if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); const pn = new PolyNode({ apiKey }); const sub = await pn.ws .subscribe('settlements') .status('all') .minSize(100) .send(); console.log({ subscriptionId: sub.id, warnings: sub.warnings, }); sub.on('settlement', (event) => { console.log('pending', event.tx_hash, event.taker_size); }); sub.on('status_update', (event) => { console.log('confirmed', event.tx_hash, event.block_number); }); sub.on('*', (event) => { if (event.event_type === 'unknown') { console.log('new event type', event.wire_event_type, event.raw); } }); sub.onOverflow((notice) => { console.error('consumer fell behind', notice); }); pn.ws.onReplay((notice) => { console.warn('reconnect replay', notice); }); ``` ## Presets and filters Current presets are `settlements`, `trades`, `prices`, `dome`, `fills`, `combos`, `redemptions`, `redemption`, `deposits`, `blocks`, `wallets`, `markets`, `large_trades`, `global`, `oracle`, and `chainlink`. Builder filters include wallets, tokens, market IDs, slugs, condition IDs, side, direction, status, size bounds, event types, initial snapshot count, reconnect `since`, Chainlink feeds and TWAP windows, combo and leg IDs, event IDs, module IDs, and action. ```typescript theme={null} const fills = await pn.ws .subscribe('fills') .wallets(['0x...']) .conditionIds(['0x...']) .since(Date.now() - 30_000) .send(); ``` ## Reconnect behavior When the socket reconnects, the SDK resubscribes with a cursor based on the latest accepted timestamp, requests a small overlap, and deduplicates the overlap. This is best-effort replay within the service's retained history; it is not an unlimited delivery guarantee. Treat `notice.guaranteed` as `false` and backfill through REST if your application requires durable completeness. The async-iterator queue is bounded. If the consumer cannot keep up, `onOverflow` reports dropped events rather than hiding the loss. Short-form rotation is different: it deliberately closes its dedicated socket at each market boundary and reconnects to subscribe to the next market and Chainlink selection. See [TypeScript short-form](/sdks/ts/short-form). ## Cleanup ```typescript theme={null} sub.unsubscribe(); pn.ws.disconnect(); ``` See the [shared settlement guide](/sdks/websocket-streaming) for acknowledgement fields, replay semantics, and event handling patterns. # User-owned execution Source: https://docs.polynode.dev/sdks/user-owned-execution Use wallet-scoped authorization with zero builder attribution and no shared builder relayer allowance. User-owned execution is an optional trading mode for platforms whose users should operate with credentials bound to their own signing wallets. Orders carry zero builder attribution, and gasless wallet operations do not consume the platform's shared builder relayer allowance. > [!NOTE] > > Use TypeScript `polynode-sdk >= 0.14.2`, Python `polynode >= 0.14.1`, or Rust > `polynode >= 0.17.1` with its `trading` feature. Wallet authorization requires > an eligible paid Polynode plan and a valid `pn_live_...` API key. It is included > in the supported SDK flow; there is no separate add-on or additional service > URL to configure. Builder mode remains the default. Existing applications do not change until they explicitly select `user_owned`. ## What changes | | `builder` (default) | `user_owned` | | - | - | - | | Order attribution | Configured builder code | Always zero | | Gasless authorization | Builder path | Credential owned by the signing wallet | | Shared builder relayer allowance | Used by eligible operations | Not used | | Builder credentials | Supported | Rejected | | Positive Polynode application fee | Optional | Rejected | | First-use ownership signature | Existing builder flow | Required per signing wallet | User-owned mode removes the shared builder allowance from these operations. It does not remove wallet balances, market rules, order API limits, or ordinary rate limits, and it should not be presented as universally unlimited trading. > [!WARNING] > > Choose the execution mode before an operation begins. Never submit in builder > mode, catch a limit or timeout, and silently replay the same intent as > user-owned. Ask the user to opt in and complete wallet authorization first. ## Which integration should I use? > [card] [Web application](/sdks/user-owned-web-app) > > Connect an injected wallet, authorize it, choose browser memory or an > encrypted backend vault, and place an actual user-owned order. > [card] Service signer > > Keep using `ensureReady` / `ensure_ready` with your HSM, MPC wallet, Privy > server wallet, or controlled private-key signer. For a normal multi-user platform, use the [complete web-app guide](/sdks/user-owned-web-app). It includes the exact Connect Wallet UX, sensitive-value table, same-origin routes, versioned vault bundle, browser signing request, atomic one-time storage, three backend SDK examples, canonical pre-submit order identity, exact-hash timeout reconciliation, and security checklist. ## Credential meanings User-owned execution uses distinct credentials for distinct purposes: | Credential | Scope | What it can do | Where to keep it | | - | - | - | - | | Polynode API key | Platform | Access eligible SDK services | Backend environment or secret manager only | | Wallet-owned relayer credential | One controlling EOA | Authorize gasless activity for that wallet | Encrypted backend vault; optional current-tab memory | | Order API key, secret, and passphrase | One trading identity | Authenticate order and account requests | Encrypted backend vault; optional current-tab memory | | Wallet signer | User or controlled service wallet | Sign ownership messages, orders, and wallet actions | Wallet, HSM, or MPC system; never a Polynode credential store | The wallet-owned relayer credential is not a private key and cannot sign an order or transfer funds by itself. It is still sensitive. Never log it, commit it, put it in a URL, or share it across wallets. Treat the controlling EOA as the isolation key. One user must never inherit another user's trader, challenge, wallet-owned credential, order credentials, prepared order, or result. ## Supported account types * **Deposit wallet (`3`)** is the default for a new V2 user-owned browser or service-signer setup. The controlling EOA signs; the deposit wallet holds collateral and positions. * **Existing Safe (`2`)** remains supported when it is the account identity already associated with that user. Do not switch an existing user to a different deterministic account merely because both addresses exist. * **EOA (`0`)** can place orders directly. Initial approvals are on-chain transactions and require gas from that EOA. * **Legacy proxy/Magic (`1`)** is rejected in user-owned mode. Gasless split, merge, wrap, and unwrap operations require the appropriate EOA-controlled smart-wallet account. A plain EOA is never silently routed through another derived wallet. Readiness deploys or verifies the selected account and its permissions. It does not create collateral. Fund the returned funder address before a BUY. ## Service-signer setup Use this model when your existing platform signer can produce both personal-message and EIP-712 signatures. The SDK obtains the wallet-scoped authorization during readiness and keeps it in memory. Save the returned credential in your own encrypted store if the process must restore it later. > [tab] TypeScript > > ```typescript theme={null} > import { PolyNodeTrader } from 'polynode-sdk'; > > const signer = process.env.POLYGON_PRIVATE_KEY; > if (!signer) throw new Error('Set POLYGON_PRIVATE_KEY'); > > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > exchangeVersion: 'v2', > }); > > const status = await trader.ensureReady(signer); > console.log(status.wallet); > console.log(status.funderAddress); > console.log(status.userRelayerAuthorized); // true > > const result = await trader.order({ > tokenId: '...', > side: 'BUY', > price: 0.50, > size: 5, > type: 'GTC', > postOnly: true, > }); > > trader.close(); > ``` > > Use `authorizeUserOwnedExecution(signer)` when you need only the authorization > result instead of full readiness. > [tab] Python > > ```python theme={null} > import os > from polynode.trading import ( > ExecutionMode, > OrderParams, > PolyNodeTrader, > TraderConfig, > ) > > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > )) > > status = await trader.ensure_ready(os.environ["POLYGON_PRIVATE_KEY"]) > print(status.wallet) > print(status.funder_address) > print(status.user_relayer_authorized) # True > > result = await trader.order(OrderParams( > token_id="...", > side="BUY", > price=0.50, > size=5, > type="GTC", > post_only=True, > )) > > trader.close() > ``` > > Use `authorize_user_owned_execution(signer)` when you need only the > authorization result. A caller-controlled `RouterSigner` may implement async > `get_address()`, `sign_message()`, and `sign_typed_data()` instead of exposing > a raw private key. > [tab] Rust > > ```rust,no_run theme={null} > use polynode::trading::{ > ExecutionMode, OrderParams, OrderSide, PolyNodeTrader, PrivateKeySigner, > TraderConfig, > }; > > # async fn example() -> polynode::Result<()> { > let signer = PrivateKeySigner::from_hex( > &std::env::var("POLYGON_PRIVATE_KEY").unwrap(), > )?; > let mut trader = PolyNodeTrader::new(TraderConfig { > polynode_key: std::env::var("POLYNODE_API_KEY").unwrap(), > execution_mode: ExecutionMode::UserOwned, > ..Default::default() > })?; > > let status = trader.ensure_ready(Box::new(signer), None).await?; > assert!(status.user_relayer_authorized); > > let result = trader.order(OrderParams { > token_id: "...".into(), > side: OrderSide::Buy, > price: 0.50, > size: 5.0, > post_only: true, > ..Default::default() > }).await?; > > trader.close(); > # Ok(()) > # } > ``` > > Use `authorize_user_owned_execution(&signer)` when you need only the > authorization result. A custom `TradingSigner` can delegate signing to an HSM > or MPC wallet. ## Restore a wallet-owned credential For a returning service signer, load only the credential saved for the active wallet and pass it in the trader configuration. The SDK revalidates its owner before any user-owned operation. > [tab] TypeScript > > ```typescript theme={null} > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > userRelayerCredentials: encryptedVaultRecord.userRelayerCredentials, > }); > ``` > [tab] Python > > ```python theme={null} > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > user_relayer_credentials=encrypted_vault_record.user_relayer_credentials, > )) > ``` > [tab] Rust > > ```rust theme={null} > let trader = PolyNodeTrader::new(TraderConfig { > polynode_key, > execution_mode: ExecutionMode::UserOwned, > user_relayer_credentials: Some(encrypted_vault_record.user_relayer_credentials), > ..Default::default() > })?; > ``` The wallet-owned credential alone does not restore order API credentials or a signer. Restore all three from the same wallet record or use the versioned bundle flow in the web-app guide. ## Order and position behavior User-owned mode enforces these invariants before signing or submission: * V2 order builder attribution is exactly zero. * Builder credentials and builder authentication are absent. * A positive Polynode fee configuration is rejected. * The relayer credential owner, controlling EOA, funder, account type, and active order credentials must describe one wallet identity. * There is no automatic transport or attribution fallback. `split`, `merge`, `convert`, wrap, and unwrap retain their wallet-specific requirements. See [Trading and fees](/sdks/trading) for funding and position methods. Use the [web-app guide](/sdks/user-owned-web-app) when the user's injected wallet signs an order while your backend retains credentials. Orders on Polymarket Protocol V2 markets, a separate and newer change from the V2 exchange, keep these invariants and need TypeScript `polynode-sdk` 0.15.0, Python `polynode` 0.15.1, or Rust `polynode` 0.18.0 or newer. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ## Network path User-owned order traffic uses the SDK's direct transport by default. Approved integrations may explicitly choose Polynode regional egress: | SDK | Explicit setting | | - | - | | TypeScript | `userOwnedClobTransport: 'polynode_proxy'` | | Python | `user_owned_clob_transport=UserOwnedClobTransport.PROXY` | | Rust | `user_owned_clob_transport: UserOwnedClobTransport::PolynodeProxy` | The selected path is fixed for each request and never falls back automatically. Regional egress changes the network path only; it does not add builder attribution or wallet custody. ## Security checklist 1. Enable user-owned mode only after the user explicitly opts in. 2. Keep the Polynode API key on the backend. 3. Bind every credential and prepared operation to one expected controlling EOA. 4. Keep wallet-owned and order API credentials in an encrypted per-wallet vault, or explicitly accept the browser-memory risks. 5. Never log challenges, credentials, API secrets, passphrases, or signatures. 6. Do not configure builder credentials, nonzero builder attribution, or a positive Polynode fee on this trader. 7. Confirm the returned account type and funder before funding it. 8. Reconcile an ambiguous order result instead of retrying a signed intent. 9. Close traders and browser sessions when their request, worker job, or login session ends. ## Common errors | Error | Meaning | | - | - | | `invalid or missing X-Polynode-Key` / HTTP 401 | The backend did not send a valid current Polynode API key. Check its environment value; never move it to the frontend. If that key works on normal API calls but this error persists, contact Polynode support to check key synchronization for wallet authorization. | | HTTP 403 during wallet authorization | The key or plan is not eligible for user-owned authorization. Use an eligible paid plan; no separate add-on is required. | | `builder credentials are forbidden` | Remove builder credentials from this trader. | | `builderCode must be null or zero` | Remove the builder override. User-owned mode forces zero attribution. | | `credential does not belong to the signing wallet` | Load the credential stored for the active EOA, not another user. | | `does not support legacy POLY_PROXY/Magic wallets` | Keep that account on its supported path; user-owned mode accepts EOA, existing Safe, and deposit-wallet identities. | | `fee ... unavailable in user_owned mode` | Remove the positive Polynode fee configuration. | | `insufficient ... collateral` | Fund the returned funder address, then create a new order request. | | `call ensureReady() first` | Complete wallet authorization and readiness before the operation. | # Web app: connect wallet to an order Source: https://docs.polynode.dev/sdks/user-owned-web-app Build a secure connect-wallet flow that ends with a zero-attribution user-owned order. This guide takes a platform from **Connect wallet** through the first actual user-owned order. It shows what belongs in the browser, what stays on your backend, how to retain credentials, and how to support more than one user without mixing their state. > [!NOTE] > > Use TypeScript `polynode-sdk >= 0.14.2`, Python `polynode >= 0.14.1`, or Rust > `polynode >= 0.17.1` with its `trading` feature. Wallet authorization requires > an eligible paid Polynode plan and a valid `pn_live_...` API key. It is not a > separate add-on and does not require another service URL. Orders on > [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2) need > TypeScript `polynode-sdk` 0.15.0, Python `polynode` 0.15.1, or Rust `polynode` 0.18.0 or newer, in both the browser and the backend. User-owned mode removes your platform's shared builder relayer allowance from these operations by using credentials bound to each signing wallet. Orders carry zero builder attribution. This is not a promise of unlimited order throughput: wallet balances, market rules, order API limits, and ordinary rate limits still apply. ## What the user sees **1. Connect the wallet on Polygon** Your application reads the connected EOA and refuses to continue on the wrong chain. **2. Enable user-owned execution** The wallet signs one short-lived ownership message. Your platform never receives a private key or seed phrase. **3. Finish wallet readiness** For a fresh default deposit wallet, deployment itself requires no user signature. The wallet then signs one EIP-712 approval batch containing all four base-order permission calls and one EIP-712 `ClobAuth` request that creates or derives its order API credentials. **4. Fund the selected trading account** Readiness creates no collateral. If USDC.e must be converted to pUSD, the default deposit-wallet flow asks for one additional EIP-712 batch signature. A separate onramp or transfer can have its own prompts outside the SDK. **5. Confirm the order** Your UI displays the SDK's exact order preview. The wallet signs the exact EIP-712 request produced for that order. **6. Show the result** Your application displays the accepted order ID or a clear failure. A timeout is reconciled as an ambiguous result, never retried blindly. ### Wallet prompt count For the default `POLY_1271` deposit-wallet path, a genuinely fresh wallet sees three setup signatures. Its first order adds one more signature when pUSD is already funded. A returning wallet whose credentials were retained in the recommended encrypted vault has no setup signatures and signs only each exact order. | Action | Fresh default wallet | Returning wallet with vaulted credentials | What it authorizes | | - | -: | -: | - | | Connect wallet | No cryptographic signature | No cryptographic signature | Lets the application read the selected account; the wallet may still show a connection confirmation | | Enable user-owned execution | 1 `personal_sign` | 0 | One short-lived ownership challenge used to issue the wallet-bound relayer credential | | Deploy the deposit wallet | 0 | 0 | A relayed `WALLET-CREATE` transaction; its payload has no user signature | | Establish base order permissions | 1 EIP-712 `Batch` | 0 when the four permissions remain set | One gasless wallet transaction containing pUSD and CTF permission calls for the standard and neg-risk exchanges | | Create or derive order API credentials | 1 EIP-712 `ClobAuth` | 0 | Off-chain creation or derivation of the wallet's CLOB API key, secret, and passphrase | | Convert funded USDC.e to pUSD | 1 EIP-712 `Batch` only when needed | 1 only when needed | A wallet-confirmed approval-and-wrap batch; it never acquires or moves assets silently | | Place an order | 1 EIP-712 order signature per order | 1 per order | One exact, visible order and no other order | That makes the normal totals explicit: * **Fresh readiness:** 3 signatures. * **First order with pUSD already funded:** 4 signatures from Connect Wallet through submission. * **First order that also needs an SDK USDC.e → pUSD conversion:** 5 signatures, excluding prompts from a separate onramp or transfer. * **Each later order with the encrypted vault restored:** 1 signature. The approval signature is one prompt, not four. The batch contains exactly the current base-order calls: pUSD allowance and CTF operator permission for each of the standard and neg-risk exchanges. User-owned onboarding does not approve fee escrow. Split and merge permissions are added only when that separate operation needs them. These counts assume the default deposit-wallet account. Explicit `SignatureType.EOA` onboarding sends the four approval calls as individual on-chain transactions paid by the EOA, so the wallet can show four transaction confirmations instead of one gasless approval-batch signature. If a platform discards both wallet-scoped credentials when the tab closes, the ownership and `ClobAuth` prompts return in the next session even though the on-chain deployment and permissions remain. Retaining the versioned bundle in the encrypted backend vault is what reduces returning users to one signature per order. None of these signatures gives your platform the wallet's private key. ## Choose a custody model | Model | Best for | Where wallet-scoped credentials live | Trade-off | | - | - | - | - | | Backend vault **(recommended)** | Production applications, multiple workers, returning users | Encrypted per-wallet backend vault | More backend work; strongest browser boundary | | Browser memory | Short sessions and the fastest TypeScript integration | Current tab's JavaScript memory only | XSS, extensions, and browser debugging tools can read live secrets | | Managed service signer | Bots or platforms that already use an HSM, MPC wallet, or server signer | Existing signer system plus backend secret store | Different UX; the user is not signing each order in an injected wallet | The first two models use the same wallet authorization. You can begin with the browser-memory model, export its versioned credential bundle once to an encrypted vault, and then use the recommended browser-sign/backend-submit model for later orders. ## Endpoints in your application The route names below are examples implemented by **your own backend**. The browser never needs a second Polynode URL and never receives the platform API key. | Example route | Browser sends | Backend returns | Backend action | | - | - | - | - | | `POST /api/user-owned/authorization/start` | Connected address | Authorization ID, expected address, expiry, display message | Call the SDK begin method and retain the complete challenge once | | `POST /api/user-owned/authorization/finish` | Authorization ID, address, personal-message signature | Wallet-owned credential in a one-time `no-store` response | Atomically take the challenge and call the SDK completion method | | `POST /api/user-owned/vault` | Versioned sensitive credential bundle | Receipt only | Validate with an SDK importer, then encrypt under the authenticated wallet record | | `POST /api/user-owned/orders/prepare` | Token, side, price, size, order options | Credential-free signing request | Load that wallet's vault record, prepare, and retain server state once | | `POST /api/user-owned/orders/submit` | Request ID, address, typed-data signature | Order result | Atomically take server state, validate, and submit once | | `POST /api/user-owned/order-attempts` | Canonical order hash and credential-free preview | Receipt only | Browser-memory model only: durably bind the attempt to the authenticated user and funder before direct submission | Use equivalent names in your framework if preferred. The security properties, field boundaries, authenticated user binding, and one-time semantics are the contract that matters. ### One-time store contract Your Redis or database wrapper must expose two operations, not a general `get()` followed by `delete()`: * `putOnce(id, owner, wallet, payload, expiresAt)` succeeds only when the ID is absent. * `takeOnceForOwner(id, owner, wallet)` atomically checks ownership and expiry, deletes the row, and returns its payload exactly once. A PostgreSQL implementation can make the security boundary explicit: ```sql theme={null} DELETE FROM user_owned_pending WHERE kind = $1 AND opaque_id = $2 AND application_user_id = $3 AND lower(expected_address) = lower($4) AND expires_at > now() RETURNING protected_payload, expires_at; ``` Use a unique constraint on `(kind, opaque_id)` for insertion. Return the same generic not-found response for a wrong owner, wrong wallet, expired ID, and already-consumed ID. A Redis implementation needs one Lua script or an equivalent transactional primitive that performs all comparisons and deletion atomically; `GET` followed by application checks and `DEL` is not sufficient. > [!WARNING] > > Do not silently fall back from builder mode to user-owned mode when a shared > builder allowance is exhausted. Ask the user to opt in, complete authorization, > and switch modes before starting an operation. A partially completed builder > request must not be replayed as a user-owned request. ## Credential boundary | Value | Sensitive? | Browser | Backend | Lifetime | | - | - | - | - | - | | Polynode API key | Yes | **Never** | Environment or secret manager | Rotate as a platform credential | | Full authorization challenge | Security-sensitive | Only its display message | Short-lived one-time store | Until its expiry; atomic take on completion | | Wallet-owned relayer credential | Yes | Optional tab memory only | Encrypted per wallet | Reuse for the same wallet; reauthorize or rotate when needed | | Order API key, secret, and passphrase | Yes | Optional tab memory only | Encrypted per wallet | Reuse only with the wallet that created them | | Prepared order server state | Security-sensitive | **Never** | One-time session or shared store | Five minutes at most; atomic take before submit | | Signing request | No secret | Yes | Keep matching server state | Five minutes at most | | Canonical order hash | No secret | Yes in browser-memory mode | Persist with the attempt before submit | Durable reconciliation key; never an authorization credential | | Wallet signatures | Yes, single-purpose | Produced here | Validate, then submit | Do not retain in logs or analytics | | Private key or seed phrase | Critical | Wallet software only | **Never** | Never request or transmit it | | Builder credentials | Not used | **Never** | **Never on this trader** | User-owned mode rejects them | The wallet-owned relayer credential cannot sign an order or transfer funds by itself, but it can authorize gasless activity for its owner. Treat it as a secret. Order API credentials can authenticate trading requests and must be protected to the same standard. ## Install only this flow's dependencies Every injected-wallet integration uses the browser entry point, even when the prepare and submit backend is written in Python or Rust: ```bash Browser theme={null} npm install polynode-sdk@^0.15.0 viem ``` That is the complete browser install. Do not add the optional builder-relayer, builder-signing, SQLite, or server-wallet packages for this user-owned flow. They belong to separate server-side integrations and are not imported by `polynode-sdk/trading/browser`. The browser entry point is ESM-only. Import it from an ESM browser build such as Vite or Next.js; do not load it with `require()`. On a bundled Node backend, leave `polynode-sdk` as a runtime dependency instead of asking the bundler to crawl integrations your application did not install. For esbuild, either externalize all packages or just the SDK: ```typescript Backend build theme={null} await esbuild.build({ entryPoints: ['src/backend.ts'], bundle: true, platform: 'node', format: 'esm', target: 'node18', external: ['polynode-sdk'], outfile: 'dist/backend.js', }); ``` The deployment must retain its production `node_modules`. The equivalent Next.js setting is `serverExternalPackages: ['polynode-sdk']`; with esbuild, `packages: 'external'` is also valid. This does not add optional builder or server-wallet packages to the user-owned installation. Install the backend SDK for the language that owns your routes: > [tab] TypeScript > > ```bash theme={null} > npm install polynode-sdk@^0.15.0 viem > ``` > [tab] Python > > ```bash theme={null} > pip install "polynode[trading]>=0.15.0,<0.16" > ``` > [tab] Rust > > ```toml Cargo.toml theme={null} > [dependencies] > polynode = { version = "0.18.0", features = ["trading"] } > tokio = { version = "1", features = ["macros", "rt-multi-thread"] } > serde = { version = "1", features = ["derive"] } > serde_json = "1" > chrono = "0.4" > anyhow = "1" > ``` > > Use your web framework's application error type (or `anyhow::Result`) around > these fragments. `std::env::VarError`, storage errors, and SDK errors are > different types and should be mapped to sanitized HTTP responses. ## Before you start * Create the platform trader with `executionMode: "user_owned"`, `ExecutionMode.USER_OWNED`, or `ExecutionMode::UserOwned`. * Use V2. The browser-signing bridge rejects legacy V1 before it fetches market data or asks for a signature. * Keep one encrypted credential record and one trader context per controlling wallet address. * Use Polygon chain ID `137` (`0x89`) and fail closed if the wallet changes account or chain. * Fund the returned `funderAddress` before a BUY. Readiness creates no balance and never moves collateral automatically. Keep funding as a distinct, wallet-confirmed step in your application. * Do not configure builder credentials, a nonzero builder code, or a positive Polynode fee. User-owned mode rejects all three. The specialized `BrowserUserOwnedSession` defaults a new session to the current deposit-wallet account type. This is deliberate and differs from the general server-signer trader's legacy fallback for an address with no deployed wallet. Pass `signatureType: SignatureType.EOA` to choose an explicit EOA; its initial approvals are on-chain transactions paid by that EOA. Existing Safe users can keep their already-bound Safe identity in the backend-vault flow. The browser session does not silently replace that Safe. Legacy proxy/Magic accounts are not supported in user-owned mode. Import the explicit account-type enum with `import { SignatureType } from 'polynode-sdk'`. ## 1. Connect and bind the wallet Read the current account and chain before asking your backend to create any state. You may offer a deliberate chain-switch button; do not sign while the provider reports another chain. ```typescript Frontend theme={null} import { createWalletClient, custom, type EIP1193Provider } from 'viem'; import { polygon } from 'viem/chains'; const provider = (window as Window & { ethereum?: EIP1193Provider }).ethereum; if (!provider) throw new Error('Install or open an EIP-1193 wallet'); const walletClient = createWalletClient({ chain: polygon, transport: custom(provider), }); const [address] = await walletClient.requestAddresses(); const chainId = await provider.request({ method: 'eth_chainId' }); if (chainId !== '0x89') { throw new Error('Switch the connected wallet to Polygon'); } ``` Record this as a pending address for the authenticated application user, then finalize that binding only after the ownership signature succeeds. On every later authorization or order route, compare the request's wallet with that server-side binding instead of trusting an address sent in JSON. ## 2. Start wallet authorization on the backend The backend calls the SDK with its own Polynode API key, keeps the complete challenge in a short-lived one-time store, and returns only the fields needed for the wallet prompt. The SDK's trader uses the normal Polynode trading service configuration; there is no second customer URL to discover. > [tab] TypeScript > > ```typescript Backend theme={null} > import { PolyNodeTrader } from 'polynode-sdk'; > > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > exchangeVersion: 'v2', > storage: 'memory', > }); > try { > const challenge = await trader.beginUserRelayerAuthorization(expectedAddress); > > await pendingAuthorizations.putOnce(challenge.challengeId, { > applicationUserId, > expectedAddress, > challenge, > }, { expiresAt: challenge.expiresAt }); > > return { > authorizationId: challenge.challengeId, > address: challenge.address, > expiresAt: challenge.expiresAt, > message: challenge.message, > }; > } finally { > trader.close(); > } > ``` > [tab] Python > > ```python Backend theme={null} > import os > from polynode.trading import ExecutionMode, PolyNodeTrader, TraderConfig > > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > db_path=":memory:", > )) > try: > challenge = await trader.begin_user_relayer_authorization(expected_address) > > await pending_authorizations.put_once( > challenge.challenge_id, > { > "application_user_id": application_user_id, > "expected_address": expected_address, > "challenge": challenge, > }, > expires_at=challenge.expires_at, > ) > > return { > "authorizationId": challenge.challenge_id, > "address": challenge.address, > "expiresAt": challenge.expires_at, > "message": challenge.message, > } > finally: > trader.close() > ``` > [tab] Rust > > ```rust Backend theme={null} > use polynode::trading::{Address, ExecutionMode, PolyNodeTrader, TraderConfig}; > > let expected_address: Address = input.address.parse()?; > > let mut trader = PolyNodeTrader::new(TraderConfig { > polynode_key: std::env::var("POLYNODE_API_KEY")?, > execution_mode: ExecutionMode::UserOwned, > db_path: ":memory:".into(), > ..Default::default() > })?; > > let challenge = trader > .begin_user_relayer_authorization(expected_address) > .await?; > > // expires_at is canonical RFC 3339 UTC with millisecond precision. > let expires_at = chrono::DateTime::parse_from_rfc3339(&challenge.expires_at)? > .with_timezone(&chrono::Utc); > let ttl = expires_at > .signed_duration_since(chrono::Utc::now()) > .to_std()?; > > pending_authorizations.put_once( > &challenge.challenge_id, > &application_user_id, > &expected_address, > &challenge, > ttl, > ).await?; > > // Return only the ID, expected address, expiry, and display message. > trader.close(); > ``` `pendingAuthorizations` represents your own server-side store. In a shared store, creation must fail if the identifier already exists. Apply a TTL equal to the challenge expiry and bind the row to both the authenticated user and expected wallet. The SDK trader may be request-scoped. A completion worker can create a new user-owned trader with the same backend configuration and use the stored challenge; do not keep a worker or process alive merely to span the wallet prompt. Close each trader after its backend job finishes, including when an SDK call throws or the client disconnects. Put the complete route body inside `try/finally` in TypeScript or Python. In Rust, keep the trader in the request scope so `Drop` runs on every `?` return; an explicit `close()` on the success path is still fine. The fragments below omit repeated route boilerplate, but this exception-safe lifetime is required for every authorization, vault, prepare, and submit handler. Authorization-challenge expiry is a canonical RFC 3339 UTC string with millisecond precision in all three SDKs, for example `2026-08-18T12:34:56.000Z`. Parse it once for your store's TTL, but retain the original complete challenge unchanged for SDK completion. Prepared-order `expiresAt` is instead an integer Unix timestamp in seconds; do not apply the challenge parser to it. ## 3. Sign the ownership message The browser checks that the response still belongs to the connected account, then requests a standard personal-message signature. ```typescript Frontend theme={null} async function assertJsonResponse(response: Response) { const text = await response.text(); let body: any; try { body = text ? JSON.parse(text) : {}; } catch { throw new Error(`Server returned invalid JSON (${response.status})`); } if (!response.ok) { throw new Error(body.error ?? body.message ?? `Request failed (${response.status})`); } return body; } const authorization = await fetch('/api/user-owned/authorization/start', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address }), }).then(assertJsonResponse); if (authorization.address.toLowerCase() !== address.toLowerCase()) { throw new Error('Authorization belongs to another wallet'); } const signature = await walletClient.signMessage({ account: address, message: authorization.message, }); ``` Do not let the frontend change the message. The SDK validates the complete challenge shape, wallet, lifetime, chain, and signature format during completion. ## 4. Complete authorization on the backend Atomically remove the saved challenge before completion, but make ownership part of that same operation. Match the ID, authenticated application user, and server-bound wallet in one `DELETE ... WHERE ... RETURNING`, transaction, or equivalent script. A mismatched caller must receive no row **and must not delete another user's challenge**. Then give the SDK only the original challenge and browser signature. > [tab] TypeScript > > ```typescript Backend theme={null} > const pending = await pendingAuthorizations.takeOnceForOwner( > input.authorizationId, > { applicationUserId, expectedAddress }, // both come from the authenticated server session > ); > if (!pending) throw new Error('Unknown, expired, or already-used authorization'); > assertApplicationUser(pending.applicationUserId); > assertExpectedWallet(pending.expectedAddress, input.address); > > try { > const credential = await trader.completeUserRelayerAuthorization( > pending.challenge, > input.signature, > pending.expectedAddress, > ); > > return { userRelayerCredentials: credential }; > } finally { > trader.close(); > } > ``` > [tab] Python > > ```python Backend theme={null} > pending = await pending_authorizations.take_once_for_owner( > input.authorization_id, > application_user_id=application_user_id, > expected_address=expected_address, # both come from the authenticated server session > ) > if pending is None: > raise ValueError("Unknown, expired, or already-used authorization") > assert_application_user(pending["application_user_id"]) > assert_expected_wallet(pending["expected_address"], input.address) > > try: > credential = await trader.complete_user_relayer_authorization( > pending["challenge"], > input.signature, > pending["expected_address"], > ) > > return { > "userRelayerCredentials": { > "key": credential.key, > "address": credential.address, > } > } > finally: > trader.close() > ``` > [tab] Rust > > ```rust Backend theme={null} > let pending = pending_authorizations > .take_once_for_owner( > &input.authorization_id, > &application_user_id, > expected_address, > ) > .await? > .ok_or("unknown, expired, or already-used authorization")?; > > assert_application_user(&pending.application_user_id)?; > assert_expected_wallet(pending.expected_address, input.address)?; > > let credential = trader > .complete_user_relayer_authorization( > &pending.challenge, > &input.signature, > pending.expected_address, > ) > .await?; > > let response_body = serde_json::json!({ > "userRelayerCredentials": credential, > }); > trader.close(); > ``` The exact JSON response shape is `{"userRelayerCredentials":{"key":"...","address":"0x..."}}`. Set `Cache-Control: no-store` on that response and exclude its body from access logs. At this point, choose the browser-memory path below or save the credential in the backend-vault path. Never include the Polynode API key in either response. ## Option A: browser-memory session This is the shortest path to an actual order. It is TypeScript-only in the browser, but the authorization backend above may use any of the three SDKs. Return the wallet-owned credential once over an authenticated same-origin HTTPS response with `Cache-Control: no-store`. Do not let an access log, error tracker, analytics tool, service worker, or response cache capture the body. ```typescript Frontend theme={null} import { BrowserUserOwnedSession } from 'polynode-sdk/trading/browser'; import { parseUnits } from 'viem'; const finish = await fetch('/api/user-owned/authorization/finish', { method: 'POST', credentials: 'same-origin', cache: 'no-store', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ authorizationId: authorization.authorizationId, address, signature, }), }).then(assertJsonResponse); const session = await BrowserUserOwnedSession.open({ wallet: { provider, address }, userRelayerCredentials: finish.userRelayerCredentials, }); console.log(session.status.funderAddress); console.log(session.status.signatureType); ``` Version 0.14.2 accepts viem's standard `EIP1193Provider` directly; no provider cast or adapter is required. `open()` still checks at runtime that the injected provider supplies `request`, `on`, and `removeListener`. `open()` forces user-owned V2, direct transport, and memory-only storage. It accepts no Polynode key, builder credential, builder code, positive fee, proxy setting, or persistent storage. It validates Polygon and the connected account, establishes the default trading account when needed, confirms permissions, and creates or derives that wallet's order API credentials. Readiness does not create collateral. Before a BUY, show the funder address and balances in your funding UI. The user must first acquire or transfer USDC.e to that exact address through your normal wallet/onramp UX. Once it is there, the SDK performs the wallet-confirmed USDC.e → pUSD conversion for either an EOA or deposit-wallet session: ```typescript Frontend theme={null} const desiredRaw = parseUnits('10', 6); // fund 10 pUSD; raw units are exact const currentPolyUsdRaw = await session.getPolyUsdBalance(); const shortfallRaw = desiredRaw > currentPolyUsdRaw ? desiredRaw - currentPolyUsdRaw : 0n; if (shortfallRaw > 0n) { const usdcRaw = await session.getUsdcBalance(); if (usdcRaw < shortfallRaw) { showAcquireOrTransferUsdc({ address: session.status.funderAddress, amountRaw: shortfallRaw - usdcRaw, decimals: 6, }); throw new Error('Waiting for USDC.e funding'); } const approved = await showFundingConfirmation({ address: session.status.funderAddress, amountRaw: shortfallRaw, action: 'Convert USDC.e to pUSD', }); if (!approved) throw new Error('Funding declined'); const transactionHash = await session.wrapToPolyUsd(shortfallRaw); showFundingTransaction(transactionHash); if (await session.getPolyUsdBalance() < desiredRaw) { throw new Error('pUSD funding did not reach the required balance'); } } ``` `wrapToPolyUsd()` never obtains assets, chooses an amount, or runs silently. It uses raw six-decimal units, checks USDC.e first, asks the connected wallet to approve and confirm the required transaction or gasless batch, and waits for confirmation. The application-defined UI functions above display the chosen amount and direct an underfunded user to your existing deposit/bridge flow. Do not prepare the order until the final pUSD balance check passes. Once funded, place the order. The session builds an exact V2 request with zero builder attribution, asks the connected wallet for its EIP-712 signature, checks the signer again, and submits it. ```typescript Frontend theme={null} const result = await session.order( { tokenId, side: 'BUY', price: 0.52, size: 5, type: 'GTC', postOnly: true, }, { confirm: async (preview) => showFinalOrderConfirmation(preview), beforeSubmit: async ({ orderHash, order }) => { const response = await fetch('/api/user-owned/order-attempts', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ orderHash, order }), }); await assertJsonResponse(response); }, }, ); if (!result.success) { throw new Error(result.error ?? 'Order was not accepted'); } showOrderId(result.orderId); ``` The confirmation callback receives the exact 11-field, credential-free order preview. Returning `false` or throwing stops the flow before signing or submission. `beforeSubmit` receives a frozen, credential-free `BrowserBeforeSubmitOrder` containing the canonical exchange `orderHash` and that preview. The SDK awaits it after finalizing the signature but before the submission request; if durable storage fails, it sends no order. Bind this record to the authenticated application user and expected funder. A browser-supplied record is useful for that user's reconciliation but must never authorize another action or another user's read. After each callback, the SDK rechecks the account and chain immediately before continuing. It also checks BUY balance before the signature. It closes the session on `pagehide`, `accountsChanged`, or `chainChanged`. Also close it explicitly on logout or when your UI no longer needs it: ```typescript theme={null} session.close(); ``` > [!WARNING] > > JavaScript strings cannot be cryptographically zeroized. `close()` removes the > SDK's references and clears its in-memory maps, but an XSS payload, malicious > extension, browser debugger, or prior application copy can still observe live > credentials. Use a strict CSP, trusted dependencies, no third-party analytics > on this route, and the backend-vault model for long-running production use. ## Option B: encrypted backend vault The recommended production model leaves long-lived credentials on your backend. The browser keeps them only long enough to transfer one versioned bundle to your own vault, then closes the session. Later orders send only a short-lived signing request to the browser. Run `BrowserUserOwnedSession.open(...)` from Option A once to complete wallet readiness and create the bound credential set. Choosing the vault model means exporting that session immediately after onboarding, not skipping onboarding. ### Export once after onboarding ```typescript Frontend theme={null} const bundle = session.exportForBackendVault(); // succeeds once per session const response = await fetch('/api/user-owned/vault', { method: 'POST', credentials: 'same-origin', cache: 'no-store', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(bundle), }); if (!response.ok) throw new Error('Vault receipt failed'); session.close(); ``` The sensitive bundle has one stable schema across all three SDKs: ```json theme={null} { "version": "1", "executionMode": "user_owned", "wallet": { "address": "0xControllingEOA", "funderAddress": "0xTradingAccount", "signatureType": 3 }, "clobCredentials": { "apiKey": "...", "apiSecret": "...", "apiPassphrase": "..." }, "userRelayerCredentials": { "key": "...", "address": "0xControllingEOA" } } ``` `signatureType` is `0` for an EOA, `2` for an existing EOA-controlled Safe, or `3` for the current deposit-wallet account. Value `1` is rejected. Your backend must parse the body with a size limit, validate it through the SDK, encrypt it under the authenticated user's wallet record, and return no copy of the credential. Key vault records by a canonical lowercase wallet address and enforce a unique owner. Never use a browser-supplied user ID or funder address as the database authority. ### Validate and load the bundle > [tab] TypeScript > > ```typescript Backend theme={null} > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > exchangeVersion: 'v2', > storage: 'memory', > }); > try { > await trader.importUserOwnedBrowserBundle(bundle); > await encryptedWalletVault.put(expectedAddress, bundle); > } finally { > trader.close(); > } > ``` > [tab] Python > > ```python Backend theme={null} > from polynode.trading import UserOwnedBrowserBundle > > validated = UserOwnedBrowserBundle.from_dict(bundle) > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > db_path=":memory:", > )) > try: > await trader.import_user_owned_browser_bundle(validated) > await encrypted_wallet_vault.put(expected_address, bundle) > finally: > trader.close() > ``` > [tab] Rust > > ```rust Backend theme={null} > use polynode::trading::UserOwnedBrowserBundle; > > let bundle: UserOwnedBrowserBundle = serde_json::from_slice(&bounded_body)?; > trader.import_user_owned_browser_bundle(bundle).await?; > encrypted_wallet_vault.put(expected_address, &bounded_body).await?; > trader.close(); > ``` The importers reject an unknown version, extra fields, unsupported wallet type, wrong credential owner, or funder that does not belong to the controlling EOA. They load credentials only into memory and do not install a signer. The vault record itself still contains secrets. Encrypt it with a managed key, restrict decryption to the order worker, audit access without recording values, and support per-wallet revocation and replacement. ### Prepare one exact order For every order, decrypt only that wallet's bundle into a dedicated in-memory trader. Ask the SDK to prepare the order, then put the server-only state in a one-time store. Return only `signingRequest` to the browser. > [tab] TypeScript > > ```typescript Backend theme={null} > const bundle = await encryptedWalletVault.get(expectedAddress); > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > exchangeVersion: 'v2', > storage: 'memory', > }); > try { > await trader.importUserOwnedBrowserBundle(bundle); > > const prepared = await trader.prepareUserOwnedOrder({ > tokenId: input.tokenId, > side: input.side, > price: input.price, > size: input.size, > type: input.type ?? 'GTC', > postOnly: input.postOnly ?? false, > }); > > const signingRequest = prepared.signingRequest; > const orderHash = prepared.orderHash; > const serverState = trader.exportPreparedUserOwnedOrderState(prepared); > > await pendingOrders.putOnce(signingRequest.requestId, { > applicationUserId, > expectedAddress, > orderHash, > order: signingRequest.order, > serverState, > }, { expiresAt: signingRequest.expiresAt }); > > return signingRequest; > } finally { > trader.close(); > } > ``` > > `exportPreparedUserOwnedOrderState()` invalidates the original in-process > object, which prevents the local copy and shared-store copy from both being > submitted. > [tab] Python > > ```python Backend theme={null} > from polynode.trading import OrderParams > > bundle = await encrypted_wallet_vault.get(expected_address) > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > db_path=":memory:", > )) > prepared = None > try: > await trader.import_user_owned_browser_bundle(bundle) > > prepared = await trader.prepare_user_owned_order(OrderParams( > token_id=input.token_id, > side=input.side, > price=input.price, > size=input.size, > type=input.type or "GTC", > post_only=bool(input.post_only), > )) > > signing_request = prepared.signing_request.to_dict() > order_hash = prepared.order_hash > server_state = trader.export_prepared_user_owned_order(prepared) > > await pending_orders.put_once( > signing_request["requestId"], > { > "application_user_id": application_user_id, > "expected_address": expected_address, > "order_hash": order_hash, > "order": signing_request["order"], > "server_state": server_state, > }, > expires_at=signing_request["expiresAt"], > ) > > return signing_request > finally: > if prepared is not None: > trader.discard_prepared_user_owned_order(prepared) > trader.close() > ``` > [tab] Rust > > ```rust Backend theme={null} > use polynode::trading::{ > ExecutionMode, OrderParams, PolyNodeTrader, TraderConfig, > UserOwnedBrowserBundle, > }; > > let bundle: UserOwnedBrowserBundle = encrypted_wallet_vault > .get(expected_address) > .await?; > let mut trader = PolyNodeTrader::new(TraderConfig { > polynode_key: std::env::var("POLYNODE_API_KEY")?, > execution_mode: ExecutionMode::UserOwned, > db_path: ":memory:".into(), > ..Default::default() > })?; > trader.import_user_owned_browser_bundle(bundle).await?; > > let prepared = trader.prepare_user_owned_order(OrderParams { > token_id: input.token_id, > side: input.side, > price: input.price, > size: input.size, > order_type: input.order_type.unwrap_or_default(), > post_only: input.post_only, > ..Default::default() > }).await?; > > let signing_request = prepared.signing_request().clone(); > let order_hash = prepared.order_hash()?; > let server_state = prepared.to_server_store_json()?; > > pending_orders.put_once( > &signing_request.request_id, > &application_user_id, > expected_address, > &order_hash, > &signing_request.order, > &server_state, > signing_request.expires_at, > ).await?; > > drop(prepared); > trader.close(); > // Return signing_request. > ``` The server-state encodings contain no Polynode key, wallet-owned relayer key, or order API credential. Each SDK authenticates the complete encoding with a domain-separated tag keyed by the backend-held Polynode key and verifies the tag again before submission. Every worker handling one pending order must use the same key. The state is still backend-only: it contains the exact order intent and security bindings and must never be accepted from a browser. Use a unique `put-if-absent`, apply the signing request's expiry as the TTL, and delete abandoned records. Rotating the platform key intentionally invalidates outstanding prepared orders; have users prepare them again. The prepared object's `orderHash` / `order_hash` / `order_hash()` is the canonical standard exchange `Order` EIP-712 digest. It is intentionally not the deposit wallet's outer `TypedDataSign` digest. It is non-secret and does not change the opaque server-state schema, but read it from the integrity-bound prepared object before export and persist it with the attempt. Never accept a replacement hash from the order-signature response. For a BUY, each SDK compares the exact maker amount with the funder's current balance before it returns a signing request. An insufficient balance therefore fails before the wallet sees an order-signature prompt. The SDK never funds the account or changes the order after preparation. ### Send only the shared signing request All three SDKs return the same version-1 browser shape: ```json theme={null} { "version": "1", "requestId": "opaque-one-time-id", "address": "0xControllingEOA", "expiresAt": 1787053800, "typedData": { "domain": {}, "types": {}, "primaryType": "Order", "message": {} }, "order": { "tokenId": "12345678901234567890", "side": "BUY", "price": 0.52, "size": 5, "orderType": "GTC", "postOnly": true, "expiration": null, "maker": "0xTradingAccount", "signer": "0xExpectedSigner", "makerAmount": "2600000", "takerAmount": "5000000" } } ``` `primaryType` is determined by the selected wallet account type. Do not assume or replace it: sign the entire returned `typedData` object exactly. Large typed-data integers are decimal strings. Do not convert token IDs or raw amounts to JavaScript `number`; doing so can change the signed value. The preview's `price` and `size` are the canonical tick- and size-rounded values used by the order. `makerAmount` and `takerAmount` are raw six-decimal-unit strings; `maker` is the trading/funder account, while `signer` is the account the order signature is bound to. ### Verify, display, and sign in the browser The browser must check the schema version, expiry, chain, and currently active account before it displays the preview. The preview is for confirmation; sign the exact `typedData` object, not a new object reconstructed from form inputs. ```typescript Frontend theme={null} const signingRequest = await fetch('/api/user-owned/orders/prepare', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderInput), }).then(assertJsonResponse); const [currentAddress] = await provider.request({ method: 'eth_accounts', }); const currentChain = await provider.request({ method: 'eth_chainId' }); if (signingRequest.version !== '1') { throw new Error('Unsupported signing request'); } if (Math.floor(Date.now() / 1000) >= signingRequest.expiresAt) { throw new Error('Order signing request expired'); } if ( currentChain !== '0x89' || !currentAddress || currentAddress.toLowerCase() !== signingRequest.address.toLowerCase() ) { throw new Error('Reconnect the expected wallet on Polygon'); } await showFinalOrderConfirmation(signingRequest.order); const orderSignature = await provider.request({ method: 'eth_signTypedData_v4', params: [currentAddress, JSON.stringify(signingRequest.typedData)], }); const orderResult = await fetch('/api/user-owned/orders/submit', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ requestId: signingRequest.requestId, address: currentAddress, signature: orderSignature, }), }).then(assertJsonResponse); ``` Do not send `typedData`, the order preview, token ID, price, or size back on the submit route. The backend uses only its prepared state plus the browser's `requestId`, `address`, and `signature`. ### Atomically take and submit on the backend Use `GETDEL`, a database `DELETE ... RETURNING`, or an equivalent transaction. The take must be atomic across workers **and conditional on the authenticated application user plus server-bound wallet**. A leaked request ID must not let a different caller delete the row. Remove the prepared state before the SDK makes the authenticated network request so a timeout cannot make the same signature reusable. > [tab] TypeScript > > ```typescript Backend theme={null} > const pending = await pendingOrders.takeOnceForOwner( > input.requestId, > { applicationUserId, expectedAddress }, // authenticated server-session values > ); > if (!pending) throw new Error('Unknown, expired, or already-used order'); > assertApplicationUser(pending.applicationUserId); > assertExpectedWallet(pending.expectedAddress, input.address); > > const bundle = await encryptedWalletVault.get(pending.expectedAddress); > const trader = new PolyNodeTrader({ > polynodeKey: process.env.POLYNODE_API_KEY!, > executionMode: 'user_owned', > exchangeVersion: 'v2', > storage: 'memory', > }); > try { > await trader.importUserOwnedBrowserBundle(bundle); > > const prepared = await trader.importPreparedUserOwnedOrderState(pending.serverState); > if (prepared.orderHash.toLowerCase() !== pending.orderHash.toLowerCase()) { > throw new Error('Prepared order identity mismatch'); > } > await orderAttempts.putOnce(pending.orderHash, { > requestId: input.requestId, > applicationUserId, > expectedAddress, > order: pending.order, > status: 'submitting', > startedAt: new Date().toISOString(), > }); > return await trader.submitPreparedUserOwnedOrder(prepared, { > requestId: input.requestId, > address: input.address, > signature: input.signature, > }); > } finally { > trader.close(); > } > ``` > [tab] Python > > ```python Backend theme={null} > from datetime import datetime, timezone > > pending = await pending_orders.take_once_for_owner( > input.request_id, > application_user_id=application_user_id, > expected_address=expected_address, # authenticated server-session values > ) > if pending is None: > raise ValueError("Unknown, expired, or already-used order") > assert_application_user(pending["application_user_id"]) > assert_expected_wallet(pending["expected_address"], input.address) > > bundle = await encrypted_wallet_vault.get(pending["expected_address"]) > trader = PolyNodeTrader(TraderConfig( > polynode_key=os.environ["POLYNODE_API_KEY"], > execution_mode=ExecutionMode.USER_OWNED, > db_path=":memory:", > )) > try: > await trader.import_user_owned_browser_bundle(bundle) > > prepared = trader.import_prepared_user_owned_order(pending["server_state"]) > if prepared.order_hash.lower() != pending["order_hash"].lower(): > raise ValueError("Prepared order identity mismatch") > await order_attempts.put_once(pending["order_hash"], { > "request_id": input.request_id, > "application_user_id": application_user_id, > "expected_address": expected_address, > "order": pending["order"], > "status": "submitting", > "started_at": datetime.now(timezone.utc).isoformat(), > }) > return await trader.submit_prepared_user_owned_order( > prepared, > request_id=input.request_id, > address=input.address, > signature=input.signature, > ) > finally: > trader.close() > ``` > [tab] Rust > > ```rust Backend theme={null} > use polynode::trading::{ > ExecutionMode, PolyNodeTrader, PreparedUserOwnedOrder, TraderConfig, > }; > > let pending = pending_orders > .take_once_for_owner( > &input.request_id, > &application_user_id, > expected_address, > ) > .await? > .ok_or("unknown, expired, or already-used order")?; > assert_application_user(&pending.application_user_id)?; > assert_expected_wallet(pending.expected_address, input.address)?; > > let bundle = encrypted_wallet_vault > .get(pending.expected_address) > .await?; > let mut trader = PolyNodeTrader::new(TraderConfig { > polynode_key: std::env::var("POLYNODE_API_KEY")?, > execution_mode: ExecutionMode::UserOwned, > db_path: ":memory:".into(), > ..Default::default() > })?; > trader.import_user_owned_browser_bundle(bundle).await?; > > let prepared = PreparedUserOwnedOrder::from_server_store_json( > &pending.server_state, > )?; > if prepared.order_hash()?.to_lowercase() != pending.order_hash.to_lowercase() { > return Err("prepared order identity mismatch".into()); > } > order_attempts.put_once( > &pending.order_hash, > &input.request_id, > &application_user_id, > expected_address, > &pending.order, > "submitting", > ).await?; > let result = trader.submit_prepared_user_owned_order( > prepared, > &input.request_id, > &input.address, > &input.signature, > ).await?; > > trader.close(); > ``` Before submission, the SDK revalidates the full typed-data and order-state pair, request version and expiry, zero builder attribution, active wallet and funder, wallet-owned credential owner, canonical low-S signature, and recovered signer. It builds authenticated order data only after those checks pass. ### Classify and reconcile a timeout The trading APIs do not expose a per-order timeout setting. Do not put an aggressive cancellation timeout around the SDK call and then assume that a cancelled HTTP request prevented submission. Use this conservative classification: * An error before the language's SDK submit method is invoked is a definite local failure. The prepared row is already one-time; let the user prepare again after correcting it. * A completed SDK result that explicitly rejects the order is definite. Show that result and prepare a new intent only after the user changes or reconfirms it. * A transport timeout, connection reset, cancelled request, worker crash, or unclassified exception after invoking the submit method is **ambiguous**. When in doubt, classify it as ambiguous. Before invoking submission, persist a non-secret attempt record separately from the consumed state: the SDK-derived canonical `orderHash`, `requestId`, authenticated user, wallet/funder, the credential-free order preview, and submission time. Set its status to `submitting`. The durable write must finish before the SDK is allowed to start the submission request. Do not put the signature, credential bundle, or reusable prepared state in that record. This identity requirement is not optional. Token, direction, price, size, and time can describe two different orders from the same wallet. They may validate an exact-hash match as defense-in-depth, but they must never select a candidate on their own. For an ambiguous attempt: 1. Load the wallet's authoritative open orders with `trader.getOpenOrders({ assetId: tokenId })` (TypeScript), `await trader.get_open_orders(asset_id=token_id)` (Python), or `trader.get_open_orders(None).await?` and filter the returned token locally (Rust). Match only an order whose `id`, case-insensitively, equals the persisted `orderHash`. If it exists, the exact order was accepted and is still open or partially open. 2. A fully filled order may no longer be open. Query [V2 fill history](/api-reference/clobv2/wallet-trades) for `attempt.order.maker`, which is the signing preview's `order.maker` and the session's `funderAddress`. Do **not** query the controlling EOA for a Safe or deposit-wallet order merely because it signed the request. Keep only rows whose `order_hash`, case-insensitively, equals the persisted `orderHash`, then group those exact rows to summarize partial fills. 3. Validate the exact-hash rows against the expected maker, token, BUY/SELL direction, raw amount bounds, and integer-rounded limit described on the fill-history page. A mismatch is a data-integrity error, not permission to search for a different hash. 4. Repeat the exact open-order and fill reads after a short bounded delay to allow indexing. If the hash remains absent, mark the attempt `needs_reconciliation` and surface it for operator/user review. An accepted order could have been cancelled or expired before the read; absence is not proof that submission failed. Local SDK order history can assist, but it is not sufficient proof after a worker crash. Never restore, resubmit, or automatically recreate the consumed state merely because the first reconciliation read found nothing. For the browser-memory model, `beforeSubmit` is the only safe place to create the durable attempt: it exposes the exact hash and the SDK awaits your storage receipt before transport. Version 0.14.2 also exposes the authenticated open-order read as `await session.getOpenOrders({ assetId: attempt.order.tokenId })`. Keep the attempt outside the session so it survives a tab refresh; use the same exact-hash fill comparison and ambiguity rules. The hash is a correlation key, not an idempotency key, and the SDK never resubmits automatically. ## Option C: managed service signer If your application already uses an HSM, MPC wallet, Privy server wallet, or another controlled signer, keep using the normal combined SDK flow. Configure a user-owned trader, run `ensureReady`/`ensure_ready`, and call `order`. The signer must support both personal-message and typed-data signatures. This model is appropriate for automated strategies. Do not convert an injected wallet user to a service signer merely to avoid implementing the split-signing flow, and never ask a user to paste a private key into your application. ## Secure route requirements Apply these controls to the authorization, vault, prepare, and submit routes: 1. Require HTTPS and an authenticated same-origin application session. 2. Bind the application user to one expected wallet; never trust a body-supplied user ID. 3. Protect cookie-authenticated writes with CSRF defenses and restrictive `SameSite` cookies. 4. Rate-limit by application user, wallet, IP risk signal, and operation. 5. Set request-body limits and reject unexpected JSON fields. 6. Use `Cache-Control: no-store` on every response that contains a challenge, credential, bundle, prepared state acknowledgment, or signature result. 7. Redact request and response bodies from access logs, traces, replay tools, exception reports, support captures, and analytics. 8. Disable service-worker caching for these paths. 9. Use a restrictive CSP and audited dependencies on any page that temporarily holds credentials. Do not run advertising or third-party analytics there. 10. Encrypt vault values at rest, restrict decryption to the order worker, and audit access by wallet ID without logging values. 11. Use atomic put/take semantics and TTLs for challenges and prepared orders. 12. Close the SDK trader after each job so active signers and in-memory credentials are released. For browser-memory mode, credential delivery should be a one-time response. Do not place it in a URL, query string, redirect, HTML, local storage, session storage, IndexedDB, cookie, global state store, or hydration payload. ## Access and common errors | Error or symptom | What to check | | - | - | | `invalid or missing X-Polynode-Key` / HTTP 401 | The authorization call must run on the backend through the SDK with a current `pn_live_...` key. Check the environment value and whitespace. Do not move the key into the browser. If that key works on normal API calls but this error persists, contact Polynode support to check key synchronization for wallet authorization. | | HTTP 403 during authorization | User-owned authorization is not enabled for that key or plan. Use an eligible paid Polynode plan; no separate add-on is required. | | HTTP 429 | A normal API or abuse limit was reached. Back off; do not switch attribution modes mid-request. | | `wrong chain`, `wallet changed`, or address mismatch | Reconnect the expected account on Polygon and prepare a new request. Never reuse the old signature. | | `unknown, expired, or already-used` | The challenge or prepared order was consumed or reached its TTL. Start that one step again. | | `insufficient ... collateral` | Fund the exact `funderAddress`, then prepare a new order. Readiness itself does not add funds. | | Approval/readiness failure | Let the first-use setup finish and confirm before preparing an order. EOA approvals require gas. | | Builder or fee configuration rejected | Remove builder credentials, nonzero builder code, and positive Polynode fee configuration from this trader. | | Signature validation failure | Do not normalize or rebuild typed data in the browser. Sign the SDK object exactly and confirm the active account did not change. | | Timeout after submit | Treat it as ambiguous. Compare the persisted canonical order hash with open-order `id` and fill `order_hash`; never select by amount/time similarity or retry automatically. | ## Production acceptance checklist * A new user can connect on Polygon, authorize, complete readiness, see the funder address, fund it, review an order, sign it, and receive an order result. * A returning user can load the encrypted record without another ownership signature unless reauthorization is required. * Two users cannot load one another's vault record, challenge, prepared state, trader, or result. * Account and chain changes close browser sessions and invalidate the current UI flow. * The browser never sees the Polynode API key or prepared server state. * Backend logs and telemetry contain no credential bundle, API secret, passphrase, full challenge, or signature. * Builder credentials, builder authentication, builder code, and positive Polynode fees are absent from the user-owned path. * Challenges and prepared orders are one-time, short-lived, and atomically consumed across all workers with the authenticated user and wallet included in the same conditional take. * The canonical exchange order hash is durably stored before every submit request and exact-matched during open-order and fill reconciliation. * A timeout cannot cause an automatic duplicate order. * Your UI says that user-owned mode removes the shared builder allowance; it does not advertise all activity as universally unlimited. For mode behavior and gasless position operations, continue with [User-owned execution](/sdks/user-owned-execution). For general order inputs, funding, cancellation, and result handling, see [Trading and fees](/sdks/trading). # Complete V3 API Source: https://docs.polynode.dev/sdks/v3-api Call the shared 120-operation V3 SDK registry and use authenticated REST for newer routes awaiting a registry release. Every SDK ships the same V3 operation registry. In TypeScript 0.14.2, Python 0.14.1, and Rust 0.17.1 it contains 120 operations. Use a named helper when one exists and improves readability. Use the registered executor for complete coverage. ## What is covered | Family | Operations | Examples | | - | -: | - | | Wallets | 15 | summary, P\&L, positions, trades, fees, rewards, redemptions, activity | | Wallet combos | 5 | positions, activity, trades, redemptions, summary | | Global combos | 3 | markets, activity, redemptions | | Markets | 11 | search, metadata, candles, price, positions, trades | | Rewards, tokens, and tags | 6 | reward configs, token metadata, tag leaderboards | | Global data | 8 | stats, leaderboard, trades, positions, fees, resolutions, conditions | | Builders | 3 | directory, builder details, attributed trades | | Webhooks | 9 | create, list, update, test, rotate secret, deliveries | | Credits | 9 | wallet totals and series, feed, leaderboard, distributors, transactions | | Identities and profiles | 7 | identity search, batches, Polymarket profiles and username flow | | Perps | 44 | instruments, market data, wallets, analytics, collateral flows, exchange metadata | The registry is the SDK contract for route availability. Endpoint reference pages remain the source for request fields and response shapes. The Builder trader leaderboard and the two Builder daily-activity routes are newer authenticated REST endpoints and are not part of the 120-operation registry in those versions. Call them over HTTPS using the examples in [Builder Trader P\&L Leaderboard](/data/builders/trader-leaderboard), [Builder Daily Activity](/data/builders/daily-activity), and [Compare Builder Daily Activity](/data/builders/activity-comparison) until a later SDK release explicitly adds them. ## Discover operations > [tab] TypeScript > > ```typescript theme={null} > import { V3_OPERATION_COUNT, V3_OPERATIONS } from 'polynode-sdk'; > > console.log(V3_OPERATION_COUNT); // 120 in polynode-sdk 0.14.2 > for (const operation of V3_OPERATIONS.filter((item) => item.domain === 'perps')) { > console.log(operation.method, operation.path); > } > ``` > [tab] Python > > ```python theme={null} > from polynode import V3_OPERATION_COUNT, V3_OPERATIONS > > print(V3_OPERATION_COUNT) # 120 in polynode 0.14.1 > for operation in V3_OPERATIONS: > if operation.domain == "perps": > print(operation.method, operation.path) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{V3_OPERATIONS, V3_OPERATION_COUNT}; > > fn main() { > println!("{V3_OPERATION_COUNT}"); // 120 in polynode 0.17.1 > for operation in V3_OPERATIONS.iter().filter(|item| item.domain == "perps") { > println!("{} {}", operation.method, operation.path); > } > } > ``` ## Call a registered route Operation names use the exact `METHOD /v3/path` form shown by the registry. Pass template fields separately; the SDK URL-encodes them. The following request reads a wallet's combo summary: > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > const pn = new PolyNode({ apiKey }); > > const wallet = '0xa9857c7bcb9bcfafd2c132ab053f34f678610058'; > const summary = await pn.v3.execute( > 'GET /v3/wallets/{address}/combos/summary', > { pathParams: { address: wallet } }, > ); > console.log(summary); > ``` > [tab] Python > > ```python theme={null} > import os > from polynode import PolyNode > > wallet = "0xa9857c7bcb9bcfafd2c132ab053f34f678610058" > with PolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > summary = pn.v3.execute( > "GET /v3/wallets/{address}/combos/summary", > path_params={"address": wallet}, > ) > print(summary) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{PolyNodeClient, V3RequestOptions}; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let client = PolyNodeClient::new( > std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") > )?; > let summary = client.v3().execute_named( > "GET /v3/wallets/{address}/combos/summary", > V3RequestOptions::default().path_param( > "address", > "0xa9857c7bcb9bcfafd2c132ab053f34f678610058", > ), > ).await?; > println!("{summary:#}"); > Ok(()) > } > ``` ## Add query parameters The registered executor accepts wire-format query names. This is useful when one example should translate directly across all three SDKs. > [tab] TypeScript > > ```typescript theme={null} > const trades = await pn.v3.execute('GET /v3/trades', { > query: { > limit: 50, > sort_by: 'order_hash', > group_by: 'order_hash', > }, > }); > ``` > [tab] Python > > ```python theme={null} > trades = pn.v3.execute( > "GET /v3/trades", > query={ > "limit": 50, > "sort_by": "order_hash", > "group_by": "order_hash", > }, > ) > ``` > [tab] Rust > > ```rust theme={null} > let trades = client.v3().execute_named( > "GET /v3/trades", > V3RequestOptions::default() > .query_param("limit", 50_u64) > .query_param("sort_by", "order_hash") > .query_param("group_by", "order_hash"), > ).await?; > ``` `group_by=order_hash` and `sort_by=order_hash` are supported on the global, wallet, market-token, and market-slug trade routes. Grouped trade responses use a smaller envelope than ungrouped list responses. They include `trades`, `rows_returned`, and `grouped_by` (plus the route identifier where applicable), but omit `limit`, `offset`, and `has_more`. The request's `limit` and `offset` still select the page. If you page grouped results, track those values in your application and stop after an empty `trades` array instead of waiting for `has_more`. ## Read perps through V3 Perps REST data uses the same executor and API key: > [tab] TypeScript > > ```typescript theme={null} > const ticker = await pn.v3.execute( > 'GET /v3/perps/tickers/{instrument}', > { pathParams: { instrument: 'BTC-USD' } }, > ); > console.log(ticker); > ``` > [tab] Python > > ```python theme={null} > ticker = pn.v3.execute( > "GET /v3/perps/tickers/{instrument}", > path_params={"instrument": "BTC-USD"}, > ) > print(ticker) > ``` > [tab] Rust > > ```rust theme={null} > let ticker = client.v3().execute_named( > "GET /v3/perps/tickers/{instrument}", > V3RequestOptions::default().path_param("instrument", "BTC-USD"), > ).await?; > println!("{ticker:#}"); > ``` See the [Perps API](/perps/overview) for instruments, response fields, filters, and freshness behavior. For live updates, use the [SDK perps stream](/sdks/perps). ## TypeScript convenience methods TypeScript also has typed helpers for frequently used V3 routes: ```typescript theme={null} const wallet = await pn.v3.wallet('0x...'); const positions = await pn.v3.walletPositions(wallet.address, { status: 'open', sort: 'size', limit: 25, }); const trades = await pn.v3.walletTrades(wallet.address, { groupBy: 'order_hash', sortBy: 'order_hash', limit: 50, }); const combos = await pn.v3.execute( 'GET /v3/wallets/{address}/combos/positions', { pathParams: { address: wallet.address }, query: { limit: 25 } }, ); ``` Use `execute()` whenever a route is in `pn.v3.operations` but does not have a dedicated helper. ## Retries and mutations The V3 clients: * retry safe reads after transient transport errors, `408`, `425`, `429`, and server errors * honor `Retry-After` within the configured retry ceiling * use the registry's retry policy for the two read-only batch POST operations * never retry state-changing requests automatically * expose the status, request ID, retry metadata, and a credential-redacted request URL on structured V3 errors > [!WARNING] > > A timeout on a webhook create, update, delete, test, secret rotation, or profile mutation is an ambiguous result. Check the resource before trying the mutation again. ## Precision V3 responses may contain exact decimal and large integer values. TypeScript and Rust retain raw V3 JSON values without forcing monetary fields through binary floating point. Python decodes JSON decimal fractions as `Decimal`. Preserve decimal strings or decimal objects until display. Do not convert identifiers, raw amounts, or exact prices to a JavaScript `number` merely for convenience. ## Raw additive routes `request()` is an escape hatch for a newly additive `/v3/` route before the published registry is updated. It is restricted to the client's configured origin and keeps credentials out of query strings. Prefer `execute()` / `execute_named()` for registered routes because the registry supplies the correct retry policy. ## Reference * [V3 Data API](/data/overview) * [Combos](/data/combos/overview) * [Fees](/data/fees/overview) * [Perps](/perps/overview) * [Webhooks](/webhooks/overview) # Settlement and Event Streams Source: https://docs.polynode.dev/sdks/websocket-streaming Subscribe to settlements and other PolyNode events with typed filtering, acknowledgements, reconnect replay, deduplication, and explicit cleanup. The event WebSocket is the fastest path from a detected Polymarket fill to your application. A `settlements` subscription emits: * `settlement` when PolyNode detects a matching transaction, with `status` set to `pending` or `confirmed` * `status_update` when a previously pending transaction is confirmed on-chain The SDK waits for the server's subscription acknowledgement before returning the subscription. It then routes typed events to handlers or an async iterator. ## Subscribe to settlements > [tab] TypeScript > > ```typescript theme={null} > import { PolyNode } from 'polynode-sdk'; > > const apiKey = process.env.POLYNODE_API_KEY; > if (!apiKey) throw new Error('Set POLYNODE_API_KEY'); > const pn = new PolyNode({ apiKey }); > > const sub = await pn.ws > .subscribe('settlements') > .status('all') > .snapshotCount(25) > .send(); > > sub.on('settlement', (event) => { > console.log(event.status, event.tx_hash, event.taker_side, event.taker_size); > }); > sub.on('status_update', (event) => { > console.log('confirmed', event.tx_hash, event.block_number); > }); > > process.once('SIGINT', () => { > sub.unsubscribe(); > pn.ws.disconnect(); > }); > ``` > [tab] Python > > ```python theme={null} > import asyncio > import os > from polynode import AsyncPolyNode > > async def main() -> None: > async with AsyncPolyNode(api_key=os.environ["POLYNODE_API_KEY"]) as pn: > sub = await ( > pn.ws.subscribe("settlements") > .status("all") > .snapshot_count(25) > .send() > ) > try: > async for event in sub: > if event.event_type == "settlement": > print(event.status, event.tx_hash, event.taker_size) > elif event.event_type == "status_update": > print("confirmed", event.tx_hash, event.block_number) > finally: > sub.unsubscribe() > pn.ws.disconnect() > > asyncio.run(main()) > ``` > [tab] Rust > > ```rust theme={null} > use polynode::{PolyNodeClient, PolyNodeEvent, WsMessage}; > use polynode::ws::{StreamOptions, Subscription, SubscriptionType}; > > #[tokio::main] > async fn main() -> polynode::Result<()> { > let client = PolyNodeClient::new( > std::env::var("POLYNODE_API_KEY").expect("Set POLYNODE_API_KEY") > )?; > let mut stream = client.stream(StreamOptions::default()).await?; > let ack = stream.subscribe_with_ack( > Subscription::new(SubscriptionType::Settlements) > .status("all") > .snapshot_count(25), > ).await?; > println!("subscription {}", ack.subscription_id); > > while let Some(message) = stream.next().await { > match message? { > WsMessage::Event(PolyNodeEvent::Settlement(event)) => { > println!("{:?} {} {}", event.status, event.tx_hash, event.taker_size); > } > WsMessage::Event(PolyNodeEvent::StatusUpdate(event)) => { > println!("confirmed {} in {}", event.tx_hash, event.block_number); > } > WsMessage::Replay(notice) => eprintln!("{}", notice.warning), > _ => {} > } > } > stream.close().await?; > Ok(()) > } > ``` `snapshotCount` / `snapshot_count` returns recent matching events before live delivery. Set it only when your application benefits from a warm start. ## Filter at the server Filters reduce bandwidth and work before events reach your process. | Filter | TypeScript | Python | Rust | Use | | - | - | - | - | - | | Wallets | `.wallets([...])` | `.wallets([...])` | `.wallets(vec![...])` | maker or taker addresses | | Tokens | `.tokens([...])` | `.tokens([...])` | `.tokens(vec![...])` | outcome token IDs | | Market slugs | `.slugs([...])` | `.slugs([...])` | `.slugs(vec![...])` | exact market slugs | | Conditions | `.conditionIds([...])` | `.condition_ids([...])` | `.condition_ids(vec![...])` | condition IDs | | Minimum / maximum size | `.minSize(n)` / `.maxSize(n)` | `.min_size(n)` / `.max_size(n)` | `.min_size(n)` / `.max_size(n)` | USD-size bounds | | Status | `.status('all')` | `.status('all')` | `.status("all")` | pending, confirmed, or both | | Replay cursor | `.since(ms)` | `.since(ms)` | `.since(ms)` | events newer than Unix milliseconds | Example wallet filter: > [tab] TypeScript > > ```typescript theme={null} > const sub = await pn.ws.subscribe('settlements') > .wallets(['0xabc...', '0xdef...']) > .minSize(1000) > .status('all') > .send(); > ``` > [tab] Python > > ```python theme={null} > sub = await ( > pn.ws.subscribe("settlements") > .wallets(["0xabc...", "0xdef..."]) > .min_size(1000) > .status("all") > .send() > ) > ``` > [tab] Rust > > ```rust theme={null} > let ack = stream.subscribe_with_ack( > Subscription::new(SubscriptionType::Settlements) > .wallets(vec!["0xabc...".into(), "0xdef...".into()]) > .min_size(1000.0) > .status("all"), > ).await?; > ``` See [Subscribing](/websocket/subscribing) for preset-specific filter behavior. ## Presets The SDKs use the same subscription names: | Preset | Typical events | | - | - | | `settlements` | settlement detection and confirmation updates | | `trades` | settlements, confirmed trades, status updates | | `dome` / `fills` | normalized per-fill events | | `combos` | combo executions and status updates | | `redemptions` / `redemption` | redemptions | | `wallets` | settlement, trade, position, deposit, conversion, and redemption activity for selected wallets | | `markets` | activity for selected markets | | `large_trades` | settlement and trade events above a size threshold | | `blocks` | block summaries | | `oracle` | oracle lifecycle events | | `chainlink` | spot or explicit TWAP price events | | `global` | the default public event set; combo events require `combos` | ## Acknowledgements Do not assume a subscription is active before the SDK's subscribe call resolves. The acknowledgement includes the server-assigned subscription ID and may include warnings. For Chainlink subscriptions it also reports the selected price source and explicit TWAP windows: > [tab] TypeScript > > ```typescript theme={null} > const prices = await pn.ws.subscribe('chainlink') > .feeds(['BTC/USD']) > .twapWindows([30]) > .send(); > > console.log(prices.id, prices.priceSource, prices.twapWindows, prices.warnings); > ``` > [tab] Python > > ```python theme={null} > prices = await ( > pn.ws.subscribe("chainlink") > .feeds(["BTC/USD"]) > .twap_windows([30]) > .send() > ) > print(prices.id, prices.price_source, prices.twap_windows, prices.warnings) > ``` > [tab] Rust > > ```rust theme={null} > let ack = stream.subscribe_with_ack( > Subscription::new(SubscriptionType::Chainlink) > .feeds(vec!["BTC/USD".into()]) > .twap_windows(vec![30]), > ).await?; > println!("{:?} {:?} {:?}", ack.price_source, ack.twap_windows, ack.warnings); > ``` One event-stream connection can carry several normal subscriptions. Chainlink feed and TWAP selection is connection-scoped, so combine all desired Chainlink feeds and windows in one Chainlink subscription on that connection. Use another connection for a different selection. ## Reconnect behavior Automatic reconnect is enabled by default. After a disconnect, the SDK: 1. opens a replacement socket 2. resubscribes each active subscription with its original filters 3. adds a best-effort `since` cursor based on the latest accepted event 4. overlaps the cursor slightly and removes duplicate delivery in the client 5. reports replay state to your application This reduces avoidable gaps, but it is not an unlimited gapless guarantee. Server history is bounded, and a disconnect can outlast it. Treat every replay notice as an observable recovery interval. > [tab] TypeScript > > ```typescript theme={null} > pn.ws.onReplay((notice) => { > console.warn(notice.phase, notice.since, notice.guaranteed, notice.warning); > }); > pn.ws.onReconnect((attempt) => console.warn('reconnected', attempt)); > pn.ws.onError((error) => console.error(error.message)); > ``` > [tab] Python > > ```python theme={null} > pn.ws.on_replay( > lambda notice: print( > notice.phase, notice.since, notice.guaranteed, notice.warning > ) > ) > pn.ws.on_reconnect(lambda attempt: print("reconnected", attempt)) > pn.ws.on_error(lambda error: print(error)) > ``` > [tab] Rust > > ```rust theme={null} > match message? { > WsMessage::Replay(notice) => { > eprintln!("{} (guaranteed={})", notice.warning, notice.guaranteed); > } > WsMessage::Error { code, message } => eprintln!("{code:?}: {message}"), > _ => {} > } > ``` > [!NOTE] > > Managed short-form streams also reconnect at every market boundary. That deliberate rotation is required to replace the old market slugs and connection-scoped Chainlink selection. See [Short-form and TWAP](/sdks/short-form). ## Slow consumers TypeScript and Python async iterators use a bounded per-subscription queue. Register an overflow callback if processing may fall behind: > [tab] TypeScript > > ```typescript theme={null} > sub.onOverflow((notice) => { > console.error('dropped events', notice.droppedEvents, notice.queueCapacity); > }); > ``` > [tab] Python > > ```python theme={null} > sub.on_overflow( > lambda notice: print("dropped events", notice.dropped_events) > ) > ``` > [tab] Rust > > Rust applies backpressure to the bounded stream instead of silently evicting settlement events. Keep the `next()` loop lightweight and hand expensive work to a bounded worker queue. Handler callbacks are still invoked immediately. Queue overflow applies to the async-iterator buffer. ## Forward-compatible events New event types do not disappear merely because your SDK predates their typed model: * TypeScript emits an `unknown` event containing `wire_event_type`, `raw`, and an optional decode error. * Python yields `UnknownEvent` with the complete raw payload. * Rust emits `WsMessage::UnknownEvent` or `WsMessage::UnknownMessage`. Log the event type and upgrade the SDK; avoid logging credentials or an entire payload when it may contain user data. ## Cleanup Stop subscriptions and close their owning socket during shutdown: > [tab] TypeScript > > ```typescript theme={null} > sub.unsubscribe(); > pn.ws.disconnect(); > ``` > [tab] Python > > ```python theme={null} > sub.unsubscribe() > pn.ws.disconnect() > ``` > [tab] Rust > > ```rust theme={null} > stream.unsubscribe(Some(ack.subscription_id)).await?; > stream.close().await?; > ``` Next: [Short-form and Chainlink TWAP](/sdks/short-form) or the full [event reference](/websocket/overview). # builder_trade Source: https://docs.polynode.dev/webhooks/events/builder-trade Fires when a trade is routed through a specific builder. Monitor builder volume, attribution, and fee flow. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider exposes builder attribution on webhooks. ## Filters | Filter | Type | Required | Description | | - | - | - | - | | `builder_codes` | `string[]` | Yes | Builder codes to watch. These attribution tags are not wallet addresses. | | `min_amount_usd` | `number` | No | Minimum trade size in USD. | ## Payload Same schema as [`trade`](/webhooks/events/trade), with `"type": "builder_trade"`. ## Use Cases * Builders monitoring their own attributed trade volume * Builder competition analysis * Trader-paid fee-flow analysis per Builder # fee_earned Source: https://docs.polynode.dev/webhooks/events/fee-earned Fires when a fee receiver gets paid. Track builder revenue, market maker fees, or protocol fee flows. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers this event type. ## Filters | Filter | Type | Description | | - | - | - | | `receiver_addresses` | `string[]` | Fee receiver addresses to watch. Max 500. Empty = all receivers. | | `min_fee_usd` | `number` | Minimum fee amount in USD. | ## Payload ```json theme={null} { "id": "evt_c1d2e3f4-5a6b-7c8d-9e0f-1a2b3c4d5e6f", "type": "fee_earned", "created_at": "2026-05-14T15:09:13.123456789+00:00", "data": { "receiver": "0x115f48dc2a731aa16251c6d6e1befc42f92accc9", "fee_usd": 0.00069, "transaction_hash": "0x8a76e72ea10587303469998405da67323d33cbab8bda053db3091b3935011b42", "timestamp": "1778770048" } } ``` ## Fields | Field | Type | Description | | - | - | - | | `receiver` | `string` | Fee receiver wallet address | | `fee_usd` | `number` | Fee amount in USD | | `transaction_hash` | `string` | On-chain transaction hash | | `timestamp` | `string` | Unix timestamp | ## Use Cases * Builders monitoring their own fee revenue in real-time * Market makers tracking fee income across markets * Protocol analytics tracking fee distribution * Revenue dashboards with instant updates ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/fees", "event_types": ["fee_earned"], "filters": { "receiver_addresses": ["0x115f48dc2a731aa16251c6d6e1befc42f92accc9"], "min_fee_usd": 1.0 } }' ``` # first_trade Source: https://docs.polynode.dev/webhooks/events/first-trade Fires when a wallet makes its first-ever Polymarket trade. Detect new market participants. ## Filters | Filter | Type | Description | | - | - | - | | `min_amount_usd` | `number` | Minimum trade size for the first trade. | ## Payload Same schema as [`trade`](/webhooks/events/trade), with `"type": "first_trade"`. ## Use Cases * Growth analytics: track new user onboarding rate * Welcome flows: trigger onboarding automations for new traders * Smart money detection: flag large first trades (potential whale entry) # large_trade Source: https://docs.polynode.dev/webhooks/events/large-trade Fires when any trade exceeds your USD threshold. No wallet filter required — catches whale trades across all markets. ## Filters | Filter | Type | Required | Description | | - | - | - | - | | `min_amount_usd` | `number` | **Yes** | Minimum trade size in USD | | `condition_ids` | `string[]` | No | Restrict to specific markets | | `event_slugs` | `string[]` | No | Restrict to specific events | | `tags` | `string[]` | No | Restrict to tagged markets | ## Payload Same schema as [`trade`](/webhooks/events/trade), with `"type": "large_trade"`. ```json theme={null} { "id": "evt_b3f2a1c0-8d4e-4f2a-9c1b-2e3f4a5b6c7d", "type": "large_trade", "created_at": "2026-05-14T14:56:30.123456789+00:00", "data": { "amount_usd": 1205.28, "price": 0.87, "direction": "BUY", "market": "Will Hyperliquid reach $48 in May?", "slug": "will-hyperliquid-reach-48-in-may", "outcome": "No", "maker": "0x337b7fca244bf2ef3272469ee02a2bd541097e26", "taker": "0x04b6d7e930cf9e493c5e6ef24b496294f95594c8", "condition_id": "0x...", "transaction_hash": "0x...", "order_hash": "0x...", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "fee_usd": 0.0, "timestamp": "1778770590" } } ``` ## Use Cases * Whale alert bots (Discord, Telegram) * Smart money tracking * Unusual activity detection * Market sentiment signals ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-bot.com/whale-alerts", "event_types": ["large_trade"], "filters": { "min_amount_usd": 500, "tags": ["politics"] } }' ``` ## Verified Behavior * Threshold is inclusive: a \$500.00 trade fires on `min_amount_usd: 500` * Trades below the threshold are silently skipped * Enrichment (market, outcome, slug) included on every delivery # market_created Source: https://docs.polynode.dev/webhooks/events/market-created Fires when a new prediction market appears on Polymarket. ## Filters | Filter | Type | Description | | - | - | - | | `tags` | `string[]` | Only markets with these tags. Max 20. | | `event_slugs` | `string[]` | Only markets in these events. Max 50. | Empty filters = all new markets. ## Payload ```json theme={null} { "id": "evt_f6a7b8c9-0d1e-2f3a-4b5c-6d7e8f9a0b1c", "type": "market_created", "created_at": "2026-05-14T15:11:00.000000000+00:00", "data": { "condition_id": "0x9622da56d800d10c93c58fe2f6fc19521b3152bc7f9e21fe97979b39749bc58b", "question": "Will Ethereum reach $5000 by June 2026?", "slug": "will-ethereum-reach-5000-june-2026", "event_slug": "crypto-june-2026", "tags": "{crypto,ethereum}", "image_url": "https://polymarket-upload.s3.us-east-2.amazonaws.com/...", "created_at": "2026-05-14 15:10:45.123456" } } ``` ## Use Cases * Market discovery: automatically list new markets on your trading UI * Analytics: track market creation patterns and categories * Alert bots: notify users when markets matching their interests appear ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/new-markets", "event_types": ["market_created"], "filters": { "tags": ["crypto"] } }' ``` # market_resolved Source: https://docs.polynode.dev/webhooks/events/market-resolved Fires when a Polymarket market is resolved. Get the winning outcome, payouts, and market details instantly. ## Filters | Filter | Type | Description | | - | - | - | | `condition_ids` | `string[]` | Specific markets to watch. Max 100. | | `event_slugs` | `string[]` | Events to watch (e.g. `us-presidential-election`). Max 50. | | `tags` | `string[]` | Tags to watch (e.g. `politics`, `crypto`). Max 20. | Empty filters = all resolutions. ## Payload ```json theme={null} { "id": "evt_e5f6a7b8-9c0d-1e2f-3a4b-5c6d7e8f9a0b", "type": "market_resolved", "created_at": "2026-05-14T15:10:30.000000000+00:00", "data": { "condition_id": "0x0ecb24de3a8b875cf80ad087a40be0c86ba47e455e89519cf46ee98361769316", "question": "Will Bitcoin reach $100k in May 2026?", "slug": "will-bitcoin-reach-100k-may-2026", "payout_numerators": "{1,0}", "payout_denominator": "1", "resolved_at": "1778770810000", "event_slug": "crypto-may-2026", "tags": "{crypto,bitcoin}" } } ``` ## Fields | Field | Type | Description | | - | - | - | | `condition_id` | `string` | Market condition ID | | `question` | `string` | Market question (enriched) | | `slug` | `string` | Market slug (enriched) | | `payout_numerators` | `string` | Payout array — `{1,0}` means Yes won, `{0,1}` means No won | | `payout_denominator` | `string` | Denominator for payout calculation | | `resolved_at` | `string` | Resolution timestamp (unix milliseconds) | | `event_slug` | `string` | Parent event slug | | `tags` | `string` | Market tags | ## Use Cases * Auto-redemption bots: trigger redemptions immediately after resolution * Settlement alerts: notify users when their markets resolve * Analytics pipelines: track resolution patterns and outcomes ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/resolutions", "event_types": ["market_resolved"], "filters": { "tags": ["politics"] } }' ``` # merge Source: https://docs.polynode.dev/webhooks/events/merge Fires when a wallet merges conditional tokens. Inverse of split — tokens combined back into collateral. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers merge event webhooks. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallets to watch. Max 500. | | `condition_ids` | `string[]` | Markets to watch. Max 100. | ## Payload Same schema as [`split`](/webhooks/events/split), with `"type": "merge"`. # neg_risk_conversion Source: https://docs.polynode.dev/webhooks/events/neg-risk-conversion Fires on neg-risk conversion events. Track hedging activity in multi-outcome markets. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers NRC event webhooks. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallets to watch. Max 500. | ## Payload ```json theme={null} { "id": "evt_e5f6a7b8-9c0d-1e2f-3a4b-5c6d7e8f9a0b", "type": "neg_risk_conversion", "created_at": "2026-05-14T15:18:00.000000000+00:00", "data": { "wallet": "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5", "market_id": "0xabc123...", "timestamp": "1778771000" } } ``` ## Use Cases * Risk tracking: NRC events signal hedging in multi-outcome markets (elections, sports) * Portfolio reconciliation: NRC changes on-chain token balances * Derivatives analytics: track neg-risk position flows # order_complete Source: https://docs.polynode.dev/webhooks/events/order-complete Fires when a multi-fill order finishes. One aggregated event per order instead of N individual fills. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider aggregates partial fills into order-level events. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallets to watch (maker or taker on any fill). Max 500. | | `min_total_usd` | `number` | Minimum total order size in USD. | ## How It Works When an order is filled across multiple transactions, polynode buffers the individual fills. After 30 seconds with no new fills for that `order_hash`, the buffered fills are aggregated and delivered as a single event. ## Payload ```json theme={null} { "id": "evt_f6a7b8c9-0d1e-2f3a-4b5c-6d7e8f9a0b1c", "type": "order_complete", "created_at": "2026-05-14T15:19:00.000000000+00:00", "data": { "order_hash": "0x608029a5926da1fc3496ba08062c7e64f66b41a2c7383b5125f3867a68ca0b08", "fill_count": 12, "total_usd": 4850.75, "fills": [ { "amount_usd": 500.0, "price": 0.62, "market": "Will Bitcoin hit $100k by 2026?", "outcome": "Yes", "timestamp": "1778770502" } ] } } ``` ## Fields | Field | Type | Description | | - | - | - | | `order_hash` | `string` | The CLOB order hash | | `fill_count` | `number` | Number of partial fills aggregated | | `total_usd` | `number` | Total USD value across all fills | | `fills` | `array` | Individual fill details | ## Use Cases * Order tracking: get one notification per order, not per fill * Execution analysis: see total fill count, slippage, and average price * Copy-trading: detect when a leader's order is fully filled # pnl_change Source: https://docs.polynode.dev/webhooks/events/pnl-change Fires when a wallet's realized PnL changes. Track profit milestones, loss alerts, and performance shifts. ## Filters | Filter | Type | Required | Description | | - | - | - | - | | `wallet_addresses` | `string[]` | **Yes** | Wallets to watch. Max 500. | | `min_pnl_change_usd` | `number` | Recommended | Minimum PnL delta to trigger. | ## Payload ```json theme={null} { "id": "evt_b2c3d4e5-6f7a-8b9c-0d1e-2f3a4b5c6d7e", "type": "pnl_change", "created_at": "2026-05-14T15:15:00.000000000+00:00", "data": { "wallet": "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5", "token_id": "83970135942868582996575481879514955574496723508450032076038091728966335782753", "realized_pnl": 22053845.83, "market": "Will Bitcoin hit $100k by 2026?", "outcome": "Yes" } } ``` ## Use Cases * Leader tracking: alert when top traders cross PnL milestones * Risk monitoring: detect sudden losses in watched portfolios * Copy-trading signals: PnL changes indicate trade activity # position_status_change Source: https://docs.polynode.dev/webhooks/events/position-status-change Fires when a watched wallet's CTF position changes state, including first observed opens. > [!NOTE] > > **Beta / polynode exclusive** — this event watches explicit wallet filters and detects CTF position lifecycle changes from on-chain ERC-1155 transfer deltas. ## What It Detects `position_status_change` tracks state transitions for watched wallets: * `none` -> `open` when the wallet first receives shares for a token after the webhook is active * `open` -> `closed` when the wallet's active-market balance returns to zero * `open` -> `redeemable` or `none` -> `redeemable` when the position is in a resolved market and the wallet holds shares * `redeemable` -> `redeemed` when the resolved-market balance returns to zero Existing positions are seeded when a new watched wallet is first seen, so the webhook does not backfill historical opens that happened before registration. It emits future transitions from that point forward. > [!WARNING] > > For this beta, `wallet_addresses` is required. Unfiltered/global position-status webhooks are intentionally not enabled. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Required. Wallets to watch. Use lowercase `0x` addresses. Max 500. | | `token_ids` | `string[]` | Optional outcome token IDs. | | `condition_ids` | `string[]` | Optional market condition IDs. | | `event_slugs` | `string[]` | Optional parent event slugs. | | `tags` | `string[]` | Optional tag filters. | | `status_from` | `string` | Optional previous status: `none`, `open`, `closed`, `redeemable`, or `redeemed`. | | `status_to` | `string` | Optional new status: `open`, `closed`, `redeemable`, or `redeemed`. | Use `status_from: "none"` and `status_to: "open"` to detect a wallet opening a new position after registration. ## Payload ```json theme={null} { "id": "evt_c3d4e5f6-7a8b-9c0d-1e2f-3a4b5c6d7e8f", "type": "position_status_change", "created_at": "2026-05-26T12:00:00.000000000+00:00", "data": { "wallet": "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5", "token_id": "83970135942868582996575481879514955574496723508450032076038091728966335782753", "condition_id": "0x3b7ad6a803daeb1994c840027b95d711d634e79a09ff3b02625600dc9d31a8bc", "from_status": "none", "to_status": "open", "previous_amount": 0, "new_amount": 150, "delta_amount": 150, "transfer_amount": 150, "source": "erc1155_transfer", "raw_event_type": "TransferSingle", "source_event_id": "0x4f606b3d4c58c723e4aeb3051e3ba92100f9b0d9116e5d60f7668c34087c8167_621", "transaction_hash": "0x4f606b3d4c58c723e4aeb3051e3ba92100f9b0d9116e5d60f7668c34087c8167", "block_number": 87481303, "timestamp": "2026-05-26T10:58:22.000000+00:00", "market": "Will Bitcoin hit $100k by 2026?", "slug": "will-bitcoin-hit-100k-by-2026", "event_slug": "bitcoin-100k-2026", "outcome": "Yes", "tags": "{Crypto,Bitcoin}" } } ``` ## Fields | Field | Type | Description | | - | - | - | | `wallet` | `string` | Watched wallet address. | | `token_id` | `string` | ERC-1155 outcome token ID. | | `condition_id` | `string` | Market condition ID. | | `from_status` | `string` | Previous tracked state. `none` means no prior tracked balance/state. | | `to_status` | `string` | New tracked state. | | `previous_amount` | `number` | Previous share balance, scaled to normal token units. | | `new_amount` | `number` | New share balance, scaled to normal token units. | | `delta_amount` | `number` | Signed balance change for the watched wallet. | | `transfer_amount` | `number` | Absolute transfer amount from the ERC-1155 event. | | `source` | `string` | `erc1155_transfer`, `split`, `merge`, or `redemption`. | | `raw_event_type` | `string` | Raw ERC-1155 event type. | | `source_event_id` | `string` | Source CTF transfer-delta ID. | | `transaction_hash` | `string` | Polygon transaction hash. | | `block_number` | `number` | Polygon block number. | | `timestamp` | `string` | Source ingestion timestamp. | | `market` | `string` | Market question, when enrichment is available. | | `slug` | `string` | Market slug, when enrichment is available. | | `event_slug` | `string` | Parent event slug. | | `outcome` | `string` | Outcome label. | | `tags` | `string` | Market tag array as text. | ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/position-opened", "event_types": ["position_status_change"], "filters": { "wallet_addresses": ["0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5"], "status_from": "none", "status_to": "open" }, "description": "Notify when a watched wallet opens a new Polymarket position" }' ``` ## Use Cases * Copy-trading: detect when a leader opens a new position, including opens that come from ERC-1155 transfers * Portfolio automation: react when a watched wallet fully exits a position * Settlement workflows: detect redemption-style zero-balance transitions for resolved markets # price_change Source: https://docs.polynode.dev/webhooks/events/price-change Fires when a token's price changes. Track price movements across any market. ## Filters | Filter | Type | Required | Description | | - | - | - | - | | `token_ids` | `string[]` | No | Specific tokens to watch. Max 100. | | `condition_ids` | `string[]` | No | Markets to watch (all tokens in market). Max 100. | | `min_delta_pct` | `number` | Recommended | Minimum price change percentage to trigger. | > [!WARNING] > > Without `min_delta_pct`, this event fires on every price update — potentially thousands per minute. Set a threshold to avoid overwhelming your endpoint. ## Payload ```json theme={null} { "id": "evt_a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d", "type": "price_change", "created_at": "2026-05-14T15:12:00.000000000+00:00", "data": { "token_id": "83970135942868582996575481879514955574496723508450032076038091728966335782753", "price": 0.81, "updated_at": "2026-05-14 15:11:55.123456", "market": "Will Al Fateh Saudi Club vs. Al Najmah Saudi Club end in a draw?", "slug": "spl-fat-njm-2026-05-14-draw", "outcome": "No", "condition_id": "0x3b7ad6a803daeb1994c840027b95d711d634e79a09ff3b02625600dc9d31a8bc" } } ``` ## Use Cases * Price alert bots: notify when a market moves significantly * Arbitrage monitoring: detect price discrepancies * Portfolio dashboards: real-time position value updates ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/prices", "event_types": ["price_change"], "filters": { "condition_ids": ["0x9622da56d800d10c93c58fe2f6fc19521b3152bc7f9e21fe97979b39749bc58b"], "min_delta_pct": 5.0 } }' ``` # redemption Source: https://docs.polynode.dev/webhooks/events/redemption Fires when a wallet redeems shares from a resolved market. Know instantly when a leader cashes out. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers this event type. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallet addresses to watch. Max 500. | | `condition_ids` | `string[]` | Market condition IDs. Max 100. | ## Payload ```json theme={null} { "id": "evt_d4e5f6a7-8b9c-0d1e-2f3a-4b5c6d7e8f9a", "type": "redemption", "created_at": "2026-05-14T15:10:00.000000000+00:00", "data": { "wallet": "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5", "condition_id": "0x7fb0835c4c761fa690ec4603eb444d080e472193ae477aa3c57f273d44dbddd9", "timestamp": "1778771000", "market": "Will Bitcoin hit $100k by 2026?", "outcome": "Yes" } } ``` ## Use Cases * Copy-trading bots: know when a leader redeems (position fully closed at settlement) * Settlement tracking: monitor which wallets are claiming payouts * Capital flow analysis: redemptions unlock USDC that may be reinvested ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/redemptions", "event_types": ["redemption"], "filters": { "wallet_addresses": ["0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5"] } }' ``` # split Source: https://docs.polynode.dev/webhooks/events/split Fires when a wallet splits conditional tokens. Track collateral movements and position restructuring. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers split event webhooks. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallets to watch. Max 500. | | `condition_ids` | `string[]` | Markets to watch. Max 100. | ## Payload ```json theme={null} { "id": "evt_d4e5f6a7-8b9c-0d1e-2f3a-4b5c6d7e8f9a", "type": "split", "created_at": "2026-05-14T15:17:00.000000000+00:00", "data": { "wallet": "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5", "condition_id": "0x7fb0835c4c761fa690ec4603eb444d080e472193ae477aa3c57f273d44dbddd9", "amount": 5000.0, "timestamp": "1778771000", "market": "Will Bitcoin hit $100k by 2026?" } } ``` ## Use Cases * Position tracking: splits indicate position restructuring * Portfolio reconciliation: track collateral movements * Copy-trading: detect complex position management by leaders # trade Source: https://docs.polynode.dev/webhooks/events/trade Fires when a fill occurs involving wallets or markets you're watching. ## Filters | Filter | Type | Description | | - | - | - | | `wallet_addresses` | `string[]` | Wallet addresses to watch (maker or taker). Max 500. | | `token_ids` | `string[]` | Outcome token IDs. Max 100. | | `condition_ids` | `string[]` | Market condition IDs. Max 100. | | `event_slugs` | `string[]` | Event slugs (e.g. `us-presidential-election`). Max 50. | | `tags` | `string[]` | Tag filters (e.g. `politics`, `crypto`). Max 20. | | `min_amount_usd` | `number` | Minimum trade size in USD. | | `side` | `string` | Filter by side: `"BUY"` or `"SELL"`. | If a filter is empty or omitted, it matches all values for that dimension. Multiple filters are AND'd together. ## Payload ```json theme={null} { "id": "evt_a60234f0-fe5d-4223-bc6a-75f1e4263eda", "type": "trade", "created_at": "2026-05-14T14:55:08.448161187+00:00", "data": { "id": "0x4f606b3d4c58c723e4aeb3051e3ba92100f9b0d9116e5d60f7668c34087c8167_621", "maker": "0x6d3c5bd13984b2de47c3a88ddc455309aab3d294", "taker": "0xd5bba58c09d18f48a71a3aefc4ff3a66954c0fe1", "amount_usd": 39.99, "price": 0.81, "fee_usd": 0.0, "direction": "BUY", "token_id": "83970135942868582996575481879514955574496723508450032076038091728966335782753", "market": "Will Al Fateh Saudi Club vs. Al Najmah Saudi Club end in a draw?", "slug": "spl-fat-njm-2026-05-14-draw", "outcome": "No", "condition_id": "0x3b7ad6a803daeb1994c840027b95d711d634e79a09ff3b02625600dc9d31a8bc", "event_slug": "spl-fat-njm-2026-05-14", "transaction_hash": "0x4f606b3d4c58c723e4aeb3051e3ba92100f9b0d9116e5d60f7668c34087c8167", "order_hash": "0x608029a5926da1fc3496ba08062c7e64f66b41a2c7383b5125f3867a68ca0b08", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "timestamp": "1778770502" } } ``` ## Fields | Field | Type | Description | | - | - | - | | `id` | `string` | Fill ID (`{tx_hash}_{log_index}`) | | `maker` | `string` | Maker wallet address | | `taker` | `string` | Taker wallet address | | `amount_usd` | `number` | Trade size in USD | | `price` | `number` | Token price (0.0 to 1.0) | | `fee_usd` | `number` | Fee in USD | | `direction` | `string` | `"BUY"` or `"SELL"` (maker's limit order direction) | | `token_id` | `string` | ERC-1155 outcome token ID | | `market` | `string` | Market question (enriched) | | `slug` | `string` | Market slug (enriched) | | `outcome` | `string` | Outcome name — `"Yes"`, `"No"`, or specific outcome (enriched) | | `condition_id` | `string` | Market condition ID | | `event_slug` | `string` | Parent event slug | | `transaction_hash` | `string` | On-chain transaction hash | | `order_hash` | `string` | CLOB order hash | | `builder` | `string` | Builder address (all zeros if no builder) | | `timestamp` | `string` | Unix timestamp | ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/trades", "event_types": ["trade"], "filters": { "wallet_addresses": ["0x6d3c5bd13984b2de47c3a88ddc455309aab3d294"], "min_amount_usd": 50 } }' ``` # wallet_activity Source: https://docs.polynode.dev/webhooks/events/wallet-activity Fires on any action by a watched wallet — trades, redemptions, splits, merges, and neg-risk conversions. One webhook replaces five. > [!NOTE] > > **polynode exclusive** — no other Polymarket data provider offers this event type. ## Filters | Filter | Type | Required | Description | | - | - | - | - | | `wallet_addresses` | `string[]` | **Yes** | Wallet addresses to watch. Max 500. | ## Payload The payload matches the underlying event type, with an additional `activity_type` field. ```json theme={null} { "id": "evt_f8a21c4d-3e5b-4a2f-b1c0-9d8e7f6a5b4c", "type": "wallet_activity", "created_at": "2026-05-14T14:55:08.123456789+00:00", "data": { "activity_type": "trade", "id": "0x6c70140012dea826e1d0d9e5371b85387f6307da03166f5c0146efbfa2636644_1005", "maker": "0x6d3c5bd13984b2de47c3a88ddc455309aab3d294", "taker": "0x84cfffc3f16dcc353094de30d4a45226eccd2f63", "amount_usd": 1.45, "price": 0.36, "direction": "BUY", "market": "Will US Lecce win on 2026-05-17?", "slug": "sea-sas-lec-2026-05-17-lec", "outcome": "Yes", "condition_id": "0x9622da56d800d10c93c58fe2f6fc19521b3152bc7f9e21fe97979b39749bc58b", "event_slug": "sea-sas-lec-2026-05-17", "transaction_hash": "0x6c70140012dea826e1d0d9e5371b85387f6307da03166f5c0146efbfa2636644", "order_hash": "0x7631f2317323ce2cdb1c2851d8f5ea898cd0e8711f03c2e1c1698ce7eb77b0db", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "fee_usd": 0.0, "timestamp": "1778770705" } } ``` ## Activity Types The `activity_type` field tells you which underlying event fired: | Value | Activity | Description | | - | - | - | | `trade` | trade fill | Wallet was maker or taker | | `redemption` | redemption | Wallet redeemed shares | | `split` | split | Wallet split tokens | | `merge` | merge | Wallet merged tokens | | `neg_risk_conversion` | neg\_risk\_conversion | NRC event | ## Use Cases * Copy-trading bots that need a single feed per leader wallet * Portfolio trackers monitoring all wallet activity * Alert systems that fire on any wallet movement ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/wallet", "event_types": ["wallet_activity"], "filters": { "wallet_addresses": [ "0x6d3c5bd13984b2de47c3a88ddc455309aab3d294", "0xdb27bf2ac5d428a9c63dbc910c5e6e75560c0ae5" ] } }' ``` # Create Webhook Source: https://docs.polynode.dev/webhooks/management/create Register a new webhook to receive event notifications. ## Endpoint ``` POST /v3/webhooks ``` ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `url` | `string` | **Yes** | Delivery URL (must start with `https://`) | | `event_types` | `string[]` | **Yes** | Event types to subscribe to (see [event types](/webhooks/overview#event-types)) | | `filters` | `object` | No | Filter criteria (see below) | | `secret` | `string` | No | HMAC signing secret. Auto-generated if omitted. | | `description` | `string` | No | Human-readable label | ### Filter Object All filter fields are optional. Empty or omitted filters match everything for that dimension. Multiple filters are AND'd together. ```json theme={null} { "wallet_addresses": ["0x1234..."], "token_ids": ["12345..."], "condition_ids": ["0xabcd..."], "event_slugs": ["us-presidential-election"], "tags": ["politics", "crypto"], "builder_codes": ["0x5678..."], "receiver_addresses": ["0x9abc..."], "min_amount_usd": 100, "min_fee_usd": 1.0, "min_delta_pct": 5.0, "min_pnl_change_usd": 50.0, "min_total_usd": 500, "side": "BUY" } ``` ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/polymarket", "event_types": ["trade", "redemption"], "filters": { "wallet_addresses": ["0x6d3c5bd13984b2de47c3a88ddc455309aab3d294"], "min_amount_usd": 100 }, "description": "Track whale trades and redemptions" }' ``` ## Response (201 Created) ```json theme={null} { "id": "wh_451e06ca0534", "url": "https://your-app.com/hooks/polymarket", "event_types": ["trade", "redemption"], "filters": { "wallet_addresses": ["0x6d3c5bd13984b2de47c3a88ddc455309aab3d294"], "min_amount_usd": 100 }, "secret": "whsec_0e4535d1565e4e4d9e24debf3e40f836", "active": true, "description": "Track whale trades and redemptions", "created_at": "2026-05-14T14:54:08.019035820+00:00" } ``` > [!WARNING] > > Save the `secret` value — it is only returned on creation. You'll need it to verify webhook signatures. # Delete Webhook Source: https://docs.polynode.dev/webhooks/management/delete Permanently delete a webhook and its delivery history. ## Endpoint ``` DELETE /v3/webhooks/:id ``` ## Example ```bash theme={null} curl -X DELETE https://api.polynode.dev/v3/webhooks/wh_451e06ca0534 \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ```json theme={null} { "deleted": true } ``` # Delivery History Source: https://docs.polynode.dev/webhooks/management/deliveries View the delivery history for a webhook — status codes, latency, errors, and retry attempts. ## Endpoint ``` GET /v3/webhooks/:id/deliveries?limit=50&offset=0 ``` ## Query Parameters | Param | Default | Description | | - | - | - | | `limit` | 50 | Max results (up to 200) | | `offset` | 0 | Pagination offset | ## Example ```bash theme={null} curl https://api.polynode.dev/v3/webhooks/wh_451e06ca0534/deliveries \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ```json theme={null} { "deliveries": [ { "event_type": "trade", "event_id": "evt_a1b2c3d4", "status_code": 200, "latency_ms": 142, "attempt": 1, "success": true, "error": null, "delivered_at": "2026-05-14T14:59:58+00:00" }, { "event_type": "trade", "event_id": "evt_b2c3d4e5", "status_code": null, "latency_ms": 5001, "attempt": 2, "success": false, "error": "error sending request for url (https://your-app.com/hooks): timeout", "delivered_at": "2026-05-14T14:59:45+00:00" } ], "count": 2 } ``` ## Fields | Field | Type | Description | | - | - | - | | `event_type` | `string` | The event type that triggered this delivery | | `event_id` | `string` | Unique event identifier | | `status_code` | `number\|null` | HTTP response status. `null` if the request failed before getting a response (timeout, connection refused). | | `latency_ms` | `number` | Round-trip time in milliseconds | | `attempt` | `number` | Delivery attempt number (1 = first try, 2+ = retries) | | `success` | `boolean` | `true` if HTTP 2xx received within 5 seconds | | `error` | `string\|null` | Error message on failure | | `delivered_at` | `string` | ISO timestamp of delivery attempt | Delivery history is retained for 7 days. # List Event Types Source: https://docs.polynode.dev/webhooks/management/event-types Retrieve all available webhook event types with descriptions and supported filters. ## Endpoint ``` GET /v3/webhooks/event-types ``` ## Example ```bash theme={null} curl https://api.polynode.dev/v3/webhooks/event-types \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ```json theme={null} { "event_types": [ { "name": "trade", "description": "Fill involving watched wallets or markets", "filters": ["wallet_addresses", "token_ids", "condition_ids", "event_slugs", "tags", "min_amount_usd", "side"], "exclusive": false }, { "name": "redemption", "description": "Wallet redeems shares from resolved market", "filters": ["wallet_addresses", "condition_ids"], "exclusive": true }, { "name": "position_status_change", "description": "Watched-wallet CTF position transitions, including first observed opens", "filters": ["wallet_addresses", "token_ids", "condition_ids", "event_slugs", "tags", "status_from", "status_to"], "exclusive": true } ] } ``` Events with `"exclusive": true` are only available through polynode. # Get Webhook Source: https://docs.polynode.dev/webhooks/management/get Retrieve one webhook subscription by id. ```text theme={null} GET /v3/webhooks/{id} ``` Returns the current configuration for a single webhook. ## Example ```bash theme={null} curl "https://api.polynode.dev/v3/webhooks/wh_451e06ca0534" \ -H "x-api-key: pn_live_..." ``` ```json theme={null} { "id": "wh_451e06ca0534", "url": "https://your-app.com/hooks/polymarket", "event_types": ["trade", "market_resolved"], "filters": { "wallet_addresses": ["0x6d3c5bd13984b2de47c3a88ddc455309aab3d294"], "min_amount_usd": 100 }, "description": "Track whale trades", "active": true, "created_at": "2026-05-14T14:55:08Z", "updated_at": "2026-05-14T14:55:08Z" } ``` ## Errors | Status | Meaning | | - | - | | `401` | Missing or invalid API key | | `404` | Webhook not found for this API key | # List Webhooks Source: https://docs.polynode.dev/webhooks/management/list List all webhooks registered to your API key. ## Endpoint ``` GET /v3/webhooks ``` ## Response ```json theme={null} { "webhooks": [ { "id": "wh_451e06ca0534", "url": "https://your-app.com/hooks/polymarket", "event_types": ["trade", "redemption"], "filters": { "wallet_addresses": ["0x6d3c..."], "min_amount_usd": 100 }, "active": true, "description": "Track whale trades", "has_secret": true, "created_at": "2026-05-14T14:54:08+00:00", "updated_at": "2026-05-14T14:54:08+00:00" } ], "count": 1 } ``` # Rotate Secret Source: https://docs.polynode.dev/webhooks/management/rotate-secret Generate a new HMAC signing secret for a webhook. ## Endpoint ``` POST /v3/webhooks/:id/rotate-secret ``` Generates a new signing secret. The old secret is immediately invalidated. Update your verification code before the next delivery arrives. ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks/wh_451e06ca0534/rotate-secret \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ```json theme={null} { "secret": "whsec_new_secret_value_here_32chars" } ``` > [!WARNING] > > Save this value immediately. It is only returned once. # Test Webhook Source: https://docs.polynode.dev/webhooks/management/test Send a test delivery to verify your endpoint is reachable and configured correctly. ## Endpoint ``` POST /v3/webhooks/:id/test ``` Sends a synthetic event with `"test": true` in the payload. The event type is the first one in your webhook's `event_types` list. ## Example ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks/wh_451e06ca0534/test \ -H "Authorization: Bearer YOUR_API_KEY" ``` ## Response ```json theme={null} { "delivered": true, "status_code": 200, "latency_ms": 89 } ``` ## Test Payload Your endpoint receives: ```json theme={null} { "id": "test_a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d", "type": "trade", "created_at": "2026-05-14T15:00:00+00:00", "data": { "test": true, "message": "This is a test delivery from polynode webhooks" } } ``` The delivery includes all standard webhook headers (`X-Webhook-ID`, `X-Webhook-Event`, `X-Webhook-Timestamp`, `X-Webhook-Signature`) so you can verify your signature validation logic. # Update Webhook Source: https://docs.polynode.dev/webhooks/management/update Update a webhook's URL, filters, event types, or active status. ## Endpoint ``` PUT /v3/webhooks/:id ``` ## Request Body All fields are optional. Only provided fields are updated. | Field | Type | Description | | - | - | - | | `url` | `string` | New delivery URL | | `event_types` | `string[]` | Replace event type subscriptions | | `filters` | `object` | Replace filter criteria | | `active` | `boolean` | Pause (`false`) or resume (`true`) | | `description` | `string` | Update label | ## Example — Pause a webhook ```bash theme={null} curl -X PUT https://api.polynode.dev/v3/webhooks/wh_451e06ca0534 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"active": false}' ``` ## Example — Change filters ```bash theme={null} curl -X PUT https://api.polynode.dev/v3/webhooks/wh_451e06ca0534 \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "filters": { "wallet_addresses": ["0xnewwallet..."], "min_amount_usd": 500 } }' ``` ## Response Returns the full updated webhook object (same schema as [List](/webhooks/management/list)). # Webhooks Source: https://docs.polynode.dev/webhooks/overview Push notifications for Polymarket events — trades, price changes, market resolutions, and more. ## Overview polynode webhooks deliver real-time event notifications to your HTTP endpoint. Instead of polling the API, register a webhook and receive a POST request whenever matching events occur. * **16 event types** covering trades, prices, markets, positions, and lifecycle events * **Enriched payloads** — every delivery includes market names, outcomes, slugs, and condition IDs * **HMAC-SHA256 signed** — verify every delivery with your webhook secret * **3-30 second polling** — event cadence depends on the event type * **Delivery transparency** — full history of every delivery attempt, status code, and latency ## Quick Start ### 1. Create a webhook ```bash theme={null} curl -X POST https://api.polynode.dev/v3/webhooks \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.com/hooks/polymarket", "event_types": ["trade", "market_resolved"], "filters": { "wallet_addresses": ["0x6d3c5bd13984b2de47c3a88ddc455309aab3d294"], "min_amount_usd": 100 }, "description": "Track whale trades" }' ``` ### 2. Receive deliveries Every delivery is a POST to your URL with this structure: ```json theme={null} { "id": "evt_a60234f0-fe5d-4223-bc6a-75f1e4263eda", "type": "trade", "created_at": "2026-05-14T14:55:08.448161187+00:00", "data": { "maker": "0x6d3c5bd13984b2de47c3a88ddc455309aab3d294", "taker": "0xd5bba58c09d18f48a71a3aefc4ff3a66954c0fe1", "amount_usd": 39.99, "price": 0.81, "direction": "BUY", "market": "Will Al Fateh Saudi Club vs. Al Najmah Saudi Club end in a draw?", "slug": "spl-fat-njm-2026-05-14-draw", "outcome": "No", "condition_id": "0x3b7ad6a803daeb1994c840027b95d711d634e79a09ff3b02625600dc9d31a8bc", "event_slug": "spl-fat-njm-2026-05-14", "transaction_hash": "0x4f606b3d4c58c723e4aeb3051e3ba92100f9b0d9116e5d60f7668c34087c8167", "order_hash": "0x608029a5926da1fc3496ba08062c7e64f66b41a2c7383b5125f3867a68ca0b08", "builder": "0x0000000000000000000000000000000000000000000000000000000000000000", "fee_usd": 0.0, "timestamp": "1778770502" } } ``` ### 3. Verify the signature Every delivery includes HMAC-SHA256 headers: ``` X-Webhook-ID: wh_451e06ca0534 X-Webhook-Event: trade X-Webhook-Timestamp: 1778770328 X-Webhook-Signature: sha256=3357c641560d55fb46edccb85d3daad3c8099806b7d5d5f60088afb759c0db29 ``` Verify with: ```python theme={null} import hmac, hashlib expected = hmac.new( secret.encode(), f"{timestamp}.{body}".encode(), hashlib.sha256 ).hexdigest() assert hmac.compare_digest(f"sha256={expected}", signature_header) ``` ## Event Types | Event | Description | Polling | Exclusive | | - | - | - | - | | [`trade`](/webhooks/events/trade) | Fill involving watched wallets or markets | 3s | | | [`large_trade`](/webhooks/events/large-trade) | Fill exceeding USD threshold | 3s | | | [`builder_trade`](/webhooks/events/builder-trade) | Fill routed through a specific builder | 3s | polynode only | | [`first_trade`](/webhooks/events/first-trade) | Wallet's first-ever Polymarket trade | 3s | | | [`price_change`](/webhooks/events/price-change) | Token price moves beyond threshold | 10s | | | [`market_resolved`](/webhooks/events/market-resolved) | Market resolved with payouts | 10s | | | [`market_created`](/webhooks/events/market-created) | New market appears | 30s | | | [`pnl_change`](/webhooks/events/pnl-change) | Wallet PnL changes beyond threshold | 15s | | | [`position_status_change`](/webhooks/events/position-status-change) | Watched-wallet position opens/exits | 30s | polynode only | | [`redemption`](/webhooks/events/redemption) | Wallet redeems shares | 15s | polynode only | | [`split`](/webhooks/events/split) | Wallet splits conditional tokens | 15s | polynode only | | [`merge`](/webhooks/events/merge) | Wallet merges conditional tokens | 15s | polynode only | | [`neg_risk_conversion`](/webhooks/events/neg-risk-conversion) | Neg-risk conversion event | 15s | polynode only | | [`fee_earned`](/webhooks/events/fee-earned) | Fee receiver gets paid | 15s | polynode only | | [`wallet_activity`](/webhooks/events/wallet-activity) | Any action by a watched wallet | 3-15s | polynode only | | [`order_complete`](/webhooks/events/order-complete) | Multi-fill order finishes | \~33s | polynode only | Events marked **polynode only** are exclusive to polynode — no other Polymarket data provider offers them. ## Management API | Method | Endpoint | Description | | - | - | - | | `POST` | `/v3/webhooks` | [Create webhook](/webhooks/management/create) | | `GET` | `/v3/webhooks` | [List webhooks](/webhooks/management/list) | | `GET` | `/v3/webhooks/:id` | [Get webhook](/webhooks/management/get) | | `PUT` | `/v3/webhooks/:id` | [Update webhook](/webhooks/management/update) | | `DELETE` | `/v3/webhooks/:id` | [Delete webhook](/webhooks/management/delete) | | `POST` | `/v3/webhooks/:id/test` | [Send test delivery](/webhooks/management/test) | | `POST` | `/v3/webhooks/:id/rotate-secret` | [Rotate secret](/webhooks/management/rotate-secret) | | `GET` | `/v3/webhooks/:id/deliveries` | [Delivery history](/webhooks/management/deliveries) | | `GET` | `/v3/webhooks/event-types` | [List event types](/webhooks/management/event-types) | ## Retry Policy | Attempt | Delay | | - | - | | 1 | Immediate | | 2 | 10 seconds | | 3 | 60 seconds | | 4 | 5 minutes | | 5 | 1 hour | A delivery is successful if your endpoint returns HTTP 2xx within 5 seconds. Failed deliveries are visible in the [delivery history](/webhooks/management/deliveries) endpoint. ## Limits | Tier | Max Webhooks | Max Deliveries/day | | - | - | - | | Starter | 10 | 50,000 | | Pro | 50 | 500,000 | | Enterprise | 500 | Unlimited | # Combo Stream Source: https://docs.polynode.dev/websocket/combos Real-time Polymarket combo trades from pending calldata through receipt confirmation. PolyNode streams Polymarket combo activity from on-chain combo transactions. The stream follows the same lifecycle as standard settlements: pending events come from mempool calldata, then confirmation events come from on-chain receipts. > [!NOTE] > > This is the on-chain combo stream. Polymarket's RFQ gateway is an off-chain maker/quoter channel. Use this stream to monitor combo executions, fills, confirmations, and enriched lifecycle actions as they hit Polygon. ## Subscribe ```json theme={null} { "action": "subscribe", "type": "combos" } ``` The default `combos` preset emits: | Event | Timing | Purpose | | - | - | - | | `combo_execution` | Pending / mempool | Combo order execution decoded before confirmation. | | `combo_status_update` | Confirmed / receipt | Confirmation, exact receipt fills, fees, transfers, lifecycle details, and latency. | Every emitted combo includes its decoded structural legs, and every leg includes a `market` object with the leg market's title, slug, image, event, outcomes, and CLOB token IDs (`market.token_ids`, Polymarket's `clobTokenIds` in outcome order). Leg market metadata is resolved ahead of trading, so it never delays a pending trade. A market Polymarket listed in the last couple of minutes can briefly arrive without `market`. See [leg market fields](/websocket/events/combo-execution#leg-market). ## Trade model `combo_execution` is intentionally shaped like the ordinary settlement stream: * Top-level `taker_*` fields describe the taker order. * `trades[]` contains every signed order from that order maker's perspective. * `size` is always shares; `amount_usdc` is always dollars. * `price` is the actual fill price, including multi-maker price improvement. * `order_hash` is the ExchangeV3 EIP-712 hash computed directly from calldata. After confirmation, the same fills are queryable through [`GET /v3/wallets/{address}/combos/trades`](/data/combos/wallet-trades). The static API adds block and log coordinates; the WebSocket adds pre-confirmation delivery, order hashes, and explicit dollar amounts. ## Full combo surface Advanced users can explicitly request lifecycle and approval events: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": [ "combo_execution", "combo_status_update", "combo_lifecycle", "combo_approval" ] } } ``` Lifecycle events are emitted when their on-chain structure is complete. AutoRedeemer redemption confirmations can also be emitted when they are condition-only, because the receipt provides the user wallet, condition ID, exact payout, normalized payout, and log index without requiring a follow-up lookup. ## Redemption routing | What you need | Subscription | What it contains | | - | - | - | | Every redemption | `{"action":"subscribe","type":"redemptions"}` | Direct Conditional Tokens redemptions plus Binary, NegRisk, and generic combo AutoRedeemer payouts, all normalized as `redemption`. | | Combo redemptions only | `{"action":"subscribe","type":"combos","filters":{"event_types":["combo_lifecycle"],"action":"Redeem"}}` | Combo-native redeem lifecycle events only. | The comprehensive `redemptions` stream identifies bridged AutoRedeemer events with `data.source`: `AutoRedeemer.BinaryRedemption`, `AutoRedeemer.NegRiskRedemption`, or `AutoRedeemer.Redemption`. A direct Conditional Tokens redemption has no AutoRedeemer source. If you subscribe to both surfaces, a generic combo AutoRedeemer payout can appear once as `combo_lifecycle` and once as normalized `redemption`. These are two representations of the same on-chain log; correlate or deduplicate them with `tx_hash` and `log_index`. ## Covered on-chain surface The combo stream covers the Polymarket on-chain contracts used for combo execution and position lifecycle activity: | Contract | Address | Surface | | - | - | - | | ExchangeV3 | `0xe3333700cA9d93003F00f0F71f8515005F6c00Aa` | Combo order execution and confirmation. | | PositionManager | `0x006F54F7f9A22e0000CC2AB60031000000ae9fEF` | Position transfers and approvals. | | BinaryModule | `0x1000008dD9001B968442c1000017eaE6E0dA00Ba` | Split, merge, redeem, migration, and result lifecycle calls. | | NegRiskModule | `0x200000900045e3B6259600682756002200028933` | Negative-risk split, merge, redeem, convert, migration, and result calls. | | CombinatorialModule | `0x30000034706C7d8e12009DAB006Be20000c031A8` | Prepare, split, merge, extract, inject, wrap, unwrap, compress, redeem, and basket conversion. | | Router | `0x12121212006e4CD160D18e3f00711DA5c3372600` | Router split, merge, redeem, horizontal split/merge, and convert. | | AutoRedeemer | `0xa1200000d0002264C9a1698e001292D00E1b00af` | Auto redeem calls and confirmations. | PositionManager approvals for ExchangeV3 and AutoRedeemer are available through `combo_approval` when requested explicitly. Collateral ERC20 allowance approvals are not part of the default combo stream. ## Example Install `ws`, save the example as `combos.mjs`, and run it with Node.js: ```bash theme={null} npm install ws node combos.mjs ``` ```javascript theme={null} import WebSocket from "ws"; const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); const pending = new Map(); const PENDING_TTL_MS = 15 * 60 * 1000; const cleanup = setInterval(() => { const cutoff = Date.now() - PENDING_TTL_MS; for (const [txHash, item] of pending) { if (item.seenAt < cutoff) pending.delete(txHash); } }, 60_000); cleanup.unref(); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "combos" })); }); ws.on("message", (raw) => { const msg = JSON.parse(raw); for (const event of msg.events ?? [msg]) { if (event.type === "combo_execution") { pending.set(event.data.tx_hash, { data: event.data, seenAt: Date.now() }); console.log("pending combo", { tx_hash: event.data.tx_hash, taker: event.data.taker_wallet, side: event.data.taker_side, outcome: event.data.outcome, price: event.data.taker_price, shares: event.data.taker_size, amount_usdc: event.data.amount_usdc, legs: event.data.legs.map((leg) => ({ outcome: leg.leg_outcome_label, market: leg.market?.title ?? leg.condition_id })), trades: event.data.trades.map((trade) => ({ order_hash: trade.order_hash, maker: trade.maker, side: trade.side, outcome: trade.outcome, price: trade.price, shares: trade.size, amount_usdc: trade.amount_usdc })) }); } if (event.type === "combo_status_update") { const original = pending.get(event.data.tx_hash)?.data; if (["CONFIRMED", "FAILED"].includes(event.data.execution_status)) { pending.delete(event.data.tx_hash); } console.log("combo status", event.data.tx_hash, { execution_status: event.data.execution_status, latency_ms: event.data.latency_ms, pending_seen: Boolean(original), fills: event.data.confirmed_fills?.length ?? 0 }); } } }); ``` ## Filters Combo subscriptions support the standard WebSocket filters plus combo-specific identifiers: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "wallets": ["0xMakerOrTaker..."], "leg_position_ids": ["123456789..."], "tokens": ["123456789..."], "combo_condition_ids": ["0xcombo..."], "condition_ids": ["0xleg_or_combo_condition..."], "event_ids": ["0xevent..."], "module_ids": [3], "side": "YES", "direction": "BUY", "status": "confirmed", "min_size": 100 } } ``` `tokens` and `leg_position_ids` both match combo position IDs and leg position IDs. Use `leg_position_ids` when you want the filter to be self-documenting. For combo subscriptions, `side` means the combo outcome (`YES` or `NO`), while `direction` means the requester's order direction (`BUY` or `SELL`). `status: "confirmed"` selects receipt-backed `combo_status_update` events, including both successful and reverted receipts; use `execution_status` to distinguish `CONFIRMED` from `FAILED`. `min_size` is a minimum USDC value. To receive only combo lifecycle redemptions: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": ["combo_lifecycle"], "action": "Redeem" } } ``` ## Event reference * [`combo_execution`](/websocket/events/combo-execution) * [`combo_status_update`](/websocket/events/combo-status-update) * [`combo_lifecycle`](/websocket/events/combo-lifecycle) * [`combo_approval`](/websocket/events/combo-approval) # Compression Source: https://docs.polynode.dev/websocket/compression Reduce WebSocket bandwidth by ~60% with built-in zlib compression. > [!NOTE] > > **Recommended for production.** Compression reduces bandwidth by \~60% with no latency impact. > Every event is compressed once on the server and delivered to all subscribers — zero per-connection overhead. > Enable it by adding `&compress=zlib` to your connection URL. ## How it works When you connect with `&compress=zlib`, the server sends settlement events as **deflate-compressed binary frames** instead of JSON text frames. Your client decompresses each binary frame with standard zlib `inflateRaw` — available in every language. Control messages (subscribe acknowledgments, errors, heartbeats, pong) are still sent as normal JSON text, so you can always read them directly. ``` wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib ``` ## Bandwidth savings Measured in production on real settlement data: | Mode | Per-connection | Max connections (1 Gbps) | Max connections (10 Gbps) | | - | - | - | - | | **Uncompressed** | \~0.78 Mbps | \~1,000 | \~10,000 | | **Compressed** | \~0.32 Mbps | \~2,500 | \~25,000 | Compression is applied **once per event** on the server, then the same compressed bytes are fanned out to all compressed subscribers. There is no per-connection compression overhead — it scales the same as uncompressed. ## Client examples > [tab] JavaScript / Node.js > > ```javascript theme={null} > import WebSocket from "ws"; > import { inflateRawSync } from "zlib"; > > const ws = new WebSocket( > "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib" > ); > > ws.on("open", () => { > ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); > }); > > ws.on("message", (data, isBinary) => { > let event; > if (isBinary) { > // Compressed event — decompress with inflateRaw > const json = inflateRawSync(data).toString(); > event = JSON.parse(json); > } else { > // Control message (subscribe ack, heartbeat, error) > event = JSON.parse(data.toString()); > } > console.log(event.type, event.data?.market_title); > }); > ``` > [tab] Python > > ```python theme={null} > import json > import zlib > import websocket > > def on_message(ws, message, is_binary=False): > if isinstance(message, bytes): > # Compressed event — decompress with raw deflate > json_str = zlib.decompress(message, -zlib.MAX_WBITS).decode() > event = json.loads(json_str) > else: > # Control message (subscribe ack, heartbeat, error) > event = json.loads(message) > print(event["type"], event.get("data", {}).get("market_title")) > > ws = websocket.WebSocketApp( > "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib", > on_open=lambda ws: ws.send(json.dumps({ > "action": "subscribe", "type": "settlements" > })), > on_message=on_message, > ) > ws.run_forever() > ``` > > With `websockets` (async): > > ```python theme={null} > import asyncio > import json > import zlib > import websockets > > async def main(): > async with websockets.connect( > "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib" > ) as ws: > await ws.send(json.dumps({ > "action": "subscribe", "type": "settlements" > })) > async for message in ws: > if isinstance(message, bytes): > event = json.loads( > zlib.decompress(message, -zlib.MAX_WBITS) > ) > else: > event = json.loads(message) > print(event["type"]) > > asyncio.run(main()) > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "bytes" > "compress/flate" > "encoding/json" > "fmt" > "io" > "log" > > "github.com/gorilla/websocket" > ) > > func main() { > c, _, err := websocket.DefaultDialer.Dial( > "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib", nil, > ) > if err != nil { log.Fatal(err) } > defer c.Close() > > c.WriteJSON(map[string]string{ > "action": "subscribe", "type": "settlements", > }) > > for { > msgType, data, err := c.ReadMessage() > if err != nil { log.Fatal(err) } > > var event map[string]interface{} > > if msgType == websocket.BinaryMessage { > // Compressed — decompress with raw deflate > r := flate.NewReader(bytes.NewReader(data)) > decompressed, _ := io.ReadAll(r) > r.Close() > json.Unmarshal(decompressed, &event) > } else { > json.Unmarshal(data, &event) > } > > fmt.Println(event["type"]) > } > } > ``` > [tab] Rust > > ```rust theme={null} > use flate2::read::DeflateDecoder; > use std::io::Read; > use tungstenite::{connect, Message}; > > fn main() { > let (mut ws, _) = connect( > "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib" > ).unwrap(); > > ws.send(Message::Text( > r#"{"action":"subscribe","type":"settlements"}"#.into() > )).unwrap(); > > loop { > let msg = ws.read().unwrap(); > let json_str = match msg { > Message::Binary(data) => { > // Compressed — decompress with raw deflate > let mut decoder = DeflateDecoder::new(&data[..]); > let mut s = String::new(); > decoder.read_to_string(&mut s).unwrap(); > s > } > Message::Text(s) => s.to_string(), > _ => continue, > }; > let event: serde_json::Value = serde_json::from_str(&json_str).unwrap(); > println!("{}", event["type"]); > } > } > ``` > [tab] Browser (pako) > > ```html theme={null} > > > ``` ## Key details > [accordion] What gets compressed? > > Only live event frames (settlements, status updates, trades) are sent as compressed binary. > > These are always sent as normal JSON text: > > * `{"type": "snapshot", ...}` — initial event snapshot > * `{"type": "subscribed", ...}` — subscription acknowledgment > * `{"type": "unsubscribed", ...}` — unsubscribe confirmation > * `{"type": "heartbeat", ...}` — server heartbeat > * `{"type": "pong"}` — ping response > * `{"type": "error", ...}` — error messages > [accordion] How do I tell if a frame is compressed? > > Check the WebSocket frame type: > > * **Binary frame** → compressed event, decompress with `inflateRaw` > * **Text frame** → normal JSON, parse directly > > Every WebSocket library exposes this distinction (e.g. `isBinary` in Node.js `ws`, `isinstance(msg, bytes)` in Python). > [accordion] What compression algorithm is used? > > Raw deflate (RFC 1951) via the `flate2` Rust crate with fast compression level. > Decompress with `inflateRaw` / `zlib.decompress(data, -zlib.MAX_WBITS)` — **not** `inflate` or `gunzip`. > [accordion] Does compression add latency? > > No measurable impact. Each event is compressed once on the server (\~0.05ms for a 1.2 KB message), > then the same compressed bytes are sent to all compressed subscribers via zero-copy fan-out. > Decompression on the client is equally fast. > [accordion] Can I mix compressed and uncompressed? > > Compression is set per connection at connect time. You cannot toggle it mid-session. > Different connections from the same API key can use different modes. ## When to use compression | Scenario | Recommendation | | - | - | | **Production bots / trading systems** | Use compression — saves bandwidth, no downside | | **Prototyping / debugging** | Skip compression — raw JSON is easier to inspect | | **High-frequency firehose (full data stream)** | Use compression — critical at scale | | **Browser dashboards** | Use compression with [pako](https://github.com/nichn4nd/pako) — reduces data transfer | # Block Event Source: https://docs.polynode.dev/websocket/events/block New Polygon block with Polymarket-specific statistics. Emitted for every new Polygon block. Includes Polymarket-specific aggregates — settlement count, trade volume, and how many of the block's transactions involved Polymarket. ```json theme={null} { "type": "block", "timestamp": 1774515147000, "data": { "event_type": "block", "block_number": 84697556, "block_hash": "0x7b7c3146decd46ca8d271620470455a44066b5e2fac557f2290bfbee5c7c5bb1", "timestamp": 1774515147000, "parent_hash": "0xd2cace3840df7c061d68b14c49d420fa6a32d7173eeffd966236c2c0dfc60738", "tx_count": 268, "polymarket_tx_count": 0, "settlement_count": 0, "trade_volume_usd": 8717.458152 } } ``` ## Fields **type** `string` *required* Always `"block"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **block\_number** `number` *required* Block height. **block\_hash** `string` *required* Block hash (0x-prefixed). **timestamp** `number` *required* Block timestamp in Unix milliseconds. **parent\_hash** `string` *required* Parent block hash. **tx\_count** `number` *required* Total transactions in the block. **polymarket\_tx\_count** `number` *required* Transactions involving Polymarket contracts. **settlement\_count** `number` *required* Number of Polymarket settlements in this block. **trade\_volume\_usd** `number` *required* Total Polymarket trade volume in this block (USD). ## Use cases * **Network monitoring** — track block production rate and Polymarket's share of network activity * **Volume dashboards** — aggregate `trade_volume_usd` over time for real-time volume charts * **Block explorer** — correlate settlements with their containing blocks # Combo Approval Event Source: https://docs.polynode.dev/websocket/events/combo-approval PositionManager approval events relevant to combo settlement and auto-redemption. Emitted for approvals that affect combo settlement or redeemability. > [!NOTE] > > The default combo stream does not include approvals. Request `combo_approval` explicitly if you need approval monitoring. Collateral ERC20 allowance approvals are intentionally not part of the default customer stream. ```json theme={null} { "type": "combo_approval", "timestamp": 1781054112400, "data": { "event_type": "combo_approval", "tx_hash": "0xabc...", "status": "confirmed", "detected_at": 1781054112400, "block_number": 88232739, "approval_type": "position_manager_approval_for_all", "owner": "0xOwner...", "operator": "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa", "approved": true, "target_role": "ExchangeV3" } } ``` ## Subscribing ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": ["combo_approval"] } } ``` ## Fields **data.tx\_hash** `string` *required* Polygon transaction hash. **data.status** `string` *required* `pending` or `confirmed`. **data.detected\_at** `number` *required* Unix milliseconds when PolyNode first saw the approval transaction. **data.block\_number** `number` Polygon block number once confirmed. **data.approval\_type** `string` *required* Approval class. Currently `position_manager_approval_for_all` or `collateral_allowance` when decoded. **data.owner** `string` *required* Wallet granting the approval. **data.operator** `string` *required* Approved operator or spender. **data.approved** `boolean` PositionManager approval status. **data.amount\_e6** `string` Raw approved amount when the decoded approval is allowance-based. **data.target\_role** `string` Known combo role for the operator, such as `ExchangeV3` or `AutoRedeemer`. # Combo Execution Event Source: https://docs.polynode.dev/websocket/events/combo-execution Pending Polymarket combo trades decoded from ExchangeV3 calldata. `combo_execution` streams a Polymarket combo trade from the mempool, before it appears in the confirmed combo-trades API. It uses the same maker/taker trade model as the standard settlement stream and includes every signed order in the transaction. > [!WARNING] > > This is a pending event. Use `combo_status_update` with the same `tx_hash` for > confirmation. A dropped or replaced Polygon transaction may never confirm. ## Example ```json theme={null} { "type": "combo_execution", "timestamp": 1785812120366, "data": { "event_type": "combo_execution", "tx_hash": "0xf4f973bcca17c05081574c36183a5f61fae8eb5895a2d46d71aaadb3cf11e556", "status": "pending", "detected_at": 1785812120366, "block_number": null, "combo_condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "legs": [ { "position_id": "759456036058902166074175781780133450895503656129754990757956704995918217217", "module_id": 1, "module_name": "BinaryModule", "condition_id": "0x01add63e0052d10828c47551c3e231dedd0000000000000000000000000000", "event_id": "0x01add63e0052d10828c47551c3e231dedd000000000000000000000000", "arity": 0, "condition_index": 0, "outcome_index": 1, "leg_outcome_label": "No", "market": { "title": "Phoenix Mercury vs. Chicago Sky", "slug": "wnba-phx-chi-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wnba-logo-PAR4befDAubM.png", "event_title": "Phoenix Mercury vs. Chicago Sky", "event_slug": "wnba-phx-chi-2026-08-03", "outcomes": ["Phoenix Mercury", "Chicago Sky"], "token_ids": [ "74953064150171307888139369905607115013164923361328779028892093225372812178760", "103031736784837797872355003049421848467848734930275080911268726099634278504076" ] } }, { "position_id": "888399010527256025342625662713948815643754849506664777044908366823210090496", "module_id": 1, "module_name": "BinaryModule", "condition_id": "0x01f6d0e6bdba3f8d15dc0928842624b9f10000000000000000000000000000", "event_id": "0x01f6d0e6bdba3f8d15dc0928842624b9f1000000000000000000000000", "arity": 0, "condition_index": 0, "outcome_index": 0, "leg_outcome_label": "Yes", "market": { "title": "National Bank Open: Tatjana Maria vs Caty McNally", "slug": "wta-maria-mcnally-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wta-logo-41f331bdf1.png", "event_title": "National Bank Open: Tatjana Maria vs Caty McNally", "event_slug": "wta-maria-mcnally-2026-08-03", "outcomes": ["Tatjana Maria", "Caty McNally"], "token_ids": [ "17162282412521239209404255350428236324471624953933197764496515696146602689810", "74731345471819956774387334586905453869113310035587873173616096006033744318106" ] } } ], "taker_wallet": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "taker_token": "1666644547653825639538654505467109608411697937035881104213580452779446501376", "taker_side": "BUY", "outcome": "YES", "taker_price": 0.57, "taker_size": 40.350877, "amount_usdc": 22.999999, "order_hashes": [ "0x9fd9da991a3d8f82bfb13e2901422a1621d87db1e27ce4da33fd5a61dec4f4b7", "0x1eb1c486ccad5622329d3e88147c6e98698521ebff86fcbd27ab7efa7fd458d5" ], "trades": [ { "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501377", "order_hash": "0x9fd9da991a3d8f82bfb13e2901422a1621d87db1e27ce4da33fd5a61dec4f4b7", "maker": "0xe2315b15280fc49bc6e60eaaeea30c0df64493a5", "signer": "0x1d0a670f95751708ad3f61aced73ca55822bb145", "taker": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "side": "BUY", "outcome": "NO", "price": 0.43, "size": 40.350877, "amount_usdc": 17.350878, "fee": 0 }, { "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501376", "order_hash": "0x1eb1c486ccad5622329d3e88147c6e98698521ebff86fcbd27ab7efa7fd458d5", "maker": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "signer": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "taker": "0xe3333700ca9d93003f00f0f71f8515005f6c00aa", "side": "BUY", "outcome": "YES", "price": 0.57, "size": 40.350877, "amount_usdc": 22.999999, "fee": 0.4945 } ] } } ``` ## How to read it The top-level trade fields describe the taker order. In the example, the taker wallet bought `40.350877` YES combo shares at `0.57` for `22.999999` USDC. Each `trades[]` row describes one signed order from that order maker's perspective. The complementary maker bought the NO position at `0.43` for the same `40.350877` shares. This is the same convention used by the settlement stream and by Exchange `OrderFilled` events. `size` always means shares. `amount_usdc` always means dollars. For BUY orders, the calldata's maker amount is USDC, so PolyNode converts it to shares before emitting `size`. For SELL orders, the maker amount is already shares. The conversion is performed in both directions so clients do not need to interpret raw fixed-point amounts. `price` is the actual fill price, not merely the signed order's limit price. This matters when one taker order receives price improvement across multiple maker orders. `amount_usdc` is the gross fill value. `fee` is reported separately and is not subtracted from it. ### Multiple maker orders A transaction with three maker orders and one taker order contains four `trades[]` rows and four `order_hashes`. These arrays are one-to-one and use the same order: maker orders in calldata order, followed by the taker order. Use `trades[i].order_hash` when working with an individual row. Top-level `taker_size` and `amount_usdc` are the taker order's total filled shares and gross USDC value across all makers. `taker_price` is the effective fill price (`amount_usdc / taker_size`), rounded to four decimal places. This is why a live multi-maker payload can be longer than the two-order example above without introducing any additional field types. ## Mapping to the static combo-trades API After confirmation, the same fill appears in [`GET /v3/wallets/{address}/combos/trades`](/data/combos/wallet-trades). | WebSocket field | Static combo-trades field | Notes | | - | - | - | | `tx_hash` | `tx_hash` | Stable correlation key | | `trades[].position_id` | `position_id` | Combo YES or NO position | | `trades[].side` | `side` | Maker-perspective `BUY` or `SELL` | | `trades[].price` | `price` | Actual fill price | | `trades[].size` | `size` | Shares traded | | `trades[].fee` | `fee` | Fee charged for that fill | | `trades[].maker` / `taker` | `wallet_address`, `wallet_role`, `counterparty_address` | Querying either participant projects the same fill for that wallet | | `trades[].order_hash` | — | Available immediately from calldata on the WebSocket | | `trades[].amount_usdc` | — | Explicit dollar value of the fill | The static endpoint additionally has confirmed-only fields such as `block_number`, `log_index`, and the on-chain timestamp. ## Fields ### Execution | Field | Type | Description | | - | - | - | | `tx_hash` | string | Polygon transaction hash | | `status` | string | Always `pending` for a mempool execution | | `detected_at` | number | Unix milliseconds when PolyNode first saw the transaction | | `block_number` | number or null | `null` before confirmation | | `combo_condition_id` | string | Derived combo condition ID | | `legs` | object\[] | Every decoded constituent leg | | `taker_wallet` | string | Wallet that made the taker order | | `taker_token` | string | Combo position ID bought or sold by the taker order | | `taker_side` | string | Taker order direction: `BUY` or `SELL` | | `outcome` | string | Taker combo position side: `YES` or `NO` | | `taker_price` | number | Actual taker fill price | | `taker_size` | number | Taker fill size in shares | | `amount_usdc` | number | Taker fill value in USDC | | `order_hashes` | string\[] | ExchangeV3 EIP-712 hashes computed from calldata | | `trades` | object\[] | Every signed order involved in the execution | ### Trade row | Field | Type | Description | | - | - | - | | `position_id` | string | Combo position filled by this order | | `order_hash` | string | ExchangeV3 EIP-712 order hash | | `maker` | string | Wallet that made this signed order | | `signer` | string | Address that signed this order | | `taker` | string | OrderFilled taker/counterparty; this can be the ExchangeV3 contract for the taker order | | `side` | string | This order maker's `BUY` or `SELL` direction | | `outcome` | string | `YES` or `NO` combo position side | | `price` | number | Actual fill price | | `size` | number | Shares filled | | `amount_usdc` | number | Dollar value filled | | `fee` | number | Fee in USDC | ### Leg row `position_id` and the decoded structural fields come directly from calldata. Every leg also includes a nested `market` object with the leg market's title, slug, image, event, outcomes, and CLOB token IDs. PolyNode resolves this metadata ahead of trading, and attaching it never delays the event. A market Polymarket listed in the last couple of minutes can briefly arrive without `market`. | Field | Type | Description | | - | - | - | | `position_id` | string | Leg position ID: the Polymarket PositionManager position ID of the selected outcome, as used by the combo contracts | | `module_id` / `module_name` | number / string | Combo module identity | | `condition_id` | string | Leg condition ID | | `event_id` | string | Leg event ID when encoded by the module | | `arity` | number | Encoded condition arity | | `condition_index` | number | Condition index within the event | | `outcome_index` | number | Selected outcome index | | `leg_outcome_label` | string | Encoded combo-leg selection (`Yes` or `No` for `BinaryModule`); this is distinct from a human label in `market.outcomes` | | `market` | object | Market metadata for the leg; see [Leg market](#leg-market) | ### Leg market | Field | Type | Description | | - | - | - | | `title` | string | Market question | | `slug` | string | Polymarket market slug | | `image` | string | Market image URL | | `event_title` | string | Title of the Polymarket event that contains the market | | `event_slug` | string | Slug of that event | | `outcomes` | string\[] | Outcome labels in outcome order | | `token_ids` | string\[] | The market's CLOB token IDs (Polymarket's `clobTokenIds`) in outcome order, one per entry in `outcomes`. These are the IDs used for CLOB order books, prices, and orders. | On current markets, `market.token_ids` and the leg `position_id` are different identifiers. The leg `position_id` identifies the selected outcome inside the combo, while `market.token_ids[outcome_index]` is the CLOB token ID for that same outcome. Use the CLOB token ID with order-book, price, and trade endpoints. In the example, the first leg selects outcome `1` (Chicago Sky), so its CLOB token ID is `103031736784837797872355003049421848467848734930275080911268726099634278504076`. Polymarket Protocol V2 markets, which Polymarket plans to use for new markets from around November 2, 2026, trade on the CLOB by their position IDs, per Polymarket. For those markets `market.token_ids` therefore carries the market's position IDs, which are its CLOB token IDs. ## Subscribe ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": ["combo_execution"] } } ``` # Combo Lifecycle Event Source: https://docs.polynode.dev/websocket/events/combo-lifecycle Split, merge, redeem, convert, wrap, unwrap, and related combo lifecycle actions. Emitted for combo-native lifecycle actions. Generic combo AutoRedeemer confirmations can also be emitted without legs when the receipt itself provides the user wallet, condition ID, exact payout, normalized payout, module name, and log index. ```json theme={null} { "type": "combo_lifecycle", "timestamp": 1781054112400, "data": { "event_type": "combo_lifecycle", "tx_hash": "0xabc...", "status": "confirmed", "detected_at": 1781054112400, "block_number": 88232739, "log_index": 44, "action": "Redeem", "user": "0xUser...", "combo_condition_id": "0xcombo...", "condition_ids": ["0xcombo..."], "module_id": 3, "module_name": "CombinatorialModule", "position_ids": ["123..."], "source_position_ids": ["123..."], "leg_position_ids": [ "759456036058902166074175781780133450895503656129754990757956704995918217217", "888399010527256025342625662713948815643754849506664777044908366823210090496" ], "legs": [ { "position_id": "759456036058902166074175781780133450895503656129754990757956704995918217217", "leg_outcome_label": "No", "market": { "title": "Phoenix Mercury vs. Chicago Sky", "slug": "wnba-phx-chi-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wnba-logo-PAR4befDAubM.png", "event_title": "Phoenix Mercury vs. Chicago Sky", "event_slug": "wnba-phx-chi-2026-08-03", "outcomes": ["Phoenix Mercury", "Chicago Sky"], "token_ids": [ "74953064150171307888139369905607115013164923361328779028892093225372812178760", "103031736784837797872355003049421848467848734930275080911268726099634278504076" ] } }, { "position_id": "888399010527256025342625662713948815643754849506664777044908366823210090496", "leg_outcome_label": "Yes", "market": { "title": "National Bank Open: Tatjana Maria vs Caty McNally", "slug": "wta-maria-mcnally-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wta-logo-41f331bdf1.png", "event_title": "National Bank Open: Tatjana Maria vs Caty McNally", "event_slug": "wta-maria-mcnally-2026-08-03", "outcomes": ["Tatjana Maria", "Caty McNally"], "token_ids": [ "17162282412521239209404255350428236324471624953933197764496515696146602689810", "74731345471819956774387334586905453869113310035587873173616096006033744318106" ] } } ], "amount_e6": "1000000", "amount_usdc": 1, "payout_e6": "1000000", "payout_usdc": 1 } } ``` ## Actions `action` can be: `Prepare`, `Split`, `Merge`, `HorizontalSplit`, `HorizontalMerge`, `Convert`, `Redeem`, `Wrap`, `Unwrap`, `Transfer`, `Compress`, `Extract`, `Inject`, `ConvertToYesBasket`, or `MergeFromYesBasket`. ## Subscribing Lifecycle events are not included in the default `combos` preset. Request them explicitly: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": ["combo_lifecycle"] } } ``` Filter by lifecycle action: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": ["combo_lifecycle"], "action": "Redeem" } } ``` Generic combo AutoRedeemer redemptions can be consumed through the combo lifecycle stream: ```json theme={null} { "type": "combo_lifecycle", "data": { "event_type": "combo_lifecycle", "tx_hash": "0x...", "status": "confirmed", "block_number": 88462228, "log_index": 27, "action": "Redeem", "user": "0xde0a3c61f87da595b215f88254a9473e6152f102", "condition_ids": ["0xd7e68ef0dfabc386f97ffdc330ecff4908cda4d08c5fc5931503f1e60cac0dfe"], "module_name": "AutoRedeemer", "payout_e6": "4500000000", "payout_usdc": 4500, "diagnostics": { "decoded_function": "AutoRedeemer.Redemption" } } } ``` ## Fields **data.action** `string` *required* Combo lifecycle action. **data.user** `string` Wallet that initiated or received the lifecycle action. **data.log\_index** `number` Receipt log index for confirmed lifecycle events. **data.combo\_condition\_id** `string` Combo condition ID when available. **data.condition\_ids** `string[]` Condition IDs involved in the lifecycle action. **data.event\_ids** `string[]` Event IDs for combo legs when available. **data.module\_id** `number` Combo module ID. Common values are `1` for binary, `2` for negative-risk, and `3` for combinatorial legs. **data.module\_name** `string` Human-readable module name when available. **data.yes\_position\_id** `string` YES combo position ID when the lifecycle action creates or affects a combo position. **data.no\_position\_id** `string` NO combo position ID when the lifecycle action creates or affects a combo position. **data.position\_ids** `string[]` Position IDs involved in the lifecycle action. **data.source\_position\_ids** `string[]` Positions consumed by the action. **data.destination\_position\_ids** `string[]` Positions created by the action. **data.legs** `object[]` Decoded legs when available, each with the same [`market`](/websocket/events/combo-execution#leg-market) object as a `combo_execution` leg. `market.token_ids` holds the leg market's CLOB token IDs in outcome order. Generic combo AutoRedeemer redemptions can be emitted without legs when the receipt includes the wallet, condition ID, and payout directly. **data.amount\_e6** `string` Raw six-decimal amount. **data.amount\_usdc** `number` USDC-normalized amount. **data.payout\_e6** `string` Exact raw payout in six-decimal USDC units for redeem actions. **data.payout\_usdc** `number` USDC-normalized payout for redeem actions when available. **data.side** `string` Combo side when available. Values: `YES` or `NO`. **data.confirmed\_transfers** `object[]` Position transfer logs decoded from the confirmed receipt. # Combo Status Update Event Source: https://docs.polynode.dev/websocket/events/combo-status-update Receipt-backed confirmation for a pending combo execution or combo lifecycle transaction. `combo_status_update` is emitted after a combo transaction is mined. Match its `tx_hash` to a pending `combo_execution`; then use `confirmed_fills[]` as the on-chain result. The fill rows use the same maker-perspective schema as `combo_execution.data.trades[]`: `size` is shares, `amount_usdc` is dollars, and `price` is the actual execution price. Receipt-only lifecycle activity can appear in `lifecycle_events[]` even when PolyNode did not observe a pending transaction. This includes combo-native AutoRedeemer activity. Standard redemption subscribers continue to receive the corresponding stable `redemption` event where applicable. ## Example ```json theme={null} { "type": "combo_status_update", "timestamp": 1785812123000, "data": { "event_type": "combo_status_update", "tx_hash": "0xf4f973bcca17c05081574c36183a5f61fae8eb5895a2d46d71aaadb3cf11e556", "block_number": 91404731, "confirmed_at": 1785812123000, "execution_status": "CONFIRMED", "pending_detected_at": 1785812120366, "latency_ms": 2634, "combo_condition_id": "0x03af499212591cdbfd21ab04df07b8fb720000000000000000000000000000", "yes_position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501376", "no_position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501377", "order_hashes": [ "0x9fd9da991a3d8f82bfb13e2901422a1621d87db1e27ce4da33fd5a61dec4f4b7", "0x1eb1c486ccad5622329d3e88147c6e98698521ebff86fcbd27ab7efa7fd458d5" ], "legs": [ { "position_id": "759456036058902166074175781780133450895503656129754990757956704995918217217", "condition_id": "0x01add63e0052d10828c47551c3e231dedd0000000000000000000000000000", "module_id": 1, "module_name": "BinaryModule", "outcome_index": 1, "leg_outcome_label": "No", "market": { "title": "Phoenix Mercury vs. Chicago Sky", "slug": "wnba-phx-chi-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wnba-logo-PAR4befDAubM.png", "event_title": "Phoenix Mercury vs. Chicago Sky", "event_slug": "wnba-phx-chi-2026-08-03", "outcomes": ["Phoenix Mercury", "Chicago Sky"], "token_ids": [ "74953064150171307888139369905607115013164923361328779028892093225372812178760", "103031736784837797872355003049421848467848734930275080911268726099634278504076" ] } }, { "position_id": "888399010527256025342625662713948815643754849506664777044908366823210090496", "condition_id": "0x01f6d0e6bdba3f8d15dc0928842624b9f10000000000000000000000000000", "module_id": 1, "module_name": "BinaryModule", "outcome_index": 0, "leg_outcome_label": "Yes", "market": { "title": "National Bank Open: Tatjana Maria vs Caty McNally", "slug": "wta-maria-mcnally-2026-08-03", "image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/wta-logo-41f331bdf1.png", "event_title": "National Bank Open: Tatjana Maria vs Caty McNally", "event_slug": "wta-maria-mcnally-2026-08-03", "outcomes": ["Tatjana Maria", "Caty McNally"], "token_ids": [ "17162282412521239209404255350428236324471624953933197764496515696146602689810", "74731345471819956774387334586905453869113310035587873173616096006033744318106" ] } } ], "confirmed_fills": [ { "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501377", "order_hash": "0x9fd9da991a3d8f82bfb13e2901422a1621d87db1e27ce4da33fd5a61dec4f4b7", "maker": "0xe2315b15280fc49bc6e60eaaeea30c0df64493a5", "taker": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "side": "BUY", "outcome": "NO", "price": 0.43, "size": 40.350877, "amount_usdc": 17.350878, "fee": 0 }, { "position_id": "1666644547653825639538654505467109608411697937035881104213580452779446501376", "order_hash": "0x1eb1c486ccad5622329d3e88147c6e98698521ebff86fcbd27ab7efa7fd458d5", "maker": "0x0d8b4fb38999aaf7658df758f3587d25fe7fd417", "taker": "0xe3333700ca9d93003f00f0f71f8515005f6c00aa", "side": "BUY", "outcome": "YES", "price": 0.57, "size": 40.350877, "amount_usdc": 22.999999, "fee": 0.4945 } ] } } ``` The example omits empty optional arrays for readability. Each leg carries the same `market` object as a [`combo_execution` leg](/websocket/events/combo-execution#leg-market), whose `token_ids` are the market's CLOB token IDs in outcome order. `combo_status_update` is receipt-backed. Its current terminal statuses are: | `execution_status` | Meaning | | - | - | | `CONFIRMED` | The transaction receipt succeeded. Fill arrays are included when the receipt emitted those logs. | | `FAILED` | The transaction was mined with a reverted receipt. Fill arrays are normally omitted. | Both values match a subscription filter of `status: "confirmed"` because both are on-chain receipt results. Do not label every status update successful; always inspect `execution_status`. If PolyNode did not observe the transaction in the mempool, the receipt event can arrive without pending-only context. In that case `pending_detected_at`, `latency_ms`, combo identifiers, decoded legs, and pending-derived wallet/value fields are omitted. ## Fields ### Confirmation | Field | Type | Description | | - | - | - | | `tx_hash` | string | Polygon transaction hash; joins to the pending execution | | `block_number` | number | Block containing the transaction | | `confirmed_at` | number | Confirmation time in Unix milliseconds | | `execution_status` | string | `CONFIRMED` for a successful receipt or `FAILED` for a reverted receipt | | `pending_detected_at` | number or omitted | Pending detection time when the transaction was observed in the mempool | | `latency_ms` | number or omitted | Pending-to-receipt latency; omitted without a pending observation | | `combo_condition_id` | string or omitted | Derived combo condition ID when recoverable | | `yes_position_id` / `no_position_id` | string or omitted | Combo outcome position IDs when available | | `leg_position_ids` | string\[] or omitted | Constituent leg position IDs (PositionManager position IDs, the same values as `legs[].position_id`) when available | | `legs` | object\[] or omitted | Decoded combo legs, each with its [`market`](/websocket/events/combo-execution#leg-market) metadata | | `order_hashes` | string\[] or omitted | Exchange order hashes recovered from receipt fills | | `confirmed_fills` | object\[] or omitted | Receipt-backed maker-perspective fills | | `execution_summaries` | object\[] or omitted | OrdersMatched-style execution summaries | | `fees` | object\[] or omitted | FeeCharged logs normalized to USDC where possible | | `confirmed_transfers` | object\[] or omitted | PositionManager transfer logs | | `lifecycle_events` | object\[] or omitted | Combo lifecycle events found in the same receipt | | `gas_used` | string or omitted | Receipt gas used when available | | `effective_gas_price` | string or omitted | Receipt effective gas price when available | Top-level `maker_address`, `signer_address`, `taker_address`, `amount_usdc`, and `notional_usdc` can also be present when they are recoverable from the pending execution or receipt. For individual fills, use `confirmed_fills[]`. ### Confirmed fill | Field | Type | Description | | - | - | - | | `position_id` | string | Combo position filled | | `order_hash` | string | ExchangeV3 order hash | | `maker` | string | Wallet that made the signed order | | `signer` | string | Order signer when available | | `taker` | string | Receipt's OrderFilled taker/counterparty | | `side` | string | Order maker's `BUY` or `SELL` direction | | `outcome` | string | `YES` or `NO` combo position side | | `price` | number | Actual fill price | | `size` | number | Shares filled | | `amount_usdc` | number | Dollar value filled | | `fee` | number | Fee in USDC | ## Subscribe `combo_status_update` is included in the default combo stream: ```json theme={null} { "action": "subscribe", "type": "combos" } ``` # Deposit Event Source: https://docs.polynode.dev/websocket/events/deposit USDC and PolyUSD deposits and withdrawals on Polymarket. Emitted when USDC.e or PolyUSD moves into or out of Polymarket contracts — deposits (funding a trading account) and withdrawals. > [!NOTE] > > **V2 update:** Polymarket V2 (the April 2026 exchange upgrade) uses PolyUSD (a 1:1 USDC.e wrapper) as collateral. Polymarket Protocol V2 markets use the same PolyUSD collateral, so deposit events do not change for them. Deposit events now include PolyUSD wrapping (USDC.e → PolyUSD via Onramp) and unwrapping (PolyUSD → USDC.e via Offramp). The event format is identical — `amount` is in USD with 6 decimal precision regardless of whether the underlying transfer is USDC.e or PolyUSD. See the [V2 Migration Guide](/guides/v2-migration) for details. ```json theme={null} { "type": "deposit", "timestamp": 1774515147000, "data": { "event_type": "deposit", "tx_hash": "0x4ec78046c86dc95e432ad938185dfff4f72644d1c4328483b6a1bcbd024e9d5c", "block_number": 84697556, "log_index": 2150, "timestamp": 1774515147000, "from": "0x53a26c4ee0776948f9fc645a6e5184f1af3deb92", "to": "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "amount": 27.489, "direction": "deposit" } } ``` ## Fields **type** `string` *required* Always `"deposit"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **from** `string` *required* Sender address. **to** `string` *required* Receiver address. **amount** `number` *required* USDC amount (6 decimal precision). **direction** `string` *required* `"deposit"` (to Polymarket) or `"withdrawal"` (from Polymarket). ## Use cases * **Whale tracking** — large deposits often precede big trades * **Fund flow analysis** — track capital entering and leaving Polymarket * **Wallet monitoring** — know when a tracked wallet funds their account # Oracle Event Source: https://docs.polynode.dev/websocket/events/oracle UMA Optimistic Oracle events — market initializations, proposals, disputes, resolutions, settlements, and admin actions on Polymarket. Oracle events stream the full lifecycle of Polymarket's UMA-based market resolution system. Every Polymarket market is resolved through UMA's Optimistic Oracle, which uses a propose-challenge-resolve cycle on the Polygon blockchain. **The only WebSocket stream of enriched UMA oracle events.** Decoded from on-chain event logs, enriched with full market metadata (title, outcomes, images, token IDs), and pushed to your connection in real-time. ## How Polymarket Resolution Works 1. A market is **initialized** on-chain (QuestionInitialized on the UMA adapter) 2. A **proposer** submits an answer (YES or NO) via ProposePrice on UMA's Optimistic Oracle V2 and posts a USDC bond 3. A 2-hour **liveness window** opens where anyone can dispute 4. If no dispute, the oracle **settles** (Settle event on OO V2) and the market **resolves** (QuestionResolved on the adapter) 5. For neg-risk markets (the majority), a second transaction calls `resolveQuestion()` on the NegRiskOperator, which triggers **condition\_resolution** on the Conditional Tokens contract. **Positions become redeemable at this point.** 6. If disputed, the question **resets** and goes to UMA's DVM for a token-holder vote 7. Admins can **flag**, **pause**, or **manually resolve** markets in edge cases ## Subscribe ```json theme={null} { "action": "subscribe", "type": "oracle" } ``` ## Oracle Event Types Every oracle event has an `oracle_type` field indicating what happened: **initialization** `string` Market initialized on-chain. The UMA adapter has registered a new question. This is the first on-chain event in a market's lifecycle. **proposal** `string` Resolution proposed on UMA Optimistic Oracle V2 (ProposePrice). A proposer has submitted an answer and posted a bond. The 2-hour liveness countdown begins. Includes `proposer` address, `proposed_price` (1.0 = YES, 0.0 = NO), and `expiration_timestamp`. **dispute** `string` Resolution disputed on UMA Optimistic Oracle V2 (DisputePrice). Someone challenged the proposed outcome. The market re-enters the proposal phase or escalates to UMA's DVM for a token-holder vote. **High signal, rare event.** Price swings are likely. Includes `proposer`, `disputer`, and `proposed_price`. **settled** `string` Settled on UMA Optimistic Oracle V2 after the liveness period expires. The oracle has accepted the proposed answer. Includes `resolved_price` and `proposer`. **resolution** `string` Market officially resolved via UMA oracle (QuestionResolved on the adapter). The most common event type (\~200+ per hour during active sports periods). Includes the final `resolved_price`, `payouts` array, and `resolved_outcome`. **reset** `string` Question reset after a dispute. The market goes back to the proposal phase. **flag** `string` Market flagged by admin. Something may be wrong with the resolution. **manual\_resolution** `string` Market manually resolved by admin, bypassing the normal oracle flow. Includes `payouts` array. **condition\_resolution** `string` Condition resolved on the Conditional Tokens contract (ConditionResolution event). **This is the moment positions become redeemable.** For neg-risk markets (the majority on Polymarket), this fires in a separate transaction \~2-3 minutes after `resolution`. For standard markets, it fires atomically with `resolution`. Includes `resolved_price`, `payouts`, `condition_id`, and full market metadata. Use this event to trigger redemption workflows. Polymarket Protocol V2 markets announce their results with this type; see [Polymarket Protocol V2 fields](#polymarket-protocol-v2-fields). ## Resolution Event (real payload) A tennis market resolved — Baena won the first set: ```json theme={null} { "type": "oracle", "timestamp": 1773755193000, "data": { "adapter_address": "0x65070be91477460d8a7aeeb94ef92fe056c2f2a7", "block_number": 84317580, "condition_id": "0xb0b51e92993bf204c76f10a49bdaa595d817f1768a9ae79e546e83695f1cb142", "event_title": "Murcia: Nikolas Sanchez Izquierdo vs Roberto Carballes Baena", "event_type": "oracle", "log_index": 197, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/atp-tour-b4390c4fb8.jpg", "market_slug": "atp-izquier-baena-2026-03-16-first-set-winner-Izquierdo-vs-Baena", "market_title": "Set 1 Winner: Izquierdo vs Baena", "neg_risk": false, "oracle_type": "resolution", "outcomes": ["Izquierdo", "Baena"], "payouts": [0, 1], "question_id": "0x34241c96d35a8ffbd4093f9a360e08f97c5691f66e9bfe29dd46e4763dae833e", "resolved_outcome": "Baena", "resolved_price": 0, "timestamp": 1773755193000, "token_ids": [ "100092605222559788173670687007064638617594421724580870112622623059744413023416", "82111831612810431769649657775457339958533284370449876495200499593908955489467" ], "tokens": { "100092605222559788173670687007064638617594421724580870112622623059744413023416": "Izquierdo", "82111831612810431769649657775457339958533284370449876495200499593908955489467": "Baena" }, "tx_hash": "" } } ``` ## Proposal Event (ProposePrice from OO V2) A proposer submits YES for an XRP price market, with a 2-hour liveness window. Proposals include full market metadata: ```json theme={null} { "type": "oracle", "timestamp": 1773755537000, "data": { "adapter_address": "0x65070be91477460d8a7aeeb94ef92fe056c2f2a7", "block_number": 84317752, "condition_id": "0xc9d0815d7f12e601ac3ce457de5b5d6f18ba5f48df5ffd246cec4c19a9254200", "event_title": "What price will XRP hit on March 17?", "event_type": "oracle", "expiration_timestamp": 1773762737000, "log_index": 372, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/XRP-logo.png", "market_slug": "will-xrp-dip-to-1pt5-on-march-17", "market_title": "Will XRP dip to $1.50 on March 17?", "neg_risk": false, "oracle_type": "proposal", "outcomes": ["Yes", "No"], "proposed_price": 1, "proposer": "0xedc1e7a3a9275c512f669cb9236f1d03c2fc2e39", "question_id": "oo_v2:0x65070be91477460d8a7aeeb94ef92fe056c2f2a7:1773720049", "timestamp": 1773755537000, "token_ids": [ "29532348047030596543075496892560093525999458628692812631919395372535371275514", "43096817250499798050326473461465682146308168398097552897166323529988349492396" ], "tokens": { "29532348047030596543075496892560093525999458628692812631919395372535371275514": "Yes", "43096817250499798050326473461465682146308168398097552897166323529988349492396": "No" }, "tx_hash": "" } } ``` ## Field Reference ### Core Fields (all oracle events) **oracle\_type** `string` *required* Type of oracle event: `initialization`, `proposal`, `dispute`, `settled`, `resolution`, `condition_resolution`, `reset`, `flag`, `unflag`, `pause`, `unpause`, `manual_resolution`. **question\_id** `string` *required* UMA's unique identifier for this market question. On Polymarket Protocol V2 markets, the condition id. **adapter\_address** `string` *required* Which UMA adapter contract this event relates to. On Polymarket Protocol V2 markets, the market's Polymarket module contract. **block\_number** `number` *required* Polygon block number where the event was emitted. **log\_index** `number` *required* Position of this event within the block's logs. **timestamp** `number` *required* Block timestamp in milliseconds. ### Proposal Fields (proposal only) **proposer** `string` Address of the account that proposed the resolution. **proposed\_price** `number` The proposed answer. `1.0` = YES (first outcome), `0.0` = NO (second outcome). **expiration\_timestamp** `number` When the 2-hour liveness window expires (unix milliseconds). After this time, the proposal can be settled if not disputed. ### Dispute Fields (dispute only) **disputer** `string` Address of the account that disputed the proposal. **proposer** `string` Address of the original proposer whose answer is being challenged. **proposed\_price** `number` The proposed answer that was disputed. ### Resolution Fields (resolution, condition\_resolution, settled, and manual\_resolution) **resolved\_price** `number` The settled price from UMA. `1.0` = first outcome wins (usually YES), `0.0` = second outcome wins (usually NO), `0.5` = split/tie. **resolved\_outcome** `string` Human-readable winning outcome (e.g. "Yes", "No", "L1ga Team"). Derived from `resolved_price` + market metadata. Returns `"Split"` for voided markets where payouts are `[1, 1]`. **payouts** `array` Payout array from UMA. `[1, 0]` means the first outcome wins. `[0, 1]` means the second outcome wins. `[1, 1]` means a split (both outcomes pay out). Present on `resolution`, `condition_resolution`, and `manual_resolution`. Polymarket Protocol V2 results use the same form. ### Polymarket Protocol V2 fields Present only on `condition_resolution` events for [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). Absent on every other market. **protocol\_version** `string` `"v2"`. **module** `string` `"binary"` for yes/no markets, `"neg_risk"` for multi-outcome markets. **payouts\_ppm** `array` The exact result as shares of 1,000,000, for example `[1000000, 0]` (first outcome wins) or `[500000, 500000]` (50/50). `payouts` carries the same result in its usual form. **derived** `boolean` `true` when a multi-outcome result follows from the rest of its event rather than from its own report, for example an outcome that resolves No because another outcome in the same event won. ### Enrichment Fields (from Polymarket metadata) These fields are populated automatically when the market's metadata is available. **condition\_id** `string` Polymarket's condition identifier for this market. **market\_title** `string` Human-readable market question (e.g. "Will Bitcoin reach \$100K?"). **market\_slug** `string` URL slug for the market on polymarket.com. **event\_title** `string` Parent event name if this market is part of a group (e.g. "Dota 2: Pipsqueak+4 vs L1ga Team (BO3)"). **market\_image** `string` Market image URL from Polymarket. **outcomes** `array` All outcome names for this market (e.g. `["Yes", "No"]` or `["Pipsqueak+4", "L1ga Team"]`). **token\_ids** `array` All conditional token IDs for this market. **tokens** `object` Map of token ID to outcome name (e.g. `{"2174263...": "Yes", "4839315...": "No"}`). **neg\_risk** `boolean` Whether this market uses the neg-risk framework (multi-outcome markets like elections). ## Frequency Oracle events are **not evenly distributed**. They come in bursts when UMA's resolver bot processes batches of markets. | Period | Typical Volume | | - | - | | Active sports hours | 200+ resolutions/hour, proposals flowing continuously | | Quiet periods | 10-50 resolutions/hour | | Proposals (ProposePrice) | \~30/hour, continuous flow | | Settlements (Settle) | \~30/hour, fires after 2-hour liveness | | Disputes | A few per month (high signal) | | Flags / Manual resolutions | Very rare | ## Trading Implications | Event | What It Means | Action | | - | - | - | | **initialization** | New market registered on-chain. | First signal of a new tradeable market | | **proposal** | Answer proposed, 2-hour countdown started. | Monitor for disputes, position accordingly | | **dispute** | Proposed outcome challenged. Uncertainty returns. | Watch for price swings, potential arb | | **settled** | Oracle accepted the answer after liveness. | Resolution imminent | | **resolution** | Market outcome decided on UMA adapter. For neg-risk markets, positions are not yet redeemable. | Outcome known, prepare for redemption | | **condition\_resolution** | Condition resolved on CTF contract. **Positions are now redeemable.** | Trigger redemption, notify users | | **reset** | Market re-enters proposal phase after dispute. | Resolution delayed, reassess positions | | **flag** | Admin flagged an issue. Market may be paused. | Caution, reduce exposure | | **manual\_resolution** | Admin override. Could be controversial. | Check outcome, compare to expectations | # Position Change Event Source: https://docs.polynode.dev/websocket/events/position-change Polymarket position transfers between wallets. Emitted when conditional tokens are transferred between wallets (ERC-1155 `TransferSingle` or `TransferBatch` events on Polymarket's CTF contract). ```json theme={null} { "data": { "amount": 0.050921, "block_number": 84697556, "condition_id": "0xc288913391d7d3b484d9e63f60996671a1888207e0d9917691c5257cbab09309", "event_title": "Bitcoin Up or Down - March 26, 4:50AM-4:55AM ET", "event_type": "position_change", "from": "0xe3f18acc55091e2c48d883fc8c8413319d4ab7b0", "log_index": 2147, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "market_slug": "btc-updown-5m-1774515000", "market_title": "Bitcoin Up or Down - March 26, 4:50AM-4:55AM ET", "neg_risk": false, "outcome": "Up", "outcomes": ["Up", "Down"], "taker_base_fee": 1000.0, "tick_size": 0.01, "timestamp": 1774515147000, "to": "0xb27bc932bf8110d8f78e55da7d5f0497a18b5b82", "token_id": "58779171378753040273547833889411100281640930430837040192014777442237090167078", "token_ids": [ "58779171378753040273547833889411100281640930430837040192014777442237090167078", "44910406836464179003614524044201701268382942629198430107881894265432491492514" ], "tokens": { "44910406836464179003614524044201701268382942629198430107881894265432491492514": "Down", "58779171378753040273547833889411100281640930430837040192014777442237090167078": "Up" }, "transfer_type": "single", "tx_hash": "0x2b72f18ba36846fa72c7083e89d1a66438e0b9b15e170325f4efde5d08cc602e" }, "timestamp": 1774515147000, "type": "position_change" } ``` ## Fields **type** `string` *required* Always `"position_change"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **from** `string` *required* Sender wallet address. **to** `string` *required* Receiver wallet address. **token\_id** `string` *required* Conditional token ID being transferred. **amount** `number` *required* Number of tokens transferred. **transfer\_type** `string` *required* `"single"` (TransferSingle) or `"batch"` (TransferBatch). **market\_title** `string` Human-readable market question. Enriched from metadata. **outcome** `string` Outcome name (e.g. "Yes", "No"). Enriched from metadata. **market\_slug** `string` Market URL slug. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **market\_image** `string` Market image URL. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **condition\_id** `string` Market condition ID (CTF contract identifier). Enriched from metadata. **outcomes** `string[]` Ordered list of outcome names (e.g. `["Yes", "No"]`). Index-aligned with `token_ids`. Enriched from metadata. **token\_ids** `string[]` Ordered list of token IDs for this market. Index-aligned with `outcomes`. Enriched from metadata. **tokens** `object` Map of token ID → outcome name for all outcomes in this market. Enriched from metadata. > [!NOTE] > > Position changes from settlements are **not** duplicated here — the `settlement` event already contains the trade details. This event tracks non-trade transfers: wallet migrations, OTC deals, and smart contract interactions. # Position Merge Event Source: https://docs.polynode.dev/websocket/events/position-merge Outcome tokens merged back into collateral on Polymarket. Emitted when outcome tokens (YES + NO shares) are merged back into collateral (USDC) via the Conditional Tokens Framework `mergePositions` function. The inverse of a [position split](/websocket/events/position-split). Merges are much rarer than splits (\~20x less frequent). They happen when a trader holds both YES and NO tokens for a condition and redeems them back to USDC. ```json theme={null} { "data": { "amount": 1414.0, "block_number": 84090704, "collateral_token": "0x3a3bd7bb9528e159577f7c2e685cc81a765002e2", "condition_id": "0xd1747284d6048b2a3dcfbee489db405f36de18f9590197dd0e5c9f0c246bf050", "event_title": "Republican Presidential Nominee 2028", "event_type": "position_merge", "log_index": 1004, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/Byron_Donalds.png", "market_slug": "will-byron-donalds-win-the-2028-republican-presidential-nomination", "market_title": "Will Byron Donalds win the 2028 Republican presidential nomination?", "neg_risk": true, "stakeholder": "0xd91e80cf2e7be2e162c6513ced06f1dd0da35296", "taker_base_fee": 0.0, "tick_size": 0.001, "timestamp": 1773301441000, "tokens": { "311624663652221737215322113380496984764966764039692273354641152455298576851": "Yes", "43292374563904271719486871569114922516560719431752184778538513591321835161630": "No" }, "tx_hash": "0x92fa6de980f6cad9eae9ef28e908d19faa10838a07f01352b0cae63b5f8299fb" }, "timestamp": 1773301441000, "type": "position_merge" } ``` ## Fields **type** `string` *required* Always `"position_merge"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **stakeholder** `string` *required* Address that triggered the merge. **collateral\_token** `string` *required* Collateral token address. USDC.e (`0x2791bca1f2de4661ed88a30c99a7a9449aa84174`) for standard markets, wrapped collateral (`0x3a3bd7bb...`) for neg\_risk markets. **condition\_id** `string` *required* Market condition ID — identifies which market's outcome tokens were burned. **amount** `number` *required* USDC amount received from merging outcome tokens (6 decimal precision). **market\_title** `string` Human-readable market question. Populated when metadata is available. **market\_slug** `string` URL slug for the market. **market\_image** `string` Market image URL. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **tokens** `object` Map of token ID → outcome name for all outcomes in this market. Enriched from metadata. ## Use cases * **Position unwinding** — detect when traders are closing positions by merging outcome tokens * **Liquidity withdrawal tracking** — merges reduce the total supply of outcome tokens in a market * **Arbitrage detection** — merges after buying both outcomes at favorable prices signal arbitrage > [!NOTE] > > Not included in `global` firehose (full data stream) by default. Subscribe explicitly with `event_types: ["position_merge"]` or use the `wallets`/`markets` subscription types which include it automatically. # Position Split Event Source: https://docs.polynode.dev/websocket/events/position-split Collateral split into outcome tokens on Polymarket. Emitted when collateral (USDC) is split into outcome tokens (YES/NO shares) via the Conditional Tokens Framework `splitPosition` function. 99%+ of splits happen as part of trade execution. This event provides supplementary data: how much collateral was split and into which market condition. ```json theme={null} { "data": { "amount": 5.190306, "block_number": 84090704, "collateral_token": "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", "condition_id": "0xab3eea0d5b61cd443affca5fcd19d3541e92f7c96f7e92111982fbcbff56bb55", "event_title": "Bitcoin Up or Down - March 12, 3:40AM-3:45AM ET", "event_type": "position_split", "log_index": 763, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "market_slug": "btc-updown-5m-1773301200", "market_title": "Bitcoin Up or Down - March 12, 3:40AM-3:45AM ET", "neg_risk": false, "stakeholder": "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "taker_base_fee": 1000.0, "tick_size": 0.01, "timestamp": 1773301441000, "tokens": { "47635040450827094965464370243227927750353541381049355332417378831540287352201": "Up", "57924371746740845060329991315866785058480643549619724503463886953768356812176": "Down" }, "tx_hash": "0x74dbde22f31ce8dcbc5b3c187c33cd131d9bb5791874e139b41c1049ae3589fc" }, "timestamp": 1773301441000, "type": "position_split" } ``` ## Fields **type** `string` *required* Always `"position_split"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **stakeholder** `string` *required* Address that triggered the split (usually the exchange contract, sometimes a direct user). **collateral\_token** `string` *required* Collateral token address. USDC.e (`0x2791bca1f2de4661ed88a30c99a7a9449aa84174`) for standard markets, wrapped collateral (`0x3a3bd7bb...`) for neg\_risk markets. **condition\_id** `string` *required* Market condition ID — identifies which market's outcome tokens were minted. **amount** `number` *required* USDC amount that was split into outcome tokens (6 decimal precision). **market\_title** `string` Human-readable market question. Populated when metadata is available. **market\_slug** `string` URL slug for the market. **market\_image** `string` Market image URL. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **tokens** `object` Map of token ID → outcome name for all outcomes in this market. Enriched from metadata. ## Use cases * **Collateral flow analysis** — track how much USDC is being converted into outcome tokens * **Market liquidity creation** — splits indicate new shares being minted for a market * **Trade enrichment** — pair with `trade` events to see the full lifecycle of a trade (split → fill) > [!NOTE] > > Not included in `global` firehose (full data stream) by default due to high volume (splits fire on most trades). Subscribe explicitly with `event_types: ["position_split"]` or use the `wallets`/`markets` subscription types which include it automatically. # Positions Converted Event Source: https://docs.polynode.dev/websocket/events/positions-converted Position conversion on neg-risk multi-outcome markets. Emitted when a user calls `convertPositions` on the NegRiskAdapter contract. This converts NO positions on selected outcomes into USDC plus YES positions on the complementary outcomes within the same multi-outcome market. Conversions are unique to neg-risk markets (multi-outcome events like "Republican Presidential Nominee" or "FIFA World Cup Winner"). They allow traders to rebalance positions across outcomes without going through the orderbook. ```json theme={null} { "data": { "amount": 98, "block_number": 85007631, "converted_outcomes": [ "Fidesz-KDNP", "TISZA" ], "event_title": "Hungary Parliamentary Election Winner", "event_type": "positions_converted", "index_set": "0x0000000000000000000000000000000000000000000000000000000000000021", "log_index": 943, "market_id": "0x355e7310dd6e18ef5fa456de7ce1331bd8c7540c4c39028db05325be19050100", "neg_risk": true, "stakeholder": "0x30cecdf29f069563ea21b8ae94492e41e53a6b2b", "taker_base_fee": null, "timestamp": 1775135299000, "tx_hash": "0x74fcb24732007ec58042c6e2ed7596c44a12f2fb34dec8bef9bbd3eaeb020718" }, "timestamp": 1775135299000, "type": "positions_converted" } ``` ## Fields **type** `string` *required* Always `"positions_converted"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **stakeholder** `string` *required* Wallet address that performed the conversion. **market\_id** `string` *required* The neg-risk market group ID (bytes32). All outcomes within the same multi-outcome event share this ID. **index\_set** `string` *required* Bitmask (hex) of which outcome indices were converted. Each bit position corresponds to an outcome in the market. For example, `0x03` (binary `11`) means outcomes at index 0 and 1 were converted. **amount** `number` *required* USDC amount per outcome that was converted (6 decimal precision). **converted\_outcomes** `string[]` Human-readable names of the outcomes that were converted. Decoded from the `index_set` bitmask using market metadata. For example: `["Fidesz-KDNP", "TISZA"]`. **event\_title** `string` Parent event title (e.g. "Hungary Parliamentary Election Winner"). Enriched from metadata. **neg\_risk** `boolean` Always `true` for conversion events (conversions only exist on neg-risk markets). **market\_title** `string` Market question. Enriched from metadata when available. **market\_slug** `string` URL slug for the market. Enriched from metadata. **market\_image** `string` Market image URL. Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. Enriched from metadata. **tokens** `object` Map of token ID to outcome name for all outcomes in this market. Enriched from metadata. ## How conversions work On a neg-risk market with N outcomes, a user holding NO positions on selected outcomes can convert them: 1. The user's NO tokens on the selected outcomes are burned 2. The user receives **(number of NO positions - 1) x amount** in USDC 3. The user receives YES tokens on all complementary outcomes (the ones NOT in the index\_set) This enables efficient position rebalancing without using the orderbook. ## Use cases * **Whale tracking** — large conversions signal sophisticated repositioning across outcomes * **Market structure analysis** — conversion flow reveals which outcomes traders are moving between * **Liquidity detection** — conversions create new YES token supply on complementary outcomes * **Arbitrage monitoring** — conversions can indicate perceived mispricing between outcomes > [!NOTE] > > Not included in `global` firehose by default (same as `position_split`/`position_merge`). Subscribe explicitly with `event_types: ["positions_converted"]` or use the `wallets`/`markets` subscription types which include it automatically. # Price Feed Event Source: https://docs.polynode.dev/websocket/events/price-feed Real-time crypto price updates -- BTC, ETH, SOL, BNB, XRP, DOGE, HYPE. Real-time crypto price data. Updates arrive approximately once per second per feed, streamed directly over WebSocket. Subscribe with `"type": "chainlink"` to receive price feed events. > [!NOTE] > > For the full guide including all 7 available feeds, filtering, and examples, see the **[Crypto Prices](/crypto/overview)** section. ```json theme={null} { "type": "price_feed", "feed": "BTC/USD", "timestamp": 1774672089, "data": { "feed": "BTC/USD", "price": 66236.61, "bid": 66229.77, "ask": 66237.94, "timestamp": 1774672089 } } ``` ## Subscribing ```json theme={null} {"action": "subscribe", "type": "chainlink"} ``` With feed filter (only receive specific feeds): ```json theme={null} { "action": "subscribe", "type": "chainlink", "filters": { "feeds": ["BTC/USD", "ETH/USD"] } } ``` Omit the `feeds` filter to receive all available price feeds. ## Response ```json theme={null} { "type": "subscribed", "subscriber_id": "550e8400-e29b-41d4-a716-446655440000", "subscription_type": "chainlink" } ``` > [!NOTE] > > Price feed subscriptions do not include a snapshot. Events start arriving with the next price observation (\~1 second). ## Fields **type** `string` *required* Always `"price_feed"`. **feed** `string` *required* Feed name (e.g. `"BTC/USD"`, `"ETH/USD"`). **timestamp** `number` *required* Observation timestamp in Unix seconds. **data** `object` *required* **data fields** **feed** `string` *required* Feed name (e.g. `"BTC/USD"`). **price** `number` *required* Mid price in USD. **bid** `number` *required* Bid price in USD. **ask** `number` *required* Ask price in USD. **timestamp** `number` *required* Observation timestamp in Unix seconds. ## Available feeds | Feed | Update rate | | - | - | | `BTC/USD` | \~1/second | | `ETH/USD` | \~1/second | | `SOL/USD` | \~1/second | | `BNB/USD` | \~1/second | | `XRP/USD` | \~1/second | | `DOGE/USD` | \~1/second | | `HYPE/USD` | \~1/second | See **[Available Feeds](/crypto/feeds)** for detailed per-feed documentation. ## Dual subscription Price feeds run on the same WebSocket connection as settlement subscriptions. Send both subscribe messages to receive both: ```json theme={null} {"action": "subscribe", "type": "settlements"} {"action": "subscribe", "type": "chainlink"} ``` Events arrive interleaved. Use the `type` field (`"settlement"` vs `"price_feed"`) to route them in your application. # Redemption Event Source: https://docs.polynode.dev/websocket/events/redemption Position payout redemptions on Polymarket. Emitted when a user redeems their outcome tokens for collateral after a market resolves. The `redeemPositions` function on the Conditional Tokens contract burns the user's shares and pays out USDC based on the resolved outcome. Every resolved market generates redemption events as holders claim their payouts. A non-zero `payout` means the user held winning shares. A zero payout means the user redeemed losing shares (no collateral returned). Recent redemption events also include the market's resolved payout vector when available. Use `winning_outcome`, `winning_token_id`, or the ordered `payouts` / `outcome_prices` arrays to identify which outcome won without making a second market lookup. This is the comprehensive redemption event class. It includes direct Conditional Tokens redemptions and PM2 AutoRedeemer payouts for normal Binary/NegRisk positions and generic combo positions. For AutoRedeemer transactions, `redeemer` is the user wallet from the AutoRedeemer log, not the contract, and `source` identifies the route. ```json theme={null} { "data": { "block_number": 85244342, "collateral_token": "0x2791bca1f2de4661ed88a30c99a7a9449aa84174", "condition_id": "0x487f28579354d6c4408eea243888cdedbe03e83a219a4708523ef455dcbc5e31", "event_title": "Bitcoin Up or Down - April 7, 8:15PM-8:20PM ET", "event_type": "redemption", "index_sets": [1, 2], "log_index": 1282, "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/BTC+fullsize.png", "market_slug": "btc-updown-5m-1775607300", "market_title": "Bitcoin Up or Down - April 7, 8:15PM-8:20PM ET", "neg_risk": false, "outcome_prices": [1.0, 0.0], "outcomes": ["Up", "Down"], "payout": 7.566434, "payout_e6": "7566434", "payouts": [1, 0], "redeemer": "0x8858aae9c92a82b00986a0f1a66338e8b0cc8641", "taker_base_fee": 1000, "tick_size": 0.01, "timestamp": 1775608721000, "token_ids": [ "81518481532502107093994258923994884503752044066839262771005198927094175386674", "112731399428633109059368520083498445904538970112239739400592554575174180266461" ], "tokens": { "112731399428633109059368520083498445904538970112239739400592554575174180266461": "Down", "81518481532502107093994258923994884503752044066839262771005198927094175386674": "Up" }, "tx_hash": "0xcfb51c25a8f6ebb0b5a7484de7812d66f2cbf9935f29c0b56561e74722c64fac", "winning_outcome": "Up", "winning_outcome_index": 0, "winning_token_id": "81518481532502107093994258923994884503752044066839262771005198927094175386674" }, "timestamp": 1775608721000, "type": "redemption" } ``` ## Fields **type** `string` *required* Always `"redemption"`. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **redeemer** `string` *required* Address that redeemed positions. This is the wallet that held the outcome tokens and called `redeemPositions`. **collateral\_token** `string` *required* Collateral token address. USDC.e (`0x2791bca1f2de4661ed88a30c99a7a9449aa84174`) for standard markets. **condition\_id** `string` *required* Market condition ID — identifies which resolved market's positions were redeemed. **index\_sets** `number[]` *required* Which outcome slots were redeemed. `[1]` = first outcome only, `[2]` = second outcome only, `[1, 2]` = both outcomes. Most redemptions include all outcomes (`[1, 2]`). **payout** `number` *required* USDC amount paid out to the redeemer (6 decimal precision). `0` means the user redeemed losing shares and received nothing. **payout\_e6** `string` Exact payout amount in six-decimal integer units. Use this for accounting-safe comparisons. **source** `string` Decoder path for bridged redemptions. `AutoRedeemer.BinaryRedemption` and `AutoRedeemer.NegRiskRedemption` identify normal Binary/NegRisk AutoRedeemer payouts; `AutoRedeemer.Redemption` identifies the generic combo AutoRedeemer route. Direct Conditional Tokens redemptions do not use an AutoRedeemer source. **market\_title** `string` Human-readable market question. Enriched from metadata. **market\_slug** `string` URL slug for the market. **market\_image** `string` Market image URL. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Enriched from Polymarket metadata. **tokens** `object` Map of token ID to outcome name for all outcomes in this market. Enriched from metadata. **token\_ids** `string[]` Ordered token IDs for this market. Same order as `outcomes`, `payouts`, and `outcome_prices`. **outcomes** `string[]` Ordered outcome labels for this market. Same order as `token_ids`, `payouts`, and `outcome_prices`. **payouts** `number[]` Resolved payout numerators for each outcome. Binary markets usually resolve to `[1, 0]` or `[0, 1]`. **outcome\_prices** `number[]` Normalized payout value for each outcome. Binary winners are `1.0`, losing outcomes are `0.0`; split outcomes can be fractional. **winning\_outcome\_index** `number` Index of the winning outcome when exactly one outcome has a non-zero payout. **winning\_outcome** `string` Label of the winning outcome when exactly one outcome has a non-zero payout. **winning\_token\_id** `string` Token ID of the winning outcome when exactly one outcome has a non-zero payout. ## Use cases * **Payout tracking** — monitor who is cashing out resolved positions and how much they receive * **Wallet PnL** — combine with trade data to calculate realized profit/loss per wallet * **Market lifecycle** — track the full arc from trading to resolution to redemption * **Winning wallet alerts** — filter for large `payout` values to spot big winners as they redeem * **Outcome-aware automations** — use `winning_outcome` or `outcome_prices` directly instead of waiting on slower market metadata refreshes ## Subscribing Subscribe directly to redemptions: ```json theme={null} { "action": "subscribe", "type": "redemptions" } ``` Or request redemptions from the settlement stream: ```json theme={null} { "action": "subscribe", "type": "settlements", "filters": { "event_types": ["redemption"] } } ``` To receive combo redemptions only, subscribe to `type: "combos"` with `event_types: ["combo_lifecycle"]` and `action: "Redeem"`. If you subscribe to both surfaces, a generic combo AutoRedeemer payout can appear in both shapes; correlate or deduplicate it with `tx_hash` and `log_index`. Filter to only winning redemptions using `min_size`: ```json theme={null} { "action": "subscribe", "type": "settlements", "filters": { "event_types": ["redemption"], "min_size": 0.01 } } ``` Track redemptions for specific wallets: ```json theme={null} { "action": "subscribe", "type": "wallets", "filters": { "wallets": ["0x8858aae9c92a82b00986a0f1a66338e8b0cc8641"], "event_types": ["redemption"] } } ``` # Settlement Event Source: https://docs.polynode.dev/websocket/events/settlement Polymarket settlement — pending (pre-chain) or confirmed (on-chain). The core polynode event. A Polymarket settlement detected before or after on-chain confirmation. **Pending settlements arrive 3–5 seconds before on-chain confirmation (1–2 Polygon blocks).** This is the data that makes polynode unique. > [!NOTE] > > **Every Polymarket exchange.** Settlement events work the same for the original exchange (V1), Polymarket's April 2026 exchange upgrade (V2) and ExchangeV3, which settles Polymarket Protocol V2 markets. No subscription changes are needed: the event format, trade fields and enrichment are the same, and `exchange_version` on each trade tells them apart. V2 settlement events may include `condition_id` directly from the V2 matchOrders calldata. See the [V2 Migration Guide](/guides/v2-migration) and [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ```json theme={null} { "data": { "block_number": null, "condition_id": "0xb564e5e20a0d3ab9b07d24ff25b19001d9d6b2d1d3121d4b9a2a0691713643cb", "detected_at": 1774515004952, "event_slug": "will-mara-corina-machado-enter-venezuela-by-january-31", "event_title": "María Corina Machado enters Venezuela by...?", "event_type": "settlement", "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/will-mara-corina-machado-enter-venezuela-by-january-31-2JimdK2AkPpQ.jpg", "market_slug": "will-mara-corina-machado-enter-venezuela-by-april-30", "market_title": "Will María Corina Machado enter Venezuela by April 30?", "neg_risk": false, "outcome": "No", "outcomes": ["Yes", "No"], "status": "pending", "taker_base_fee": null, "taker_price": 0.85, "taker_side": "BUY", "taker_size": 12.1647, "taker_token": "105661833938076784158167307763414073000325182187633954283290589114908891807534", "taker_wallet": "0x5b78254f3e639788fed14221bf8a8bd15c2fa88a", "tick_size": 0.01, "token_ids": [ "52054255865962303053567273154012826122522952121382457828722214406382382900565", "105661833938076784158167307763414073000325182187633954283290589114908891807534" ], "tokens": { "105661833938076784158167307763414073000325182187633954283290589114908891807534": "No", "52054255865962303053567273154012826122522952121382457828722214406382382900565": "Yes" }, "trades": [ { "maker": "0x0bfb8009df6c46c1fdd79b65896cf224dc4526a7", "maker_amount": "96000000", "order_hash": "0x2ca8ef3e7a72fac98a54fba5d92cdbf352633e3f7d929252f3204c35ca65ae80", "outcome": "Yes", "price": 0.16, "side": "BUY", "signer": "0x9b4371d8fe1fad11c0a2209ebbc4ca97a040b3f2", "size": 600.0, "taker": "0x5b78254f3e639788fed14221bf8a8bd15c2fa88a", "taker_amount": "600000000", "token_id": "52054255865962303053567273154012826122522952121382457828722214406382382900565" }, { "maker": "0x5b78254f3e639788fed14221bf8a8bd15c2fa88a", "maker_amount": "10340000", "order_hash": "0x42961ee60f3ad3bea6df8fb1f98abcf090a05cd03b70d697ab899ad4a960059d", "outcome": "No", "price": 0.85, "side": "BUY", "signer": "0x28167f8e9da7739f338056e52cea318892cad166", "size": 12.1647, "taker": "0x5b78254f3e639788fed14221bf8a8bd15c2fa88a", "taker_amount": "12164700", "token_id": "105661833938076784158167307763414073000325182187633954283290589114908891807534" } ], "tx_hash": "0xa5afa27aa8a7c1f75e24202f4a92d266b0ca965a306e3846574d0c1004a41b63" }, "timestamp": 1774515004952, "type": "settlement" } ``` > [!NOTE] > > Every WebSocket event is wrapped with three top-level fields: `type`, `timestamp`, and `data`. The `data` object also contains an `event_type` field that always matches the top-level `type` — use whichever is convenient for your parsing logic. ## Fields **type** `string` *required* Always `"settlement"`. **timestamp** `number` *required* Unix milliseconds. Use this as the canonical event time. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash (0x-prefixed). **status** `string` *required* `"pending"` — detected pre-chain, not yet confirmed. `"confirmed"` — included in a block. **detected\_at** `number` *required* Unix milliseconds when the transaction was first detected by PolyNode. **block\_number** `number | null` *required* Block number. `null` when `status` is `"pending"`, set when `"confirmed"`. **taker\_wallet** `string` *required* Taker (settler) wallet address. **taker\_token** `string` *required* Polymarket conditional token ID. **taker\_side** `string` *required* `"BUY"` or `"SELL"` — the taker's side of the trade. **taker\_price** `number` *required* Fill price (0.0–1.0 for binary markets). **taker\_size** `number` *required* Fill size in shares. **market\_title** `string` Human-readable market question. Enriched from Polymarket metadata. **outcome** `string` Outcome name (e.g. "Yes", "No", "Donald Trump"). Enriched from metadata. **market\_slug** `string` Market URL slug (e.g. `"bitcoin-100k-2026"`). Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **market\_image** `string` Market image URL. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **condition\_id** `string` Market condition ID (CTF contract identifier). Enriched from metadata. **protocol\_version** `string` `"v2"` on events for Polymarket Protocol V2 markets. Absent on every other market. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). **module** `string` Polymarket Protocol V2 markets only: `"binary"` for yes/no markets, `"neg_risk"` for multi-outcome markets. Absent on every other market. **event\_slug** `string` Parent event URL slug (e.g. `"will-mara-corina-machado-enter-venezuela-by-january-31"`). Enriched from metadata. **outcomes** `string[]` Ordered list of outcome names (e.g. `["Yes", "No"]`). Index-aligned with `token_ids`. Enriched from metadata. **token\_ids** `string[]` Ordered list of token IDs for this market. Index-aligned with `outcomes`. Enriched from metadata. **tokens** `object` Map of token ID → outcome name for all outcomes in this market (e.g. `{"123...": "Yes", "456...": "No"}`). Enriched from metadata. **trades** `object[]` *required* Array of matched maker orders in this settlement. **trade fields** **maker** `string` *required* Maker wallet address. **signer** `string` *required* Order signer address (may differ from maker for smart contract wallets). **taker** `string` *required* Taker wallet address. **token\_id** `string` *required* Conditional token ID. **side** `string` *required* `"BUY"` or `"SELL"`. **price** `number` *required* Fill price (0.0–1.0). **size** `number` *required* Fill size in shares. **maker\_amount** `string` *required* Raw maker amount (6 decimal USDC or tokens). **taker\_amount** `string` *required* Raw taker amount (6 decimal USDC or tokens). **outcome** `string` Outcome name for this trade's token (e.g. "Yes", "No", "Up"). Enriched from metadata. **order\_hash** `string` EIP-712 order hash for this maker's limit order. Persistent across partial fills. Computed from calldata pre-chain, so this is available on pending settlements before block confirmation. **exchange\_version** `string` Exchange contract version: `"v2"` for trades settled on Polymarket's April 2026 exchange contracts (CTF Exchange V2), `"v3"` for trades settled on ExchangeV3, which settles Polymarket Protocol V2 markets. Absent for trades on the original V1 exchange. Use this to distinguish which exchange system processed the settlement. ## Ordering guarantees **Confirmed settlements** are delivered in strict block order. All confirmed events from block N arrive before any from block N+1. Within a block, events are ordered by log index. Polygon uses Bor consensus with single-validator sprints, making chain reorganizations effectively nonexistent. **Pending settlements** are best-effort ordered by detection time. Because they are extracted from the mempool before block inclusion, there is no guaranteed global sequence. Two pending events detected within the same second may arrive in either order. Do not assume pending ordering reflects eventual on-chain ordering. **Pending-to-confirmed pairing:** every pending settlement will be followed by a corresponding `status_update` event when the same `tx_hash` confirms on-chain. You will never receive a confirmed update without a prior pending event for the same transaction. **A note on sender and nonce:** Polymarket trades are submitted by Polymarket's relayer EOAs, not by the traders themselves. Users sign EIP-712 orders off-chain, and the relayer submits the on-chain transaction. The transaction sender and nonce reflect the relayer's state, not the trader's intent or ordering. For this reason, sender address and nonce are not included in settlement events — they would be misleading to build on. ## The full lifecycle For every Polymarket settlement, polynode emits up to three events on the WebSocket stream as the transaction moves from mempool to confirmed block: | Event | When it fires | Source | What it contains | | - | - | - | - | | **`settlement` (pending)** | 3–5s before block confirmation | Mempool calldata | All fills in `data.trades[]`, decoded from the matchOrders calldata. Per-maker prices are estimated from aggregate amounts. | | **`status_update`** | At block confirmation | Receipt logs | Confirmation metadata (block, latency) **plus** `data.confirmed_fills[]` — exact per-fill data from the on-chain `OrderFilled` logs. | | **`settlement` (confirmed)** *(legacy)* | At block confirmation | Calldata replay | Same shape as the pending settlement, with `status: "confirmed"` and `block_number` set. Same calldata-derived prices. | The pending settlement gives you speed (2–5 second lead before the block). The `status_update` with `confirmed_fills` gives you exactness — those are the canonical prices Polymarket itself reads from the chain. ### Pending → confirmed pairing Every pending settlement is followed by a corresponding `status_update` event when the same `tx_hash` confirms on-chain. Match them by `tx_hash`: ```javascript theme={null} const pending = new Map(); ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, msg.data); return; } if (msg.type === "status_update") { const original = pending.get(msg.data.tx_hash); pending.delete(msg.data.tx_hash); // The status_update has confirmed_fills with the EXACT prices from // the on-chain OrderFilled logs. Compare against the pending estimate // if you want, or just use confirmed_fills as the source of truth. for (const fill of msg.data.confirmed_fills || []) { console.log(`Confirmed: ${fill.side} ${fill.size} @ ${fill.price} (block ${msg.data.block_number})`); } } }; ``` ### When to use which * **Pending `settlement` only** — you want the 2–5 second lead time and you don't mind \~0.01–0.04 estimation error on the rare multi-maker fill (e.g. copy trading, frontend price ticks). * **`status_update.confirmed_fills` only** — you need exact prices and don't care about pre-confirmation. (e.g. analytics, P\&L, bookkeeping). * **Both together (pending settlement + status\_update with confirmed\_fills)** — you want the speed of pending detection AND the exact prices once confirmed. The recommended pattern for most production integrations. For the full schema of `confirmed_fills[]` and a longer treatment of when to use each layer, see the [Trade Tracking guide](/guides/trade-tracking) and the [Status Update event reference](/websocket/events/status-update). ## Pending vs confirmed (field-level) | Field | Pending | Confirmed | | - | - | - | | `status` | `"pending"` | `"confirmed"` | | `block_number` | `null` | block number | | `detected_at` | when polynode first detected TX | same value | | Latency | \~0ms from detection | 2–5s after detection (1–2 blocks) | > [!TIP] > > Subscribe with `"status": "pending"` to get the 2–5 second edge. You'll receive a separate `status_update` event when the same transaction confirms on-chain, including `latency_ms` and `confirmed_fills[]`. ## Use cases * **Copy trading** — detect whale trades 1–2 blocks before confirmation and execute your own order * **Market making** — adjust spreads based on incoming settlements * **Analytics** — track real-time volume and price movements * **Alerts** — notify on large trades or specific wallet activity ## Tracking a specific wallet's trades > [!WARNING] > > **To find a wallet's trades, iterate `data.trades[]` and match by `maker`. Never match by `taker`.** The `maker` field on each entry is the wallet that placed the order. The `taker` field is the counterparty, which is not what you want. Each entry in `data.trades[]` is one fill, and the `maker` field on that entry is the wallet whose trade it is. To track a specific wallet, find the entries in `trades[]` where `maker === your_wallet`: ```javascript theme={null} ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type !== "settlement") return; for (const fill of msg.data.trades) { if (fill.maker.toLowerCase() === MY_WALLET.toLowerCase()) { console.log("My trade:", fill.side, fill.size, fill.outcome, "@", fill.price); } } }; ``` That's it. One rule: **`maker === your_wallet`**. ### Why not match by `taker` If you match by `taker === your_wallet`, you get **counterparty fills**, not the wallet's actual trade. The `taker` field on each fill is the opposite party, so matching it gives you the wrong wallet's perspective — including the **opposite token** and the **complement price**. For example, if your wallet bought Up at 0.80, matching by `taker` returns a fill showing the counterparty buying Down at 0.20. For a deeper explanation of why the on-chain `OrderFilled` events are structured this way, see the [Trade Event reference](/websocket/events/trade#tracking-a-specific-wallets-trades) or the [Dome migration guide](/dome-migration#order-perspective). # Status Update Event Source: https://docs.polynode.dev/websocket/events/status-update Notification when a pending settlement confirms on-chain, with exact fill data from receipt logs. Fired when a previously pending settlement is confirmed in a block. Links back to the original `settlement` event via `tx_hash`, includes the confirmation latency, and attaches **confirmed fill data** from on-chain `OrderFilled` receipt logs. The `confirmed_fills` array contains the exact execution prices and sizes from the blockchain — the same data source Polymarket's own activity API reads. This gives you both speed (pre-confirmation detection) and accuracy (on-chain execution data) in a single subscription. ```json theme={null} { "data": { "block_number": 85296338, "condition_id": "0xcd1b782d94423552e19db1ca2bec7bcf5a445de8586638e41da75fae3d138ac4", "confirmed_at": 1775713418000, "confirmed_fills": [ { "order_hash": "0x8238c0666c...", "maker": "0x48ac40fc...", "taker": "0xc51f90d3...", "token_id": "97486603884638701907147078120258734284412618667021950609483989581295500093074", "side": "BUY", "price": 0.56, "size": 2.25, "maker_amount": "1260000", "taker_amount": "2250000", "fee": 0.176785 }, { "order_hash": "0x3d388dd54a...", "maker": "0x25f4707c...", "taker": "0xc51f90d3...", "token_id": "97486603884638701907147078120258734284412618667021950609483989581295500093074", "side": "BUY", "price": 0.56, "size": 7.0, "maker_amount": "3920000", "taker_amount": "7000000", "fee": 0.55 } ], "event_title": "Augusta National Invitational - Winner ", "event_type": "status_update", "latency_ms": 3928, "maker_wallets": [ "0x48ac40fc...", "0x25f4707c..." ], "market_slug": "will-charl-schwartzel-win-the-2026-masters-tournament", "market_title": "Will Charl Schwartzel win the 2026 Masters tournament?", "neg_risk": true, "order_hashes": [ "0x8238c0666c...", "0x3d388dd54a..." ], "outcome": "No", "outcomes": ["Yes", "No"], "pending_detected_at": 1775713414072, "taker_wallet": "0xc51f90d3...", "tick_size": 0.001, "token_id": "97486603884638701907147078120258734284412618667021950609483989581295500093074", "tx_hash": "0x7599f442e4..." }, "timestamp": 1775713418000, "type": "status_update" } ``` ## Fields **type** `string` *required* Always `"status_update"`. **timestamp** `number` *required* Unix milliseconds of the confirmation. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash — matches the original `settlement` event. **token\_id** `string` *required* Conditional token ID. **block\_number** `number` *required* Block where the transaction was included. **confirmed\_at** `number` *required* Unix milliseconds of block confirmation. **pending\_detected\_at** `number` *required* Unix milliseconds when the transaction was first detected by polynode. **latency\_ms** `number` *required* Time between initial detection and block confirmation, in milliseconds. Typical values: 2000–5000ms (median \~2900ms). Corresponds to 1–2 Polygon blocks. **taker\_wallet** `string` *required* Taker wallet address from the original settlement. **maker\_wallets** `string[]` Maker wallet addresses from the original settlement. **order\_hashes** `string[]` EIP-712 order hashes from the original pending settlement. Each hash uniquely identifies a maker's limit order on Polymarket's order book. **execution\_status** `string` `"FAILED"` when the transaction was included in a block but failed on chain, so no trade settled. `confirmed_fills` is then absent. Omitted for successful confirmations. **confirmed\_fills** `object[]` Exact fill data from on-chain `OrderFilled` receipt logs. Each entry represents one maker's fill with the precise execution price and size as settled by the contract. Present when receipt decoding succeeds (vast majority of blocks). `null` on the rare occasion receipt data is unavailable. **confirmed fill fields** **order\_hash** `string` EIP-712 order hash for this specific fill. **maker** `string` Maker wallet address. **taker** `string` Taker wallet address (or exchange contract address for the taker's own fill event). **token\_id** `string` Conditional token ID for this specific fill. **side** `string` `"BUY"` or `"SELL"` from the maker's perspective. **price** `number` Exact execution price from the on-chain settlement. This is the canonical price — the same value Polymarket's own APIs report. **size** `number` Gross token amount filled (before fees). Polymarket's activity API reports net-of-fee sizes, so this value will be slightly larger than what Polymarket shows. Use the `fee` field to compute the net: `net_size = size - fee / price`. **maker\_amount** `string` Raw maker amount from the OrderFilled event (integer string, 6 decimal precision for USDC). **taker\_amount** `string` Raw taker amount from the OrderFilled event (integer string). **fee** `number` Fee charged on this fill in USDC. `null` if no fee. **market\_title** `string` Market question. Enriched from metadata. **outcome** `string` Outcome name. Enriched from metadata. **market\_image** `string` Market image URL. Enriched from metadata. **market\_slug** `string` Market URL slug. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **condition\_id** `string` Market condition ID (CTF contract identifier). Enriched from metadata. **outcomes** `string[]` Ordered list of outcome names (e.g. `["Yes", "No"]`). Index-aligned with `token_ids`. Enriched from metadata. **token\_ids** `string[]` Ordered list of token IDs for this market. Index-aligned with `outcomes`. Enriched from metadata. **tokens** `object` Map of token ID to outcome name for all outcomes in this market (e.g. `{"123...": "Yes", "456...": "No"}`). Enriched from metadata. > [!WARNING] > > `status_update` events arrive in bursts. A single Polygon block typically contains 30–80 Polymarket settlements, so expect 30–80 `status_update` messages within \~100ms each time a block confirms (\~2s interval). If you only need pending detection, subscribe with `"status": "pending"` or exclude `"status_update"` from your `event_types` filter. ## How to use Match `status_update` events back to their `settlement` by `tx_hash`: ```javascript theme={null} const pending = new Map(); // tx_hash → settlement data ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, msg.data); } if (msg.type === "status_update") { const original = pending.get(msg.data.tx_hash); console.log(`Confirmed in ${msg.data.latency_ms}ms`, original); // Use confirmed_fills for exact on-chain prices if (msg.data.confirmed_fills) { for (const fill of msg.data.confirmed_fills) { console.log(` ${fill.side} ${fill.size} @ ${fill.price} (fee: ${fill.fee})`); } } pending.delete(msg.data.tx_hash); } }; ``` # Trade Event Source: https://docs.polynode.dev/websocket/events/trade Confirmed on-chain trade execution from Polymarket exchange contracts. A confirmed on-chain trade from Polymarket's exchange contracts. > [!WARNING] > > **Don't confuse `trade` events with the `trades[]` array inside `settlement` events.** They are related but not the same thing. > > A `trade` event is one of three ways polynode exposes the same fill data, depending on what you need: > > | Shape | When it fires | Source | Format | > | - | - | - | - | > | `settlement.trades[]` | Pre-confirmation (3-5s before the block) | Calldata (estimated for multi-maker) | Array inside one event | > | `trade` events (this page) | At block confirmation | Receipt logs (exact) | One separate WS message per fill | > | `status_update.confirmed_fills[]` | At block confirmation | Receipt logs (exact) | Array inside one event | > > `trade` events and `confirmed_fills[]` contain the **same exact data** — they're both decoded from the on-chain `OrderFilled` logs, just packaged differently. If you already subscribe to `settlement` events, you can read `confirmed_fills[]` from the `status_update` instead of also subscribing to `trade` events. If you only want the post-confirmation per-fill stream, subscribe to `trade` events directly. > > `settlement.trades[]` is the **pre-confirmation equivalent** — it has the same shape but the per-maker prices are estimated from the calldata's aggregate amounts. Use it for speed (3-5 second lead), use `trade` events or `confirmed_fills[]` for exactness. > [!NOTE] > > **Every Polymarket exchange.** Trade events work the same for the original exchange (V1), Polymarket's April 2026 exchange upgrade (V2) and ExchangeV3, which settles Polymarket Protocol V2 markets. The `fee` field is decoded the same way for all of them. No changes to your subscription or parsing logic are needed; `exchange_version` tells them apart. ```json theme={null} { "data": { "block_number": 84705489, "condition_id": "0x158fa5bd542d4982a5b09eee29c5d23f8f1304367adc1a8e4396b692eb550466", "event_slug": "eth-updown-5m-1774530900", "event_title": "Ethereum Up or Down - March 26, 9:15AM-9:20AM ET", "event_type": "trade", "exchange": "ctf_exchange", "fee": 0.122535, "log_index": 1996, "maker": "0x4b8cf80092c60b9b23d22133eb63eb4508fe4d31", "maker_amount": "2130000", "market_image": "https://polymarket-upload.s3.us-east-2.amazonaws.com/ETH+fullsize.jpg", "market_slug": "eth-updown-5m-1774530900", "market_title": "Ethereum Up or Down - March 26, 9:15AM-9:20AM ET", "neg_risk": false, "order_hash": "0x916fa5c2728c93e19ea5d7c254b07234815ad01e59597573c09d852fe53ee564", "outcome": "Up", "outcomes": ["Up", "Down"], "price": 0.71, "side": "BUY", "size": 3.0, "taker": "0x536be02af900fe046fa708c8059c04f737a2cee3", "taker_amount": "3000000", "taker_base_fee": 1000.0, "tick_size": 0.01, "timestamp": 1774531013000, "token_id": "67838338591118719610402948028043822510398368770316608063235371949564584838291", "token_ids": [ "67838338591118719610402948028043822510398368770316608063235371949564584838291", "106640979554519903529443899392736422684573887313790829687503639341656103167080" ], "tokens": { "106640979554519903529443899392736422684573887313790829687503639341656103167080": "Down", "67838338591118719610402948028043822510398368770316608063235371949564584838291": "Up" }, "tx_hash": "0xaf3d097f3b2e799c0a14cca4e7709122b397c9b920c276c0fd3caa4848ea9808" }, "timestamp": 1774531013000, "type": "trade" } ``` ## Fields **type** `string` *required* Always `"trade"`. **timestamp** `number` *required* Unix milliseconds of the block. **data** `object` *required* **data fields** **tx\_hash** `string` *required* Transaction hash. **block\_number** `number` *required* Block number. **log\_index** `number` *required* Log index within the transaction. `(tx_hash, log_index)` is globally unique. **timestamp** `number` *required* Block timestamp in Unix milliseconds. **exchange** `string` *required* `"ctf_exchange"` or `"neg_risk_ctf_exchange"`. Polymarket Protocol V2 markets use the same two values: `"ctf_exchange"` for yes/no markets and `"neg_risk_ctf_exchange"` for multi-outcome markets. **maker** `string` *required* Maker wallet address. **taker** `string` *required* Taker wallet address. **token\_id** `string` *required* Conditional token ID. **side** `string` *required* `"BUY"` or `"SELL"`. **price** `number` *required* Fill price (0.0–1.0 for binary markets). **size** `number` *required* Fill size in shares. **maker\_amount** `string` *required* Raw maker amount (6 decimal precision). **taker\_amount** `string` *required* Raw taker amount (6 decimal precision). **fee** `number` Fee charged on this trade in USDC. Decoded from the OrderFilled log. `null` when fee is zero or not present. **order\_hash** `string` EIP-712 order hash. Uniquely identifies the maker's limit order on Polymarket's CLOB. **Persistent across partial fills** — the same `order_hash` appears every time a slice of that limit order is matched. **exchange\_version** `string` Exchange contract version: `"v2"` for trades settled on Polymarket's April 2026 exchange contracts (CTF Exchange V2), `"v3"` for trades settled on ExchangeV3, which settles Polymarket Protocol V2 markets. Absent for trades on the original V1 exchange. **market\_title** `string` Market question. Enriched from metadata. **outcome** `string` Outcome name. Enriched from metadata. **market\_slug** `string` Market URL slug. Enriched from metadata. **market\_image** `string` Market image URL. Enriched from metadata. **event\_title** `string` Parent event title. Enriched from metadata. **neg\_risk** `boolean` Whether this market uses the negRisk contract type. Enriched from metadata. **tick\_size** `number` Minimum price increment (e.g. `0.01` or `0.001`). Enriched from metadata. **taker\_base\_fee** `number` Taker fee rate in basis points. `200` = 2%, `1000` = 10%, `null` = no fee. Short-term crypto markets (5-minute ETH/BTC) typically have `1000` (10%), while standard markets have `200` (2%). Enriched from Polymarket metadata. **condition\_id** `string` Market condition ID (CTF contract identifier). Enriched from metadata. **protocol\_version** `string` `"v2"` on events for Polymarket Protocol V2 markets. Absent on every other market. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). **module** `string` Polymarket Protocol V2 markets only: `"binary"` for yes/no markets, `"neg_risk"` for multi-outcome markets. Absent on every other market. **event\_slug** `string` Parent event URL slug. Enriched from metadata. **outcomes** `string[]` Ordered list of outcome names (e.g. `["Yes", "No"]`). Index-aligned with `token_ids`. Enriched from metadata. **token\_ids** `string[]` Ordered list of token IDs for this market. Index-aligned with `outcomes`. Enriched from metadata. **tokens** `object` Map of token ID → outcome name for all outcomes in this market (e.g. `{"123...": "Yes", "456...": "No"}`). Enriched from metadata. ## Ordering guarantees Trade events are delivered in strict block order. All trades from block N arrive before any trades from block N+1. Within a block, trades are ordered by `log_index`. The tuple `(tx_hash, log_index)` is globally unique and can be used as a deduplication key. Polygon uses Bor consensus with single-validator sprints, making chain reorganizations effectively nonexistent. You can safely assume that once you receive a trade from block N+1, you have received all trades from block N. ## Settlement vs trade | | Settlement | Trade | | - | - | - | | Source | Pre-chain detection | On-chain confirmation | | Timing | Pending (pre-chain) or confirmed | Confirmed only | | Contains | Full settlement with all maker fills | Single maker-taker fill | | Use case | Early detection, copy trading | Accurate historical record | > [!NOTE] > > A single settlement can contain multiple trades (one per matched maker order). If you subscribe to both `settlement` and `trade`, you'll see the settlement first (pending), then individual trades (confirmed). > [!TIP] > > **Tracking limit orders across fills:** Use `order_hash` to group partial fills of the same limit order. When a maker places a 1,000-share order and it fills in three separate transactions, all three trades share the same `order_hash`. This is the EIP-712 hash of the signed order struct — it's deterministic from the order parameters and matches Polymarket's CLOB order hash. ## Tracking a specific wallet's trades > [!WARNING] > > **TL;DR — Always filter by `maker`, never by `taker`.** A single transaction emits multiple `trade` events as separate WebSocket messages. The wallet's actual fill is the event where `data.maker === your_wallet`. The other events show the counterparties' perspective. This is the most common source of confusion when integrating with the trade stream. Once you understand the on-chain structure, the fix is one line. > [!NOTE] > > **`trade` events have no sub-array.** Each fill arrives as its own WebSocket message with top-level `maker`, `taker`, `side`, `price`, `token_id`, etc. Inspect each incoming message individually. If you're looking for a `trades[]` array, you're thinking of [settlement events](/websocket/events/settlement), which bundle all fills from a single `matchOrders` transaction into one message with a nested `data.trades[]` array. ### How `OrderFilled` events work on-chain Every match on Polymarket emits one `OrderFilled` log per maker order, plus one additional log for the taker's own order. **All fields on each log — `side`, `token_id`, `price`, `size` — are recorded from the maker's perspective on that specific log.** * `maker` = whoever placed the limit order that got filled (the resting order) * `taker` = whoever's order matched into it * `side` = whether the maker was buying or selling When a user submits an order that matches against N existing maker orders, the on-chain settlement emits **N + 1 events**: 1. **N events with the user as `taker`** — one per counterparty maker order they matched against. These show the counterparties' tokens, prices, and sides, not the user's. 2. **One additional event with the user as `maker`** and the exchange contract as `taker` (`0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e` for standard markets, `0xc5d563a36ae78145c45a50134d48a1215220f80a` for neg-risk markets). **This is the user's actual fill.** Polymarket's activity API and Dome both follow this same convention, because they read directly from these `OrderFilled` logs. If you've used Dome before with `event.user === yourWallet`, the equivalent here is `event.maker === yourWallet`. See the [Dome migration guide](/dome-migration#order-perspective) for the same explanation in Dome's terminology. ### Real example Live data from transaction `0x910466c40141da9784fe0dd6b8e7a81d0b46ed3667100b83c714ee70eaf39ab2` on April 9, 2026. The user `0xf5a77527f5154e4cd84ef32c73fab4ba58ec4be0` placed a market BUY for the Up token on an Ethereum 5-minute market. The transaction emitted **4 trade events**: ``` log_index=586 maker=0x0b9353ae taker=0xf5a77527 side=BUY price=0.21 size=5 token=Down log_index=596 maker=0xfcdc071d taker=0xf5a77527 side=BUY price=0.20 size=12 token=Down log_index=606 maker=0x2e9b93fa taker=0xf5a77527 side=BUY price=0.19 size=1.79 token=Down log_index=610 maker=0xf5a77527 taker=0xExchange side=BUY price=0.7983 size=18.79 token=Up ← USER'S ACTUAL TRADE ``` The first three events show counterparties (other wallets) buying the **Down** token at 0.21, 0.20, 0.19. The user happens to appear as the `taker` on each of those because the contract matched their order against them, but those events represent the counterparties' trades, not the user's. The user's actual trade is the fourth event: **`BUY Up at 0.7983 size=18.79`**, where they appear as `maker` and the CTF Exchange contract appears as `taker`. Polymarket's activity API confirms this exact trade: `side=BUY outcome=Up price=0.7983 size=18.51` (the slight size difference is the fee deduction). If you filter by `taker == wallet`, you get the first three events (counterparty perspective on the Down token). If you filter by `maker == wallet`, you get the user's actual fourth event (the Up token at 0.7983). ### The right way to filter ```javascript theme={null} ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type !== "trade") return; const t = msg.data; // CORRECT — match by maker. This is the user's actual fill. if (t.maker.toLowerCase() === MY_WALLET.toLowerCase()) { console.log("My trade:", t.side, t.size, t.outcome, "@", t.price); } // WRONG — match by taker. Returns counterparty fills with the OPPOSITE // token and the COMPLEMENT price (e.g. BUY Down 0.20 when you actually // bought Up at 0.80). // if (t.taker.toLowerCase() === MY_WALLET.toLowerCase()) { ... } }; ``` ### Subscribing only to a specific wallet If you only want events involving a specific wallet, use the `wallets` filter on the subscription. The server-side filter matches **both** `maker` and `taker` fields, so you receive every event the wallet appears in. Apply `maker === wallet` on the client side to get only the wallet's actual trades: ```javascript theme={null} ws.send(JSON.stringify({ action: "subscribe", type: "trades", filters: { wallets: ["0xYourWallet"] } })); ``` # Examples Source: https://docs.polynode.dev/websocket/examples Complete WebSocket examples in JavaScript, Python, and wscat. ## JavaScript / Node.js ### Track all pending settlements ```javascript theme={null} const WebSocket = require("ws"); const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "settlements", filters: { status: "pending" } })); }); ws.on("message", (data) => { const msg = JSON.parse(data); switch (msg.type) { case "snapshot": console.log(`Loaded ${msg.count} recent settlements`); break; case "settlement": const d = msg.data; console.log( `${d.status.toUpperCase()} | ${d.taker_side} ${d.taker_size} shares @ ${d.taker_price}`, `| "${d.market_title}" (${d.outcome})` ); break; case "status_update": console.log(`Confirmed: ${msg.data.tx_hash} in ${msg.data.latency_ms}ms`); break; case "heartbeat": break; // ignore } }); // Reconnect on close ws.on("close", () => setTimeout(() => process.exit(1), 1000)); ``` ### Whale alerts (\$5K+) ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "large_trades", filters: { min_size: 5000 } })); }); ws.on("message", (data) => { const msg = JSON.parse(data); if (msg.type === "settlement") { const d = msg.data; console.log(`WHALE ALERT: ${d.taker_side} $${d.taker_size.toFixed(0)} @ ${d.taker_price}`); console.log(` Market: ${d.market_title} (${d.outcome})`); console.log(` Wallet: ${d.taker_wallet}`); console.log(` TX: ${d.tx_hash}`); } }); ``` ### Monitor a specific market by slug ```javascript theme={null} ws.send(JSON.stringify({ action: "subscribe", type: "markets", filters: { slugs: ["will-pete-hegseth-win-the-2028-us-presidential-election"], snapshot_count: 100 // Get last 100 events } })); ``` ### Track a wallet ```javascript theme={null} const TRACKED_WALLET = "0xabcdef1234567890abcdef1234567890abcdef12"; ws.send(JSON.stringify({ action: "subscribe", type: "wallets", filters: { wallets: [TRACKED_WALLET] } })); // To find the wallet's actual trades inside settlement events, // iterate data.trades[] and match by maker. NEVER match by taker. ws.on("message", (raw) => { const msg = JSON.parse(raw); if (msg.type !== "settlement") return; for (const fill of msg.data.trades) { if (fill.maker.toLowerCase() === TRACKED_WALLET.toLowerCase()) { console.log(`Trade: ${fill.side} ${fill.size} ${fill.outcome} @ ${fill.price}`); } } }); ``` > [!WARNING] > > Always match by `fill.maker`, never by `fill.taker`. The `taker` field is the counterparty — matching it returns the wrong wallet's perspective with the **opposite token** and the **complement price**. See the [Settlement Event reference](/websocket/events/settlement#tracking-a-specific-wallets-trades) for full details. ### Chainlink price feed This unchanged subscription follows the default Chainlink stream. See [Chainlink TWAP Prices](/crypto/twap) to select the 30-second window, the 60-second window, or both during the August transition. ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "chainlink", filters: { feeds: ["BTC/USD"] } })); }); ws.on("message", (data) => { const msg = JSON.parse(data); if (msg.type === "price_feed") { const d = msg.data; console.log(`BTC/USD: $${d.price.toFixed(2)} (bid: $${d.bid.toFixed(2)}, ask: $${d.ask.toFixed(2)})`); } }); ``` ### Settlements + price feeds on same connection ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.on("open", () => { // Subscribe to both — they're independent streams ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); ws.send(JSON.stringify({ action: "subscribe", type: "chainlink" })); }); ws.on("message", (data) => { const msg = JSON.parse(data); switch (msg.type) { case "settlement": console.log(`TRADE: ${msg.data.taker_side} ${msg.data.taker_size} @ ${msg.data.taker_price}`); break; case "price_feed": console.log(`BTC: $${msg.data.price.toFixed(2)}`); break; } }); ``` ## Python ### asyncio client with reconnection ```python theme={null} import asyncio import json import websockets API_KEY = "pn_live_YOUR_KEY" URL = f"wss://ws.polynode.dev/ws?key={API_KEY}" async def connect(): while True: try: async with websockets.connect(URL) as ws: # Subscribe to pending settlements await ws.send(json.dumps({ "action": "subscribe", "type": "settlements", "filters": {"status": "pending", "min_size": 100} })) async for message in ws: msg = json.loads(message) if msg["type"] == "snapshot": print(f"Loaded {msg['count']} recent events") elif msg["type"] == "settlement": d = msg["data"] print(f"{d['taker_side']} {d['taker_size']:.0f} @ {d['taker_price']:.2f}" f" | {d.get('market_title', 'unknown')}") elif msg["type"] == "status_update": print(f"Confirmed: {msg['data']['tx_hash'][:16]}..." f" ({msg['data']['latency_ms']}ms)") except (websockets.ConnectionClosed, ConnectionError) as e: print(f"Disconnected: {e}. Reconnecting in 3s...") await asyncio.sleep(3) asyncio.run(connect()) ``` ### Multiple wallet subscriptions ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); const subscriptionIds = []; ws.on("open", () => { // Subscribe to multiple wallet groups — each creates an independent subscription ws.send(JSON.stringify({ action: "subscribe", type: "wallets", filters: { wallets: ["0xWallet1...", "0xWallet2..."] } })); ws.send(JSON.stringify({ action: "subscribe", type: "wallets", filters: { wallets: ["0xWallet3...", "0xWallet4..."] } })); }); ws.on("message", (data) => { const msg = JSON.parse(data); if (msg.type === "subscribed") { // Save subscription_id for targeted unsubscribe later subscriptionIds.push(msg.subscription_id); console.log(`Subscribed: ${msg.subscription_id}`); } if (msg.type === "settlement") { console.log(`${msg.data.taker_side} ${msg.data.taker_size} @ ${msg.data.taker_price}`); } }); // Later: remove just one subscription // ws.send(JSON.stringify({ action: "unsubscribe", subscription_id: subscriptionIds[0] })); // Or remove all // ws.send(JSON.stringify({ action: "unsubscribe" })); ``` ## wscat (CLI) Quick testing from the command line: ```bash theme={null} # Install npm install -g wscat # Connect wscat -c "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY" # Once connected, paste: {"action": "subscribe", "type": "settlements", "filters": {"status": "pending"}} ``` ```bash theme={null} # Subscribe to Chainlink BTC/USD prices {"action": "subscribe", "type": "chainlink"} # Subscribe to whale trades (stacks with previous subscriptions) {"action": "subscribe", "type": "large_trades", "filters": {"min_size": 10000}} # Subscribe by market slug {"action": "subscribe", "type": "markets", "filters": {"slugs": ["bitcoin-100k-2026"]}} # Ping {"action": "ping"} # Unsubscribe a specific subscription (use the subscription_id from the ack) {"action": "unsubscribe", "subscription_id": "abc123:1"} # Unsubscribe all {"action": "unsubscribe"} ``` ## curl (WebSocket upgrade) ```bash theme={null} # Using websocat (Rust CLI tool) websocat "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY" # Then type: {"action":"subscribe","type":"settlements"} ``` ## Common patterns ### Reconnection with exponential backoff ```javascript theme={null} function createConnection() { let delay = 1000; function connect() { const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); ws.onopen = () => { delay = 1000; // Reset backoff ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); }; ws.onclose = () => { console.log(`Reconnecting in ${delay}ms...`); setTimeout(connect, delay); delay = Math.min(delay * 2, 30000); // Max 30s }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type !== "heartbeat") { handleEvent(msg); } }; } connect(); } ``` ### Pending-to-confirmed tracking ```javascript theme={null} const pending = new Map(); function handleEvent(msg) { if (msg.type === "settlement" && msg.data.status === "pending") { pending.set(msg.data.tx_hash, { ...msg.data, received_at: Date.now() }); console.log(`PENDING: ${msg.data.taker_side} ${msg.data.taker_size} @ ${msg.data.taker_price}`); } if (msg.type === "status_update") { const original = pending.get(msg.data.tx_hash); if (original) { console.log(`CONFIRMED: ${msg.data.latency_ms}ms latency, block ${msg.data.block_number}`); pending.delete(msg.data.tx_hash); } } } ``` # WebSocket Overview Source: https://docs.polynode.dev/websocket/overview Real-time Polymarket trades, 3-5 seconds before on-chain confirmation. polynode's WebSocket is the fastest way to get Polymarket trade data. Every fill is delivered **3-5 seconds before on-chain confirmation** (1-2 blocks early). Subscribe to `fills` to get one clean event per trade, or `settlements` for the full transaction lifecycle. > [card] [Fills](/websocket/subscribing#fills) > > Individual trades, one per message. Pre-confirmation, flat format, no array parsing. The fastest way to track trades. > [card] [Settlements](/websocket/subscribing#settlements) > > Full transaction bundles with all fills in a `trades[]` array plus status lifecycle tracking. > [card] [Trades](/websocket/subscribing#trades) > > Confirmed on-chain fills. Same data as settlements but after block confirmation with exact receipt values. > [card] [Combos](/websocket/combos) > > Pending Polymarket combo trades, order hashes, decoded legs, and receipt confirmations. > [card] Up to 5 second edge > > Settlements and fills detected before on-chain confirmation. Typically 3-5 seconds (1-2 blocks) early. > [card] Filtered subscriptions > > Subscribe by wallet, token, market slug, side, size, or event type. Only receive what you need. > [card] Enriched events > > Standard market events include title, outcome, slug, and image. Combo legs always include structural IDs; their cached `market` details are optional. > [card] [Crypto price feeds](/crypto/overview) > > Real-time prices for BTC, ETH, SOL, BNB, XRP, DOGE, and HYPE (\~1/second each). Subscribe with `"type": "chainlink"` on the same connection. > [card] Oracle resolution stream > > UMA Optimistic Oracle events: market resolutions, disputes, proposals, and admin actions. Subscribe with `"type": "oracle"` to track the full resolution lifecycle. > [!TIP] > > **Save \~60% bandwidth with compression.** Add `&compress=zlib` to your connection URL and decompress binary frames with standard `inflateRaw`. Zero latency impact, recommended for production. [See compression docs →](/websocket/compression) > [!NOTE] > > **Polymarket Protocol V2 markets** arrive on the same streams as the same event types, with a few optional fields. No subscription changes are needed. See [Polymarket Protocol V2 markets](/guides/polymarket-protocol-v2). ## Quick start **1. Get an API key** ```bash theme={null} curl -s -X POST https://api.polynode.dev/v1/keys \ -H "Content-Type: application/json" \ -d '{"name": "my-app"}' ``` Save the `pn_live_...` key from the response. **2. Stream trades (30 seconds)** Save this as `stream.js` and run with `API_KEY=pn_live_... node stream.js`: ```javascript Node.js theme={null} const WebSocket = require("ws"); const API_KEY = process.env.API_KEY || "YOUR_API_KEY"; const DURATION = 30000; const ws = new WebSocket("wss://ws.polynode.dev/ws?key=" + API_KEY); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "fills" })); console.log("Streaming trades for " + (DURATION / 1000) + "s...\n"); }); let count = 0; ws.on("message", (raw) => { const msg = JSON.parse(raw); if (msg.type !== "event") return; count++; const d = msg.data; console.log({ outcome: d.token_label, side: d.side, price: d.price, shares: d.shares_normalized, user: d.user, market: d.title }); }); ws.on("close", () => console.log("\nDone. " + count + " trades.")); setTimeout(() => ws.close(), DURATION); ``` ```python Python theme={null} import asyncio, json, websockets, time API_KEY = "YOUR_API_KEY" DURATION = 30 async def stream(): url = f"wss://ws.polynode.dev/ws?key={API_KEY}" async with websockets.connect(url) as ws: await ws.send(json.dumps({"action": "subscribe", "type": "fills"})) print(f"Streaming trades for {DURATION}s...\n") count = 0 end = time.time() + DURATION async for message in ws: if time.time() > end: break msg = json.loads(message) if msg.get("type") != "event": continue count += 1 d = msg["data"] print(f"{d['token_label']:5} {d['side']:4} {d['shares_normalized']:>8.2f} shares @ {d['price']:<8} | {d['user'][:12]}... | {d['title'][:50]}") print(f"\nDone. {count} trades.") asyncio.run(stream()) ``` You'll see individual trades streaming in, one per line. Each event is a single fill with clear fields for outcome, side, price, shares, and the wallet involved. **3. What you'll see** Every message is one flat event with everything you need. Here's a real captured fill: ```json theme={null} { "type": "event", "data": { "side": "BUY", "price": 0.85, "shares_normalized": 1.67, "token_label": "Up", "title": "Bitcoin Up or Down - April 30, 2:50PM-2:55PM ET", "user": "0xe54bbd9dcef861af50bf2c4dcc354a87e87bff96", "taker": "0x70412cbf28288d47ece30002be45efff5d2d5c73", "order_hash": "0x40169bc2d2af4dded1fbe4d2655838f2b79ba4a9aabc548b8fec3649e66ed9f4", "tx_hash": "0xef710f81783210de00d90fd477d3c190c3acd657cf7dd5dae31188c53ded2e4e", "market_slug": "btc-updown-5m-1777575000", "condition_id": "0x6fe03c3c781f62d456518a3a6b2b95c0d0bee427243bcef06f5b37b3f1c395b7", "token_id": "28011179493432352359106676407817901302975340324989108630179591254583544078282", "shares": 1670000, "timestamp": 1777575164, "block_number": null, "log_index": null } } ``` `block_number: null` means this was detected **before** the block confirmed. Pre-confirmation delivery, 3-5 seconds ahead of on-chain settlement. One event per fill, no arrays to iterate, all fields included. > [!NOTE] > > **`fills` vs `settlements`** — both stream the same trades at the same speed. `fills` gives you one flat event per trade (simplest). `settlements` gives you the full transaction bundle with a `trades[]` array and lifecycle tracking via `status_update` events. Start with `fills`, move to `settlements` when you need the full lifecycle. See [Subscriptions](/websocket/subscribing) for all options. > [accordion] Settlement-based quick start (full lifecycle) > > If you need the full transaction format with nested fills and status lifecycle, subscribe to `settlements` instead: > > ```javascript theme={null} > const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); > > ws.onopen = () => { > ws.send(JSON.stringify({ action: "subscribe", type: "settlements" })); > }; > > ws.onmessage = (event) => { > const msg = JSON.parse(event.data); > if (msg.type === "settlement") { > const d = msg.data; > console.log(`${d.taker_side} ${d.taker_size} @ ${d.taker_price} | ${d.market_title}`); > for (const fill of d.trades) { > console.log(` ${fill.side} ${fill.size} @ ${fill.price} | maker: ${fill.maker}`); > } > } > }; > ``` > > See [Settlement Event](/websocket/events/settlement) for the full field reference. ## Connection URL ``` wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY ``` With compression (\~60% bandwidth savings): ``` wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY&compress=zlib ``` The API key is passed as a query parameter. Keys starting with `pn_live_` or `qm_live_` are accepted. ## Connection limits Most apps only need one Event WebSocket connection. A single connection can carry multiple filtered subscriptions at once, including fills, settlements, trades, blocks, wallet filters, market filters, oracle events, and Chainlink price feeds. | Tier | Concurrent Event WebSockets | Filter items per subscription | Session limit | | - | - | - | - | | **Free** | 1 | 10,000 | 1 hour/day | | **Starter** (\$50/mo) | 10 | 10,000 | Unlimited | | **Growth** (\$200/mo) | 50 | 10,000 | Unlimited | | **Enterprise** (\$750/mo) | Unlimited | Custom | Unlimited | > [!NOTE] > > Event WebSocket limits apply to `ws.polynode.dev`. Orderbook WebSocket limits for `ob.polynode.dev` are listed separately in the [Orderbook Stream](/orderbook/overview) docs. > [!NOTE] > > Successfully delivered settlements, status updates, trades, redemptions, oracle events, and related event payloads appear under **On-chain events** in your [usage dashboard](https://polynode.dev/dashboard/usage). Compression reduces counted transfer because the meter uses the encoded payload delivered to the connection. Heartbeats, acknowledgements, control frames, and failed sends do not count. See [Monthly usage allowances](/guides/rate-limits#monthly-usage-allowances). ## Multiple streams, one connection PolyNode supports multiple subscription types on the same WebSocket: | Stream | Purpose | Subscribe | | - | - | - | | **Fills** | Individual pre-confirmation trades, one flat event per fill. Simplest format. | `{"action":"subscribe","type":"fills"}` | | **Settlements** | Pre-confirmation transaction bundles with all fills in a `trades[]` array (default) | `{"action":"subscribe","type":"settlements"}` | | **Trades** | Confirmed on-chain fills with exact receipt values | `{"action":"subscribe","type":"trades"}` | | **Prices** | Price-moving settlement and trade events for specific markets | `{"action":"subscribe","type":"prices"}` | | **Combos** | Pending combo trades with order hashes, decoded legs, and receipt confirmations | `{"action":"subscribe","type":"combos"}` | | **Blocks** | New Polygon block notifications with Polymarket stats | `{"action":"subscribe","type":"blocks"}` | | **Wallets** | All activity for specified wallets | `{"action":"subscribe","type":"wallets","filters":{"wallets":["0x..."]}}` | | **Markets** | All activity for specified markets | `{"action":"subscribe","type":"markets","filters":{"tokens":["..."]}}` | | **Deposits** | USDC.e and Polymarket USD deposit/withdrawal activity | `{"action":"subscribe","type":"deposits"}` | | **Large Trades** | Whale alerts (\$1K+ by default) | `{"action":"subscribe","type":"large_trades"}` | | **Global** | Full firehose of the default public event set | `{"action":"subscribe","type":"global"}` | | **Oracle** | UMA resolution lifecycle (resolutions, disputes, flags) | `{"action":"subscribe","type":"oracle"}` | | **Chainlink** | Real-time crypto prices (7 feeds, \~1/sec each) | `{"action":"subscribe","type":"chainlink"}` | All can run simultaneously on the same connection. See [Subscriptions & Filters](/websocket/subscribing) for full details on each type, including default event types and available filters. ## Heartbeat The server sends a heartbeat every 30 seconds: * A WebSocket-level **Ping** frame (handled automatically by WS clients) * A text message: `{"type": "heartbeat", "ts": 1772386305181}` If no heartbeat arrives within \~35 seconds, the connection is dead — reconnect. The server monitors client liveness via incoming messages and Pong frames. If no activity is received from the client within 5 minutes, the server closes the connection with a close frame explaining the reason. Standard WebSocket clients handle Pong automatically, which counts as activity. ### Application-level keepalive Send a ping message to confirm the connection is alive: ```json theme={null} {"action": "ping"} ``` Response: ```json theme={null} {"type": "pong", "ts": 1774429169820} ``` Any message you send (subscribe, unsubscribe, ping) resets the server's liveness timer. > [!WARNING] > > **Running behind a reverse proxy (Railway, Render, Heroku, AWS ALB, etc.)?** Some cloud platform proxies intercept WebSocket Ping/Pong control frames at the proxy layer and don't forward them to your application. This means the server never receives your client's automatic Pong responses, and the connection gets dropped for inactivity. > > **The fix:** Send `{"action": "ping"}` every 30-60 seconds from your application code. These are regular text frames that pass through any proxy. This is the recommended keepalive method for any containerized or cloud-hosted deployment. > > ```python theme={null} > # Python example — keepalive for cloud-hosted clients > import asyncio, json, websockets > > async def stream(): > url = "wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY" > async with websockets.connect(url, ping_interval=None, ping_timeout=None) as ws: > await ws.send(json.dumps({"action": "subscribe", "type": "fills"})) > > async def keepalive(): > while True: > await asyncio.sleep(30) > await ws.send(json.dumps({"action": "ping"})) > > ping_task = asyncio.create_task(keepalive()) > try: > async for message in ws: > msg = json.loads(message) > if msg["type"] in ("pong", "heartbeat"): > continue > # handle events... > finally: > ping_task.cancel() > > asyncio.run(stream()) > ``` > > ```javascript theme={null} > // Node.js example — keepalive for cloud-hosted clients > const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_YOUR_KEY"); > > ws.onopen = () => { > ws.send(JSON.stringify({ action: "subscribe", type: "fills" })); > setInterval(() => ws.send(JSON.stringify({ action: "ping" })), 30000); > }; > ``` ## Connection lifecycle ``` Connect → wss://ws.polynode.dev/ws?key=pn_live_... ↓ Send → {"action": "subscribe", "type": "fills"} ↓ Receive ← {"type": "subscribed", "subscriber_id": "...", "subscription_id": "...:1"} ↓ Receive ← {"type": "snapshot", "count": 20, "events": [...]} (recent flat fills) ↓ Send → {"action": "subscribe", ...} (additional subscriptions stack) Receive ← {"type": "subscribed", "subscription_id": "...:2"} ↓ Receive ← {"type": "event", "data": {...}} (live fills) Receive ← Ping frame (every 30s) Send → Pong frame (automatic) Receive ← {"type": "heartbeat", ...} (every 30s) Send → {"action": "ping"} (optional, recommended if cloud-hosted) Receive ← {"type": "pong", "ts": ...} (keepalive response) ↓ Send → {"action": "unsubscribe", "subscription_id": "...:1"} (remove one) Send → {"action": "unsubscribe"} (remove all) Receive ← {"type": "unsubscribed"} ``` ## Error handling Invalid messages return structured errors: ```json theme={null} { "type": "error", "code": "invalid_json", "message": "Message is not valid JSON." } ``` | Error code | Cause | | - | - | | `invalid_json` | Message is not valid JSON | | `invalid_message` | Unknown action or missing required fields | | `unresolved_slugs` | Slug not found in market metadata | | `unresolved_condition_ids` | Condition ID not found in metadata | ## Reconnection Polynode does not send a close frame before disconnecting. Implement reconnection with exponential backoff and use the `since` filter to fill any gaps: ```javascript theme={null} let delay = 1000; let lastEventTs = null; function fillTimestampMs(event) { // Fill envelopes keep their timestamp in data, in UNIX seconds. return Number.isFinite(event.data?.timestamp) ? event.data.timestamp * 1000 : null; } function connect() { const ws = new WebSocket("wss://ws.polynode.dev/ws?key=pn_live_..."); ws.onopen = () => { delay = 1000; const filters = lastEventTs ? { since: lastEventTs } : {}; ws.send(JSON.stringify({ action: "subscribe", type: "fills", filters })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); // Snapshot items and live fills use the same envelope. const fills = msg.type === "snapshot" ? msg.events : msg.type === "event" ? [msg] : []; for (const fill of fills) { const timestampMs = fillTimestampMs(fill); if (timestampMs) lastEventTs = Math.max(lastEventTs || 0, timestampMs); // Process fill.data here. Deduplicate by tx_hash + order_hash if needed. } }; ws.onclose = () => setTimeout(connect, Math.min(delay *= 2, 30000)); } ``` The `since` filter returns all events after that timestamp within your tier's lookback window (free: 30s, starter: 2min, growth/enterprise: 5min). When `since` is set, it overrides `snapshot_count`. For outages longer than your lookback window, use the REST API to backfill. # Subscriptions & Filters Source: https://docs.polynode.dev/websocket/subscribing Subscription types, filter options, and how event matching works. ## Subscribe message Send a JSON message after connecting to start receiving events: ```json theme={null} { "action": "subscribe", "type": "settlements", "filters": { "wallets": ["0x1234..."], "tokens": ["21742633..."], "slugs": ["bitcoin-100k-2026"], "condition_ids": ["0xabc..."], "side": "BUY", "status": "pending", "min_size": 100, "max_size": 10000, "event_types": ["settlement", "status_update"], "snapshot_count": 50, "since": 1774412600000 } } ``` All fields except `action` are optional. ## Subscribe response Successful subscriptions return an acknowledgement: ```json theme={null} { "type": "subscribed", "subscriber_id": "connection-id", "subscription_id": "connection-id:0", "subscription_type": "combos" } ``` Event messages use this envelope: ```json theme={null} { "type": "combo_execution", "timestamp": 1781054110000, "data": { "event_type": "combo_execution", "tx_hash": "0xb0411705aaefc17991e4121acecd8aad03901ddc359cfdb7cf8773f46942927a" } } ``` The initial snapshot wraps recent events in `events[]`; live messages use the single-event envelope above. Consumers should handle both: ```javascript theme={null} function handleMessage(raw) { const message = JSON.parse(raw); for (const event of message.events ?? [message]) { if (event.type === "combo_execution") { console.log(event.data.tx_hash); } } } ``` ## Subscription types The `type` field selects a preset of event types. If you also set `filters.event_types`, it overrides the preset. **fills** `string` Events: `settlement` (reformatted as one flat event per fill) The simplest way to stream Polymarket trades. Each fill arrives as its own flat event with clear fields: `user` (the wallet whose fill this is), `side`, `price`, `shares_normalized`, `token_label` (outcome name), and `title` (market name). No arrays to iterate, no nested objects to unpack. Pre-confirmation delivery, 3-5 seconds before on-chain settlement. Same speed as `settlements`, just a cleaner format for per-trade tracking. ```javascript theme={null} const ws = new WebSocket("wss://ws.polynode.dev/ws?key=YOUR_KEY"); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "fills" })); }); ws.on("message", (raw) => { const msg = JSON.parse(raw); for (const event of msg.events ?? [msg]) { if (event.type !== "event") continue; const fill = event.data; console.log({ outcome: fill.token_label, side: fill.side, price: fill.price, shares: fill.shares_normalized, user: fill.user, market: fill.title }); } }); ``` The initial snapshot uses the same flat fill envelope as live delivery: `{"type":"snapshot","count":N,"events":[{"type":"event","data":{...}}]}`. For `fills`, `count` is the number of flat fills, not the number of settlement transactions. If no fill matches, replay still completes explicitly with `{"type":"snapshot","count":0,"events":[]}`. **Example event:** ```json theme={null} { "type": "event", "data": { "order_hash": "0x7b281ecba532e471...", "user": "0x0c6367b4e0022ca702ad6f33cd2cf504b2cc3cbb", "taker": "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "tx_hash": "0xf7d09a5f24609e82...", "side": "BUY", "price": 0.59, "shares": 33898304, "shares_normalized": 33.898304, "token_id": "111868385514416639...", "token_label": "Astralis", "condition_id": "0xd546a1f7ff24a008...", "market_slug": "cs2-ast10-eye-2026-04-09-game1", "title": "Counter-Strike: Astralis vs EYEBALLERS - Map 1 Winner", "timestamp": 1775731431, "block_number": null, "log_index": null } } ``` `block_number: null` means pre-confirmation (detected before the block). Once confirmed, a `status_update` fires on the `settlements` subscription if you have one active. If you only need trades and don't care about the confirmation lifecycle, `fills` is all you need. **settlements** `default` Events: `settlement`, `status_update` Pending and confirmed Polymarket settlements. The default subscription type. Each event contains a `trades[]` array with all fills in the transaction. Use this when you need the full settlement lifecycle (pending detection, block confirmation via `status_update`, and all fills grouped by transaction). If you just want individual trades in a flat format, use [`fills`](#fills) instead. **trades** `string` Events: `settlement`, `trade`, `status_update` All trade activity including confirmed on-chain trades. **prices** `string` Events: `settlement`, `trade` Price-moving events only. Useful for building price feeds. **combos** `string` Events: `combo_execution`, `combo_status_update` Polymarket combo executions and confirmations. Pending `combo_execution` events expose taker-level execution fields plus one maker-perspective row per signed order in `trades[]`. Confirmed `combo_status_update` events include receipt-derived fills, transfers, fees, gas fields, and confirmation latency when the pending event was seen first. Each `legs[]` entry includes its decoded structural identifiers. Its nested `market` title, slug, image, outcomes, and token IDs are added from the in-memory metadata cache when available; the hot path never waits on an external lookup. Lifecycle and approval events are available by explicit request: ```json theme={null} { "action": "subscribe", "type": "combos", "filters": { "event_types": [ "combo_execution", "combo_status_update", "combo_lifecycle", "combo_approval" ] } } ``` See [Combo Stream](/websocket/combos) for the full field reference and filters. **dome** `string` Events: `settlement` (reformatted as per-fill flat events) Dome API-compatible feed. Each settlement is exploded into individual flat events — one per order fill — matching the exact field names and structure of Dome's WebSocket API. Designed as a drop-in replacement for Dome with 3-5 second faster delivery. See [Dome Migration](/dome-migration) for full field reference and copy trading examples. This is the simplest subscription type for **per-wallet trade tracking**. Each fill arrives as its own flat event with a `user` field. Filter incoming events by `event.data.user === your_wallet` to get the wallet's actual trades — no array iteration, no maker/taker confusion. ```javascript theme={null} import WebSocket from "ws"; const TRACKED_WALLET = "0x..."; const ws = new WebSocket("wss://ws.polynode.dev/ws?key=YOUR_KEY"); ws.on("open", () => { ws.send(JSON.stringify({ action: "subscribe", type: "dome" })); }); ws.on("message", (raw) => { const msg = JSON.parse(raw); if (msg.type !== "event") return; const fill = msg.data; if (fill.user.toLowerCase() !== TRACKED_WALLET.toLowerCase()) return; console.log( fill.side, fill.shares_normalized, fill.token_label, "@", fill.price, "in", fill.title ); }); ``` **Real captured event** (live data from April 9, 2026): ```json theme={null} { "type": "event", "data": { "order_hash": "0x7b281ecba532e47147e9919e073635b44ce0361527f46ee1067f2ca152aea765", "user": "0x0c6367b4e0022ca702ad6f33cd2cf504b2cc3cbb", "taker": "0x4bfb41d5b3570defd03c39a9a4d8de6bd8b8982e", "tx_hash": "0xf7d09a5f24609e8209298d7be35fa33ba8a3749ebb51f8a13d10d547467d104d", "side": "BUY", "price": 0.59, "shares": 33898304, "shares_normalized": 33.898304, "token_id": "111868385514416639450414573730782830447093166389406898626712932606174471659926", "token_label": "Astralis", "condition_id": "0xd546a1f7ff24a008a90bf80a06a7f7aa034abb33311d6727d325f9b848e93940", "market_slug": "cs2-ast10-eye-2026-04-09-game1", "title": "Counter-Strike: Astralis vs EYEBALLERS - Map 1 Winner", "timestamp": 1775731431, "block_number": null, "log_index": null } } ``` In this event, `user` is the wallet whose trade this is (`0x0c6367b4...`), and `taker` is the CTF Exchange contract (`0x4bfb41d5...`) — that pattern means this is the user's own fill, not a counterparty fill. The user bought Astralis at 0.59 for 33.9 shares. The same transaction also produces a separate event for the counterparty (with `user = counterparty_wallet, taker = real_taker_wallet`). To track only the wallet you care about, filter by `event.data.user === your_wallet` and ignore everything else. **blocks** `string` Events: `block` New Polygon block notifications with Polymarket-specific stats (settlement count, trade volume). **wallets** `string` Events: `settlement`, `trade`, `position_change`, `deposit`, `status_update`, `position_split`, `position_merge`, `positions_converted`, `redemption` All activity for specific wallets. Best used with the `wallets` filter. **redemptions** `string` Events: `redemption` Comprehensive payout-redemption feed. It includes direct Conditional Tokens redemptions and Binary, NegRisk, and generic combo AutoRedeemer payouts normalized into the same `redemption` shape. AutoRedeemer variants are distinguished by `data.source`; use a `combos` subscription filtered to `combo_lifecycle` + `action: "Redeem"` when you need combo redemptions only. **markets** `string` Events: `settlement`, `trade`, `position_change`, `status_update`, `position_split`, `position_merge`, `positions_converted`, `redemption` All activity for specific markets. Best used with `tokens`, `slugs`, or `condition_ids` filters. **deposits** `string` Events: `deposit` USDC.e and Polymarket USD deposit/withdrawal activity involving known Polymarket contracts. **large\_trades** `string` Events: `settlement`, `trade` Whale alerts. Defaults to `min_size: 1000` (\$1K+) unless you set your own. **global** `string` Events: `settlement`, `trade`, `position_change`, `deposit`, `block`, `status_update`, `oracle`, `redemption` Unfiltered stream of the default public event set (**firehose**). High throughput — use with caution. This counts toward your plan's firehose connection limit. Combo events are not included in `global` by default; use `type: "combos"` for combo activity. > [!NOTE] > > **Firehose** refers to any WebSocket subscription with no filters applied — receiving every event at full throughput. Filtered subscriptions (specifying wallets, tokens, slugs, or size thresholds) don't count toward your firehose limit and use far less bandwidth. **oracle** `string` Events: `oracle` UMA Optimistic Oracle events: market resolutions, proposals, disputes, flags, and admin actions. See [Oracle Event](/websocket/events/oracle). **chainlink** `string` Events: `price_feed` Real-time crypto prices (\~1 update/second per feed). 7 feeds available: BTC, ETH, SOL, BNB, XRP, DOGE, HYPE. Use the `feeds` filter to select specific feeds (e.g. `["BTC/USD", "ETH/USD"]`). See [Crypto Prices](/crypto/overview). ## Filters All filters are optional. Omit the `filters` object entirely to receive all events matching the subscription type. ### Market identification **tokens** `string[]` Filter by Polymarket conditional token IDs. Match if **any** token in the list appears in the event. ```json theme={null} "tokens": ["21742633143463906290569404...", "98765432..."] ``` **slugs** `string[]` Filter by market URL slugs. Resolved to token IDs at subscribe time — zero performance cost after that. ```json theme={null} "slugs": ["bitcoin-100k-2026", "trump-2024"] ``` > [!WARNING] > > If a slug isn't found in metadata, you'll get a warning in the `subscribed` response. The subscription still activates for any resolved slugs. **condition\_ids** `string[]` Filter by Polymarket condition IDs. Resolved to token IDs at subscribe time. Polymarket Protocol V2 condition IDs are accepted in the 66-character form or in Polymarket's 31-byte form (`0x` plus 62 hex characters). ```json theme={null} "condition_ids": ["0x123abc..."] ``` ### Combo identification These filters apply to `type: "combos"` subscriptions. **combo\_condition\_ids** `string[]` Filter by derived combo condition IDs. ```json theme={null} "combo_condition_ids": ["0xcombo..."] ``` **leg\_position\_ids** `string[]` Filter by constituent leg position IDs. `tokens` also matches combo and leg position IDs, but `leg_position_ids` makes the intent explicit. ```json theme={null} "leg_position_ids": ["123456789..."] ``` **event\_ids** `string[]` Filter by combo leg event IDs when available. **module\_ids** `number[]` Filter by combo module ID. Common values are `1` for binary, `2` for negative-risk, and `3` for combinatorial legs. **action** `string` Filter `combo_lifecycle` events by lifecycle action. Values include `Prepare`, `Split`, `Merge`, `HorizontalSplit`, `HorizontalMerge`, `Convert`, `Redeem`, `Wrap`, `Unwrap`, `Transfer`, `Compress`, `Extract`, `Inject`, `ConvertToYesBasket`, and `MergeFromYesBasket`. **direction** `string` Filter `combo_execution` events by requester direction. Values: `"BUY"` or `"SELL"` > [!NOTE] > > For `type: "combos"`, `condition_ids` are matched directly against combo and leg condition IDs. They are not resolved through standard market metadata at subscription time. ### Wallet filtering **wallets** `string[]` Filter by wallet addresses (case-insensitive). Matches if the wallet is involved as maker **or** taker. ```json theme={null} "wallets": ["0xabcdef1234567890..."] ``` > [!WARNING] > > **Tracking a specific wallet in ordinary `settlement` or `trade` events?** Match > by `maker`, not by `taker`. > > For `settlement` events: iterate `data.trades[]` and find entries where `fill.maker === your_wallet`. > > For `trade` events: filter incoming events by `data.maker === your_wallet`. > > The `maker` field on each fill is the wallet that placed the order. The `taker` field is the counterparty — matching against it returns the wrong wallet's perspective with the **opposite token** and the **complement price** (e.g. shows `BUY Down 0.20` when the wallet actually bought `Up at 0.80`). This is how on-chain `OrderFilled` events are structured. See the [Settlement Event](/websocket/events/settlement#tracking-a-specific-wallets-trades) or [Trade Event](/websocket/events/trade#tracking-a-specific-wallets-trades) reference for full code examples. > > For `type: "combos"`, the `wallets` subscription filter deliberately matches > any involved maker **or** taker. Inside `combo_execution.trades[]`, each row is > still expressed from that signed order maker's perspective. ### Trade filtering **side** `string` Filter by side. Case-insensitive. * Ordinary `settlement` and `trade` events: `"BUY"` or `"SELL"` * Combo execution and lifecycle events: `"YES"` or `"NO"` For a combo requester's `BUY` or `SELL` direction, use the combo-specific `direction` filter instead. **min\_size** `number` Minimum trade size in USD. Events below this size are dropped. ```json theme={null} "min_size": 1000 ``` **max\_size** `number` Maximum trade size in USD. Events above this size are dropped. **status** `string` (default: all) Filter by chain stage across event families. | Value | Description | | - | - | | `"pending"` | Only pre-chain detections | | `"confirmed"` | Only confirmed in a block | | `"all"` | Both pending and confirmed (default) | For combos, `"confirmed"` means a receipt-backed `combo_status_update`. It includes both successful and reverted receipts; inspect that event's `execution_status` for `CONFIRMED` versus `FAILED`. ### Event control **event\_types** `string[]` Override the subscription type's default event list. Valid values: `"settlement"`, `"trade"`, `"status_update"`, `"block"`, `"position_change"`, `"deposit"`, `"position_split"`, `"position_merge"`, `"positions_converted"`, `"redemption"`, `"oracle"`, `"combo_execution"`, `"combo_status_update"`, `"combo_lifecycle"`, `"combo_approval"` **snapshot\_count** `number` (default: 20) Number of recent matching events to receive immediately after subscribing. Max varies by tier (free: 20, starter: 100, growth: 200, enterprise: 500). For a `fills` subscription, this counts flat fill events. For example, `snapshot_count: 20` returns at most 20 items in `events[]`, each in the exact same `{"type":"event","data":{...}}` shape as a live fill. **since** `number` UNIX timestamp in milliseconds. When set, the initial snapshot returns all events **after** this timestamp instead of just the most recent N events. Useful for gap-filling after a reconnect or cold start. ```json theme={null} "since": 1774412600000 ``` The server keeps a rolling window of recent events in memory. Timestamps older than your tier's lookback window are clamped to the window edge. | Tier | Max lookback | | - | - | | Free | 30 seconds | | Starter | 2 minutes | | Growth | 5 minutes | | Enterprise | 5 minutes | > [!NOTE] > > **`since` vs `snapshot_count`** — these are two separate snapshot modes. Use `snapshot_count` when you just want the last N events (capped by tier). Use `since` when you need every event after a specific timestamp (e.g. reconnecting after a drop). If you pass both, `since` takes priority and `snapshot_count` is ignored. See [tier limits](/guides/rate-limits#tier-limits) for the full breakdown. ### Price feed filtering **feeds** `string[]` Filter by price feed names. Only applies to `chainlink` subscriptions. Available feeds: `BTC/USD`, `ETH/USD`, `SOL/USD`, `BNB/USD`, `XRP/USD`, `DOGE/USD`, `HYPE/USD`. ```json theme={null} "feeds": ["BTC/USD", "ETH/USD", "SOL/USD"] ``` Omit to receive all 7 feeds. See [Crypto Prices](/crypto/overview) for details. ## Matching logic Filters use **AND** logic between different filter types and **OR** logic within each filter: * An event must match **all** active filter categories (wallets AND tokens AND side AND size range) * Within a category, matching **any** value is sufficient (wallet A OR wallet B) * Empty/omitted filters match everything in that category ## Multiple subscriptions You can send multiple `subscribe` messages on the same connection — they **stack**. Each subscribe creates an independent subscription with its own filters. Events matching *any* of your active subscriptions are delivered, deduplicated so you never receive the same event twice. ```javascript theme={null} // Subscribe to two different wallet groups independently ws.send(JSON.stringify({ action: "subscribe", type: "wallets", filters: { wallets: ["0xaaa..."] } })); ws.send(JSON.stringify({ action: "subscribe", type: "wallets", filters: { wallets: ["0xbbb..."] } })); // Both subscriptions are active — events for either wallet are delivered ``` ## Acknowledgement and initial replay Snapshot-capable event subscriptions acknowledge first, then send replay. For `fills`, you receive these two messages in this order: **1. Confirmation:** your subscription ID and any warnings: ```json theme={null} { "type": "subscribed", "subscriber_id": "550e8400-e29b-41d4-a716-446655440000", "subscription_id": "550e8400-e29b-41d4-a716-446655440000:1", "subscription_type": "fills", "warnings": [] } ``` **2. Snapshot:** recent flat fills matching your filters: ```json theme={null} { "type": "snapshot", "count": 20, "events": [ { "type": "event", "data": { "timestamp": 1775731431 } } ] } ``` Save the `subscription_id` if you need to remove a specific subscription later. ## Unsubscribe ### Remove a specific subscription ```json theme={null} {"action": "unsubscribe", "subscription_id": "550e8400-...:1"} ``` Response: ```json theme={null} { "type": "unsubscribed", "subscriber_id": "550e8400-...", "subscription_id": "550e8400-...:1" } ``` ### Remove all subscriptions ```json theme={null} {"action": "unsubscribe"} ``` Response: ```json theme={null} {"type": "unsubscribed", "subscriber_id": "550e8400-..."} ``` > [!TIP] > > To change filters on an existing subscription, unsubscribe by `subscription_id` and send a new subscribe with the updated filters.